openapi: "3.0.3"
info:
  title: "Tether Relay and Tether API"
  version: "1.0.0"
  description: "Route-derived OpenAPI contract generated from tether-relay backend sources. Regenerate with scripts/sync-openapi-from-backend.mjs."
servers:
  -
    url: "https://your-instance.example.com"
    description: "Production"
  -
    url: "http://localhost:2212"
    description: "Local API service"
tags:
  -
    name: "Agent Flows"
  -
    name: "AI"
  -
    name: "Ai Consumption"
  -
    name: "Applications"
  -
    name: "Approval"
  -
    name: "Auth"
  -
    name: "Auth Connections"
  -
    name: "Automations"
  -
    name: "Calls"
  -
    name: "Campaigns"
  -
    name: "Client Errors"
  -
    name: "Contact Analytics"
  -
    name: "Contact Metrics"
  -
    name: "Contact Notes"
  -
    name: "Contacts"
  -
    name: "Conversation Monitor"
  -
    name: "Conversations"
  -
    name: "D"
  -
    name: "Departments"
  -
    name: "Email"
  -
    name: "Escalation Dashboard"
  -
    name: "Event Logs"
  -
    name: "Google Sheets"
  -
    name: "Marketplace"
  -
    name: "Media"
  -
    name: "Media Storage"
  -
    name: "Messages"
  -
    name: "Notification Sounds"
  -
    name: "Notifications"
  -
    name: "Org Snapshots"
  -
    name: "Organizations"
  -
    name: "Outreach"
  -
    name: "Outreach Metrics"
  -
    name: "Outreach Sources"
  -
    name: "Phone Numbers"
  -
    name: "Pipelines"
  -
    name: "Playground Sessions"
  -
    name: "Processes"
  -
    name: "Prompts"
  -
    name: "Record Logs"
  -
    name: "Record Summaries"
  -
    name: "Reminders"
  -
    name: "Saved Filters"
  -
    name: "Search"
  -
    name: "Sms"
  -
    name: "Templates"
  -
    name: "Tovi"
  -
    name: "Traces"
  -
    name: "Upload"
  -
    name: "User Snapshots"
  -
    name: "Users"
  -
    name: "Vertical"
  -
    name: "Webchats"
  -
    name: "Webhook"
paths:
  "/api/agent-flows":
    get:
      operationId: "get_api_agent_flows"
      summary: "GET /api/agent-flows"
      tags:
        - "Agent Flows"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/agent-flows/{workflowId}":
    get:
      operationId: "get_api_agent_flows_workflowId"
      summary: "GET /api/agent-flows/{workflowId}"
      tags:
        - "Agent Flows"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "workflowId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/agent-flows/{workflowId}/link":
    post:
      operationId: "post_api_agent_flows_workflowId_link"
      summary: "POST /api/agent-flows/{workflowId}/link"
      tags:
        - "Agent Flows"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "workflowId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/agent-flows/{workflowId}/preview":
    post:
      operationId: "post_api_agent_flows_workflowId_preview"
      summary: "POST /api/agent-flows/{workflowId}/preview"
      tags:
        - "Agent Flows"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "workflowId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/agent-flows/run-state/{conversationId}/{promptId}":
    get:
      operationId: "get_api_agent_flows_run_state_conversationId_promptId"
      summary: "GET /api/agent-flows/run-state/{conversationId}/{promptId}"
      tags:
        - "Agent Flows"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "conversationId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "promptId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/agent-flows/run-state/{conversationId}/{promptId}/reset":
    post:
      operationId: "post_api_agent_flows_run_state_conversationId_promptId_reset"
      summary: "POST /api/agent-flows/run-state/{conversationId}/{promptId}/reset"
      tags:
        - "Agent Flows"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "conversationId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "promptId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/agent-flows/run-state/by-contact/{workflowId}/{contactId}":
    get:
      operationId: "get_api_agent_flows_run_state_by_contact_workflowId_contactId"
      summary: "GET /api/agent-flows/run-state/by-contact/{workflowId}/{contactId}"
      tags:
        - "Agent Flows"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "workflowId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "contactId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/agent-flows/run-state/by-contact/{workflowId}/{contactId}/reset":
    post:
      operationId: "post_api_agent_flows_run_state_by_contact_workflowId_contactId_reset"
      summary: "POST /api/agent-flows/run-state/by-contact/{workflowId}/{contactId}/reset"
      tags:
        - "Agent Flows"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "workflowId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "contactId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/agent-flows/run-state/by-scope/{workflowId}/{scopeType}/{scopeId}":
    get:
      operationId: "get_api_agent_flows_run_state_by_scope_workflowId_scopeType_scopeId"
      summary: "GET /api/agent-flows/run-state/by-scope/{workflowId}/{scopeType}/{scopeId}"
      tags:
        - "Agent Flows"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "workflowId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "scopeType"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "scopeId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/agent-flows/run-state/by-scope/{workflowId}/{scopeType}/{scopeId}/reset":
    post:
      operationId: "post_api_agent_flows_run_state_by_scope_workflowId_scopeType_scopeId_reset"
      summary: "POST /api/agent-flows/run-state/by-scope/{workflowId}/{scopeType}/{scopeId}/reset"
      tags:
        - "Agent Flows"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "workflowId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "scopeType"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "scopeId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/agent-flows/run-state/count/{workflowId}":
    get:
      operationId: "get_api_agent_flows_run_state_count_workflowId"
      summary: "GET /api/agent-flows/run-state/count/{workflowId}"
      tags:
        - "Agent Flows"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "workflowId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/ai-consumption":
    get:
      operationId: "list_ai_consumption"
      summary: "List AI consumption records"
      description: "One row per billable AI model invocation, across agents, workflow AI nodes, automations, background extraction, Tovi and voice. Each row carries the token counts, the cost, and the per-million rates the cost was computed from, so a total is reproducible after model prices change. Admin and superadmin only."
      tags:
        - "AI Consumption"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          name: "from"
          in: "query"
          required: false
          description: "Start of the range (inclusive), ISO-8601. Defaults to 30 days ago."
          schema:
            type: "string"
            format: "date-time"
        -
          name: "to"
          in: "query"
          required: false
          description: "End of the range (exclusive), ISO-8601. Defaults to now."
          schema:
            type: "string"
            format: "date-time"
        -
          name: "sourceType"
          in: "query"
          required: false
          schema:
            type: "string"
            enum:
              - "ai_agent"
              - "ai_generation"
              - "ai_classification"
              - "ai_summarization"
              - "ai_extraction"
              - "ai_sentiment"
              - "tovi"
              - "voice_agent"
        -
          name: "mode"
          in: "query"
          required: false
          description: "Traffic class. Omitted means production only - playground, simulation, preview and node-test spend is recorded but excluded from totals by default."
          schema:
            type: "string"
            enum:
              - "production"
              - "playground"
              - "simulation"
              - "preview"
              - "node_test"
        -
          name: "model"
          in: "query"
          required: false
          schema:
            type: "string"
        -
          name: "provider"
          in: "query"
          required: false
          schema:
            type: "string"
        -
          name: "userId"
          in: "query"
          required: false
          description: "Acting user. System-initiated work is recorded under an explicit system actor."
          schema:
            type: "string"
        -
          name: "sourceName"
          in: "query"
          required: false
          description: "Case-insensitive substring match against the display-name snapshot."
          schema:
            type: "string"
        -
          name: "search"
          in: "query"
          required: false
          description: "Free text matched case-insensitively against the source name, model, provider, acting user and type. Narrows the other filters rather than replacing them. Spaces and underscores are interchangeable, so the displayed 'AI Agent' matches the stored `ai_agent`."
          schema:
            type: "string"
        -
          name: "status"
          in: "query"
          required: false
          description: "Restrict to successful or failed calls. A failed call still spent input tokens and is recorded, so this is how those are reached in a large result set."
          schema:
            type: "string"
            enum:
              - "success"
              - "error"
        -
          name: "organizationId"
          in: "query"
          required: false
          description: "SUPERADMIN only. `all` returns a cross-organization view, which is distinct from omitting the parameter (the caller’s own organization). Ignored for every other role."
          schema:
            type: "string"
        -
          name: "sortBy"
          in: "query"
          required: false
          description: "Column to order by. Defaults to most recent first."
          schema:
            type: "string"
            enum:
              - "startedAt"
              - "cost"
              - "tokens"
              - "duration"
            default: "startedAt"
        -
          name: "sortDir"
          in: "query"
          required: false
          schema:
            type: "string"
            enum:
              - "asc"
              - "desc"
            default: "desc"
        -
          name: "page"
          in: "query"
          required: false
          schema:
            type: "integer"
            minimum: 1
            default: 1
        -
          name: "limit"
          in: "query"
          required: false
          schema:
            type: "integer"
            minimum: 1
            maximum: 100
            default: 20
      responses:
        "200":
          description: "Consumption rows"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiConsumptionListResponse"
        "400":
          description: "Invalid query parameters"
        "403":
          description: "Caller is not an admin or superadmin"
  "/api/ai-consumption/summary":
    get:
      operationId: "get_ai_consumption_summary"
      summary: "Totals and breakdowns of AI consumption"
      description: "Aggregate totals plus breakdowns by type, model, user and name, and a time series for charting. Uses the same filters as the row list so a chart and the table beneath it cannot disagree."
      tags:
        - "AI Consumption"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          name: "from"
          in: "query"
          required: false
          description: "Start of the range (inclusive), ISO-8601. Defaults to 30 days ago."
          schema:
            type: "string"
            format: "date-time"
        -
          name: "to"
          in: "query"
          required: false
          description: "End of the range (exclusive), ISO-8601. Defaults to now."
          schema:
            type: "string"
            format: "date-time"
        -
          name: "sourceType"
          in: "query"
          required: false
          schema:
            type: "string"
            enum:
              - "ai_agent"
              - "ai_generation"
              - "ai_classification"
              - "ai_summarization"
              - "ai_extraction"
              - "ai_sentiment"
              - "tovi"
              - "voice_agent"
        -
          name: "mode"
          in: "query"
          required: false
          description: "Traffic class. Omitted means production only - playground, simulation, preview and node-test spend is recorded but excluded from totals by default."
          schema:
            type: "string"
            enum:
              - "production"
              - "playground"
              - "simulation"
              - "preview"
              - "node_test"
        -
          name: "model"
          in: "query"
          required: false
          schema:
            type: "string"
        -
          name: "provider"
          in: "query"
          required: false
          schema:
            type: "string"
        -
          name: "userId"
          in: "query"
          required: false
          description: "Acting user. System-initiated work is recorded under an explicit system actor."
          schema:
            type: "string"
        -
          name: "sourceName"
          in: "query"
          required: false
          description: "Case-insensitive substring match against the display-name snapshot."
          schema:
            type: "string"
        -
          name: "search"
          in: "query"
          required: false
          description: "Free text matched case-insensitively against the source name, model, provider, acting user and type. Narrows the other filters rather than replacing them. Spaces and underscores are interchangeable, so the displayed 'AI Agent' matches the stored `ai_agent`."
          schema:
            type: "string"
        -
          name: "status"
          in: "query"
          required: false
          description: "Restrict to successful or failed calls. A failed call still spent input tokens and is recorded, so this is how those are reached in a large result set."
          schema:
            type: "string"
            enum:
              - "success"
              - "error"
        -
          name: "organizationId"
          in: "query"
          required: false
          description: "SUPERADMIN only. `all` returns a cross-organization view, which is distinct from omitting the parameter (the caller’s own organization). Ignored for every other role."
          schema:
            type: "string"
        -
          name: "interval"
          in: "query"
          required: false
          description: "Bucket width for the time series."
          schema:
            type: "string"
            enum:
              - "hour"
              - "day"
              - "week"
            default: "day"
      responses:
        "200":
          description: "Consumption summary"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiConsumptionSummaryResponse"
        "400":
          description: "Invalid query parameters"
        "403":
          description: "Caller is not an admin or superadmin"
  "/api/ai-models":
    get:
      operationId: "get_all_ai_models"
      summary: "Get the organization's AI model catalog"
      description: "Returns the authenticated organization's provider and model catalog sorted by providerName. The catalog is initialized once from read-only bootstrap templates and is tenant-isolated thereafter."
      tags:
        - "AI Models"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "AI models returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsListResponse"
        "403":
          description: "Only superadmins can read AI models"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "500":
          description: "Failed to fetch AI models"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
    post:
      operationId: "create_ai_model"
      summary: "Create new AI model (superadmin only)"
      description: "Adds a provider to the authenticated organization's AI model catalog. SUPERADMIN-only. vercelUniqueName must be unique within that organization; duplicates return 400."
      tags:
        - "AI Models"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CreateAiModelRequest"
      responses:
        "201":
          description: "AI model created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelResponse"
        "400":
          description: "Missing required fields or duplicate"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "403":
          description: "Only superadmins can create AI models"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "500":
          description: "Failed to create AI model"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
  "/api/ai-models/{id}":
    get:
      operationId: "get_ai_model_by_id"
      summary: "Get single AI model by ID"
      description: "Returns one provider from the authenticated organization's AI model catalog by _id."
      tags:
        - "AI Models"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "AI model returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelSingleResponse"
        "403":
          description: "Only superadmins can read AI models"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "404":
          description: "AI Model not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "500":
          description: "Failed to fetch AI model"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
    put:
      operationId: "update_ai_model"
      summary: "Update AI model (superadmin only)"
      description: "Updates a provider in the authenticated organization's AI model catalog. SUPERADMIN-only. Provider IDs owned by another organization return 404."
      tags:
        - "AI Models"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateAiModelRequest"
      responses:
        "200":
          description: "AI model updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelResponse"
        "400":
          description: "Duplicate vercelUniqueName"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "403":
          description: "Only superadmins can update AI models"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "404":
          description: "AI Model not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "500":
          description: "Failed to update AI model"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
    delete:
      operationId: "delete_ai_model"
      summary: "Delete AI model (superadmin only)"
      description: "Removes a provider from the authenticated organization's AI model catalog. SUPERADMIN-only; no other organization's catalog is changed."
      tags:
        - "AI Models"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "AI model deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsSimpleSuccessResponse"
        "403":
          description: "Only superadmins can delete AI models"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "409":
          description: "Provider is still referenced by one or more model assignments"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "500":
          description: "Failed to delete AI model"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
  "/api/ai-models/catalog":
    get:
      operationId: "get_ai_model_catalog"
      summary: "Browse supported Vercel AI Gateway models (superadmin only)"
      description: "Fetches the public Vercel AI Gateway catalog on demand and returns normalized language-model metadata for the registry supported providers. This endpoint does not persist models."
      tags:
        - "AI Models"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Gateway model catalog returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsCatalogResponse"
        "403":
          description: "Only superadmins can browse the model catalog"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "502":
          description: "Gateway catalog unavailable or invalid"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "504":
          description: "Gateway catalog request timed out"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
  "/api/ai-models/organization/{organizationId}":
    get:
      operationId: "get_organization_ai_providers"
      summary: "Get organization configured AI providers"
      description: "Legacy endpoint that returns the organization's configured providers (one per registered AiModel) with their API keys masked, plus the currentAiProviderIndex / currentAiModelIndex / currentAiModelVercelUniqueName fields. New consumers should prefer /settings + /assignments instead."
      tags:
        - "AI Models"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Organization AI providers returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsOrganizationProvidersResponse"
        "404":
          description: "Organization credentials not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "500":
          description: "Failed to fetch AI providers"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
  "/api/ai-models/organization/{organizationId}/api-key":
    post:
      operationId: "set_provider_api_key"
      summary: "Set or update API key for a provider"
      description: "Stores or replaces the API key for a single provider (anthropic, openai, google) on the organization's credentials. SUPERADMIN-only and tenant-scoped - callers cannot set keys for organizations they do not belong to. For backward compatibility, the legacy anthropicApiKey field is mirrored when provider=anthropic."
      tags:
        - "AI Models"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/SetProviderApiKeyRequest"
      responses:
        "200":
          description: "API key updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SetProviderApiKeyResponse"
        "400":
          description: "Invalid provider or missing API key"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "403":
          description: "Only superadmins can configure AI provider credentials"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "500":
          description: "Failed to set API key"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
  "/api/ai-models/organization/{organizationId}/api-key/{provider}":
    delete:
      operationId: "remove_provider_api_key"
      summary: "Remove API key for a provider"
      description: "Removes the stored API key for a provider from the organization's credentials. SUPERADMIN-only and tenant-scoped. Removing the anthropic key also clears the legacy anthropicApiKey field."
      tags:
        - "AI Models"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "provider"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "API key removed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsSimpleSuccessResponse"
        "400":
          description: "Invalid provider"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "404":
          description: "Organization credentials not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "500":
          description: "Failed to remove API key"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
  "/api/ai-models/organization/{organizationId}/api-key/{provider}/toggle":
    patch:
      operationId: "toggle_provider_status"
      summary: "Toggle provider enabled/disabled status"
      description: "Flips the isEnabled flag on the stored provider entry. SUPERADMIN-only and tenant-scoped. If only the legacy anthropicApiKey exists for the org, it is migrated into the new providerApiKeys array as part of this call."
      tags:
        - "AI Models"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "provider"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ToggleProviderStatusRequest"
      responses:
        "200":
          description: "Provider status toggled"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsSimpleSuccessResponse"
        "400":
          description: "Invalid provider"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "403":
          description: "Only superadmins can configure AI provider credentials"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "404":
          description: "Organization credentials or provider not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "500":
          description: "Failed to toggle provider status"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
  "/api/ai-models/organization/{organizationId}/assignments":
    get:
      operationId: "get_model_assignments"
      summary: "Get all model assignments for organization"
      description: "Returns the raw section-to-(provider, model) assignment map. Unassigned sections are absent (not defaulted) so the UI can render a setup-required state instead of a hidden default silently taking effect."
      tags:
        - "AI Models"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Model assignments returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsModelAssignmentsResponse"
        "500":
          description: "Failed to fetch model assignments"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
    put:
      operationId: "update_model_assignment"
      summary: "Update model assignment for a system section"
      description: "Assigns a (provider, model) pair to one of the supported system sections - dataExtraction, automations, or messageGeneration. SUPERADMIN-only and tenant-scoped. Validates that the provider and model both exist in the organization's AI model catalog before saving."
      tags:
        - "AI Models"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateModelAssignmentRequest"
      responses:
        "200":
          description: "Model assignment updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UpdateModelAssignmentResponse"
        "400":
          description: "Invalid section, provider, or model"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "403":
          description: "Only superadmins can configure tenant-wide model assignments"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "500":
          description: "Failed to update model assignment"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
  "/api/ai-models/organization/{organizationId}/catalog":
    get:
      operationId: "get_api_ai_models_organization_organizationId_catalog"
      summary: "GET /api/ai-models/organization/{organizationId}/catalog"
      tags:
        - "AI"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/ai-models/organization/{organizationId}/current":
    post:
      operationId: "set_current_ai_model"
      summary: "Set current active AI model for organization"
      description: "Legacy endpoint that sets the organization-wide active model by writing currentAiProviderIndex, currentAiModelIndex and currentAiModelVercelUniqueName. SUPERADMIN-only and tenant-scoped. Superseded by section-based model assignments."
      tags:
        - "AI Models"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/SetCurrentAiModelRequest"
      responses:
        "200":
          description: "Current AI model updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsSimpleSuccessResponse"
        "403":
          description: "Only superadmins can configure tenant-wide model assignments"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "404":
          description: "AI Model not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "500":
          description: "Failed to set current AI model"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
  "/api/ai-models/organization/{organizationId}/policy":
    get:
      operationId: "get_api_ai_models_organization_organizationId_policy"
      summary: "GET /api/ai-models/organization/{organizationId}/policy"
      tags:
        - "AI"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
    put:
      operationId: "put_api_ai_models_organization_organizationId_policy"
      summary: "PUT /api/ai-models/organization/{organizationId}/policy"
      tags:
        - "AI"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/ai-models/organization/{organizationId}/policy/hidden-models":
    post:
      operationId: "post_api_ai_models_organization_organizationId_policy_hidden_models"
      summary: "POST /api/ai-models/organization/{organizationId}/policy/hidden-models"
      tags:
        - "AI"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/ai-models/organization/{organizationId}/provider":
    post:
      operationId: "add_organization_ai_provider"
      summary: "Add AI provider to organization"
      description: "Legacy endpoint that appends an entry to the aiProviders array on OrganizationCredentials with the supplied aiModel (AiModel _id), modelDetail (modelName) and apiKey. SUPERADMIN-only and tenant-scoped. The selected modelDetail must exist within the chosen provider."
      tags:
        - "AI Models"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AddOrganizationAiProviderRequest"
      responses:
        "200":
          description: "Provider added"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsOrganizationProvidersResponse"
        "400":
          description: "Missing required fields or invalid model"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "403":
          description: "Only superadmins can configure AI provider credentials"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "404":
          description: "AI Model not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "500":
          description: "Failed to add AI provider"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
  "/api/ai-models/organization/{organizationId}/provider/{providerId}":
    put:
      operationId: "update_organization_ai_provider"
      summary: "Update an existing AI provider configuration for organization"
      description: "Legacy endpoint that updates the modelDetail and/or apiKey on a single aiProviders entry identified by providerId. SUPERADMIN-only and tenant-scoped. At least one field must be supplied."
      tags:
        - "AI Models"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "providerId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateOrganizationAiProviderRequest"
      responses:
        "200":
          description: "Provider updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsSimpleSuccessResponse"
        "400":
          description: "No fields to update"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "403":
          description: "Only superadmins can configure AI provider credentials"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "404":
          description: "Organization credentials or provider not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "500":
          description: "Failed to update AI provider"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
    delete:
      operationId: "remove_organization_ai_provider"
      summary: "Remove AI provider from organization"
      description: "Legacy endpoint that removes a single aiProviders entry from OrganizationCredentials by providerId, and adjusts currentAiProviderIndex if needed. SUPERADMIN-only and tenant-scoped."
      tags:
        - "AI Models"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "providerId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Provider removed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsSimpleSuccessResponse"
        "404":
          description: "Organization credentials or provider not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
        "500":
          description: "Failed to remove AI provider"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
  "/api/ai-models/organization/{organizationId}/settings":
    get:
      operationId: "get_organization_ai_settings"
      summary: "Get organization AI settings (providers, API key status, model assignments)"
      description: "Returns the per-provider configuration summary (hasApiKey, isEnabled, available models) and current section-based model assignments for the organization. Used by the AI Settings page to render provider cards and section dropdowns."
      tags:
        - "AI Models"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "AI settings returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsOrganizationAiSettingsResponse"
        "500":
          description: "Failed to fetch AI settings"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiModelsErrorResponse"
  "/api/ai-models/organization/{organizationId}/usage":
    get:
      operationId: "get_api_ai_models_organization_organizationId_usage"
      summary: "GET /api/ai-models/organization/{organizationId}/usage"
      tags:
        - "AI"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/ai-models/sync":
    post:
      operationId: "post_api_ai_models_sync"
      summary: "POST /api/ai-models/sync"
      tags:
        - "AI"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/ai/calendar-playground":
    post:
      operationId: "post_ai_calendar_playground"
      summary: "Generate calendar agent playground response"
      description: "Runs a one-off calendar-agent turn for the prompt editor. No promptId is required; the caller supplies the calendar instructions directly via promptOverride. Calendar tools are injected when the ENABLE_CALENDAR_TOOLS feature flag is enabled, so schedulers can exercise booking flows without a live conversation."
      tags:
        - "AI"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AICalendarPlaygroundRequest"
      responses:
        "200":
          description: "Calendar playground response generated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIPlaygroundResponse"
        "400":
          description: "message is required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
        "500":
          description: "Failed to process calendar playground message"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
  "/api/ai/nl-create":
    post:
      operationId: "post_ai_nl_create"
      summary: "Generate XML prompt from natural language"
      description: "Generates a full XML prompt from a natural language instruction, or iteratively refines an existing prompt when conversationHistory and existingPrompt are supplied. Does not persist anything; the returned prompt text is meant to be saved by the caller."
      tags:
        - "AI"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AINLCreateRequest"
      responses:
        "200":
          description: "Prompt drafted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AINLCreateResponse"
        "400":
          description: "instruction is required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
        "500":
          description: "Failed to generate prompt"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
  "/api/ai/nl-edit":
    post:
      operationId: "post_ai_nl_edit"
      summary: "Rewrite a selected prompt section via natural language"
      description: "Rewrites a highlighted section of an XML prompt according to the user instruction while leaving the surrounding prompt untouched. Returns only the replacement text; the caller is responsible for splicing it back into the editor."
      tags:
        - "AI"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AINLEditRequest"
      responses:
        "200":
          description: "Selection rewritten"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AINLEditResponse"
        "400":
          description: "selectedText and instruction are required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
        "500":
          description: "Failed to process NL edit"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
  "/api/ai/playground":
    post:
      operationId: "post_ai_playground"
      summary: "Generate playground AI response"
      description: "Runs a one-off playground turn against the specified prompt using the caller-supplied conversation history. Used by the prompt editor to preview replies; does not persist conversation state. ADMIN and SUPERADMIN callers also receive the captured MessageMetric for the turn."
      tags:
        - "AI"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AIPlaygroundRequest"
      responses:
        "200":
          description: "AI response generated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIPlaygroundResponse"
        "400":
          description: "Message and prompt id are required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
        "404":
          description: "User or prompt not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
        "500":
          description: "Failed to process playground message"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
  "/api/ai/playground/approval/cancel":
    post:
      operationId: "post_ai_playground_approval_cancel"
      summary: "Cancel a pending playground tool approval"
      description: "Cancels a pending playground tool approval card (e.g. when the tester dismisses it). Idempotent: returns success even if the approval has already expired or been consumed."
      tags:
        - "AI"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AIPlaygroundApprovalCancelRequest"
      responses:
        "200":
          description: "Approval cancelled"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AISimpleSuccessResponse"
        "400":
          description: "Invalid request body"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
  "/api/ai/playground/approval/respond":
    post:
      operationId: "post_ai_playground_approval_respond"
      summary: "Respond to a playground tool approval card"
      description: "Resolves a playground approval card by approving or rejecting it. Approving executes the requested tool with the originally captured arguments and resumes the playground turn; rejecting stashes a rejection sentinel so the agent acknowledges and moves on. Returns the resumed AI response and any new approval cards."
      tags:
        - "AI"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AIPlaygroundApprovalRespondRequest"
      responses:
        "200":
          description: "Approval resolved and playground resumed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIPlaygroundApprovalRespondResponse"
        "400":
          description: "Invalid request body"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
        "403":
          description: "Approval owner or organization mismatch"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
        "404":
          description: "Approval expired or already handled"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
        "500":
          description: "Failed to resume playground after approval"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
        "503":
          description: "Approval service temporarily unavailable"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
  "/api/ai/process":
    post:
      operationId: "post_ai_process"
      summary: "Generate AI response for conversation"
      description: "Generates an AI reply for an existing conversation and writes the message back into the conversation. Caller must own the conversation, be assigned to it, or be an ADMIN/SUPERADMIN. Supports optional mergeContextPrompt, followUpProcess, and enableTools overrides."
      tags:
        - "AI"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AIProcessRequest"
      responses:
        "200":
          description: "AI response generated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIProcessResponse"
        "400":
          description: "Invalid conversation id"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
        "403":
          description: "Not authorized for conversation"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
        "404":
          description: "Conversation or context not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
        "500":
          description: "Failed to process chat request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AIErrorResponse"
  "/api/application-management":
    get:
      operationId: "get_application_configs"
      summary: "Get all application management configurations"
      description: "List every application-management configuration the caller can see. Each configuration governs how a given application source (e.g. a CRM webhook) maps fields to Tether and which automations it can trigger."
      tags:
        - "ApplicationConfigs"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Configurations returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationConfigListResponse"
        "400":
          description: "Missing user or organization"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationManagementErrorResponse"
        "500":
          description: "Failed to fetch configurations"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationManagementErrorResponse"
    post:
      operationId: "post_application_config"
      summary: "Create a new application management configuration"
      description: "Create an application-management configuration for the caller's organization. `configurationName` must be unique per-org; `defaultStatus` selects the status applied to new applications when none is provided."
      tags:
        - "ApplicationConfigs"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CreateApplicationConfigRequest"
      responses:
        "201":
          description: "Configuration created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationConfigResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationManagementErrorResponse"
        "500":
          description: "Failed to create configuration"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationManagementErrorResponse"
  "/api/application-management/{id}":
    get:
      operationId: "get_application_config_by_id"
      summary: "Get a specific application management configuration"
      description: "Fetch a single application-management configuration by `_id`. Cross-org reads are rejected."
      tags:
        - "ApplicationConfigs"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Configuration returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationConfigResponse"
        "400":
          description: "Missing required ids"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationManagementErrorResponse"
        "404":
          description: "Configuration not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationManagementErrorResponse"
        "500":
          description: "Failed to fetch configuration"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationManagementErrorResponse"
    put:
      operationId: "put_application_config"
      summary: "Update an application management configuration"
      description: "Update mutable fields on an application-management configuration. Only ADMIN/SUPERADMIN may toggle status or change source mappings."
      tags:
        - "ApplicationConfigs"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateApplicationConfigRequest"
      responses:
        "200":
          description: "Configuration updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationConfigResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationManagementErrorResponse"
        "403":
          description: "Permission denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationManagementErrorResponse"
        "404":
          description: "Configuration not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationManagementErrorResponse"
        "500":
          description: "Failed to update configuration"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationManagementErrorResponse"
    delete:
      operationId: "delete_application_config"
      summary: "Delete an application management configuration"
      description: "Permanently delete the application-management configuration. Existing application records keep their `configurationId` reference but new applications cannot use a deleted configuration."
      tags:
        - "ApplicationConfigs"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Configuration deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationConfigResponse"
        "400":
          description: "Missing required ids"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationManagementErrorResponse"
        "404":
          description: "Configuration not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationManagementErrorResponse"
        "500":
          description: "Failed to delete configuration"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationManagementErrorResponse"
  "/api/application-trigger":
    post:
      operationId: "post_application_trigger"
      summary: "Trigger an application from an external system"
      description: "Webhook entry point used by external systems (mortgage CRMs, custom integrations) to push an application into Tether. Creates or updates the contact (matched by phone), creates the Application record, and emits the downstream events that fire automations. Requires the per-org API key."
      tags:
        - "ApplicationTrigger"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/TriggerApplicationRequest"
      responses:
        "200":
          description: "Application received successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TriggerApplicationResponse"
        "400":
          description: "Missing required fields"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationTriggerErrorResponse"
        "401":
          description: "Invalid or missing API key"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationTriggerErrorResponse"
        "500":
          description: "Error processing application webhook"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationTriggerErrorResponse"
  "/api/applications":
    get:
      operationId: "get_applications"
      summary: "List applications by query filters"
      description: "Returns every Application in the caller organization matching the supplied filters, sorted by `createdAt` desc. No pagination - use `/list` for paginated results. Supports filtering by contact, status, owner, pipeline stage and a free-text search."
      tags:
        - "Applications"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "contactId"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "status"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "search"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "pipelineStage"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "pipelineStageIds"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "assignees"
          required: false
          description: "Filter by assigned user id. Repeat the parameter for several users (matches any). Pass `unassigned` to return applications with no assignees."
          schema:
            type: "string"
      responses:
        "200":
          description: "Applications returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsQueryResponse"
        "500":
          description: "Failed to fetch applications"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsErrorResponse"
    post:
      operationId: "post_applications"
      summary: "Create application"
      description: "Creates a new Application for an existing Contact in the caller organization. The contact must belong to the same organization. The caller must supply either a `status` or a `pipelineStage`; the request resolves the appropriate Pipeline and stage on the way in."
      tags:
        - "Applications"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CreateApplicationRequest"
      responses:
        "201":
          description: "Application created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationMutationResponse"
        "400":
          description: "Missing required fields"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsErrorResponse"
        "404":
          description: "Contact not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsErrorResponse"
        "500":
          description: "Failed to create application"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsErrorResponse"
  "/api/applications/{id}":
    get:
      operationId: "get_application_by_id"
      summary: "Get application by id"
      description: "Returns a single Application with `contactId` and `assignees` populated as partial documents (firstName/lastName/phoneNumber/email and fullName/email respectively). Scoped to the caller organization."
      tags:
        - "Applications"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Application returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationSingleResponse"
        "404":
          description: "Application not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsErrorResponse"
        "500":
          description: "Failed to fetch application"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsErrorResponse"
    put:
      operationId: "put_application"
      summary: "Update application"
      description: "Patches mutable fields on an Application (status, pipelineStage, pipelineId, owner, custom fields). Pipeline-stage transitions are resolved against the application's pipeline before saving. `fromHistoryModal` suppresses some side-effects when set."
      tags:
        - "Applications"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateApplicationRequest"
      responses:
        "200":
          description: "Application updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationMutationResponse"
        "400":
          description: "Application id is required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsErrorResponse"
        "404":
          description: "Application not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsErrorResponse"
        "500":
          description: "Failed to update application"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsErrorResponse"
    delete:
      operationId: "delete_application"
      summary: "Delete application"
      description: "Permanently deletes an Application from the caller organization. Conversations remain in place - only the Application record is removed."
      tags:
        - "Applications"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Application deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsSimpleSuccessResponse"
        "404":
          description: "Application not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsErrorResponse"
        "500":
          description: "Failed to delete application"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsErrorResponse"
  "/api/applications/{id}/archive":
    post:
      operationId: "post_api_applications_id_archive"
      summary: "POST /api/applications/{id}/archive"
      tags:
        - "Applications"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/applications/{id}/assignees":
    put:
      operationId: "put_application_assignees"
      summary: "Set application assignees"
      description: "Replaces the assignee list on an Application. Assignment, not ownership: several users may be assigned, and `[]` is a valid unassigned state. Any member of the organization may assign; every assignee must belong to the application's own organization. This is the only write path for `assignees` - the generic `PUT /api/applications/{id}` ignores the field. Revisioned: pass the `expectedRevision` you read, and a `commandIdempotencyKey` so a retry is not applied twice."
      tags:
        - "Applications"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/SetApplicationAssigneesRequest"
      responses:
        "200":
          description: "Assignees updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationMutationResponse"
        "400":
          description: "Invalid request, or an assignee outside the organization"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsErrorResponse"
        "404":
          description: "Application not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsErrorResponse"
        "409":
          description: "Conflict. `REVISION_CONFLICT` (or `APPLICATION_REVISION_CONFLICT`) means the application changed first - re-read it and reapply. A reused idempotency key also returns 409, so branch on the code, not the status."
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsErrorResponse"
        "500":
          description: "Failed to update assignees"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsErrorResponse"
  "/api/applications/{id}/command":
    put:
      operationId: "put_api_applications_id_command"
      summary: "PUT /api/applications/{id}/command"
      tags:
        - "Applications"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/applications/{id}/conversations":
    get:
      operationId: "get_application_conversations"
      summary: "Get conversations linked to application"
      description: "Returns the Conversations linked to the Application (via its Contact) as a flat array plus a `count`. Selected fields only, with a derived `conversationState` from the latest message map. Note: response is NOT wrapped in a `{ success, data }` envelope."
      tags:
        - "Applications"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Conversations returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationConversationsResponse"
        "404":
          description: "Application not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsBareErrorResponse"
        "500":
          description: "Failed to get application conversations"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsBareErrorResponse"
  "/api/applications/{id}/stage":
    put:
      operationId: "put_api_applications_id_stage"
      summary: "PUT /api/applications/{id}/stage"
      tags:
        - "Applications"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/applications/{id}/time-to-contact":
    get:
      operationId: "get_application_time_to_contact"
      summary: "Calculate application time-to-contact"
      description: "Calculates the elapsed time between when the Application was created and the first outbound message in any linked Conversation. Returns `timeToContact: null` (and an explanatory message) when no outbound message has been sent yet."
      tags:
        - "Applications"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Time-to-contact returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationTimeToContactResponse"
        "400":
          description: "Invalid application ID or missing creation date"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsBareErrorResponse"
        "404":
          description: "Application not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsBareErrorResponse"
        "500":
          description: "Failed to calculate time-to-contact"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsBareErrorResponse"
  "/api/applications/canonical":
    get:
      operationId: "get_api_applications_canonical"
      summary: "GET /api/applications/canonical"
      tags:
        - "Applications"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/applications/commands/create":
    post:
      operationId: "post_api_applications_commands_create"
      summary: "POST /api/applications/commands/create"
      tags:
        - "Applications"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/applications/list":
    post:
      operationId: "post_applications_list"
      summary: "List applications with pagination"
      description: "Returns a paginated, filterable list of Applications in the caller organization. Body fields (page, size, search, status, contactId, etc.) are all optional; sensible defaults apply (page=1, size=10)."
      tags:
        - "Applications"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ListApplicationsRequest"
      responses:
        "200":
          description: "Applications returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsPaginatedListResponse"
        "500":
          description: "Failed to fetch applications"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplicationsErrorResponse"
  "/api/applications/validate":
    post:
      operationId: "post_api_applications_validate"
      summary: "POST /api/applications/validate"
      tags:
        - "Applications"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/approval/internal/{id}/approve":
    post:
      operationId: "post_approval_internal_approve"
      summary: "Approve a pending internal approval request"
      description: "Approves a pending INTERNAL approval request as the authenticated agent. Executes the deferred tool with the originally captured arguments; on success the approval transitions to `approved` and the result is attached; on tool failure it transitions to `failed` and a failureReason is recorded."
      tags:
        - "Approval"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ApprovalInternalActionRequest"
      responses:
        "200":
          description: "Internal approval approved"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApprovalInternalActionResponse"
        "400":
          description: "Missing approvalRequestId or response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApprovalErrorResponse"
        "401":
          description: "Authentication required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApprovalErrorResponse"
        "409":
          description: "Internal approval not found or already responded"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApprovalErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApprovalErrorResponse"
  "/api/approval/internal/{id}/reject":
    post:
      operationId: "post_approval_internal_reject"
      summary: "Reject a pending internal approval request"
      description: "Rejects a pending INTERNAL approval request as the authenticated agent. Optional `notes` are persisted to `rejectionNotes`. The deferred tool is not executed; the agent autopilot is notified so it can acknowledge and continue."
      tags:
        - "Approval"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ApprovalInternalActionRequest"
      responses:
        "200":
          description: "Internal approval rejected"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApprovalInternalActionResponse"
        "400":
          description: "Missing approvalRequestId or response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApprovalErrorResponse"
        "401":
          description: "Authentication required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApprovalErrorResponse"
        "409":
          description: "Internal approval not found or already responded"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApprovalErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApprovalErrorResponse"
  "/api/approval/internal/list":
    get:
      operationId: "get_approval_internal_list"
      summary: "List internal approval requests for the organization"
      description: "Returns paginated INTERNAL approval requests for the caller organization, sorted newest first, with userId / approvedBy / contactId / escalationTargets populated. Restricted to SUPERADMIN, ADMIN, and DEPARTMENT_HEAD roles. The `status` query supports comma-separated values for history views (e.g. `approved,rejected,failed`); defaults to `pending`."
      tags:
        - "Approval"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "status"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "limit"
          required: false
          schema:
            type: "integer"
            minimum: 1
            maximum: 100
            default: 50
        -
          in: "query"
          name: "skip"
          required: false
          schema:
            type: "integer"
            minimum: 0
            default: 0
      responses:
        "200":
          description: "Internal approvals returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApprovalListResponse"
        "401":
          description: "Authentication required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApprovalErrorResponse"
        "403":
          description: "Caller lacks required role"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApprovalErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApprovalErrorResponse"
  "/api/approval/respond":
    post:
      operationId: "post_approval_respond"
      summary: "Submit a contact approval/rejection from the webchat widget"
      description: "Unauthenticated endpoint called from the webchat widget when a contact taps approve/reject on an approval card. The atomic transition only succeeds for pending CONTACT-type requests whose webchatId matches the supplied value; approvals trigger execution of the deferred tool and (on failure) record a failureReason."
      tags:
        - "Approval"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ApprovalRespondRequest"
      responses:
        "200":
          description: "Approval response processed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApprovalRespondResponse"
        "400":
          description: "Missing or invalid response value"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApprovalErrorResponse"
        "403":
          description: "Webchat id does not match the approval request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApprovalErrorResponse"
        "409":
          description: "Approval request not found or already responded"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApprovalErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApprovalErrorResponse"
  "/api/auth-connections":
    get:
      operationId: "get_auth_connections"
      summary: "List auth connections"
      description: "Every auth connection in the organization, without credentials: the client secret and the private key are stored encrypted and are never returned by any endpoint. Admin only. A workflow author uses `/api/auth-connections/options` instead."
      tags:
        - "Auth Connections"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "organizationId"
          required: false
          schema:
            type: "string"
            pattern: "^[a-f\\d]{24}$"
          description: "Organization to act on. Defaults to the caller's own when omitted or empty. Only a SUPERADMIN may name a different one; an ADMIN doing so is refused with 403, and a value that is not an ObjectId is refused with 400 rather than falling back to the caller's own organization."
      responses:
        "200":
          description: "Connections returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionListResponse"
        "400":
          description: "`organizationId` was given but is not an ObjectId"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
        "403":
          description: "Not an admin, or naming another organization without being a superadmin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
    post:
      operationId: "post_auth_connections"
      summary: "Create an auth connection"
      description: "Stores the gateway credentials and generates the key pair the DPoP proofs are signed with. The private half never leaves the server and there is no endpoint that accepts one, so a connection can only ever be bound to a key this server made. The token URL must be https, since the client secret is posted to it."
      tags:
        - "Auth Connections"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "organizationId"
          required: false
          schema:
            type: "string"
            pattern: "^[a-f\\d]{24}$"
          description: "Organization to act on. Defaults to the caller's own when omitted or empty. Only a SUPERADMIN may name a different one; an ADMIN doing so is refused with 403, and a value that is not an ObjectId is refused with 400 rather than falling back to the caller's own organization."
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AuthConnectionCreateRequest"
      responses:
        "201":
          description: "Connection created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionResponse"
        "400":
          description: "Validation error, or `organizationId` is not an ObjectId"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
        "403":
          description: "Not an admin, or naming another organization without being a superadmin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
        "409":
          description: "A connection with that name already exists"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
  "/api/auth-connections/{connectionId}":
    get:
      operationId: "get_auth_connection_by_id"
      summary: "Get one auth connection"
      description: "Scoped to the organization, so a connection belonging to another one reads as 404 rather than 403. Credentials are not included."
      tags:
        - "Auth Connections"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "connectionId"
          required: true
          schema:
            type: "string"
            pattern: "^[a-f\\d]{24}$"
          description: "The connection id. Must be an ObjectId."
        -
          in: "query"
          name: "organizationId"
          required: false
          schema:
            type: "string"
            pattern: "^[a-f\\d]{24}$"
          description: "Organization to act on. Defaults to the caller's own when omitted or empty. Only a SUPERADMIN may name a different one; an ADMIN doing so is refused with 403, and a value that is not an ObjectId is refused with 400 rather than falling back to the caller's own organization."
      responses:
        "200":
          description: "Connection returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionResponse"
        "400":
          description: "The connection id or `organizationId` is not an ObjectId"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
        "403":
          description: "Not an admin, or naming another organization without being a superadmin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
        "404":
          description: "No such connection"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
    put:
      operationId: "put_auth_connection_by_id"
      summary: "Update an auth connection"
      description: "Every field is optional, so editing the allowlist does not force the secret to be re-entered: omitting `clientSecret` leaves the stored one alone. Changing the secret drops the cached access token, so a rotation takes effect on the next call without a deploy."
      tags:
        - "Auth Connections"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "connectionId"
          required: true
          schema:
            type: "string"
            pattern: "^[a-f\\d]{24}$"
          description: "The connection id. Must be an ObjectId."
        -
          in: "query"
          name: "organizationId"
          required: false
          schema:
            type: "string"
            pattern: "^[a-f\\d]{24}$"
          description: "Organization to act on. Defaults to the caller's own when omitted or empty. Only a SUPERADMIN may name a different one; an ADMIN doing so is refused with 403, and a value that is not an ObjectId is refused with 400 rather than falling back to the caller's own organization."
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AuthConnectionUpdateRequest"
      responses:
        "200":
          description: "Connection updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionResponse"
        "400":
          description: "Validation error, or the connection id or `organizationId` is not an ObjectId"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
        "403":
          description: "Not an admin, or naming another organization without being a superadmin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
        "404":
          description: "No such connection"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
        "409":
          description: "A connection with that name already exists"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
    delete:
      operationId: "delete_auth_connection_by_id"
      summary: "Delete an auth connection"
      description: "Any workflow still pointing at this connection begins failing its authenticated calls. The cached token is dropped with it."
      tags:
        - "Auth Connections"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "connectionId"
          required: true
          schema:
            type: "string"
            pattern: "^[a-f\\d]{24}$"
          description: "The connection id. Must be an ObjectId."
        -
          in: "query"
          name: "organizationId"
          required: false
          schema:
            type: "string"
            pattern: "^[a-f\\d]{24}$"
          description: "Organization to act on. Defaults to the caller's own when omitted or empty. Only a SUPERADMIN may name a different one; an ADMIN doing so is refused with 403, and a value that is not an ObjectId is refused with 400 rather than falling back to the caller's own organization."
      responses:
        "200":
          description: "Connection deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionDeleteResponse"
        "400":
          description: "The connection id or `organizationId` is not an ObjectId"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
        "403":
          description: "Not an admin, or naming another organization without being a superadmin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
        "404":
          description: "No such connection"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
  "/api/auth-connections/{connectionId}/regenerate-key":
    post:
      operationId: "post_auth_connection_regenerate_key"
      summary: "Generate a new key pair"
      description: "Replaces the key pair and invalidates the access token bound to the old one. Not reversible, and calls through this connection fail until the new public key is registered with the gateway, so the UI confirms first. No workflow needs editing."
      tags:
        - "Auth Connections"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "connectionId"
          required: true
          schema:
            type: "string"
            pattern: "^[a-f\\d]{24}$"
          description: "The connection id. Must be an ObjectId."
        -
          in: "query"
          name: "organizationId"
          required: false
          schema:
            type: "string"
            pattern: "^[a-f\\d]{24}$"
          description: "Organization to act on. Defaults to the caller's own when omitted or empty. Only a SUPERADMIN may name a different one; an ADMIN doing so is refused with 403, and a value that is not an ObjectId is refused with 400 rather than falling back to the caller's own organization."
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AuthConnectionRegenerateKeyRequest"
      responses:
        "200":
          description: "New key pair generated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionResponse"
        "400":
          description: "The connection id or `organizationId` is not an ObjectId"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
        "403":
          description: "Not an admin, or naming another organization without being a superadmin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
        "404":
          description: "No such connection"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
  "/api/auth-connections/{connectionId}/test":
    post:
      operationId: "post_auth_connection_test"
      summary: "Test the credentials"
      description: "Performs a real client-credentials token request against the gateway, bypassing the cache, so a bad credential is found here rather than inside a customer-facing workflow run. The token itself is never returned; the response carries only whether it worked and when it expires. The outcome is also stored for the health display."
      tags:
        - "Auth Connections"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "connectionId"
          required: true
          schema:
            type: "string"
            pattern: "^[a-f\\d]{24}$"
          description: "The connection id. Must be an ObjectId."
        -
          in: "query"
          name: "organizationId"
          required: false
          schema:
            type: "string"
            pattern: "^[a-f\\d]{24}$"
          description: "Organization to act on. Defaults to the caller's own when omitted or empty. Only a SUPERADMIN may name a different one; an ADMIN doing so is refused with 403, and a value that is not an ObjectId is refused with 400 rather than falling back to the caller's own organization."
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AuthConnectionTestRequest"
      responses:
        "200":
          description: "Test completed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionTestResponse"
        "400":
          description: "The connection id or `organizationId` is not an ObjectId"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
        "403":
          description: "Not an admin, or naming another organization without being a superadmin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
        "404":
          description: "No such connection"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
  "/api/auth-connections/options":
    get:
      operationId: "get_auth_connections_options"
      summary: "List connections for the HTTP node picker"
      description: "Name, id and active flag only. Deliberately outside the admin gate: selecting a connection on an HTTP node is authoring rather than administration, and every role can author a workflow. Carries no credentials, no URLs and no key material."
      tags:
        - "Auth Connections"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "organizationId"
          required: false
          schema:
            type: "string"
            pattern: "^[a-f\\d]{24}$"
          description: "Organization to act on. Defaults to the caller's own when omitted or empty. Only a SUPERADMIN may name a different one; an ADMIN doing so is refused with 403, and a value that is not an ObjectId is refused with 400 rather than falling back to the caller's own organization."
      responses:
        "200":
          description: "Connection options returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionOptionListResponse"
        "400":
          description: "`organizationId` was given but is not an ObjectId"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
        "403":
          description: "Naming another organization without being a superadmin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthConnectionErrorResponse"
  "/api/auth/activity":
    post:
      operationId: "post_auth_activity"
      summary: "Track authenticated user activity heartbeat"
      description: "Heartbeat endpoint called periodically by the client to update the authenticated user's lastActivity timestamp. Used by org-level idle-timeout enforcement during refresh."
      tags:
        - "Auth"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Activity tracked"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthActivitySuccessResponse"
        "401":
          description: "Authentication required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
        "500":
          description: "Activity tracking failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
  "/api/auth/exit-impersonation":
    post:
      operationId: "post_auth_exit_impersonation"
      summary: "Exit impersonation and restore original admin session"
      description: "Verify the supplied original-admin token (captured at impersonation start) and return it so the client can restore the admin session. Only callable from a session whose token carries the isImpersonation flag."
      tags:
        - "Auth"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AuthExitImpersonationRequest"
      responses:
        "200":
          description: "Impersonation exited"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthExitImpersonationResponse"
        "400":
          description: "Not in impersonation mode or missing original admin credentials"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
        "401":
          description: "Invalid original admin token"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
  "/api/auth/impersonate/{userId}":
    get:
      operationId: "get_auth_impersonate_user"
      summary: "Get impersonation credentials for a user"
      description: "Issue an impersonation token that lets a SUPERADMIN (or ADMIN within their own organization) sign in as the target user via /api/auth/login. Also returns the caller's original-admin token so the impersonated session can later be exited via /api/auth/exit-impersonation."
      tags:
        - "Auth"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "userId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Impersonation credentials returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthImpersonateCredentialsResponse"
        "400":
          description: "User ID is required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
        "403":
          description: "Caller is not allowed to impersonate this user"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
        "500":
          description: "Failed to get impersonation credentials"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
  "/api/auth/login":
    post:
      operationId: "post_auth_login"
      summary: "Login with password or impersonation token"
      description: "Authenticate a user with email + password or with an impersonation token issued by /api/auth/impersonate/{userId}. On success returns an access token, a refresh token, the user payload, and the resolved session config."
      tags:
        - "Auth"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AuthLoginRequest"
      responses:
        "200":
          description: "Login successful"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthLoginResponse"
        "401":
          description: "Invalid credentials"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
        "403":
          description: "Account disabled or password auth disabled"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
        "404":
          description: "User not found (returned as invalid-credentials for security)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
  "/api/auth/okta/authorize":
    get:
      operationId: "get_auth_okta_authorize"
      summary: "Start Okta authorization flow via WorkOS"
      description: "Public endpoint invoked by the browser to begin SSO via Okta (brokered through WorkOS SSO). Builds the Okta authorization URL and responds with a 302 redirect. Returns 400 when WorkOS or the Okta connection is not configured."
      tags:
        - "Auth"
      parameters:
        -
          in: "query"
          name: "redirect_uri"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "state"
          required: false
          schema:
            type: "string"
      responses:
        "302":
          description: "Redirect to Okta authorization URL"
        "400":
          description: "Okta or WorkOS is not configured"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
        "500":
          description: "Failed to initiate Okta login"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
  "/api/auth/password-requirements":
    get:
      operationId: "get_api_auth_password_requirements"
      summary: "GET /api/auth/password-requirements"
      tags:
        - "Auth"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
  "/api/auth/refresh":
    post:
      operationId: "post_auth_refresh"
      summary: "Refresh session tokens"
      description: "Exchange a valid refresh token for a new access token, socket token, and rotated refresh token. The supplied refresh token is consumed and replaced; an expired or unknown token returns 401."
      tags:
        - "Auth"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AuthRefreshTokenRequest"
      responses:
        "200":
          description: "Token refreshed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthRefreshResponse"
        "400":
          description: "Missing refresh token"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
        "401":
          description: "Invalid, expired, or inactive refresh token"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
        "403":
          description: "Account disabled"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
  "/api/auth/register":
    post:
      operationId: "post_auth_register"
      summary: "Register user"
      description: "Create a new user account using an authenticated session. Superadmins may create Admin, Department Head, or Sales Rep accounts in any existing organization; admins may create Department Head or Sales Rep accounts in their own organization; department heads may create Sales Rep accounts only in their own department. Sales Reps cannot create accounts, and SUPERADMIN creation is always forbidden. Any supplied department must belong to the target organization. When WorkOS is enabled the user is also provisioned in WorkOS; otherwise the password is validated locally and hashed before persistence."
      tags:
        - "Auth"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AuthRegisterRequest"
      responses:
        "201":
          description: "User registered"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthRegisterResponse"
        "400":
          description: "Invalid payload, missing organization, duplicate email, or password does not meet requirements"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthRegisterErrorResponse"
        "401":
          description: "Missing, invalid, or expired token"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
        "403":
          description: "Account disabled, forbidden role, or organization/department scope violation"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
        "404":
          description: "Organization or department not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
        "500":
          description: "WorkOS provisioning failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
  "/api/auth/verify-token":
    get:
      operationId: "get_auth_verify_token"
      summary: "Verify the bearer token is valid"
      description: "Cheap probe that verifies the access token in the Authorization header is signed and unexpired. Returns 200 with a confirmation message when valid, 401 otherwise. A 401 always carries a `code`: `TOKEN_EXPIRED` means the token ran out and the refresh token behind it should be used, while `TOKEN_INVALID` means the session is over. Treating the two alike signs out a session that was never refused. Only a 401 is a verdict on the token: a 503 with `AUTH_UNAVAILABLE` means the check itself failed, and any other non-2xx comes from something in front of the API, so neither should end the session. Used by the client to gate startup before mounting authenticated routes."
      tags:
        - "Auth"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Token is valid"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthVerifyTokenResponse"
        "401":
          description: "Missing, invalid, or expired token"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
        "503":
          description: "The token could not be checked; try again"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
  "/api/auth/workos/authorize":
    get:
      operationId: "get_auth_workos_authorize"
      summary: "Start WorkOS authorization flow"
      description: "Public endpoint invoked by the browser to begin WorkOS AuthKit sign-in. Builds the authorization URL with redirect_uri, state, optional login_hint/organization_id/prompt and responds with a 302 redirect to WorkOS."
      tags:
        - "Auth"
      parameters:
        -
          in: "query"
          name: "redirect_uri"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "state"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "login_hint"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "organization_id"
          required: false
          schema:
            type: "string"
          description: "Only forwarded when the value starts with \"org_\"."
        -
          in: "query"
          name: "prompt"
          required: false
          schema:
            type: "string"
      responses:
        "302":
          description: "Redirect to WorkOS authorization URL"
        "400":
          description: "WorkOS is not enabled or client id missing"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
        "500":
          description: "Failed to initiate WorkOS login"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
  "/api/auth/workos/callback":
    get:
      operationId: "get_auth_workos_callback"
      summary: "Handle WorkOS callback (browser redirect)"
      description: "Called by the WorkOS/Okta provider in the browser after authorization. Exchanges the code with WorkOS (SSO first, then AuthKit fallback), upserts the user in MongoDB, and 302 redirects back to the frontend sign-in page so the SPA can finalize the session via POST callback."
      tags:
        - "Auth"
      parameters:
        -
          in: "query"
          name: "code"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "state"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "error"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "redirect_uri"
          required: false
          schema:
            type: "string"
      responses:
        "302":
          description: "Redirect back to frontend sign-in page"
        "500":
          description: "Callback handling failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
    post:
      operationId: "post_auth_workos_callback"
      summary: "Handle WorkOS callback (API response mode)"
      description: "Called by the SPA after the browser redirect to finalize the WorkOS session. Exchanges the authorization code, upserts the user, and returns access/refresh tokens plus the resolved session config - the JSON equivalent of the GET callback redirect."
      tags:
        - "Auth"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AuthWorkOSCallbackRequest"
      responses:
        "200":
          description: "Auth session created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthLoginResponse"
        "400":
          description: "No authorization code or callback error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
        "500":
          description: "Callback handling failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
  "/api/auth/workos/client-id":
    get:
      operationId: "get_auth_workos_client_id"
      summary: "Get WorkOS client id"
      description: "Public endpoint that returns the WorkOS client id the SPA needs to bootstrap AuthKit. Returns 500 when WORKOS_CLIENT_ID is not configured on the server."
      tags:
        - "Auth"
      responses:
        "200":
          description: "Client id returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthWorkOSClientIdResponse"
        "500":
          description: "WorkOS client id is not configured"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AuthErrorResponse"
  "/api/automations":
    get:
      operationId: "get_automations"
      summary: "Get all automations for the organization"
      description: "Returns every Automation in the caller organization, sorted by `createdAt` desc, enriched with the calling user's SMS notification settings. Empty action arrays are stripped from the response."
      tags:
        - "Automations"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Automations list returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AutomationsListResponse"
        "400":
          description: "Organization ID and User ID are required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AutomationsErrorResponse"
    post:
      operationId: "post_automations"
      summary: "Create a new automation"
      description: "Creates a new Automation in the caller organization. The trigger logic (event vs timer), conditions, schedule and actions are all configurable. The `enabled` field in the body sets the calling user's per-automation preference at creation time (defaults to `true`); it does NOT set a global enabled flag on the Automation itself, and other users start with no preference until they call PATCH /{id}/preference."
      tags:
        - "Automations"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AutomationCreateRequest"
      responses:
        "201":
          description: "Automation created successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AutomationMutationResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AutomationsErrorResponse"
        "500":
          description: "Error creating automation"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AutomationsErrorResponse"
  "/api/automations/{id}":
    get:
      operationId: "get_automations_by_id"
      summary: "Get a specific automation by ID"
      description: "Returns a single Automation in the caller organization, enriched with the caller's SMS notification settings. Empty action arrays are stripped from the response."
      tags:
        - "Automations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Automation returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AutomationSingleResponse"
        "404":
          description: "Automation not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AutomationsErrorResponse"
    put:
      operationId: "put_automations_by_id"
      summary: "Update an existing automation"
      description: "Updates editable fields on an Automation owned by the caller. Schedule, timerLogic, conditions, and actions are replaced wholesale when provided; omit fields to leave them unchanged."
      tags:
        - "Automations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AutomationUpdateRequest"
      responses:
        "200":
          description: "Automation updated successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AutomationMutationResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AutomationsErrorResponse"
        "404":
          description: "Automation not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AutomationsErrorResponse"
        "500":
          description: "Error updating automation"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AutomationsErrorResponse"
    delete:
      operationId: "delete_automations_by_id"
      summary: "Delete an automation"
      description: "Permanently deletes an Automation in the caller organization. Per-user SMS notification settings stored on User documents under `automations[automationId]` are not auto-cleaned and become inert."
      tags:
        - "Automations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Automation deleted successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AutomationsSimpleSuccessResponse"
        "404":
          description: "Automation not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AutomationsErrorResponse"
  "/api/automations/{id}/sms-settings":
    patch:
      operationId: "patch_automations_sms_settings"
      summary: "Update user-specific SMS notification settings for an automation"
      description: "Updates the calling user's per-automation SMS notification configuration (enabled flag, recipient phone numbers, custom message body, optional template id). Stored on the User document; the Automation itself is not modified."
      tags:
        - "Automations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AutomationSmsSettingsRequest"
      responses:
        "200":
          description: "SMS notification settings updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AutomationSmsSettingsResponse"
        "404":
          description: "Automation not found in your organization"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AutomationsErrorResponse"
  "/api/calls/{callId}":
    get:
      operationId: "get_calls_callId"
      summary: "Get a single call by ID"
      description: "Returns a `Call` document scoped to the caller's organization with `contactId` and `userId` populated (`userId` is absent for AI calls nobody placed; see `createdBy`). Used by the call-detail drawer / call card."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "callId"
          required: true
          schema:
            type: "string"
          description: "The provider-agnostic `callId` minted by Tether (also used as `providerCallId` for SDK calls)."
      responses:
        "200":
          description: "Call document"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsSingleCallResponse"
        "400":
          description: "callId missing or invalid"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "404":
          description: "Call not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/{callId}/discard":
    post:
      operationId: "post_calls_callId_discard"
      summary: "Discard a dialpad call record"
      description: "Deletes the `Call` document and, if its linked voice `Conversation` has no messages, deletes that conversation too. If `deleteContact: true` is supplied with `contactId`, also deletes a newly-created placeholder contact (`firstName: \"New Contact\"`, `source: \"Outgoing Call\"`) and emits `contact_removed`. Safe no-op if the call was already deleted. Used when a user dials a wrong number from the dialpad."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "callId"
          required: true
          schema:
            type: "string"
          description: "The provider-agnostic `callId` minted by Tether (also used as `providerCallId` for SDK calls)."
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CallsDiscardCallRequest"
      responses:
        "200":
          description: "Call discarded (or not found, treated as success)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsSimpleSuccessResponse"
        "400":
          description: "callId missing"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "500":
          description: "Internal error during discard"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/{callId}/hold":
    post:
      operationId: "post_api_calls_callId_hold"
      summary: "POST /api/calls/{callId}/hold"
      tags:
        - "Calls"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "callId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/calls/{callId}/mute":
    post:
      operationId: "post_api_calls_callId_mute"
      summary: "POST /api/calls/{callId}/mute"
      tags:
        - "Calls"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "callId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/calls/{callId}/recording":
    get:
      operationId: "get_calls_callId_recording"
      summary: "Get a call recording (audio + transcription)"
      description: "Returns the audio recording for a completed call along with any available transcription. The shape depends on the provider: Twilio recordings are fetched server-side and returned as a base64 `audioData` blob; Sinch / ElevenLabs / external recordings are returned as a signed `audioUrl` (S3 or R2). Transcriptions are lazy-fetched/transformed on first read and cached on the `Call` document."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "callId"
          required: true
          schema:
            type: "string"
          description: "The provider-agnostic `callId` minted by Tether (also used as `providerCallId` for SDK calls)."
      responses:
        "200":
          description: "Recording payload"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsRecordingResponse"
        "400":
          description: "callId missing, unsupported provider, or Twilio creds missing"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "404":
          description: "Call or recording not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "500":
          description: "Failed to fetch or sign the recording"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/{callId}/resume":
    post:
      operationId: "post_api_calls_callId_resume"
      summary: "POST /api/calls/{callId}/resume"
      tags:
        - "Calls"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "callId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/calls/{callId}/terminate":
    post:
      operationId: "post_calls_callId_terminate"
      summary: "Terminate an active call"
      description: "Asks the underlying voice provider (Sinch or Twilio, depending on the call's `provider` field) to hang up the active call and marks the local `Call` record as ended. Used by the dialer's \"End call\" button."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "callId"
          required: true
          schema:
            type: "string"
          description: "The provider-agnostic `callId` minted by Tether (also used as `providerCallId` for SDK calls)."
      responses:
        "200":
          description: "Call terminated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsSimpleSuccessResponse"
        "400":
          description: "callId missing or termination failed at the provider"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/{callId}/transfer":
    post:
      operationId: "post_api_calls_callId_transfer"
      summary: "POST /api/calls/{callId}/transfer"
      tags:
        - "Calls"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "callId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/calls/{callId}/transfer/cancel":
    post:
      operationId: "post_api_calls_callId_transfer_cancel"
      summary: "POST /api/calls/{callId}/transfer/cancel"
      tags:
        - "Calls"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "callId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/calls/{callId}/transfer/complete":
    post:
      operationId: "post_api_calls_callId_transfer_complete"
      summary: "POST /api/calls/{callId}/transfer/complete"
      tags:
        - "Calls"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "callId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/calls/{callId}/wrap-up":
    patch:
      operationId: "patch_api_calls_callId_wrap_up"
      summary: "PATCH /api/calls/{callId}/wrap-up"
      tags:
        - "Calls"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "callId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/calls/ai/concurrency":
    get:
      operationId: "get_api_calls_ai_concurrency"
      summary: "GET /api/calls/ai/concurrency"
      tags:
        - "Calls"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/calls/ai/outbound":
    post:
      operationId: "post_calls_ai_outbound"
      summary: "Initiate an outbound AI voice call"
      description: "Places an outbound call to a contact using the configured AI voice provider (currently ElevenLabs, which originates into the Sinch Voice API SIP termination endpoint). Resolves or creates the contact, picks a voice-enabled agent (Prompt), picks a Sinch number permitted to dial with the AI (`routing.outbound.ai`) to call from, and asks the provider to dial. Guarded by a 30s Redis idempotency lock keyed on user+contact+agent+toNumber; concurrent retries return 429 with `OUTBOUND_IN_FLIGHT`. Caches conversation context for the post-call webhook."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CallsInitiateOutboundAiCallRequest"
      responses:
        "200":
          description: "AI call initiated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsOutboundAiCallResponse"
        "400":
          description: "Missing contact/phone, agent not synced, or no AI-enabled number"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "404":
          description: "Contact or user not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "429":
          description: "Duplicate outbound dial in flight"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "500":
          description: "Provider failure"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/ai/outbound-lines":
    get:
      operationId: "get_api_calls_ai_outbound_lines"
      summary: "GET /api/calls/ai/outbound-lines"
      tags:
        - "Calls"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/calls/history":
    get:
      operationId: "get_calls_history"
      summary: "List calls with filters"
      description: "Returns a paginated list of calls for the authenticated user's organization. Filterable by `contactId`, `userId`, and `status`. Results are sorted by `createdAt` descending with `contactId` and `userId` populated. `userId` is the person who placed or took the call; AI calls nobody placed (inbound AI calls, workflow-placed AI calls) have no `userId`, and `createdBy` names the AI agent instead. For ElevenLabs recordings stored in R2, signed playback URLs are generated inline."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "contactId"
          required: false
          schema:
            type: "string"
          description: "Filter by contact ObjectId."
        -
          in: "query"
          name: "userId"
          required: false
          schema:
            type: "string"
          description: "Filter by user ObjectId."
        -
          in: "query"
          name: "status"
          required: false
          schema:
            type: "string"
          description: "Filter by call status (e.g. `completed`, `no-answer`, `failed`)."
        -
          in: "query"
          name: "limit"
          required: false
          schema:
            type: "string"
          description: "Page size as a string (parsed to int; default 50)."
        -
          in: "query"
          name: "offset"
          required: false
          schema:
            type: "string"
          description: "Skip count as a string (parsed to int; default 0)."
      responses:
        "200":
          description: "Call history page"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsHistoryResponse"
        "400":
          description: "Validation or internal failure"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/ingest":
    post:
      operationId: "post_calls_ingest"
      summary: "Ingest an externally completed call record"
      description: "Public ingestion endpoint for vendor-agnostic external calling systems to push completed call records into Tether. Authenticated via a user-scoped API key (Bearer token from `GET /api/user/api-key`) - does NOT use the standard JWT auth. Creates the same `Contact` / `Conversation` / `Call` / recording artifacts as the ElevenLabs post-call webhook. Idempotent on `externalCallId`. Uploads recordings (base64 MP3 or URL) to R2. Emits `call_activity` (`contactId`/`conversationId` only), `call_ended`, `call_recording_ready`, and `fetch_messages` socket events."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CallsIngestExternalCallRequest"
      responses:
        "200":
          description: "Duplicate detected via externalCallId - existing record returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsIngestDedupResponse"
        "201":
          description: "Call ingested"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsIngestCreatedResponse"
        "400":
          description: "Validation error or recording could not be processed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsIngestErrorResponse"
        "401":
          description: "Missing or invalid API key"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsIngestErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsIngestErrorResponse"
  "/api/calls/providers":
    get:
      operationId: "get_calls_providers"
      summary: "Get the active voice provider for the organization"
      description: "Returns the currently active voice provider (Sinch or Twilio) and the calling user's default voice number for that provider: their own linked number first, then one linked to a group they belong to, then one shared with them through a `send` grant (user, then department, then group), most recently updated within each. `via` says which. Read-only; used by the dialer and AI-readiness banners to know which SDK to load. Open to any authenticated user."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Active provider and the caller's phone number for that provider"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsActiveProviderResponse"
        "401":
          description: "Missing or invalid auth token"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "500":
          description: "Internal error loading provider"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/providers/active":
    post:
      operationId: "post_calls_providers_active"
      summary: "Set the active voice provider (superadmin)"
      description: "Switches the active voice provider for the organization to either `twilio` or `sinch`. The target provider must already be configured (credentials present); otherwise the call is rejected. Superadmin only."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CallsSetActiveVoiceProviderRequest"
      responses:
        "200":
          description: "Active provider switched"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsSimpleSuccessResponse"
        "400":
          description: "Provider not configured or invalid"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "401":
          description: "Unauthorized or not a superadmin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "500":
          description: "Failed to set active provider"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/providers/config":
    get:
      operationId: "get_calls_providers_config"
      summary: "Get full voice provider configuration (superadmin)"
      description: "Returns the configured Twilio and Sinch credentials for the org plus the active provider and the caller's assigned phone numbers. Superadmin only - response includes raw account SIDs / API keys. Superadmins may pass `?organizationId=` to inspect another tenant."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "organizationId"
          required: false
          schema:
            type: "string"
          description: "Superadmin-only override to target a different org."
      responses:
        "200":
          description: "Provider configuration with credentials"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsVoiceProviderConfigResponse"
        "401":
          description: "Unauthorized or not a superadmin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "500":
          description: "Failed to load configuration"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
    post:
      operationId: "post_calls_providers_config"
      summary: "Save voice provider configuration (superadmin)"
      description: "Persists Twilio or Sinch credentials in `OrganizationCredentials.voiceProviders` and optionally upserts the caller's phone number in the org-level phone number store. Superadmin only - overwrites existing config for that provider. Credentials are trimmed server-side. A `phoneNumber` that is a short code (5 or 6 digits, or an org line stored with `numberType: \"shortcode\"`) returns 400 with `code: \"VOICE_NOT_ALLOWED_ON_SHORTCODE\"` before anything is saved: a short code is SMS only."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CallsSaveVoiceProviderConfigRequest"
      responses:
        "200":
          description: "Configuration saved"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsSimpleSuccessResponse"
        "400":
          description: "Invalid provider, validation error, or a short code as the voice number (`VOICE_NOT_ALLOWED_ON_SHORTCODE`)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "401":
          description: "Unauthorized or not a superadmin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "500":
          description: "Failed to save configuration"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/providers/config/{provider}":
    delete:
      operationId: "delete_calls_providers_config_provider"
      summary: "Remove voice provider configuration (superadmin)"
      description: "Deletes the named provider from `OrganizationCredentials.voiceProviders`, unsets it as the active provider if applicable, clears the matching legacy flat credential fields, and releases the caller's lines on that provider. A short code line linked to the caller is left as it is. Superadmin only. Path value must be `twilio` or `sinch`."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "provider"
          required: true
          schema:
            type: "string"
            enum:
              - "twilio"
              - "sinch"
          description: "Voice provider to remove."
      responses:
        "200":
          description: "Configuration removed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsSimpleSuccessResponse"
        "400":
          description: "Invalid provider"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "401":
          description: "Unauthorized or not a superadmin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "500":
          description: "Failed to remove configuration"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/sdk/answer":
    post:
      operationId: "post_calls_sdk_answer"
      summary: "Mark an inbound conference call as answered"
      description: "Updates an existing inbound `Call` to status `in-progress` when the user picks up. Looks up the record by `callId`, Twilio call SID, or a fuzzy fallback on caller number within the last 5 minutes. Emits `call_answered` to the call owner and answering user only, plus an org-wide `call_activity` refresh event (`contactId`/`conversationId` only) when the call has a contact. Returns success even when no record is found (best-effort)."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CallsAnswerInboundCallRequest"
      responses:
        "200":
          description: "Call marked answered (or no record found, but proceed)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsCallSuccessResponse"
        "400":
          description: "Internal failure while updating"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/sdk/inbound":
    post:
      operationId: "post_calls_sdk_inbound"
      summary: "Record an inbound SDK call (phone to browser)"
      description: "Persists a `Call` record (status `answered`) for an inbound PSTN call routed to the user's browser via the active voice provider's SDK. Looks up or creates a contact by caller number and links a voice `Conversation`. Emits the `call_answered` socket event to the call owner only, plus an org-wide `call_activity` refresh event (`contactId`/`conversationId` only) when a contact is resolved."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CallsRecordInboundCallRequest"
      responses:
        "200":
          description: "Inbound call recorded"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsCallSuccessResponse"
        "400":
          description: "callerNumber missing or validation failure"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/sdk/initiate":
    post:
      operationId: "post_calls_sdk_initiate"
      summary: "Record an outbound SDK call (browser to phone)"
      description: "Persists a `Call` record (and conversation, if a contact is resolved) for a browser-initiated outbound call placed via the active voice provider's SDK. Either `contactId` or `phoneNumber` must be provided; if both are absent the request is rejected. Emits the `call_initiated` socket event to the calling user only, plus an org-wide `call_activity` refresh event (`contactId`/`conversationId` only) when a contact is resolved."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CallsInitiateSdkCallRequest"
      responses:
        "200":
          description: "Call record created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsCallSuccessResponse"
        "400":
          description: "Validation failure or contactId/phoneNumber missing"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/sdk/reject":
    post:
      operationId: "post_calls_sdk_reject"
      summary: "Reject an inbound conference call"
      description: "Updates the `Call` to status `no-answer` and sets `endTime`. Emits the `call_rejected` socket event to the call owner and acting user only. Note: the PSTN caller is not actively kicked from the conference yet (TODO via Sinch REST API)."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CallsRejectInboundCallRequest"
      responses:
        "200":
          description: "Call rejected"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsCallSuccessResponse"
        "400":
          description: "callId missing or validation failure"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "404":
          description: "Call not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/statistics":
    get:
      operationId: "get_calls_statistics"
      summary: "Get aggregate call statistics for the org"
      description: "Returns aggregate counters (`totalCalls`, `totalDuration`, `averageDuration`) plus per-status breakdowns for the org. Filterable by `startDate` / `endDate` (ISO strings applied to `createdAt`)."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "startDate"
          required: false
          schema:
            type: "string"
            format: "date-time"
          description: "ISO start of the reporting window."
        -
          in: "query"
          name: "endDate"
          required: false
          schema:
            type: "string"
            format: "date-time"
          description: "ISO end of the reporting window."
      responses:
        "200":
          description: "Aggregate statistics"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsStatisticsResponse"
        "400":
          description: "Validation or internal failure"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/token":
    get:
      operationId: "get_calls_token"
      summary: "Generate a Sinch Voice SDK token (legacy alias)"
      description: "Legacy alias for `/api/calls/token/sinch`. Mints a short-lived (10-minute) Sinch RTC JWT for the calling user along with their default Sinch caller ID. Kept for older clients; new code should call `/token/sinch` or `/token/twilio` directly."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Sinch RTC token + caller identifier"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsSinchTokenResponse"
        "400":
          description: "Sinch credentials not configured for this org"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "500":
          description: "Failed to generate token"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/token/sinch":
    get:
      operationId: "get_calls_token_sinch"
      summary: "Generate a Sinch Voice SDK token"
      description: "Mints a short-lived (10-minute) Sinch RTC JWT scoped to the authenticated user, plus the application key and the user's default Sinch caller ID. Required for the Sinch Web/Mobile SDK to register and place PSTN calls."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Sinch RTC token + caller identifier"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsSinchTokenResponse"
        "400":
          description: "Sinch credentials not configured for this org"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "500":
          description: "Failed to generate token"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/token/twilio":
    get:
      operationId: "get_calls_token_twilio"
      summary: "Generate a Twilio Voice SDK token"
      description: "Mints a Twilio AccessToken with a VoiceGrant for the calling user using the org's Twilio API key / TwiML app SID. Returns the JWT plus the user's Twilio phone number as the SDK identity. Required for the Twilio Voice SDK to register and place PSTN calls."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Twilio access token + identity"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsTwilioTokenResponse"
        "400":
          description: "Twilio credentials missing or user has no Twilio number"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsTwilioTokenErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "500":
          description: "Failed to generate token"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/transferable-destinations":
    get:
      operationId: "get_api_calls_transferable_destinations"
      summary: "GET /api/calls/transferable-destinations"
      tags:
        - "Calls"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/calls/user/phone-numbers":
    get:
      operationId: "get_calls_user_phone_numbers"
      summary: "List the current user's voice phone numbers"
      description: "Returns the read-only list of phone numbers the authenticated user may send from: linked to them, linked to a user group they belong to, or shared with them through a `send` grant (to them, their department or one of their groups); released numbers excluded, newest update first. Each entry says which in `via`. Used by the dialer's \"My Numbers\" UI. Writes live on the org phone-number endpoints (admin)."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "User voice phone numbers"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsUserPhoneNumbersResponse"
        "401":
          description: "Missing or invalid auth token"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "500":
          description: "Failed to load phone numbers"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/voice-ai/config":
    get:
      operationId: "get_calls_voice_ai_config"
      summary: "Get organization-level Voice AI configuration"
      description: "Returns the org's AI voice provider selection (e.g. `elevenlabs`), boolean flags for whether the ElevenLabs API key, tool secret and Sinch application credentials are configured (without leaking values), the org's Sinch SIP termination host, and a flattened list of all Sinch voice phone numbers across users in the org. Read access is open to any authenticated user."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Voice AI config + org phone numbers"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsVoiceAiConfigResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
    post:
      operationId: "post_calls_voice_ai_config"
      summary: "Save organization-level Voice AI configuration (superadmin)"
      description: "Persists the AI voice provider selection, ElevenLabs API key, and Sinch application credentials. Optionally generates a fresh ElevenLabs tool secret (32-byte hex). After save, attempts to auto-configure the ElevenLabs workspace post-call webhook and stores the returned HMAC `webhookSecret`. Webhook configuration failures are logged but don't fail the save. Superadmin only.\n\nA regenerated tool secret is also pushed into the org's ElevenLabs workspace secret, which every registered webhook tool header references; if that push fails the response carries `toolSecretSyncFailed: true` and voice tool calls will fail auth until a re-save succeeds."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CallsSaveVoiceAiConfigRequest"
      responses:
        "200":
          description: "Configuration saved"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsSimpleSuccessResponse"
        "401":
          description: "Unauthorized or not a superadmin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/voice-ai/llms":
    get:
      operationId: "get_calls_voice_ai_llms"
      summary: "List available LLM models from the configured provider"
      description: "Fetches the catalog of LLMs supported by the org's configured AI voice provider. Used by the agent-builder UI to pick a model for a Prompt."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Available LLMs"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsLLMsResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "500":
          description: "Provider error or no provider configured"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/voice-ai/phone-number/toggle":
    post:
      operationId: "post_calls_voice_ai_phone_number_toggle"
      summary: "Toggle AI on/off for a phone number (superadmin)"
      description: "Atomically sets the AI routing legs on a single user-owned phone number. When enabling: imports the number into ElevenLabs (linking to the chosen agent) with per-leg SIP trunk configs pointing at the Sinch Voice API. When disabling: removes it from ElevenLabs. Fails fast (without DB writes) if the selected agent isn't synced to ElevenLabs or if provider-side operations error - preventing silent drift. Superadmin only."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CallsTogglePhoneNumberAiRequest"
      responses:
        "200":
          description: "Toggle applied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsSimpleSuccessResponse"
        "400":
          description: "Agent not synced, AI on a short code, or invalid input"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsTogglePhoneNumberAiErrorResponse"
        "401":
          description: "Unauthorized or not a superadmin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "500":
          description: "Provider sync error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/voice-ai/tools":
    get:
      operationId: "get_calls_voice_ai_tools"
      summary: "List available server-side tools for Voice AI agents"
      description: "Returns the static catalog of server tools that can be attached to a Voice AI agent (e.g. `checkBusinessHours`, `getContact`, `checkAvailability`, `transfer`). Includes `disabled` flags and `disabledReason` for tools that are coming soon."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Tool catalog"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsVoiceAiToolsResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/voice-ai/transferable-agents":
    get:
      operationId: "get_calls_voice_ai_transferable_agents"
      summary: "List Voice AI agents eligible as transfer targets"
      description: "Returns the set of Prompts in the caller's organization that can be configured as transfer destinations for the Voice AI `transfer` server tool. An agent is eligible when its `voiceAI.enabled` is `true` AND it has been synced to ElevenLabs (`voiceAI.elevenlabsAgentId` is set) - only synced agents have a routable agent ID for inter-agent transfer. Pass `excludePromptId` with the current agent's id so the agent cannot transfer to itself; non-ObjectId values are ignored (no exclusion is applied)."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "excludePromptId"
          required: false
          description: "Prompt `_id` to exclude from the result. Typically the current agent's id, to prevent self-transfer."
          schema:
            type: "string"
      responses:
        "200":
          description: "Transferable agents list"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsVoiceAiTransferableAgentsResponse"
        "401":
          description: "Unauthorized - no organizationId on the token"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/calls/voice-ai/voices":
    get:
      operationId: "get_calls_voice_ai_voices"
      summary: "List available AI voices from the configured provider"
      description: "Fetches the catalog of TTS voices from the org's configured AI voice provider (e.g. ElevenLabs). Used by the agent-builder UI to pick a voice for a Prompt."
      tags:
        - "Calls"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Available voices"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsVoicesResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
        "500":
          description: "Provider error or no provider configured"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CallsErrorResponse"
  "/api/campaigns":
    get:
      operationId: "get_campaigns"
      summary: "Get all campaigns for organization"
      description: "Returns all campaigns for the authenticated user organization, optionally filtered by status (importing, scheduled, sending, sent, failed, partial success, cancelled). A campaign with recipient rows takes `stats` from its counters (`recipientCount`, `sentCount`, `failedCount`), also while it sends, and lists its first 100 failures in `failedDetails`; `failedCount` has the full number. A campaign that ended before recipient rows existed keeps the numbers stored on it."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "status"
          required: false
          schema:
            type: "string"
      responses:
        "200":
          description: "Campaigns returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CampaignListResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
    post:
      operationId: "post_campaigns"
      summary: "Create a new campaign"
      description: "Creates a new SMS campaign for the authenticated user organization. Accepts new and existing contacts and optional segmentation and assignment configs, and writes one recipient row per contact. The campaign is created `scheduled`. A campaign without a future date (or a segmented one with a segment due now) is queued for the bulk send workers in the request; the workers move it to `sending`. A campaign that could not be queued is started by the next scheduler run."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CreateCampaignRequest"
      responses:
        "201":
          description: "Campaign created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CampaignMutationResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
  "/api/campaigns/{id}":
    get:
      operationId: "get_campaigns_by_id"
      summary: "Get campaign by ID"
      description: "Returns the full campaign document by id, including segmentation and assignment config, recipient counters, and aggregated stats. `stats` comes from the recipient counters, and `failedDetails` lists the first 100 failed recipients (`failedCount` has the full number)."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Campaign returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CampaignDetailResponse"
        "404":
          description: "Campaign not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
    patch:
      operationId: "patch_campaigns_by_id"
      summary: "Update a scheduled campaign"
      description: "Updates name, message, scheduleDate, autopilot flag, status, or per-segment overrides on a scheduled campaign. Cannot modify campaigns that have already been sent."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateCampaignRequest"
      responses:
        "200":
          description: "Campaign updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CampaignMutationResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "404":
          description: "Campaign not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
    delete:
      operationId: "delete_campaigns_by_id"
      summary: "Delete (cancel) a campaign"
      description: "Cancels a campaign and releases its reserved SMS quota for the scheduled date. Sent or in-progress campaigns cannot be cancelled."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Campaign cancelled"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SuccessMessageResponse"
        "400":
          description: "Cannot cancel"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "404":
          description: "Campaign not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
  "/api/campaigns/{id}/cancel":
    post:
      operationId: "post_campaigns_cancel"
      summary: "Cancel a scheduled or sending campaign"
      description: "Explicit cancel endpoint. A `scheduled` campaign is marked cancelled and its reserved SMS quota is released. A `sending` campaign (including a segmented campaign between its segments) is cancelled with a compare-and-set on its status: the bulk send workers stop at the next recipient, recipients already sent stay sent, the sends so far are committed to the quota and the rest of the reservation is released, and a contact the campaign created is deleted only while its recipient row is still pending. A campaign in any other status returns 400 `Only scheduled or sending campaigns can be cancelled`. A sending campaign that finishes before the cancel lands returns 400 `The campaign finished sending before it could be cancelled`."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Campaign cancelled"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CampaignMutationResponse"
        "400":
          description: "Only scheduled or sending campaigns can be cancelled, or the campaign finished sending before it could be cancelled"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "404":
          description: "Campaign not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
  "/api/campaigns/{id}/import":
    get:
      operationId: "get_campaigns_import"
      summary: "Get the CSV import progress of a campaign"
      description: "Returns the import state and counts of a campaign created from a CSV file, and the progress of its async operation. `import.totalRows` is the number of selected review rows the import resolves. A campaign whose import operation failed is moved to `failed`."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Import progress returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CampaignImportStatusResponse"
        "404":
          description: "Campaign or import not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
  "/api/campaigns/{id}/send":
    post:
      operationId: "post_campaigns_send"
      summary: "Send a scheduled campaign immediately"
      description: "Queues a scheduled campaign for the bulk send workers right now, bypassing the original scheduleDate. The response returns the campaign still `scheduled`; the workers move it to `sending` and the last settled recipient sets its final status. A segmented campaign between its segments (`sending`, nothing going out) sends its next segment. Sending now moves the send to today: today's daily SMS limit must have room for it (else 409 `DAILY_LIMIT_REACHED`), and its quota reservation moves from the scheduled day to today. Only a `scheduled` campaign, or a segmented one between its segments, may be sent on-demand; 409 while a segment is going out."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Campaign queued for sending"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CampaignMutationResponse"
        "400":
          description: "Only scheduled campaigns can be sent"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "404":
          description: "Campaign not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "409":
          description: "Today's SMS limit has no room for the send (DAILY_LIMIT_REACHED), or a segment is going out"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
  "/api/campaigns/analytics":
    get:
      operationId: "get_campaigns_analytics"
      summary: "Get campaign analytics for organization"
      description: "Returns aggregate campaign analytics for the authenticated user organization: total campaigns, status breakdown (scheduled/sent/failed/partial/cancelled), segmented campaign counts, and per-message totals with overall success rate."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Analytics returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CampaignAnalyticsResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
  "/api/campaigns/auto-segment":
    post:
      operationId: "post_campaigns_auto_segment"
      summary: "Calculate auto-segmented campaign schedule"
      description: "Returns a suggested segment schedule for a campaign given the total contact count. For limited plans the response respects the organization's daily SMS quota and skips fully booked days; for unlimited plans contacts are split into 100-per-day segments. Each segment carries a UTC ISO scheduledDate."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AutoSegmentRequest"
      responses:
        "200":
          description: "Auto-segment plan returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AutoSegmentResponse"
        "400":
          description: "totalContacts is required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
  "/api/campaigns/import":
    post:
      operationId: "post_campaigns_import"
      summary: "Launch a campaign from a reviewed CSV file"
      description: "Creates a campaign whose recipients are the selected rows of a `ready` CSV review session (POST /api/campaigns/import/sessions). The JSON body names the session in `importId` with the campaign settings. The segments and the assignment must be the ones the review was classified for; otherwise 409 `CSV_REVIEW_OUT_OF_DATE` asks for a new review. A review with less than 24 hours left returns 409 `CSV_IMPORT_SESSION_EXPIRING`, and a review still analyzing or already launched returns 409 `CSV_IMPORT_SESSION_NOT_READY`. The request freezes the review, creates the campaign in the `importing` status and returns 202. An async operation then reads the selected rows in file order in batches: a selected `new` row creates a contact (exact phone match, then the org merge rules), a selected existing row uses its contact, and each row becomes one recipient in the segment the analysis gave it. ContactCreated workflows start only for the contacts it created. When every row is written the campaign moves to `scheduled` and the review rows and file are deleted; a campaign whose schedule date has passed is sent by the next scheduler run. A campaign is never sent while it is `importing`. Poll GET /api/campaigns/{id}/import for progress."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/LaunchCampaignCsvImportRequest"
      responses:
        "202":
          description: "Campaign created, import queued"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CampaignImportStartResponse"
        "400":
          description: "Validation error, no selected rows, or a campaign check failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "403":
          description: "Campaign line not granted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "404":
          description: "Review not found, or it belongs to another user"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "409":
          description: "Review not ready (`CSV_IMPORT_SESSION_NOT_READY`), about to expire (`CSV_IMPORT_SESSION_EXPIRING`), or reviewed for other segments or another assignment (`CSV_REVIEW_OUT_OF_DATE`)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "503":
          description: "Import queue unavailable"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
  "/api/campaigns/import/sessions":
    post:
      operationId: "post_campaigns_import_sessions"
      summary: "Upload a campaign CSV file for review"
      description: "Uploads a campaign CSV file and starts its analysis. Multipart body: `file` (the CSV) and `config`, a JSON string with the segments and the assignment the rows are classified for. The request checks the file, stores it and returns 202 with the review session in the `analyzing` status. An async operation then reads the file in batches of 1,000 rows and writes one review row per data row in a review group (see CampaignCsvRowCategory). It creates and changes no contact. Rows of `new`, `existing`, `outbound` and `inbound` start selected, `other_users` rows are opt-in, and `protected`, `duplicate`, `invalid` and `outside_segments` rows cannot be selected. A review session belongs to the user who uploaded it; other users get 404. A session that is not launched is deleted with its rows 7 days after the upload. The file may hold at most CAMPAIGN_CSV_MAX_ROWS data rows (default 250,000; more returns 400) and CAMPAIGN_CSV_MAX_BYTES bytes (default 50 MB; more returns 413). Poll GET /api/campaigns/import/sessions/{importId} until `status` is `ready`."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "multipart/form-data":
            schema:
              "$ref": "#/components/schemas/CreateCampaignCsvReviewRequest"
      responses:
        "202":
          description: "File stored, analysis queued"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CampaignCsvReviewStartResponse"
        "400":
          description: "No file, not a CSV file, invalid config, no phoneNumber column, no data rows, or too many rows"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "413":
          description: "File too large"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "503":
          description: "File storage not configured, or the analysis could not be queued"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
  "/api/campaigns/import/sessions/{importId}":
    get:
      operationId: "get_campaigns_import_sessions_by_id"
      summary: "Get a campaign CSV review"
      description: "Returns the status of a CSV review session and the total and selected rows of each review group. While the session is `analyzing`, `analyzedRows` counts the rows written so far. A session whose analysis operation failed or was cancelled is moved to `failed` with `error` set."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "importId"
          required: true
          schema:
            type: "string"
          description: "The CSV review session id returned by the upload."
      responses:
        "200":
          description: "Review returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CampaignCsvReviewResponse"
        "400":
          description: "Invalid importId"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "404":
          description: "Review not found, or it belongs to another user"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
    delete:
      operationId: "delete_campaigns_import_sessions_by_id"
      summary: "Discard a campaign CSV review"
      description: "Deletes a CSV review session, its rows and the stored file. A session a campaign was launched from cannot be discarded (409 `CSV_IMPORT_SESSION_LAUNCHED`)."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "importId"
          required: true
          schema:
            type: "string"
          description: "The CSV review session id returned by the upload."
      responses:
        "200":
          description: "Review discarded"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SuccessMessageResponse"
        "400":
          description: "Invalid importId"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "404":
          description: "Review not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "409":
          description: "A campaign was already launched from this review"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
  "/api/campaigns/import/sessions/{importId}/rows":
    get:
      operationId: "get_campaigns_import_sessions_rows"
      summary: "List one page of a review group"
      description: "Returns one page of the rows of one review group, in file order. Pass `nextAfter` of a page as `after` for the next page, or `previousBefore` as `before` for the previous page; each is null when there is no such page. `search` matches every word against the first name, last name or phone number."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "importId"
          required: true
          schema:
            type: "string"
          description: "The CSV review session id returned by the upload."
        -
          in: "query"
          name: "category"
          required: true
          schema:
            "$ref": "#/components/schemas/CampaignCsvRowCategory"
          description: "The review group to page."
        -
          in: "query"
          name: "after"
          required: false
          schema:
            type: "integer"
            minimum: -1
          description: "`rowNo` of the last row of the previous page; the page starts after it."
        -
          in: "query"
          name: "before"
          required: false
          schema:
            type: "integer"
            minimum: 0
          description: "`rowNo` of the first row of the next page; the page ends before it. Ignored when `after` is sent."
        -
          in: "query"
          name: "limit"
          required: false
          schema:
            type: "integer"
            minimum: 1
            maximum: 200
            default: 100
        -
          in: "query"
          name: "search"
          required: false
          schema:
            type: "string"
            maxLength: 100
          description: "Words to match against the name or phone number."
      responses:
        "200":
          description: "Rows returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CampaignCsvReviewRowsResponse"
        "400":
          description: "Invalid query"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "404":
          description: "Review not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
  "/api/campaigns/import/sessions/{importId}/rows/selection":
    patch:
      operationId: "patch_campaigns_import_sessions_rows_selection"
      summary: "Select or clear review rows"
      description: "Selects or clears up to 500 rows by id and returns the recounted review. Only a `ready` review can change (409 `CSV_IMPORT_SESSION_NOT_READY`). A request that names a row of a group that cannot be selected (`protected`, `duplicate`, `invalid`, `outside_segments`) is refused as a whole with 409 `CSV_ROW_NOT_SELECTABLE`."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "importId"
          required: true
          schema:
            type: "string"
          description: "The CSV review session id returned by the upload."
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateCampaignCsvRowSelectionRequest"
      responses:
        "200":
          description: "Selection changed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CampaignCsvReviewSelectionResponse"
        "400":
          description: "Invalid body"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "404":
          description: "Review not found, or a row is not in this review"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "409":
          description: "Review not ready, or a row cannot be selected"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
  "/api/campaigns/import/sessions/{importId}/selection":
    post:
      operationId: "post_campaigns_import_sessions_selection"
      summary: "Select or clear a whole review group"
      description: "Selects or clears every row of one selectable review group in one write and returns the recounted review. With `search`, only the rows of the group that search matches change, the same rows GET .../rows returns for it. Only a `ready` review can change (409 `CSV_IMPORT_SESSION_NOT_READY`)."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "importId"
          required: true
          schema:
            type: "string"
          description: "The CSV review session id returned by the upload."
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateCampaignCsvCategorySelectionRequest"
      responses:
        "200":
          description: "Selection changed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CampaignCsvReviewSelectionResponse"
        "400":
          description: "Invalid body"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "404":
          description: "Review not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "409":
          description: "Review not ready"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
  "/api/campaigns/next-available-slot":
    get:
      operationId: "get_campaigns_next_available_slot"
      summary: "Get the next date with available SMS quota"
      description: "Searches up to 60 days ahead for the next date that has enough remaining SMS quota to accommodate the requested contactCount. Always returns today's usage so the UI can render the quota banner even when contactCount is omitted."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "contactCount"
          required: false
          schema:
            type: "integer"
            minimum: 0
            default: 0
          description: "Number of contacts the upcoming campaign would target. Omit for general quota info."
      responses:
        "200":
          description: "Next available slot returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NextAvailableSlotResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
  "/api/campaigns/scheduled":
    get:
      operationId: "get_campaigns_scheduled"
      summary: "Get scheduled messages for current user"
      description: "Returns single-contact scheduled messages created by the authenticated user that have not yet been sent."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Scheduled messages returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ScheduledMessagesListResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
    post:
      operationId: "post_campaigns_scheduled"
      summary: "Create a scheduled message for a single contact"
      description: "Creates a single-contact scheduled message (a one-off campaign) that will be delivered at scheduleDate. Used by the conversation composer when a rep schedules a follow-up."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CreateScheduledMessageRequest"
      responses:
        "201":
          description: "Scheduled message created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ScheduledMessageResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "404":
          description: "Contact or user not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
  "/api/campaigns/scheduled/{campaignId}":
    put:
      operationId: "put_campaigns_scheduled_by_id"
      summary: "Update a scheduled message"
      description: "Updates a single-contact scheduled message before it has been sent. Allows changing message body, scheduleDate, autopilot flag, and assignment."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "campaignId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateScheduledMessageRequest"
      responses:
        "200":
          description: "Scheduled message updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ScheduledMessageResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "404":
          description: "Campaign not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
  "/api/campaigns/team-performance":
    get:
      operationId: "get_campaigns_team_performance"
      summary: "Get team performance metrics for campaigns"
      description: "Returns per-user campaign performance metrics (campaigns sent, contacts reached, success rate) for the authenticated user organization, used by the campaigns dashboard team view."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Team performance returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TeamPerformanceResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
  "/api/campaigns/upcoming":
    get:
      operationId: "get_campaigns_upcoming"
      summary: "Get upcoming scheduled campaigns"
      description: "Returns campaigns with status `scheduled` whose scheduleDate is within the next `days` (default 7) for the authenticated user organization."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "days"
          required: false
          schema:
            type: "integer"
            default: 7
      responses:
        "200":
          description: "Upcoming campaigns returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CampaignListResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
  "/api/campaigns/usage-calendar":
    get:
      operationId: "get_campaigns_usage_calendar"
      summary: "Get per-date SMS usage and campaign breakdown"
      description: "Returns SMS usage (sent + reserved) and the list of scheduled/sent campaigns per organization-local date within the requested range. Each campaign entry lists at most the first 100 failures in `failedDetails` and carries the campaign's full failure total in `failedCount`. Used by the Campaigns overview calendar."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "from"
          required: true
          schema:
            type: "string"
            format: "date"
          description: "Inclusive start date (YYYY-MM-DD, org-local timezone)."
        -
          in: "query"
          name: "to"
          required: true
          schema:
            type: "string"
            format: "date"
          description: "Inclusive end date (YYYY-MM-DD, org-local timezone)."
      responses:
        "200":
          description: "Usage calendar returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UsageCalendarResponse"
        "400":
          description: "from and to query params are required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
  "/api/campaigns/validate-contacts":
    post:
      operationId: "post_campaigns_validate_contacts"
      summary: "Classify campaign contacts for the Review step"
      description: "Classifies the provided CSV/contact payload into buckets (new, existing, already-messaged inbound/outbound, assigned-to-other-user, protected, etc.) using the organization's contact protection period and the campaign's segmentation/assignment configuration. Returns { success, data: ContactValidationResult }."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ValidateContactsRequest"
      responses:
        "200":
          description: "Classification result returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ValidateContactsResponse"
        "400":
          description: "No contacts provided"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
  "/api/campaigns/validate-date":
    post:
      operationId: "post_campaigns_validate_date"
      summary: "Validate that a date has enough remaining SMS quota"
      description: "Returns whether the organization's daily SMS quota for the supplied date (derived from scheduledISO in the org's timezone) has room for contactCount additional messages. When excludeCampaignId is supplied, that campaign's current reservation on the date is excluded from the calculation (used when editing)."
      tags:
        - "Campaigns"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ValidateDateRequest"
      responses:
        "200":
          description: "Validation result returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ValidateDateResponse"
        "400":
          description: "scheduledISO and contactCount are required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ErrorResponse"
  "/api/client-errors":
    post:
      operationId: "post_client_errors"
      summary: "Report browser errors from the Tether client"
      description: "Accepts a batch of client-side errors (uncaught exceptions, unhandled rejections, React boundary crashes, service-worker failures) and forwards them to Axiom. Unauthenticated so errors on the sign-in page are still captured; when a Bearer token is sent, user and organization are taken from the verified token, never from the body."
      tags:
        - "Telemetry"
      security:
        []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ReportClientErrorsRequest"
      responses:
        "202":
          description: "Errors accepted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ForwardTracesResponse"
        "400":
          description: "Malformed error batch"
        "429":
          description: "Too many reports from this client"
  "/api/contact":
    post:
      operationId: "post_contact"
      summary: "Create contact"
      description: "Creates a new Contact in the caller's organization, normalizing phone numbers and emails and assigning the contact to the requested pipeline + stage (defaulting to the org's Contact pipeline and its first stage). Requires at least one phone number or email. A phone number (primary or in `conflictingPhoneNumbers`) or a secondary email that is not in the stored format after normalization is rejected with `400 INVALID_CONTACT_METHOD` and nothing is written; a malformed primary `email` fails the request contract as `400 VALIDATION_ERROR`. A phone or email that another contact in the organization already holds does not fail the request: the contact is still created, the value is parked in `conflictingPhoneNumbers` / `conflictingEmails`, the pair is queued for dedup review, and `data.warnings` carries one `CONTACT_METHOD_QUARANTINED` entry per parked value. A body carrying `commandIdempotencyKey` is validated the same way and resolved through the same organization merge policy, so it returns the same outcome as the same body without a key. Emits the `contact_created` socket event and logs a manual event."
      tags:
        - "Contacts"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AddContactRequest"
      responses:
        "200":
          description: "Contact merged into an existing contact (`outcome: merged`)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMutationSuccessEnvelope"
        "201":
          description: "Contact created. Check `data.warnings` for identity values that were quarantined rather than persisted."
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMutationSuccessEnvelope"
        "400":
          description: "Validation or business error. `INVALID_CONTACT_METHOD` when a phone number (primary or in `conflictingPhoneNumbers`) or a secondary email is malformed (`error.details.invalid` names each field and value); `VALIDATION_ERROR` when the body fails the request contract, for example neither a phone number nor an email, or a malformed `email`."
          content:
            "application/json":
              schema:
                anyOf:
                  -
                    "$ref": "#/components/schemas/InvalidContactMethodResponse"
                  -
                    "$ref": "#/components/schemas/ApiErrorEnvelope"
        "404":
          description: "Requested pipeline not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiErrorEnvelope"
        "409":
          description: "A phone number or email was taken by another contact between validation and the write. Retry the request; the value will be quarantined."
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMethodConflictResponse"
        "422":
          description: "A validation rule rejected the change"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiErrorEnvelope"
    put:
      operationId: "put_contact"
      summary: "Update contact"
      description: "Updates a contact identified by `_id` in the body. Resolves pipeline stage / status pairs to keep them in sync, records pipeline transitions, logs a manual event with field-level diffs, and emits the `contact_updated` socket event. A phone number or email the update introduces (primary or in `conflictingPhoneNumbers` / `conflictingEmails`) that is not in the stored format after normalization, or is not a string, is rejected with `400 INVALID_CONTACT_METHOD` and nothing is written; values already stored on the contact are not re-checked and are kept exactly as stored. `null` for `phoneNumber` or `email` clears the field, like `[]`. Org-scoped unless caller is SUPERADMIN."
      tags:
        - "Contacts"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateContactRequest"
      responses:
        "200":
          description: "Contact updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyContactMutationResponse"
        "400":
          description: "Validation error. `INVALID_CONTACT_METHOD` when a phone number or email is malformed or not a string (`error.details.invalid` names each field and value); `VALIDATION_ERROR` when another field has the wrong type."
          content:
            "application/json":
              schema:
                anyOf:
                  -
                    "$ref": "#/components/schemas/InvalidContactMethodResponse"
                  -
                    "$ref": "#/components/schemas/ApiErrorEnvelope"
        "404":
          description: "Contact not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiErrorEnvelope"
        "409":
          description: "Phone number or email is already held by another contact - nothing was written"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMethodConflictResponse"
  "/api/contact-analytics/{contactId}":
    get:
      operationId: "get_contact_analytics"
      summary: "Get contact-level analytics (7 modules)"
      description: "Aggregates 7 analytics modules for a single contact: engagement score, pipeline position, calls, conversations, channel preferences, AI-vs-human handling and a paginated activity timeline. Results are cached server-side for 5 minutes per contact unless `force=true` is passed."
      tags:
        - "Contact Analytics"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "contactId"
          required: true
          schema:
            type: "string"
        -
          in: "query"
          name: "timelineLimit"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "timelinePage"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "force"
          required: false
          schema:
            type: "string"
            enum:
              - "true"
          description: "Pass `true` to bypass the 5-minute in-memory cache (used by the refresh button)."
      responses:
        "200":
          description: "Contact analytics returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactAnalyticsResponse"
        "400":
          description: "Invalid contact ID"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactAnalyticsErrorResponse"
        "404":
          description: "Contact not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactAnalyticsErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactAnalyticsErrorResponse"
  "/api/contact-metrics/by-user":
    get:
      operationId: "get_contact_metrics_by_user"
      summary: "Get metrics breakdown by user (Admin only)"
      description: "ADMIN/SUPERADMIN-only - return the org metrics broken down by owning user, with the same category buckets the summary endpoint reports. Used by the leaderboard / per-rep activity reports."
      tags:
        - "Contact Metrics"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "startDate"
          required: false
          schema:
            type: "string"
            format: "date-time"
        -
          in: "query"
          name: "endDate"
          required: false
          schema:
            type: "string"
            format: "date-time"
        -
          in: "query"
          name: "pipelineId"
          required: false
          schema:
            type: "string"
      responses:
        "200":
          description: "User metrics returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMetricsByUserResponse"
        "400":
          description: "Invalid pipeline ID"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMetricsErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMetricsErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMetricsErrorResponse"
  "/api/contact-metrics/config":
    get:
      operationId: "get_metrics_config"
      summary: "Get category configuration"
      description: "Return the per-organization metrics category configuration: the list of categories with their statuses and colors, optionally scoped to a pipeline."
      tags:
        - "Contact Metrics"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "pipelineId"
          required: false
          schema:
            type: "string"
      responses:
        "200":
          description: "Metrics config returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMetricsConfigResponse"
        "400":
          description: "Invalid pipeline ID"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMetricsErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMetricsErrorResponse"
    put:
      operationId: "update_metrics_config"
      summary: "Update category configuration"
      description: "Update the org-wide metrics categories. ADMIN/SUPERADMIN only. Categories cover existing statuses - orphaned contacts roll up under \"uncategorized\" in the summary endpoint."
      tags:
        - "Contact Metrics"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateMetricsConfigRequest"
      responses:
        "200":
          description: "Metrics config updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMetricsConfigUpdateResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMetricsErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMetricsErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMetricsErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMetricsErrorResponse"
  "/api/contact-metrics/contact":
    get:
      operationId: "get_contact_metrics"
      summary: "Get aggregated contact metrics"
      description: "Return aggregated contact counts bucketed by the categories configured for the org/pipeline (e.g. \"New\", \"Working\", \"Closed\"), with contacted/never-contacted splits. Scope is derived from the caller's role (own contacts / department / whole org)."
      tags:
        - "Contact Metrics"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "startDate"
          required: false
          schema:
            type: "string"
            format: "date-time"
        -
          in: "query"
          name: "endDate"
          required: false
          schema:
            type: "string"
            format: "date-time"
        -
          in: "query"
          name: "pipelineId"
          required: false
          schema:
            type: "string"
      responses:
        "200":
          description: "Contact metrics returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMetricsSummaryResponse"
        "400":
          description: "Invalid pipeline ID"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMetricsErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMetricsErrorResponse"
  "/api/contact-metrics/contacts":
    get:
      operationId: "get_contacts_by_category"
      summary: "Get contacts by category with pagination"
      description: "Drill-down endpoint - return the paginated contact list that maps to the requested `categoryKey` (or all uncategorized contacts when `categoryKey` is omitted)."
      tags:
        - "Contact Metrics"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "categoryKey"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "startDate"
          required: false
          schema:
            type: "string"
            format: "date-time"
        -
          in: "query"
          name: "endDate"
          required: false
          schema:
            type: "string"
            format: "date-time"
        -
          in: "query"
          name: "page"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "limit"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "pipelineId"
          required: false
          schema:
            type: "string"
      responses:
        "200":
          description: "Contacts returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactsByCategoryResponse"
        "400":
          description: "Invalid pipeline ID"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMetricsErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMetricsErrorResponse"
  "/api/contact-notes":
    get:
      operationId: "get_contact_notes"
      summary: "Get all notes for a contact with pagination"
      description: "List notes attached to a contact, newest first. Authors are populated and attachment `key`s are replaced with signed URLs that expire in ~1 hour."
      tags:
        - "Contact Notes"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "contactId"
          required: true
          schema:
            type: "string"
        -
          in: "query"
          name: "limit"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "offset"
          required: false
          schema:
            type: "string"
      responses:
        "200":
          description: "Contact notes returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactNotesListResponse"
        "400":
          description: "contactId query parameter is required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactNotesErrorResponse"
        "500":
          description: "Failed to fetch contact notes"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactNotesErrorResponse"
    post:
      operationId: "create_contact_note"
      summary: "Create a new contact note"
      description: "Create a note on a contact. `mentions` triggers @-mention notifications to the listed userIds. `attachments` accepts R2 keys returned from `POST /api/upload`."
      tags:
        - "Contact Notes"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CreateContactNoteRequest"
      responses:
        "201":
          description: "Contact note created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactNoteMutationResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactNotesErrorResponse"
        "404":
          description: "Contact not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactNotesErrorResponse"
        "500":
          description: "Failed to create contact note"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactNotesErrorResponse"
  "/api/contact-notes/{noteId}":
    patch:
      operationId: "update_contact_note"
      summary: "Update a contact note"
      description: "Edit a note's body, mentions or attachments; updating flips `isEdited` to true. The note's author may edit their own note. A note an AI agent wrote (no `userId`, `createdBy.type` `ai`) may be edited by an org ADMIN or SUPERADMIN. Nobody else may edit a note, and admins may not edit a note a person wrote (403)."
      tags:
        - "Contact Notes"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "noteId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateContactNoteRequest"
      responses:
        "200":
          description: "Contact note updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactNoteMutationResponse"
        "403":
          description: "Permission denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactNotesErrorResponse"
        "404":
          description: "Contact note not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactNotesErrorResponse"
        "500":
          description: "Failed to update contact note"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactNotesErrorResponse"
    delete:
      operationId: "delete_contact_note"
      summary: "Delete a contact note"
      description: "Soft-delete a note (it stops appearing in lists). The note's author may delete their own note. A note an AI agent wrote (no `userId`, `createdBy.type` `ai`) may be deleted by an org ADMIN or SUPERADMIN. Nobody else may delete a note, and admins may not delete a note a person wrote (403)."
      tags:
        - "Contact Notes"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "noteId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Contact note deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactNoteDeleteResponse"
        "403":
          description: "Permission denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactNotesErrorResponse"
        "404":
          description: "Contact note not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactNotesErrorResponse"
        "500":
          description: "Failed to delete contact note"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactNotesErrorResponse"
  "/api/contact-notes/{noteId}/reaction":
    post:
      operationId: "toggle_reaction"
      summary: "Toggle reaction on a contact note"
      description: "Add or remove the caller's reaction (an emoji) on a contact note. Acts as a toggle - re-sending the same emoji removes it."
      tags:
        - "Contact Notes"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "noteId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ToggleReactionRequest"
      responses:
        "200":
          description: "Reaction toggled"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactNoteMutationResponse"
        "400":
          description: "emoji is required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactNotesErrorResponse"
        "404":
          description: "Contact note not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactNotesErrorResponse"
        "500":
          description: "Failed to toggle reaction"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactNotesErrorResponse"
  "/api/contact-notes/download":
    get:
      operationId: "download_attachment"
      summary: "Download attachment (generates signed URL and redirects)"
      description: "Generate a short-lived signed R2 URL for a note attachment with `Content-Disposition: attachment`, and 302-redirect to it. Used by the notes UI to force-download attachments rather than render inline."
      tags:
        - "Contact Notes"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "key"
          required: true
          schema:
            type: "string"
        -
          in: "query"
          name: "fileName"
          required: false
          schema:
            type: "string"
      responses:
        "302":
          description: "Redirect to the signed download URL. The signed URL has `Content-Disposition: attachment` so the browser downloads the file."
          headers:
            Location:
              description: "Signed object-storage URL (R2). Time-limited to ~1 hour."
              schema:
                type: "string"
                format: "uri"
        "400":
          description: "Storage key is required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactNotesErrorResponse"
        "500":
          description: "Failed to generate download URL"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactNotesErrorResponse"
  "/api/contact/list-generator":
    get:
      operationId: "get_contact_list_generator"
      summary: "Get contacts for list generator"
      description: "Returns a paginated, lightweight list of contacts for the bulk-messaging list-generator UI. Supports stage / time-range / date-range / message-status / message-count filters; results are scoped to the caller's organization."
      tags:
        - "Contacts"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "stages"
          required: false
          schema:
            type: "string"
            description: "JSON array"
        -
          in: "query"
          name: "timeRange"
          required: false
          schema:
            type: "string"
            description: "JSON object"
        -
          in: "query"
          name: "dateRange"
          required: false
          schema:
            type: "string"
            description: "JSON object"
        -
          in: "query"
          name: "page"
          required: false
          schema:
            type: "integer"
            minimum: 1
            default: 1
        -
          in: "query"
          name: "limit"
          required: false
          schema:
            type: "integer"
            minimum: 1
            default: 10
        -
          in: "query"
          name: "searchValue"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "messageStatus"
          required: false
          schema:
            type: "string"
            enum:
              - "all"
              - "answered"
              - "unanswered"
        -
          in: "query"
          name: "messageCountValue"
          required: false
          schema:
            type: "integer"
      responses:
        "200":
          description: "Contacts returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ListGeneratorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiErrorEnvelope"
  "/api/contact/map-excess-data":
    post:
      operationId: "post_contact_map_excess_data"
      summary: "Map excess fields for contact payload"
      description: "Re-runs the AI lead-mapper on a contact's `misc` (excess) data to promote previously-unmapped values to first-class fields. Never overwrites an existing firstName/lastName/email; persists the remaining excess fields back to `misc`."
      tags:
        - "Contacts"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/MapExcessDataRequest"
      responses:
        "200":
          description: "Mapped excess data"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/GenericObjectResponse"
        "400":
          description: "Invalid payload"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiErrorEnvelope"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiErrorEnvelope"
  "/api/contact/message-seen":
    post:
      operationId: "post_contact_message_seen"
      summary: "Mark a conversation as seen"
      description: "Clears the `isUpdated` flag on the specified conversation and asynchronously recomputes the parent contact's `isUpdated` based on whether any other conversation is still unseen. Emits the `contact_updated` socket event."
      tags:
        - "Contacts"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/MarkMessageSeenRequest"
      responses:
        "200":
          description: "Conversation marked as seen"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MessageResponse"
        "404":
          description: "Conversation not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts":
    get:
      operationId: "get_contacts"
      summary: "List contacts"
      description: "Returns a paginated, role-scoped list of contacts with rich filtering (search, source/leadSource, owner/assignee, status/pipeline, dateRange, messageStatus, lastMessageTimeRange). Non-admin/department-lead callers are forced to `ownerFilter=my`; SUPERADMIN sees all orgs."
      tags:
        - "Contacts"
      parameters:
        -
          in: "query"
          name: "page"
          required: false
          schema:
            type: "integer"
            minimum: 1
            default: 1
        -
          in: "query"
          name: "size"
          required: false
          schema:
            type: "integer"
            minimum: 1
            default: 50
        -
          in: "query"
          name: "search"
          required: false
          schema:
            type: "string"
            default: ""
        -
          in: "query"
          name: "source"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "leadSource"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "ownerFilter"
          required: false
          schema:
            type: "string"
            default: "my"
        -
          in: "query"
          name: "status"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "pipelineStage"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "pipelineId"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "dateRange"
          required: false
          schema:
            type: "string"
            description: "JSON string range"
        -
          in: "query"
          name: "owner"
          required: false
          schema:
            oneOf:
              -
                type: "string"
              -
                type: "array"
                items:
                  type: "string"
        -
          in: "query"
          name: "assignee"
          required: false
          schema:
            oneOf:
              -
                type: "string"
              -
                type: "array"
                items:
                  type: "string"
        -
          in: "query"
          name: "messageStatus"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "lastMessageTimeRange"
          required: false
          schema:
            type: "string"
            description: "JSON string range"
        -
          in: "query"
          name: "lastMessageDateRange"
          required: false
          schema:
            type: "string"
            description: "JSON string range"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Contacts returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/GetContactsSuccessEnvelope"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiErrorEnvelope"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiErrorEnvelope"
    post:
      operationId: "post_contacts"
      summary: "List contacts by pipeline status buckets"
      description: "Returns contacts grouped by pipeline status / stage, supporting per-bucket pagination via the `page` map. Used by the Kanban board to fetch each column. Honors the same ownership, search, and advanced filters as the flat list endpoint."
      tags:
        - "Contacts"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/GetContactsPerStatusRequest"
      responses:
        "200":
          description: "Contacts grouped by status"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactsByStageResponse"
        "404":
          description: "Pipeline not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/{contactId}/documents":
    get:
      operationId: "get_contact_documents"
      summary: "List documents on a contact"
      description: "Returns the documents array stored on the contact, each augmented with a short-lived signed URL for client download."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "contactId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Documents returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactDocumentsListResponse"
        "400":
          description: "Invalid contact id"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Contact not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
    post:
      operationId: "post_contact_document_save"
      summary: "Save an existing R2 object as a contact document"
      description: "Attaches an already-uploaded R2 object (referenced by storageKey) to the contact as a typed document. Validates documentType against the organization's configured documentTypes."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "contactId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/SaveContactDocumentRequest"
      responses:
        "201":
          description: "Document attached"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactDocumentMutationResponse"
        "400":
          description: "Validation error (missing fields or invalid documentType)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Contact or organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "409":
          description: "Document with this storage key already exists"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/{contactId}/documents/{documentId}":
    put:
      operationId: "put_contact_document"
      summary: "Update a contact document's type or notes"
      description: "Updates the documentType and/or notes on a document attached to a contact. At least one of the two fields must be provided."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "contactId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "documentId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateContactDocumentRequest"
      responses:
        "200":
          description: "Document updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactDocumentMutationResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Contact, document, or organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
    delete:
      operationId: "delete_contact_document"
      summary: "Detach a document from a contact"
      description: "Removes the document entry from the contact's documents array. The underlying R2 object is intentionally preserved so it remains addressable by any message attachments that reference it."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "contactId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "documentId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Document removed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MessageResponse"
        "400":
          description: "Invalid contact or document id"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Contact or document not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/{contactId}/documents/download":
    get:
      operationId: "get_contact_document_download"
      summary: "Redirect to a signed download URL for a document"
      description: "Returns an HTTP 302 redirect to a short-lived signed R2 URL with Content-Disposition: attachment, forcing browsers to download the file rather than render it inline."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "contactId"
          required: true
          schema:
            type: "string"
        -
          in: "query"
          name: "key"
          required: true
          schema:
            type: "string"
          description: "R2 storage key of the document."
        -
          in: "query"
          name: "fileName"
          required: false
          schema:
            type: "string"
          description: "Filename to suggest to the browser."
      security:
        -
          bearerAuth:
            []
      responses:
        "302":
          description: "Redirect to signed download URL"
          headers:
            Location:
              description: "Short-lived signed R2 URL carrying Content-Disposition: attachment. Clients should follow the redirect to download the file."
              schema:
                type: "string"
                format: "uri"
        "400":
          description: "Missing storage key"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Failed to generate download URL"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/{contactId}/documents/upload":
    post:
      operationId: "post_contact_document_upload"
      summary: "Upload a new document for a contact (multipart)"
      description: "Accepts a multipart/form-data upload (max 25 MB) and stores it in R2 under a deterministic per-contact key, then attaches the resulting document record to the contact. documentType must match an entry in the organization's configured documentTypes."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "contactId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "multipart/form-data":
            schema:
              "$ref": "#/components/schemas/UploadContactDocumentForm"
            encoding:
              file:
                contentType: "application/octet-stream"
      responses:
        "201":
          description: "Document uploaded"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactDocumentMutationResponse"
        "400":
          description: "Missing file or invalid documentType"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Contact or organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Upload failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/{id}":
    get:
      operationId: "get_contact_by_id"
      summary: "Get contact by id"
      description: "Returns the full Contact document for the given id, scoped to the caller's organization (SUPERADMIN bypasses the scope). Used by the contact detail panel and deep links."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Contact returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/GetContactByIdSuccessEnvelope"
        "404":
          description: "Contact not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiErrorEnvelope"
    patch:
      operationId: "patch_contact_field"
      summary: "Patch contact fields"
      description: "Partial-updates the contact: resolves pipeline stage / status pairs, normalizes phone numbers (rejecting provisioned org SMS numbers and, with `400 INVALID_CONTACT_METHOD`, phone numbers and secondary emails that are not in the stored format after normalization, including in `conflictingPhoneNumbers` / `conflictingEmails`; a malformed primary `email` fails the request contract as `400 VALIDATION_ERROR`; values already stored in the same field on the contact are not re-checked and are kept exactly as stored), records pipeline transitions, logs manual events with field-level diffs, and emits `contact_updated`. Used by the inline contact-edit panel."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/PatchContactRequest"
      responses:
        "200":
          description: "Contact updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMutationSuccessEnvelope"
        "400":
          description: "Validation error. `INVALID_CONTACT_METHOD` when a phone number (primary or secondary) or a secondary email is malformed (`error.details.invalid` names each field and value); `VALIDATION_ERROR` when the body fails the request contract, including a malformed `email` or a field of the wrong type."
          content:
            "application/json":
              schema:
                anyOf:
                  -
                    "$ref": "#/components/schemas/InvalidContactMethodResponse"
                  -
                    "$ref": "#/components/schemas/ApiErrorEnvelope"
        "404":
          description: "Contact not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiErrorEnvelope"
        "409":
          description: "Phone number or email is already held by another contact - nothing was written"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMethodConflictResponse"
    delete:
      operationId: "delete_contact_by_id"
      summary: "Delete contact by id"
      description: "Cascade-deletes the contact along with its conversations and messages, creates a Contact Deleted notification for the assignees, logs a manual event, and emits `contact_removed`. Org-scoped unless caller is SUPERADMIN."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Contact deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MessageResponse"
        "404":
          description: "Contact not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/{id}/block":
    patch:
      operationId: "patch_contact_block"
      summary: "Block contact"
      description: "Marks the contact `isBlocked: true`, records `blockedBy`/`blockedAt`, force-disconnects any active webchat devices, and invalidates the blocked-device cache. Returns the synced/removed webchat device ids. Org-scoped unless caller is SUPERADMIN."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Contact blocked"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/BlockUnblockResponse"
        "404":
          description: "Contact not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/{id}/dedup-reviews/pending":
    get:
      operationId: "get_contact_dedup_reviews_pending"
      summary: "List pending dedup reviews involving a contact"
      description: "Returns the pending ContactDedupReview entries where this contact appears as either source or candidate. SUPERADMIN may override organizationId via query."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
        -
          in: "query"
          name: "organizationId"
          required: false
          schema:
            type: "string"
          description: "SUPERADMIN-only override of the target organization."
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Pending reviews returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactDedupReviewListResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/{id}/execute-custom-fields":
    post:
      operationId: "post_contact_execute_custom_fields"
      summary: "Execute contact custom fields"
      description: "Re-runs the org's conditional / computed custom-field expressions against this contact and persists any updates. Used by the admin \"Run rules now\" action when a rule definition changes."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Custom fields executed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/GenericObjectResponse"
        "400":
          description: "Invalid request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Execution failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/{id}/protection-status":
    get:
      operationId: "get_contact_protection_status"
      summary: "Get contact protection status"
      description: "Returns whether the caller is currently blocked from this contact by the organization's contactProtectionPeriod. Admins, owners, and assigned reps bypass protection."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Protection status returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactProtectionStatusResponse"
        "404":
          description: "Contact not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/{id}/separate":
    post:
      operationId: "post_contact_separate"
      summary: "Separate one contact into two"
      description: "Splits the source contact into two contacts based on a field split and child-record assignment plan. Admin/Superadmin only. Validates phone format, email format, and uniqueness; rejects splits that would violate the per-org phone uniqueness invariant."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/SeparateContactRequest"
      responses:
        "200":
          description: "Contact separated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SeparateContactResponseEnvelope"
        "400":
          description: "Invalid payload or precondition error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "403":
          description: "Caller is not admin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Contact not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/{id}/separate/commit":
    post:
      operationId: "post_api_contacts_id_separate_commit"
      summary: "POST /api/contacts/{id}/separate/commit"
      tags:
        - "Contacts"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/contacts/{id}/separate/prepare":
    post:
      operationId: "post_api_contacts_id_separate_prepare"
      summary: "POST /api/contacts/{id}/separate/prepare"
      tags:
        - "Contacts"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/contacts/{id}/separation-data":
    get:
      operationId: "get_contact_separation_data"
      summary: "Get contact separation wizard data"
      description: "Returns the contact plus all child records (conversations, applications, notes, reminders) needed to drive the admin Separation wizard. Admin/Superadmin only."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Separation data returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactSeparationDataResponse"
        "400":
          description: "Invalid contact id"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "403":
          description: "Caller is not admin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Contact not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/{id}/unblock":
    patch:
      operationId: "patch_contact_unblock"
      summary: "Unblock contact"
      description: "Clears the contact's blocked state (`isBlocked: false`, clears `blockedBy`/`blockedAt`) and invalidates the blocked-device cache so future webchat sessions are accepted again. Org-scoped unless caller is SUPERADMIN."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Contact unblocked"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/BlockUnblockResponse"
        "404":
          description: "Contact not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/{id}/unverify":
    patch:
      operationId: "patch_contact_unverify"
      summary: "Unverify a contact (admin)"
      description: "Clears verification on the contact and records unverifiedBy/unverifiedAt. Admin or Superadmin only."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Contact unverified"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactWrappedMutationResponse"
        "400":
          description: "Invalid contact id"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "403":
          description: "Caller lacks admin permission"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Contact not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/{id}/verify":
    patch:
      operationId: "patch_contact_verify"
      summary: "Verify a contact (admin)"
      description: "Marks the contact as verified, recording verifiedBy/verifiedAt and optional verificationSource. Admin or Superadmin only."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/VerifyContactRequest"
      responses:
        "200":
          description: "Contact verified"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactWrappedMutationResponse"
        "400":
          description: "Invalid contact id"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "403":
          description: "Caller lacks admin permission"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Contact not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/{id}/verify-contact-methods":
    patch:
      operationId: "patch_contact_verify_contact_methods"
      summary: "Set or clear verification on a contact's phone or email entry"
      description: "Toggles verification metadata on a single entry in a contact's `phoneNumber[]` or `email[]` array. Pass `verifiedAt` as an ISO timestamp to mark the entry verified (also stamps `verifiedBy` from the caller and the supplied `verificationSource`); pass `verifiedAt: null` (or omit it) to clear all three. Phone values are normalized via the same E.164 helper the rest of the API uses; email values are lower-cased. Scoped to the caller's organization unless SUPERADMIN. Emits a `contact_updated` socket event and writes a manual-event audit entry (`CONTACT_METHOD_VERIFIED` / `CONTACT_METHOD_UNVERIFIED`)."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/SetContactMethodVerificationRequest"
      responses:
        "200":
          description: "Verification metadata updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SetContactMethodVerificationResponse"
        "400":
          description: "Invalid id/type/value/verifiedAt/verificationSource, or missing organizationId for non-SUPERADMIN"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Contact not found, or no matching phone/email entry on the contact"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/active":
    post:
      operationId: "post_contacts_active"
      summary: "List active contacts for user context"
      description: "Returns contacts that have conversation activity (`lastMessageTime` set), scoped to the caller's ownership / assignment, sorted newest activity first with an exact `total` for pagination. Used to power the active conversations sidebar. `query` is matched literally, case-insensitive, as a substring of first name, last name or phone number; several words must all match. The response carries `data` and `total` only."
      tags:
        - "Contacts"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/GetContactsWithConversationsRequest"
      responses:
        "200":
          description: "Active contacts returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ActiveContactsResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/bulk-delete":
    delete:
      operationId: "delete_contacts_bulk"
      summary: "Bulk delete contacts"
      description: "Cascade-deletes every contact in `contactIds` along with its conversations and messages, emits `contact_removed` per contact, and creates a Contact Deleted notification per assignee. Org-scoped unless caller is SUPERADMIN."
      tags:
        - "Contacts"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/BulkDeleteContactsRequest"
      responses:
        "200":
          description: "Bulk delete completed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/BulkDeleteResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "No contacts found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/bulk-job/{jobId}":
    get:
      operationId: "get_contact_bulk_job"
      summary: "Poll a bulk-delete background job"
      description: "Returns the progress of a background bulk job created by `DELETE /api/contacts/query-bulk-delete`. Jobs live in an in-memory store and expire some time after completion; the response includes the cumulative `processed` count and the final `status` (`pending` while running, `completed`, or `failed`). Scoped to the caller's organization - SUPERADMIN can poll any org's jobs. Returns 404 for unknown/expired job IDs or jobs the caller does not own (no information leak)."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "jobId"
          required: true
          description: "Job UUID returned by `DELETE /api/contacts/query-bulk-delete`."
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Job status"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactBulkJobStatusResponse"
        "404":
          description: "Job not found, expired, or not owned by caller's organization"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/bulk-job/{jobId}/artifact":
    get:
      operationId: "get_api_contacts_bulk_job_jobId_artifact"
      summary: "GET /api/contacts/bulk-job/{jobId}/artifact"
      tags:
        - "Contacts"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "jobId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/contacts/bulk-update-status":
    put:
      operationId: "put_contacts_bulk_update_status"
      summary: "Bulk update contact status"
      description: "Updates `status`, `pipelineStage` (and inferred `pipelineId`) on every contact in `contactIds`. Records pipeline transitions for contacts whose status actually changed and logs a manual event per contact. Org-scoped unless caller is SUPERADMIN."
      tags:
        - "Contacts"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/BulkUpdateContactStatusRequest"
      responses:
        "200":
          description: "Bulk update completed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/BulkUpdateStatusResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/canonical/{id}":
    get:
      operationId: "get_api_contacts_canonical_id"
      summary: "GET /api/contacts/canonical/{id}"
      tags:
        - "Contacts"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
    patch:
      operationId: "patch_api_contacts_canonical_id"
      summary: "PATCH /api/contacts/canonical/{id}"
      tags:
        - "Contacts"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/contacts/canonical/{id}/archive":
    post:
      operationId: "post_api_contacts_canonical_id_archive"
      summary: "POST /api/contacts/canonical/{id}/archive"
      tags:
        - "Contacts"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/contacts/canonical/aggregate":
    post:
      operationId: "post_api_contacts_canonical_aggregate"
      summary: "POST /api/contacts/canonical/aggregate"
      tags:
        - "Contacts"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/contacts/canonical/list":
    post:
      operationId: "post_api_contacts_canonical_list"
      summary: "POST /api/contacts/canonical/list"
      tags:
        - "Contacts"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/contacts/counts":
    post:
      operationId: "post_contacts_counts"
      summary: "Get contact counts for filters"
      description: "Returns two contact counts for the caller's role: `my` (contacts with a conversation assigned to the caller) and `all` (every contact in the organization for admins, the department's assigned contacts for a department head, the same as `my` for everyone else). Used by the filter drawer's owner select. Honors search and source filters. Earlier versions also returned a count per user id; those keys are gone."
      tags:
        - "Contacts"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/GetContactCountsRequest"
      responses:
        "200":
          description: "Counts returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactCountsResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/dedup-reviews/{reviewId}":
    get:
      operationId: "get_api_contacts_dedup_reviews_reviewId"
      summary: "GET /api/contacts/dedup-reviews/{reviewId}"
      tags:
        - "Contacts"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "reviewId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/contacts/dedup-reviews/{reviewId}/keep-separate":
    patch:
      operationId: "patch_contact_dedup_review_keep_separate"
      summary: "Resolve a dedup review by keeping the pair separate"
      description: "Marks the review as kept_separate without merging the contacts. Admin/Superadmin only."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "reviewId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ContactDedupReviewResolutionBody"
      responses:
        "200":
          description: "Review kept separate"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactDedupReviewKeepSeparateResponse"
        "400":
          description: "Invalid reviewId"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "403":
          description: "Caller is not admin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Review not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "409":
          description: "Review already resolved"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/dedup-reviews/{reviewId}/keep-separate/commit":
    post:
      operationId: "post_api_contacts_dedup_reviews_reviewId_keep_separate_commit"
      summary: "POST /api/contacts/dedup-reviews/{reviewId}/keep-separate/commit"
      tags:
        - "Contacts"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "reviewId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/contacts/dedup-reviews/{reviewId}/keep-separate/prepare":
    post:
      operationId: "post_api_contacts_dedup_reviews_reviewId_keep_separate_prepare"
      summary: "POST /api/contacts/dedup-reviews/{reviewId}/keep-separate/prepare"
      tags:
        - "Contacts"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "reviewId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/contacts/dedup-reviews/{reviewId}/merge":
    patch:
      operationId: "patch_contact_dedup_review_merge"
      summary: "Resolve a dedup review by merging the pair"
      description: "Merges the source contact into the candidate contact using optional per-field choices, then marks the review merged. Cascades any other pending reviews on the same source contact to kept_separate."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "reviewId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ContactDedupReviewResolutionBody"
      responses:
        "200":
          description: "Review merged"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactDedupReviewMergeResponse"
        "400":
          description: "Invalid reviewId or payload"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "403":
          description: "Caller is not admin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Review not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "409":
          description: "Review already resolved"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "410":
          description: "One or both contacts no longer exist"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/dedup-reviews/{reviewId}/merge/commit":
    post:
      operationId: "post_api_contacts_dedup_reviews_reviewId_merge_commit"
      summary: "POST /api/contacts/dedup-reviews/{reviewId}/merge/commit"
      tags:
        - "Contacts"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "reviewId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/contacts/dedup-reviews/{reviewId}/merge/prepare":
    post:
      operationId: "post_api_contacts_dedup_reviews_reviewId_merge_prepare"
      summary: "POST /api/contacts/dedup-reviews/{reviewId}/merge/prepare"
      tags:
        - "Contacts"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "reviewId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/contacts/dedup-reviews/bulk/keep-separate":
    patch:
      operationId: "patch_contacts_dedup_reviews_bulk_keep_separate"
      summary: "Bulk-resolve dedup reviews as kept separate"
      description: "Resolves up to 500 dedup reviews as kept_separate in a single call. Pairs are processed in parallel; the response reports per-review success/failure plus a summary."
      tags:
        - "Contacts"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ContactDedupReviewBulkRequest"
      responses:
        "200":
          description: "Bulk keep-separate attempted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactDedupReviewBulkResponse"
        "400":
          description: "reviewIds missing or too many"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "403":
          description: "Caller is not admin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/dedup-reviews/bulk/merge":
    patch:
      operationId: "patch_contacts_dedup_reviews_bulk_merge"
      summary: "Bulk-resolve dedup reviews as merged"
      description: "Resolves up to 25 dedup reviews as merged in a single call. Each pair is processed sequentially; the response reports per-review success/failure plus a summary."
      tags:
        - "Contacts"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ContactDedupReviewBulkRequest"
      responses:
        "200":
          description: "Bulk merge attempted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactDedupReviewBulkResponse"
        "400":
          description: "reviewIds missing or too many"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "403":
          description: "Caller is not admin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/dedup-reviews/pending":
    get:
      operationId: "get_contacts_dedup_reviews_pending"
      summary: "List org-wide pending dedup reviews"
      description: "Returns pending ContactDedupReview pairs for the caller's organization, grouped by source contact with candidates sorted by score. SUPERADMIN may target another org via the orgId query parameter."
      tags:
        - "Contacts"
      parameters:
        -
          in: "query"
          name: "orgId"
          required: false
          schema:
            type: "string"
          description: "SUPERADMIN-only override of the target organization."
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Pending reviews returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactDedupReviewGroupedResponse"
        "403":
          description: "Caller is not admin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/dedup-reviews/pending/bulk-candidates":
    get:
      operationId: "get_api_contacts_dedup_reviews_pending_bulk_candidates"
      summary: "GET /api/contacts/dedup-reviews/pending/bulk-candidates"
      tags:
        - "Contacts"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/contacts/dedup-reviews/resolved":
    get:
      operationId: "get_contacts_dedup_reviews_resolved"
      summary: "List org-wide resolved dedup reviews"
      description: "Returns ContactDedupReview entries that have been resolved (merged or kept_separate) for the caller's organization. SUPERADMIN may target another org via the orgId query parameter."
      tags:
        - "Contacts"
      parameters:
        -
          in: "query"
          name: "orgId"
          required: false
          schema:
            type: "string"
          description: "SUPERADMIN-only override of the target organization."
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Resolved reviews returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactDedupReviewListResponse"
        "403":
          description: "Caller is not admin"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/find-or-create-by-phone":
    post:
      operationId: "post_contacts_find_or_create_by_phone"
      summary: "Find or create a contact by phone number"
      description: "Looks up a contact in the caller's organization by phone number, creating a new contact (placed at the first pipeline stage) when none exists. Used by the dialpad flow when an outgoing call needs a contact reference."
      tags:
        - "Contacts"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/FindOrCreateContactByPhoneRequest"
      responses:
        "200":
          description: "Existing contact returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/FindOrCreateContactResponse"
        "201":
          description: "Contact created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/FindOrCreateContactResponse"
        "400":
          description: "`phoneNumber` missing or not a string (`{ error }`), or a number that cannot be normalized to the stored format (`INVALID_CONTACT_METHOD`). Nothing is created."
          content:
            "application/json":
              schema:
                anyOf:
                  -
                    "$ref": "#/components/schemas/LegacyErrorResponse"
                  -
                    "$ref": "#/components/schemas/InvalidContactMethodResponse"
        "404":
          description: "No Contact pipeline configured for organization"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/inactive":
    get:
      operationId: "get_contacts_inactive"
      summary: "Get inactive contacts phone/email list"
      description: "Returns contacts the caller owns or is assigned to that do not yet have a conversation in the requested channel (SMS or email). Used by the new-conversation picker. Pass `includeExisting=true` to also surface contacts with an existing conversation, annotated with `existingConversationId`."
      tags:
        - "Contacts"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "channelType"
          required: false
          schema:
            type: "string"
            enum:
              - "sms"
              - "email"
        -
          in: "query"
          name: "includeExisting"
          required: false
          schema:
            type: "string"
            enum:
              - "true"
              - "1"
          description: "When truthy, include contacts that already have an existing conversation in the requested channel. Returned items will carry an \"existingConversationId\" field for those contacts."
      responses:
        "200":
          description: "Inactive contacts returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactsArrayResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/phoneNumber":
    post:
      operationId: "post_contacts_by_phone"
      summary: "Get contact by phone number"
      description: "Looks up a contact by phone number. Org-scoped unless the caller is SUPERADMIN, in which case the lookup spans every organization. Non-admin callers only see contacts with a conversation assigned to them (department heads: assigned to their department), except when `context` is `contact-creation`, which checks the whole organization. `selectedUser._id` pins the lookup to one contact id. When several contacts hold the number (a SUPERADMIN lookup across organizations), the first match is returned. Used to resolve a contact reference for incoming-call routing and the dialpad. Returns 404 when no contact matches or the caller cannot see it."
      tags:
        - "Contacts"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/GetContactByPhoneRequest"
      responses:
        "200":
          description: "Contact returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactByPhoneResponse"
        "400":
          description: "Organization ID missing from a non-superadmin token"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Contact not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/query-bulk-delete":
    delete:
      operationId: "delete_contact_query_bulk_delete"
      summary: "Bulk-delete all matching contacts (async)"
      description: "Starts a background job that cascade-deletes every contact matching the supplied filter - for each contact it also deletes the org's conversations and messages for that contact, fires assignee notifications, emits `contact_removed` socket events, and writes manual-event audit entries (`CONTACT_DELETE`). The handler responds 202 immediately with a `jobId`; the caller should poll `GET /api/contacts/bulk-job/{jobId}` for progress. The job is registered synchronously before the response is sent so the first poll never gets a 404."
      tags:
        - "Contacts"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ContactBulkQueryFilter"
      responses:
        "202":
          description: "Bulk delete job started"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactBulkQueryDeleteResponse"
        "400":
          description: "Missing `stageIds[]` when `orgWide` is not true"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/query-bulk-export":
    get:
      operationId: "get_contact_query_bulk_export"
      summary: "Stream a CSV export of all matching contacts"
      description: "Streams a CSV of every contact matching the supplied filter as `text/csv` with `Content-Disposition: attachment; filename=\"contacts-YYYY-MM-DD.csv\"`. Columns: `First Name, Last Name, Phone, Email, Pipeline, Stage, Created Date`. Uses a Mongo cursor so even multi-thousand exports stream incrementally without buffering. Filter semantics match the other `query-*` endpoints, but parameters are passed as query string: `stageIds` is a comma-separated list, `advancedParams` is a JSON-encoded string (malformed JSON is silently ignored)."
      tags:
        - "Contacts"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "stageIds"
          required: false
          description: "Comma-separated pipeline-stage IDs. Required unless `orgWide=true`."
          schema:
            type: "string"
          example: "64b2c3d4e5f60012345678aa,64b2c3d4e5f60012345678ab"
        -
          in: "query"
          name: "pipelineType"
          required: false
          description: "Which model to export from. Defaults to `Contact`."
          schema:
            type: "string"
            enum:
              - "Contact"
              - "Application"
        -
          in: "query"
          name: "orgWide"
          required: false
          description: "Set to `true` to export across the whole organization and ignore `stageIds`."
          schema:
            type: "string"
            enum:
              - "true"
              - "false"
        -
          in: "query"
          name: "ownerFilter"
          required: false
          description: "Owner-based scope (`owned` / `unowned`) applied identically to the contacts list view."
          schema:
            type: "string"
        -
          in: "query"
          name: "advancedParams"
          required: false
          description: "JSON-encoded filter object (same shape used by the Contacts list view advanced filters). Malformed JSON is silently ignored."
          schema:
            type: "string"
          example: "{\"createdAfter\":\"2026-01-01T00:00:00.000Z\"}"
      responses:
        "200":
          description: "CSV stream"
          headers:
            Content-Disposition:
              description: "Attachment header carrying the date-stamped filename."
              schema:
                type: "string"
              example: "attachment; filename=\"contacts-2026-05-20.csv\""
          content:
            "text/csv":
              schema:
                type: "string"
                example: "First Name,Last Name,Phone,Email,Pipeline,Stage,Created Date\n\"Alex\",\"Morgan\",\"+14165550100\",\"alex.morgan@example.com\",\"Sales\",\"New Lead\",\"2026-05-20\"\n"
        "400":
          description: "Missing `stageIds` when `orgWide` is not `true`"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/query-bulk-move":
    put:
      operationId: "put_contact_query_bulk_move"
      summary: "Bulk-move all matching contacts to a target pipeline stage"
      description: "Moves every contact matching the supplied filter into the given pipeline stage. `targetStageId` and `targetStatus` are both required; the server resolves the underlying `pipelineId` from `targetStageId` and writes all three. For each contact whose status, pipelineStage, or pipelineId actually changes, the server records a stage-transition history entry, emits a `contact_updated` socket event, and writes a manual-event audit entry (`CONTACT_UPDATE`). Filter semantics are identical to `query-count`: either provide `stageIds[]` or `orgWide: true`."
      tags:
        - "Contacts"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ContactBulkQueryMoveRequest"
      responses:
        "200":
          description: "Move applied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactBulkQueryMoveResponse"
        "400":
          description: "Missing `stageIds[]` (when not `orgWide`), or missing `targetStageId`/`targetStatus`"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/query-bulk-sms":
    post:
      operationId: "post_api_contacts_query_bulk_sms"
      summary: "POST /api/contacts/query-bulk-sms"
      tags:
        - "Contacts"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/contacts/query-count":
    post:
      operationId: "post_contact_query_count"
      summary: "Count contacts matching a pipeline-stage / advanced-filter query"
      description: "Returns the count of contacts (or Applications when `pipelineType=Application`) that match the supplied filter. The same filter shape powers `query-bulk-move`, `query-bulk-delete`, and `query-bulk-export`, so the count returned here is the number of records those bulk operations would target with identical input. Either supply `stageIds[]` (one or more pipeline-stage IDs) OR set `orgWide: true` to ignore stages and count across the whole organization. `ownerFilter` and `advancedParams` apply the same way they do in the Contacts list view."
      tags:
        - "Contacts"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ContactBulkQueryFilter"
      responses:
        "200":
          description: "Matching count"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactBulkQueryCountResponse"
        "400":
          description: "Missing `stageIds[]` when `orgWide` is not true"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/status":
    post:
      operationId: "post_contacts_status"
      summary: "Get contacts for one status"
      description: "Returns the paginated contacts in a single pipeline status / stage. Used to expand a Kanban column or status drawer beyond its initial page. Honors search, ownership, and the unified-filter-drawer advanced filters."
      tags:
        - "Contacts"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/GetContactsByStatusRequest"
      responses:
        "200":
          description: "Contacts returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactsByStatusResponse"
        "404":
          description: "Status not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/statuses":
    post:
      operationId: "post_contacts_statuses"
      summary: "Get contacts across all statuses"
      description: "Returns the initial page of contacts for every status in the requested Contact pipeline at once. Used when the Kanban board first loads to hydrate every column in a single round trip."
      tags:
        - "Contacts"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/GetAllInitialContactsByStatusRequest"
      responses:
        "200":
          description: "Contacts grouped by statuses"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactsByStageResponse"
        "400":
          description: "Invalid pipeline id"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/conversation":
    delete:
      operationId: "delete_conversation"
      summary: "Delete a conversation and its messages"
      description: "Permanently delete a conversation and every Message attached to it. Used by admin/cleanup tooling; the underlying contact and calls are preserved."
      tags:
        - "Conversations"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/DeleteConversationRequest"
      responses:
        "200":
          description: "Conversation deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MessageResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Conversation not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/conversation-monitor/report":
    get:
      operationId: "get_conversation_monitor_report"
      summary: "Get conversation monitor report"
      description: "Returns a paginated dashboard of conversations the autopilot/agent has likely stalled on, combining AI-stuck and abandoned-conversation categories. The page contains contact/conversation identifiers, channel, latest inbound timestamp, assignee names, and per-row access. Query params: page, limit (<=100), category (ai_stuck | agent_abandoned), skipThreshold, departmentId, organizationId (SUPERADMIN only)."
      tags:
        - "Conversation Monitor"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "page"
          required: false
          schema:
            type: "integer"
            minimum: 1
            default: 1
        -
          in: "query"
          name: "limit"
          required: false
          schema:
            type: "integer"
            minimum: 1
            maximum: 100
            default: 25
        -
          in: "query"
          name: "category"
          required: false
          schema:
            type: "string"
            enum:
              - "ai_stuck"
              - "agent_abandoned"
        -
          in: "query"
          name: "skipThreshold"
          required: false
          schema:
            type: "string"
            enum:
              - "true"
              - "false"
          description: "When \"true\", ignores the configured threshold and returns all candidates."
        -
          in: "query"
          name: "departmentId"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "organizationId"
          required: false
          schema:
            type: "string"
          description: "SUPERADMIN-only override to inspect another organization."
      responses:
        "200":
          description: "Conversation monitor report returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConversationMonitorReportResponse"
        "403":
          description: "Access denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConversationMonitorErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConversationMonitorErrorResponse"
        "500":
          description: "Failed to fetch report"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConversationMonitorErrorResponse"
  "/api/conversation/{conversationId}/held-reply/discard":
    post:
      operationId: "post_api_conversation_conversationId_held_reply_discard"
      summary: "POST /api/conversation/{conversationId}/held-reply/discard"
      tags:
        - "Conversations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "conversationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/conversation/{conversationId}/held-reply/send":
    post:
      operationId: "post_api_conversation_conversationId_held_reply_send"
      summary: "POST /api/conversation/{conversationId}/held-reply/send"
      tags:
        - "Conversations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "conversationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/conversation/{conversationId}/messages":
    get:
      operationId: "get_conversation_messages"
      summary: "Get messages and calls by conversation"
      description: "Return the chronological message/call timeline for a conversation, along with counts and the resolution block (CSAT, resolver) when the conversation has been resolved."
      tags:
        - "Conversations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "conversationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Messages returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConversationMessagesResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Conversation not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/conversation/{conversationId}/messages/search":
    get:
      operationId: "get_conversation_messages_search"
      summary: "Search messages within a conversation"
      description: "Returns `{ messageId, createdAt }` for each `body` field regex match in the conversation, plus a total count and truncation flag. Backs the in-conversation find bar - does not return message bodies. Email messages whose content lives only in `emailMetadata.bodyHtml` will not match."
      tags:
        - "Conversations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "conversationId"
          required: true
          schema:
            type: "string"
        -
          in: "query"
          name: "q"
          required: true
          schema:
            type: "string"
            minLength: 1
            maxLength: 500
          description: "Search query (regex-escaped server-side)"
        -
          in: "query"
          name: "matchCase"
          required: false
          schema:
            type: "boolean"
            default: false
        -
          in: "query"
          name: "wholeWord"
          required: false
          schema:
            type: "boolean"
            default: false
        -
          in: "query"
          name: "limit"
          required: false
          schema:
            type: "integer"
            minimum: 1
            maximum: 5000
            default: 2000
        -
          in: "query"
          name: "fromDate"
          required: false
          schema:
            type: "string"
            pattern: "^\\d{4}-\\d{2}-\\d{2}$"
          description: "Inclusive lower bound (UTC), YYYY-MM-DD"
        -
          in: "query"
          name: "toDate"
          required: false
          schema:
            type: "string"
            pattern: "^\\d{4}-\\d{2}-\\d{2}$"
          description: "Inclusive upper bound (UTC), YYYY-MM-DD"
      responses:
        "200":
          description: "Search matches returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConversationMessageSearchResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Conversation not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/conversation/{conversationId}/send-message":
    post:
      operationId: "post_conversation_send_message"
      summary: "Send a message to a conversation"
      description: "Send an outbound message (text + optional attachments) on the conversation's current channel. `isInternal: true` posts a whisper note visible only to agents."
      tags:
        - "Conversations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "conversationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/SendMessageToConversationRequest"
      responses:
        "200":
          description: "Message sent"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SendMessageToConversationResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Conversation not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "422":
          description: "`SMS_TOO_LONG` (body: `SmsTooLongErrorResponse`): the conversation is SMS and the message would go out as more than 3 segments, which carriers deliver unreliably. That is 459 characters in GSM-7, or 201 once any character (an emoji, an accent, a curly quote) puts the whole message in UCS-2. The text is measured as it would be sent: after placeholders are filled in and whitespace is tidied, and including a link for each document attachment such as a PDF, because a document is sent as a link inside the SMS. Image and video attachments send the message as MMS, which is not capped, and internal notes are not capped. Nothing was sent, so the message can be shortened and sent again; the same text fails the same way every time. The body is the same with or without `expectedRevision` / `commandIdempotencyKey`. Sending the same body again under the same `commandIdempotencyKey` replays the refusal: the same status, `error.code` and envelope, a fixed `error.message`, and no `segments`, `encoding` or `maxCharacters`, because only the code of a failed command is kept. A shortened body under that key is a different request and is refused with `409 IDEMPOTENCY_KEY_REUSED`; send it with a new key. Other 422 codes on this endpoint (`VALIDATION_RULE_FAILED`, `NO_SENDING_NUMBER`) carry their own bodies."
          content:
            "application/json":
              schema:
                anyOf:
                  -
                    "$ref": "#/components/schemas/SmsTooLongErrorResponse"
                  -
                    "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/conversation/{id}":
    get:
      operationId: "get_conversation_by_id"
      summary: "Get conversation by ID"
      description: "Fetch the conversation metadata (contact, channel, autopilot state, assignees, last activity) by `_id`. Messages live on the dedicated `/messages` endpoint."
      tags:
        - "Conversations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Conversation returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConversationByIdResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Conversation not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
    put:
      operationId: "put_conversation_by_id"
      summary: "Update conversation"
      description: "Update mutable conversation fields: autopilot toggle, active process/prompt, assignees, and history-modal flag. Used by the conversation detail panel."
      tags:
        - "Conversations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateConversationRequest"
      responses:
        "200":
          description: "Conversation updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConversationUpdateResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Conversation not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/conversation/{id}/applications":
    get:
      operationId: "get_conversation_applications"
      summary: "Get applications linked to a conversation"
      description: "Return every Application currently linked to the conversation. Used by the conversation detail panel to render the linked-applications widget."
      tags:
        - "Conversations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Applications returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConversationApplicationsResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Conversation not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
    put:
      operationId: "put_api_conversation_id_applications"
      summary: "PUT /api/conversation/{id}/applications"
      tags:
        - "Conversations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/conversation/{id}/applications/link":
    post:
      operationId: "post_conversation_applications_link"
      summary: "Link conversation to applications"
      description: "Associate one or more existing Application records with this conversation so the agent panel can show them and automations can branch on them."
      tags:
        - "Conversations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/LinkApplicationsRequest"
      responses:
        "200":
          description: "Applications linked"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LinkApplicationsResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Conversation not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/conversation/{id}/applications/unlink":
    post:
      operationId: "post_conversation_applications_unlink"
      summary: "Unlink conversation from applications"
      description: "Detach one or more Applications from a conversation. The Application records themselves are not deleted."
      tags:
        - "Conversations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UnlinkApplicationsRequest"
      responses:
        "200":
          description: "Applications unlinked"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UnlinkApplicationsResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Conversation not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/conversation/{id}/archive":
    post:
      operationId: "post_api_conversation_id_archive"
      summary: "POST /api/conversation/{id}/archive"
      tags:
        - "Conversations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/conversation/{id}/csat":
    post:
      operationId: "post_conversation_csat_by_id"
      summary: "Submit CSAT for a specific conversation (authenticated)"
      description: "Authenticated variant of CSAT submission, used by the agent surface to record CSAT on behalf of a contact when needed."
      tags:
        - "Conversations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/SubmitConversationCsatRequest"
      responses:
        "200":
          description: "CSAT submitted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CsatSubmitResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Conversation not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/conversation/{id}/csat/request":
    post:
      operationId: "post_conversation_csat_request"
      summary: "Request CSAT prompt for webchat conversation"
      description: "Push a CSAT prompt over the webchat socket so the visitor is asked to rate the conversation. Used by the agent surface during resolution."
      tags:
        - "Conversations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "CSAT prompt requested"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SuccessResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Conversation not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "502":
          description: "Failed to reach webchat socket"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/conversation/{id}/resolve":
    put:
      operationId: "put_conversation_resolve"
      summary: "Toggle resolve/unresolve conversation"
      description: "Toggle the conversation between resolved and active. Resolving stamps `resolvedAt`/`resolvedBy` and may trigger a CSAT prompt for webchat conversations."
      tags:
        - "Conversations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ToggleResolveConversationRequest"
      responses:
        "200":
          description: "Resolve state toggled"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConversationResolveResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Conversation not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/conversation/all":
    get:
      operationId: "get_conversation_all"
      summary: "Get conversations by contact"
      description: "Return every conversation in the caller's organization that belongs to the given contact, sorted by most recent first. Powers the contact-detail conversations tab."
      tags:
        - "Conversations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "contactId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Conversations returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConversationsByContactResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Contact not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/conversation/batch/inspect":
    post:
      operationId: "post_api_conversation_batch_inspect"
      summary: "POST /api/conversation/batch/inspect"
      tags:
        - "Conversations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/conversation/batch/messages":
    post:
      operationId: "post_api_conversation_batch_messages"
      summary: "POST /api/conversation/batch/messages"
      tags:
        - "Conversations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/conversation/contact/{contactId}/messages/search":
    get:
      operationId: "get_conversation_contact_messages_search"
      summary: "Search messages across all conversations for a contact"
      description: "Full-text body-field search across every conversation the caller can access for a contact. Results are grouped by conversation with matching message snippets. Supports comma-separated `channelType` filter and a date range. Same body-only caveat as the per-conversation search."
      tags:
        - "Conversations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "contactId"
          required: true
          schema:
            type: "string"
        -
          in: "query"
          name: "q"
          required: true
          schema:
            type: "string"
            minLength: 1
            maxLength: 500
        -
          in: "query"
          name: "matchCase"
          required: false
          schema:
            type: "boolean"
            default: false
        -
          in: "query"
          name: "wholeWord"
          required: false
          schema:
            type: "boolean"
            default: false
        -
          in: "query"
          name: "channelType"
          required: false
          schema:
            type: "string"
          description: "Single channel or comma-separated list (e.g. \"sms,email\")"
        -
          in: "query"
          name: "fromDate"
          required: false
          schema:
            type: "string"
            pattern: "^\\d{4}-\\d{2}-\\d{2}$"
        -
          in: "query"
          name: "toDate"
          required: false
          schema:
            type: "string"
            pattern: "^\\d{4}-\\d{2}-\\d{2}$"
        -
          in: "query"
          name: "limit"
          required: false
          schema:
            type: "integer"
            minimum: 1
            maximum: 5000
            default: 2000
      responses:
        "200":
          description: "Grouped search results returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactMessageSearchResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Contact not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/conversation/csat":
    post:
      operationId: "post_conversation_csat"
      summary: "Submit CSAT from webchat widget (tiered auth)"
      description: "Public endpoint used by the webchat widget to submit a CSAT rating for a conversation identified by `webchatId`. Auth is tiered - if no bearer token is present, the request is gated by the visitor session."
      tags:
        - "Conversations"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/SubmitWebchatCsatRequest"
      responses:
        "200":
          description: "CSAT submitted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CsatSubmitResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "401":
          description: "Authentication required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Conversation not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/conversation/list":
    get:
      operationId: "get_conversation_list"
      summary: "List conversations with filters"
      description: "Return conversations matching any combination of filters: contactId, applicationId, userId, agentId (Prompt._id), channel, direction (works across all channels - voice via Call.direction, non-voice via latest message isIncoming), conversationState, conversationId, time range. Cursor-paginated by lastMessageTime. RBAC: SUPERADMIN sees all orgs, ADMIN/DEPT_HEAD/SALES_REP scoped per role. Also powers the ListConversationsAction workflow node."
      tags:
        - "Conversations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "conversationId"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "contactId"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "applicationId"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "userId"
          required: false
          schema:
            type: "string"
          description: "A user id returns conversations that user is assigned to; the literal 'unassigned' returns conversations with no assignee (every one for SUPERADMIN and ADMIN; for scoped roles only those on lines the caller can read, and an empty list when they read none)."
        -
          in: "query"
          name: "agentId"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "channel"
          required: false
          schema:
            type: "string"
            enum:
              - "sms"
              - "webchat"
              - "email"
              - "voice"
              - "facebook"
        -
          in: "query"
          name: "direction"
          required: false
          schema:
            type: "string"
            enum:
              - "inbound"
              - "outbound"
        -
          in: "query"
          name: "status"
          required: false
          schema:
            type: "string"
            enum:
              - "resolved"
              - "pending_agent_message"
              - "pending_user_message"
              - "pending_contact_message"
        -
          in: "query"
          name: "startDate"
          required: false
          schema:
            type: "string"
          description: "Inclusive lower bound (matched on lastMessageTime, falling back to createdAt). Full ISO 8601 datetime or date-only YYYY-MM-DD."
        -
          in: "query"
          name: "endDate"
          required: false
          schema:
            type: "string"
          description: "Inclusive upper bound. Full ISO 8601 datetime or date-only YYYY-MM-DD (extended to end-of-day UTC)."
        -
          in: "query"
          name: "limit"
          required: false
          schema:
            type: "integer"
            minimum: 1
            maximum: 200
            default: 50
        -
          in: "query"
          name: "cursor"
          required: false
          schema:
            type: "string"
          description: "ISO timestamp from the previous page's nextCursor."
      responses:
        "200":
          description: "Conversations returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ListConversationsResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/conversation/sidebar":
    post:
      operationId: "post_conversation_sidebar"
      summary: "List conversations for the conversations sidebar"
      description: "One row per conversation (voice excluded), page/size paginated. Sorted with unanswered bulk-campaign sends last; otherwise unread first, then by state (pending user, pending agent, pending contact, resolved, none), then newest activity first. Each row carries its own state, unread flag, latest message and autopilot flag plus the contact fields the row renders. Accepts the sidebar's filter drawer: conversation filters (unread, state, live chats, channel, assignee, agent) match each conversation; contact filters (search, source, stage, custom fields, reminders, bulk, verified, blocked) match the contact first. RBAC: org-wide roles see the org, DEPARTMENT_HEAD conversations assigned to their department, everyone else conversations assigned to them."
      tags:
        - "Conversations"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/GetContactsWithConversationsRequest"
      responses:
        "200":
          description: "Conversation rows returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SidebarConversationsResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/conversation/unseen":
    post:
      operationId: "post_conversation_unseen"
      summary: "Mark conversation as unseen"
      description: "Flip the seen-state for the conversation back to unseen for the calling user so it re-surfaces in the inbox unread list."
      tags:
        - "Conversations"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/MarkConversationAsUnseenRequest"
      responses:
        "200":
          description: "Conversation marked as unseen"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MessageResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Conversation not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/conversation/webchat/{webchatId}/csat-status":
    get:
      operationId: "get_conversation_webchat_csat_status"
      summary: "Get webchat CSAT status (no auth required)"
      description: "Public endpoint polled by the webchat widget to check whether a CSAT prompt should be shown for the current session."
      tags:
        - "Conversations"
      parameters:
        -
          in: "path"
          name: "webchatId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "CSAT status returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatCsatStatusResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/departments":
    get:
      operationId: "get_departments"
      summary: "List all departments in the organization"
      description: "Return every department for the caller's organization with populated `managerIds`, `userIds`, `createdBy`, and `updatedBy` references. Powers the org-admin departments list view."
      tags:
        - "Departments"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Departments returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentListResponse"
        "400":
          description: "Missing organization ID"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
    post:
      operationId: "post_departments"
      summary: "Create a new department"
      description: "Create a department within the caller's organization. Name must be unique per-org; provided `managerIds`/`userIds` are validated against the same org."
      tags:
        - "Departments"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CreateDepartmentRequest"
      responses:
        "201":
          description: "Department created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
        "409":
          description: "Department with this name already exists"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
  "/api/departments/{id}":
    get:
      operationId: "get_departments_id"
      summary: "Get a department by ID"
      description: "Fetch a single department by `_id` with populated managers/users; rejects cross-org reads."
      tags:
        - "Departments"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Department returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentResponse"
        "400":
          description: "Missing organization ID"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
        "404":
          description: "Department not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
    put:
      operationId: "put_departments_id"
      summary: "Update a department"
      description: "Update mutable fields of a department. Renaming to a name already in use within the organization returns 409. Manager/user lists are replaced atomically."
      tags:
        - "Departments"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateDepartmentRequest"
      responses:
        "200":
          description: "Department updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
        "404":
          description: "Department not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
        "409":
          description: "Department with this name already exists"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
    delete:
      operationId: "delete_departments_id"
      summary: "Delete a department"
      description: "Delete a department. Members must first be transferred via `/api/departments/transfer/scan-bulk` + `/execute` (with `deleteSourceDepartmentId`) - direct deletion will fail when the department still has members. Refused with 409 while any phone number or email account still shares access with the department (a grant to it): remove the department from their sharing first."
      tags:
        - "Departments"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Department deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentMessageResponse"
        "400":
          description: "Missing organization ID"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
        "404":
          description: "Department not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
        "409":
          description: "Phone numbers or email accounts still share access with the department; the message says how many"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
  "/api/departments/{id}/users":
    get:
      operationId: "get_departments_id_users"
      summary: "Get users in a department"
      description: "Return populated users assigned to the department, along with the department metadata. Used by the department detail view to render the member roster."
      tags:
        - "Departments"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Department users returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentUsersResponse"
        "400":
          description: "Missing organization ID"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
        "404":
          description: "Department not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DepartmentErrorResponse"
  "/api/departments/transfer/{transferId}/status":
    get:
      operationId: "get_departments_transfer_status"
      summary: "Poll execution status of a transfer"
      description: "Return the lifecycle status of a previously-submitted transfer job (`pending`, `running`, `completed`, `failed`). The client polls this until completion to gate UI confirmation."
      tags:
        - "DepartmentTransfer"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "transferId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Status returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TransferStatusResponse"
        "404":
          description: "Transfer not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TransferErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TransferErrorResponse"
  "/api/departments/transfer/execute":
    post:
      operationId: "post_departments_transfer_execute"
      summary: "Execute a user transfer using mappings from a scan"
      description: "Apply the assignments returned by `/scan` or `/scan-bulk`. The supplied `scanVersion` must still match the live state - a stale scan returns 400 and the caller must re-scan. Optionally deletes the source department after a successful bulk move. Returns 202 with a `transferId` for status polling."
      tags:
        - "DepartmentTransfer"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/TransferExecuteRequest"
      responses:
        "202":
          description: "Transfer accepted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TransferStatusResponse"
        "400":
          description: "Validation error / stale scan"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TransferErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TransferErrorResponse"
        "409":
          description: "Conflict (e.g. another transfer in progress), or `deleteSourceDepartmentId` names a department that phone numbers or email accounts still share access with (a grant to it); remove it from their sharing first. Nothing is moved."
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TransferErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TransferErrorResponse"
  "/api/departments/transfer/scan":
    post:
      operationId: "post_departments_transfer_scan"
      summary: "Deep scan dependencies for a single-user department transfer"
      description: "Compute the dependency manifest for moving one user to a new department: prompts, automations, conversations, contacts and approval policies that need remapping. Returns a `scanVersion` token that must be echoed on `/execute` to detect stale plans."
      tags:
        - "DepartmentTransfer"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/TransferScanRequest"
      responses:
        "200":
          description: "Scan completed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ScanResultResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TransferErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TransferErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TransferErrorResponse"
  "/api/departments/transfer/scan-bulk":
    post:
      operationId: "post_departments_transfer_scan_bulk"
      summary: "Deep scan dependencies for a bulk/department-deletion transfer"
      description: "Bulk variant of `/scan` - accepts an array of `{ userId, targetDepartmentId }` pairs (typically every member of a department being deleted) and returns the combined dependency manifest plus a `scanVersion`."
      tags:
        - "DepartmentTransfer"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/BulkTransferScanRequest"
      responses:
        "200":
          description: "Bulk scan completed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ScanResultResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TransferErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TransferErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TransferErrorResponse"
  "/api/email/accounts":
    get:
      operationId: "get_email_accounts"
      summary: "List email accounts for the current user"
      description: "Returns active `EmailAccount` documents (across Gmail and Outlook), sorted newest-first. Admins see every mailbox in their organization. Everyone else, and an admin passing `mine=true` (the compose \"From\" picker), sees the mailboxes they may send from: connected by them, linked to them, linked to a group they belong to, or shared with them (their user, their department or one of their groups) through a `send` grant. Each entry carries `via`, saying how the caller reaches it, and `verbs`, the verbs it gives (`[\"send\"]`, or `[]` where `via` is `null`). The OAuth `tokens` subdocument is stripped from each entry."
      tags:
        - "Email"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          name: "mine"
          in: "query"
          required: false
          description: "`true` limits an admin to the mailboxes they may personally send from, as for a non-admin. Ignored for non-admins, who always get that set."
          schema:
            type: "string"
            enum:
              - "true"
              - "false"
      responses:
        "200":
          description: "Email accounts list"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailAccountListResponse"
        "500":
          description: "Unable to list email accounts"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
  "/api/email/accounts/{accountId}":
    delete:
      operationId: "delete_email_accounts_accountId"
      summary: "Disconnect an email account"
      description: "Soft-disconnects the account: stops the mailbox watch (Gmail `users.stop`, Outlook subscription delete), marks the `EmailAccount` `isActive: false`, and clears `historyId` / `watchExpiration`. The stored OAuth tokens are kept on the document but the account no longer participates in sync."
      tags:
        - "Email"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "accountId"
          required: true
          schema:
            type: "string"
          description: "Internal `_id` of the `EmailAccount` document."
      responses:
        "200":
          description: "Account disconnected"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailAccountDisconnectResponse"
        "404":
          description: "Account not found or not owned by the caller"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
        "500":
          description: "Unable to disconnect account"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
  "/api/email/accounts/providers/available":
    get:
      operationId: "get_email_accounts_providers_available"
      summary: "List configured email providers"
      description: "Reports which email providers the relay is *capable* of authorizing against - that is, which provider OAuth client IDs and secrets are configured on the backend. Frontends use this to show or hide \"Connect Gmail\" / \"Connect Outlook\" buttons. Always returns 200 even when no providers are configured."
      tags:
        - "Email"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Provider availability map keyed by provider name. `true` means OAuth credentials are configured on this backend."
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailProviderAvailabilityResponse"
  "/api/email/messages/attachments/rehydrate":
    post:
      operationId: "post_email_messages_attachments_rehydrate"
      summary: "Rehydrate email message attachments from provider"
      description: "Re-downloads attachment bytes for an email message from the provider and re-uploads them to R2 storage. Used when the stored signed URL expired or the attachment was never persisted locally."
      tags:
        - "Email"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/EmailRehydrateAttachmentsRequest"
      responses:
        "200":
          description: "Attachments rehydrated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailRehydrateAttachmentsResponse"
        "400":
          description: "messageId required or missing metadata"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
        "404":
          description: "Message or account not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
        "500":
          description: "Unable to rehydrate attachments"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
  "/api/email/messages/draft":
    post:
      operationId: "post_email_messages_draft"
      summary: "Create an email draft conversation"
      description: "Creates a draft email conversation bound to the supplied recipient(s) and account. The resulting conversation/message can be edited and sent through the standard send flow."
      tags:
        - "Email"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/EmailCreateDraftRequest"
      responses:
        "200":
          description: "Draft created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailCreateDraftResponse"
        "400":
          description: "Missing required fields"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
        "404":
          description: "Email account not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
        "500":
          description: "Unable to create email draft"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
  "/api/email/messages/send":
    post:
      operationId: "post_email_messages_send"
      summary: "Send an email message"
      description: "Sends an email through the authenticated user's connected mailbox (Gmail or Outlook). The mailbox is resolved by matching the `from` address against the user's connected accounts - the user must have previously completed the OAuth flow for that address. Supports plain-text or HTML bodies, CC/BCC, threading (replies), and attachments stored in R2."
      tags:
        - "Email"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/EmailSendMessageRequest"
      responses:
        "200":
          description: "Email sent. Returns the stored message document, conversation id, and provider thread id."
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailSendMessageResponse"
        "400":
          description: "Missing required fields, invalid `from` format, or attempted to send a private note through this endpoint."
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
        "404":
          description: "No active mailbox is connected for the given `from` address on the authenticated user."
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
        "500":
          description: "Unexpected failure while sending through the email provider."
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
  "/api/email/messages/sync":
    post:
      operationId: "post_email_messages_sync"
      summary: "Sync email messages from provider"
      description: "Triggers an asynchronous historical sync of the specified connected mailbox (Gmail or Outlook). Returns immediately; observe progress via `GET /api/email/messages/sync/status`."
      tags:
        - "Email"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/EmailSyncMessagesRequest"
      responses:
        "200":
          description: "Sync started or status returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailSyncStartedResponse"
        "404":
          description: "Email account not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
        "500":
          description: "Unable to sync email messages"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
  "/api/email/messages/sync/status":
    get:
      operationId: "get_email_messages_sync_status"
      summary: "Get email sync status for an account"
      description: "Returns the latest historical-sync progress for a connected mailbox: whether a sync is in flight, last completion timestamp, and progress counters. Use this to drive a progress indicator after kicking off `POST /api/email/messages/sync`."
      tags:
        - "Email"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "accountId"
          required: true
          schema:
            type: "string"
          description: "Internal `_id` of the `EmailAccount` to query."
      responses:
        "200":
          description: "Sync status returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailSyncStatusResponse"
        "400":
          description: "accountId is required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
  "/api/email/oauth/authorize":
    get:
      operationId: "get_email_oauth_authorize"
      summary: "Initiate email OAuth authorization flow"
      description: "Returns the provider-hosted authorization URL the user must visit to grant mailbox access. The server packs `{ userId, organizationId, provider }` into the OAuth `state` parameter so the callback can attribute the resulting tokens. Supports Gmail and Outlook."
      tags:
        - "Email"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "provider"
          required: false
          schema:
            type: "string"
            enum:
              - "gmail"
              - "outlook"
            default: "gmail"
          description: "Email provider to authorize against. Defaults to `gmail`."
      responses:
        "200":
          description: "Authorization URL returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailAuthorizeUrlResponse"
        "400":
          description: "Unsupported email provider"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
  "/api/email/oauth/callback":
    get:
      operationId: "get_email_oauth_callback"
      summary: "Handle email OAuth callback"
      description: "Provider redirect target. Exchanges the authorization `code` for tokens, persists or refreshes the `EmailAccount`, sets up mailbox watch (Gmail Pub/Sub or Outlook Graph subscription) when configured, then **302-redirects** to the client settings page with `?provider=<name>&status=success|error`. This route is public (no bearer auth) - the userId/organizationId come from the signed OAuth `state`. Only the pre-redirect validation failures surface as JSON (400). On a downstream failure the user is still 302-redirected back to the settings page with `status=error`."
      tags:
        - "Email"
      parameters:
        -
          in: "query"
          name: "code"
          required: false
          schema:
            type: "string"
          description: "Authorization code returned by the provider."
        -
          in: "query"
          name: "state"
          required: false
          schema:
            type: "string"
          description: "Base64-encoded JSON `{ userId, organizationId, provider }` echoed back by the provider."
      responses:
        "302":
          description: "Redirect to `${CLIENT_URL}/settings?provider=<name>&status=success` on success, or `${CLIENT_URL}/settings?status=error` on failure. Frontends should observe the `provider` and `status` query parameters on the resulting settings page to surface the outcome to the user."
          headers:
            Location:
              description: "Client settings URL with provider and status query parameters."
              schema:
                type: "string"
                format: "uri"
        "400":
          description: "Missing code or state, or invalid state payload"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailOAuthCallbackErrorResponse"
  "/api/escalation-dashboard/agent-conversations":
    get:
      operationId: "get_agent_conversations"
      summary: "List conversations for a single agent (paginated)"
      description: "Returns the SMS / email / webchat conversations attached to a single agent for the dashboard's per-agent drill-down. `type=assignee` lists conversations where the agent is in `assignees`; `type=owner` lists conversations where the agent is the `userId` owner. Voice conversations are intentionally excluded."
      tags:
        - "Escalation Dashboard"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "departmentId"
          required: false
          schema:
            type: "string"
          description: "Optional department filter. ADMIN/SUPERADMIN may pass any departmentId; DEPARTMENT_HEAD is implicitly scoped to their own department and any other value is ignored."
        -
          in: "query"
          name: "userId"
          required: true
          schema:
            type: "string"
          description: "Target agent's user id. Must be a valid ObjectId in the caller's organization (and department, for DEPARTMENT_HEAD)."
        -
          in: "query"
          name: "type"
          required: false
          schema:
            type: "string"
            enum:
              - "assignee"
              - "owner"
            default: "assignee"
        -
          in: "query"
          name: "page"
          required: false
          schema:
            type: "integer"
            minimum: 1
            default: 1
            description: "1-based page number."
        -
          in: "query"
          name: "limit"
          required: false
          schema:
            type: "integer"
            minimum: 1
            maximum: 100
            default: 20
            description: "Page size. Clamped to [1, 100]."
      responses:
        "200":
          description: "Agent conversations returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AgentConversationsResponse"
        "400":
          description: "Missing or invalid userId"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationDashboardError"
        "403":
          description: "Access denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationDashboardError"
        "500":
          description: "Error fetching agent conversations"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationDashboardError"
  "/api/escalation-dashboard/agents":
    get:
      operationId: "get_agent_statuses"
      summary: "List agents with current presence and capacity"
      description: "Returns one entry per agent in scope with their connection state, availability toggle, current unresolved chat count, configured max-chats ceiling, and the last assignment / availability timestamps. Used to populate the agent grid on the escalation dashboard."
      tags:
        - "Escalation Dashboard"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "departmentId"
          required: false
          schema:
            type: "string"
          description: "Optional department filter. ADMIN/SUPERADMIN may pass any departmentId; DEPARTMENT_HEAD is implicitly scoped to their own department and any other value is ignored."
      responses:
        "200":
          description: "Agent statuses returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AgentStatusesResponse"
        "403":
          description: "Access denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationDashboardError"
        "500":
          description: "Error fetching agent statuses"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationDashboardError"
  "/api/escalation-dashboard/assignments":
    get:
      operationId: "get_assignment_history"
      summary: "List historical escalation assignments (paginated)"
      description: "Returns paginated EscalationAssignment records (an audit log of every queue → agent or direct assignment), enriched with contact, assignee, and department names. Supports filtering by assignee, automation, date range, and free-text contact search."
      tags:
        - "Escalation Dashboard"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "departmentId"
          required: false
          schema:
            type: "string"
          description: "Optional department filter. ADMIN/SUPERADMIN may pass any departmentId; DEPARTMENT_HEAD is implicitly scoped to their own department and any other value is ignored."
        -
          in: "query"
          name: "page"
          required: false
          schema:
            type: "integer"
            minimum: 1
            default: 1
            description: "1-based page number."
        -
          in: "query"
          name: "limit"
          required: false
          schema:
            type: "integer"
            minimum: 1
            maximum: 100
            default: 20
            description: "Page size. Clamped to [1, 100]."
        -
          in: "query"
          name: "assigneeId"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "automationId"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "startDate"
          required: false
          schema:
            type: "string"
            format: "date-time"
        -
          in: "query"
          name: "endDate"
          required: false
          schema:
            type: "string"
            format: "date-time"
        -
          in: "query"
          name: "search"
          required: false
          schema:
            type: "string"
          description: "Case-insensitive substring match against contact firstName, lastName, or phoneNumber.value."
      responses:
        "200":
          description: "Assignment history returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AssignmentHistoryResponse"
        "403":
          description: "Access denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationDashboardError"
        "500":
          description: "Error fetching assignment history"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationDashboardError"
  "/api/escalation-dashboard/availability-events":
    get:
      operationId: "get_availability_events"
      summary: "List raw availability events (paginated)"
      description: "Returns the raw AgentAvailabilityEvent stream (connection / availability / capacity transitions) within a time window, optionally filtered by user, category, value, and source. Used to back the audit / drill-down view on the escalation dashboard."
      tags:
        - "Escalation Dashboard"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "departmentId"
          required: false
          schema:
            type: "string"
          description: "Optional department filter. ADMIN/SUPERADMIN may pass any departmentId; DEPARTMENT_HEAD is implicitly scoped to their own department and any other value is ignored."
        -
          in: "query"
          name: "userId"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "start"
          required: false
          schema:
            type: "string"
            format: "date-time"
          description: "ISO-8601 start of the window. Defaults to end - 24h."
        -
          in: "query"
          name: "end"
          required: false
          schema:
            type: "string"
            format: "date-time"
          description: "ISO-8601 end of the window. Defaults to now."
        -
          in: "query"
          name: "page"
          required: false
          schema:
            type: "integer"
            minimum: 1
            default: 1
            description: "1-based page number."
        -
          in: "query"
          name: "limit"
          required: false
          schema:
            type: "integer"
            minimum: 1
            maximum: 200
            default: 50
            description: "Page size. Clamped to [1, 200]."
        -
          in: "query"
          name: "category"
          required: false
          schema:
            type: "string"
            enum:
              - "connection"
              - "availability"
              - "capacity"
        -
          in: "query"
          name: "value"
          required: false
          schema:
            type: "string"
            enum:
              - "online"
              - "offline"
              - "available"
              - "unavailable"
              - "at_capacity"
              - "has_capacity"
        -
          in: "query"
          name: "source"
          required: false
          schema:
            type: "string"
            enum:
              - "socket"
              - "toggle"
              - "auto_away"
              - "assignment"
              - "resolution"
              - "system"
      responses:
        "200":
          description: "Availability events returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AvailabilityEventsResponse"
        "400":
          description: "Invalid start or end date"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationDashboardError"
        "403":
          description: "Access denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationDashboardError"
        "500":
          description: "Error fetching availability events"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationDashboardError"
  "/api/escalation-dashboard/availability-timeline":
    get:
      operationId: "get_availability_timeline"
      summary: "Get bucketed per-agent and aggregate availability timeline"
      description: "Returns availability state buckets over a time window for charting. Each bucket carries the dominant state per agent and the aggregate state across the org/department, plus per-agent online / available / at-capacity durations within the bucket. Defaults to the last 24 hours with 15-minute buckets if start/end/bucketMinutes are omitted."
      tags:
        - "Escalation Dashboard"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "departmentId"
          required: false
          schema:
            type: "string"
          description: "Optional department filter. ADMIN/SUPERADMIN may pass any departmentId; DEPARTMENT_HEAD is implicitly scoped to their own department and any other value is ignored."
        -
          in: "query"
          name: "start"
          required: false
          schema:
            type: "string"
            format: "date-time"
          description: "ISO-8601 start of the window. Defaults to end - 24h."
        -
          in: "query"
          name: "end"
          required: false
          schema:
            type: "string"
            format: "date-time"
          description: "ISO-8601 end of the window. Defaults to now."
        -
          in: "query"
          name: "bucketMinutes"
          required: false
          schema:
            type: "integer"
            minimum: 1
            maximum: 120
            default: 15
            description: "Bucket size in minutes. Clamped to [1, 120]."
      responses:
        "200":
          description: "Availability timeline returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AvailabilityTimelineResponse"
        "400":
          description: "Invalid start or end date"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationDashboardError"
        "403":
          description: "Access denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationDashboardError"
        "500":
          description: "Error fetching availability timeline"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationDashboardError"
  "/api/escalation-dashboard/filters":
    get:
      operationId: "get_filter_options"
      summary: "Get filter dropdown options (users, automations, departments)"
      description: "Returns the option lists used to populate the dashboard's filter dropdowns: in-scope users, automations that have escalation configured, and (for ADMIN/SUPERADMIN only) all departments in the organization."
      tags:
        - "Escalation Dashboard"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "departmentId"
          required: false
          schema:
            type: "string"
          description: "Optional department filter. ADMIN/SUPERADMIN may pass any departmentId; DEPARTMENT_HEAD is implicitly scoped to their own department and any other value is ignored."
      responses:
        "200":
          description: "Filter options returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/FilterOptionsResponse"
        "403":
          description: "Access denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationDashboardError"
        "500":
          description: "Error fetching filter options"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationDashboardError"
  "/api/escalation-dashboard/queue":
    get:
      operationId: "get_escalation_queue"
      summary: "List current escalation queue items"
      description: "Returns the live escalation queue (contacts waiting for an agent), enriched with contact / automation metadata and per-item wait time in milliseconds. Sorted oldest-waiting first. Optionally scoped to a department by filtering on automations that escalate to that department."
      tags:
        - "Escalation Dashboard"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "departmentId"
          required: false
          schema:
            type: "string"
          description: "Optional department filter. ADMIN/SUPERADMIN may pass any departmentId; DEPARTMENT_HEAD is implicitly scoped to their own department and any other value is ignored."
      responses:
        "200":
          description: "Escalation queue returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationQueueResponse"
        "403":
          description: "Access denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationDashboardError"
        "500":
          description: "Error fetching escalation queue"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationDashboardError"
  "/api/escalation-dashboard/stats":
    get:
      operationId: "get_escalation_stats"
      summary: "Get aggregate escalation dashboard statistics"
      description: "Returns top-line escalation dashboard counters: online agents, available agents, current queue length, assignments made today, and rolling 7-day average queue wait time. Optionally scoped to a department."
      tags:
        - "Escalation Dashboard"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "departmentId"
          required: false
          schema:
            type: "string"
          description: "Optional department filter. ADMIN/SUPERADMIN may pass any departmentId; DEPARTMENT_HEAD is implicitly scoped to their own department and any other value is ignored."
        -
          in: "query"
          name: "tz"
          required: false
          schema:
            type: "string"
          description: "IANA timezone name (e.g. \"America/Toronto\") used to compute the start-of-today boundary for the assignedToday counter. Defaults to server local time."
      responses:
        "200":
          description: "Escalation stats returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationStatsResponse"
        "403":
          description: "Access denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationDashboardError"
        "500":
          description: "Error fetching escalation stats"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationDashboardError"
  "/api/event-logs":
    get:
      operationId: "get_event_logs"
      summary: "Get event logs with filters and pagination"
      description: "Paginated list of EventLog records, with optional filters (`organizationId`, `userId`, `contactId`, `direction`, `automationTriggered`) and a `days` lookback window. Powers the audit/event-log surface; non-SUPERADMIN callers are pinned to their own org."
      tags:
        - "Event Logs"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "page"
          required: false
          schema:
            type: "integer"
            minimum: 1
            default: 1
        -
          in: "query"
          name: "limit"
          required: false
          schema:
            type: "integer"
            minimum: 1
            default: 50
        -
          in: "query"
          name: "organizationId"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "userId"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "contactId"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "direction"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "automationTriggered"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "days"
          required: false
          schema:
            type: "number"
            default: 7
      responses:
        "200":
          description: "Event logs returned with pagination"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EventLogListResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EventLogErrorResponse"
        "403":
          description: "Access denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EventLogErrorResponse"
        "500":
          description: "Error fetching event logs"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EventLogErrorResponse"
  "/api/event-logs/{id}":
    get:
      operationId: "get_event_log_by_id"
      summary: "Get a single event log by ID"
      description: "Fetch a single EventLog by `_id`. Used by the audit drawer to render the full payload of a row clicked from the list view. Cross-org access is denied for non-SUPERADMIN callers."
      tags:
        - "Event Logs"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Event log returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EventLogSingleResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EventLogErrorResponse"
        "403":
          description: "Access denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EventLogErrorResponse"
        "404":
          description: "Event log not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EventLogErrorResponse"
        "500":
          description: "Error fetching event log"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EventLogErrorResponse"
  "/api/google-sheets/oauth/google/callback":
    get:
      operationId: "get_google_sheets_oauth_callback"
      summary: "Google OAuth callback for the Google Sheets integration"
      description: "Public endpoint (no `authMiddleware`) that completes the Google OAuth flow for the Google Sheets scraper service. The relay proxies the upstream response - when the upstream returns a 3xx with a `Location` header, the relay forwards that redirect (typically back to the application UI). JSON or text bodies are forwarded with the upstream status."
      tags:
        - "Google Sheets"
      parameters:
        -
          in: "query"
          name: "code"
          required: false
          schema:
            type: "string"
          description: "OAuth authorization code returned by Google"
        -
          in: "query"
          name: "state"
          required: false
          schema:
            type: "string"
          description: "Opaque state token forwarded back to the OAuth caller"
        -
          in: "query"
          name: "scope"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "error"
          required: false
          schema:
            type: "string"
          description: "Set when the user denies the OAuth consent or the provider rejects the request"
      responses:
        "200":
          description: "Non-redirect upstream response (rare; e.g. the scraper directly returns a JSON status without redirecting)."
          content:
            "text/html":
              schema:
                type: "string"
              example: "<html><body>Google Sheets connection completed. You can close this window.</body></html>"
            "application/json":
              schema:
                type: "object"
                properties:
                  status:
                    type: "string"
                    description: "Upstream status flag forwarded verbatim."
                additionalProperties: true
              example:
                status: "success"
        "302":
          description: "Redirect back to the application UI (forwarded from the google-sheets-scraper service). On success the URL carries `google_sheets_status=success`; on user/provider denial it carries `google_sheets_status=error&reason=…`."
          headers:
            Location:
              description: "Application redirect URL."
              schema:
                type: "string"
              example: "https://app.tetherai.ca/integrations/google-sheets?google_sheets_status=success"
        "502":
          description: "Google Sheets service unavailable"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/GoogleSheetsErrorResponse"
  "/api/lead-management":
    get:
      operationId: "get_lead_management"
      summary: "List lead management configurations for the current user"
      description: "Returns every LeadManagement configuration owned by the authenticated user in the current organization, ordered by createdAt (newest first)."
      tags:
        - "Lead Management"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Configurations returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LeadManagementListResponse"
        "400":
          description: "User ID and Organization ID are required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LeadManagementErrorResponse"
        "500":
          description: "Error fetching lead management configurations"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LeadManagementErrorResponse"
    post:
      operationId: "post_lead_management"
      summary: "Create a lead management configuration"
      description: "Creates a new LeadManagement configuration for the authenticated user. The configurationName must be unique per user (case-insensitive) and defaultProcess must resolve to an existing Prompt ID."
      tags:
        - "Lead Management"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CreateLeadManagementRequest"
      responses:
        "201":
          description: "Configuration created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LeadManagementMutationResponse"
        "400":
          description: "Validation error, duplicate name, or a sending line that is not an active SMS line of the organization on its active SMS provider"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LeadManagementErrorResponse"
        "500":
          description: "Error creating lead management"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LeadManagementErrorResponse"
  "/api/lead-management/{id}":
    get:
      operationId: "get_lead_management_by_id"
      summary: "Get a lead management configuration by id"
      description: "Returns the LeadManagement configuration with the given id, scoped to the authenticated user and organization. Returns 404 when the configuration does not exist or belongs to another user."
      tags:
        - "Lead Management"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Configuration returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LeadManagementDetailResponse"
        "400":
          description: "Invalid id"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LeadManagementErrorResponse"
        "404":
          description: "Configuration not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LeadManagementErrorResponse"
        "500":
          description: "Error fetching lead management configuration"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LeadManagementErrorResponse"
    put:
      operationId: "put_lead_management"
      summary: "Update a lead management configuration"
      description: "Updates the LeadManagement configuration with the given id. Caller must own the configuration. Each field is validated independently; defaultProcess (when supplied) must resolve to an existing Prompt ID."
      tags:
        - "Lead Management"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateLeadManagementRequest"
      responses:
        "200":
          description: "Configuration updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LeadManagementMutationResponse"
        "400":
          description: "Validation error, or a sending line that is not an active SMS line of the organization on its active SMS provider"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LeadManagementErrorResponse"
        "403":
          description: "Permission denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LeadManagementErrorResponse"
        "404":
          description: "Configuration not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LeadManagementErrorResponse"
        "500":
          description: "Error updating lead management"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LeadManagementErrorResponse"
    delete:
      operationId: "delete_lead_management"
      summary: "Delete a lead management configuration"
      description: "Deletes the LeadManagement configuration owned by the authenticated user. Returns 404 if no matching configuration exists for this user."
      tags:
        - "Lead Management"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Configuration deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LeadManagementMessageResponse"
        "400":
          description: "Invalid id"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LeadManagementErrorResponse"
        "404":
          description: "Configuration not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LeadManagementErrorResponse"
        "500":
          description: "Error deleting lead management configuration"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LeadManagementErrorResponse"
  "/api/marketplace":
    get:
      operationId: "browse_marketplace"
      summary: "Browse marketplace items (org + marketplace)"
      description: "List published items the caller can acquire - items scoped to the caller's organization plus globally-published marketplace items - filtered by itemType/search and paginated."
      tags:
        - "Marketplace"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "filter"
          required: false
          schema:
            type: "string"
            enum:
              - "all"
              - "organization"
              - "marketplace"
        -
          in: "query"
          name: "itemType"
          required: false
          schema:
            type: "string"
            enum:
              - "prompt"
              - "template"
        -
          in: "query"
          name: "search"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "page"
          required: false
          schema:
            type: "integer"
            minimum: 1
            default: 1
        -
          in: "query"
          name: "limit"
          required: false
          schema:
            type: "integer"
            minimum: 1
            default: 20
      responses:
        "200":
          description: "Marketplace items returned with pagination"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceBrowseResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
  "/api/marketplace/{id}":
    get:
      operationId: "get_published_item"
      summary: "Get single marketplace item details"
      description: "Return the full PublishedItem document for a marketplace listing, including metadata and share settings, provided the caller is in scope to view it."
      tags:
        - "Marketplace"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Marketplace item returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplacePublishedItemResponse"
        "403":
          description: "Not authorized to view this item"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
        "404":
          description: "Marketplace item not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
    patch:
      operationId: "update_publish_settings"
      summary: "Update publish settings for a marketplace item"
      description: "Patch shareType, isContentVisible, and allowEditableReferences on an existing PublishedItem. Admin/Superadmin only and the caller must be the original publisher (Superadmin override)."
      tags:
        - "Marketplace"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdatePublishSettingsRequest"
      responses:
        "200":
          description: "Publish settings updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceUpdatePublishSettingsResponse"
        "403":
          description: "Only Admin/Superadmin or not authorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
        "404":
          description: "Marketplace item not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
    delete:
      operationId: "unpublish_item"
      summary: "Unpublish a marketplace item by published-item id"
      description: "Delete the PublishedItem with the given id and cascade-delete every UserAcquiredItem that referenced it. Admin/Superadmin only; ADMIN must also be the original publisher."
      tags:
        - "Marketplace"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Item unpublished"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceUnpublishResponse"
        "403":
          description: "Only Admin/Superadmin can unpublish or not the original publisher"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
        "404":
          description: "Published item not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
  "/api/marketplace/{id}/acquire":
    post:
      operationId: "acquire_item"
      summary: "Acquire a marketplace item (reference or copy)"
      description: "Acquire a published prompt for the calling user. When shareType is `copy` a duplicate Prompt document is created and ownership assigned to the caller; when `reference` only a UserAcquiredItem link is recorded. Templates must be acquired via /api/marketplace/{id}/import-to-automations instead."
      tags:
        - "Marketplace"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AcquireItemRequest"
      responses:
        "201":
          description: "Item acquired"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceAcquireResponse"
        "400":
          description: "Invalid ID, already acquired, deprecated, or unsupported type"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
        "403":
          description: "Not authorized to acquire this item"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
        "404":
          description: "Marketplace item or original item not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
  "/api/marketplace/acquired":
    get:
      operationId: "get_acquired_items"
      summary: "Get user acquired items"
      description: "List every marketplace item the caller has previously acquired, optionally filtered by itemType. Returned records link back to the underlying prompt/template the user owns or references."
      tags:
        - "Marketplace"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "itemType"
          required: false
          schema:
            type: "string"
      responses:
        "200":
          description: "Acquired items returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceAcquiredItemsResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
  "/api/marketplace/automations/sms-status":
    get:
      operationId: "get_automations_sms_status"
      summary: "Get SMS status for all automations in user organization"
      description: "Return SMS-readiness status for every automation in the caller's organization. Used by the marketplace template-import flow to show which automations a template can be applied to."
      tags:
        - "Marketplace"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Automation SMS statuses returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceAutomationsSmsStatusResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
        "500":
          description: "Failed to fetch automation SMS status"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
  "/api/marketplace/by-item/{itemId}":
    delete:
      operationId: "unpublish_by_item_id"
      summary: "Unpublish a marketplace listing by source item id"
      description: "Find the active PublishedItem whose source itemId matches and delete it, along with every UserAcquiredItem that referenced it. Admin/Superadmin only; ADMIN must also be the original publisher."
      tags:
        - "Marketplace"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "itemId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Item unpublished"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceUnpublishResponse"
        "403":
          description: "Only Admin/Superadmin can unpublish or not the original publisher"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
        "404":
          description: "Published item not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
  "/api/marketplace/my-published":
    get:
      operationId: "get_my_published_items"
      summary: "Get items published by current user"
      description: "List every PublishedItem record whose publishedBy matches the caller, optionally filtered by itemType. Used by the publisher dashboard to manage their own listings."
      tags:
        - "Marketplace"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "itemType"
          required: false
          schema:
            type: "string"
      responses:
        "200":
          description: "Published items returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceMyPublishedItemsResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
  "/api/marketplace/publish":
    post:
      operationId: "publish_item"
      summary: "Publish an item to organization and/or marketplace"
      description: "Publish a prompt or template to the caller's organization scope, the global marketplace scope, or both. Admin/Superadmin only; rejects duplicate publications of the same itemId."
      tags:
        - "Marketplace"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/PublishItemRequest"
      responses:
        "201":
          description: "Item published"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplacePublishResponse"
        "400":
          description: "Missing required fields, invalid item type, or already published"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
        "403":
          description: "Only Admin/Superadmin can publish or item not owned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
        "404":
          description: "User or item not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
  "/api/media":
    get:
      operationId: "get_api_media"
      summary: "GET /api/media"
      tags:
        - "Media"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
    post:
      operationId: "post_api_media"
      summary: "POST /api/media"
      tags:
        - "Media"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/media-storage/config":
    get:
      operationId: "get_api_media_storage_config"
      summary: "GET /api/media-storage/config"
      tags:
        - "Media Storage"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
    post:
      operationId: "post_api_media_storage_config"
      summary: "POST /api/media-storage/config"
      tags:
        - "Media Storage"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
    delete:
      operationId: "delete_api_media_storage_config"
      summary: "DELETE /api/media-storage/config"
      tags:
        - "Media Storage"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/media/{mediaId}":
    get:
      operationId: "get_api_media_mediaId"
      summary: "GET /api/media/{mediaId}"
      tags:
        - "Media"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "mediaId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
    patch:
      operationId: "patch_api_media_mediaId"
      summary: "PATCH /api/media/{mediaId}"
      tags:
        - "Media"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "mediaId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
    delete:
      operationId: "delete_api_media_mediaId"
      summary: "DELETE /api/media/{mediaId}"
      tags:
        - "Media"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "mediaId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/media/{mediaId}/download":
    get:
      operationId: "get_api_media_mediaId_download"
      summary: "GET /api/media/{mediaId}/download"
      tags:
        - "Media"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "mediaId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/media/application/{applicationId}":
    get:
      operationId: "get_api_media_application_applicationId"
      summary: "GET /api/media/application/{applicationId}"
      tags:
        - "Media"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "applicationId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/media/conversation/{conversationId}":
    get:
      operationId: "get_api_media_conversation_conversationId"
      summary: "GET /api/media/conversation/{conversationId}"
      tags:
        - "Media"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "conversationId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/media/upload":
    post:
      operationId: "post_api_media_upload"
      summary: "POST /api/media/upload"
      tags:
        - "Media"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/messages/attachment-url/{storageKey}":
    get:
      operationId: "get_messages_attachment_url"
      summary: "Get signed URL for an attachment"
      description: "Return a short-lived signed R2 URL for the attachment along with the storage key (and `remappedFrom` when a stale email-attachment key was rewritten). The signed URL is used by previews that need the URL itself rather than a redirect."
      tags:
        - "Messages"
      parameters:
        -
          in: "path"
          name: "storageKey"
          required: true
          schema:
            type: "string"
          description: "Full R2 storage key"
        -
          in: "query"
          name: "inline"
          required: false
          schema:
            type: "string"
          description: "Set to \"1\" or \"true\" to request inline content disposition for PDFs"
        -
          in: "query"
          name: "contentType"
          required: false
          schema:
            type: "string"
      responses:
        "200":
          description: "Signed URL returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AttachmentSignedUrlResponse"
        "400":
          description: "Invalid storage key"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "401":
          description: "Authentication required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "403":
          description: "Permission denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Attachment not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "503":
          description: "Storage not configured"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/messages/attachment/{storageKey}":
    get:
      operationId: "get_messages_attachment"
      summary: "Get attachment by storage key (redirects to signed URL)"
      description: "Resolve a message attachment by R2 storage key and 302-redirect to a short-lived signed URL. Used by the conversation UI to render inline media without bundling presigned URLs in the message body."
      tags:
        - "Messages"
      parameters:
        -
          in: "path"
          name: "storageKey"
          required: true
          schema:
            type: "string"
          description: "Full R2 storage key (e.g. messages/{orgId}/{msgId}/{filename})"
      responses:
        "302":
          description: "Redirect to signed URL"
        "400":
          description: "Invalid storage key"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "401":
          description: "Authentication required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "403":
          description: "Permission denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Attachment not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "503":
          description: "Storage not configured"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/messages/download":
    get:
      operationId: "get_messages_download"
      summary: "Download an attachment with forced Content-Disposition"
      description: "Streams the attachment bytes back with `Content-Disposition: attachment`. Requires authentication (JWT or webchat session) and is scoped to the caller's organization: the storage key must belong to the caller's org, and webchat callers cannot fetch internal attachments."
      tags:
        - "Messages"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "key"
          required: true
          schema:
            type: "string"
          description: "Full R2 storage key (must belong to the caller's organization)"
        -
          in: "query"
          name: "fileName"
          required: false
          schema:
            type: "string"
            default: "download"
          description: "Filename to suggest in the Content-Disposition header"
      responses:
        "200":
          description: "Attachment bytes with an attachment Content-Disposition"
        "400":
          description: "Storage key is required or invalid"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MessagesDownloadErrorResponse"
        "401":
          description: "Authentication required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MessagesDownloadErrorResponse"
        "403":
          description: "Attachment belongs to another organization"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MessagesDownloadErrorResponse"
        "500":
          description: "Failed to download attachment"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MessagesDownloadErrorResponse"
  "/api/messages/quick-bulk-send":
    post:
      operationId: "post_messages_quick_bulk_send"
      summary: "Send quick bulk SMS to multiple contacts"
      description: "Fan-out send of a single SMS body (or templated body via `templateId`) to up to 50,000 contacts. Up to 500 distinct contacts are sent inside the request, which returns 200 with a per-contact result list with `success`/`error` so the UI can surface partial failures. More than 500 distinct contacts are not sent in the request: they become a durable `bulk_sms` async operation, which the async-operation runner sends one contact at a time, and the request returns 202 with `queued: true`, the `operationId` (also in `jobId`) and its `status`, a `summary` with nothing sent yet and an empty `results`. Any user who may send a quick bulk send may queue one; the chosen line's grant is checked first. More than 50,000 `contactIds` returns 400; select all and use the bulk SMS operation (`POST /api/contacts/query-bulk-sms`) instead. Messages sent by a quick bulk send do not emit per-message live conversation updates."
      tags:
        - "Messages"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/SendQuickBulkSmsRequest"
      responses:
        "200":
          description: "Bulk send results"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/QuickBulkSmsResponse"
        "202":
          description: "More than 25 contacts: queued as a bulk SMS operation"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/QuickBulkSmsQueuedResponse"
        "400":
          description: "Validation error, including more than 50,000 contactIds"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "403":
          description: "The chosen line is not granted to the caller (`PHONE_NUMBER_NOT_GRANTED`)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "No contacts found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/messages/sms-limits":
    get:
      operationId: "get_messages_sms_limits"
      summary: "Get what the SMS segment limit reserves for a document link"
      description: "A document attachment such as a PDF is sent as a hosted link appended to the SMS body, so it counts toward the 3-segment limit. `documentLinkLength` is the length of one such link on this deployment. Each document adds one link on its own line, after a blank line that follows the text."
      tags:
        - "Messages"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "SMS limits returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsLimitsResponse"
  "/api/messages/webchat/{webchatId}":
    get:
      operationId: "get_messages_webchat"
      summary: "Get all messages for a webchat session (no auth)"
      description: "Public endpoint used by the webchat widget to bootstrap the conversation history for a session. Returns sender metadata only when `showSenderNameInWebchat` is enabled on the webchat config."
      tags:
        - "Messages"
      parameters:
        -
          in: "path"
          name: "webchatId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Webchat messages returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatMessagesResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/notification-sounds":
    get:
      operationId: "get_notification_sounds"
      summary: "Get all notification sounds for organization"
      description: "Return the catalog of available notification sounds for the caller's organization. Backed by a yet-to-land `NotificationConfig` model, so for now this returns an empty array (placeholder endpoint)."
      tags:
        - "Notification Sounds"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Notification sounds returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NotificationSoundsListResponse"
        "500":
          description: "Failed to fetch notification sounds"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NotificationSoundsErrorResponse"
  "/api/notification-sounds/preferences":
    get:
      operationId: "get_notification_preferences"
      summary: "Get user notification sound preferences"
      description: "Return the authenticated user's notification-sound preferences (`enabled`, `volume`). Defaults are `enabled=true` and `volume=1.0` when no preference has been persisted."
      tags:
        - "Notification Sounds"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Notification preferences returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NotificationPreferencesResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NotificationSoundsErrorResponse"
        "500":
          description: "Failed to fetch notification preferences"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NotificationSoundsErrorResponse"
    post:
      operationId: "update_notification_preferences"
      summary: "Update user notification sound preferences"
      description: "Update the authenticated user's notification-sound preferences. At least one of `enabled` or `volume` must be present; `volume` must be in [0, 1]."
      tags:
        - "Notification Sounds"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateNotificationPreferencesRequest"
      responses:
        "200":
          description: "Notification preferences updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NotificationPreferencesResponse"
        "400":
          description: "At least one preference must be provided or invalid volume"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NotificationSoundsErrorResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NotificationSoundsErrorResponse"
        "500":
          description: "Failed to update notification preferences"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NotificationSoundsErrorResponse"
  "/api/notifications":
    get:
      operationId: "get_notifications"
      summary: "Get notifications for the logged-in user"
      description: "Return the authenticated user's in-app notifications, transformed for the bell-tray UI. Status (`read`/`unread`) is overlaid from the per-user `User.notifications[].status` map."
      tags:
        - "Notification"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Notifications list (raw array, not enveloped)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NotificationListResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NotificationErrorResponse"
    post:
      operationId: "post_notifications"
      summary: "Mark all notifications as read and delete them"
      description: "\"Clear all\" - marks every notification for the authenticated user as read and removes them from the in-app tray. Idempotent; returns 200 even when there is nothing to clear."
      tags:
        - "Notification"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "All notifications deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NotificationDeleteAllResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NotificationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NotificationErrorResponse"
  "/api/notifications/{notificationId}":
    delete:
      operationId: "delete_notifications_notificationId"
      summary: "Mark a single notification as read and delete it"
      description: "Dismiss a single notification by id. Returns 404 if the notification does not belong to the calling user."
      tags:
        - "Notification"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "notificationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Notification deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NotificationDeleteOneResponse"
        "400":
          description: "Notification ID is required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NotificationErrorResponse"
        "404":
          description: "Notification not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NotificationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NotificationErrorResponse"
  "/api/notifications/mentions":
    post:
      operationId: "post_notifications_mentions"
      summary: "Send mention notifications to mentioned users"
      description: "Fan-out helper called by note/comment surfaces when one or more `@user` mentions are detected. Creates a notification per mentioned user (excluding the author) and returns the recipient list."
      tags:
        - "Notification"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/NotificationSendMentionsRequest"
      responses:
        "200":
          description: "Mention notifications sent"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NotificationMentionsSentResponse"
        "400":
          description: "contactId and mentions array are required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NotificationErrorResponse"
        "500":
          description: "Failed to send mention notifications"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/NotificationErrorResponse"
  "/api/org-snapshots":
    get:
      operationId: "get_org_snapshots"
      summary: "List organization snapshots"
      description: "Returns the list of organization-level snapshots. Superadmin only."
      tags:
        - "Org Snapshots"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Snapshots returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotListResponse"
        "400":
          description: "Invalid request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
        "403":
          description: "Forbidden - superadmin role required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
        "500":
          description: "Failed to retrieve snapshots"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
    post:
      operationId: "post_org_snapshot"
      summary: "Create an organization snapshot"
      description: "Captures an organization-level snapshot (pipelines, automations, prompts, templates) of a source user inside a source organization. Superadmin only."
      tags:
        - "Org Snapshots"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CreateOrgSnapshotRequest"
      responses:
        "201":
          description: "Snapshot created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotCreateResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
        "403":
          description: "Forbidden - superadmin role required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
        "404":
          description: "Source organization or user not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
        "409":
          description: "Snapshot name already exists"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
        "500":
          description: "Failed to create snapshot"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
  "/api/org-snapshots/{id}":
    get:
      operationId: "get_org_snapshot_by_id"
      summary: "Get an organization snapshot"
      description: "Returns the full snapshot detail (pipelines, automations, prompts, templates, counts) for the given snapshot id. Superadmin only."
      tags:
        - "Org Snapshots"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Snapshot returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotDetailResponse"
        "400":
          description: "Invalid snapshot id"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
        "403":
          description: "Forbidden - superadmin role required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
        "404":
          description: "Snapshot not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
        "500":
          description: "Failed to retrieve snapshot"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
    delete:
      operationId: "delete_org_snapshot"
      summary: "Delete an organization snapshot"
      description: "Permanently removes the organization snapshot. Superadmin only."
      tags:
        - "Org Snapshots"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Snapshot deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotMessageResponse"
        "400":
          description: "Invalid snapshot id"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
        "403":
          description: "Forbidden - superadmin role required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
        "404":
          description: "Snapshot not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
        "500":
          description: "Failed to delete snapshot"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
  "/api/org-snapshots/{id}/apply":
    post:
      operationId: "post_org_snapshot_apply"
      summary: "Apply an organization snapshot"
      description: "Creates a new organization (with credentials, dynamic properties, and pipelines) by cloning the snapshot inside a single transaction. Optionally seeds a first admin user with cloned automations, prompts, and templates. Superadmin only."
      tags:
        - "Org Snapshots"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ApplyOrgSnapshotRequest"
      responses:
        "201":
          description: "Snapshot applied - new organization created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplyOrgSnapshotResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
        "403":
          description: "Forbidden - superadmin role required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
        "404":
          description: "Snapshot not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
        "409":
          description: "Conflict - organization name, phone, or user email already exists"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
        "422":
          description: "Mongoose validation failure"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
        "500":
          description: "Failed to apply snapshot - all changes rolled back"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
  "/api/org-snapshots/orgs/{organizationId}/users":
    get:
      operationId: "get_org_snapshot_org_users"
      summary: "List users for a source organization"
      description: "Helper endpoint used by the snapshot creation UI. Returns users that belong to the given source organization. Superadmin only."
      tags:
        - "Org Snapshots"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Users returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotOrgUsersResponse"
        "400":
          description: "Organization id is required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
        "403":
          description: "Forbidden - superadmin role required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
        "500":
          description: "Failed to retrieve users"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSnapshotErrorResponse"
  "/api/organizations":
    get:
      operationId: "get_organizations"
      summary: "List all organizations"
      description: "Returns all organizations (sorted by name) with a thin projection (name, phoneNumber, address, logoUrl, loginDisabled, contactProtectionPeriod). Logo URLs are re-signed on the fly."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Organizations returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationListResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
    post:
      operationId: "post_organizations"
      summary: "Create a new organization"
      description: "Creates an organization plus its first ADMIN user, seeded credentials document, default document/process types, and a default DynamicProperties (Contact) layout. Rejects duplicates by name or phone number and validates credentials are not already in use."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CreateOrganizationRequest"
      responses:
        "201":
          description: "Organization created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/CreateOrganizationResponse"
        "400":
          description: "Validation or duplicate error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/{id}":
    get:
      operationId: "get_organizations_id"
      summary: "Get an organization by id (SuperAdmin only)"
      description: "Returns the full organization document for the given id, including populated credentials (Anthropic, Sinch, Twilio, etc.) and a resolved logoUrl. Only callable by SUPERADMIN."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Organization returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationByIdResponse"
        "403":
          description: "Unauthorized. Only superadmins can access this endpoint."
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
    delete:
      operationId: "delete_organizations_id"
      summary: "Delete an organization (superadmin only)"
      description: "Hard-deletes the Organization document by id. Restricted to SUPERADMIN. Note: associated users/credentials/dynamic-properties/etc. are not cascaded by this endpoint."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Organization deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationDeleteResponse"
        "400":
          description: "Missing organization ID"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationDeleteResponse"
        "403":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationDeleteResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationDeleteResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationDeleteResponse"
  "/api/organizations/{organizationId}/ai-cost-settings":
    get:
      operationId: "get_api_organizations_organizationId_ai_cost_settings"
      summary: "Get AI cost settings (SuperAdmin only)"
      description: "Returns the organization's USD per ElevenLabs credit for the AI consumption ledger (null means the default), the rate in effect, the default and the highest accepted rate, and the latest run that repriced the organization's voice rows. Requires SUPERADMIN."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "AI cost settings returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiCostSettingsResponse"
        "400":
          description: "Invalid organizationId"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
    put:
      operationId: "put_api_organizations_organizationId_ai_cost_settings"
      summary: "Set the USD per ElevenLabs credit (SuperAdmin only)"
      description: "Sets the organization's USD per ElevenLabs credit, or null to go back to the default. When the rate the voice rows use changes (or the last run at this rate failed or was lost), the organization's voice rows are repriced in the background; `repriceQueued` says whether that run was queued. Returns 503 when the rate was saved but the run could not be queued. Requires SUPERADMIN."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateAiCostSettingsRequest"
      responses:
        "200":
          description: "Rate saved"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AiCostSettingsUpdateResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "503":
          description: "Rate saved, but the reprice run could not be queued; save again to retry"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/{organizationId}/autopilot-monitor-settings":
    get:
      operationId: "get_organizations_organizationId_autopilot_monitor_settings"
      summary: "Get autopilot monitor settings"
      description: "Returns the autopilot monitor threshold (in minutes) used to flag conversations the AI has held idle for too long. Admin can read own org; SuperAdmin can read any org."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Autopilot monitor settings returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AutopilotMonitorSettingsResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
    put:
      operationId: "put_organizations_organizationId_autopilot_monitor_settings"
      summary: "Update autopilot monitor settings"
      description: "Updates the autopilot monitor threshold (in minutes; positive integer >= 1) used by the autopilot watchdog. Admin can update own org; SuperAdmin can update any org."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateAutopilotMonitorSettingsRequest"
      responses:
        "200":
          description: "Autopilot monitor settings updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AutopilotMonitorSettingsUpdateResponse"
        "400":
          description: "thresholdMinutes must be a positive integer (>= 1)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/{organizationId}/blocked-ips":
    get:
      operationId: "get_organizations_organizationId_blocked_ips"
      summary: "Get blocked IPs for an organization"
      description: "Returns the list of IPs blocked for webchat sessions on this organization plus the customer-facing ipBlockedMessage shown when a blocked IP attempts to connect. Admin can read own org; SuperAdmin can read any org."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Blocked IPs returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/BlockedIPsResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
    post:
      operationId: "post_organizations_organizationId_blocked_ips"
      summary: "Add an IP to the blocklist"
      description: "Validates and adds an IPv4/IPv6 address to the org blocklist (de-duplicated via $addToSet). Invalidates the Redis blocklist cache and force-disconnects any active webchat sockets currently connected from that IP."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AddBlockedIPRequest"
      responses:
        "200":
          description: "IP blocked"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/BlockedIPMutationResponse"
        "400":
          description: "Invalid IP address"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/{organizationId}/blocked-ips/{ip}":
    delete:
      operationId: "delete_organizations_organizationId_blocked_ips_ip"
      summary: "Remove an IP from the blocklist"
      description: "Removes an IP from the org blocklist and invalidates the Redis blocklist cache so the IP can reconnect on its next webchat session."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "ip"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "IP unblocked"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/BlockedIPMutationResponse"
        "400":
          description: "Missing IP address"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/{organizationId}/business-hours":
    get:
      operationId: "get_organizations_organizationId_business_hours"
      summary: "Get organization business hours configuration"
      description: "Returns the organization-wide business-hours schedule: timezone, weekly schedule, holidays, exceptional hours, and whether users may override at the user level. Admin/SuperAdmin can read; non-superadmins can only read their own org."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Business hours returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgBusinessHoursResponse"
        "403":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
    put:
      operationId: "put_organizations_organizationId_business_hours"
      summary: "Update organization business hours configuration"
      description: "Partially updates business-hours settings: timezone, weekly schedule (or null to clear), holidays, exceptional hours, and the allowUserBusinessHoursOverride toggle. Validates IANA timezones, HH:mm times, and YYYY-MM-DD dates. Admin can update own org; SuperAdmin can update any org."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateOrgBusinessHoursRequest"
      responses:
        "200":
          description: "Business hours updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgBusinessHoursResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/{organizationId}/call-dispositions":
    get:
      operationId: "get_api_organizations_organizationId_call_dispositions"
      summary: "GET /api/organizations/{organizationId}/call-dispositions"
      tags:
        - "Organizations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
    put:
      operationId: "put_api_organizations_organizationId_call_dispositions"
      summary: "PUT /api/organizations/{organizationId}/call-dispositions"
      tags:
        - "Organizations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/organizations/{organizationId}/contact-protection-settings":
    get:
      operationId: "get_organizations_organizationId_contact_protection_settings"
      summary: "Get contact protection period settings"
      description: "Returns the contact protection period in hours (how long a newly-assigned contact stays protected from reassignment). Admin can read own org; SuperAdmin can read any org."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Contact protection settings returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactProtectionSettingsResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
    put:
      operationId: "put_organizations_organizationId_contact_protection_settings"
      summary: "Update contact protection period settings"
      description: "Updates the contact protection period (non-negative integer hours, capped at 720 = 30 days). Admin can update own org; SuperAdmin can update any org."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateContactProtectionSettingsRequest"
      responses:
        "200":
          description: "Contact protection settings updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactProtectionSettingsUpdateResponse"
        "400":
          description: "contactProtectionPeriod must be a non-negative integer between 0 and 720 hours"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/{organizationId}/document-types":
    get:
      operationId: "get_organizations_organizationId_document_types"
      summary: "Get organization document types"
      description: "Returns the list of document types configured for the organization (used to classify contact-attached documents). Returns an empty array if none configured."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Document types returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgDocumentTypesResponse"
        "400":
          description: "Organization ID is required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Failed to fetch document types"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
    put:
      operationId: "put_organizations_organizationId_document_types"
      summary: "Update organization document types"
      description: "Replaces the list of document types for the organization. Each entry requires a non-empty name; names must be unique (case-insensitive). Admin can update own org; SuperAdmin can update any org."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateOrgDocumentTypesRequest"
      responses:
        "200":
          description: "Document types updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgDocumentTypesUpdateResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Failed to update document types"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/{organizationId}/email-accounts":
    get:
      operationId: "get_organizations_organizationId_email_accounts"
      summary: "List the organization mailboxes (admin)"
      description: "Every EmailAccount in the SELECTED organization, newest first, OAuth tokens excluded, with the linked user's or group's identity flattened in (`linkedUserName`, `linkedUserEmail`, `linkedGroupName`). Each row carries its access `grants`; the field is omitted for a mailbox that predates grants. Admin or SuperAdmin; an Admin may only list their own organization."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
          description: "The organization that owns the mailboxes."
      responses:
        "200":
          description: "Mailboxes returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgEmailAccountListResponse"
        "400":
          description: "Invalid organizationId"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
        "403":
          description: "Forbidden (not an admin, or another organization)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
        "500":
          description: "Failed to list organization email accounts"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
  "/api/organizations/{organizationId}/escalation-settings":
    get:
      operationId: "get_organizations_organizationId_escalation_settings"
      summary: "Get escalation settings"
      description: "Returns the organization escalation configuration (currently maxUnresolvedChatsPerAgent; defaults to 3). Admin can read own org; SuperAdmin can read any org."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Escalation settings returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationSettingsResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
    put:
      operationId: "put_organizations_organizationId_escalation_settings"
      summary: "Update escalation settings"
      description: "Updates maxUnresolvedChatsPerAgent (non-negative integer; 0 means no limit). Admin can update own org; SuperAdmin can update any org."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateEscalationSettingsRequest"
      responses:
        "200":
          description: "Escalation settings updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EscalationSettingsUpdateResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/{organizationId}/extraction-rules":
    get:
      operationId: "get_organizations_organizationId_extraction_rules"
      summary: "Get extraction rules"
      description: "Returns the per-organization extraction rules for built-in contact fields and for custom fields defined under DynamicProperties for the given section type (defaults to \"Contact\"). Each rule contains mode (allowlist/blacklist), values, regex patterns, and an optional prompt."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
        -
          in: "query"
          name: "type"
          required: false
          schema:
            type: "string"
            default: "Contact"
      responses:
        "200":
          description: "Extraction rules returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ExtractionRulesResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
    put:
      operationId: "put_organizations_organizationId_extraction_rules"
      summary: "Update extraction rules"
      description: "Replaces built-in field extraction rules (Contact-only) and updates extraction rules on existing custom-field properties within DynamicProperties for the given section type. Validates regex patterns and rejects unknown custom field keys."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
        -
          in: "query"
          name: "type"
          required: false
          schema:
            type: "string"
            default: "Contact"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateExtractionRulesRequest"
      responses:
        "200":
          description: "Extraction rules updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ExtractionRulesUpdateResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/{organizationId}/ip-blocked-message":
    patch:
      operationId: "patch_organizations_organizationId_ip_blocked_message"
      summary: "Update the IP blocked message"
      description: "Updates the customer-facing message shown to webchat visitors whose IP is on the org blocklist. Empty strings revert to the default (\"Due to previous violations your IP has been blocked\")."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateIPBlockedMessageRequest"
      responses:
        "200":
          description: "IP blocked message updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/IPBlockedMessageResponse"
        "400":
          description: "Invalid message"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/{organizationId}/missed-call-message":
    get:
      operationId: "get_organizations_organizationId_missed_call_message"
      summary: "Get missed call auto-message configuration"
      description: "Returns the missed-call auto-reply message template and the flag indicating whether the auto-reply is enabled. Restricted to ADMIN (own org) or SUPERADMIN."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Missed call configuration returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MissedCallMessageResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Failed to get configuration"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
    put:
      operationId: "put_organizations_organizationId_missed_call_message"
      summary: "Update missed call auto-message configuration"
      description: "Partially updates the missed-call message template (string up to 500 chars) and/or the missedCallAutoMessageEnabled flag. Restricted to ADMIN (own org) or SUPERADMIN."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateMissedCallMessageRequest"
      responses:
        "200":
          description: "Missed call configuration updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MissedCallMessageResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Failed to update configuration"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/{organizationId}/missed-call-message/placeholders":
    get:
      operationId: "get_organizations_organizationId_missed_call_message_placeholders"
      summary: "List supported placeholders for missed-call messages"
      description: "Returns the list of supported placeholder tokens (e.g. {{contactName}}) that can be embedded in the missed-call auto-message template. Restricted to ADMIN (own org) or SUPERADMIN."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Placeholders returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MissedCallPlaceholdersResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Failed to get placeholders"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/{organizationId}/org-settings":
    get:
      operationId: "get_api_organizations_organizationId_org_settings"
      summary: "GET /api/organizations/{organizationId}/org-settings"
      tags:
        - "Organizations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
    put:
      operationId: "put_api_organizations_organizationId_org_settings"
      summary: "PUT /api/organizations/{organizationId}/org-settings"
      tags:
        - "Organizations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/organizations/{organizationId}/outreach-close-stages":
    get:
      operationId: "get_organizations_organizationId_outreach_close_stages"
      summary: "Get outreach close stages"
      description: "Returns the list of pipeline stage names that count as \"closed\" for outreach metrics. Readable by org members; SuperAdmin can read any org."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Close stages returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachCloseStagesResponse"
        "403":
          description: "Access denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationStatusErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationStatusErrorResponse"
        "500":
          description: "Error fetching close stages"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationStatusErrorResponse"
    put:
      operationId: "put_organizations_organizationId_outreach_close_stages"
      summary: "Update outreach close stages"
      description: "Replaces the list of pipeline stage names that count as \"closed\" for outreach metrics. Admin-only (own org for Admin; any org for SuperAdmin). Body must contain a stages array of strings."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateOutreachCloseStagesRequest"
      responses:
        "200":
          description: "Close stages updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachCloseStagesResponse"
        "400":
          description: "\"stages\" must be an array of strings"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationStatusErrorResponse"
        "403":
          description: "Admin access required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationStatusErrorResponse"
        "500":
          description: "Error updating close stages"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationStatusErrorResponse"
  "/api/organizations/{organizationId}/outreach-gross-profit-config":
    get:
      operationId: "get_organizations_organizationId_outreach_gross_profit_config"
      summary: "Get outreach gross profit config"
      description: "Returns the entity type + property key used to calculate gross profit in outreach ROI metrics, or null if not configured. Readable by org members; SuperAdmin can read any org."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Gross profit config returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachGrossProfitConfigResponse"
        "403":
          description: "Access denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationStatusErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationStatusErrorResponse"
        "500":
          description: "Error fetching gross profit config"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationStatusErrorResponse"
    put:
      operationId: "put_organizations_organizationId_outreach_gross_profit_config"
      summary: "Update outreach gross profit config"
      description: "Sets (or clears) the Contact property used to calculate gross profit for outreach ROI. Body { entityType: \"Contact\", propertyKey: string }; sending null or an empty object clears the config. Admin-only (own org for Admin; any org for SuperAdmin)."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateOutreachGrossProfitConfigRequest"
      responses:
        "200":
          description: "Gross profit config updated or cleared"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachGrossProfitConfigResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationStatusErrorResponse"
        "403":
          description: "Admin access required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationStatusErrorResponse"
        "500":
          description: "Error updating gross profit config"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationStatusErrorResponse"
  "/api/organizations/{organizationId}/phone-numbers":
    get:
      operationId: "get_organizations_organizationId_phone_numbers"
      summary: "List the organization phone numbers"
      description: "Every PhoneNumber resource in the organization, newest first, joined with the linked user's or group's identity, plus a coverage summary (how many users have a directly linked number, which providers have a usable org default line, how many unlinked numbers auto-assignment could hand out). Each row carries its access `grants`; the field is omitted for a number that predates grants. Admin or SuperAdmin; an Admin may only list their own organization."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
          description: "The organization that owns the phone numbers."
      responses:
        "200":
          description: "Phone numbers returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgPhoneNumberListResponse"
        "400":
          description: "Invalid organizationId"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
        "403":
          description: "Forbidden (not an admin, or another organization)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
        "500":
          description: "Failed to list organization phone numbers"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
    post:
      operationId: "post_organizations_organizationId_phone_numbers"
      summary: "Add a phone number to the organization"
      description: "Create a PhoneNumber resource. It may be linked to at most one user or one group of the organization (unlinked numbers are spares; the org default must be unlinked). `grants` is optional; every principal must belong to the organization and each grant is stamped with the calling admin. A number created here always stores a grant list (`[]` when none is sent). Setting `isOrgDefault` demotes the current default for the same provider in the same transaction. Admin or SuperAdmin."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
          description: "The organization that owns the phone numbers."
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CreateOrgPhoneNumberRequest"
      responses:
        "201":
          description: "Phone number created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgPhoneNumberMutationResult"
        "400":
          description: "Validation error: malformed body, both link targets, a grant principal not in the organization (the message names it), a duplicate grant, a grant with no verbs, a send grant on the org default, a short code that starts with `+` or is not 5 or 6 digits, a short code as the org default, or a short code with voice capability, AI routing, a forward number, an ElevenLabs id or an AI agent"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
        "403":
          description: "Forbidden (not an admin, or another organization)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
        "404":
          description: "Linked user or group not found in the organization"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
        "409":
          description: "The phone number is already provisioned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
        "500":
          description: "Failed to create phone number"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
  "/api/organizations/{organizationId}/plan":
    put:
      operationId: "put_organizations_organizationId_plan"
      summary: "Update organization SMS plan (SuperAdmin only)"
      description: "Updates the SMS plan tier for the organization. Allowed plan values: skip, essentials, fasttrack, partner, unlimited. SUPERADMIN only."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateOrganizationPlanRequest"
      responses:
        "200":
          description: "Plan updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UpdateOrganizationPlanResponse"
        "400":
          description: "Invalid plan"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Unauthorized. Only SUPERADMIN can update organization plans."
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/{organizationId}/self-serve-settings":
    get:
      operationId: "get_api_organizations_organizationId_self_serve_settings"
      summary: "GET /api/organizations/{organizationId}/self-serve-settings"
      tags:
        - "Organizations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
    put:
      operationId: "put_api_organizations_organizationId_self_serve_settings"
      summary: "PUT /api/organizations/{organizationId}/self-serve-settings"
      tags:
        - "Organizations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/organizations/{organizationId}/session-settings":
    get:
      operationId: "get_organizations_organizationId_session_settings"
      summary: "Get session settings (SuperAdmin only)"
      description: "Returns the org session-management overrides (idle/token timeouts, warning time, idle tracking flag, SSO and password silent-renewal flags, and fallback behaviors). Null/undefined values mean \"use the global default\". Requires SUPERADMIN."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Session settings returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SessionSettingsResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
    put:
      operationId: "put_organizations_organizationId_session_settings"
      summary: "Update session settings (SuperAdmin only)"
      description: "Partially updates session-management settings on the organization. Pass null on any individual field to revert it to the global default. Requires SUPERADMIN."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateSessionSettingsRequest"
      responses:
        "200":
          description: "Session settings updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SessionSettingsUpdateResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/{organizationId}/timezone":
    get:
      operationId: "get_organizations_organizationId_timezone"
      summary: "Get organization timezone"
      description: "Returns the IANA timezone string stored on the organization document (defaults to \"UTC\" if unset)."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Timezone returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgTimezoneResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
    put:
      operationId: "put_organizations_organizationId_timezone"
      summary: "Update organization timezone"
      description: "Updates the organization-level IANA timezone (e.g. \"America/New_York\"). Validated via Intl.DateTimeFormat. Accessible by ADMIN (own org) and SUPERADMIN (any org)."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateOrgTimezoneRequest"
      responses:
        "200":
          description: "Timezone updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgTimezoneResponse"
        "400":
          description: "Invalid timezone"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Unauthorized. Only ADMIN or SUPERADMIN can update organization timezone."
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/{organizationId}/tovi-access-settings":
    get:
      operationId: "get_api_organizations_organizationId_tovi_access_settings"
      summary: "GET /api/organizations/{organizationId}/tovi-access-settings"
      tags:
        - "Organizations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
    put:
      operationId: "put_api_organizations_organizationId_tovi_access_settings"
      summary: "PUT /api/organizations/{organizationId}/tovi-access-settings"
      tags:
        - "Organizations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/organizations/{organizationId}/user-groups":
    get:
      operationId: "get_api_organizations_organizationId_user_groups"
      summary: "GET /api/organizations/{organizationId}/user-groups"
      tags:
        - "Organizations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
    post:
      operationId: "post_api_organizations_organizationId_user_groups"
      summary: "POST /api/organizations/{organizationId}/user-groups"
      tags:
        - "Organizations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/organizations/{organizationId}/user-groups/{groupId}":
    get:
      operationId: "get_api_organizations_organizationId_user_groups_groupId"
      summary: "GET /api/organizations/{organizationId}/user-groups/{groupId}"
      tags:
        - "Organizations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "groupId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
    put:
      operationId: "put_api_organizations_organizationId_user_groups_groupId"
      summary: "PUT /api/organizations/{organizationId}/user-groups/{groupId}"
      tags:
        - "Organizations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "groupId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
    delete:
      operationId: "delete_api_organizations_organizationId_user_groups_groupId"
      summary: "DELETE /api/organizations/{organizationId}/user-groups/{groupId}"
      tags:
        - "Organizations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "groupId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/organizations/{organizationId}/users":
    get:
      operationId: "get_api_organizations_organizationId_users"
      summary: "GET /api/organizations/{organizationId}/users"
      tags:
        - "Organizations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/organizations/{organizationId}/voice-concurrency-settings":
    get:
      operationId: "get_api_organizations_organizationId_voice_concurrency_settings"
      summary: "GET /api/organizations/{organizationId}/voice-concurrency-settings"
      tags:
        - "Organizations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/organizations/{organizationId}/webchat-settings":
    get:
      operationId: "get_organizations_organizationId_webchat_settings"
      summary: "Get webchat settings"
      description: "Returns the org-level webchat settings: showSenderNameInWebchat (whether the human agent name is shown) and aiAssistantName (the display name used by the AI assistant). Admin can read own org; SuperAdmin can read any org."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Webchat settings returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatSettingsResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
    put:
      operationId: "put_organizations_organizationId_webchat_settings"
      summary: "Update webchat settings"
      description: "Partially updates showSenderNameInWebchat and/or aiAssistantName on the organization. Admin can update own org; SuperAdmin can update any org."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateWebchatSettingsRequest"
      responses:
        "200":
          description: "Webchat settings updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatSettingsUpdateResponse"
        "400":
          description: "No valid fields provided"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/api-keys":
    post:
      operationId: "post_organizations_api_keys"
      summary: "Get organization API keys"
      description: "Returns the OrganizationCredentials document (Anthropic / Sinch / Twilio / OpenAI / Google) for the organization, plus the resolved current AI/SMS provider. SuperAdmin can read any org by passing { id }; non-superadmins always get their own org."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/GetApiKeysRequest"
      responses:
        "200":
          description: "API keys returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiKeysResponse"
        "400":
          description: "Invalid token"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
    put:
      operationId: "put_organizations_api_keys"
      summary: "Update organization API keys and details"
      description: "Updates org-level details (name/phoneNumber/address/logoUrl) and replaces the OrganizationCredentials document. Validates the new credentials are not already in use by another org, uploads logo to R2 if provided as data URL, and backfills missing DynamicProperties section.properties fields."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateApiKeysRequest"
      responses:
        "200":
          description: "API keys updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationMessageResponse"
        "400":
          description: "Missing organization ID"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/dashboard":
    get:
      operationId: "get_organizations_dashboard"
      summary: "Get dashboard data (Admin and SuperAdmin only)"
      description: "Returns aggregate stats (total organizations / users / admins) plus a per-organization listing with members. SuperAdmin sees all orgs/users; Admin sees only their own org/users."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Dashboard data returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DashboardResponse"
        "403":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/document-types/user":
    get:
      operationId: "get_organizations_document_types_user"
      summary: "Get document types for the current user organization"
      description: "Returns the document types configured for the caller's own organization, resolved from the bearer token. Convenience endpoint for clients that do not have the organizationId on hand."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Document types returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgDocumentTypesResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Failed to fetch document types"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/multi-options-customer-profile/{contactId}":
    get:
      operationId: "get_organizations_multi_options_customer_profile_contactId"
      summary: "Get extracted field-change history options for a contact"
      description: "Returns merged field-change suggestions from TempExtractedData for the given contact (contact, application, and conversation field changes). If conversationId is supplied, conversation field changes are scoped to that conversation."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "contactId"
          required: true
          schema:
            type: "string"
        -
          in: "query"
          name: "conversationId"
          required: false
          schema:
            type: "string"
      responses:
        "200":
          description: "Field-change options returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SectionsOptionsResponse"
        "500":
          description: "Failed to fetch field history"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/section-types/{id}":
    get:
      operationId: "get_organizations_section_types_id"
      summary: "Get section/entity types for an organization"
      description: "Returns the built-in entity types (Contact, Application, Conversation), custom entity types defined via DynamicProperties, and an id↔type index so clients can render link-target labels. Access restricted to org members; SuperAdmin can read any org."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Section types returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSectionTypesResponse"
        "403":
          description: "Unauthorized: Access to different organization denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Failed to fetch section types"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/sections/{id}":
    get:
      operationId: "get_organizations_sections_id"
      summary: "Get DynamicProperties sections for an organization"
      description: "Returns the sections array (custom-property layout) stored in DynamicProperties for the given organization and section type (defaults to \"Contact\"). Org members may read their own org; SuperAdmin can read any org."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
        -
          in: "query"
          name: "type"
          required: false
          schema:
            type: "string"
            default: "Contact"
      responses:
        "200":
          description: "Sections returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSectionsResponse"
        "400":
          description: "Invalid section type"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Unauthorized: Access to different organization denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Failed to fetch organization sections"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
    put:
      operationId: "put_organizations_sections_id"
      summary: "Update DynamicProperties sections for an organization"
      description: "Replaces the sections layout for the given section type (defaults to \"Contact\"). Performs renames on existing owner documents, validates regex patterns / link-target graphs, and rejects modifications to protected schema fields. Removing a property or changing its dataType leaves instance data on owner documents untouched. Admin or SuperAdmin only."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
        -
          in: "query"
          name: "type"
          required: false
          schema:
            type: "string"
            default: "Contact"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateOrgSectionsRequest"
      responses:
        "200":
          description: "Sections updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UpdateOrgSectionsResponse"
        "400":
          description: "Validation error (regex, protected fields, link graph, etc.)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Failed to update organization section"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
    delete:
      operationId: "delete_organizations_sections_id"
      summary: "Delete a custom entity type for an organization"
      description: "Deletes the DynamicProperties config document for a custom entity type (passed via ?type=... or body.type). Built-in types (Contact/Conversation/Application) cannot be deleted, and types still referenced by link properties on sibling configs are rejected with 409."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
        -
          in: "query"
          name: "type"
          required: false
          schema:
            type: "string"
      responses:
        "200":
          description: "Entity type deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DeleteOrgSectionResponse"
        "400":
          description: "type is required / cannot delete built-in type"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Unauthorized: Access to different organization denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "No config found for type"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "409":
          description: "Entity type is linked from other configs"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DeleteOrgSectionConflictResponse"
        "500":
          description: "Failed to delete entity type"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/sections/{id}/property-usage":
    get:
      operationId: "get_organizations_sections_id_property_usage"
      summary: "Count owner records holding a value for one configured property"
      description: "Returns how many owner records currently hold a non-empty value for a single configured property, so the settings editor can warn before a data type change leaves stored values inconsistent with their new type. Built-in types are counted on their own collection; a custom type has no collection of its own, so the linkId graph is walked and every branch that attaches it is probed. Legacy display-name and oldName aliases are probed too, since a value written under one still resolves on read. Read-only. Org members may read their own org; SuperAdmin can read any org."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
        -
          in: "query"
          name: "type"
          required: false
          schema:
            type: "string"
            default: "Contact"
        -
          in: "query"
          name: "key"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Usage returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgPropertyUsageResponse"
        "400":
          description: "Invalid section type / key is required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Unauthorized: Access to different organization denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Failed to fetch property usage"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/transfer/{transferId}/status":
    get:
      operationId: "get_organizations_transfer_transferId_status"
      summary: "Get cross-organization user transfer status (SuperAdmin only)"
      description: "Returns the status snapshot of an asynchronous cross-org user transfer (audit-log doc): status (in_progress/completed/failed), timestamps, original action payload, and error string if any. SUPERADMIN only."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "transferId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Transfer status returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgTransferStatusResponse"
        "403":
          description: "Forbidden: Only Superadmin can transfer users between organizations"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Transfer not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/transfer/execute":
    post:
      operationId: "post_organizations_transfer_execute"
      summary: "Execute a cross-organization user transfer (SuperAdmin only)"
      description: "Kicks off an asynchronous transfer of a user (and their owned data: contacts, conversations, automations, workflows, webchat configs, acquired items, email/calendar/sheets integrations, voice numbers, etc.) into a target organization. Requires a fresh scanVersion from /transfer/scan and a reassigneeUserId that owns whatever cannot be moved. SUPERADMIN only."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/OrgTransferExecuteRequest"
      responses:
        "202":
          description: "Transfer accepted and started in the background"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgTransferExecuteResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Forbidden: Only Superadmin can transfer users between organizations"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/transfer/preview":
    post:
      operationId: "post_organizations_transfer_preview"
      summary: "Preview owned-resource counts for a cross-organization user transfer (SuperAdmin only)"
      description: "Returns aggregate counts of items currently owned by the user (contacts, conversations, assignee-only conversations, automations, workflows, webchat configurations, acquired items, integrations, voice numbers, prompts, automation keys, etc.) so the operator can review what would be moved. Does not mutate state."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/OrgTransferPreviewRequest"
      responses:
        "200":
          description: "Preview counts returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgTransferPreviewResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Forbidden: Only Superadmin can transfer users between organizations"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/transfer/scan":
    post:
      operationId: "post_organizations_transfer_scan"
      summary: "Scan a cross-organization user transfer for warnings and conflicts (SuperAdmin only)"
      description: "Performs the deeper scan that produces a scanVersion (required by /transfer/execute): warnings, owned-resource counts, agent usage breakdowns, reassignee agents, and role hints. Does not mutate state."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/OrgTransferScanRequest"
      responses:
        "200":
          description: "Scan result returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgTransferScanResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Forbidden: Only Superadmin can transfer users between organizations"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/user":
    get:
      operationId: "get_organizations_user"
      summary: "Get current user organization details"
      description: "Returns the basic organization details (name, phoneNumber, address, logoUrl) for the organization resolved from the caller bearer token. The logoUrl is re-signed on each call."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Organization details returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationDetailsResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
    put:
      operationId: "put_organizations_user"
      summary: "Update current user organization details"
      description: "Partially updates name, phoneNumber, address, and/or logoUrl on the caller's organization. When logoUrl is a base64 data URL or http(s) URL it is uploaded to R2 and stored as a signed-storage key; passing \"\" or null clears the logo."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateOrganizationDetailsRequest"
      responses:
        "200":
          description: "Organization details updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationMessageResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/outreach":
    post:
      operationId: "post_outreach"
      summary: "Trigger outreach processing for a lead"
      tags:
        - "Outreach"
      security:
        -
          bearerAuth:
            []
      description: "Public endpoint authenticated via API key in Authorization header. Accepts lead data and processes it through the configured lead management pipeline."
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/OutreachTriggerRequest"
      responses:
        "200":
          description: "Outreach processed successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachTriggerResponse"
        "400":
          description: "Validation error (missing configurationId, no contact data, inactive config, etc.)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachErrorResponse"
        "401":
          description: "No API key provided or invalid"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachErrorResponse"
        "404":
          description: "Configuration or contact not found for this API key"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachErrorResponse"
        "500":
          description: "Failed to process outreach"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachErrorResponse"
  "/api/outreach-metrics":
    get:
      operationId: "get_outreach_metrics"
      summary: "Get live outreach metrics per source"
      description: "Returns live per-source metrics (leads, cost, costPerLead, contactPercentage, closePercentage, stageDistribution, grossProfit, roi) aggregated over the authenticated user's active outreach configs. Admins can scope to another user via filterUserId, or pass filterUserId=all for an organization-wide view. Date range can be supplied as preset (today/week/month/allTime) or explicit from/to ISO timestamps. Responses are cached for 10 minutes per filter combination."
      tags:
        - "Outreach Metrics"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "filterUserId"
          required: false
          schema:
            type: "string"
          description: "Admin-only. Target a specific user's configs, or 'all' for the whole organization."
        -
          in: "query"
          name: "preset"
          required: false
          schema:
            type: "string"
            enum:
              - "today"
              - "week"
              - "month"
              - "allTime"
          description: "Named date range. Mutually exclusive with from/to."
        -
          in: "query"
          name: "from"
          required: false
          schema:
            type: "string"
            format: "date-time"
          description: "Inclusive lower bound on contact createdAt (ISO timestamp)."
        -
          in: "query"
          name: "to"
          required: false
          schema:
            type: "string"
            format: "date-time"
          description: "Inclusive upper bound on contact createdAt (ISO timestamp)."
      responses:
        "200":
          description: "Metrics returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachMetricsResponse"
        "400":
          description: "Invalid date range or preset"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachErrorResponse"
        "403":
          description: "Admin access required to filter by user"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachErrorResponse"
        "500":
          description: "Error calculating outreach metrics"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachErrorResponse"
  "/api/outreach-metrics/clear-cache":
    post:
      operationId: "post_outreach_metrics_clear_cache"
      summary: "Clear cached outreach metrics for the current user"
      description: "Invalidates every cached outreach-metrics variant whose key starts with the authenticated user's userId, forcing the next /api/outreach-metrics call to recompute."
      tags:
        - "Outreach Metrics"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Cache cleared"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachMessageResponse"
        "500":
          description: "Error clearing cache"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachErrorResponse"
  "/api/outreach-metrics/history":
    get:
      operationId: "get_outreach_metrics_history"
      summary: "Get historical stage distribution for outreach contacts"
      description: "Returns counts of pipeline-stage transitions for outreach contacts grouped by period (day/week/month), stage, and lead source. Backed by ContactPipelineTransition records and scoped to the org's outreach configs."
      tags:
        - "Outreach Metrics"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "from"
          required: true
          schema:
            type: "string"
            format: "date-time"
          description: "Inclusive lower bound on transition createdAt."
        -
          in: "query"
          name: "to"
          required: true
          schema:
            type: "string"
            format: "date-time"
          description: "Inclusive upper bound on transition createdAt."
        -
          in: "query"
          name: "groupBy"
          required: false
          schema:
            type: "string"
            enum:
              - "day"
              - "week"
              - "month"
            default: "day"
        -
          in: "query"
          name: "source"
          required: false
          schema:
            type: "string"
          description: "Optional source name filter (case-insensitive exact match)."
        -
          in: "query"
          name: "filterUserId"
          required: false
          schema:
            type: "string"
          description: "Admin-only. Target a specific user, or 'all' for the whole organization."
      responses:
        "200":
          description: "History returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachMetricsHistoryResponse"
        "400":
          description: "'from' and 'to' query params are required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachErrorResponse"
        "403":
          description: "Admin access required to filter by user"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachErrorResponse"
        "500":
          description: "Error fetching outreach metrics history"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachErrorResponse"
  "/api/outreach-sources":
    get:
      operationId: "get_outreach_sources"
      summary: "List outreach sources for the organization"
      description: "Returns active outreach sources for the org, sorted by name. The protected \"Any\" source is always returned as the first entry even when it is not persisted in the database."
      tags:
        - "Outreach Sources"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Sources returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachSourceListResponse"
        "500":
          description: "Error fetching outreach sources"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachErrorResponse"
    post:
      operationId: "post_outreach_sources"
      summary: "Create a new outreach source"
      description: "Admin-only. Creates a new outreach source for the org. The reserved name \"Any\" is rejected, and duplicates are matched case-insensitively."
      tags:
        - "Outreach Sources"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CreateOutreachSourceRequest"
      responses:
        "201":
          description: "Source created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachSourceMutationResponse"
        "400":
          description: "Validation error or duplicate name"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachErrorResponse"
        "403":
          description: "Admin access required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachErrorResponse"
        "500":
          description: "Error creating outreach source"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachErrorResponse"
  "/api/outreach-sources/{id}":
    delete:
      operationId: "delete_outreach_sources_by_id"
      summary: "Delete an outreach source"
      description: "Admin-only. Deletes the outreach source identified by id. The protected \"Any\" source cannot be deleted."
      tags:
        - "Outreach Sources"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Source deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachMessageResponse"
        "400":
          description: "\"Any\" is protected and cannot be deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachErrorResponse"
        "403":
          description: "Admin access required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachErrorResponse"
        "404":
          description: "Source not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachErrorResponse"
        "500":
          description: "Error deleting outreach source"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachErrorResponse"
  "/api/phone-numbers":
    get:
      operationId: "get_api_phone_numbers"
      summary: "List the phone numbers the caller may send from (or read)"
      description: "Every org phone number the caller may use for `verb` (default `send`). For `send`: linked to them, linked to a user group they belong to, or shared with them through a send grant (to them, their department or one of their groups). For `read`: shared with them through a read grant only - a link gives send, never read. Each row says how in `via` and lists every verb the caller holds on it in `verbs`. The default list is the send-from picker set and never contains a line the caller may only read. `?verb=read` returns the lines whose conversations the caller can see (for filtering realtime line events); it can include read-only lines, which are not send-from options. Admins get no widening here: these are the lines that are theirs, not every line in the org. The org default line is never a send row; `orgDefaultAvailable` says whether one covers the requested channel. It appears in the read set only through an explicit read grant. With `?channel=sms|voice` only numbers usable to start a conversation on that channel are returned (the active provider for the channel, the capability, active status). Any authenticated user."
      tags:
        - "Phone Numbers"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "verb"
          required: false
          schema:
            type: "string"
            enum:
              - "send"
              - "read"
            default: "send"
          description: "`send` (default): lines the caller may send from. `read`: lines whose conversations the caller can see through a read grant."
        -
          in: "query"
          name: "channel"
          required: false
          schema:
            type: "string"
            enum:
              - "sms"
              - "voice"
          description: "Only numbers usable to start a conversation on this channel: the organization's active provider for it, the capability, and active status. Omit for every number."
      responses:
        "200":
          description: "Send-from numbers"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SelfSendFromListResponse"
        "400":
          description: "verb must be send or read"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
        "401":
          description: "Authentication required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
        "500":
          description: "Failed to list phone numbers"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
    post:
      operationId: "post_api_phone_numbers"
      summary: "POST /api/phone-numbers"
      tags:
        - "Phone Numbers"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/phone-numbers/{phoneNumberId}":
    delete:
      operationId: "delete_api_phone_numbers_phoneNumberId"
      summary: "DELETE /api/phone-numbers/{phoneNumberId}"
      tags:
        - "Phone Numbers"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "phoneNumberId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/phone-numbers/for-users":
    get:
      operationId: "get_api_phone_numbers_for_users"
      summary: "List the phone numbers specific teammates may send from"
      description: "Every org phone number any of the listed users may send from (link, group link or `send` grant), one row per number. `userIds` on a row names the listed users who may send from it and `via` is the best way any of them reaches it; `linkedUserId` stays the number's inbound owner. Scoped to the caller's organization, at most 200 users per request. The org default line is never a row; `orgDefaultAvailable` reports it. Same `channel` narrowing as `GET /api/phone-numbers`. Any authenticated user (the campaign builder lists assignees' lines)."
      tags:
        - "Phone Numbers"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "userIds"
          required: true
          schema:
            type: "string"
          description: "Comma-separated user ids. Invalid ids are ignored."
        -
          in: "query"
          name: "channel"
          required: false
          schema:
            type: "string"
            enum:
              - "sms"
              - "voice"
          description: "Only numbers usable to start a conversation on this channel: the organization's active provider for it, the capability, and active status. Omit for every number."
      responses:
        "200":
          description: "Send-from numbers for the listed users"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ForUsersSendFromListResponse"
        "401":
          description: "Authentication required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
        "500":
          description: "Failed to list phone numbers"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
  "/api/phone-numbers/org":
    get:
      operationId: "get_api_phone_numbers_org"
      summary: "List the organization numbers an org-line picker may offer"
      description: "Admins (Admin, SuperAdmin) get every phone number in the organization. Anyone else gets only the numbers they may send from: linked to them or to a group they belong to, shared with them by a `send` grant, or the org default line (anyone may send from it). Rows carry the linked user's name or group name and `via`; `via` is null on a row an admin sees only because they are an admin. Same `channel` narrowing as `GET /api/phone-numbers`."
      tags:
        - "Phone Numbers"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "channel"
          required: false
          schema:
            type: "string"
            enum:
              - "sms"
              - "voice"
          description: "Only numbers usable to start a conversation on this channel: the organization's active provider for it, the capability, and active status. Omit for every number."
      responses:
        "200":
          description: "Organization send-from numbers"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgSendFromListResponse"
        "401":
          description: "Authentication required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
        "500":
          description: "Failed to list phone numbers"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
  "/api/pipelines":
    get:
      operationId: "get_pipelines"
      summary: "Get organization pipeline"
      description: "Return a single pipeline for the org - defaults to the default pipeline of the given `type`, or the pipeline identified by `pipelineId`. The response includes stages and `pipelineStageIds` for the canvas renderer."
      tags:
        - "Pipelines"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "type"
          required: false
          schema:
            type: "string"
            enum:
              - "Contact"
              - "Application"
            default: "Contact"
        -
          in: "query"
          name: "pipelineId"
          required: false
          schema:
            type: "string"
      responses:
        "200":
          description: "Pipeline returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "404":
          description: "Pipeline not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
    post:
      operationId: "post_pipelines"
      summary: "Update or create organization pipeline"
      description: "Upsert the org's default pipeline for the given `type`. When the legacy `stages` mapping is provided, the controller also migrates existing records from `oldStage` to `newStage` and returns the per-stage migration counts on the response."
      tags:
        - "Pipelines"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "type"
          required: false
          schema:
            type: "string"
            enum:
              - "Contact"
              - "Application"
            default: "Contact"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdatePipelineRequest"
      responses:
        "200":
          description: "Pipeline updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineMutationResponse"
        "201":
          description: "Pipeline created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineMutationResponse"
        "207":
          description: "Pipeline updated with partial migration failure"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineMigrationErrorResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "404":
          description: "Pipeline not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
  "/api/pipelines/{pipelineId}":
    delete:
      operationId: "delete_pipeline"
      summary: "Delete a pipeline"
      description: "Hard-deletes the pipeline and its stages. If the pipeline still has assigned records, provide a targetPipelineId in the body so the records are migrated to the first active stage of that pipeline before deletion. The default pipeline cannot be deleted."
      tags:
        - "Pipelines"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "pipelineId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/DeletePipelineRequest"
      responses:
        "200":
          description: "Pipeline deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/DeletePipelineResponse"
        "400":
          description: "Validation error or undeletable pipeline"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "404":
          description: "Pipeline not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
  "/api/pipelines/{pipelineId}/usage":
    get:
      operationId: "get_pipeline_usage"
      summary: "Check pipeline usage and deletion alternatives"
      description: "Returns whether the pipeline still has assigned records and lists other active pipelines of the same type that can receive those records during deletion."
      tags:
        - "Pipelines"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "pipelineId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Pipeline usage returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineUsageResponse"
        "400":
          description: "Invalid pipelineId format"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "404":
          description: "Pipeline not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
  "/api/pipelines/create":
    post:
      operationId: "post_pipelines_create"
      summary: "Create a new pipeline"
      description: "Create a brand-new pipeline (with its `pipelineStages`) for the given `type`. Setting `isDefault: true` switches the org's default pipeline to the newly-created one."
      tags:
        - "Pipelines"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "type"
          required: false
          schema:
            type: "string"
            enum:
              - "Contact"
              - "Application"
            default: "Contact"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CreatePipelineRequest"
      responses:
        "201":
          description: "Pipeline created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineMutationResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
  "/api/pipelines/list":
    get:
      operationId: "get_pipelines_list"
      summary: "List organization pipelines"
      description: "List every active pipeline for the org filtered by `type` (Contact or Application). Used by the pipeline switcher in the inbox UI."
      tags:
        - "Pipelines"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "type"
          required: false
          schema:
            type: "string"
            enum:
              - "Contact"
              - "Application"
            default: "Contact"
      responses:
        "200":
          description: "Pipelines returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineListResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
  "/api/pipelines/set-default":
    post:
      operationId: "post_pipelines_set_default"
      summary: "Set a pipeline as default"
      description: "Promote a pipeline to be the org-wide default for its `type`. The previously-default pipeline keeps its records but loses the default flag."
      tags:
        - "Pipelines"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/SetDefaultPipelineRequest"
      responses:
        "200":
          description: "Default pipeline updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineMutationResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "404":
          description: "Pipeline not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
  "/api/pipelines/stages/{stageId}/usage":
    get:
      operationId: "get_pipeline_stage_usage"
      summary: "Check pipeline stage usage and reassignment alternatives"
      description: "Returns whether the stage still has assigned records and lists the other active stages on the same pipeline that the records can be reassigned to."
      tags:
        - "Pipelines"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "stageId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Pipeline stage usage returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineStageUsageResponse"
        "400":
          description: "Invalid stageId format"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "404":
          description: "Pipeline stage or parent pipeline not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
  "/api/pipelines/stages/reassign":
    post:
      operationId: "post_pipelines_stages_reassign"
      summary: "Reassign records from one pipeline stage to another"
      description: "Moves all contacts or applications from sourceStageId to targetStageId (must belong to the same pipeline) and deactivates the source stage. The body requires both stage ids."
      tags:
        - "Pipelines"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ReassignPipelineStageRequest"
      responses:
        "200":
          description: "Stage records reassigned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ReassignPipelineStageResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "404":
          description: "Source or target stage not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PipelineErrorResponse"
  "/api/playground-sessions":
    get:
      operationId: "get_api_playground_sessions"
      summary: "GET /api/playground-sessions"
      tags:
        - "Playground Sessions"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/playground-sessions/{id}":
    get:
      operationId: "get_api_playground_sessions_id"
      summary: "GET /api/playground-sessions/{id}"
      tags:
        - "Playground Sessions"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
    patch:
      operationId: "patch_api_playground_sessions_id"
      summary: "PATCH /api/playground-sessions/{id}"
      tags:
        - "Playground Sessions"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
    delete:
      operationId: "delete_api_playground_sessions_id"
      summary: "DELETE /api/playground-sessions/{id}"
      tags:
        - "Playground Sessions"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/processes":
    get:
      operationId: "get_processes"
      summary: "Get processes (prompts) for current user"
      description: "Return every Prompt assigned to the authenticated user, populated for the playground/agent surfaces. \"Process\" is legacy naming for Prompt records."
      tags:
        - "Process"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Processes fetched successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ProcessListResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ProcessErrorResponse"
        "500":
          description: "Failed to fetch processes"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ProcessErrorResponse"
    post:
      operationId: "post_processes"
      summary: "Get processes (prompts) for a selected user"
      description: "Admin variant - return every Prompt assigned to the user identified by `selectedUser.userId`. Used when a manager opens another rep's playground; the caller must have access to the target user."
      tags:
        - "Process"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ProcessGetForSelectedUserRequest"
      responses:
        "200":
          description: "Processes fetched successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ProcessListResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ProcessErrorResponse"
        "500":
          description: "Failed to fetch processes"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ProcessErrorResponse"
  "/api/prompts/{promptId}":
    get:
      operationId: "get_prompts_by_id"
      summary: "Get a specific prompt by ID"
      description: "Returns a single prompt the caller owns or has acquired as a marketplace reference. The response includes access-metadata flags (`_isOwned`, `_isReference`, `_isEditableReference`) so the UI can render the right edit affordances."
      tags:
        - "Prompts"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "promptId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Prompt returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptWithAccessMetadataResponse"
        "403":
          description: "Prompt not found or not accessible by user"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "404":
          description: "Prompt not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
    put:
      operationId: "put_prompts_by_id"
      summary: "Update a user prompt"
      description: "Updates editable fields on a prompt the caller owns. Prompt text, name, description, temperature/responseTime, tools and toolConfigs are mutable here; versioning is handled separately via the /versions endpoints."
      tags:
        - "Prompts"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "promptId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/PromptUpdateRequest"
      responses:
        "200":
          description: "Prompt updated successfully (may include a versionSnapshot when a checkpoint was captured)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptUpdateResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "403":
          description: "Prompt not found, not owned, hidden, or marketplace-reference"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "404":
          description: "User or prompt not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "409":
          description: "SMS-approval conflict - agent is currently assigned to SMS conversations and newly required tools change its approval surface"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptSmsApprovalConflictResponse"
    delete:
      operationId: "delete_prompts_by_id"
      summary: "Delete a user prompt"
      description: "Deletes a prompt the caller owns. Refuses to delete a prompt that has been published to the marketplace (HTTP 400). To consolidate before deleting, use POST /api/prompts/reassign."
      tags:
        - "Prompts"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "promptId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Prompt deleted successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptDeleteResponse"
        "400":
          description: "Cannot delete a published prompt"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptDeletePublishedErrorResponse"
        "403":
          description: "Prompt not found or not owned by user"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
  "/api/prompts/{promptId}/usage":
    get:
      operationId: "get_prompts_usage"
      summary: "Check prompt usage by contacts and conversations"
      description: "Reports how many Contacts and Conversations currently reference the prompt and returns up to a few alternative prompts the caller could reassign them to. Used by the delete/reassign confirmation flow."
      tags:
        - "Prompts"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "promptId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Prompt usage information returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptUsageResponse"
        "403":
          description: "Prompt not found or not owned by user"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "404":
          description: "User or prompt not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
  "/api/prompts/{promptId}/versions":
    get:
      operationId: "get_prompts_versions"
      summary: "List versions for a prompt"
      description: "Returns paginated version snapshots for a prompt the caller owns or has acquired as an editable reference. Each item is a summary (preview, displayVersion, label, source) and is marked as matchesCurrentPrompt when its text equals the live prompt."
      tags:
        - "Prompts"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "promptId"
          required: true
          schema:
            type: "string"
        -
          in: "query"
          name: "limit"
          required: false
          schema:
            type: "integer"
            minimum: 1
            maximum: 100
            default: 20
        -
          in: "query"
          name: "skip"
          required: false
          schema:
            type: "integer"
            minimum: 0
            default: 0
      responses:
        "200":
          description: "Versions returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptVersionListResponse"
        "403":
          description: "Prompt not found or not accessible by user"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "404":
          description: "Prompt not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
    post:
      operationId: "post_prompts_version_checkpoint"
      summary: "Create a prompt version checkpoint"
      description: "Snapshots the prompt text into a new immutable version. If prompt text is omitted, the current prompt body is used. Returns the new version document; if the text is unchanged from the latest version, the request is treated as a no-op and skipped is true."
      tags:
        - "Prompts"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "promptId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/PromptVersionCheckpointRequest"
      responses:
        "201":
          description: "Version saved (or no-op when unchanged)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptVersionCheckpointResponse"
        "403":
          description: "Prompt not found or not accessible by user"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "404":
          description: "Prompt not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
  "/api/prompts/{promptId}/versions/{versionId}":
    get:
      operationId: "get_prompts_version_by_id"
      summary: "Get a single prompt version"
      description: "Returns the full version document (including the prompt body and metadata) for a specific version of a prompt the caller can access."
      tags:
        - "Prompts"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "promptId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "versionId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Version returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptVersionDocument"
        "400":
          description: "Invalid version id"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "403":
          description: "Prompt not found or not accessible by user"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "404":
          description: "Version not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
    patch:
      operationId: "patch_prompts_version_metadata"
      summary: "Update prompt version metadata"
      description: "Updates editable metadata fields (displayVersion, title, description) on a prompt version. Passing an explicit null clears the field; at least one field must be supplied."
      tags:
        - "Prompts"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "promptId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "versionId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/PromptVersionMetadataUpdateRequest"
      responses:
        "200":
          description: "Prompt version updated successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptVersionUpdateResponse"
        "400":
          description: "Invalid version id or no fields to update"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "403":
          description: "Prompt not found or not accessible by user"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "404":
          description: "Version not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
  "/api/prompts/{promptId}/versions/{versionId}/restore":
    post:
      operationId: "post_api_prompts_promptId_versions_versionId_restore"
      summary: "POST /api/prompts/{promptId}/versions/{versionId}/restore"
      tags:
        - "Prompts"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "promptId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "versionId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/prompts/{promptId}/voice-sync":
    get:
      operationId: "get_api_prompts_promptId_voice_sync"
      summary: "GET /api/prompts/{promptId}/voice-sync"
      tags:
        - "Prompts"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "promptId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/prompts/admin/all":
    get:
      operationId: "get_prompts_admin_all"
      summary: "List all prompts (superadmin)"
      description: "Superadmin-only paginated listing of every prompt across organizations. Supports text search on name, organization filtering, and visibility filtering (all, hidden, visible). Used by the global Prompt Visibility Management view."
      tags:
        - "Prompts"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "page"
          required: false
          schema:
            type: "integer"
            minimum: 1
            default: 1
        -
          in: "query"
          name: "limit"
          required: false
          schema:
            type: "integer"
            minimum: 1
            default: 50
        -
          in: "query"
          name: "search"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "organizationId"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "visibility"
          required: false
          schema:
            type: "string"
            enum:
              - "all"
              - "hidden"
              - "visible"
            default: "all"
      responses:
        "200":
          description: "Prompts returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AdminPromptListResponse"
        "403":
          description: "Superadmin access required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
  "/api/prompts/admin/org":
    get:
      operationId: "get_prompts_admin_org"
      summary: "List prompts for the current admin organization"
      description: "Paginated listing of prompts scoped to the caller organization, available to admins and superadmins. Supports text search on name and visibility filtering. Used by the per-org Admin Prompt Visibility Management view."
      tags:
        - "Prompts"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "page"
          required: false
          schema:
            type: "integer"
            minimum: 1
            default: 1
        -
          in: "query"
          name: "limit"
          required: false
          schema:
            type: "integer"
            minimum: 1
            default: 50
        -
          in: "query"
          name: "search"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "visibility"
          required: false
          schema:
            type: "string"
            enum:
              - "all"
              - "hidden"
              - "visible"
            default: "all"
      responses:
        "200":
          description: "Prompts returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AdminPromptListResponse"
        "403":
          description: "Admin access required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
  "/api/prompts/by-workflow/{workflowId}":
    get:
      operationId: "get_api_prompts_by_workflow_workflowId"
      summary: "GET /api/prompts/by-workflow/{workflowId}"
      tags:
        - "Prompts"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "workflowId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/prompts/create":
    post:
      operationId: "post_prompts_create"
      summary: "Create a new prompt"
      description: "Creates a new Prompt document owned by the calling user and organization. The body becomes the live prompt content; subsequent edits create versions, not new prompts."
      tags:
        - "Prompts"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/PromptCreateRequest"
      responses:
        "200":
          description: "Prompt created successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptCreateResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
  "/api/prompts/org/options":
    get:
      operationId: "get_api_prompts_org_options"
      summary: "GET /api/prompts/org/options"
      tags:
        - "Prompts"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/prompts/reassign":
    post:
      operationId: "post_prompts_reassign"
      summary: "Reassign contacts and conversations from one prompt to another"
      description: "Moves every Contact and Conversation pointing at `promptId` over to `targetPromptId`, then deletes the source prompt. Both prompts must be owned by the caller. Used when consolidating or retiring prompts without orphaning conversations."
      tags:
        - "Prompts"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/PromptReassignRequest"
      responses:
        "200":
          description: "Successfully reassigned and deleted prompt"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptReassignResponse"
        "400":
          description: "Both promptId and targetPromptId are required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "403":
          description: "Prompt not found or not owned by user"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "404":
          description: "User or prompt not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
  "/api/prompts/user":
    get:
      operationId: "get_prompts_user"
      summary: "Get all prompts for the current user"
      description: "Returns the full PromptDocument array owned by the caller. For non-admin callers, the `prompt` body field is stripped on entries marked `isHidden`. Returns an empty object `{}` when the user has no prompts."
      tags:
        - "Prompts"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "User prompts returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptUserPromptsResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
  "/api/prompts/user/summary":
    get:
      operationId: "get_prompts_user_summary"
      summary: "Get summarized user prompts including reference prompts"
      description: "Returns a flat summarized list mixing own-prompt summaries and acquired reference-prompt summaries (marketplace references). Each entry is discriminated by `isReference`/`isOwned`. An optional `userId` query selects another user (admin use)."
      tags:
        - "Prompts"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "userId"
          required: false
          schema:
            type: "string"
          description: "Optional user ID to fetch prompts for (defaults to current user)"
      responses:
        "200":
          description: "Summarized prompts returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptSummarizedPromptListResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PromptErrorResponse"
  "/api/prompts/voice-agents":
    get:
      operationId: "get_api_prompts_voice_agents"
      summary: "GET /api/prompts/voice-agents"
      tags:
        - "Prompts"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/record-logs":
    get:
      operationId: "get_record_logs"
      summary: "Get unified record audit logs (change + action) with filters and pagination"
      description: "Paginated, filterable per-record audit log. Two fetch modes: **contact-hub** (`contactId`) returns every log for a contact plus its conversations, applications and custom entities; **single-entity** (`entityType` + `entityId`) returns just that record. Filter by `kind` (change|action), `changeCategory` (state|field), `field`, `action`, `actorUserId`, `actorType` (user|system|automation|workflow) and a `from`/`to` date range. `excludeCustomEntity` drops linked custom-entity rows (used by the Main entity changes surface). Org-scoped; non-SUPERADMIN callers are pinned to their own org."
      tags:
        - "Record Logs"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "contactId"
          required: false
          schema:
            type: "string"
          description: "Contact-hub mode: all logs rolling up to this contact."
        -
          in: "query"
          name: "entityType"
          required: false
          schema:
            type: "string"
            enum:
              - "Contact"
              - "Application"
              - "Conversation"
              - "CustomEntity"
        -
          in: "query"
          name: "entityId"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "kind"
          required: false
          schema:
            type: "string"
            enum:
              - "change"
              - "action"
        -
          in: "query"
          name: "changeCategory"
          required: false
          schema:
            type: "string"
            enum:
              - "state"
              - "field"
        -
          in: "query"
          name: "field"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "action"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "actorUserId"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "actorType"
          required: false
          schema:
            type: "string"
            enum:
              - "user"
              - "system"
              - "automation"
              - "workflow"
        -
          in: "query"
          name: "from"
          required: false
          schema:
            type: "string"
            format: "date-time"
        -
          in: "query"
          name: "to"
          required: false
          schema:
            type: "string"
            format: "date-time"
        -
          in: "query"
          name: "excludeCustomEntity"
          required: false
          schema:
            type: "boolean"
        -
          in: "query"
          name: "page"
          required: false
          schema:
            type: "integer"
            minimum: 1
            default: 1
        -
          in: "query"
          name: "size"
          required: false
          schema:
            type: "integer"
            minimum: 1
            maximum: 200
            default: 50
      responses:
        "200":
          description: "Record logs returned with pagination"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/RecordLogListResponse"
        "400":
          description: "Missing fetch mode (need contactId or entityType+entityId)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/RecordLogErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/RecordLogErrorResponse"
        "403":
          description: "Access denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/RecordLogErrorResponse"
        "500":
          description: "Error fetching record logs"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/RecordLogErrorResponse"
  "/api/record-logs/facets":
    get:
      operationId: "get_api_record_logs_facets"
      summary: "GET /api/record-logs/facets"
      tags:
        - "Record Logs"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/record-logs/field-metadata":
    get:
      operationId: "get_record_field_metadata"
      summary: "Who first set and who last changed every field of one record"
      description: "One call per record for the field hover: for each field of a contact, application or conversation, the first setter and time and the last setter and time. Rows never expire. Fields set when the record was created and never changed since have no row; read the record's createdBy/createdAt for those. Custom-entity fields carry customEntityType and customEntityInstanceId. Org-scoped."
      tags:
        - "Record Logs"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "entityType"
          required: true
          schema:
            type: "string"
            enum:
              - "Contact"
              - "Application"
              - "Conversation"
        -
          in: "query"
          name: "entityId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Field stamps for the record."
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/RecordFieldMetadataResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/RecordLogErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/RecordLogErrorResponse"
        "403":
          description: "Access denied"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/RecordLogErrorResponse"
        "500":
          description: "Server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/RecordLogErrorResponse"
  "/api/record-summaries/{recordType}/{recordId}":
    get:
      operationId: "get_api_record_summaries_recordType_recordId"
      summary: "GET /api/record-summaries/{recordType}/{recordId}"
      tags:
        - "Record Summaries"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "recordType"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "recordId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
    post:
      operationId: "post_api_record_summaries_recordType_recordId"
      summary: "POST /api/record-summaries/{recordType}/{recordId}"
      tags:
        - "Record Summaries"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "recordType"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "recordId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/reminders":
    get:
      operationId: "get_reminders"
      summary: "List reminders for the current user or for one record"
      description: "Returns reminders scoped to the caller's organization, sorted by `reminderDate` ascending.\n\n`scope=mine` (the default) is the caller's personal list: only reminders with `assigneeId = userId`. Unassigned reminders belong to no personal list and are not returned.\n\n`scope=record` returns every reminder attached to the requested record whatever its assignee, for the per-contact / per-application / per-conversation surfaces; it requires at least one of `contactId`, `contactIds`, `applicationId` or `conversationId`. Reminders the caller does not own are readable but cannot be updated or deleted.\n\nFilters combine (AND). `status` selects unfired (`pending`, the default), fired, or both."
      tags:
        - "Reminders"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "contactId"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "contactIds"
          required: false
          schema:
            type: "string"
          description: "Comma-separated list of contact ids"
        -
          in: "query"
          name: "applicationId"
          required: false
          schema:
            type: "string"
          description: "Only reminders attached to this application"
        -
          in: "query"
          name: "conversationId"
          required: false
          schema:
            type: "string"
          description: "Only reminders attached to this conversation"
        -
          in: "query"
          name: "scope"
          required: false
          schema:
            type: "string"
            enum:
              - "mine"
              - "record"
            default: "mine"
          description: "'mine' restricts to the caller's own reminders; 'record' returns everyone's for the filtered record."
        -
          in: "query"
          name: "status"
          required: false
          schema:
            type: "string"
            enum:
              - "pending"
              - "fired"
              - "all"
            default: "pending"
      responses:
        "200":
          description: "Reminders returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ReminderListResponse"
        "400":
          description: "Invalid filter: malformed id, unrecognised scope/status, or scope=record with no record filter"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ReminderErrorResponse"
        "404":
          description: "Filtered application or conversation is not in this organization"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ReminderErrorResponse"
        "500":
          description: "Failed to fetch reminders"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ReminderErrorResponse"
    post:
      operationId: "post_reminders"
      summary: "Create a reminder for a contact"
      description: "Creates an unfired reminder for the given contact. `reminderDate` must parse to a valid future date. The reminder is scoped to the caller's organization. `assigneeId` decides who is notified when it fires and defaults to the calling user; pass `null` to create a silent reminder that notifies nobody. `createdBy` is recorded as provenance only.\n\nPass `applicationId` and/or `conversationId` to attach the reminder to the record it was composed from - both must belong to the caller's organization. `contactId` stays required and populated either way, so the reminder still rolls up to the contact."
      tags:
        - "Reminders"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CreateReminderRequest"
      responses:
        "201":
          description: "Reminder created successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ReminderMutationResponse"
        "400":
          description: "Missing required fields or reminderDate is not a valid future date"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ReminderErrorResponse"
        "404":
          description: "Contact not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ReminderErrorResponse"
        "500":
          description: "Failed to create reminder"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ReminderErrorResponse"
  "/api/reminders/{reminderId}":
    patch:
      operationId: "patch_api_reminders_reminderId"
      summary: "PATCH /api/reminders/{reminderId}"
      tags:
        - "Reminders"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "reminderId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
    delete:
      operationId: "delete_reminders_reminderId"
      summary: "Delete (complete) a reminder"
      description: "Deletes the reminder. The reminder must belong to the caller's organization, and the caller must be its assignee. An unassigned reminder belongs to nobody and may be deleted by any member of the organization."
      tags:
        - "Reminders"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "reminderId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Reminder deleted successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ReminderDeleteResponse"
        "403":
          description: "Reminder is assigned to another user"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ReminderErrorResponse"
        "404":
          description: "Reminder not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ReminderErrorResponse"
        "500":
          description: "Failed to delete reminder"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ReminderErrorResponse"
  "/api/saved-filters":
    get:
      operationId: "get_api_saved_filters"
      summary: "GET /api/saved-filters"
      tags:
        - "Saved Filters"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
    post:
      operationId: "post_api_saved_filters"
      summary: "POST /api/saved-filters"
      tags:
        - "Saved Filters"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/saved-filters/{id}":
    put:
      operationId: "put_api_saved_filters_id"
      summary: "PUT /api/saved-filters/{id}"
      tags:
        - "Saved Filters"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
    delete:
      operationId: "delete_api_saved_filters_id"
      summary: "DELETE /api/saved-filters/{id}"
      tags:
        - "Saved Filters"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/search":
    get:
      operationId: "get_api_search"
      summary: "GET /api/search"
      tags:
        - "Search"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/sms/providers":
    get:
      operationId: "get_sms_providers"
      summary: "Get active SMS provider for the organization"
      description: "Returns the currently-selected SMS provider for the caller's organization (or the org passed via `?organizationId=` when the caller is a SUPERADMIN). Open to any authenticated user - used by send surfaces to render readiness banners and disable the composer when no provider is configured. The response is `{ provider: \"twilio\" | \"sinch\" | \"textgrid\" | null }`."
      tags:
        - "SMS"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "organizationId"
          required: false
          schema:
            type: "string"
          description: "SUPERADMIN-only override. Other roles are pinned to the org on their JWT and this parameter is ignored."
      responses:
        "200":
          description: "Active SMS provider (or `null` if none is configured)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsActiveProviderResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsErrorResponse"
        "500":
          description: "Failed to get SMS provider"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsErrorResponse"
  "/api/sms/providers/active":
    post:
      operationId: "post_sms_providers_active"
      summary: "Set active SMS provider"
      description: "Switches the organization's active SMS provider. The provider must already be configured (`POST /api/sms/providers/config` first), otherwise 400. Requires SUPERADMIN."
      tags:
        - "SMS"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/SmsSetActiveProviderRequest"
      responses:
        "200":
          description: "Active SMS provider set"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsMutationResponse"
        "400":
          description: "Invalid or unconfigured provider"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsErrorResponse"
        "403":
          description: "Forbidden (requires SUPERADMIN)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsErrorResponse"
        "500":
          description: "Failed to set active SMS provider"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsErrorResponse"
  "/api/sms/providers/config":
    get:
      operationId: "get_sms_providers_config"
      summary: "Get full SMS provider configuration"
      description: "Returns every supported SMS provider with its current configuration and enabled state for the org. Requires SUPERADMIN - the body includes raw credentials (Twilio/Sinch/TextGrid keys), so the route is gated. Each entry reports `isConfigured` (credentials present) and `isEnabled` (configured AND not explicitly disabled)."
      tags:
        - "SMS"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "organizationId"
          required: false
          schema:
            type: "string"
          description: "SUPERADMIN-only override of the target organization."
      responses:
        "200":
          description: "SMS provider configuration"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsProviderConfigResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsErrorResponse"
        "403":
          description: "Forbidden (requires SUPERADMIN)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsErrorResponse"
        "500":
          description: "Failed to get SMS provider configuration"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsErrorResponse"
    post:
      operationId: "post_sms_providers_config"
      summary: "Save SMS provider configuration"
      description: "Upserts the credentials for a single SMS provider (`twilio`, `sinch`, or `textgrid`) on the caller's organization. Whitespace is trimmed from every credential before persistence. Only fields relevant to the chosen `provider` are read; other fields are ignored. Requires SUPERADMIN."
      tags:
        - "SMS"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/SmsSaveProviderConfigRequest"
      responses:
        "200":
          description: "Configuration saved"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsMutationResponse"
        "400":
          description: "Invalid provider"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsErrorResponse"
        "403":
          description: "Forbidden (requires SUPERADMIN)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsErrorResponse"
        "500":
          description: "Failed to save SMS provider configuration"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsErrorResponse"
  "/api/sms/providers/config/{provider}":
    delete:
      operationId: "delete_sms_providers_config_provider"
      summary: "Remove SMS provider configuration"
      description: "Removes a provider entry from `smsProviders` and clears legacy flat credential fields for that provider. If the deleted provider was the active one, `smsProvider` is unset (the org will report `provider: null` from `GET /api/sms/providers` until a new active provider is selected). Requires SUPERADMIN."
      tags:
        - "SMS"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "provider"
          required: true
          schema:
            type: "string"
            enum:
              - "twilio"
              - "sinch"
              - "textgrid"
          description: "Provider whose configuration should be removed."
      responses:
        "200":
          description: "Configuration removed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsMutationResponse"
        "400":
          description: "Invalid provider"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsErrorResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsErrorResponse"
        "403":
          description: "Forbidden (requires SUPERADMIN)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsErrorResponse"
        "500":
          description: "Failed to remove SMS provider configuration"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsErrorResponse"
  "/api/templates":
    get:
      operationId: "get_templates"
      summary: "List all templates"
      description: "Returns every template visible to the caller in their organization, optionally filtered by `type` (e.g. `automation`, `message`). Powers the template picker in composers and the automation builder."
      tags:
        - "Templates"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "type"
          required: false
          schema:
            type: "string"
      responses:
        "200":
          description: "Templates returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TemplatesListResponse"
        "500":
          description: "Failed to fetch templates"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TemplatesErrorResponse"
    post:
      operationId: "post_templates"
      summary: "Create template"
      description: "Create a template scoped to the caller's organization. `name`, `template` body and `type` are required; `category` is required for non-automation types."
      tags:
        - "Templates"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CreateTemplateRequest"
      responses:
        "201":
          description: "Template created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TemplateMutationResponse"
        "400":
          description: "Missing required fields"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TemplatesErrorResponse"
        "500":
          description: "Failed to create template"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TemplatesErrorResponse"
  "/api/templates/{id}":
    get:
      operationId: "get_template_by_id"
      summary: "Get template by id"
      description: "Fetch a single template by `_id` (within the caller's organization scope)."
      tags:
        - "Templates"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Template returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TemplateMutationResponse"
        "404":
          description: "Template not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TemplatesErrorResponse"
        "500":
          description: "Failed to fetch template"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TemplatesErrorResponse"
    put:
      operationId: "put_template"
      summary: "Update template"
      description: "Update mutable fields of a template (`name`, `template`, `type`, `category`). Cross-org updates are not allowed."
      tags:
        - "Templates"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateTemplateRequest"
      responses:
        "200":
          description: "Template updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TemplateMutationResponse"
        "404":
          description: "Template not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TemplatesErrorResponse"
        "500":
          description: "Failed to update template"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TemplatesErrorResponse"
    delete:
      operationId: "delete_template"
      summary: "Delete template"
      description: "Permanently delete the template by `_id`. Cross-org deletes are rejected."
      tags:
        - "Templates"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Template deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TemplateDeleteResponse"
        "404":
          description: "Template not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TemplatesErrorResponse"
        "500":
          description: "Failed to delete template"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/TemplatesErrorResponse"
  "/api/tovi/contacts":
    get:
      operationId: "get_api_tovi_contacts"
      summary: "GET /api/tovi/contacts"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/tovi/conversation-investigations/inspect":
    post:
      operationId: "post_api_tovi_conversation_investigations_inspect"
      summary: "POST /api/tovi/conversation-investigations/inspect"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/tovi/memory":
    get:
      operationId: "get_api_tovi_memory"
      summary: "GET /api/tovi/memory"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/tovi/memory/items":
    post:
      operationId: "post_api_tovi_memory_items"
      summary: "POST /api/tovi/memory/items"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/tovi/memory/items/{itemId}":
    patch:
      operationId: "patch_api_tovi_memory_items_itemId"
      summary: "PATCH /api/tovi/memory/items/{itemId}"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "itemId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
    delete:
      operationId: "delete_api_tovi_memory_items_itemId"
      summary: "DELETE /api/tovi/memory/items/{itemId}"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "itemId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/tovi/memory/learned-items":
    delete:
      operationId: "delete_api_tovi_memory_learned_items"
      summary: "DELETE /api/tovi/memory/learned-items"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/tovi/memory/onboarding":
    patch:
      operationId: "patch_api_tovi_memory_onboarding"
      summary: "PATCH /api/tovi/memory/onboarding"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/tovi/memory/profile":
    patch:
      operationId: "patch_api_tovi_memory_profile"
      summary: "PATCH /api/tovi/memory/profile"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/tovi/memory/settings":
    patch:
      operationId: "patch_api_tovi_memory_settings"
      summary: "PATCH /api/tovi/memory/settings"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/tovi/pipeline-stages":
    get:
      operationId: "get_api_tovi_pipeline_stages"
      summary: "GET /api/tovi/pipeline-stages"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/tovi/pipelines":
    get:
      operationId: "get_api_tovi_pipelines"
      summary: "GET /api/tovi/pipelines"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/tovi/threads":
    get:
      operationId: "get_api_tovi_threads"
      summary: "GET /api/tovi/threads"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
    post:
      operationId: "post_api_tovi_threads"
      summary: "POST /api/tovi/threads"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/tovi/threads/{threadId}":
    get:
      operationId: "get_api_tovi_threads_threadId"
      summary: "GET /api/tovi/threads/{threadId}"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "threadId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
    patch:
      operationId: "patch_api_tovi_threads_threadId"
      summary: "PATCH /api/tovi/threads/{threadId}"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "threadId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
    delete:
      operationId: "delete_api_tovi_threads_threadId"
      summary: "DELETE /api/tovi/threads/{threadId}"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "threadId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/tovi/threads/{threadId}/messages/{messageId}/apply":
    post:
      operationId: "post_api_tovi_threads_threadId_messages_messageId_apply"
      summary: "POST /api/tovi/threads/{threadId}/messages/{messageId}/apply"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "threadId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "messageId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/tovi/threads/{threadId}/messages/{messageId}/discard":
    post:
      operationId: "post_api_tovi_threads_threadId_messages_messageId_discard"
      summary: "POST /api/tovi/threads/{threadId}/messages/{messageId}/discard"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "threadId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "messageId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/tovi/threads/{threadId}/messages/stream":
    post:
      operationId: "post_api_tovi_threads_threadId_messages_stream"
      summary: "POST /api/tovi/threads/{threadId}/messages/stream"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "threadId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/tovi/threads/{threadId}/mode":
    put:
      operationId: "put_api_tovi_threads_threadId_mode"
      summary: "PUT /api/tovi/threads/{threadId}/mode"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "threadId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/tovi/threads/{threadId}/runs/stop":
    post:
      operationId: "post_api_tovi_threads_threadId_runs_stop"
      summary: "POST /api/tovi/threads/{threadId}/runs/stop"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "threadId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/tovi/threads/{threadId}/surface-events":
    post:
      operationId: "post_api_tovi_threads_threadId_surface_events"
      summary: "POST /api/tovi/threads/{threadId}/surface-events"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "threadId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/tovi/workflows":
    get:
      operationId: "get_api_tovi_workflows"
      summary: "GET /api/tovi/workflows"
      tags:
        - "Tovi"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/traces":
    post:
      operationId: "post_traces"
      summary: "Forward telemetry traces to the backend collector"
      description: "Accepts an OpenTelemetry-compatible trace payload from a client (browser SDK, mobile, or another service) and forwards it to the backend collector for ingestion. Fire-and-forget: the API returns 202 once the payload is queued; downstream processing failures are not surfaced to the caller."
      tags:
        - "Telemetry"
      security:
        []
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ForwardTracesRequest"
      responses:
        "202":
          description: "Traces accepted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ForwardTracesResponse"
  "/api/upload":
    post:
      operationId: "post_upload"
      summary: "Upload one or more files to R2 storage"
      description: "Accepts up to 10 files as `multipart/form-data` under the `files` field. Each file is uploaded to R2 under a per-organization storage key and returned with a freshly generated signed URL."
      tags:
        - "Upload"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "multipart/form-data":
            schema:
              type: "object"
              properties:
                files:
                  type: "array"
                  maxItems: 10
                  items:
                    type: "string"
                    format: "binary"
                  description: "Up to 10 binary files, each ≤50 MB. Field name must be exactly `files`."
              required:
                - "files"
              description: "Multipart form. Send each file as a separate `files` part. Example with curl: `curl -F \"files=@invoice.pdf\" -F \"files=@receipt.png\" -H \"Authorization: Bearer $TOKEN\" /api/upload`."
              example:
                files:
                  - "<binary: invoice.pdf>"
                  - "<binary: receipt.png>"
      responses:
        "200":
          description: "Files uploaded"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UploadFilesResponse"
        "400":
          description: "No files uploaded"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UploadErrorResponse"
        "401":
          description: "Authentication required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UploadErrorResponse"
        "500":
          description: "Failed to upload files"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UploadErrorResponse"
        "503":
          description: "File upload service not configured"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UploadErrorResponse"
  "/api/user-snapshots":
    get:
      operationId: "get_user_snapshots"
      summary: "List user snapshots"
      description: "Returns the list of user-level snapshots visible to the caller. Superadmins see all snapshots; admins see snapshots assigned to their organization or marked as global."
      tags:
        - "User Snapshots"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Snapshots returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotListResponse"
        "400":
          description: "Invalid request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "403":
          description: "Forbidden - admin or superadmin role required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "500":
          description: "Failed to retrieve snapshots"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
    post:
      operationId: "post_user_snapshot"
      summary: "Create a user snapshot"
      description: "Captures a user-level snapshot (automations, prompts, templates, and pipeline-stage/agent references) for the specified source user in a source organization. Admins can only snapshot their own organization."
      tags:
        - "User Snapshots"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CreateUserSnapshotRequest"
      responses:
        "201":
          description: "Snapshot created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotCreateResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "403":
          description: "Forbidden - cannot snapshot another organization"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "404":
          description: "Source organization or user not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "409":
          description: "Snapshot name already exists"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "422":
          description: "Mongoose validation failure"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "500":
          description: "Failed to create snapshot"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
  "/api/user-snapshots/{id}":
    get:
      operationId: "get_user_snapshot_by_id"
      summary: "Get a user snapshot"
      description: "Returns the full snapshot detail (automations, prompts, templates, source refs, counts) for the given snapshot id, subject to access rules."
      tags:
        - "User Snapshots"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Snapshot returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotDetailResponse"
        "400":
          description: "Invalid snapshot id"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "404":
          description: "Snapshot not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "500":
          description: "Failed to retrieve snapshot"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
    delete:
      operationId: "delete_user_snapshot"
      summary: "Delete a user snapshot"
      description: "Deletes a user snapshot. Admins can only delete snapshots they created; superadmins can delete any snapshot."
      tags:
        - "User Snapshots"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Snapshot deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotMessageResponse"
        "400":
          description: "Invalid snapshot id"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "403":
          description: "Forbidden - only the creator (or a superadmin) may delete this snapshot"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "404":
          description: "Snapshot not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "500":
          description: "Failed to delete snapshot"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
  "/api/user-snapshots/{id}/apply":
    post:
      operationId: "post_user_snapshot_apply"
      summary: "Apply a user snapshot"
      description: "Creates a new user in the caller organization and clones the snapshot automations, prompts, and templates (with pipeline-stage and agent mappings) inside a single transaction. Same-org applies skip automations and templates to avoid duplicates."
      tags:
        - "User Snapshots"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ApplyUserSnapshotRequest"
      responses:
        "201":
          description: "Snapshot applied - new user created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApplyUserSnapshotResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "404":
          description: "Snapshot not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "409":
          description: "Conflict - new user email already exists"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "422":
          description: "Mongoose validation failure"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "500":
          description: "Failed to apply snapshot - all changes rolled back"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
  "/api/user-snapshots/{id}/apply-refs":
    get:
      operationId: "get_user_snapshot_apply_refs"
      summary: "Get apply references (pipeline stages and agents)"
      description: "Returns the source pipeline-stage and agent references captured in the snapshot, plus the caller-organization pipelines and agents available as mapping targets when applying the snapshot."
      tags:
        - "User Snapshots"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Apply refs returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotApplyRefsResponse"
        "400":
          description: "Missing organization context or invalid id"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "404":
          description: "Snapshot not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "500":
          description: "Failed to retrieve apply refs"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
  "/api/user-snapshots/{id}/assign":
    patch:
      operationId: "patch_user_snapshot_assign"
      summary: "Update snapshot assignment / global flag"
      description: "Updates which organizations a snapshot is assigned to and whether it is globally visible. Superadmins may set both assignedOrgIds and isGlobal; admins may only toggle isGlobal on snapshots they created."
      tags:
        - "User Snapshots"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/AssignUserSnapshotRequest"
      responses:
        "200":
          description: "Snapshot access updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/AssignUserSnapshotResponse"
        "400":
          description: "Validation error or no valid fields to update"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "403":
          description: "Forbidden - admins may only manage their own snapshots"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "404":
          description: "Snapshot not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "500":
          description: "Failed to update snapshot access"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
  "/api/user-snapshots/orgs/{orgId}/users":
    get:
      operationId: "get_user_snapshot_org_users"
      summary: "List users for a source organization"
      description: "Helper endpoint used by the snapshot creation UI. Returns users that belong to the given organization. Admins may only request users from their own organization."
      tags:
        - "User Snapshots"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "orgId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Users returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotOrgUsersResponse"
        "400":
          description: "Organization id is required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "403":
          description: "Forbidden - cannot view users from another organization"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
        "500":
          description: "Failed to retrieve users"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSnapshotErrorResponse"
  "/api/user/{id}":
    put:
      operationId: "put_user_by_id"
      summary: "Update a user by ID (admin)"
      description: "Admin endpoint: updates a target user fields (name, email, phone, designation, access role, department). Returns 409 if the new email is already in use."
      tags:
        - "User"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UserUpdateByIdRequest"
      responses:
        "200":
          description: "User updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserAdminMutationResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserAdminErrorResponse"
        "403":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserAdminErrorResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserAdminErrorResponse"
        "409":
          description: "Email already in use"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserAdminErrorResponse"
    delete:
      operationId: "delete_user_by_id"
      summary: "Delete a user by ID"
      description: "Permanently removes a user from the organization. Only admins or superadmins may invoke this endpoint."
      tags:
        - "Users"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "User deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserDeleteResponse"
        "400":
          description: "Invalid user id"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserAdminErrorResponse"
        "403":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserAdminErrorResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserAdminErrorResponse"
        "500":
          description: "Failed to delete user"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserAdminErrorResponse"
  "/api/user/{id}/toggle-password-auth":
    put:
      operationId: "put_user_toggle_password_auth"
      summary: "Toggle password authentication for a user"
      description: "Enables or disables password-based login for the target user. Admin only. SUPERADMIN users cannot have password auth disabled."
      tags:
        - "Users"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Password auth toggled"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserTogglePasswordAuthResponse"
        "400":
          description: "Invalid user id"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserAdminErrorResponse"
        "403":
          description: "Unauthorized or SUPERADMIN user"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserAdminErrorResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserAdminErrorResponse"
        "500":
          description: "Failed to toggle password auth"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserAdminErrorResponse"
  "/api/user/api-key":
    get:
      operationId: "get_user_api_key"
      summary: "Get user API key"
      description: "Returns the authenticated user personal API key used for programmatic access to the Tether Relay API."
      tags:
        - "Users"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "API key returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserApiKeyResponse"
        "400":
          description: "Invalid request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "500":
          description: "Failed to fetch API key"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
  "/api/user/api-key/regenerate":
    post:
      operationId: "post_user_api_key_regenerate"
      summary: "Regenerate user API key"
      description: "Rotates the authenticated user API key and returns the new value. The previous key is invalidated immediately."
      tags:
        - "Users"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "API key regenerated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserApiKeyRegenerateResponse"
        "400":
          description: "Invalid request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "500":
          description: "Failed to regenerate API key"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
  "/api/user/chat-availability":
    get:
      operationId: "get_user_chat_availability"
      summary: "Get chat availability status"
      description: "Returns whether the authenticated user is currently marked as available for chat routing."
      tags:
        - "Users"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Chat availability returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserChatAvailabilityResponse"
        "400":
          description: "Invalid request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "500":
          description: "Failed to fetch chat availability"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
    put:
      operationId: "put_user_chat_availability"
      summary: "Update chat availability status"
      description: "Toggles the authenticated user availability for chat routing. Affects whether new conversations are assigned to this user by the round-robin allocator."
      tags:
        - "User"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UserUpdateChatAvailabilityRequest"
      responses:
        "200":
          description: "Chat availability updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserUpdateChatAvailabilityResponse"
        "400":
          description: "isAvailable must be a boolean"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
  "/api/user/list":
    get:
      operationId: "get_user_list"
      summary: "List users in organization"
      description: "Returns the list of users in the authenticated caller organization, filtered by access role visibility rules."
      tags:
        - "Users"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Users list returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserListResponse"
        "400":
          description: "Invalid request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "500":
          description: "Failed to fetch users list"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
    post:
      operationId: "post_user_list"
      summary: "List users in organization and team (filtered)"
      description: "Returns users filtered by organizationId and/or departmentId. Visibility is further constrained by the caller access role."
      tags:
        - "User"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UserListByTeamRequest"
      responses:
        "200":
          description: "Users list returned (bare array of user summaries - no envelope)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserListByTeamResponse"
        "401":
          description: "Access role not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
  "/api/user/notification-preferences":
    get:
      operationId: "get_user_notification_preferences"
      summary: "Get notification preferences"
      description: "Returns the authenticated user notification toggles for AI responses, automations, escalations, calls, campaigns, and other events."
      tags:
        - "Users"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Notification preferences returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserNotificationPreferencesResponse"
        "400":
          description: "Invalid request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "500":
          description: "Failed to fetch notification preferences"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
    put:
      operationId: "put_user_notification_preferences"
      summary: "Update notification preferences"
      description: "Replaces the authenticated user notification preferences map (AI responses, automations, escalations, calls, campaigns, etc.). Unspecified keys retain their current values."
      tags:
        - "User"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UserUpdateNotificationPreferencesRequest"
      responses:
        "200":
          description: "Notification preferences updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserUpdateNotificationPreferencesResponse"
        "400":
          description: "Notification preferences are required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
  "/api/user/profile":
    get:
      operationId: "get_user_profile"
      summary: "Get current user profile"
      description: "Returns the authenticated user profile, including organization, role, persona, automations, and other settings."
      tags:
        - "Users"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "User profile returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserProfileResponse"
        "400":
          description: "Invalid request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "401":
          description: "Authentication required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "500":
          description: "Failed to fetch profile"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
    put:
      operationId: "put_user_profile"
      summary: "Update current user profile"
      description: "Updates the authenticated user profile fields (name, email, phone, designation, persona, automations, notification preferences, call forwarding). Returns 409 if the new email is already in use."
      tags:
        - "User"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UserUpdateProfileRequest"
      responses:
        "200":
          description: "Profile updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserUpdateProfileResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "409":
          description: "Email already in use"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
  "/api/user/reset-password":
    post:
      operationId: "post_user_reset_password"
      summary: "Reset a user password (admin)"
      description: "Admin endpoint: sets a new password for the specified user. The previous password is invalidated. The caller must be ADMIN or SUPERADMIN."
      tags:
        - "User"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UserResetPasswordRequest"
      responses:
        "200":
          description: "Password reset successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSimpleMessageResponse"
        "400":
          description: "User ID and new password are required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "403":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "404":
          description: "User not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
  "/api/user/sms-templates":
    get:
      operationId: "get_user_sms_templates"
      summary: "Get all SMS templates for organization"
      description: "Returns SMS, campaign, script, and automation templates visible to the authenticated user, optionally filtered by template type."
      tags:
        - "Users"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "type"
          required: false
          schema:
            type: "string"
            enum:
              - "sms"
              - "campaign"
              - "script"
              - "automation"
      responses:
        "200":
          description: "Templates returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSmsTemplateListResponse"
        "400":
          description: "Invalid template type"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "500":
          description: "Failed to fetch templates"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
    post:
      operationId: "post_user_sms_templates"
      summary: "Create a new SMS template"
      description: "Creates a reusable template (sms, campaign, script, or automation) for the authenticated user organization. Templates may include placeholders like `{{firstName}}` resolved at send time."
      tags:
        - "User"
        - "Templates"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UserCreateSmsTemplateRequest"
      responses:
        "201":
          description: "Template created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSmsTemplateDocument"
        "400":
          description: "Name, template and type are required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
  "/api/user/sms-templates/{templateId}":
    post:
      operationId: "post_user_sms_template_with_data"
      summary: "Get template with contact data placeholders resolved"
      description: "Returns the template body with placeholders (`{{firstName}}`, `{{lastName}}`, etc.) resolved against the supplied contact phone/channel. Used by the composer to preview the final message."
      tags:
        - "User"
        - "Templates"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "templateId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UserGetTemplateWithDataRequest"
      responses:
        "200":
          description: "Resolved template returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserResolvedTemplateResponse"
        "404":
          description: "Template not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
    put:
      operationId: "put_user_sms_template"
      summary: "Update an SMS template"
      description: "Updates name, body, type, or category on a template the authenticated user owns (or any template, for admins). At least one field must be supplied."
      tags:
        - "User"
        - "Templates"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "templateId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UserUpdateSmsTemplateRequest"
      responses:
        "200":
          description: "Template updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSmsTemplateDocument"
        "400":
          description: "At least one field is required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "404":
          description: "Template not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
    delete:
      operationId: "delete_user_sms_template"
      summary: "Delete an SMS template"
      description: "Deletes a template owned by the authenticated user (or any template, for admins). Returns 403 if the caller does not own the template."
      tags:
        - "Users"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "templateId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Template deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSmsTemplateDeleteResponse"
        "400":
          description: "Invalid template id"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "404":
          description: "Template not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "500":
          description: "Failed to delete template"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
  "/api/user/sms-templates/by-type/{type}":
    get:
      operationId: "get_user_sms_templates_by_type"
      summary: "Get templates filtered by type"
      description: "Returns templates of a single type (sms, campaign, script, automation) visible to the authenticated user."
      tags:
        - "Users"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "type"
          required: true
          schema:
            type: "string"
            enum:
              - "sms"
              - "campaign"
              - "script"
              - "automation"
      responses:
        "200":
          description: "Templates returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSmsTemplateListResponse"
        "400":
          description: "Invalid template type"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "404":
          description: "Templates not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "500":
          description: "Failed to fetch templates"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
  "/api/user/template-categories":
    get:
      operationId: "get_user_template_categories"
      summary: "Get all template categories"
      description: "Returns the catalog of template categories used to group SMS, campaign, script, and automation templates."
      tags:
        - "Users"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Categories returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserTemplateCategoryListResponse"
        "400":
          description: "Invalid request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "500":
          description: "Failed to fetch categories"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
    post:
      operationId: "post_user_template_categories"
      summary: "Create a template category (superadmin)"
      description: "Creates a new template category used to group SMS/campaign/script/automation templates. Superadmin only. Category names must be unique."
      tags:
        - "User"
        - "Templates"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UserCreateTemplateCategoryRequest"
      responses:
        "201":
          description: "Category created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserTemplateCategoryDocument"
        "400":
          description: "Validation error or name exists"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "403":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
  "/api/user/template-categories/{id}":
    put:
      operationId: "put_user_template_category"
      summary: "Update a template category (superadmin)"
      description: "Updates a template category fields (displayName, description, color, isActive). Superadmin only. Returns 400 if the new name conflicts with another category."
      tags:
        - "User"
        - "Templates"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UserUpdateTemplateCategoryRequest"
      responses:
        "200":
          description: "Category updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserTemplateCategoryDocument"
        "400":
          description: "Category name already exists"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "403":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "404":
          description: "Category not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
    delete:
      operationId: "delete_user_template_category"
      summary: "Delete a template category (superadmin)"
      description: "Deletes a template category. Superadmin only. Returns 403 for non-superadmin callers."
      tags:
        - "Users"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Category deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserTemplateCategoryDeleteResponse"
        "400":
          description: "Invalid category id"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "403":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "404":
          description: "Category not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "500":
          description: "Failed to delete category"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
  "/api/user/template-categories/reorder":
    post:
      operationId: "post_user_template_categories_reorder"
      summary: "Reorder template categories (superadmin)"
      description: "Updates the sortOrder of template categories to match the supplied id array (first id becomes sortOrder 0). Superadmin only."
      tags:
        - "User"
        - "Templates"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UserReorderTemplateCategoriesRequest"
      responses:
        "200":
          description: "Categories reordered"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserSimpleMessageResponse"
        "400":
          description: "categoryIds must be an array"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
        "403":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UserErrorResponse"
  "/api/vault":
    get:
      operationId: "get_vault"
      summary: "List all vault secret names"
      description: "Returns the names of every secret stored in WorkOS Vault for the caller's organization. Values are never returned by the list endpoint. Requires WorkOS to be enabled on the deployment."
      tags:
        - "Vault"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Secret names returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/VaultListResponse"
        "400":
          description: "WorkOS is not enabled"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/VaultErrorResponse"
    post:
      operationId: "post_vault"
      summary: "Create a new vault secret"
      description: "Create a new WorkOS Vault secret scoped to the caller's organization. Returns 409 if a secret with the same name already exists - use `/api/vault/upsert` for create-or-update semantics."
      tags:
        - "Vault"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/VaultCreateSecretRequest"
      responses:
        "201":
          description: "Secret created successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/VaultMutationResponse"
        "400":
          description: "Validation error or WorkOS not enabled"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/VaultErrorResponse"
        "409":
          description: "Secret already exists"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/VaultErrorResponse"
  "/api/vault/{secretName}":
    put:
      operationId: "put_vault_by_name"
      summary: "Update an existing vault secret"
      description: "Update the value of an existing vault secret identified by name. Returns 404 when the secret does not exist; the upsert endpoint should be used to handle that case implicitly."
      tags:
        - "Vault"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "secretName"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/VaultUpdateSecretRequest"
      responses:
        "200":
          description: "Secret updated successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/VaultMutationResponse"
        "400":
          description: "Validation error or WorkOS not enabled"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/VaultErrorResponse"
        "404":
          description: "Secret does not exist"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/VaultErrorResponse"
    delete:
      operationId: "delete_vault_by_name"
      summary: "Delete a vault secret"
      description: "Permanently delete a vault secret by name. Deletion is idempotent - calling against a non-existent secret still returns 200 success."
      tags:
        - "Vault"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "secretName"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/VaultDeleteSecretRequest"
      responses:
        "200":
          description: "Secret deleted successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/VaultDeleteResponse"
        "400":
          description: "WorkOS organization ID required or WorkOS not enabled"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/VaultErrorResponse"
  "/api/vault/upsert":
    post:
      operationId: "post_vault_upsert"
      summary: "Create or update a vault secret"
      description: "Idempotent variant of secret creation - updates the value when `name` already exists, otherwise creates it. Used by automated flows where the caller does not know whether the secret already exists."
      tags:
        - "Vault"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/VaultUpsertSecretRequest"
      responses:
        "200":
          description: "Secret saved successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/VaultMutationResponse"
        "400":
          description: "Validation error or WorkOS not enabled"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/VaultErrorResponse"
  "/api/vertical":
    get:
      operationId: "get_vertical"
      summary: "Get the current vertical (public)"
      description: "Returns the single configured vertical. When no vertical has been created yet, a default fallback (`{ name: \"TetherAI\" }`) is returned with 200 so frontends can render branding before initial setup."
      tags:
        - "Vertical"
      responses:
        "200":
          description: "Vertical returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/VerticalGetResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/VerticalErrorResponse"
    post:
      operationId: "post_vertical"
      summary: "Create a vertical (public, only one allowed)"
      description: "Bootstrap the single vertical record for this deployment. Public (no auth) because it runs once during initial install; returns 400 if a vertical already exists."
      tags:
        - "Vertical"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/VerticalCreateRequest"
      responses:
        "201":
          description: "Vertical created successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/VerticalMutationResponse"
        "400":
          description: "Name is required or vertical already exists"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/VerticalErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/VerticalErrorResponse"
  "/api/webchats":
    get:
      operationId: "get_webchats"
      summary: "List all webchat configurations"
      description: "List every webchat widget configured for the caller's organization, newest-first. Icon fields are returned as freshly-signed R2 URLs."
      tags:
        - "Webchats"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Webchat configurations returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatListResponse"
        "500":
          description: "Failed to fetch webchat configurations"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatErrorResponse"
    post:
      operationId: "post_webchats"
      summary: "Create webchat configuration"
      description: "Create a new webchat widget configuration. `allowedDomains` restricts the embed origins; `promptId` selects which Prompt the agent uses for AI responses on inbound visitor messages."
      tags:
        - "Webchats"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CreateWebchatRequest"
      responses:
        "201":
          description: "Webchat configuration created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatMutationResponse"
        "400":
          description: "Missing required fields"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatErrorResponse"
        "500":
          description: "Failed to create webchat configuration"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatErrorResponse"
  "/api/webchats/{id}":
    get:
      operationId: "get_webchat_by_id"
      summary: "Get webchat configuration by id"
      description: "Fetch a single webchat configuration by `_id`. Used by the widget management UI."
      tags:
        - "Webchats"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Webchat configuration returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatSingleResponse"
        "400":
          description: "Webchat ID is required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatErrorResponse"
        "404":
          description: "Webchat configuration not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatErrorResponse"
        "500":
          description: "Failed to fetch webchat configuration"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatErrorResponse"
    put:
      operationId: "put_webchat"
      summary: "Update webchat configuration"
      description: "Update mutable fields on a webchat widget. `icon` accepts an empty string or null to clear the configured icon."
      tags:
        - "Webchats"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateWebchatRequest"
      responses:
        "200":
          description: "Webchat configuration updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatMutationResponse"
        "400":
          description: "Invalid input"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatErrorResponse"
        "404":
          description: "Webchat configuration not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatErrorResponse"
        "500":
          description: "Failed to update webchat configuration"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatErrorResponse"
    delete:
      operationId: "delete_webchat"
      summary: "Delete webchat configuration"
      description: "Permanently delete a webchat configuration. Existing conversations created via this widget keep their `webchatConfigId` reference but no new sessions can start."
      tags:
        - "Webchats"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Webchat configuration deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatMessageResponse"
        "400":
          description: "Webchat ID is required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatErrorResponse"
        "404":
          description: "Webchat configuration not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatErrorResponse"
        "500":
          description: "Failed to delete webchat configuration"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatErrorResponse"
  "/api/webchats/{id}/icon-source":
    get:
      operationId: "get_api_webchats_id_icon_source"
      summary: "GET /api/webchats/{id}/icon-source"
      tags:
        - "Webchats"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/webchats/superadmin/all":
    get:
      operationId: "get_api_webchats_superadmin_all"
      summary: "GET /api/webchats/superadmin/all"
      tags:
        - "Webchats"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/webchats/superadmin/debug":
    get:
      operationId: "get_api_webchats_superadmin_debug"
      summary: "GET /api/webchats/superadmin/debug"
      tags:
        - "Webchats"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/webhook":
    post:
      operationId: "post_webhook"
      summary: "Handle inbound SMS webhook (Sinch)"
      description: "Inbound webhook called by Sinch when an SMS is delivered to a Tether-provisioned number. Responds 200 immediately to prevent Sinch retries and processes the message asynchronously (contact upsert, conversation routing, automation triggering, AI reply pipeline)."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/SmsWebhookRequest"
      responses:
        "200":
          description: "Webhook accepted (immediate ack - processing continues async)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SmsWebhookAckResponse"
        "500":
          description: "Webhook processing failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/calls/sinch":
    post:
      operationId: "post_webhook_calls_sinch"
      summary: "Handle Sinch voice call webhook"
      description: "Inbound voice call webhook posted by Sinch for ICE (Incoming Call Event), ACE (Answered Call Event), and DiCE (Disconnect Event). For ICE the endpoint returns SVAML instructing Sinch how to route/record the call; for ACE and DiCE it updates the Call record and acknowledges receipt."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/SinchCallWebhookRequest"
      responses:
        "200":
          description: "SVAML response. For Incoming Call Event (ICE) the body carries a routing `action` (`connectConf`, `hangup`, etc.); for ACE/DiCE the body is empty."
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SinchCallWebhookSvamlResponse"
        "500":
          description: "Call webhook processing failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/calls/twilio":
    post:
      operationId: "post_webhook_calls_twilio"
      summary: "Handle Twilio voice call webhook (legacy)"
      description: "Legacy catch-all Twilio voice webhook retained for backwards compatibility. Acknowledges with 200 and forwards the payload to the calls service for status processing - new integrations should target the specific /api/webhook/calls/twilio/{inbound,outbound,status,recording,amd} routes instead."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/TwilioCallWebhookRequest"
      responses:
        "200":
          description: "Plain-text acknowledgement. New integrations should use the typed inbound/outbound/status/recording/amd routes instead."
          content:
            "text/plain":
              schema:
                type: "string"
                example: "OK"
        "500":
          description: "Call webhook processing failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/calls/twilio/amd":
    post:
      operationId: "post_webhook_calls_twilio_amd"
      summary: "Handle Twilio answering machine detection"
      description: "AMD callback posted by Twilio with the AnsweredBy classification (human, machine_start, machine_end_beep, machine_end_silence, fax, unknown). Stamps the result on the Call record and may trigger a voicemail-drop or missed-call follow-up depending on automation settings."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/TwilioAmdStatusRequest"
      responses:
        "200":
          description: "Plain-text acknowledgement (Twilio only checks 2xx)."
          content:
            "text/plain":
              schema:
                type: "string"
                example: "OK"
        "500":
          description: "AMD processing failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/calls/twilio/inbound":
    post:
      operationId: "post_webhook_calls_twilio_inbound"
      summary: "Handle Twilio inbound PSTN call"
      description: "Inbound PSTN webhook called by Twilio when a customer dials a Tether-provisioned Twilio number. Resolves the owning org/user, creates a Call record, and returns TwiML that dials the browser client (or the ElevenLabs voice agent when AI calling is enabled)."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/TwilioInboundCallRequest"
      responses:
        "200":
          description: "TwiML response. Dials the agent's browser client (or, when AI calling is enabled, the configured ElevenLabs agent number)."
          content:
            "application/xml":
              schema:
                type: "string"
              example: "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response><Dial answerOnBridge=\"true\" record=\"record-from-answer\" recordingStatusCallback=\"/api/webhook/calls/twilio/recording\" recordingStatusCallbackMethod=\"POST\"><Client statusCallback=\"/api/webhook/calls/twilio/status\" statusCallbackMethod=\"POST\" statusCallbackEvent=\"initiated,ringing,answered,completed\">client_64a1b2c3d4e5f60012345679</Client></Dial></Response>"
        "500":
          description: "Call processing failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/calls/twilio/outbound":
    post:
      operationId: "post_webhook_calls_twilio_outbound"
      summary: "Handle Twilio outbound browser call"
      description: "Outbound voice webhook hit when an agent's browser device.connect() places a call. Validates the from/to numbers, creates the outbound Call record, and returns TwiML that bridges the browser leg to the PSTN destination."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/TwilioOutboundCallRequest"
      responses:
        "200":
          description: "TwiML response. Bridges the browser leg to the PSTN destination with answering-machine detection and recording enabled."
          content:
            "application/xml":
              schema:
                type: "string"
              example: "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response><Dial callerId=\"+12362320246\" record=\"record-from-answer\" recordingStatusCallback=\"/api/webhook/calls/twilio/recording\" recordingStatusCallbackMethod=\"POST\" answerOnBridge=\"true\"><Number statusCallback=\"/api/webhook/calls/twilio/status\" statusCallbackMethod=\"POST\" statusCallbackEvent=\"initiated,ringing,answered,completed\" machineDetection=\"Enable\" machineDetectionTimeout=\"30\" machineDetectionSpeechThreshold=\"2400\" machineDetectionSpeechEndThreshold=\"1200\" machineDetectionSilenceTimeout=\"5000\" amdStatusCallback=\"/api/webhook/calls/twilio/amd\" amdStatusCallbackMethod=\"POST\">+14165550100</Number></Dial></Response>"
        "500":
          description: "Call processing failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/calls/twilio/recording":
    post:
      operationId: "post_webhook_calls_twilio_recording"
      summary: "Handle Twilio recording status"
      description: "Recording-completed callback posted by Twilio once a call recording finishes. Downloads the audio from the Twilio recording URL, uploads it to R2, and attaches the storage key + duration to the parent Call record."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/TwilioRecordingStatusRequest"
      responses:
        "200":
          description: "Plain-text acknowledgement (Twilio only checks 2xx)."
          content:
            "text/plain":
              schema:
                type: "string"
                example: "OK"
        "500":
          description: "Recording processing failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/calls/twilio/status":
    post:
      operationId: "post_webhook_calls_twilio_status"
      summary: "Handle Twilio call status updates"
      description: "Status callback posted by Twilio as a call transitions through queued / ringing / in-progress / completed / busy / no-answer / failed. Updates the Call record with final status, duration, and end timestamp and emits a socket event so the agent UI reflects the change."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/TwilioCallStatusRequest"
      responses:
        "200":
          description: "Plain-text acknowledgement (Twilio only checks 2xx)."
          content:
            "text/plain":
              schema:
                type: "string"
                example: "OK"
        "500":
          description: "Status processing failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/elevenlabs":
    post:
      operationId: "post_webhook_elevenlabs"
      summary: "Handle ElevenLabs post-call webhook"
      description: "Inbound webhook called by ElevenLabs after a voice AI call completes. Dispatches by `type`: `post_call_transcription` creates the Call record and AI summary note, `post_call_audio` uploads the recording, `call_initiation_failure` records a missed/failed call and optionally fires a missed-call auto-SMS. Authenticated via HMAC signature (`elevenlabs-signature` header) or Bearer token (per-org `elevenlabsToolSecret`)."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ElevenLabsPostCallWebhookRequest"
      responses:
        "200":
          description: "Event processed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ElevenLabsPostCallWebhookResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/elevenlabs/personalization":
    post:
      operationId: "post_webhook_elevenlabs_personalization"
      summary: "Handle ElevenLabs pre-call personalization webhook"
      description: "Inbound webhook called by ElevenLabs when a call connects so the AI agent can greet the caller by name. Looks up the contact by caller_id, caches the call context in Redis (24h TTL) for the post-call webhook, and returns dynamic variables for prompt injection. Authenticated via Bearer token (per-org `elevenlabsToolSecret`)."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ElevenLabsPersonalizationRequest"
      responses:
        "200":
          description: "Personalization variables returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ElevenLabsPersonalizationResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/elevenlabs/tools/agent-state":
    post:
      operationId: "post_api_webhook_elevenlabs_tools_agent_state"
      summary: "POST /api/webhook/elevenlabs/tools/agent-state"
      tags:
        - "Webhook"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
  "/api/webhook/elevenlabs/tools/check-availability":
    post:
      operationId: "post_webhook_elevenlabs_tools_check_availability"
      summary: "ElevenLabs tool: check human agent availability"
      description: "Server tool webhook called by the ElevenLabs voice agent mid-call to check whether any human agents in the organization are currently online and chat-available. Authenticated via Bearer token (per-org `elevenlabsToolSecret`)."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ElevenLabsToolCallRequest"
      responses:
        "200":
          description: "Agent availability"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ElevenLabsCheckAvailabilityResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/elevenlabs/tools/check-business-hours":
    post:
      operationId: "post_webhook_elevenlabs_tools_check_business_hours"
      summary: "ElevenLabs tool: check business hours"
      description: "Server tool webhook called by the ElevenLabs voice agent mid-call to check whether the organization is currently within business hours (default Mon-Fri 9am-5pm in the org timezone). Authenticated via Bearer token (per-org `elevenlabsToolSecret`)."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ElevenLabsToolCallRequest"
      responses:
        "200":
          description: "Business hours status"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ElevenLabsCheckBusinessHoursResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/elevenlabs/tools/create-note":
    post:
      operationId: "post_webhook_elevenlabs_tools_create_note"
      summary: "ElevenLabs tool: save a mid-call note to the contact"
      description: "Server tool webhook called by the ElevenLabs voice agent mid-call to persist a free-form note on the caller's contact. Identifies the contact by `phone_number` within the org scoped from the tool secret. The note is stored as a `ContactNote` with `type: 'ai_summary'` so the contact timeline can distinguish AI-authored notes from human ones, and emits the same `note_created` socket event as the manual flow so live UIs update in real time. Per ElevenLabs convention, recoverable problems return HTTP 200 with `success:false`. Authenticated via Bearer token (per-org `elevenlabsToolSecret`)."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ElevenLabsCreateNoteRequest"
      responses:
        "200":
          description: "Note creation result. Inspect `success`."
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ElevenLabsCreateNoteResponse"
        "401":
          description: "Unauthorized - missing or invalid tool secret"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/elevenlabs/tools/escalate":
    post:
      operationId: "post_api_webhook_elevenlabs_tools_escalate"
      summary: "POST /api/webhook/elevenlabs/tools/escalate"
      tags:
        - "Webhook"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
  "/api/webhook/elevenlabs/tools/get-contact":
    post:
      operationId: "post_webhook_elevenlabs_tools_get_contact"
      summary: "ElevenLabs tool: lookup contact by phone number"
      description: "Server tool webhook called by the ElevenLabs voice agent mid-call to look up a contact by phone number within the calling organization. Authenticated via Bearer token (per-org `elevenlabsToolSecret`)."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ElevenLabsGetContactRequest"
      responses:
        "200":
          description: "Contact lookup result"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ElevenLabsGetContactResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/elevenlabs/tools/send-sms":
    post:
      operationId: "post_webhook_elevenlabs_tools_send_sms"
      summary: "ElevenLabs tool: send an SMS to the caller mid-call"
      description: "Server tool webhook called by the ElevenLabs voice agent mid-call to text the caller a link, confirmation, or follow-up info while the call is still active. Identifies the contact by `phone_number` within the org scoped from the tool secret and sends as the agent, in the contact's SMS thread on the chosen line (created if needed, assigned to the line's owner). The line is the first of: the line the call is on (`conversation_id`), the one usable SMS line the agent answers on (`agent_id`), the line of the contact's most recent SMS thread, the org default line. Dispatches through the standard `sendOutboundMessage` helper so it routes via the org's configured SMS provider (Sinch / TextGrid / Twilio) and appears in the conversation thread as an AI-authored message. The send is marked `skipAutomation` so it doesn't retrigger workflows in a loop. Recoverable problems return HTTP 200 with `success:false`. Authenticated via Bearer token (per-org `elevenlabsToolSecret`)."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ElevenLabsSendSmsRequest"
      responses:
        "200":
          description: "SMS send result. Inspect `success`."
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ElevenLabsSendSmsResponse"
        "401":
          description: "Unauthorized - missing or invalid tool secret"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/elevenlabs/tools/transfer":
    post:
      operationId: "post_webhook_elevenlabs_tools_transfer"
      summary: "ElevenLabs tool: transfer call to human agent (stub)"
      description: "Server tool webhook called by the ElevenLabs voice agent mid-call when the caller requests a transfer. Currently a stub - real Sinch SIP REFER implementation lands in a follow-up. Authenticated via Bearer token (per-org `elevenlabsToolSecret`)."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ElevenLabsTransferRequest"
      responses:
        "200":
          description: "Transfer outcome"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ElevenLabsTransferResponse"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/elevenlabs/tools/update-contact":
    post:
      operationId: "post_webhook_elevenlabs_tools_update_contact"
      summary: "ElevenLabs tool: update contact fields mid-call"
      description: "Server tool webhook called by the ElevenLabs voice agent mid-call to correct or enrich a caller's contact record - typically when the caller spells their name or gives a new email. Identifies the contact by `phone_number` within the org scoped from the tool secret; at least one of `first_name`/`last_name`/`email` must be supplied. Phone number itself is intentionally NOT updatable here (would require de-dupe + verification flow). New emails are appended to the contact's `email[]` array (preserving history) and become primary if no primary exists yet. Per ElevenLabs convention, recoverable problems (missing fields, contact not found) return HTTP 200 with `success:false` so the agent can speak the error to the caller. Authenticated via Bearer token (per-org `elevenlabsToolSecret`)."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ElevenLabsUpdateContactRequest"
      responses:
        "200":
          description: "Update result. Inspect `success` to disambiguate applied update vs. recoverable error."
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ElevenLabsUpdateContactResponse"
        "401":
          description: "Unauthorized - missing or invalid tool secret"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/elevenlabs/tools/workflow/{workflowId}":
    post:
      operationId: "post_api_webhook_elevenlabs_tools_workflow_workflowId"
      summary: "POST /api/webhook/elevenlabs/tools/workflow/{workflowId}"
      tags:
        - "Webhook"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "workflowId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
  "/api/webhook/elevenlabs/tools/workflow/{workflowId}/{toolName}":
    post:
      operationId: "post_api_webhook_elevenlabs_tools_workflow_workflowId_toolName"
      summary: "POST /api/webhook/elevenlabs/tools/workflow/{workflowId}/{toolName}"
      tags:
        - "Webhook"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "workflowId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "toolName"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
  "/api/webhook/email/gmail":
    post:
      operationId: "post_webhook_email_gmail"
      summary: "Gmail Pub/Sub push webhook"
      description: "Receives Gmail Pub/Sub push notifications. The relay decodes the base64 payload, looks up the matching `EmailAccount` by history id, and triggers an incremental sync. Public endpoint - auth is enforced by the Pub/Sub OIDC token, not bearer JWT."
      tags:
        - "Email"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/EmailWebhookRequest"
      responses:
        "200":
          description: "Plain-text acknowledgement. The body is the literal text `OK`; Pub/Sub only checks the 2xx status to mark the push delivery as acknowledged."
          content:
            "text/plain":
              schema:
                type: "string"
                example: "OK"
        "500":
          description: "Webhook processing failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
  "/api/webhook/email/outlook":
    post:
      operationId: "post_webhook_email_outlook"
      summary: "Handle Outlook (Microsoft Graph) change notification"
      description: "Inbound webhook called by Microsoft Graph when a subscribed mailbox receives a new message. On subscription creation Graph performs a validation handshake by sending a `validationToken` query parameter, which the endpoint echoes back as plain text. Notification payloads are accepted with 202 and processed asynchronously."
      tags:
        - "Webhooks"
      parameters:
        -
          in: "query"
          name: "validationToken"
          required: false
          schema:
            type: "string"
          description: "Sent by Microsoft Graph during subscription validation. When present the endpoint echoes it back as text/plain and skips notification processing."
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/OutlookWebhookRequest"
      responses:
        "200":
          description: "Validation handshake - the supplied `validationToken` is echoed back as plain text."
          content:
            "text/plain":
              schema:
                type: "string"
              example: "A1B2C3D4-E5F6-7890-ABCD-EF1234567890"
        "202":
          description: "Notification accepted for async processing. Body is the literal text `Accepted`."
          content:
            "text/plain":
              schema:
                type: "string"
              example: "Accepted"
        "500":
          description: "Webhook processing failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/inbox-drop":
    post:
      operationId: "post_webhook_inbox_drop"
      summary: "Inbox Drop ingress - inbound email payload from provider adapter"
      description: "Inbox Drop ingress that receives a parsed inbound email payload from a provider-specific adapter (today: the `sendgrid-inbound` service). The api evaluates which workflows' `InboxDropTrigger` nodes match the email's `subject`/`from` filters and enqueues one BullMQ job per match. **Auth is the shared `INTERNAL_SERVICE_TOKEN` via the `X-Internal-Token` header - NOT user auth.** Adapter services hold this token; external callers must not hit this endpoint directly. Returns 202 with `matchedCount` so the caller can decide whether to fall back to a non-workflow path when no workflow matched."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/InboxDropRequest"
      responses:
        "202":
          description: "Inbound email accepted and matching workflows enqueued"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/InboxDropResponse"
        "400":
          description: "Missing organizationId/emailData, or invalid email fields"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/InboxDropValidationErrorResponse"
        "401":
          description: "INTERNAL_SERVICE_TOKEN not configured server-side"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
        "403":
          description: "Internal service token mismatch"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/mms":
    post:
      operationId: "post_webhook_mms"
      summary: "Handle inbound MMS webhook (Sinch)"
      description: "Inbound webhook called by the Sinch MMS JSON API when an MMS is delivered to a Tether-provisioned number. Acknowledges within 10 seconds and processes asynchronously: media is downloaded and re-uploaded to R2, then the message is appended to the contact's conversation."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/MmsWebhookRequest"
      responses:
        "200":
          description: "Webhook accepted (immediate ack - processing continues async)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MmsWebhookAckResponse"
        "500":
          description: "Webhook processing failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/notification-sound":
    get:
      operationId: "get_webhook_notification_sound"
      summary: "Get notification sound file"
      description: "Public endpoint serving the default notification MP3 used by the webchat widget and the agent client to chirp on new messages. Falls back to an inline base64 beep when the static file is unreachable so the client never sees a broken sound URL."
      tags:
        - "Webhooks"
      responses:
        "200":
          description: "MP3 audio file returned with `Content-Type: audio/mpeg`. When the static asset is unreachable the endpoint serves an inline base64-encoded fallback beep - the response is still a valid MP3 but very short (~1 KB)."
          content:
            "audio/mpeg":
              schema:
                type: "string"
                format: "binary"
                description: "Binary MP3 stream. Roughly 12 KB for the default sound; ~1 KB for the inline fallback beep."
                example: "<binary: MP3 audio stream - Content-Type: audio/mpeg, ~12 KB>"
        "404":
          description: "Sound file not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookAssetErrorResponse"
  "/api/webhook/outreach":
    post:
      operationId: "post_webhook_outreach"
      summary: "Handle outreach webhook (backwards compatibility)"
      description: "Backwards-compatible alias that proxies to the outreach trigger handler. Authenticated via API key. New integrations should call the canonical `/api/outreach/trigger` endpoint directly; this route is kept so older customer integrations continue to work."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/OutreachWebhookRequest"
      responses:
        "200":
          description: "Outreach processed. Same shape as `POST /api/outreach` - the legacy webhook route is a thin alias."
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OutreachTriggerResponse"
        "400":
          description: "Validation error (missing configurationId, no contact data, etc.)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
        "401":
          description: "No API key provided"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
        "404":
          description: "Configuration or contact not found for this API key"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
        "500":
          description: "Outreach processing failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/sinch/delivery-receipt":
    post:
      operationId: "post_webhook_sinch_delivery_receipt"
      summary: "Handle Sinch SMS delivery receipt"
      description: "Status callback posted by Sinch for outbound SMS batches. An SMS stored as a conversation Message carries that Message id as `client_reference` when it goes out through Sinch (on each batch of a send split for media). Each status is applied to the one Message it is about, and a socket event is broadcast so the org's connected clients see the new status. The Message is found by `client_reference` when it names a Message of the batch, then by `batch_id` when one Message has it, then by `batch_id` and recipient (matched through the contact's phone). A report that still matches more than one Message is logged and skipped, and a report without `batch_id` is ignored."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/SinchDeliveryReceiptRequest"
      responses:
        "200":
          description: "Receipt processed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SinchDeliveryReceiptAckResponse"
        "500":
          description: "Receipt processing failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/sinch/mms-delivery-receipt":
    post:
      operationId: "post_webhook_sinch_mms_delivery_receipt"
      summary: "Handle Sinch MMS delivery receipt"
      description: "Status callback posted by the Sinch MMS JSON API for outbound MMS batches. Handles N101 (Sent), N102 (Delivered), N103 (Expired), E101 (Sending Failure), and E102 (Delivery Failure) codes by updating the Message and emitting a socket event to the org."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/MmsDeliveryReceiptRequest"
      responses:
        "200":
          description: "Receipt processed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/SinchMmsDeliveryReceiptAckResponse"
        "500":
          description: "Receipt processing failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/textgrid/sms":
    post:
      operationId: "post_webhook_textgrid_sms"
      summary: "Handle inbound SMS/MMS webhook (TextGrid)"
      description: "Inbound webhook called by TextGrid when an SMS or MMS is delivered to a Tether-provisioned number. Payload shape matches Twilio (AccountSid, MessageSid, Body, From, To, NumMedia, MediaUrl*). Responds with empty TwiML."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/TextGridInboundSmsRequest"
      responses:
        "200":
          description: "Empty TwiML response acknowledging receipt. TextGrid persists the message + drives automation server-side; no TwiML is returned to the caller."
          content:
            "application/xml":
              schema:
                type: "string"
              example: "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response></Response>"
  "/api/webhook/textgrid/sms-status":
    post:
      operationId: "post_webhook_textgrid_sms_status"
      summary: "Handle TextGrid SMS delivery status callback"
      description: "Status callback called by TextGrid for delivered/undelivered messages. Updates the corresponding Message document and broadcasts a socket event to the organization."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/TextGridSmsStatusRequest"
      responses:
        "200":
          description: "Plain-text acknowledgement (TextGrid only checks 2xx)."
          content:
            "text/plain":
              schema:
                type: "string"
                example: "OK"
  "/api/webhook/twilio/sms":
    post:
      operationId: "post_webhook_twilio_sms"
      summary: "Handle inbound SMS webhook (Twilio)"
      description: "Inbound webhook called by Twilio when an SMS or MMS is delivered to a Tether-provisioned Twilio number. Persists the message and any attached media, drives automation/AI replies, and responds with empty TwiML."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/TwilioInboundSmsRequest"
      responses:
        "200":
          description: "Empty TwiML response acknowledging receipt. Tether handles persistence + automation server-side; Twilio expects empty TwiML."
          content:
            "application/xml":
              schema:
                type: "string"
              example: "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response></Response>"
        "500":
          description: "Webhook processing failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/twilio/sms-status":
    post:
      operationId: "post_webhook_twilio_sms_status"
      summary: "Handle Twilio SMS status callback"
      description: "Status callback posted by Twilio for outbound SMS/MMS as the message transitions through queued / sent / delivered / failed. Updates the corresponding Message document and broadcasts a socket event so the org sees the latest delivery state."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/TwilioSmsStatusRequest"
      responses:
        "200":
          description: "Plain-text acknowledgement (Twilio only checks the 2xx status)."
          content:
            "text/plain":
              schema:
                type: "string"
                example: "OK"
        "500":
          description: "Status processing failed"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/webhook/webchat":
    post:
      operationId: "post_webhook_webchat"
      summary: "Handle inbound webchat message"
      description: "Inbound webhook called by the webchat socket server (on behalf of the embedded widget) when a visitor sends a message. Validates the configured webchatConfigId, upserts the visitor as a contact, and persists the message + any attachments. For a customer message the response is sent only once the message is stored or definitively refused: 2xx means the Message row exists, 4xx means it never will be stored. Two responses fall outside that guarantee: a page-context system emit (isSystemContext) is answered 2xx as \"handled\" and implies no row, and a replay that arrives while the first attempt for the same clientMessageId is still being stored is answered 503 ingest_in_progress before that attempt resolves. 5xx responses carry a `retryable` flag that callers must check before retrying (`not_persisted` is a 500 that is NOT retryable; `ingest_in_progress` is a 503 that is). Sends carrying a `clientMessageId` are idempotent per webchat session: a replay that finds the row already stored answers with it and `duplicate: true`."
      tags:
        - "Webhooks"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/WebchatWebhookRequest"
      responses:
        "200":
          description: "Message stored (or, for page-context system emits, handled)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatWebhookAckResponse"
        "400":
          description: "Missing required fields"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
        "403":
          description: "Contact is blocked; message not stored (code contact_blocked). IP blocks are enforced by the webchat socket server before this endpoint is reached. A merge target found blocked by extraction is discovered only after the message is stored and acknowledged, so it never produces this response."
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatWebhookRefusedResponse"
        "404":
          description: "Webchat configuration or its owner not found (code webchat_config_not_found / user_not_found)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatWebhookRefusedResponse"
        "409":
          description: "Conversation already resolved; a webchat never reopens, message not stored (code conversation_resolved)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatWebhookRefusedResponse"
        "422":
          description: "Page-context system emit rejected (code page_context_disabled / page_context_rejected)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatWebhookRefusedResponse"
        "500":
          description: "Processing failed before the message was stored (code internal_error is retryable; not_persisted is not)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatWebhookRefusedResponse"
        "503":
          description: "Another attempt for the same clientMessageId is being stored right now; retry shortly (code ingest_in_progress, retryable)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebchatWebhookRefusedResponse"
  "/api/webhook/webchat-icon-url":
    get:
      operationId: "get_api_webhook_webchat_icon_url"
      summary: "GET /api/webhook/webchat-icon-url"
      tags:
        - "Webhook"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
  "/api/webhook/webchat-script":
    get:
      operationId: "get_webhook_webchat_script"
      summary: "Get webchat embed script"
      description: "Public endpoint returning the JavaScript webchat widget loader with the resolved configuration (colors, position, starter message, etc.) inlined. Used by the `<script src=\"…webchat-script?webchatConfigId=…\">` tag a customer pastes onto their site."
      tags:
        - "Webhooks"
      parameters:
        -
          in: "query"
          name: "webchatConfigId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "JavaScript embed script with the resolved webchat configuration inlined."
          content:
            "application/javascript":
              schema:
                type: "string"
              example: "(function(){var w=window,d=document,c={webchatConfigId:\"64a1b2c3d4e5f60012345678\",primaryColor:\"#3B82F6\",position:\"bottom-right\",starterMessage:\"Hi! How can we help?\",apiBaseUrl:\"https://api.tetherai.ca\"};w.__TETHER_WEBCHAT__=c;var s=d.createElement(\"script\");s.src=c.apiBaseUrl+\"/static/webchat-runtime.js\";s.async=true;d.head.appendChild(s);})();"
        "400":
          description: "webchatConfigId is required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookAssetErrorResponse"
        "404":
          description: "Webchat configuration not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookAssetErrorResponse"
  "/api/webhook/workflow":
    post:
      operationId: "post_webhook_workflow"
      summary: "Workflow engine webhook ingress"
      description: "Generic webhook ingress for WorkflowEngine `WebhookTrigger` nodes. Auth is JWT or User API key in the `Authorization: Bearer <token>` header. The API key is a **user-level** key, resolved against the `User` record and scoped to that user's organization. It is not a per-workflow secret, even though it is surfaced in the workflow builder next to the webhook id. The body must include a `webhookId` string that matches one or more `WebhookTrigger.data.webhookId` values for workflows in the caller's organization; everything else in the body is forwarded verbatim as the trigger node's `payload` output, so the body is flat and there is no nested `payload` key to send. The api validates auth, evaluates matching triggers, and enqueues one BullMQ job per match (workflows themselves execute on the workflow-runner service). Returns 202 with the `matchedCount` so the caller can tell whether any workflow was actually queued."
      tags:
        - "Webhooks"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/WorkflowWebhookIngressRequest"
      responses:
        "202":
          description: "Webhook accepted and matching workflows enqueued"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowWebhookIngressResponse"
        "400":
          description: "Body missing `webhookId` string"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
        "401":
          description: "Authentication required (JWT or User API key)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WebhookErrorResponse"
  "/api/workflows":
    get:
      operationId: "get_workflows"
      summary: "Get all workflows for the organization"
      description: "Returns every Workflow in the caller organization, sorted by `createdAt` desc. Each workflow includes its node/edge canvas, viewport, enabled flag, creator metadata and `folderId` (null or absent = top level). `folderId` narrows the list to one folder; `search` matches the start of words in the name or description across every folder."
      tags:
        - "Workflows"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "folderId"
          required: false
          schema:
            type: "string"
          description: "`root` lists workflows outside any folder (including ones that predate folders); a folder id lists only that folder. Omit for every folder."
        -
          in: "query"
          name: "search"
          required: false
          schema:
            type: "string"
            maxLength: 200
          description: "Every word must start a word of the name, or every word must start a word of the description (case- and accent-insensitive; camelCase and letter/digit parts count as words). Served by an index. Searches all folders."
      responses:
        "200":
          description: "Workflows list returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsListResponse"
        "400":
          description: "Organization ID is required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
    post:
      operationId: "post_workflows"
      summary: "Create a new workflow"
      description: "Creates a new Workflow owned by the caller user and organization. Stores the visual builder canvas (nodes + edges + viewport) and metadata. Names must be unique within the organization."
      tags:
        - "Workflows"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/WorkflowCreateRequest"
      responses:
        "201":
          description: "Workflow created successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowMutationResponse"
        "400":
          description: "Validation error or duplicate name"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
        "409":
          description: "Stable command key was already used with a different payload"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowConflictResponse"
  "/api/workflows/{id}":
    get:
      operationId: "get_workflows_by_id"
      summary: "Get a specific workflow by ID"
      description: "Returns a single Workflow scoped to the caller organization, including its full node/edge canvas and viewport. Used to hydrate the workflow builder."
      tags:
        - "Workflows"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Workflow returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowSingleResponse"
        "404":
          description: "Workflow not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
    put:
      operationId: "put_workflows_by_id"
      summary: "Update a workflow"
      description: "Updates editable fields on a Workflow scoped to the caller organization. Nodes, edges, viewport, name, description, and enabled flag are all replaceable. Renames must keep the name unique within the organization."
      tags:
        - "Workflows"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/WorkflowUpdateRequest"
      responses:
        "200":
          description: "Workflow updated successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowMutationResponse"
        "400":
          description: "Duplicate name"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
        "404":
          description: "Workflow not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
        "409":
          description: "Workflow revision or graph version is stale"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowConflictResponse"
    delete:
      operationId: "delete_workflows_by_id"
      summary: "Archive a workflow (compatibility alias)"
      description: "Deprecated compatibility alias for the preconditioned soft-archive command. The workflow definition and execution history are retained; the workflow is disabled and excluded from runnable discovery."
      tags:
        - "Workflows"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/WorkflowArchiveRequest"
      responses:
        "200":
          description: "Workflow archived successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowMutationResponse"
        "404":
          description: "Workflow not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
        "409":
          description: "Workflow revision is stale"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowConflictResponse"
  "/api/workflows/{id}/archive":
    post:
      operationId: "post_workflows_archive"
      summary: "Archive a workflow"
      description: "Soft-archives a workflow with an exact resource revision and stable command key. Archive atomically disables the definition and retains its graph and execution history."
      tags:
        - "Workflows"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/WorkflowArchiveRequest"
      responses:
        "200":
          description: "Workflow archived successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowMutationResponse"
        "404":
          description: "Workflow not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
        "409":
          description: "Workflow revision is stale"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowConflictResponse"
  "/api/workflows/{id}/execute":
    post:
      operationId: "post_workflows_execute"
      summary: "Manually execute a workflow"
      description: "Runs a workflow synchronously through the workflow engine for testing or one-off use. Optional contactId/conversationId scope the run; the response includes the WorkflowExecution record plus a summary of nodes executed and duration."
      tags:
        - "Workflows"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/WorkflowExecuteRequest"
      responses:
        "202":
          description: "Workflow execution queued (runs asynchronously on the workflow-runner service)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowExecuteQueuedResponse"
        "500":
          description: "Error executing workflow"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
  "/api/workflows/{id}/execution-stats":
    get:
      operationId: "get_api_workflows_id_execution_stats"
      summary: "GET /api/workflows/{id}/execution-stats"
      tags:
        - "Automations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/workflows/{id}/executions":
    get:
      operationId: "get_api_workflows_id_executions"
      summary: "GET /api/workflows/{id}/executions"
      tags:
        - "Automations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/workflows/{id}/toggle":
    patch:
      operationId: "patch_workflows_toggle"
      summary: "Toggle workflow enabled state"
      description: "Sets the workflow's `enabled` flag (organization-scoped) without modifying the canvas. Disabled workflows are skipped by the trigger system even when their conditions match."
      tags:
        - "Workflows"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/WorkflowToggleRequest"
      responses:
        "200":
          description: "Workflow toggled successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowMutationResponse"
        "400":
          description: "Enabled status must be a boolean"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
        "404":
          description: "Workflow not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
        "409":
          description: "Workflow revision is stale or the workflow is archived"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowConflictResponse"
  "/api/workflows/executions":
    get:
      operationId: "get_workflow_executions"
      summary: "List workflow executions (paginated, filterable)"
      description: "Lists recent `WorkflowExecution` records for the caller organization. Drives the Workflows Dashboard page in the client - mirrors the event-logs/Automations Dashboard pattern but sourced from the workflow runner's execution records (not the legacy event-handler automation system; the two are independent). Each row includes the trigger metadata (`triggeredBy`, `triggerData`) and context refs (`contactId`, `conversationId`) so the client can render a per-trigger linked-entity link - e.g. for the `application_created` trigger, the row links to the contact profile of the application owner (since there is no standalone application detail page). The full node-by-node execution trace and workflow variables are omitted from list rows for payload size; fetch them with `GET /api/workflows/executions/{executionId}`. Non-SUPERADMIN callers are always scoped to their own organization regardless of any `organizationId` query param."
      tags:
        - "Workflows"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "query"
          name: "workflowId"
          required: false
          description: "Filter to executions of a specific workflow."
          schema:
            type: "string"
        -
          in: "query"
          name: "triggeredBy"
          required: false
          description: "Filter by trigger kind. Use `all` (default) for no filter. Mirrors `WorkflowExecution.triggeredBy`."
          schema:
            type: "string"
            enum:
              - "all"
              - "message"
              - "timer"
              - "webhook"
              - "manual"
              - "schedule"
              - "contact_created"
              - "contact_updated"
              - "application_created"
              - "application_updated"
              - "conversation_started"
              - "email"
              - "sendgrid_inbound"
        -
          in: "query"
          name: "status"
          required: false
          description: "Filter by execution status. Use `all` (default) for no filter."
          schema:
            type: "string"
            enum:
              - "all"
              - "pending"
              - "running"
              - "completed"
              - "failed"
              - "cancelled"
              - "waiting"
        -
          in: "query"
          name: "days"
          required: false
          description: "Time-range filter (executions where `createdAt` is within the last N days). Must be a positive number. Fractional values supported (e.g. `0.0417` for the last hour)."
          schema:
            type: "number"
            minimum: 0
            exclusiveMinimum: true
        -
          in: "query"
          name: "organizationId"
          required: false
          description: "Cross-org filter - **SUPERADMIN only**. Ignored for regular admins (response is always scoped to the caller's own organization for them)."
          schema:
            type: "string"
        -
          in: "query"
          name: "page"
          required: false
          description: "Page number (1-indexed). Default 1."
          schema:
            type: "integer"
            minimum: 1
            default: 1
        -
          in: "query"
          name: "limit"
          required: false
          description: "Page size. Default 20, max 100."
          schema:
            type: "integer"
            minimum: 1
            maximum: 100
            default: 20
      responses:
        "200":
          description: "Paginated execution list (newest first)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowExecutionsListResponse"
        "400":
          description: "Missing organization context"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
        "500":
          description: "Error listing executions"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
  "/api/workflows/executions/{executionId}":
    get:
      operationId: "get_workflow_execution_by_id"
      summary: "Get a single workflow execution by id (with full node trace)"
      description: "Returns one `WorkflowExecution` record including the full `nodeExecutions` array (node-by-node status, input/output, error, duration) and any `variables` set during the run. Used by the Workflows Dashboard detail panel; the list endpoint omits these fields for payload size. Non-SUPERADMIN callers are scoped to their own organization."
      tags:
        - "Workflows"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "executionId"
          required: true
          description: "The `_id` of the WorkflowExecution."
          schema:
            type: "string"
      responses:
        "200":
          description: "Execution returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowExecutionDetailResponse"
        "404":
          description: "Execution not found (or not visible to this organization)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
        "500":
          description: "Error fetching execution"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
  "/api/workflows/executions/{executionId}/widget/cancel":
    post:
      operationId: "post_api_workflows_executions_executionId_widget_cancel"
      summary: "POST /api/workflows/executions/{executionId}/widget/cancel"
      tags:
        - "Automations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "executionId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/workflows/executions/{executionId}/widget/components/{componentId}":
    get:
      operationId: "get_api_workflows_executions_executionId_widget_components_componentId"
      summary: "GET /api/workflows/executions/{executionId}/widget/components/{componentId}"
      tags:
        - "Automations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "executionId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "componentId"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/workflows/executions/{executionId}/widget/heartbeat":
    post:
      operationId: "post_api_workflows_executions_executionId_widget_heartbeat"
      summary: "POST /api/workflows/executions/{executionId}/widget/heartbeat"
      tags:
        - "Automations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "executionId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/workflows/executions/{executionId}/widget/submit":
    post:
      operationId: "post_api_workflows_executions_executionId_widget_submit"
      summary: "POST /api/workflows/executions/{executionId}/widget/submit"
      tags:
        - "Automations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "executionId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/workflows/executions/pending-widgets":
    get:
      operationId: "get_api_workflows_executions_pending_widgets"
      summary: "GET /api/workflows/executions/pending-widgets"
      tags:
        - "Automations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/workflows/folders":
    get:
      operationId: "get_workflow_folders"
      summary: "List workflow folders"
      description: "Every workflow folder in the caller organization as a flat list sorted by name. Folders nest through `parentFolderId` (null = top level). Folders only organize the workflow list: they carry no permissions and nothing at runtime reads them."
      tags:
        - "Workflows"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Folders returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowFolderListResponse"
    post:
      operationId: "post_workflow_folders"
      summary: "Create a workflow folder"
      description: "Creates a folder at the top level or inside `parentFolderId`. Sibling names are unique per organization, ignoring case."
      tags:
        - "Workflows"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/WorkflowFolderCreateRequest"
      responses:
        "201":
          description: "Folder created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowFolderResponse"
        "400":
          description: "Validation error or a sibling folder already has this name (WORKFLOW_FOLDER_DUPLICATE_NAME)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
        "404":
          description: "Parent folder not found (WORKFLOW_FOLDER_NOT_FOUND)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
  "/api/workflows/folders/{folderId}":
    patch:
      operationId: "patch_workflow_folder"
      summary: "Rename or move a workflow folder"
      description: "Renames the folder and/or moves it under another folder (`parentFolderId: null` = top level). A folder cannot be moved into itself or any folder beneath it. Its workflows and subfolders move with it."
      tags:
        - "Workflows"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "folderId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/WorkflowFolderUpdateRequest"
      responses:
        "200":
          description: "Folder updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowFolderResponse"
        "400":
          description: "Validation error, duplicate sibling name, or the move would nest the folder inside itself (WORKFLOW_FOLDER_CYCLE)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
        "404":
          description: "Folder not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
    delete:
      operationId: "delete_workflow_folder"
      summary: "Delete an empty workflow folder"
      description: "Deletes a folder that holds no subfolder and no live workflow. A non-empty folder is refused rather than cascaded, so no workflow is ever deleted or moved by a folder delete. Archived workflows still pointing at the folder are moved to the top level."
      tags:
        - "Workflows"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "folderId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Folder deleted"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowFolderDeleteResponse"
        "404":
          description: "Folder not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
        "409":
          description: "Folder is not empty (WORKFLOW_FOLDER_NOT_EMPTY; details carry folderCount and workflowCount)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
  "/api/workflows/move":
    post:
      operationId: "post_workflows_move"
      summary: "Move workflows to a folder"
      description: "Moves 1-500 workflows into a folder, or to the top level with `folderId: null`. All or nothing: if any id is not a live workflow of the organization, nothing moves. Only `folderId` changes: enabled state, graph, triggers, `revision` and `version` are untouched."
      tags:
        - "Workflows"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/WorkflowMoveRequest"
      responses:
        "200":
          description: "Workflows moved"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowMoveResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
        "404":
          description: "A workflow (WORKFLOW_NOT_FOUND, details.missingWorkflowIds) or the folder (WORKFLOW_FOLDER_NOT_FOUND) was not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
  "/api/workflows/node-catalog":
    get:
      operationId: "get_workflows_node_catalog"
      summary: "List every registered workflow node definition"
      description: "Returns the catalog of all node definitions registered in the workflow engine - trigger, action, condition, and transform nodes. Each entry carries the node `type`, `category`, human-readable `label`/`description`/`icon`, a JSON Schema for the node's `data` (config) shape, the declared `outputShape` keys (for chaining), and an optional `sampleInput`. Powers the visual builder's node picker and per-node config form."
      tags:
        - "Workflows"
      security:
        -
          bearerAuth:
            []
      responses:
        "200":
          description: "Node catalog returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowNodeCatalogResponse"
        "500":
          description: "Failed to serialize the catalog"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
  "/api/workflows/nodes/{type}/test":
    post:
      operationId: "post_workflows_nodes_type_test"
      summary: "Validate and dry-run a single workflow node definition"
      description: "Per-node dry-run endpoint used by the workflow builder when an author clicks \"Test\" on a node. The supplied `config` is parsed against the node's `configSchema`; on validation failure the response is HTTP 200 with `success:false` and a Zod-style `issues[]` array so the UI can render field-level errors (4xx is intentionally avoided because the client wrapper throws on 4xx and strips the issues payload). On success: trigger-category nodes are executed against a synthesized `ExecutionContext` built from `input` (so the response reflects the actual trigger output a workflow would see) and side-effecting nodes return a mocked output derived from `outputShape` (real execution is deferred until per-executor dryRun guards land). Special cases:\n  - `WebhookTrigger`: simulates the HTTP-boundary validation done by `/api/webhook/workflow` and surfaces the same `webhookId` checks the real evaluator would apply.\n  - `AIExtractNode`: actually runs an LLM call against the user-supplied sample text (the request `input` is serialized as JSON and fed to the model as context - DB-backed context sources like `conversation`/`callTranscript` are skipped in test mode). Uses the organization's `dataExtraction` model assignment via `OrganizationCredentials.modelAssignments`; if unconfigured, returns `success:false` with `code:'AI_SETUP_REQUIRED'`. The response includes the structured extraction shape (flattened keys + nested `extracted` + `confidence`/`missingFields`/`branch`/`usage`/`provider`/`model`).\n  - `AIGenerateNode`: actually runs an LLM call against the user-supplied sample text, returning the generated string on `output.text`. Uses the organization's `messageGeneration` model assignment; same `AI_SETUP_REQUIRED` contract as `AIExtractNode`. At workflow runtime (not via this test endpoint, which has no `ExecutionContext`) the `instructions` field supports the same `{{...}}` placeholder grammar as `SendMessageAction` - workflow variables (`{{varName}}`), contact/conversation/application fields (`{{contact.firstName}}`), `{{triggerData.*}}` paths, `{{vault.secretName}}`, and prior-node output references (`{{nodeId.output.path}}`) are resolved before the prompt is sent to the model. Builder dry-runs are not persisted as `MessageAiCallMetric`."
      tags:
        - "Workflows"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "type"
          required: true
          description: "Registered node type (e.g. `WebhookTrigger`, `SendMessage`, `IfCondition`)."
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/WorkflowNodeTestRequest"
            examples:
              webhookTrigger:
                summary: "WebhookTrigger - config + simulated request body"
                value:
                  config:
                    webhookId: "wh_64d2f9c5e8a1d4e001a0b1c3"
                  input:
                    webhookId: "wh_64d2f9c5e8a1d4e001a0b1c3"
                    payload:
                      lead:
                        name: "Alex Nguyen"
                        email: "alex.nguyen@example.com"
              aiExtract:
                summary: "AIExtractNode - fields + context sources, with a sample conversation as `input`"
                value:
                  config:
                    fields:
                      -
                        key: "preferredDate"
                        description: "The appointment date the customer prefers, as an ISO 8601 string."
                        type: "date"
                        required: true
                      -
                        key: "urgency"
                        description: "How urgent the request is."
                        type: "enum"
                        required: false
                        enumValues:
                          - "low"
                          - "medium"
                          - "high"
                    contextSources:
                      -
                        source: "conversation"
                        messageLimit: 50
                    generalPrompt: "Prefer the most recent message when dates conflict."
                    confidenceThreshold: 0.6
                    outputVariable: "extracted"
                  input:
                    messages:
                      - "Hi, can I book for Thursday afternoon? Pretty urgent - my insurance lapses Friday."
                      - "Sure, let me check. Around 3pm work?"
                      - "3pm Thursday is perfect."
              aiGenerate:
                summary: "AIGenerateNode - instructions + context sources, generating a follow-up email"
                value:
                  config:
                    instructions: "Draft a short follow-up email referencing the appointment we just confirmed. Friendly tone, no preamble, two paragraphs max."
                    contextSources:
                      -
                        source: "conversation"
                        messageLimit: 20
                    outputStyle: "reply"
                    maxTokens: 600
                    temperature: 0.7
                    outputVariable: "followUpDraft"
                  input:
                    messages:
                      - "Hi, can I book for Thursday afternoon? Pretty urgent - my insurance lapses Friday."
                      - "Sure, 3pm Thursday it is. See you then!"
              aiGenerateWithPlaceholders:
                summary: "AIGenerateNode - instructions using `{{...}}` placeholders that are resolved against the ExecutionContext at workflow runtime"
                value:
                  config:
                    instructions: "Write a one-line internal note for {{contact.firstName}} about application {{triggerData.applicationId}}. Reference: {{recentSummary}}"
                    contextSources:
                      []
                    outputStyle: "note"
                    maxTokens: 200
                    temperature: 0.3
                    outputVariable: "internalNote"
                  input:
                    {}
      responses:
        "200":
          description: "Test executed (success, mocked output, or validation failure). Inspect `success` to disambiguate."
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowNodeTestResponse"
              examples:
                webhookTriggerSuccess:
                  summary: "WebhookTrigger - real trigger execution"
                  value:
                    success: true
                    output:
                      webhookId: "wh_64d2f9c5e8a1d4e001a0b1c3"
                      payload:
                        lead:
                          name: "Alex Nguyen"
                          email: "alex.nguyen@example.com"
                    durationMs: 4
                aiExtractFound:
                  summary: "AIExtractNode - extraction succeeded, routed to `found` branch"
                  value:
                    success: true
                    output:
                      preferredDate: "2026-06-04T15:00:00Z"
                      urgency: "high"
                      extracted:
                        preferredDate: "2026-06-04T15:00:00Z"
                        urgency: "high"
                      confidence: 0.92
                      missingFields:
                        []
                      branch: "found"
                      usage:
                        inputTokens: 312
                        outputTokens: 48
                        totalTokens: 360
                      provider: "anthropic"
                      model: "claude-haiku-4-5"
                    durationMs: 1180
                aiExtractNotFound:
                  summary: "AIExtractNode - model could not find any required fields"
                  value:
                    success: true
                    output:
                      preferredDate: null
                      urgency: null
                      extracted:
                        preferredDate: null
                        urgency: null
                      confidence: 0.15
                      missingFields:
                        - "preferredDate"
                        - "urgency"
                      branch: "not_found"
                      usage:
                        inputTokens: 298
                        outputTokens: 42
                        totalTokens: 340
                      provider: "anthropic"
                      model: "claude-haiku-4-5"
                    durationMs: 980
                aiExtractLowConfidence:
                  summary: "AIExtractNode - partial extraction or confidence below threshold, routed to `low_confidence` branch"
                  value:
                    success: true
                    output:
                      preferredDate: "2026-06-04T15:00:00Z"
                      urgency: null
                      extracted:
                        preferredDate: "2026-06-04T15:00:00Z"
                        urgency: null
                      confidence: 0.42
                      missingFields:
                        - "urgency"
                      branch: "low_confidence"
                      usage:
                        inputTokens: 305
                        outputTokens: 38
                        totalTokens: 343
                      provider: "anthropic"
                      model: "claude-haiku-4-5"
                    durationMs: 1020
                aiExtractSetupRequired:
                  summary: "AIExtractNode - no `dataExtraction` model configured"
                  value:
                    success: false
                    code: "AI_SETUP_REQUIRED"
                    message: "AI setup required for section \"dataExtraction\": NO_MODEL_ASSIGNMENT"
                    durationMs: 12
                aiGenerateSuccess:
                  summary: "AIGenerateNode - text generated, routed to `success` branch"
                  value:
                    success: true
                    output:
                      text: "Just confirming our appointment at 3pm Thursday - looking forward to seeing you then. If anything comes up before then, reply to this message and I'll get back to you right away."
                      branch: "success"
                      usage:
                        inputTokens: 184
                        outputTokens: 62
                        totalTokens: 246
                      provider: "anthropic"
                      model: "claude-haiku-4-5"
                    durationMs: 940
                aiGenerateSetupRequired:
                  summary: "AIGenerateNode - no `messageGeneration` model configured"
                  value:
                    success: false
                    code: "AI_SETUP_REQUIRED"
                    message: "AI setup required for section \"messageGeneration\": NO_MODEL_ASSIGNMENT"
                    durationMs: 12
                validationFailure:
                  summary: "Config validation failed - Zod issues returned for the UI to surface"
                  value:
                    success: false
                    message: "Config validation failed"
                    issues:
                      -
                        code: "too_small"
                        path:
                          - "fields"
                        message: "Array must contain at least 1 element(s)"
                    durationMs: 2
        "404":
          description: "Unknown node type"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
        "500":
          description: "Unhandled error executing the test"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
  "/api/workflows/owner-schema/{ownerType}":
    get:
      operationId: "get_api_workflows_owner_schema_ownerType"
      summary: "GET /api/workflows/owner-schema/{ownerType}"
      tags:
        - "Automations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "ownerType"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
  "/api/workflows/runnable":
    get:
      operationId: "get_api_workflows_runnable"
      summary: "GET /api/workflows/runnable"
      tags:
        - "Automations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/api/workflows/schedule/preview":
    post:
      operationId: "post_api_workflows_schedule_preview"
      summary: "POST /api/workflows/schedule/preview"
      tags:
        - "Automations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              type: "object"
              additionalProperties: true
      security:
        -
          bearerAuth:
            []
  "/api/workflows/validation-runs":
    get:
      operationId: "get_api_workflows_validation_runs"
      summary: "GET /api/workflows/validation-runs"
      tags:
        - "Automations"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      security:
        -
          bearerAuth:
            []
  "/d/{token}":
    get:
      operationId: "get_d_token"
      summary: "GET /d/{token}"
      tags:
        - "D"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "token"
          required: true
          schema:
            type: "string"
  "/d/{token}/download":
    get:
      operationId: "get_d_token_download"
      summary: "GET /d/{token}/download"
      tags:
        - "D"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "token"
          required: true
          schema:
            type: "string"
  "/d/{token}/view":
    get:
      operationId: "get_d_token_view"
      summary: "GET /d/{token}/view"
      tags:
        - "D"
      responses:
        "200":
          description: "Successful response"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiResponse"
        "400":
          description: "Bad request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "401":
          description: "Unauthorized"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ApiError"
      parameters:
        -
          in: "path"
          name: "token"
          required: true
          schema:
            type: "string"
  "/api/organizations/{organizationId}/conditional-fields":
    get:
      operationId: "get_conditional_fields"
      summary: "List conditional fields for an organization"
      description: "Return every conditional field defined for the organization, optionally filtered by `type` (e.g. `contact`/`application`) and `sectionType`. Used by the field-builder UI to render the configured catalog."
      tags:
        - "ConditionalFields"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
        -
          in: "query"
          name: "type"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "sectionType"
          required: false
          schema:
            type: "string"
      responses:
        "200":
          description: "Fields returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConditionalFieldListResponse"
        "400":
          description: "Organization id is required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConditionalFieldErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConditionalFieldErrorResponse"
    post:
      operationId: "post_conditional_field"
      summary: "Create a conditional field"
      description: "Create a derived (\"conditional\") field whose value is computed from an `expression` over other fields in the section. The expression is validated before persistence."
      tags:
        - "ConditionalFields"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/CreateConditionalFieldRequest"
      responses:
        "201":
          description: "Field created"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConditionalFieldResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConditionalFieldErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConditionalFieldErrorResponse"
  "/api/organizations/{organizationId}/conditional-fields/catalog":
    get:
      operationId: "get_conditional_fields_catalog"
      summary: "Get the field catalog for an organization"
      description: "Return the full catalog of sections and fields available for use inside conditional-field expressions, scoped to the requested type/sectionType. This is the autocomplete source for the expression editor."
      tags:
        - "ConditionalFields"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
        -
          in: "query"
          name: "type"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "sectionType"
          required: false
          schema:
            type: "string"
      responses:
        "200":
          description: "Catalog returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConditionalFieldCatalogResponse"
        "400":
          description: "Organization id is required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConditionalFieldErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConditionalFieldErrorResponse"
  "/api/organizations/{organizationId}/conditional-fields/validate":
    post:
      operationId: "post_validate_conditional_field"
      summary: "Validate a conditional field expression"
      description: "Type-check a conditional-field definition without persisting it. Returns the parsed expression diagnostics so the UI can highlight errors live in the expression editor."
      tags:
        - "ConditionalFields"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ValidateConditionalFieldRequest"
      responses:
        "200":
          description: "Validation result"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConditionalFieldResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConditionalFieldErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConditionalFieldErrorResponse"
  "/api/organizations/{organizationId}/conditional-fields/reorder":
    post:
      operationId: "post_reorder_conditional_fields"
      summary: "Reorder conditional fields"
      description: "Replace the ordering of conditional fields within a section. The `order` array must list every field id currently in scope; the new index is the position in the array."
      tags:
        - "ConditionalFields"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ReorderConditionalFieldsRequest"
      responses:
        "200":
          description: "Fields reordered"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConditionalFieldListResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConditionalFieldErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConditionalFieldErrorResponse"
  "/api/organizations/{organizationId}/conditional-fields/{fieldId}":
    put:
      operationId: "put_conditional_field"
      summary: "Update a conditional field"
      description: "Update an existing conditional field. The new `expression` is validated against the catalog before persistence."
      tags:
        - "ConditionalFields"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "fieldId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateConditionalFieldRequest"
      responses:
        "200":
          description: "Field updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConditionalFieldResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConditionalFieldErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConditionalFieldErrorResponse"
    delete:
      operationId: "delete_conditional_field"
      summary: "Delete a conditional field"
      description: "Permanently delete a conditional field. Other fields referencing the deleted field will fail validation on next save and must be fixed by the operator."
      tags:
        - "ConditionalFields"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "fieldId"
          required: true
          schema:
            type: "string"
        -
          in: "query"
          name: "type"
          required: false
          schema:
            type: "string"
        -
          in: "query"
          name: "sectionType"
          required: false
          schema:
            type: "string"
      responses:
        "204":
          description: "Field deleted. No body."
        "400":
          description: "Organization id is required or validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConditionalFieldErrorResponse"
        "403":
          description: "Forbidden - caller is not authorized to delete fields in this organization"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConditionalFieldErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ConditionalFieldErrorResponse"
  "/api/contacts/{id}/execute-custom-fields/all":
    post:
      operationId: "post_contact_execute_custom_fields_all"
      summary: "Execute custom fields across contact, conversations and applications (disabled)"
      deprecated: true
      description: "Disabled. The companion `/execute-custom-fields` route is what callers should use; this aggregate variant is commented out in the API router to avoid double-running with hook-driven rule execution. Documented as `deprecated` + `410 Gone` until it is re-enabled. See `ExecuteAllCustomFieldsResponse` for the shape it would return when restored."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      responses:
        "410":
          description: "Endpoint is currently disabled"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/contacts/{id}/phone-number/verify":
    patch:
      operationId: "patch_contact_phone_number_verify"
      summary: "Set or clear phone-number verification timestamp"
      description: "Marks a specific phone number on the contact as verified (or clears verification when verifiedAt is null). Operates on the matching entry inside the phoneNumber array; org-scoped unless caller is SUPERADMIN."
      tags:
        - "Contacts"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      security:
        -
          bearerAuth:
            []
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/SetContactPhoneVerificationRequest"
      responses:
        "200":
          description: "Phone verification updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactWrappedMutationResponse"
        "400":
          description: "Invalid payload"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "404":
          description: "Contact or phone number not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/organizations/{organizationId}/email-accounts/oauth/authorize":
    get:
      operationId: "get_organizations_organizationId_email_accounts_oauth_authorize"
      summary: "Connect a mailbox on behalf of a user or group (admin)"
      description: "Returns the provider authorization URL for an admin connecting a mailbox into the SELECTED organization, pre-linked to exactly one user or group of that organization. The signed OAuth state carries the selected organization, so the callback stores the mailbox there. Admin or SuperAdmin."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
          description: "The organization that owns the mailboxes."
        -
          in: "query"
          name: "provider"
          required: false
          schema:
            type: "string"
            enum:
              - "gmail"
              - "outlook"
            default: "gmail"
        -
          in: "query"
          name: "linkedUserId"
          required: false
          schema:
            type: "string"
          description: "User to link the mailbox to. Exactly one of linkedUserId / linkedGroupId."
        -
          in: "query"
          name: "linkedGroupId"
          required: false
          schema:
            type: "string"
          description: "Active group to link the mailbox to. Exactly one of linkedUserId / linkedGroupId."
      responses:
        "200":
          description: "Authorization URL returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailAuthorizeUrlResponse"
        "400":
          description: "Invalid organizationId, link target missing, both targets, target not in the organization, or unsupported provider"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
        "403":
          description: "Forbidden (not an admin, or another organization)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
  "/api/organizations/{organizationId}/email-accounts/{accountId}":
    put:
      operationId: "put_organizations_organizationId_email_accounts_accountId"
      summary: "Update who a mailbox is shared with (admin)"
      description: "Mailboxes are created and linked by the OAuth connect flow; this sets the only admin-managed field, `grants` - who else may send from the mailbox beyond its link. Mailbox grants carry `send` only: a `read` verb is refused with a 400 (read access to a mailbox cannot be granted yet). `grants`, when present, REPLACES the whole list (`[]` removes every grant); when absent nothing changes. Every principal must be a user, user group or department of the organization and may appear once; new or changed grants are stamped with the calling admin, unchanged ones keep their original `grantedBy`/`grantedAt`. Returns the updated mailbox (tokens excluded). Admin or SuperAdmin."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
          description: "The organization that owns the mailboxes."
        -
          in: "path"
          name: "accountId"
          required: true
          schema:
            type: "string"
          description: "`_id` of the EmailAccount."
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateOrgEmailAccountRequest"
      responses:
        "200":
          description: "Mailbox updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgEmailAccountUpdateResponse"
        "400":
          description: "Validation error: invalid id, malformed grant, duplicate grant, grant with no verbs, a `read` verb (mailboxes take send grants only), or a grant principal not in the organization (the message names it)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
        "403":
          description: "Forbidden (not an admin, or another organization)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
        "404":
          description: "Email account not found in the organization"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
        "500":
          description: "Failed to update email account"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/EmailErrorResponse"
  "/api/marketplace/{id}/import-to-automations":
    post:
      operationId: "import_template_to_automations"
      summary: "Import SMS template to multiple automations"
      description: "Import the SMS template body of a marketplace listing into one or more automations owned by the caller, in a single Mongo transaction. Each target automation must be SMS-enabled; per-automation failures are returned in `failed[]` with a 207 partial-success status when at least one target imported cleanly."
      tags:
        - "Marketplace"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ImportTemplateToAutomationsRequest"
      responses:
        "200":
          description: "Template imported to all automations"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceImportToAutomationsResponse"
        "207":
          description: "Template imported to some automations"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceImportToAutomationsResponse"
        "400":
          description: "Validation failed or no automations imported"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceImportToAutomationsResponse"
        "404":
          description: "Published template, user, or template content not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
        "500":
          description: "Failed to import template"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/MarketplaceErrorResponse"
  "/api/messages/upload-attachment":
    post:
      operationId: "post_messages_upload_attachment"
      summary: "Upload an attachment to R2 storage (tiered auth)"
      description: "Upload a single message attachment to R2 storage. Accepts authenticated agent uploads or unauthenticated webchat uploads gated by a valid `webchatConfigId`. Returns the storage key plus content metadata for inclusion in a subsequent send-message call."
      tags:
        - "Messages"
      requestBody:
        required: true
        content:
          "multipart/form-data":
            schema:
              type: "object"
              properties:
                file:
                  type: "string"
                  format: "binary"
                  description: "A single binary attachment (image, video, PDF, Office document, CSV, or plain text). Max 50 MB."
                webchatConfigId:
                  type: "string"
                  description: "Required when the caller is the webchat widget (no JWT/API-key). Validated against the org's active webchat configurations to gate unauthenticated uploads."
              required:
                - "file"
              description: "Multipart form. Send the file as a `file` part; for unauthenticated webchat uploads also include `webchatConfigId`. Example with curl: `curl -F \"file=@receipt.png\" -H \"Authorization: Bearer $TOKEN\" /api/messages/upload-attachment`."
              example:
                file: "<binary: receipt.png>"
                webchatConfigId: "64a1b2c3d4e5f60012345678"
      responses:
        "200":
          description: "Attachment uploaded"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/UploadAttachmentResponse"
        "400":
          description: "No file uploaded"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "401":
          description: "Authentication required"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
        "429":
          description: "Rate limit exceeded"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/RateLimitResponse"
        "503":
          description: "Storage not configured"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/LegacyErrorResponse"
  "/api/organizations/{organizationId}/contact-dedup-reviews/pending":
    get:
      operationId: "get_organizations_organizationId_contact_dedup_reviews_pending"
      summary: "Get pending contact dedup reviews"
      description: "Returns pending fuzzy-match / phone-conflict contact dedup reviews grouped by source contact, with candidate contacts (filtered to allowed contact fields), score, threshold snapshot, and field breakdown. Org-scoped via bearer token; SuperAdmin can read any org."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Pending contact dedup reviews returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactDedupReviewListResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/{organizationId}/contact-dedup-reviews/resolved":
    get:
      operationId: "get_organizations_organizationId_contact_dedup_reviews_resolved"
      summary: "Get resolved contact dedup reviews"
      description: "Returns the audit history of resolved contact dedup reviews (merged or kept_separate) with populated source/candidate contact references and the resolving user. Org-scoped via bearer token; SuperAdmin can read any org."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Resolved contact dedup reviews returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactDedupReviewListResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/{organizationId}/contact-dedup-reviews/{reviewId}/merge":
    patch:
      operationId: "patch_organizations_organizationId_contact_dedup_reviews_reviewId_merge"
      summary: "Mark a contact dedup review as merged"
      description: "Marks the review as merged, merging the source contact into the candidate per the optional resolution payload, recording the resolving user, and writing an audit log entry. Emits socket updates so other clients refresh their dedup queues."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "reviewId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ContactDedupReviewResolutionRequest"
      responses:
        "200":
          description: "Contact dedup review marked as merged"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactDedupReviewMutationResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Contact dedup review not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/{organizationId}/contact-dedup-reviews/{reviewId}/keep-separate":
    patch:
      operationId: "patch_organizations_organizationId_contact_dedup_reviews_reviewId_keep_separate"
      summary: "Mark a contact dedup review as kept separate"
      description: "Marks the review as kept_separate (no merge), records the resolving user, and writes an audit log entry. Suppresses future fuzzy-match suggestions for this contact pair."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
        -
          in: "path"
          name: "reviewId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: false
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/ContactDedupReviewResolutionRequest"
      responses:
        "200":
          description: "Contact dedup review marked as kept separate"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactDedupReviewMutationResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Contact dedup review not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/{organizationId}/contact-fuzzy-merge-settings":
    get:
      operationId: "get_organizations_organizationId_contact_fuzzy_merge_settings"
      summary: "Get contact fuzzy-merge settings"
      description: "Returns the active fuzzy-merge configuration used to detect duplicate contacts (candidate limit, match/review thresholds, custom-field rules with weights, trigger / instant-merge field lists, and per-field conflict resolution rules)."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      responses:
        "200":
          description: "Contact fuzzy merge settings returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactFuzzyMergeSettingsResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
    put:
      operationId: "put_organizations_organizationId_contact_fuzzy_merge_settings"
      summary: "Update contact fuzzy-merge settings"
      description: "Partially updates the fuzzy-merge configuration: numeric thresholds (0-100% or absolute), candidate limit (1-200), custom field rules (field path / weight / matchMode), lookup-trigger and instant-merge field lists, and per-field conflict resolution rules. All changes are validated against the merged configuration."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateContactFuzzyMergeSettingsRequest"
      responses:
        "200":
          description: "Contact fuzzy merge settings updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/ContactFuzzyMergeSettingsUpdateResponse"
        "400":
          description: "Validation error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "403":
          description: "Forbidden"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "404":
          description: "Organization not found"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
        "500":
          description: "Internal server error"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrganizationErrorResponse"
  "/api/organizations/{organizationId}/phone-numbers/{phoneNumberId}":
    put:
      operationId: "put_organizations_organizationId_phone_numbers_phoneNumberId"
      summary: "Update an organization phone number"
      description: "Partial update of link target, number, capabilities, label, routing (deep-merged), AI binding, status, number type and org-default flag. A `numberType` change re-checks the number for the new type: a change to `shortcode` needs 5 or 6 digits, and a change from `shortcode` to `longcode` or `tollfree` needs a valid E.164 number, so send the new `phoneNumber` with the type change. `grants`, when present, REPLACES the whole grant list (`[]` removes every grant); when absent, stored grants are left untouched. A grant that is unchanged keeps its original `grantedBy`/`grantedAt`; new or changed grants are stamped with the calling admin. Admin or SuperAdmin."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
          description: "The organization that owns the phone numbers."
        -
          in: "path"
          name: "phoneNumberId"
          required: true
          schema:
            type: "string"
          description: "`_id` of the PhoneNumber resource."
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/UpdateOrgPhoneNumberRequest"
      responses:
        "200":
          description: "Phone number updated"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgPhoneNumberMutationResult"
        "400":
          description: "Validation error: malformed body, both link targets, an inactive org default, a grant principal not in the organization (the message names it), a duplicate grant, a grant with no verbs, a send grant on the org default, a short code that starts with `+` or is not 5 or 6 digits (a type change re-checks the stored number), a type change away from `shortcode` without a valid E.164 `phoneNumber`, a short code as the org default, or a short code with voice capability, AI routing, a forward number, an ElevenLabs id or an AI agent"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
        "403":
          description: "Forbidden (not an admin, or another organization)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
        "404":
          description: "Phone number, linked user or linked group not found in the organization"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
        "409":
          description: "The new phone number is already provisioned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
        "500":
          description: "Failed to update phone number"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
    delete:
      operationId: "delete_organizations_organizationId_phone_numbers_phoneNumberId"
      summary: "Remove an organization phone number"
      description: "Detaches any AI voice wiring first (fails with 502 if the provider refuses). If unresolved conversations still reference the number it is disabled (`status: inactive`, `softDisabled: true`) instead of removed; otherwise it is soft-deleted. Removing or disabling the org default clears the default and says so (`clearedOrgDefault`). Admin or SuperAdmin."
      tags:
        - "Organizations"
      security:
        -
          bearerAuth:
            []
      parameters:
        -
          in: "path"
          name: "organizationId"
          required: true
          schema:
            type: "string"
          description: "The organization that owns the phone numbers."
        -
          in: "path"
          name: "phoneNumberId"
          required: true
          schema:
            type: "string"
          description: "`_id` of the PhoneNumber resource."
      responses:
        "200":
          description: "Phone number removed or disabled"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/OrgPhoneNumberDeleteResult"
        "400":
          description: "Invalid id"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
        "403":
          description: "Forbidden (not an admin, or another organization)"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
        "404":
          description: "Phone number not found in the organization"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
        "500":
          description: "Failed to delete phone number"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
        "502":
          description: "Could not remove the number from the AI voice provider"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/PhoneNumberErrorResponse"
  "/api/tools":
    get:
      operationId: "get_tools"
      summary: "List available tool metadata"
      description: "Returns a static map of every AI tool the agent runtime can invoke, keyed by tool name. Used by the playground/agent builder to render the tool palette and surface tool descriptions."
      tags:
        - "Tools"
      responses:
        "200":
          description: "Tools returned"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/GetToolsResponse"
  "/api/workflows/{id}/execute/sendgrid-inbound":
    post:
      operationId: "post_workflows_execute_sendgrid_inbound"
      summary: "Execute a workflow for a SendGrid inbound email"
      description: "Internal service endpoint that runs a workflow against an inbound SendGrid email payload. Authenticated via the INTERNAL_SERVICE_TOKEN bearer (not user auth). Validates the email payload (from / to / subject required) and rejects unauthorized requests with 403."
      tags:
        - "Workflows"
      parameters:
        -
          in: "path"
          name: "id"
          required: true
          schema:
            type: "string"
      requestBody:
        required: true
        content:
          "application/json":
            schema:
              "$ref": "#/components/schemas/WorkflowSendGridInboundRequest"
      responses:
        "200":
          description: "Workflow executed successfully"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowExecuteSendGridInboundResponse"
        "400":
          description: "Missing or invalid email data"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
        "403":
          description: "Unauthorized internal service request"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
        "404":
          description: "Workflow not found or not enabled"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
        "500":
          description: "Error executing workflow"
          content:
            "application/json":
              schema:
                "$ref": "#/components/schemas/WorkflowsErrorResponse"
components:
  securitySchemes:
    bearerAuth:
      type: "http"
      scheme: "bearer"
      bearerFormat: "JWT"
  schemas:
    ApiResponse:
      type: "object"
      additionalProperties: true
      description: "Generic response envelope. Endpoint-specific fields are intentionally open."
    ApiError:
      type: "object"
      additionalProperties: true
      properties:
        message:
          type: "string"
        code:
          type: "string"
      description: "Generic error envelope. Endpoint-specific fields are intentionally open."
    AiConsumptionTotals:
      type: "object"
      properties:
        calls:
          type: "integer"
        inputTokens:
          type: "integer"
        outputTokens:
          type: "integer"
        cacheReadTokens:
          type: "integer"
        cacheWriteTokens:
          type: "integer"
        reasoningTokens:
          type: "integer"
          description: "Thinking tokens billed apart from output (Google). Providers that count thinking inside output, such as OpenAI, are not included."
        totalTokens:
          type: "integer"
        inputCost:
          type: "number"
        outputCost:
          type: "number"
        reasoningCost:
          type: "number"
          description: "Cost of those thinking tokens, at the output rate. Already included in totalCost."
        totalCost:
          type: "number"
        durationMs:
          type: "integer"
    AiConsumptionRecord:
      type: "object"
      properties:
        _id:
          type: "string"
        organizationId:
          type: "string"
        environment:
          type: "string"
          description: "Deployment the spend occurred in. Required because an organization id is identical across environments."
        invocationId:
          type: "string"
        attempt:
          type: "integer"
        parentInvocationId:
          type: "string"
          nullable: true
        sourceType:
          type: "string"
          enum:
            - "ai_agent"
            - "ai_generation"
            - "ai_classification"
            - "ai_summarization"
            - "ai_extraction"
            - "ai_sentiment"
            - "tovi"
            - "voice_agent"
        sourceId:
          type: "string"
          nullable: true
        sourceName:
          type: "string"
        agentId:
          type: "string"
          nullable: true
        workflowId:
          type: "string"
          nullable: true
        workflowNodeId:
          type: "string"
          nullable: true
        conversationId:
          type: "string"
          nullable: true
        callId:
          type: "string"
          nullable: true
        actor:
          type: "object"
          properties:
            kind:
              type: "string"
              enum:
                - "user"
                - "system"
            userId:
              type: "string"
              nullable: true
            userName:
              type: "string"
              nullable: true
        surface:
          type: "string"
          enum:
            - "in_app"
            - "mcp"
          nullable: true
        mode:
          type: "string"
          enum:
            - "production"
            - "playground"
            - "simulation"
            - "preview"
            - "node_test"
        provider:
          type: "string"
        model:
          type: "string"
        tokens:
          type: "object"
          properties:
            input:
              type: "integer"
            output:
              type: "integer"
            cacheRead:
              type: "integer"
            cacheWrite:
              type: "integer"
            reasoning:
              type: "integer"
            total:
              type: "integer"
        cost:
          type: "object"
          properties:
            input:
              type: "number"
            output:
              type: "number"
            cacheRead:
              type: "number"
            cacheWrite:
              type: "number"
            reasoning:
              type: "number"
              description: "Thinking billed at the output rate. Set only where the provider reports it outside output (Google)."
            total:
              type: "number"
            currency:
              type: "string"
            credits:
              type: "number"
              description: "What the provider charged in its own credits (ElevenLabs voice). total is these credits at pricing.usdPerCredit."
        pricing:
          type: "object"
          description: "Rates this row was priced at. `provider` means the provider reported the charge itself (voice); `catalog` means Tether computed it."
          properties:
            source:
              type: "string"
              enum:
                - "catalog"
                - "gateway"
                - "provider"
                - "unavailable"
            pricedAt:
              type: "string"
              format: "date-time"
            inputPerM:
              type: "number"
            outputPerM:
              type: "number"
            cacheReadPerM:
              type: "number"
            cacheWritePerM:
              type: "number"
            usdPerCredit:
              type: "number"
              description: "USD for one provider credit, set when cost.credits is."
        startedAt:
          type: "string"
          format: "date-time"
        completedAt:
          type: "string"
          format: "date-time"
        durationMs:
          type: "integer"
        status:
          type: "string"
          enum:
            - "success"
            - "error"
        errorCode:
          type: "string"
          nullable: true
        backfill:
          type: "object"
          nullable: true
          description: "Set when a backfill script inserted or rewrote this row, naming the run so it can be undone. Absent on rows the product wrote."
          properties:
            source:
              type: "string"
            runId:
              type: "string"
            action:
              type: "string"
              enum:
                - "insert"
                - "update"
            at:
              type: "string"
              format: "date-time"
            insertRunId:
              type: "string"
              description: "On a rewrite of a row an earlier backfill run inserted: that run, which still owns the row."
    AiConsumptionListResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/AiConsumptionRecord"
        pagination:
          type: "object"
          properties:
            page:
              type: "integer"
            limit:
              type: "integer"
            total:
              type: "integer"
            totalPages:
              type: "integer"
    AiConsumptionBucket:
      type: "object"
      description: "One grouped row: the totals plus what they are grouped by."
      allOf:
        -
          "$ref": "#/components/schemas/AiConsumptionTotals"
        -
          type: "object"
          properties:
            key:
              type: "string"
            label:
              type: "string"
          required:
            - "key"
            - "label"
    AiConsumptionTimePoint:
      type: "object"
      description: "One bucket of the cost-over-time series, split by source type."
      allOf:
        -
          "$ref": "#/components/schemas/AiConsumptionTotals"
        -
          type: "object"
          properties:
            at:
              type: "string"
              format: "date-time"
            sourceType:
              type: "string"
          required:
            - "at"
            - "sourceType"
    AiConsumptionSummaryResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "object"
          properties:
            from:
              type: "string"
              format: "date-time"
            to:
              type: "string"
              format: "date-time"
            mcpToolCalls:
              type: "integer"
              description: "Tovi tool calls served over MCP in this window. Counted but never costed: over MCP the client runs its own model, so there are no tokens on Tether's side and these are not rows in the ledger. Zero when the view is filtered to a type other than Tovi."
            totals:
              "$ref": "#/components/schemas/AiConsumptionTotals"
            byType:
              type: "array"
              items:
                "$ref": "#/components/schemas/AiConsumptionBucket"
            byModel:
              type: "array"
              items:
                "$ref": "#/components/schemas/AiConsumptionBucket"
            byUser:
              type: "array"
              items:
                "$ref": "#/components/schemas/AiConsumptionBucket"
            byName:
              type: "array"
              items:
                "$ref": "#/components/schemas/AiConsumptionBucket"
            timeseries:
              type: "array"
              items:
                "$ref": "#/components/schemas/AiConsumptionTimePoint"
    AiModelsErrorResponse:
      type: "object"
      description: "Error envelope returned by AI Models endpoints. `error` may be present on contract-validation failures."
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
        error:
          description: "Optional error detail (string or structured object on validation failures)."
      required:
        - "success"
      additionalProperties: true
      example:
        success: false
        message: "Organization credentials not found"
    AiModelsSimpleSuccessResponse:
      type: "object"
      description: "Generic success envelope used for delete / update endpoints that do not return a resource."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
      required:
        - "success"
      additionalProperties: true
      example:
        success: true
        message: "API key for anthropic removed successfully"
    AiModelPricing:
      type: "object"
      properties:
        inputCost:
          type: "string"
          example: "$3.00 / 1M tokens"
        outputCost:
          type: "string"
          example: "$15.00 / 1M tokens"
      required:
        - "inputCost"
        - "outputCost"
      additionalProperties: true
    AiModelDetail:
      type: "object"
      description: "Persisted metadata for one model in an organization's catalog."
      properties:
        _id:
          type: "string"
        modelName:
          type: "string"
          description: "Provider model identifier."
        displayName:
          type: "string"
          description: "Human-readable picker label."
        tags:
          type: "array"
          items:
            type: "string"
          description: "Operator-managed presentation and capability labels."
        visible:
          type: "boolean"
          description: "Whether the model is offered for new selections. Missing legacy values behave as true."
          default: true
        pricing:
          "$ref": "#/components/schemas/AiModelPricing"
        description:
          type: "string"
        contextWindow:
          type: "integer"
          minimum: 1
        maxOutputTokens:
          type: "integer"
          minimum: 1
      required:
        - "modelName"
        - "pricing"
      additionalProperties: true
    AiModelDocument:
      type: "object"
      description: "A provider plus the models available in an organization's catalog."
      properties:
        _id:
          type: "string"
        providerName:
          type: "string"
        vercelUniqueName:
          type: "string"
          description: "Vercel AI SDK provider identifier (e.g. `anthropic`, `openai`, `google`)."
        websiteUrl:
          type: "string"
        modelDetails:
          type: "array"
          items:
            "$ref": "#/components/schemas/AiModelDetail"
          description: "Per-model organization catalog metadata."
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "5f7b1c2e8a1d4e0012c3b4a5"
        providerName: "Anthropic"
        vercelUniqueName: "anthropic"
        websiteUrl: "https://www.anthropic.com"
        modelDetails:
          -
            modelName: "claude-sonnet-4-6"
            description: "Latest Sonnet release."
          -
            modelName: "claude-haiku-4-5"
            description: "Fast, cost-efficient Haiku."
        createdAt: "2025-09-12T14:22:10.000Z"
        updatedAt: "2026-04-30T09:11:45.000Z"
    AiModelsListResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/AiModelDocument"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          -
            _id: "5f7b1c2e8a1d4e0012c3b4a5"
            providerName: "Anthropic"
            vercelUniqueName: "anthropic"
            websiteUrl: "https://www.anthropic.com"
            modelDetails:
              -
                modelName: "claude-sonnet-4-6"
          -
            _id: "5f7b1c2e8a1d4e0012c3b4a6"
            providerName: "OpenAI"
            vercelUniqueName: "openai"
            websiteUrl: "https://platform.openai.com"
            modelDetails:
              -
                modelName: "gpt-4o-mini"
    AiModelsCatalogModel:
      type: "object"
      description: "Editable model metadata normalized from the public Vercel AI Gateway catalog."
      properties:
        provider:
          type: "string"
          enum:
            - "anthropic"
            - "openai"
            - "google"
        modelName:
          type: "string"
        displayName:
          type: "string"
        description:
          type: "string"
        tags:
          type: "array"
          items:
            type: "string"
        pricing:
          "$ref": "#/components/schemas/AiModelPricing"
        contextWindow:
          type: "integer"
          minimum: 1
        maxOutputTokens:
          type: "integer"
          minimum: 1
      required:
        - "provider"
        - "modelName"
        - "displayName"
        - "tags"
        - "pricing"
      additionalProperties: false
    AiModelsCatalogResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/AiModelsCatalogModel"
      required:
        - "success"
        - "data"
      additionalProperties: false
    AiModelSingleResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          "$ref": "#/components/schemas/AiModelDocument"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          _id: "5f7b1c2e8a1d4e0012c3b4a5"
          providerName: "Anthropic"
          vercelUniqueName: "anthropic"
          websiteUrl: "https://www.anthropic.com"
          modelDetails:
            -
              modelName: "claude-sonnet-4-6"
            -
              modelName: "claude-haiku-4-5"
    AiModelsMaskedProvider:
      type: "object"
      description: "Per-organization configured AI provider entry. `apiKey` is masked (first 4 + last 4 characters)."
      properties:
        _id:
          type: "string"
        aiModel:
          description: "Populated `AiModelDocument` or the raw ObjectId reference."
          oneOf:
            -
              "$ref": "#/components/schemas/AiModelDocument"
            -
              type: "string"
        modelDetail:
          type: "string"
        apiKey:
          type: "string"
          description: "Masked representation of the stored API key."
      additionalProperties: true
      example:
        _id: "65f9b1c2e8a1d4e001a0b1c3"
        aiModel: "5f7b1c2e8a1d4e0012c3b4a5"
        modelDetail: "claude-sonnet-4-6"
        apiKey: "sk-a••••••••f9d2"
    AiModelsOrganizationProvidersResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            aiProviders:
              type: "array"
              items:
                "$ref": "#/components/schemas/AiModelsMaskedProvider"
            currentAiProviderIndex:
              type: "integer"
              nullable: true
            currentAiModelIndex:
              type: "integer"
              nullable: true
            currentAiModelVercelUniqueName:
              type: "string"
              nullable: true
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          aiProviders:
            -
              _id: "65f9b1c2e8a1d4e001a0b1c3"
              aiModel: "5f7b1c2e8a1d4e0012c3b4a5"
              modelDetail: "claude-sonnet-4-6"
              apiKey: "sk-a••••••••f9d2"
          currentAiProviderIndex: 0
          currentAiModelIndex: 0
          currentAiModelVercelUniqueName: "anthropic"
    AiModelsAvailableModelSummary:
      type: "object"
      description: "A single model available for a provider."
      properties:
        modelName:
          type: "string"
        displayName:
          type: "string"
        tags:
          type: "array"
          items:
            type: "string"
        visible:
          type: "boolean"
          description: "Visibility value stored in the registry; missing legacy values are included."
        description:
          type: "string"
        pricing:
          "$ref": "#/components/schemas/AiModelPricing"
        contextWindow:
          type: "integer"
          minimum: 1
        maxOutputTokens:
          type: "integer"
          minimum: 1
      additionalProperties: true
      example:
        modelName: "claude-sonnet-4-6"
        description: "Balanced reasoning + speed."
        pricing:
          inputCost: "$3.00 / 1M tokens"
          outputCost: "$15.00 / 1M tokens"
    AiModelsProviderStatus:
      type: "object"
      description: "Per-provider configuration / availability summary for the org settings view."
      properties:
        hasApiKey:
          type: "boolean"
        isEnabled:
          type: "boolean"
        providerName:
          type: "string"
        websiteUrl:
          type: "string"
        availableModels:
          type: "array"
          items:
            "$ref": "#/components/schemas/AiModelsAvailableModelSummary"
      additionalProperties: true
      example:
        hasApiKey: true
        isEnabled: true
        providerName: "Anthropic"
        websiteUrl: "https://www.anthropic.com"
        availableModels:
          -
            modelName: "claude-sonnet-4-6"
            description: "Balanced reasoning + speed."
          -
            modelName: "claude-haiku-4-5"
            description: "Fast and cost-efficient."
    AiModelsSectionAssignment:
      type: "object"
      description: "A model assignment for one system section (`dataExtraction`, `automations`, `messageGeneration`)."
      properties:
        provider:
          type: "string"
          enum:
            - "anthropic"
            - "openai"
            - "google"
        model:
          type: "string"
      additionalProperties: true
      example:
        provider: "anthropic"
        model: "claude-sonnet-4-6"
    AiModelsModelAssignmentsMap:
      type: "object"
      description: "Sparse map keyed by system section name. Sections may be absent if unassigned."
      properties:
        dataExtraction:
          "$ref": "#/components/schemas/AiModelsSectionAssignment"
        automations:
          "$ref": "#/components/schemas/AiModelsSectionAssignment"
        messageGeneration:
          "$ref": "#/components/schemas/AiModelsSectionAssignment"
      additionalProperties: true
      example:
        dataExtraction:
          provider: "openai"
          model: "gpt-4o-mini"
        automations:
          provider: "anthropic"
          model: "claude-haiku-4-5"
        messageGeneration:
          provider: "anthropic"
          model: "claude-sonnet-4-6"
    AiModelsOrganizationAiSettingsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            providers:
              type: "object"
              description: "Map keyed by provider `vercelUniqueName` (e.g. `anthropic`)."
              additionalProperties:
                "$ref": "#/components/schemas/AiModelsProviderStatus"
            modelAssignments:
              "$ref": "#/components/schemas/AiModelsModelAssignmentsMap"
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          providers:
            anthropic:
              hasApiKey: true
              isEnabled: true
              providerName: "Anthropic"
              websiteUrl: "https://www.anthropic.com"
              availableModels:
                -
                  modelName: "claude-sonnet-4-6"
            openai:
              hasApiKey: false
              isEnabled: false
              providerName: "OpenAI"
              websiteUrl: "https://platform.openai.com"
              availableModels:
                -
                  modelName: "gpt-4o-mini"
          modelAssignments:
            dataExtraction:
              provider: "anthropic"
              model: "claude-haiku-4-5"
            messageGeneration:
              provider: "anthropic"
              model: "claude-sonnet-4-6"
    AiModelsModelAssignmentsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          "$ref": "#/components/schemas/AiModelsModelAssignmentsMap"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          dataExtraction:
            provider: "openai"
            model: "gpt-4o-mini"
          automations:
            provider: "anthropic"
            model: "claude-haiku-4-5"
          messageGeneration:
            provider: "anthropic"
            model: "claude-sonnet-4-6"
    CreateAiModelRequest:
      type: "object"
      properties:
        providerName:
          type: "string"
          description: "Human-readable provider name shown in the admin UI (e.g. `Anthropic`, `OpenAI`)."
        vercelUniqueName:
          type: "string"
          description: "Vercel AI SDK provider identifier (e.g. `anthropic`, `openai`, `google`). Must be unique within the organization."
        websiteUrl:
          type: "string"
          description: "Provider marketing/docs URL displayed alongside the provider card."
        modelDetails:
          type: "array"
          items:
            "$ref": "#/components/schemas/AiModelDetail"
          description: "Per-model organization catalog metadata."
      required:
        - "providerName"
        - "vercelUniqueName"
      additionalProperties: true
      example:
        providerName: "Anthropic"
        vercelUniqueName: "anthropic"
        websiteUrl: "https://www.anthropic.com"
        modelDetails:
          -
            modelName: "claude-sonnet-4-6"
            description: "Balanced reasoning + speed."
    UpdateAiModelRequest:
      type: "object"
      properties:
        providerName:
          type: "string"
          description: "Human-readable provider name shown in the admin UI (e.g. `Anthropic`, `OpenAI`)."
        vercelUniqueName:
          type: "string"
          description: "Vercel AI SDK provider identifier (e.g. `anthropic`, `openai`, `google`). If changed, it must remain unique within the organization."
        websiteUrl:
          type: "string"
          description: "Provider marketing/docs URL displayed alongside the provider card."
        modelDetails:
          type: "array"
          items:
            "$ref": "#/components/schemas/AiModelDetail"
          description: "Per-model organization catalog metadata."
      additionalProperties: true
      example:
        providerName: "Anthropic"
        modelDetails:
          -
            modelName: "claude-sonnet-4-6"
          -
            modelName: "claude-haiku-4-5"
    AddOrganizationAiProviderRequest:
      type: "object"
      properties:
        aiModel:
          type: "string"
          description: "ObjectId of the `AiModel` registry entry (provider) to attach to this organization."
        modelDetail:
          type: "string"
          description: "`modelName` to use within the chosen provider; must exist in that AiModel's `modelDetails`."
        apiKey:
          type: "string"
          description: "Provider API key; stored encrypted and never returned in GET responses."
      required:
        - "aiModel"
        - "modelDetail"
        - "apiKey"
      additionalProperties: true
      example:
        aiModel: "5f7b1c2e8a1d4e0012c3b4a5"
        modelDetail: "claude-sonnet-4-6"
        apiKey: "sk-ant-api03-AbCdEf1234567890XyZ"
    UpdateOrganizationAiProviderRequest:
      type: "object"
      properties:
        modelDetail:
          type: "string"
          description: "New `modelName` for this provider entry; must exist in the underlying AiModel's `modelDetails`."
        apiKey:
          type: "string"
          description: "Replacement provider API key; stored encrypted and never returned in GET responses."
      additionalProperties: true
      example:
        modelDetail: "claude-haiku-4-5"
    SetCurrentAiModelRequest:
      type: "object"
      properties:
        index:
          type: "integer"
          description: "Position in the legacy `aiProviders[]` array. Superseded by section assignments."
        modelDetail:
          type: "string"
          description: "`modelName` to activate within the chosen provider; must exist in that AiModel's `modelDetails`."
        aiModelId:
          type: "string"
          description: "ObjectId of the `AiModel` registry entry whose `vercelUniqueName` becomes the org's current provider."
      required:
        - "index"
        - "modelDetail"
        - "aiModelId"
      additionalProperties: true
      example:
        index: 0
        modelDetail: "claude-sonnet-4-6"
        aiModelId: "5f7b1c2e8a1d4e0012c3b4a5"
    SetProviderApiKeyRequest:
      type: "object"
      properties:
        provider:
          type: "string"
          enum:
            - "anthropic"
            - "openai"
            - "google"
          description: "Provider whose key is being set, identified by its `vercelUniqueName`."
        apiKey:
          type: "string"
          description: "Provider API key; stored encrypted and never returned in GET responses."
        isEnabled:
          type: "boolean"
          description: "Whether the provider should be active immediately after the key is stored. Defaults to `true` when omitted."
      required:
        - "provider"
        - "apiKey"
      additionalProperties: true
      example:
        provider: "anthropic"
        apiKey: "sk-ant-api03-AbCdEf1234567890XyZ"
        isEnabled: true
    ToggleProviderStatusRequest:
      type: "object"
      properties:
        isEnabled:
          type: "boolean"
          description: "New enabled state for the provider; `false` disables it without removing the stored API key."
      required:
        - "isEnabled"
      additionalProperties: true
      example:
        isEnabled: false
    UpdateModelAssignmentRequest:
      type: "object"
      properties:
        section:
          type: "string"
          enum:
            - "dataExtraction"
            - "automations"
            - "messageGeneration"
          description: "Which system section this assignment governs: `dataExtraction`, `automations`, or `messageGeneration`."
        provider:
          type: "string"
          enum:
            - "anthropic"
            - "openai"
            - "google"
          description: "Provider that will serve this section, identified by its `vercelUniqueName`."
        model:
          type: "string"
          description: "`modelName` from the provider's `modelDetails`; must exist in the organization's catalog."
      required:
        - "section"
        - "provider"
        - "model"
      additionalProperties: true
      example:
        section: "messageGeneration"
        provider: "anthropic"
        model: "claude-sonnet-4-6"
    AiModelResponse:
      type: "object"
      description: "Single-provider success envelope returned by organization catalog create/update."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          "$ref": "#/components/schemas/AiModelDocument"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          _id: "5f7b1c2e8a1d4e0012c3b4a5"
          providerName: "Anthropic"
          vercelUniqueName: "anthropic"
          websiteUrl: "https://www.anthropic.com"
          modelDetails:
            -
              modelName: "claude-sonnet-4-6"
              description: "Latest Sonnet release."
            -
              modelName: "claude-haiku-4-5"
              description: "Fast, cost-efficient Haiku."
    SetProviderApiKeyResponse:
      type: "object"
      description: "Returned after a provider API key is set or updated."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        data:
          type: "object"
          properties:
            provider:
              type: "string"
              enum:
                - "anthropic"
                - "openai"
                - "google"
            isEnabled:
              type: "boolean"
            hasApiKey:
              type: "boolean"
              enum:
                - true
          required:
            - "provider"
            - "isEnabled"
            - "hasApiKey"
          additionalProperties: true
      required:
        - "success"
        - "message"
        - "data"
      additionalProperties: true
      example:
        success: true
        message: "API key for anthropic updated successfully"
        data:
          provider: "anthropic"
          isEnabled: true
          hasApiKey: true
    UpdateModelAssignmentResponse:
      type: "object"
      description: "Returned after a section's model assignment is updated."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        data:
          type: "object"
          properties:
            section:
              type: "string"
              enum:
                - "dataExtraction"
                - "automations"
                - "messageGeneration"
            assignment:
              type: "object"
              properties:
                provider:
                  type: "string"
                  enum:
                    - "anthropic"
                    - "openai"
                    - "google"
                model:
                  type: "string"
              required:
                - "provider"
                - "model"
              additionalProperties: true
          required:
            - "section"
            - "assignment"
          additionalProperties: true
      required:
        - "success"
        - "message"
        - "data"
      additionalProperties: true
      example:
        success: true
        message: "Model assignment for messageGeneration updated successfully"
        data:
          section: "messageGeneration"
          assignment:
            provider: "anthropic"
            model: "claude-sonnet-4-6"
    AIPlaygroundRequest:
      type: "object"
      properties:
        message:
          type: "string"
          description: "The latest user turn to send into the agent. Appended to `conversation` server-side; do not include it twice."
        promptId:
          type: "string"
          description: "Identifies the saved prompt to run this turn against. Required - the playground refuses to run without a target prompt."
        conversationId:
          type: "string"
          description: "Optional id of an existing conversation used for context lookup (variables, business context). The playground does not persist back into it."
        conversation:
          type: "array"
          description: "Prior turns the editor is replaying for this playground session. The server does not load history from storage - whatever is sent here is the entire visible history."
          items:
            type: "object"
            properties:
              role:
                type: "string"
              content:
                type: "string"
            additionalProperties: true
      required:
        - "message"
        - "promptId"
      additionalProperties: true
      example:
        message: "Hi, I was hoping to book a tour for next Tuesday."
        promptId: "5f7b1c2e8a1d4e0012c3b4a5"
        conversationId: "64d2f9c5e8a1d4e001a0b1c2"
        conversation:
          -
            role: "user"
            content: "Hello there"
          -
            role: "assistant"
            content: "Hi! How can I help today?"
    AIProcessRequest:
      type: "object"
      properties:
        conversationId:
          type: "string"
          description: "Target conversation to generate a reply for. Caller must own it, be assigned, or be ADMIN/SUPERADMIN. The literal value `new-sms` is rejected."
        mergeContextPrompt:
          type: "string"
          description: "Free-form context to splice into the system prompt for this single turn (e.g. tour notes, lead status) without modifying the saved prompt."
      required:
        - "conversationId"
      additionalProperties: true
      example:
        conversationId: "64d2f9c5e8a1d4e001a0b1c2"
        mergeContextPrompt: "The lead just toured the property and is comparing two units."
    AiModelOverride:
      type: "object"
      properties:
        provider:
          type: "string"
          enum:
            - "anthropic"
            - "openai"
            - "google"
        model:
          type: "string"
      required:
        - "provider"
        - "model"
      additionalProperties: false
      example:
        provider: "anthropic"
        model: "claude-sonnet-4-6"
    AICalendarPlaygroundRequest:
      type: "object"
      properties:
        message:
          type: "string"
        promptOverride:
          type: "string"
          description: "Calendar agent system prompt text being edited by the tester"
        conversation:
          type: "array"
          items:
            type: "object"
            properties:
              role:
                type: "string"
                enum:
                  - "user"
                  - "assistant"
              content:
                type: "string"
            additionalProperties: true
      required:
        - "message"
      additionalProperties: true
      example:
        message: "Can we book me in for Tuesday at 2pm?"
        promptOverride: "<calendarAgent>You are a scheduling assistant. Ask clarifying questions and confirm before booking.</calendarAgent>"
        conversation:
          -
            role: "user"
            content: "I would like to schedule a tour."
          -
            role: "assistant"
            content: "Sure - which day works for you?"
    AINLCreateRequest:
      type: "object"
      properties:
        instruction:
          type: "string"
          description: "Natural-language ask describing what the prompt should accomplish."
        existingPrompt:
          type: "string"
          description: "Optional current prompt XML to iteratively refine; absent for first-draft generation."
        conversationHistory:
          type: "array"
          description: "Prior turns in this prompt-drafting session, replayed so the model can continue an iterative refinement thread."
          items:
            type: "object"
            properties:
              role:
                type: "string"
                enum:
                  - "user"
                  - "assistant"
              content:
                type: "string"
            required:
              - "role"
              - "content"
        variableContext:
          type: "object"
          additionalProperties: true
          description: "Available runtime variables and field scopes (grouped) the editor exposes; constrains the model to real `@variables` instead of inventing placeholders."
        assistedMode:
          type: "boolean"
          description: "When true, drafting uses the stronger battle-tested XML architecture system prompt; otherwise stays closer to the user request with lighter guardrails."
        modelOverride:
          "$ref": "#/components/schemas/AiModelOverride"
          description: "Pin to a specific provider/model (e.g. `{ provider: 'anthropic', model: 'claude-sonnet-4-6' }`) overriding the org's default assignment."
      required:
        - "instruction"
      additionalProperties: true
      example:
        instruction: "Draft a friendly follow-up agent that re-engages leads 24h after the last reply."
        existingPrompt: ""
        conversationHistory:
          []
        variableContext:
          firstName: "Alex"
          propertyName: "Maple Court"
        assistedMode: true
        modelOverride:
          provider: "anthropic"
          model: "claude-sonnet-4-6"
    AINLCreateResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        prompt:
          type: "string"
          description: "Generated XML prompt"
      required:
        - "success"
        - "prompt"
      additionalProperties: true
      example:
        success: true
        prompt: "<prompt><role>Friendly leasing follow-up agent</role><goal>Re-engage leads 24h after their last reply.</goal></prompt>"
    AINLEditRequest:
      type: "object"
      properties:
        selectedText:
          type: "string"
          description: "The exact substring the user highlighted in the editor; the model rewrites only this slice and the caller splices the result back in."
        instruction:
          type: "string"
          description: "Natural-language directive for how to rewrite the selection."
        fullPrompt:
          type: "string"
          description: "The full surrounding XML prompt, supplied as read-only context so the rewrite stays consistent in tone and structure."
        context:
          type: "string"
          description: "Optional hint about where the selection lives (e.g. `goal section`, `rule list`) to disambiguate the rewrite target."
        variableContext:
          type: "object"
          additionalProperties: true
          description: "Available runtime variables and field scopes; constrains the rewrite to real `@variables` instead of inventing placeholders."
        assistedMode:
          type: "boolean"
          description: "When true, editing uses the stronger battle-tested XML architecture system prompt; otherwise stays closer to the user request with lighter guardrails."
        modelOverride:
          "$ref": "#/components/schemas/AiModelOverride"
          description: "Pin to a specific provider/model (e.g. `{ provider: 'anthropic', model: 'claude-sonnet-4-6' }`) overriding the org's default assignment."
      required:
        - "selectedText"
        - "instruction"
      additionalProperties: true
      example:
        selectedText: "Reply promptly to all leads."
        instruction: "Make this more specific - mention SLA of 5 minutes during business hours."
        fullPrompt: "<prompt><role>Leasing assistant</role><goal>Reply promptly to all leads.</goal></prompt>"
        context: "goal section"
        assistedMode: false
        modelOverride:
          provider: "openai"
          model: "gpt-4o-mini"
    AINLEditResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        rewrittenText:
          type: "string"
      required:
        - "success"
        - "rewrittenText"
      additionalProperties: true
      example:
        success: true
        rewrittenText: "Reply to all leads within 5 minutes during business hours (Mon-Fri, 9am-6pm local)."
    AIPlaygroundApprovalCancelRequest:
      type: "object"
      properties:
        approvalKey:
          type: "string"
          description: "Opaque key issued with the approval card. Idempotent - a no-op if the approval has already expired or been consumed."
      required:
        - "approvalKey"
      additionalProperties: true
      example:
        approvalKey: "playground:5f7b1c2e8a1d4e0012c3b4a5:tool-call-7c2a"
    AIPlaygroundApprovalRespondRequest:
      type: "object"
      properties:
        approvalKey:
          type: "string"
          description: "Opaque key for the approval card being resolved. Single-use - consumed atomically; a second call returns `approval_expired`."
        decision:
          type: "string"
          enum:
            - "approve"
            - "reject"
          description: "`approve` runs the tool with the captured args; `reject` stashes a sentinel so the agent acknowledges and moves on."
        conversation:
          type: "array"
          description: "Visible playground history at the moment the user clicked the approval card. Replayed on resume; a synthetic resume note is appended server-side."
          items:
            type: "object"
            properties:
              role:
                type: "string"
                enum:
                  - "user"
                  - "assistant"
              content:
                type: "string"
            additionalProperties: true
          default:
            []
        promptId:
          type: "string"
          description: "Prompt id used for the original playground turn; the resumed turn re-runs the same prompt so behavior stays consistent."
        conversationId:
          type: "string"
          description: "Optional conversation id used for context lookup on the resumed turn; matches the value originally passed to `/api/ai/playground`."
        promptOverride:
          type: "string"
          description: "Optional inline prompt text that replaces the saved prompt for this resumed turn - used by editors testing un-saved edits."
        modelOverride:
          "$ref": "#/components/schemas/AiModelOverride"
          description: "Pin the resumed turn to a specific provider/model (e.g. `{ provider: 'anthropic', model: 'claude-sonnet-4-6' }`) overriding the org's default assignment."
      required:
        - "approvalKey"
        - "decision"
        - "promptId"
      additionalProperties: true
      example:
        approvalKey: "playground:5f7b1c2e8a1d4e0012c3b4a5:tool-call-7c2a"
        decision: "approve"
        conversation:
          -
            role: "user"
            content: "Please book me for Tuesday at 2pm."
          -
            role: "assistant"
            content: "I will go ahead and request that slot."
        promptId: "5f7b1c2e8a1d4e0012c3b4a5"
        conversationId: "64d2f9c5e8a1d4e001a0b1c2"
        modelOverride:
          provider: "anthropic"
          model: "claude-sonnet-4-6"
    AIErrorResponse:
      type: "object"
      description: "Error envelope used across AI endpoints. The `error` field is a stable machine-readable code on approval-related failures (`approval_owner_mismatch`, `approval_org_mismatch`, `approval_expired`, `approval_service_unavailable`) and a human-readable string elsewhere. `message` is set alongside on the approval paths so the UI can render both."
      properties:
        success:
          type: "boolean"
          enum:
            - false
        error:
          type: "string"
        message:
          type: "string"
      required:
        - "error"
      additionalProperties: true
      example:
        success: false
        error: "approval_expired"
        message: "This approval request has expired or was already handled. Please send a new playground message to retry."
    AISimpleSuccessResponse:
      type: "object"
      description: "Generic 200 envelope for fire-and-forget AI endpoints (e.g. approval/cancel)."
      properties:
        success:
          type: "boolean"
          enum:
            - true
      required:
        - "success"
      additionalProperties: true
      example:
        success: true
    AIApprovalCard:
      type: "object"
      description: "Pending tool-approval card surfaced by the playground when the agent wants to run a tool that requires sign-off."
      properties:
        approvalId:
          type: "string"
        toolName:
          type: "string"
        toolArgs:
          type: "object"
          additionalProperties: true
        createdAt:
          type: "string"
          format: "date-time"
        expiresAt:
          type: "string"
          format: "date-time"
      required:
        - "approvalId"
        - "toolName"
      additionalProperties: true
      example:
        approvalId: "apr_64d2f9c5e8a1d4e001a0b1c2"
        toolName: "sendSms"
        toolArgs:
          phone: "+14165550100"
          message: "Hi Alex - confirming your appointment for Friday at 2pm."
        createdAt: "2026-05-20T15:04:01.135Z"
        expiresAt: "2026-05-20T15:09:01.135Z"
    AIPlaygroundMessageMetric:
      type: "object"
      description: "MessageMetric snapshot captured for the playground turn - only included for ADMIN/SUPERADMIN callers. Surfaces underlying AI calls and tool calls for debugging."
      properties:
        organizationId:
          type: "string"
        metricRunId:
          type: "string"
        aiAgentName:
          type: "string"
        aiCalls:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
        toolCalls:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
      additionalProperties: true
      example:
        organizationId: "64a1b2c3d4e5f60012345678"
        metricRunId: "run_64d2f9c5e8a1d4e001a0b1c2"
        aiAgentName: "Leasing Specialist"
        aiCalls:
          -
            provider: "anthropic"
            model: "claude-sonnet-4-6"
            inputTokens: 412
            outputTokens: 88
            durationMs: 1742
        toolCalls:
          -
            name: "getContact"
            args:
              phone: "+14165550100"
            durationMs: 84
    AIPlaygroundResponse:
      type: "object"
      description: "Playground turn result. `approvalCards` is only set when the agent paused for tool approval; `messageMetric` is only set for ADMIN/SUPERADMIN."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        response:
          type: "string"
        approvalCards:
          type: "array"
          items:
            "$ref": "#/components/schemas/AIApprovalCard"
        messageMetric:
          "$ref": "#/components/schemas/AIPlaygroundMessageMetric"
      required:
        - "success"
        - "response"
      additionalProperties: true
      example:
        success: true
        response: "Great - I can book you for Friday at 2pm. Want me to send a confirmation text?"
        messageMetric:
          organizationId: "64a1b2c3d4e5f60012345678"
          metricRunId: "run_64d2f9c5e8a1d4e001a0b1c2"
          aiAgentName: "Leasing Specialist"
          aiCalls:
            []
          toolCalls:
            []
    AIPlaygroundApprovalRespondResponse:
      type: "object"
      description: "Returned after a playground approval is resolved (approve or reject). `response` carries the resumed agent reply; `toolError` flags that the underlying tool execution failed."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        response:
          type: "string"
        decision:
          type: "string"
          enum:
            - "approve"
            - "reject"
        toolError:
          type: "boolean"
        approvalCards:
          type: "array"
          items:
            "$ref": "#/components/schemas/AIApprovalCard"
      required:
        - "success"
        - "response"
        - "decision"
      additionalProperties: true
      example:
        success: true
        decision: "approve"
        response: "Sent! I just texted Alex the confirmation."
    AIProcessResponse:
      type: "object"
      description: "Returned by `/api/ai/process` after the AI reply has been generated and persisted into the conversation."
      properties:
        message:
          type: "string"
          description: "The generated assistant message text that was appended to the conversation."
      required:
        - "message"
      additionalProperties: true
      example:
        message: "Hi Alex - thanks for reaching out! Are you still interested in the Maple Court corner unit?"
    CreateApplicationConfigRequest:
      type: "object"
      properties:
        configurationName:
          type: "string"
          description: "Internal identifier shown in the Applications management list (unique per org)."
        name:
          type: "string"
          description: "Display name surfaced on the Application record."
        description:
          type: "string"
          description: "Free-text note explaining what this configuration is used for."
        source:
          type: "string"
          default: "Any"
          description: "Origin label (e.g. `Zillow`, `Encompass`) used to attribute leads."
        defaultStatus:
          type: "string"
          description: "Initial status applied to new Applications created with this config."
        allowRecontact:
          type: "boolean"
          default: false
          description: "When true, the same contact can produce additional Applications even if a prior one exists."
        status:
          type: "string"
          enum:
            - "active"
            - "inactive"
          default: "active"
          description: "Lifecycle state of the config itself: `active` makes it selectable, `inactive` retires it."
      required:
        - "configurationName"
        - "defaultStatus"
      additionalProperties: true
      example:
        configurationName: "Mortgage CRM Webhook"
        name: "mortgage-crm"
        description: "Maps applications from Encompass CRM"
        source: "Encompass"
        defaultStatus: "new"
        allowRecontact: false
        status: "active"
    UpdateApplicationConfigRequest:
      type: "object"
      properties:
        configurationName:
          type: "string"
          description: "Internal identifier shown in the Applications management list (unique per org)."
        name:
          type: "string"
          description: "Display name surfaced on the Application record."
        description:
          type: "string"
          description: "Free-text note explaining what this configuration is used for."
        source:
          type: "string"
          description: "Origin label (e.g. `Zillow`, `Encompass`) used to attribute leads."
        defaultStatus:
          type: "string"
          description: "Initial status applied to new Applications created with this config."
        allowRecontact:
          type: "boolean"
          description: "When true, the same contact can produce additional Applications even if a prior one exists."
        status:
          type: "string"
          enum:
            - "active"
            - "inactive"
          description: "Lifecycle state of the config itself: `active` makes it selectable, `inactive` retires it."
      additionalProperties: true
      example:
        status: "inactive"
        description: "Deprecated; replaced by Encompass v2 integration"
    ApplicationConfigResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        message:
          type: "string"
        data:
          type: "object"
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        message: "Configuration created"
        data:
          _id: "66c0a0b0c0d0e0f0a0b0c0d0"
          configurationName: "Mortgage CRM Webhook"
          source: "Encompass"
          defaultStatus: "new"
          status: "active"
          organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
    ApplicationConfigListResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
      additionalProperties: true
      example:
        success: true
        data:
          -
            _id: "66c0a0b0c0d0e0f0a0b0c0d0"
            configurationName: "Mortgage CRM Webhook"
            source: "Encompass"
            status: "active"
    ApplicationManagementErrorResponse:
      type: "object"
      description: "Error envelope for `/api/application-management` endpoints. Most failures only set `error`; mutating endpoints occasionally surface a `success:false` + `message` pair."
      properties:
        error:
          type: "string"
        message:
          type: "string"
        success:
          type: "boolean"
          enum:
            - false
      required:
        - "error"
      additionalProperties: true
      example:
        error: "Application management entry not found"
    ApplicationsErrorResponse:
      type: "object"
      description: "Standard error envelope for Applications endpoints (CRUD + list)."
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
        error:
          description: "Optional error detail (string or structured object on validation failures)."
      required:
        - "success"
      additionalProperties: true
      example:
        success: false
        message: "Application not found"
    ApplicationsBareErrorResponse:
      type: "object"
      description: "Bare error envelope used by `/conversations` and `/time-to-contact` routes which respond with `{ error }` only."
      properties:
        error:
          type: "string"
      required:
        - "error"
      additionalProperties: true
      example:
        error: "Application not found"
    ApplicationsSimpleSuccessResponse:
      type: "object"
      description: "Generic success envelope used for delete endpoints that do not return a resource."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
      required:
        - "success"
      additionalProperties: true
      example:
        success: true
        message: "Application deleted successfully"
    ApplicationDocument:
      type: "object"
      description: "An `Application` document. Applications are org-owned and have no owner; `assignees` carries who works them. Populated fields (`contactId`, `assignees`) may be either an ObjectId string or a partial subset of the related document."
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        organizationId:
          type: "string"
        contactId:
          description: "ObjectId or populated Contact subset (firstName, lastName, phoneNumber, email)."
        assignees:
          type: "array"
          description: "Users assigned to work this application. ObjectIds or populated User subsets (fullName, email). An empty array means unassigned."
          items:
            {}
        status:
          type: "string"
        pipelineId:
          type: "string"
          nullable: true
        pipelineStage:
          type: "string"
          nullable: true
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "64d2f9c5e8a1d4e001a0b1c2"
        name: "Maple Court - Unit 412"
        organizationId: "64a1b2c3d4e5f60012345678"
        contactId:
          _id: "64b2c3d4e5f60012345678aa"
          firstName: "Alex"
          lastName: "Nguyen"
          phoneNumber: "+14155551234"
          email: "alex.nguyen@example.com"
        assignees:
          -
            _id: "64a1b2c3d4e5f60012345679"
            fullName: "Jordan Lee"
            email: "jordan@maplegroup.example"
        status: "in_progress"
        pipelineId: "64a1b2c3d4e5f6001234567a"
        pipelineStage: "Tour scheduled"
        createdAt: "2026-04-12T14:22:10.000Z"
        updatedAt: "2026-04-22T10:14:00.000Z"
    ApplicationSingleResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          "$ref": "#/components/schemas/ApplicationDocument"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          _id: "64d2f9c5e8a1d4e001a0b1c2"
          name: "Maple Court - Unit 412"
          organizationId: "64a1b2c3d4e5f60012345678"
          status: "in_progress"
          pipelineId: "64a1b2c3d4e5f6001234567a"
          pipelineStage: "Tour scheduled"
          createdAt: "2026-04-12T14:22:10.000Z"
          updatedAt: "2026-04-22T10:14:00.000Z"
    ApplicationMutationResponse:
      type: "object"
      description: "Returned by `POST /api/applications` and `PUT /api/applications/{id}` - wraps the created/updated `ApplicationDocument` plus a status message."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        data:
          "$ref": "#/components/schemas/ApplicationDocument"
      required:
        - "success"
        - "message"
        - "data"
      additionalProperties: true
      example:
        success: true
        message: "Application created successfully"
        data:
          _id: "64d2f9c5e8a1d4e001a0b1c2"
          name: "Maple Court - Unit 412"
          organizationId: "64a1b2c3d4e5f60012345678"
          status: "in_progress"
          pipelineStage: "Tour scheduled"
          createdAt: "2026-04-12T14:22:10.000Z"
          updatedAt: "2026-04-12T14:22:10.000Z"
    ApplicationsPaginatedListResponse:
      type: "object"
      description: "Paginated list response for `POST /api/applications/list`."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/ApplicationDocument"
        total:
          type: "integer"
          description: "Total matching applications across all pages."
        page:
          type: "integer"
        size:
          type: "integer"
      required:
        - "success"
        - "data"
        - "total"
        - "page"
        - "size"
      additionalProperties: true
      example:
        success: true
        total: 142
        page: 1
        size: 10
        data:
          -
            _id: "64d2f9c5e8a1d4e001a0b1c2"
            name: "Maple Court - Unit 412"
            status: "in_progress"
            pipelineStage: "Tour scheduled"
    ApplicationsQueryResponse:
      type: "object"
      description: "List response for `GET /api/applications` (query-string variant). Returns all matches, sorted by `createdAt` desc."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/ApplicationDocument"
        total:
          type: "integer"
          description: "Number of applications returned (no pagination on this endpoint)."
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          -
            _id: "64d2f9c5e8a1d4e001a0b1c2"
            name: "Maple Court - Unit 412"
            organizationId: "64a1b2c3d4e5f60012345678"
            status: "in_progress"
            pipelineStage: "Tour scheduled"
            createdAt: "2026-04-12T14:22:10.000Z"
            updatedAt: "2026-04-22T10:14:00.000Z"
        total: 1
    ApplicationLinkedConversation:
      type: "object"
      description: "Conversation summary returned by `GET /api/applications/{id}/conversations`. Selected fields only plus a derived `conversationState`."
      properties:
        _id:
          type: "string"
        contactId:
          type: "string"
        channelType:
          type: "string"
        channelIdentifier:
          type: "string"
        subject:
          type: "string"
        lastMessageTime:
          type: "string"
          format: "date-time"
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
        latestMessage:
          type: "object"
          additionalProperties: true
        isResolved:
          type: "boolean"
        isAutopilot:
          type: "boolean"
        conversationState:
          type: "string"
          description: "Derived state from the latest message map."
      additionalProperties: true
      example:
        _id: "64d2f9c5e8a1d4e001a0b1c2"
        contactId: "64b2c3d4e5f60012345678aa"
        channelType: "sms"
        channelIdentifier: "+14155551234"
        subject: "Tour follow-up"
        lastMessageTime: "2026-04-22T10:14:00.000Z"
        createdAt: "2026-04-12T14:22:10.000Z"
        updatedAt: "2026-04-22T10:14:00.000Z"
        latestMessage:
          direction: "inbound"
          body: "Sounds good, see you Tuesday."
        isResolved: false
        isAutopilot: true
        conversationState: "awaiting_reply"
    ApplicationConversationsResponse:
      type: "object"
      description: "Note: this endpoint does NOT use the `{ success, data }` envelope - it returns the conversations array and a count at the top level."
      properties:
        conversations:
          type: "array"
          items:
            "$ref": "#/components/schemas/ApplicationLinkedConversation"
        count:
          type: "integer"
      required:
        - "conversations"
        - "count"
      additionalProperties: true
      example:
        conversations:
          -
            _id: "64d2f9c5e8a1d4e001a0b1c2"
            contactId: "64b2c3d4e5f60012345678aa"
            channelType: "sms"
            subject: "Tour follow-up"
            lastMessageTime: "2026-04-22T10:14:00.000Z"
            isResolved: false
            isAutopilot: true
            conversationState: "awaiting_reply"
        count: 1
    ApplicationTimeToContactResponse:
      type: "object"
      description: "Time elapsed between application creation and the first outbound message in any linked conversation. `timeToContact` and `firstContactAt` are null when no outbound message has been sent yet."
      properties:
        timeToContact:
          type: "integer"
          nullable: true
          description: "Milliseconds between application creation and first outbound message. Null if no outbound message yet."
        unit:
          type: "string"
          enum:
            - "milliseconds"
        firstContactAt:
          type: "string"
          format: "date-time"
          nullable: true
        message:
          type: "string"
          description: "Explanatory message when `timeToContact` is null."
        formatted:
          type: "object"
          description: "Same value expressed in different units (only present on the success path)."
          properties:
            milliseconds:
              type: "integer"
            seconds:
              type: "integer"
            minutes:
              type: "integer"
            hours:
              type: "integer"
            days:
              type: "integer"
          additionalProperties: true
      required:
        - "unit"
      additionalProperties: true
      example:
        timeToContact: 184000
        unit: "milliseconds"
        firstContactAt: "2026-04-12T14:25:14.000Z"
        formatted:
          milliseconds: 184000
          seconds: 184
          minutes: 3
          hours: 0
          days: 0
    CreateApplicationRequest:
      type: "object"
      properties:
        contactId:
          type: "string"
          description: "Contact `_id` this Application belongs to."
        name:
          type: "string"
          description: "Display name for the Application (e.g. property/unit label)."
        status:
          type: "string"
          description: "Initial status label; mutually exchangeable with `pipelineStage` (one of the two must be provided)."
        pipelineStage:
          type: "string"
          description: "Stage `_id` within the chosen pipeline."
        pipelineId:
          type: "string"
          description: "Pipeline `_id` this Application is tracked under."
        assignees:
          type: "array"
          items:
            type: "string"
          description: "User `_id`s to assign to the Application. Omit or send `[]` for none. Applications have no owner; a `userId` in the body is ignored."
      required:
        - "contactId"
        - "name"
      description: "Either status or pipelineStage should be provided."
      additionalProperties: true
      example:
        contactId: "64b2c3d4e5f60012345678aa"
        name: "Maple Court - Unit 412"
        pipelineStage: "New lead"
        pipelineId: "64a1b2c3d4e5f6001234567a"
    ListApplicationsRequest:
      type: "object"
      properties:
        page:
          type: "integer"
          minimum: 1
          default: 1
        size:
          type: "integer"
          minimum: 1
          default: 10
        search:
          type: "string"
        contactId:
          type: "string"
        status:
          type: "string"
        pipelineStage:
          type: "string"
        pipelineStageIds:
          type: "string"
          description: "JSON array string or single id string."
        assignees:
          type: "array"
          items:
            type: "string"
          description: "Assigned user `_id`s to filter by (matches any). Include `unassigned` to match applications with no assignees."
      additionalProperties: true
      example:
        page: 1
        size: 25
        search: "maple court"
        pipelineStage: "Tour scheduled"
        assignees:
          - "64a1b2c3d4e5f60012345679"
    SetApplicationAssigneesRequest:
      type: "object"
      properties:
        assigneeIds:
          type: "array"
          items:
            type: "string"
          maxItems: 50
          description: "User `_id`s to assign, replacing the current list wholesale. Send `[]` to unassign everyone. Must be exact ids, with no duplicates."
        expectedRevision:
          type: "integer"
          minimum: 0
          description: "The `revision` of the Application you read. The write is rejected with 409 if it has changed since."
        commandIdempotencyKey:
          type: "string"
          description: "Caller-generated key; replaying it returns the first result."
      required:
        - "assigneeIds"
        - "expectedRevision"
        - "commandIdempotencyKey"
      example:
        assigneeIds:
          - "64a1b2c3d4e5f60012345679"
        expectedRevision: 4
        commandIdempotencyKey: "a7f3c0de-1b2a-4c3d-9e8f-0a1b2c3d4e5f"
    UpdateApplicationRequest:
      type: "object"
      properties:
        _id:
          type: "string"
          description: "Application `_id` (redundant with the path id; tolerated for legacy clients)."
        fromHistoryModal:
          type: "boolean"
          description: "Suppresses side-effects (audit log, socket emit) when the update originates from the history viewer."
        pipelineId:
          type: "string"
          description: "New pipeline `_id` if moving the Application to a different pipeline."
      additionalProperties: true
      example:
        pipelineId: "64a1b2c3d4e5f6001234567a"
        pipelineStage: "Application submitted"
        status: "in_progress"
    TriggerApplicationRequest:
      type: "object"
      properties:
        phoneNumber:
          type: "array"
          items:
            type: "object"
            properties:
              value:
                type: "string"
              isActive:
                type: "boolean"
            required:
              - "value"
        firstName:
          type: "string"
        lastName:
          type: "string"
        name:
          type: "string"
          description: "Application name"
        status:
          type: "string"
          description: "Application status"
        description:
          type: "string"
        notes:
          type: "string"
        amount:
          type: "number"
        loanType:
          type: "string"
        applicationDate:
          type: "string"
      required:
        - "phoneNumber"
        - "firstName"
        - "lastName"
        - "name"
        - "status"
      additionalProperties: true
      example:
        phoneNumber:
          -
            value: "+14155550123"
            isActive: true
        firstName: "Jane"
        lastName: "Doe"
        name: "Refi 2026-05"
        status: "submitted"
        amount: 425000
        loanType: "conventional"
        applicationDate: "2026-05-18"
        notes: "Referred by Brenda"
    TriggerApplicationResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        message:
          type: "string"
        data:
          type: "object"
          properties:
            application:
              type: "object"
              additionalProperties: true
            contact:
              type: "object"
              properties:
                id:
                  type: "string"
                phoneNumber:
                  type: "array"
                  items:
                    type: "object"
                    properties:
                      value:
                        type: "string"
                      isPrimary:
                        type: "boolean"
                    required:
                      - "value"
                firstName:
                  type: "string"
                lastName:
                  type: "string"
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        message: "Application received successfully"
        data:
          application:
            _id: "66b0a0b0c0d0e0f0a0b0c0d0"
            name: "Refi 2026-05"
            status: "submitted"
            amount: 425000
          contact:
            id: "65c2d0e0f0a0b0c0d0e0f0a0"
            phoneNumber:
              -
                value: "+14155550123"
                isPrimary: true
            firstName: "Jane"
            lastName: "Doe"
    ApplicationTriggerErrorResponse:
      type: "object"
      description: "Error envelope for `/api/application-trigger` (legacy API-key authed external entry point)."
      properties:
        error:
          type: "string"
        message:
          type: "string"
        success:
          type: "boolean"
          enum:
            - false
      required:
        - "error"
      additionalProperties: true
      example:
        error: "Invalid API key"
    ApprovalRespondRequest:
      type: "object"
      properties:
        approvalRequestId:
          type: "string"
          description: "Approval row `_id` returned in the pending-approvals list."
        webchatId:
          type: "string"
          description: "Webchat session id used to authenticate the responder (when responding via the webchat surface)."
        response:
          type: "string"
          enum:
            - "approved"
            - "rejected"
          description: "`approved` or `rejected`."
      required:
        - "approvalRequestId"
        - "webchatId"
        - "response"
      additionalProperties: false
      example:
        approvalRequestId: "64d2f9c5e8a1d4e001a0b1c2"
        webchatId: "wc_8f3a1b2c4d5e6f70"
        response: "approved"
    ApprovalRespondResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        status:
          type: "string"
          enum:
            - "approved"
            - "rejected"
            - "failed"
        result:
          {}
        failureReason:
          type: "string"
      required:
        - "success"
        - "status"
      additionalProperties: true
      example:
        success: true
        status: "approved"
        result:
          bookingId: "bk_64a1b2c3d4e5f60012345678"
          confirmedAt: "2026-04-22T10:14:00.000Z"
    ApprovalInternalActionRequest:
      type: "object"
      properties:
        notes:
          type: "string"
          description: "Optional reviewer note attached to the approve/reject action."
      additionalProperties: true
      example:
        notes: "Cannot approve - pricing is outside the agreed range."
    ApprovalInternalActionResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        status:
          type: "string"
          enum:
            - "approved"
            - "rejected"
            - "failed"
        result:
          {}
        failureReason:
          type: "string"
      required:
        - "success"
        - "status"
      additionalProperties: true
      example:
        success: true
        status: "approved"
        result:
          bookingId: "bk_64a1b2c3d4e5f60012345678"
    ApprovalRequestDto:
      type: "object"
      properties:
        _id:
          type: "string"
        organizationId:
          type: "string"
        userId:
          oneOf:
            -
              type: "string"
            -
              type: "object"
              additionalProperties: true
        contactId:
          oneOf:
            -
              type: "string"
            -
              type: "object"
              additionalProperties: true
        conversationId:
          type: "string"
        messageId:
          type: "string"
        approvalType:
          type: "string"
          enum:
            - "contact"
            - "internal"
        internalApprovalMode:
          type: "string"
          enum:
            - "blocking"
            - "non_blocking"
          nullable: true
        status:
          type: "string"
          enum:
            - "pending"
            - "approved"
            - "rejected"
            - "failed"
            - "skipped"
        question:
          type: "string"
        deferredTool:
          type: "string"
        deferredToolArgs:
          type: "object"
          additionalProperties: true
        deferredToolResult:
          {}
        failureReason:
          type: "string"
          nullable: true
        rejectionNotes:
          type: "string"
          nullable: true
        approvedBy:
          nullable: true
          oneOf:
            -
              type: "string"
            -
              type: "object"
              additionalProperties: true
        escalationTargets:
          type: "array"
          items:
            oneOf:
              -
                type: "string"
              -
                type: "object"
                additionalProperties: true
        internalInterimMessage:
          type: "string"
          nullable: true
        respondedAt:
          type: "string"
          format: "date-time"
          nullable: true
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "64d2f9c5e8a1d4e001a0b1c2"
        organizationId: "64a1b2c3d4e5f60012345678"
        userId:
          _id: "64a1b2c3d4e5f60012345679"
          fullName: "Jordan Lee"
        contactId:
          _id: "64b2c3d4e5f60012345678aa"
          firstName: "Alex"
          lastName: "Nguyen"
          phoneNumber: "+14155551234"
        conversationId: "64d2f9c5e8a1d4e001a0b1c3"
        messageId: "64d2f9c5e8a1d4e001a0b1c4"
        approvalType: "internal"
        internalApprovalMode: "blocking"
        status: "pending"
        question: "Approve booking a Tuesday 2pm tour for Alex Nguyen?"
        deferredTool: "book_tour"
        deferredToolArgs:
          startsAt: "2026-04-29T18:00:00.000Z"
          contactId: "64b2c3d4e5f60012345678aa"
        escalationTargets:
          -
            _id: "64a1b2c3d4e5f6001234567b"
            fullName: "Sam Patel"
        createdAt: "2026-04-22T10:14:00.000Z"
        updatedAt: "2026-04-22T10:14:00.000Z"
    ApprovalListResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        approvals:
          type: "array"
          items:
            "$ref": "#/components/schemas/ApprovalRequestDto"
        total:
          type: "integer"
        limit:
          type: "integer"
        skip:
          type: "integer"
      required:
        - "success"
        - "approvals"
        - "total"
        - "limit"
        - "skip"
      additionalProperties: true
      example:
        success: true
        approvals:
          -
            _id: "64d2f9c5e8a1d4e001a0b1c2"
            approvalType: "internal"
            status: "pending"
            question: "Approve booking a Tuesday 2pm tour for Alex Nguyen?"
            deferredTool: "book_tour"
            createdAt: "2026-04-22T10:14:00.000Z"
        total: 1
        limit: 50
        skip: 0
    ApprovalErrorResponse:
      type: "object"
      description: "Error envelope for the Approval system. The internal approve/reject paths return `code` enums (`already_resolved`, `forbidden`, `not_found`) when a row was already consumed or the caller is not the owner; the public respond endpoint returns the same envelope."
      properties:
        error:
          type: "string"
        message:
          type: "string"
        code:
          type: "string"
        success:
          type: "boolean"
          enum:
            - false
      required:
        - "error"
      additionalProperties: true
      example:
        error: "Approval already resolved"
        code: "already_resolved"
    AuthConnectionPublicJwk:
      type: "object"
      description: "The public half of the connection key, in JWK form. Safe to display and to hand to the gateway operator, who may need to register it."
      properties:
        kty:
          type: "string"
        crv:
          type: "string"
        x:
          type: "string"
        y:
          type: "string"
      required:
        - "kty"
        - "crv"
        - "x"
        - "y"
      additionalProperties: true
      example:
        kty: "EC"
        crv: "P-256"
        x: "iwKAt9zxlHzXYKtNpLm8e50RQB5KoO1OfUduUTx4_dk"
        y: "G1iDsJCk9eGPTMw7Wb0cUQo-AtBqyratIbC9UaFwAPg"
    AuthConnectionView:
      type: "object"
      description: "The only shape any endpoint returns. `clientSecret` and `privateKeyPem` are absent by construction, not by filtering."
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        type:
          type: "string"
          enum:
            - "oauth2_client_credentials_dpop"
        tokenUrl:
          type: "string"
        clientId:
          type: "string"
        scopes:
          type: "array"
          items:
            type: "string"
        allowedHosts:
          type: "array"
          items:
            type: "string"
          description: "Hosts this connection may be used against. A request to any other host is refused before a token is spent."
        authorizationScheme:
          type: "string"
          enum:
            - "DPoP"
            - "Bearer"
          description: "Scheme word sent in the Authorization header in front of the DPoP-bound token. The DPoP proof header is sent in both modes."
        publicJwk:
          "$ref": "#/components/schemas/AuthConnectionPublicJwk"
        jwkThumbprint:
          type: "string"
          description: "RFC 7638 thumbprint. The access token is bound to this value."
        isActive:
          type: "boolean"
        lastTokenFetchedAt:
          type: "string"
          format: "date-time"
        lastTokenExpiresAt:
          type: "string"
          format: "date-time"
        lastError:
          type: "string"
        lastErrorAt:
          type: "string"
          format: "date-time"
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      required:
        - "_id"
        - "name"
        - "type"
        - "tokenUrl"
        - "clientId"
        - "authorizationScheme"
        - "isActive"
      additionalProperties: true
      example:
        _id: "6ab3d1f2c4e5a60123456789"
        name: "Spring Underwriting"
        type: "oauth2_client_credentials_dpop"
        tokenUrl: "https://auth.example.com/oauth2/token"
        clientId: "client-abc"
        scopes:
          - "underwriting.read"
        allowedHosts:
          - "gateway.example.com"
        authorizationScheme: "DPoP"
        jwkThumbprint: "5MBNqyGaaNaWVo3c-W7Q5HorbYFA6tHxRlglvb7JDBI"
        isActive: true
    AuthConnectionOption:
      type: "object"
      description: "What the HTTP node picker renders, and nothing more."
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        isActive:
          type: "boolean"
      required:
        - "_id"
        - "name"
        - "isActive"
      additionalProperties: false
      example:
        _id: "6ab3d1f2c4e5a60123456789"
        name: "Spring Underwriting"
        isActive: true
    AuthConnectionCreateRequest:
      type: "object"
      properties:
        name:
          type: "string"
          maxLength: 120
        type:
          type: "string"
          enum:
            - "oauth2_client_credentials_dpop"
        tokenUrl:
          type: "string"
          format: "uri"
          description: "Must be https: the client secret is posted to it."
        clientId:
          type: "string"
        clientSecret:
          type: "string"
          description: "Stored encrypted, never returned."
        scopes:
          type: "array"
          items:
            type: "string"
        allowedHosts:
          type: "array"
          items:
            type: "string"
            description: "A bare hostname, optionally with a port. No scheme."
          minItems: 1
          description: "Required. An empty allowlist is a misconfiguration, and the runtime refuses a connection that has one."
        authorizationScheme:
          type: "string"
          enum:
            - "DPoP"
            - "Bearer"
          default: "DPoP"
          description: "Scheme word sent in the Authorization header. Use Bearer for gateways that accept only that word; the DPoP proof is still sent."
      required:
        - "name"
        - "tokenUrl"
        - "clientId"
        - "clientSecret"
        - "allowedHosts"
      additionalProperties: false
      example:
        name: "Spring Underwriting"
        tokenUrl: "https://auth.example.com/oauth2/token"
        clientId: "client-abc"
        clientSecret: "REDACTED"
        scopes:
          - "underwriting.read"
        allowedHosts:
          - "gateway.example.com"
    AuthConnectionUpdateRequest:
      type: "object"
      description: "Every field optional. Omitting `clientSecret` leaves the stored one alone."
      properties:
        name:
          type: "string"
          maxLength: 120
        tokenUrl:
          type: "string"
          format: "uri"
        clientId:
          type: "string"
        clientSecret:
          type: "string"
        scopes:
          type: "array"
          items:
            type: "string"
        allowedHosts:
          type: "array"
          items:
            type: "string"
          minItems: 1
        authorizationScheme:
          type: "string"
          enum:
            - "DPoP"
            - "Bearer"
        isActive:
          type: "boolean"
      additionalProperties: false
      example:
        allowedHosts:
          - "gateway.example.com"
          - "gateway2.example.com"
    AuthConnectionTestRequest:
      type: "object"
      additionalProperties: false
      description: "No fields. The connection under test is named in the path."
      example:
        {}
    AuthConnectionRegenerateKeyRequest:
      type: "object"
      additionalProperties: false
      description: "No fields. The connection is named in the path."
      example:
        {}
    AuthConnectionListResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/AuthConnectionView"
      required:
        - "success"
        - "data"
      additionalProperties: true
    AuthConnectionOptionListResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/AuthConnectionOption"
      required:
        - "success"
        - "data"
      additionalProperties: true
    AuthConnectionResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          "$ref": "#/components/schemas/AuthConnectionView"
      required:
        - "success"
        - "data"
      additionalProperties: true
    AuthConnectionDeleteResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
      required:
        - "success"
      additionalProperties: true
      example:
        success: true
        message: "Connection deleted"
    AuthConnectionTestResponse:
      type: "object"
      description: "The outcome only. The access token is never part of any response, successful or not."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            ok:
              type: "boolean"
            expiresAt:
              type: "string"
              format: "date-time"
            tokenType:
              type: "string"
              enum:
                - "DPoP"
            error:
              type: "string"
              description: "Present when `ok` is false. Carries the status, never the gateway response body."
          required:
            - "ok"
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          ok: true
          expiresAt: "2026-09-24T11:00:00.000Z"
          tokenType: "DPoP"
    AuthConnectionErrorResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
      required:
        - "success"
        - "message"
      additionalProperties: true
      example:
        success: false
        message: "Connection not found"
    AuthLoginRequest:
      type: "object"
      properties:
        email:
          type: "string"
          format: "email"
          description: "Login email; used to look up the user before credential check."
        password:
          type: "string"
          description: "Plain-text password; verified via WorkOS when the user is migrated, otherwise via the local bcrypt hash. Mutually exclusive with `impersonationToken`."
        impersonationToken:
          type: "string"
          description: "Single-use JWT issued by `/api/auth/impersonate/{userId}`; must carry the `isImpersonation` flag and match `email`. Mutually exclusive with `password`."
      required:
        - "email"
      description: "Provide either password or impersonationToken with email."
      additionalProperties: false
      example:
        email: "ops@acme.example"
        password: "CorrectHorseBatteryStaple!"
    AuthRefreshTokenRequest:
      type: "object"
      properties:
        refreshToken:
          type: "string"
          description: "Raw refresh token previously returned by login/refresh; consumed and rotated server-side. Expired or unknown tokens return 401."
      required:
        - "refreshToken"
      additionalProperties: false
      example:
        refreshToken: "rt_5f7b1c2e8a1d4e0012c3b4a5e6f7a8b9c0d1e2f3a4b5c6d7e8f9"
    AuthRegisterRequest:
      type: "object"
      properties:
        email:
          type: "string"
          format: "email"
          description: "New user email; must be unique across the platform."
        password:
          type: "string"
          description: "Plain-text password; validated against WorkOS policy when enabled, otherwise against the local 8+ char / mixed-case / number / special-char rule. Hashed with bcrypt before persistence."
        fullName:
          type: "string"
          description: "Display name; split into first/last when provisioning the WorkOS user."
        organizationId:
          type: "string"
          description: "Mongo `_id` of an existing organization. Required for superadmins. For admins and department heads, defaults to their own organization and cannot refer to another organization."
        accessRole:
          type: "string"
          description: "Defaults to `SALES_REP`. Superadmins may assign ADMIN, DEPARTMENT_HEAD, or SALES_REP; admins may assign DEPARTMENT_HEAD or SALES_REP; department heads may assign only SALES_REP. SUPERADMIN creation is forbidden."
        phoneNumber:
          type: "string"
          description: "User's personal phone number. Rejected when it collides with one of the org's provisioned SMS numbers."
        designation:
          type: "string"
          description: "Free-form job title shown in the UI (e.g. \"Customer Success Lead\")."
        departmentId:
          type: "string"
          description: "Mongo `_id` of an existing department in the target organization; defaults to the caller's own department for department heads, who cannot choose a different department. Used to update the department's `userIds`/`managerIds` array."
      required:
        - "email"
        - "password"
      additionalProperties: true
      example:
        email: "sam.patel@acme.example"
        password: "CorrectHorseBatteryStaple!"
        fullName: "Sam Patel"
        organizationId: "5f7b1c2e8a1d4e0012c3b4a5"
        accessRole: "SALES_REP"
        phoneNumber: "+14165550100"
        designation: "Customer Success Lead"
        departmentId: "6a8c2d3f9b1e5a0023d4c5b6"
    AuthExitImpersonationRequest:
      type: "object"
      properties:
        originalAdminToken:
          type: "string"
          description: "Original admin JWT captured at impersonation start; re-verified server-side and must resolve to a SUPERADMIN/ADMIN role matching `originalAdminUser`."
        originalAdminUser:
          type: "object"
          additionalProperties: true
          description: "Original admin payload (id, email, …) captured at impersonation start. Its `id`/`email` must match the verified `originalAdminToken` payload - guards against tampering."
      required:
        - "originalAdminToken"
        - "originalAdminUser"
      additionalProperties: false
      example:
        originalAdminToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1Zjdi..."
        originalAdminUser:
          id: "5f7b1c2e8a1d4e0012c3b4a5"
          email: "admin@acme.example"
          fullName: "Acme Admin"
          organizationId: "5f7b1c2e8a1d4e0012c3b4a5"
          accessRole: "ADMIN"
    AuthWorkOSCallbackRequest:
      type: "object"
      properties:
        code:
          type: "string"
          description: "OAuth authorization code returned by WorkOS/Okta; exchanged server-side (SSO first, AuthKit fallback). Required unless `error` is set."
        state:
          type: "string"
          description: "Opaque CSRF state token round-tripped from the original `/authorize` call."
        error:
          type: "string"
          description: "Provider-reported error code; when present the request short-circuits with a 400 instead of attempting code exchange."
        redirect_uri:
          type: "string"
          description: "Redirect URI used in the original `/authorize` call; must match for the code exchange to succeed. Falls back to `${CLIENT_URL}/signin`."
        organizationId:
          type: "string"
          description: "Mongo `_id` used to assign the org when provisioning a brand-new WorkOS user; falls back to `DEFAULT_ORGANIZATION_ID` then the oldest org."
      additionalProperties: true
      example:
        code: "01HX9R3K4N6P8QZBVTYM2D5A7C"
        state: "tether-csrf-7f4b2c1d"
        redirect_uri: "https://app.tether.example/auth/callback"
        organizationId: "org_01HX9R3K4N6P8QZBVTYM2D5A7C"
    AuthErrorResponse:
      type: "object"
      description: "Generic error envelope returned by Auth endpoints. Most paths include only `error`; a few add `details`/`code` for diagnostic context."
      properties:
        error:
          type: "string"
        details:
          type: "string"
        code:
          type: "string"
      required:
        - "error"
      additionalProperties: true
      example:
        error: "Token expired"
        code: "TOKEN_EXPIRED"
    AuthVerifyTokenResponse:
      type: "object"
      properties:
        message:
          type: "string"
          example: "Token is good"
      required:
        - "message"
      additionalProperties: false
      example:
        message: "Token is good"
    AuthActivitySuccessResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          example: true
      required:
        - "success"
      additionalProperties: false
      example:
        success: true
    AuthOriginalAdmin:
      type: "object"
      description: "Original admin payload returned alongside an impersonation token so the SPA can later restore the admin session via /api/auth/exit-impersonation."
      properties:
        id:
          type: "string"
        email:
          type: "string"
          format: "email"
        fullName:
          type: "string"
        organizationId:
          type: "string"
        accessRole:
          type: "string"
        conversationOpenPreference:
          type: "string"
        token:
          type: "string"
          nullable: true
          description: "Token to restore admin session"
      additionalProperties: true
      example:
        id: "5f7b1c2e8a1d4e0012c3b4a5"
        email: "admin@acme.example"
        fullName: "Acme Admin"
        organizationId: "5f7b1c2e8a1d4e0012c3b4a5"
        accessRole: "ADMIN"
        conversationOpenPreference: "split"
        token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1Zjdi..."
    AuthImpersonateCredentialsResponse:
      type: "object"
      properties:
        email:
          type: "string"
          format: "email"
        impersonationToken:
          type: "string"
        fullName:
          type: "string"
        originalAdmin:
          nullable: true
          allOf:
            -
              "$ref": "#/components/schemas/AuthOriginalAdmin"
      required:
        - "email"
        - "impersonationToken"
      additionalProperties: true
      example:
        email: "sam.patel@acme.example"
        impersonationToken: "imp_5f7b1c2e8a1d4e0012c3b4a5e6f7a8b9c0d1e2f3a4b5c6d7e8"
        fullName: "Sam Patel"
        originalAdmin:
          id: "5f7b1c2e8a1d4e0012c3b4a5"
          email: "admin@acme.example"
          fullName: "Acme Admin"
          organizationId: "5f7b1c2e8a1d4e0012c3b4a5"
          accessRole: "ADMIN"
          token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1Zjdi..."
    AuthWorkOSClientIdResponse:
      type: "object"
      properties:
        clientId:
          type: "string"
      required:
        - "clientId"
      additionalProperties: false
      example:
        clientId: "client_01HX9R3K4N6P8QZBVTYM2D5A7C"
    AuthSessionConfig:
      type: "object"
      description: "Resolved session configuration returned alongside tokens. Mirrors the org-level idle-timeout / SSO renewal policy so the client can enforce it."
      properties:
        enabled:
          type: "boolean"
        idleTimeoutMinutes:
          type: "number"
        tokenExpiryHours:
          type: "number"
        warningTimeMinutes:
          type: "number"
        idleTrackingEnabled:
          type: "boolean"
        ssoSilentRenewalEnabled:
          type: "boolean"
        ssoFallbackBehavior:
          type: "string"
        passwordSilentRenewalEnabled:
          type: "boolean"
        passwordFallbackBehavior:
          type: "string"
      required:
        - "enabled"
      additionalProperties: true
      example:
        enabled: true
        idleTimeoutMinutes: 30
        tokenExpiryHours: 8
        warningTimeMinutes: 2
        idleTrackingEnabled: true
        ssoSilentRenewalEnabled: true
        ssoFallbackBehavior: "redirect"
        passwordSilentRenewalEnabled: false
        passwordFallbackBehavior: "logout"
    AuthUserSummary:
      type: "object"
      description: "Compact User payload returned with auth tokens."
      properties:
        id:
          type: "string"
        email:
          type: "string"
          format: "email"
        fullName:
          type: "string"
        organizationId:
          type: "string"
        workosOrganizationId:
          type: "string"
        accessRole:
          type: "string"
        departmentId:
          type: "string"
        workosUserId:
          type: "string"
        conversationOpenPreference:
          type: "string"
      required:
        - "id"
        - "email"
        - "organizationId"
        - "accessRole"
      additionalProperties: true
      example:
        id: "5f7b1c2e8a1d4e0012c3b4a5"
        email: "admin@acme.example"
        fullName: "Acme Admin"
        organizationId: "64a1b2c3d4e5f60012345678"
        accessRole: "ADMIN"
        conversationOpenPreference: "split"
    AuthLoginResponse:
      type: "object"
      description: "Returned by `/api/auth/login` and `POST /api/auth/workos/callback` on success. Contains access + refresh tokens, session config, and the resolved user."
      properties:
        token:
          type: "string"
          description: "JWT access token."
        refreshToken:
          type: "string"
        sessionConfig:
          "$ref": "#/components/schemas/AuthSessionConfig"
        user:
          "$ref": "#/components/schemas/AuthUserSummary"
      required:
        - "token"
        - "refreshToken"
        - "sessionConfig"
        - "user"
      additionalProperties: true
      example:
        token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1Zjdi..."
        refreshToken: "rt_64d2f9c5e8a1d4e001a0b1c2e6f7a8b9"
        sessionConfig:
          enabled: true
          idleTimeoutMinutes: 30
          tokenExpiryHours: 8
          warningTimeMinutes: 2
        user:
          id: "5f7b1c2e8a1d4e0012c3b4a5"
          email: "admin@acme.example"
          fullName: "Acme Admin"
          organizationId: "64a1b2c3d4e5f60012345678"
          accessRole: "ADMIN"
    AuthRefreshResponse:
      type: "object"
      description: "Refresh-token rotation envelope. Adds `socketToken` for re-authenticating the realtime socket alongside the new HTTP tokens."
      properties:
        token:
          type: "string"
        socketToken:
          type: "string"
        refreshToken:
          type: "string"
        sessionConfig:
          "$ref": "#/components/schemas/AuthSessionConfig"
        user:
          "$ref": "#/components/schemas/AuthUserSummary"
      required:
        - "token"
        - "socketToken"
        - "refreshToken"
        - "sessionConfig"
        - "user"
      additionalProperties: true
      example:
        token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1Zjdi..."
        socketToken: "st_eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
        refreshToken: "rt_64d2f9c5e8a1d4e001a0b1c2e6f7a8b9"
        sessionConfig:
          enabled: true
          idleTimeoutMinutes: 30
        user:
          id: "5f7b1c2e8a1d4e0012c3b4a5"
          email: "admin@acme.example"
          organizationId: "64a1b2c3d4e5f60012345678"
          accessRole: "ADMIN"
    AuthRegisterResponse:
      type: "object"
      description: "Minimal envelope returned after a user is registered."
      properties:
        message:
          type: "string"
      required:
        - "message"
      additionalProperties: true
      example:
        message: "User registered successfully"
    AuthPasswordRequirements:
      type: "object"
      description: "Diagnostic detail returned when the password fails policy or WorkOS validation."
      properties:
        minLength:
          type: "integer"
        requireUppercase:
          type: "boolean"
        requireLowercase:
          type: "boolean"
        requireNumber:
          type: "boolean"
        requireSpecial:
          type: "boolean"
      additionalProperties: true
      example:
        minLength: 8
        requireUppercase: true
        requireLowercase: true
        requireNumber: true
        requireSpecial: true
    AuthRegisterErrorResponse:
      type: "object"
      description: "Validation envelope returned by `/api/auth/register` when the email is taken or the password violates policy."
      properties:
        error:
          type: "string"
        message:
          type: "string"
        suggestions:
          type: "array"
          items:
            type: "string"
          description: "WorkOS-provided suggestions for strengthening the password."
        passwordRequirements:
          "$ref": "#/components/schemas/AuthPasswordRequirements"
      required:
        - "error"
      additionalProperties: true
      example:
        error: "Password does not meet WorkOS requirements"
        message: "Password must include at least one number and one special character."
        suggestions:
          - "Add a digit"
          - "Add a punctuation mark"
        passwordRequirements:
          minLength: 8
          requireNumber: true
          requireSpecial: true
    AuthExitImpersonationResponse:
      type: "object"
      description: "Returned by `/api/auth/exit-impersonation` after the original admin session is restored."
      properties:
        token:
          type: "string"
          description: "Original-admin access token to swap back into."
        user:
          "$ref": "#/components/schemas/AuthUserSummary"
        message:
          type: "string"
      required:
        - "token"
        - "user"
        - "message"
      additionalProperties: true
      example:
        token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
        user:
          id: "5f7b1c2e8a1d4e0012c3b4a5"
          email: "admin@acme.example"
          organizationId: "64a1b2c3d4e5f60012345678"
          accessRole: "ADMIN"
        message: "Impersonation exited successfully"
    AutomationsErrorResponse:
      type: "object"
      description: "Standard error envelope for Automations endpoints."
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
      required:
        - "success"
      additionalProperties: true
      example:
        success: false
        message: "Automation not found"
    AutomationsSimpleSuccessResponse:
      type: "object"
      description: "Generic success envelope used for delete endpoints."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
      required:
        - "success"
      additionalProperties: true
      example:
        success: true
        message: "Automation deleted successfully"
    AutomationUserSmsNotification:
      type: "object"
      description: "User-specific SMS notification settings, merged from the calling user's `User.automations[automationId]` preference."
      properties:
        enabled:
          type: "boolean"
        phoneNumbers:
          type: "array"
          items:
            type: "string"
        message:
          type: "string"
        templateId:
          type: "string"
      additionalProperties: true
      example:
        enabled: true
        phoneNumbers:
          - "+14155551234"
        message: "New lead just signed up - please follow up."
        templateId: "new-lead-alert"
    AutomationDocument:
      type: "object"
      description: "An `Automation` document with two derived per-user fields: `enabled` (from `User.automations[id]`) and `userSmsNotification` (per-user SMS settings)."
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        description:
          type: "string"
        organizationId:
          type: "string"
        userId:
          type: "string"
        event:
          type: "string"
        actions:
          type: "object"
          additionalProperties: true
        sourceStatuses:
          type: "array"
          items:
            type: "string"
        maxTransitions:
          type: "number"
        triggerType:
          type: "string"
        conditions:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
        triggerLogicType:
          type: "string"
          description: "Either \"event\" or \"timer\"."
        timerLogic:
          type: "object"
          additionalProperties: true
          nullable: true
        schedule:
          type: "object"
          additionalProperties: true
          nullable: true
        maxFollowUpCount:
          type: "number"
          nullable: true
        enabled:
          type: "boolean"
          description: "Whether the automation fires for the organization."
        userSmsNotification:
          description: "Present only when the calling user has configured SMS notifications for this automation."
          nullable: true
          allOf:
            -
              "$ref": "#/components/schemas/AutomationUserSmsNotification"
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "64d2f9c5e8a1d4e001a0b1c2"
        name: "Follow-up after 24h"
        description: "Send a follow-up SMS if the lead has not replied in 24h."
        organizationId: "64a1b2c3d4e5f60012345678"
        userId: "64a1b2c3d4e5f60012345679"
        event: "message.received"
        actions:
          sendMessage:
            -
              template: "follow-up-24h"
              channel: "sms"
        sourceStatuses:
          - "New lead"
        maxTransitions: 3
        triggerType: "status_change"
        conditions:
          -
            field: "lastInboundDirection"
            op: "eq"
            value: "inbound"
        triggerLogicType: "timer"
        timerLogic:
          enabled: true
          delay: 24
          unit: "hours"
        schedule:
          start: "09:00"
          end: "18:00"
        maxFollowUpCount: 3
        enabled: true
        userSmsNotification:
          enabled: true
          phoneNumbers:
            - "+14155551234"
          message: "New lead pending follow-up."
        createdAt: "2026-04-12T14:22:10.000Z"
        updatedAt: "2026-04-22T10:14:00.000Z"
    AutomationsListResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/AutomationDocument"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          -
            _id: "64d2f9c5e8a1d4e001a0b1c2"
            name: "Follow-up after 24h"
            description: "Send a follow-up SMS if the lead has not replied in 24h."
            triggerLogicType: "timer"
            enabled: true
    AutomationSingleResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          "$ref": "#/components/schemas/AutomationDocument"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          _id: "64d2f9c5e8a1d4e001a0b1c2"
          name: "Follow-up after 24h"
          description: "Send a follow-up SMS if the lead has not replied in 24h."
          triggerLogicType: "timer"
          enabled: true
    AutomationMutationResponse:
      type: "object"
      description: "Returned by `POST /api/automations` and `PUT /api/automations/{id}` - wraps the created/updated `AutomationDocument` plus a status message."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        data:
          "$ref": "#/components/schemas/AutomationDocument"
      required:
        - "success"
        - "message"
        - "data"
      additionalProperties: true
      example:
        success: true
        message: "Automation created successfully"
        data:
          _id: "64d2f9c5e8a1d4e001a0b1c2"
          name: "Follow-up after 24h"
          description: "Send a follow-up SMS if the lead has not replied in 24h."
          triggerLogicType: "timer"
          enabled: false
    AutomationSmsSettingsResponse:
      type: "object"
      description: "Returned after per-user SMS notification settings for an automation are updated."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        data:
          type: "object"
          properties:
            automationId:
              type: "string"
            smsNotification:
              type: "object"
              properties:
                enabled:
                  type: "boolean"
                phoneNumbers:
                  type: "array"
                  items:
                    type: "string"
                message:
                  type: "string"
                templateId:
                  type: "string"
              additionalProperties: true
          required:
            - "automationId"
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        message: "SMS notification settings updated successfully"
        data:
          automationId: "64d2f9c5e8a1d4e001a0b1c2"
          smsNotification:
            enabled: true
            phoneNumbers:
              - "+14165550100"
            message: "New escalation on lead {{contact.firstName}}"
            templateId: "64a1b2c3d4e5f60012345679"
    AutomationCreateRequest:
      type: "object"
      properties:
        name:
          type: "string"
        description:
          type: "string"
        event:
          type: "string"
        actions:
          type: "object"
          additionalProperties: true
        sourceStatuses:
          type: "array"
          items:
            type: "string"
        maxTransitions:
          type: "number"
        enabled:
          type: "boolean"
          description: "Whether the automation fires for the organization. Defaults to `true` when omitted."
        triggerType:
          type: "string"
        conditions:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
        triggerLogicType:
          type: "string"
          description: "Either \"event\" or \"timer\""
        timerLogic:
          type: "object"
          properties:
            enabled:
              type: "boolean"
              description: "Master switch for the timer-logic block; when false the rest of `timerLogic` is ignored."
            delay:
              type: "number"
              minimum: 1
            unit:
              type: "string"
          additionalProperties: true
        schedule:
          type: "object"
          properties:
            start:
              type: "string"
              description: "HH:MM format (24-hour, UTC)"
            end:
              type: "string"
              description: "HH:MM format (24-hour, UTC)"
          additionalProperties: true
        maxFollowUpCount:
          type: "number"
          minimum: 1
      required:
        - "name"
        - "description"
      additionalProperties: true
      example:
        name: "Follow-up after 24h"
        description: "Send a follow-up SMS if the lead has not replied in 24h."
        event: "message.received"
        actions:
          sendMessage:
            -
              template: "follow-up-24h"
              channel: "sms"
        sourceStatuses:
          - "New lead"
        triggerType: "status_change"
        triggerLogicType: "timer"
        timerLogic:
          enabled: true
          delay: 24
          unit: "hours"
        schedule:
          start: "09:00"
          end: "18:00"
        maxFollowUpCount: 3
    AutomationUpdateRequest:
      type: "object"
      properties:
        name:
          type: "string"
        description:
          type: "string"
        event:
          type: "string"
        actions:
          type: "object"
          additionalProperties: true
        sourceStatuses:
          type: "array"
          items:
            type: "string"
        maxTransitions:
          type: "number"
        enabled:
          type: "boolean"
          description: "Whether the automation fires for the organization."
        triggerType:
          type: "string"
        conditions:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
        triggerLogicType:
          type: "string"
          description: "Either \"event\" or \"timer\""
        timerLogic:
          type: "object"
          properties:
            enabled:
              type: "boolean"
              description: "Master switch for the timer-logic block."
            delay:
              type: "number"
              minimum: 1
            unit:
              type: "string"
          additionalProperties: true
          nullable: true
        schedule:
          type: "object"
          properties:
            start:
              type: "string"
              description: "HH:MM format (24-hour, UTC)"
            end:
              type: "string"
              description: "HH:MM format (24-hour, UTC)"
          additionalProperties: true
          nullable: true
        maxFollowUpCount:
          type: "number"
          minimum: 1
          nullable: true
      additionalProperties: true
      example:
        description: "Updated copy and slightly longer delay."
        timerLogic:
          enabled: true
          delay: 36
          unit: "hours"
        maxFollowUpCount: 4
    AutomationSmsSettingsRequest:
      type: "object"
      properties:
        smsNotificationEnabled:
          type: "boolean"
          description: "Master switch for the per-user SMS notification on this automation."
        smsNotificationPhoneNumbers:
          type: "array"
          items:
            type: "string"
          description: "Phone numbers to ping when the automation fires."
        smsNotificationMessage:
          type: "string"
          description: "Custom body (supports `{{contact.firstName}}` placeholders); ignored when `smsNotificationTemplateId` is set."
        smsNotificationTemplateId:
          type: "string"
          description: "Template `_id` whose body is used; mutually exclusive with `smsNotificationMessage`."
      additionalProperties: true
      example:
        smsNotificationEnabled: true
        smsNotificationPhoneNumbers:
          - "+14155551234"
          - "+14155555678"
        smsNotificationMessage: "New lead pending follow-up."
        smsNotificationTemplateId: "new-lead-alert"
    CallsErrorResponse:
      type: "object"
      description: "Error envelope used across most calls endpoints. Some endpoints wrap a string error; validation endpoints (parseContractInput) return a structured `error` object with `code` and `details`."
      properties:
        success:
          type: "boolean"
          enum:
            - false
        error:
          oneOf:
            -
              type: "string"
            -
              type: "object"
              properties:
                code:
                  type: "string"
                message:
                  type: "string"
                details:
                  type: "array"
                  items:
                    type: "object"
                    additionalProperties: true
              additionalProperties: true
        code:
          type: "string"
          description: "Stable error code on certain errors (e.g. `AGENT_NOT_SYNCED`, `OUTBOUND_IN_FLIGHT`, `VOICE_NOT_ALLOWED_ON_SHORTCODE`)."
      additionalProperties: true
      example:
        success: false
        error: "Call not found"
    CallsSimpleSuccessResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
      required:
        - "success"
      additionalProperties: true
      example:
        success: true
        message: "Configuration saved"
    CallsActiveProviderResponse:
      type: "object"
      properties:
        provider:
          type: "string"
          nullable: true
          enum:
            - "twilio"
            - "sinch"
            - null
          description: "Active voice provider for this org, or null if none is configured."
        phoneNumber:
          type: "string"
          nullable: true
          description: "Calling user's default phone number for the active provider."
        via:
          type: "string"
          nullable: true
          enum:
            - "link"
            - "group"
            - "grant"
            - null
          description: "How the caller reaches `phoneNumber`: linked to them, linked to one of their groups, or shared by a send grant. Null when there is no number (or no provider)."
      additionalProperties: true
      example:
        provider: "sinch"
        phoneNumber: "+14165550100"
    CallsVoiceProviderConfigItem:
      type: "object"
      properties:
        provider:
          type: "string"
          enum:
            - "twilio"
            - "sinch"
        isEnabled:
          type: "boolean"
        isConfigured:
          type: "boolean"
        phoneNumber:
          type: "string"
        twilioAccountSid:
          type: "string"
        twilioAuthToken:
          type: "string"
        twilioApiKeySid:
          type: "string"
        twilioApiKeySecret:
          type: "string"
        twilioTwimlAppSid:
          type: "string"
        twilioServiceSid:
          type: "string"
        sinchApplicationKey:
          type: "string"
        sinchApplicationSecret:
          type: "string"
      additionalProperties: true
      example:
        provider: "sinch"
        isEnabled: true
        isConfigured: true
        phoneNumber: "+14165550100"
        sinchApplicationKey: "sinch-app-key-xxxx"
        sinchApplicationSecret: "sinch-app-secret-xxxx"
    CallsUserPhoneNumberEntry:
      type: "object"
      description: "A voice phone number assigned to the user from the org-level phone number store."
      properties:
        provider:
          type: "string"
          enum:
            - "twilio"
            - "sinch"
        phoneNumber:
          type: "string"
        isDefault:
          type: "boolean"
        isInboundEnabled:
          type: "boolean"
        routing:
          type: "object"
          description: "Per-leg routing policy. Four independent toggles: each direction can be open or closed to humans and to the AI on its own."
          properties:
            inbound:
              type: "object"
              properties:
                enabled:
                  type: "boolean"
                  description: "Accept inbound calls at all."
                ai:
                  type: "boolean"
                  description: "Inbound is answered by the AI agent."
                forwardToNumber:
                  type: "string"
                  description: "Forward inbound to this PSTN number instead of ringing a browser. Rejected while inbound.ai is on."
            outbound:
              type: "object"
              properties:
                enabled:
                  type: "boolean"
                  description: "A human may use this number as caller ID."
                ai:
                  type: "boolean"
                  description: "The AI may use this number as caller ID."
        aiAgentId:
          type: "string"
          description: "Prompt._id linked when either AI leg is on."
        elevenlabsPhoneNumberId:
          type: "string"
          description: "ElevenLabs phone-number ID once imported."
        label:
          type: "string"
        phoneNumberId:
          type: "string"
          description: "The org PhoneNumber resource id."
        via:
          type: "string"
          enum:
            - "link"
            - "group"
            - "grant"
          description: "How the user reaches the number: linked to them, linked to one of their groups, or shared by a send grant."
      additionalProperties: true
      example:
        provider: "sinch"
        phoneNumber: "+14165550100"
        isDefault: true
        isInboundEnabled: true
        routing:
          inbound:
            enabled: true
            ai: false
          outbound:
            enabled: true
            ai: false
        label: "Main line"
    CallsVoiceProviderConfigResponse:
      type: "object"
      properties:
        activeProvider:
          type: "string"
          nullable: true
          enum:
            - "twilio"
            - "sinch"
            - null
        providers:
          type: "array"
          items:
            "$ref": "#/components/schemas/CallsVoiceProviderConfigItem"
        userPhoneNumbers:
          type: "array"
          items:
            "$ref": "#/components/schemas/CallsUserPhoneNumberEntry"
      additionalProperties: true
      example:
        activeProvider: "sinch"
        providers:
          -
            provider: "sinch"
            isEnabled: true
            isConfigured: true
            phoneNumber: "+14165550100"
        userPhoneNumbers:
          -
            provider: "sinch"
            phoneNumber: "+14165550100"
            isDefault: true
    CallsUserPhoneNumbersResponse:
      type: "object"
      properties:
        phoneNumbers:
          type: "array"
          items:
            "$ref": "#/components/schemas/CallsUserPhoneNumberEntry"
      additionalProperties: true
      example:
        phoneNumbers:
          -
            provider: "sinch"
            phoneNumber: "+14165550100"
            isDefault: true
            isInboundEnabled: true
            routing:
              inbound:
                enabled: true
                ai: false
              outbound:
                enabled: true
                ai: false
    CallsSinchTokenResponse:
      type: "object"
      properties:
        token:
          type: "string"
          description: "Sinch RTC JWT (HS256, 10-minute expiry)."
        applicationKey:
          type: "string"
        userId:
          type: "string"
        callerIdentifier:
          type: "string"
          description: "User's default Sinch phone number used as the caller ID for PSTN calls. May be empty if not configured."
        expiresIn:
          type: "integer"
          description: "Seconds until expiry (always 600)."
      required:
        - "token"
        - "applicationKey"
        - "userId"
        - "expiresIn"
      additionalProperties: true
      example:
        token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.example.token"
        applicationKey: "sinch-app-key-xxxx"
        userId: "64f0a1b2c3d4e5f6a7b8c9d4"
        callerIdentifier: "+14165550100"
        expiresIn: 600
    CallsTwilioTokenResponse:
      type: "object"
      properties:
        token:
          type: "string"
          description: "Twilio AccessToken JWT with VoiceGrant."
        identity:
          type: "string"
          description: "User's Twilio phone number used as the SDK identity."
        userId:
          type: "string"
      required:
        - "token"
        - "identity"
        - "userId"
      additionalProperties: true
      example:
        token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.example.twilio"
        identity: "+14165550100"
        userId: "64f0a1b2c3d4e5f6a7b8c9d4"
    CallsTwilioTokenErrorResponse:
      type: "object"
      description: "Twilio-credentials-missing error includes a `missing` map so the UI can show which fields are unset."
      properties:
        error:
          type: "string"
        missing:
          type: "object"
          properties:
            accountSid:
              type: "boolean"
            apiKeySid:
              type: "boolean"
            apiKeySecret:
              type: "boolean"
            twimlAppSid:
              type: "boolean"
          additionalProperties: true
      additionalProperties: true
      example:
        error: "Twilio credentials missing"
        missing:
          accountSid: false
          apiKeySid: true
          apiKeySecret: true
          twimlAppSid: false
    CallDocument:
      type: "object"
      description: "A `Call` document. Many fields are provider-specific; clients should be tolerant of additional properties. The ai* detail fields below (aiTurnDetails, aiLlmUsage, aiLlmPrice, aiCost, aiCharging, aiCallSuccessful, aiEvaluationResults, aiDataCollection, aiDynamicVariables, aiFeaturesUsage, aiSummaryTitle, aiTerminationReason) are **only included for ADMIN and SUPERADMIN callers**. Non-admin requests receive the same document with those fields omitted; `aiTranscript`, `aiSummary`, and `aiHandledDuration` remain visible to all roles."
      properties:
        _id:
          type: "string"
        callId:
          type: "string"
        provider:
          type: "string"
          enum:
            - "twilio"
            - "sinch"
            - "elevenlabs"
            - "external"
        providerCallId:
          type: "string"
        direction:
          type: "string"
          enum:
            - "inbound"
            - "outbound"
        status:
          type: "string"
          description: "e.g. initiated, ringing, in-progress, answered, completed, no-answer, busy, failed."
        from:
          type: "string"
        to:
          type: "string"
        contactId:
          description: "ObjectId or populated Contact subset (firstName, lastName, phoneNumber, email)."
        conversationId:
          type: "string"
        organizationId:
          type: "string"
        userId:
          description: "ObjectId or populated User subset (fullName, email) of the person who placed or took the call. Absent or null for AI calls nobody placed (inbound AI calls, workflow-placed AI calls). Never the phone line owner standing in for an AI agent."
        createdBy:
          type: "object"
          nullable: true
          description: "Who or what made the call record: a user who placed it from the app (`type: \"user\"`, userId), or the AI agent that handled it (`type: \"ai\"`, promptId, `label` = the agent persona or agent name, plus workflowId/executionId when a workflow placed it). Older calls may not have it."
          properties:
            type:
              type: "string"
              enum:
                - "user"
                - "ai"
                - "automation"
                - "workflow"
                - "system"
            userId:
              type: "string"
            promptId:
              type: "string"
            automationId:
              type: "string"
            workflowId:
              type: "string"
            executionId:
              type: "string"
            label:
              type: "string"
          required:
            - "type"
          example:
            type: "ai"
            promptId: "64f0a1b2c3d4e5f6a7b8c9f1"
            label: "Riley"
        providerPhoneNumber:
          type: "string"
        startTime:
          type: "string"
          format: "date-time"
        answerTime:
          type: "string"
          format: "date-time"
        endTime:
          type: "string"
          format: "date-time"
        duration:
          type: "number"
        recordings:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
        aiAgentId:
          type: "string"
        aiTranscript:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
        aiSummary:
          type: "string"
        aiHandledDuration:
          type: "number"
        aiTurnDetails:
          type: "array"
          description: "Admin-only. Per-turn LLM usage / cost / tool-call detail derived from the post-call transcript. Only turns carrying usage/cost/tool data are included."
          items:
            type: "object"
            additionalProperties: true
        aiLlmUsage:
          type: "object"
          description: "Admin-only. Raw nested model-level usage from `metadata.charging.llm_usage`. Shape: `{ irreversible_generation: { model_usage: { \"<model>\": { input, input_cache_read, input_cache_write, output_total } } }, initiated_generation: {...} }`."
          additionalProperties: true
        aiLlmPrice:
          type: "number"
          description: "Admin-only. USD decimal LLM price (e.g. `0.0986894`). Source: `metadata.charging.llm_price`."
        aiCost:
          type: "number"
          description: "Admin-only. Total call cost as raw integer in microcents (1 unit = $0.0001). UI formats. Example: `4101` = $0.4101."
        aiCharging:
          type: "object"
          description: "Admin-only. Charging breakdown from `metadata.charging`."
          properties:
            llm_charge:
              type: "number"
            call_charge:
              type: "number"
            llm_price:
              type: "number"
            dev_discount:
              type: "boolean"
            is_burst:
              type: "boolean"
            tier:
              type: "string"
          additionalProperties: true
        aiCallSuccessful:
          type: "string"
          enum:
            - "success"
            - "failure"
            - "unknown"
          nullable: true
          description: "Admin-only. ElevenLabs analysis verdict from `analysis.call_successful`. NOT a boolean."
        aiEvaluationResults:
          type: "object"
          description: "Admin-only. ElevenLabs `analysis.evaluation_criteria_results`. **Object keyed by criteria name** (NOT the `_list` array variant). Each value: `{ criteria_id, result, rationale? }`. Shape divergence vs `aiDataCollection` (which is an array) is intentional."
          additionalProperties: true
        aiDataCollection:
          type: "array"
          description: "Admin-only. ElevenLabs `analysis.data_collection_results_list`. **Array form** preserves order for UI iteration. Each item: `{ data_collection_id, value, json_schema, rationale? }`. Shape divergence vs `aiEvaluationResults` (which is an object) is intentional."
          items:
            type: "object"
            additionalProperties: true
        aiDynamicVariables:
          type: "object"
          description: "Admin-only. `conversation_initiation_client_data.dynamic_variables` - caller-supplied variables plus `system__*` variables ElevenLabs injects."
          additionalProperties: true
        aiFeaturesUsage:
          type: "object"
          description: "Admin-only. `metadata.features_usage` - which ElevenLabs features were enabled/used during the call."
          additionalProperties: true
        aiSummaryTitle:
          type: "string"
          description: "Admin-only. Short call-summary title from `analysis.call_summary_title`. The long-form summary stays on `aiSummary`."
        aiTerminationReason:
          type: "string"
          description: "Admin-only. `metadata.termination_reason` - e.g. `\"Client disconnected: 1000\"`."
        metadata:
          type: "object"
          additionalProperties: true
        providerMetadata:
          type: "object"
          additionalProperties: true
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "64f0a1b2c3d4e5f6a7b8cb00"
        callId: "64f0a1b2c3d4e5f6a7b8cb00"
        provider: "sinch"
        providerCallId: "sinch-call-abc123"
        direction: "outbound"
        status: "completed"
        from: "+14165550100"
        to: "+14165550199"
        contactId: "64f0a1b2c3d4e5f6a7b8c9d0"
        conversationId: "64f0a1b2c3d4e5f6a7b8c9e0"
        organizationId: "64f0a1b2c3d4e5f6a7b8c9d3"
        userId: "64f0a1b2c3d4e5f6a7b8c9d4"
        providerPhoneNumber: "+14165550100"
        startTime: "2026-05-15T09:10:00.000Z"
        answerTime: "2026-05-15T09:10:08.000Z"
        endTime: "2026-05-15T09:12:34.000Z"
        duration: 154
        recordings:
          []
        createdAt: "2026-05-15T09:10:00.000Z"
        updatedAt: "2026-05-15T09:12:34.000Z"
    CallsCallSuccessResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        call:
          "$ref": "#/components/schemas/CallDocument"
        message:
          type: "string"
      required:
        - "success"
      additionalProperties: true
      example:
        success: true
        call:
          _id: "64f0a1b2c3d4e5f6a7b8cb00"
          callId: "64f0a1b2c3d4e5f6a7b8cb00"
          provider: "sinch"
          direction: "outbound"
          status: "initiated"
          from: "+14165550100"
          to: "+14165550199"
        message: "Call recorded"
    CallsSingleCallResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        call:
          "$ref": "#/components/schemas/CallDocument"
      required:
        - "success"
        - "call"
      additionalProperties: true
      example:
        success: true
        call:
          _id: "64f0a1b2c3d4e5f6a7b8cb00"
          callId: "64f0a1b2c3d4e5f6a7b8cb00"
          provider: "sinch"
          direction: "outbound"
          status: "completed"
          duration: 154
    CallsHistoryResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        calls:
          type: "array"
          items:
            "$ref": "#/components/schemas/CallDocument"
        total:
          type: "integer"
      required:
        - "success"
        - "calls"
        - "total"
      additionalProperties: true
      example:
        success: true
        calls:
          []
        total: 0
    CallsStatisticsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        statistics:
          type: "object"
          properties:
            totalCalls:
              type: "integer"
            totalDuration:
              type: "number"
              description: "Sum of `duration` in seconds across all calls in the window."
            averageDuration:
              type: "number"
            byStatus:
              type: "object"
              description: "Map of call status -> aggregate counters."
              additionalProperties:
                type: "object"
                properties:
                  count:
                    type: "integer"
                  totalDuration:
                    type: "number"
                  avgDuration:
                    type: "number"
                additionalProperties: true
          additionalProperties: true
      required:
        - "success"
        - "statistics"
      additionalProperties: true
      example:
        success: true
        statistics:
          totalCalls: 124
          totalDuration: 18450
          averageDuration: 148.79
          byStatus:
            completed:
              count: 102
              totalDuration: 17800
              avgDuration: 174.5
            no-answer:
              count: 18
              totalDuration: 0
              avgDuration: 0
            failed:
              count: 4
              totalDuration: 650
              avgDuration: 162.5
    CallsRecordingResponse:
      type: "object"
      description: "Shape depends on provider. Twilio returns base64 `audioData`; Sinch / ElevenLabs / external return a signed `audioUrl`."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        audioData:
          type: "string"
          description: "data URI (Twilio only)."
        audioUrl:
          type: "string"
          description: "Signed S3 (Sinch) or R2 (ElevenLabs/external) URL."
        duration:
          type: "number"
        recordingId:
          type: "string"
        transcriptionText:
          type: "string"
          nullable: true
        transcriptionData:
          nullable: true
          description: "Structured per-utterance transcription (provider-shaped)."
          oneOf:
            -
              type: "array"
              items:
                type: "object"
                additionalProperties: true
            -
              type: "object"
              additionalProperties: true
        direction:
          type: "string"
          enum:
            - "inbound"
            - "outbound"
        from:
          type: "string"
        to:
          type: "string"
      required:
        - "success"
      additionalProperties: true
      example:
        success: true
        audioUrl: "https://example-r2.signed/.../recording.mp3?X-Amz-Expires=600"
        duration: 154
        recordingId: "rec_abc123"
        transcriptionText: "Agent: Hi, this is Alex from Example Corp..."
        transcriptionData:
          -
            role: "agent"
            message: "Hi, this is Alex from Example Corp."
            timestamp: 0.5
          -
            role: "user"
            message: "Hey Alex."
            timestamp: 2.8
        direction: "outbound"
        from: "+14165550100"
        to: "+14165550199"
    CallsInitiateSdkCallRequest:
      type: "object"
      description: "At least one of `contactId` or `phoneNumber` must be provided."
      properties:
        contactId:
          type: "string"
          description: "Contact ObjectId to dial; the contact's phone number is used as the destination."
        phoneNumber:
          type: "string"
          description: "Destination number in E.164; if no contact matches, the call is recorded without one."
      anyOf:
        -
          required:
            - "contactId"
        -
          required:
            - "phoneNumber"
      additionalProperties: true
      example:
        contactId: "64f0a1b2c3d4e5f6a7b8c9d0"
        phoneNumber: "+14165550199"
    CallsRecordInboundCallRequest:
      type: "object"
      properties:
        callerNumber:
          type: "string"
          description: "E.164 caller number."
      required:
        - "callerNumber"
      additionalProperties: true
      example:
        callerNumber: "+14165550199"
    CallsAnswerInboundCallRequest:
      type: "object"
      description: "At least one identifier (callId, twilioCallSid, or callerNumber) should be supplied so the server can locate the Call record."
      properties:
        callId:
          type: "string"
          description: "Tether-minted call identifier - primary lookup key for the Call record."
        conferenceId:
          type: "string"
          description: "Twilio conference room name binding the agent leg to the customer leg."
        callerNumber:
          type: "string"
          description: "PSTN caller number in E.164, used as a fuzzy fallback when no IDs match."
        twilioCallSid:
          type: "string"
          description: "Twilio Call SID (`providerCallId`) used to locate the record when the Tether `callId` is unknown."
      anyOf:
        -
          required:
            - "callId"
        -
          required:
            - "twilioCallSid"
        -
          required:
            - "callerNumber"
      additionalProperties: true
      example:
        callId: "64f0a1b2c3d4e5f6a7b8cb00"
        callerNumber: "+14165550199"
    CallsRejectInboundCallRequest:
      type: "object"
      properties:
        callId:
          type: "string"
          description: "Tether-minted call identifier of the inbound Call to mark as `no-answer`."
        conferenceId:
          type: "string"
          description: "Twilio conference room name the PSTN caller is parked in (reserved for future REST hangup)."
      required:
        - "callId"
      additionalProperties: true
      example:
        callId: "64f0a1b2c3d4e5f6a7b8cb00"
    CallsDiscardCallRequest:
      type: "object"
      properties:
        contactId:
          type: "string"
        deleteContact:
          type: "boolean"
          description: "Only deletes the contact when it was a placeholder (`firstName: \"New Contact\"`, `source: \"Outgoing Call\"`) created from the dialpad."
      additionalProperties: true
      example:
        contactId: "64f0a1b2c3d4e5f6a7b8c9d0"
        deleteContact: true
    CallsSaveVoiceProviderConfigRequest:
      type: "object"
      properties:
        provider:
          type: "string"
          enum:
            - "twilio"
            - "sinch"
          description: "Voice provider whose credentials are being saved: `twilio` or `sinch`."
        phoneNumber:
          type: "string"
          description: "Caller's default phone number for this provider; upserted into the org-level phone number store."
        twilioAccountSid:
          type: "string"
          description: "Twilio Account SID identifying the customer account."
        twilioAuthToken:
          type: "string"
          description: "Twilio auth token paired with the Account SID for REST API calls."
        twilioApiKeySid:
          type: "string"
          description: "Twilio API Key SID used to mint browser-client access tokens."
        twilioApiKeySecret:
          type: "string"
          description: "Secret paired with the Twilio API Key SID for signing access tokens."
        twilioTwimlAppSid:
          type: "string"
          description: "TwiML Application SID that routes outbound SDK calls to Tether's voice webhook."
        twilioServiceSid:
          type: "string"
          description: "Twilio Conversations / Messaging service SID associated with this number."
        sinchApplicationKey:
          type: "string"
          description: "Sinch application key (UUID) identifying the Voice RTC application."
        sinchApplicationSecret:
          type: "string"
          description: "Sinch application secret used to sign RTC JWTs server-side."
      required:
        - "provider"
      additionalProperties: true
      example:
        provider: "sinch"
        phoneNumber: "+14165550100"
        sinchApplicationKey: "sinch-app-key-xxxx"
        sinchApplicationSecret: "sinch-app-secret-xxxx"
    CallsSetActiveVoiceProviderRequest:
      type: "object"
      properties:
        provider:
          type: "string"
          enum:
            - "twilio"
            - "sinch"
          description: "Voice provider to activate for the org; must already have credentials configured."
      required:
        - "provider"
      additionalProperties: true
      example:
        provider: "sinch"
    CallsInitiateOutboundAiCallRequest:
      type: "object"
      description: "Either `contactId` or `phoneNumber` must be supplied. `phoneNumber` will find-or-create a contact."
      properties:
        contactId:
          type: "string"
        phoneNumber:
          type: "string"
          description: "E.164 phone number (the `+` prefix will be added if missing)."
        agentId:
          type: "string"
          description: "Prompt._id - ElevenLabs-synced voice agent to use. Defaults to the first voice-enabled agent in the org."
        fromNumber:
          type: "string"
          description: "Specific Sinch number to call from. Defaults to the first AI-enabled Sinch number assigned to the user."
        callReason:
          type: "string"
          description: "Free-text context passed to the agent as the `call_reason` dynamic variable."
      additionalProperties: true
      example:
        contactId: "64f0a1b2c3d4e5f6a7b8c9d0"
        agentId: "64f0a1b2c3d4e5f6a7b8cc00"
        fromNumber: "+14165550100"
        callReason: "Follow up on insurance quote"
    CallsOutboundAiCallResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        conversationId:
          type: "string"
          description: "ElevenLabs conversation ID for the placed call."
        sipCallId:
          type: "string"
        message:
          type: "string"
        deduplicated:
          type: "boolean"
          description: "True when the request matched an in-flight idempotency lock and the cached conversationId/sipCallId is returned."
      required:
        - "success"
      additionalProperties: true
      example:
        success: true
        conversationId: "eleven-conv-abc123"
        sipCallId: "sip-call-xyz789"
        message: "AI call initiated"
        deduplicated: false
    CallsIngestTranscriptTurn:
      type: "object"
      properties:
        role:
          type: "string"
          enum:
            - "agent"
            - "user"
        message:
          type: "string"
        timestamp:
          type: "number"
          description: "Optional seconds-into-call."
      required:
        - "role"
        - "message"
      additionalProperties: false
      example:
        role: "agent"
        message: "Hi, this is Alex from Example Corp."
        timestamp: 0.5
    CallsIngestExternalCallRequest:
      type: "object"
      description: "Vendor-agnostic completed-call payload. `transcript`, `summary`, and `recording` are required when `status === \"completed\"`."
      properties:
        direction:
          type: "string"
          enum:
            - "inbound"
            - "outbound"
        fromNumber:
          type: "string"
          description: "E.164 (e.g. +14155551234)."
        toNumber:
          type: "string"
          description: "E.164."
        duration:
          type: "number"
          description: "Call duration in seconds (non-negative)."
        status:
          type: "string"
          enum:
            - "completed"
            - "no-answer"
            - "busy"
            - "failed"
        transcript:
          type: "array"
          description: "Structured transcript (required when status is \"completed\"). Plain text is not accepted."
          items:
            "$ref": "#/components/schemas/CallsIngestTranscriptTurn"
        summary:
          type: "string"
          description: "Required when status is \"completed\"."
        recording:
          type: "string"
          description: "Required when status is \"completed\". Base64-encoded MP3 (optionally with a `data:audio/...;base64,` prefix) or a publicly downloadable URL."
        externalCallId:
          type: "string"
          description: "Optional external identifier used for idempotency."
        agentName:
          type: "string"
          description: "Name of the external AI agent."
        metadata:
          type: "object"
          description: "Arbitrary vendor metadata (stored on `providerMetadata.metadata`)."
          additionalProperties: true
        callerName:
          type: "string"
          description: "Used to backfill placeholder contact name when the contact was newly created as \"Unknown Caller\"."
        callStartTime:
          type: "string"
          format: "date-time"
          description: "ISO start time; defaults to now."
        aiTurnDetails:
          type: "array"
          description: "Optional. Per-turn LLM usage / cost / tool-call detail. Each item open-ended."
          items:
            type: "object"
            additionalProperties: true
        aiLlmUsage:
          type: "object"
          description: "Optional. Raw nested model-level usage (mirror ElevenLabs `metadata.charging.llm_usage`)."
          additionalProperties: true
        aiLlmPrice:
          type: "number"
          description: "Optional. USD decimal LLM price (e.g. `0.0986894`)."
        aiCost:
          type: "number"
          description: "Optional. Total call cost as raw integer microcents (1 unit = $0.0001)."
        aiCharging:
          type: "object"
          description: "Optional. Charging breakdown - open-ended object."
          additionalProperties: true
        aiCallSuccessful:
          type: "string"
          enum:
            - "success"
            - "failure"
            - "unknown"
          description: "Optional. Analysis verdict. Must be one of `success`, `failure`, `unknown` if provided. NOT a boolean."
        aiEvaluationResults:
          type: "object"
          description: "Optional. Evaluation results - **object keyed by criteria name** (NOT an array)."
          additionalProperties: true
        aiDataCollection:
          type: "array"
          description: "Optional. Data collection results - **array form**, preserves order."
          items:
            type: "object"
            additionalProperties: true
        aiDynamicVariables:
          type: "object"
          description: "Optional. Dynamic variables from the conversation init payload."
          additionalProperties: true
        aiFeaturesUsage:
          type: "object"
          description: "Optional. Which provider features were enabled/used during the call."
          additionalProperties: true
        aiSummaryTitle:
          type: "string"
          description: "Optional. Short title for the call (long-form summary goes in `summary`)."
        aiTerminationReason:
          type: "string"
          description: "Optional. Reason the call ended (e.g. `\"Client disconnected: 1000\"`)."
      required:
        - "direction"
        - "fromNumber"
        - "toNumber"
        - "duration"
        - "status"
      additionalProperties: true
      example:
        direction: "outbound"
        fromNumber: "+14165550100"
        toNumber: "+14165550199"
        duration: 154
        status: "completed"
        transcript:
          -
            role: "agent"
            message: "Hi, this is Alex from Example Corp."
            timestamp: 0.5
          -
            role: "user"
            message: "Hey Alex."
            timestamp: 2.8
        summary: "Confirmed appointment for Friday at 2pm."
        recording: "https://vendor.example/recordings/abc123.mp3"
        externalCallId: "vendor-call-abc123"
        agentName: "Alex (Example Agent)"
        callStartTime: "2026-05-15T09:10:00.000Z"
        aiCallSuccessful: "success"
        aiCost: 4101
        aiLlmPrice: 0.0986894
        aiSummaryTitle: "Friday 2pm appointment confirmed"
        aiTerminationReason: "Client disconnected: 1000"
        aiCharging:
          llm_charge: 986
          call_charge: 3115
          llm_price: 0.0986894
          dev_discount: false
          is_burst: false
          tier: "standard"
        aiEvaluationResults:
          booking_confirmed:
            criteria_id: "crit_1"
            result: "pass"
            rationale: "Customer confirmed Friday 2pm."
        aiDataCollection:
          -
            data_collection_id: "appointment_time"
            value: "Friday 2pm"
            json_schema:
              type: "string"
              description: "Booked appointment time"
        aiDynamicVariables:
          caller_first_name: "Alex"
          system__caller_phone: "+14165550199"
        aiFeaturesUsage:
          language_detection: true
          profanity_filter: true
    CallsIngestCreatedResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        callId:
          type: "string"
          description: "Tether Call._id."
        contactId:
          type: "string"
        conversationId:
          type: "string"
      required:
        - "success"
        - "callId"
        - "contactId"
        - "conversationId"
      additionalProperties: true
      example:
        success: true
        callId: "64f0a1b2c3d4e5f6a7b8cb00"
        contactId: "64f0a1b2c3d4e5f6a7b8c9d0"
        conversationId: "64f0a1b2c3d4e5f6a7b8c9e0"
    CallsIngestDedupResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        deduplicated:
          type: "boolean"
          enum:
            - true
        callId:
          type: "string"
      required:
        - "success"
        - "deduplicated"
        - "callId"
      additionalProperties: true
      example:
        success: true
        deduplicated: true
        callId: "64f0a1b2c3d4e5f6a7b8cb00"
    CallsIngestErrorResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - false
        error:
          type: "string"
      required:
        - "success"
        - "error"
      additionalProperties: true
      example:
        success: false
        error: "Missing required field: transcript"
    CallsVoiceAiOrgPhoneNumber:
      type: "object"
      description: "A Sinch phone number from a user in the org, flattened with `userName` and `userId`."
      properties:
        provider:
          type: "string"
          enum:
            - "sinch"
        phoneNumber:
          type: "string"
        isDefault:
          type: "boolean"
        isInboundEnabled:
          type: "boolean"
        routing:
          type: "object"
          description: "Per-leg routing policy. Four independent toggles: each direction can be open or closed to humans and to the AI on its own."
          properties:
            inbound:
              type: "object"
              properties:
                enabled:
                  type: "boolean"
                  description: "Accept inbound calls at all."
                ai:
                  type: "boolean"
                  description: "Inbound is answered by the AI agent."
                forwardToNumber:
                  type: "string"
                  description: "Forward inbound to this PSTN number instead of ringing a browser. Rejected while inbound.ai is on."
            outbound:
              type: "object"
              properties:
                enabled:
                  type: "boolean"
                  description: "A human may use this number as caller ID."
                ai:
                  type: "boolean"
                  description: "The AI may use this number as caller ID."
        aiAgentId:
          type: "string"
        elevenlabsPhoneNumberId:
          type: "string"
        label:
          type: "string"
        userName:
          type: "string"
        userId:
          type: "string"
      additionalProperties: true
      example:
        provider: "sinch"
        phoneNumber: "+14165550100"
        isDefault: true
        isInboundEnabled: true
        routing:
          inbound:
            enabled: true
            ai: true
          outbound:
            enabled: false
            ai: true
        aiAgentId: "64f0a1b2c3d4e5f6a7b8cc00"
        elevenlabsPhoneNumberId: "eleven-pn-abc123"
        label: "Main line"
        userName: "Alex Rep"
        userId: "64f0a1b2c3d4e5f6a7b8c9d4"
    CallsVoiceAiConfigResponse:
      type: "object"
      properties:
        aiVoiceProvider:
          type: "string"
          nullable: true
          description: "e.g. `elevenlabs`. Null if not configured."
        hasApiKey:
          type: "boolean"
          description: "True when ElevenLabs API key is set."
        hasToolSecret:
          type: "boolean"
          description: "True when an ElevenLabs tool secret has been generated."
        sinchSipDomain:
          type: "string"
          nullable: true
          description: "Sinch Voice API SIP termination host the AI provider sends outbound INVITEs to. Null means the regional default applies."
        phoneNumbers:
          type: "array"
          items:
            "$ref": "#/components/schemas/CallsVoiceAiOrgPhoneNumber"
      additionalProperties: true
      example:
        aiVoiceProvider: "elevenlabs"
        hasApiKey: true
        hasToolSecret: true
        sinchSipDomain: "use1.vp.sip.sinch.com"
        phoneNumbers:
          []
    CallsSaveVoiceAiConfigRequest:
      type: "object"
      description: "Only the supplied fields are updated (no field is required, since admins partially edit)."
      properties:
        aiVoiceProvider:
          type: "string"
          nullable: true
          description: "e.g. `elevenlabs`. Pass `null` to clear."
        elevenlabsApiKey:
          type: "string"
        generateToolSecret:
          type: "boolean"
          description: "When true, a fresh 32-byte hex `elevenlabsToolSecret` is generated, stored, and pushed into the org ElevenLabs workspace secret the tool headers reference."
        sinchSipDomain:
          type: "string"
          description: "Sinch Voice API SIP termination host. An empty string clears it, restoring the regional default."
      additionalProperties: true
      example:
        aiVoiceProvider: "elevenlabs"
        elevenlabsApiKey: "sk_eleven_xxxxxxxxxxxxxxxx"
        generateToolSecret: true
        sinchSipDomain: "use1.vp.sip.sinch.com"
    CallsTogglePhoneNumberAiRequest:
      type: "object"
      properties:
        userId:
          type: "string"
          description: "User whose assigned phone number is being toggled."
        phoneNumber:
          type: "string"
          description: "Exact phone number string to match against the user's assigned phone numbers."
        routing:
          type: "object"
          description: "Per-leg routing policy. Four independent toggles: each direction can be open or closed to humans and to the AI on its own."
          properties:
            inbound:
              type: "object"
              properties:
                enabled:
                  type: "boolean"
                  description: "Accept inbound calls at all."
                ai:
                  type: "boolean"
                  description: "Inbound is answered by the AI agent."
                forwardToNumber:
                  type: "string"
                  description: "Forward inbound to this PSTN number instead of ringing a browser. Rejected while inbound.ai is on."
            outbound:
              type: "object"
              properties:
                enabled:
                  type: "boolean"
                  description: "A human may use this number as caller ID."
                ai:
                  type: "boolean"
                  description: "The AI may use this number as caller ID."
        aiAgentId:
          type: "string"
          description: "Prompt._id to link when enabling AI. Required to switch agents on a number that already has an AI leg on."
      required:
        - "phoneNumber"
      additionalProperties: true
      example:
        phoneNumber: "+14165550100"
        routing:
          inbound:
            ai: true
          outbound:
            ai: true
        aiAgentId: "64f0a1b2c3d4e5f6a7b8cc00"
    CallsTogglePhoneNumberAiErrorResponse:
      type: "object"
      properties:
        error:
          type: "string"
        code:
          type: "string"
          description: "Stable code: `PHONE_NUMBER_NOT_FOUND` when the number is not in the organization, `AGENT_NOT_SYNCED` when the agent has no `elevenlabsAgentId`, `AI_NOT_ALLOWED_ON_GROUP` when inbound AI is requested on a group-linked number, `AI_NOT_ALLOWED_ON_SHORTCODE` when AI is turned on for a short code (SMS only)."
          enum:
            - "PHONE_NUMBER_NOT_FOUND"
            - "AGENT_NOT_SYNCED"
            - "AI_NOT_ALLOWED_ON_GROUP"
            - "AI_NOT_ALLOWED_ON_SHORTCODE"
      additionalProperties: true
      example:
        error: "Agent not synced to ElevenLabs"
        code: "AGENT_NOT_SYNCED"
    CallsVoicesResponse:
      type: "object"
      properties:
        voices:
          type: "array"
          description: "Provider-shaped voice descriptors; ElevenLabs voices include `voice_id`, `name`, `labels`, etc."
          items:
            type: "object"
            additionalProperties: true
      required:
        - "voices"
      additionalProperties: true
      example:
        voices:
          -
            voice_id: "21m00Tcm4TlvDq8ikWAM"
            name: "Rachel"
            labels:
              accent: "american"
              age: "young"
    CallsLLMsResponse:
      type: "object"
      properties:
        llms:
          type: "array"
          description: "Provider-shaped LLM descriptors."
          items:
            type: "object"
            additionalProperties: true
      required:
        - "llms"
      additionalProperties: true
      example:
        llms:
          -
            id: "gpt-4o-mini"
            name: "GPT-4o mini"
          -
            id: "claude-3-5-sonnet"
            name: "Claude 3.5 Sonnet"
    CallsVoiceAiTool:
      type: "object"
      properties:
        key:
          type: "string"
          description: "Stable identifier (e.g. `checkBusinessHours`, `getContact`, `checkAvailability`, `transfer`)."
        label:
          type: "string"
        description:
          type: "string"
        disabled:
          type: "boolean"
        disabledReason:
          type: "string"
      required:
        - "key"
        - "label"
        - "description"
      additionalProperties: true
      example:
        key: "checkBusinessHours"
        label: "Check business hours"
        description: "Returns whether the org is currently open and the next open window."
        disabled: false
    CallsVoiceAiToolsResponse:
      type: "object"
      properties:
        tools:
          type: "array"
          items:
            "$ref": "#/components/schemas/CallsVoiceAiTool"
      required:
        - "tools"
      additionalProperties: true
      example:
        tools:
          -
            key: "checkBusinessHours"
            label: "Check business hours"
            description: "Returns whether the org is currently open and the next open window."
            disabled: false
    CallsVoiceAiTransferableAgent:
      type: "object"
      description: "A single Prompt eligible as a Voice AI transfer target."
      properties:
        id:
          type: "string"
          description: "Prompt `_id` (stringified ObjectId)."
        name:
          type: "string"
      required:
        - "id"
        - "name"
      additionalProperties: true
      example:
        id: "64d2f9c5e8a1d4e001a0b1c2"
        name: "Senior Leasing Specialist"
    CallsVoiceAiTransferableAgentsResponse:
      type: "object"
      properties:
        agents:
          type: "array"
          items:
            "$ref": "#/components/schemas/CallsVoiceAiTransferableAgent"
      required:
        - "agents"
      additionalProperties: true
      example:
        agents:
          -
            id: "64d2f9c5e8a1d4e001a0b1c2"
            name: "Senior Leasing Specialist"
          -
            id: "64d2f9c5e8a1d4e001a0b1c3"
            name: "Maintenance Coordinator"
    ErrorResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
        error:
          type: "string"
      additionalProperties: true
      example:
        success: false
        message: "Validation error"
        error: "name is required"
    SuccessMessageResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        message:
          type: "string"
      additionalProperties: true
      example:
        success: true
        message: "Campaign cancelled"
    CampaignDto:
      type: "object"
      properties:
        _id:
          type: "string"
        organizationId:
          type: "string"
        name:
          type: "string"
        message:
          type: "string"
        userIds:
          type: "array"
          items:
            type: "string"
        scheduleDate:
          type: "string"
          format: "date-time"
        process:
          type: "string"
        contactStatus:
          type: "string"
        isAutopilot:
          type: "boolean"
        checkConsent:
          type: "boolean"
          description: "\"Check consent before sending\". Omitted means true: every send is checked and the campaign sends at the long code rate. False skips the check for sends from a short code and lets them go at the short code rate; sends from any other line are still checked; accepted only when the organization allows campaigns to skip the check."
        type:
          type: "string"
        status:
          type: "string"
          description: "One of: importing, scheduled, sending, sent, failed, partial success, cancelled. `importing`: the recipients are still being imported from an uploaded CSV file and nothing sends the campaign yet. `sending`: a send run is in progress."
        csvImport:
          "$ref": "#/components/schemas/CampaignCsvImport"
        recipientCount:
          type: "integer"
          description: "Number of recipients (CampaignRecipient rows) of the campaign."
        sentCount:
          type: "integer"
          description: "Recipients sent so far."
        failedCount:
          type: "integer"
          description: "Recipients whose send failed."
        blockedCount:
          type: "integer"
          description: "Recipients refused on purpose (Do-Not-Contact or blocked contact)."
        createdBy:
          type: "object"
          additionalProperties: true
        failedUserIds:
          type: "array"
          items:
            type: "string"
        failedDetails:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
        segmentation:
          type: "object"
          additionalProperties: true
          description: "Segmentation config with segments array when enabled"
        assignment:
          type: "object"
          additionalProperties: true
          description: "Assignment config when enabled"
        stats:
          type: "object"
          properties:
            total:
              type: "integer"
            sent:
              type: "integer"
            failed:
              type: "integer"
            successRate:
              type: "string"
          additionalProperties: false
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "665f1a0c0e0a4b001a2c9f10"
        organizationId: "64ee9a8b1e7f2a0011223344"
        name: "Q2 Lead Gen"
        message: "Hi {{firstName}}, are you still interested in a quote?"
        userIds:
          - "64ee9a8b1e7f2a0011223399"
        scheduleDate: "2026-05-20T15:00:00.000Z"
        process: "64eea1110000000000000001"
        contactStatus: "New Lead"
        isAutopilot: false
        type: "sms"
        status: "scheduled"
        createdBy:
          _id: "64ee9a8b1e7f2a0011223399"
          fullName: "Alex Rep"
        failedUserIds:
          []
        failedDetails:
          []
        stats:
          total: 250
          sent: 0
          failed: 0
          successRate: "0%"
        createdAt: "2026-05-18T12:34:56.000Z"
        updatedAt: "2026-05-18T12:34:56.000Z"
    CreateCampaignRequest:
      type: "object"
      properties:
        name:
          type: "string"
        message:
          type: "string"
        newContacts:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
        selectedExistingContacts:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
        userIds:
          type: "array"
          items:
            type: "string"
          description: "Legacy format - contact IDs"
        scheduleDate:
          type: "string"
          format: "date-time"
        process:
          type: "string"
        status:
          type: "string"
        isAutopilot:
          type: "boolean"
        checkConsent:
          type: "boolean"
          description: "\"Check consent before sending\". Omitted means true: every send is checked and the campaign sends at the long code rate. False skips the check for sends from a short code and lets them go at the short code rate; sends from any other line are still checked; accepted only when the organization allows campaigns to skip the check."
        type:
          type: "string"
        segmentation:
          type: "object"
          additionalProperties: true
        assignment:
          type: "object"
          additionalProperties: true
      required:
        - "name"
        - "message"
      additionalProperties: true
      example:
        name: "Q2 Lead Gen"
        message: "Hi {{firstName}}, are you still interested?"
        newContacts:
          -
            firstName: "Jamie"
            phoneNumber: "+14155550133"
        selectedExistingContacts:
          -
            _id: "665f1a0c0e0a4b001a2c9f01"
            firstName: "Sam"
            lastName: "Patel"
            phoneNumber: "+14165550100"
          -
            _id: "665f1a0c0e0a4b001a2c9f02"
            firstName: "Alex"
            lastName: "Morgan"
            phoneNumber: "+14165550101"
        scheduleDate: "2026-05-20T15:00:00.000Z"
        isAutopilot: false
        type: "sms"
    CreateCampaignCsvReviewRequest:
      type: "object"
      properties:
        file:
          type: "string"
          format: "binary"
          description: "CSV file with a header row. A phoneNumber column is required; firstName, lastName and email are read when present. Header names are matched ignoring case, spaces and punctuation; phone, mobile, mobileNumber and cellPhone also name the phone column, and emailAddress the email column. Other columns are ignored."
        config:
          type: "string"
          description: "Optional JSON object with what the rows are classified for: `segmentation` (`enabled`, `distributionType`, and `segments` with `id` and `contactCount`; rows fill the segments in file order, and with a custom distribution rows past the segment sizes go to `outside_segments`) and `assignment` (`isAssignmentEnabled`, `assignmentType` `campaign` or `segment`, `selectedUsers`, `segmentAssignments`). The launch must send the same segments and assignment."
      required:
        - "file"
    CampaignCsvRowCategory:
      type: "string"
      enum:
        - "new"
        - "existing"
        - "outbound"
        - "inbound"
        - "other_users"
        - "protected"
        - "duplicate"
        - "invalid"
        - "outside_segments"
      description: "Review group of a CSV row. `new`: no contact has the number (launching creates one). `existing`: a contact a campaign target owns, with no SMS history. `outbound` / `inbound`: a contact a campaign target owns whose last SMS went out / came in. `other_users`: a contact no campaign target owns. `protected`: inside another user's contact protection window. `duplicate`: the number appeared on an earlier row. `invalid`: no usable phone number. `outside_segments`: past the segment sizes of a custom split. The campaign target is the creator, the assigned users, or the row's segment assignee. `new`, `existing`, `outbound` and `inbound` start selected; `other_users` is opt-in; the other groups cannot be selected."
    CampaignCsvReviewSession:
      type: "object"
      properties:
        importId:
          type: "string"
        status:
          type: "string"
          enum:
            - "analyzing"
            - "ready"
            - "committing"
            - "committed"
            - "failed"
          description: "`analyzing`: the rows are being written. `ready`: the selection can change and a campaign can be launched. `committing` / `committed`: a campaign was launched from the review (`campaignId`). `failed`: see `error`."
        fileName:
          type: "string"
          nullable: true
        totalRows:
          type: "integer"
          description: "Data rows in the file."
        analyzedRows:
          type: "integer"
          description: "Rows the analysis has written so far."
        counts:
          type: "object"
          description: "Total and selected rows of each review group, keyed by CampaignCsvRowCategory."
          additionalProperties:
            type: "object"
            properties:
              total:
                type: "integer"
              selected:
                type: "integer"
        segmentSelected:
          type: "object"
          description: "Selected rows per segment id (segmented campaigns)."
          additionalProperties:
            type: "integer"
        selectedTotal:
          type: "integer"
          description: "Selected rows of every group."
        campaignId:
          type: "string"
          nullable: true
        error:
          type: "string"
          nullable: true
      additionalProperties: true
      example:
        importId: "6710b2c4e8a1d4e001a0b2e0"
        status: "ready"
        fileName: "contacts.csv"
        totalRows: 3
        analyzedRows: 3
        counts:
          new:
            total: 1
            selected: 1
          existing:
            total: 0
            selected: 0
          outbound:
            total: 1
            selected: 1
          inbound:
            total: 0
            selected: 0
          other_users:
            total: 0
            selected: 0
          protected:
            total: 0
            selected: 0
          duplicate:
            total: 1
            selected: 0
          invalid:
            total: 0
            selected: 0
          outside_segments:
            total: 0
            selected: 0
        segmentSelected:
          {}
        selectedTotal: 2
        campaignId: null
        error: null
    CampaignCsvReviewStartResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          allOf:
            -
              "$ref": "#/components/schemas/CampaignCsvReviewSession"
            -
              type: "object"
              properties:
                operationId:
                  type: "string"
                  description: "The async operation that analyzes the file."
      additionalProperties: true
    CampaignCsvReviewResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          "$ref": "#/components/schemas/CampaignCsvReviewSession"
      additionalProperties: true
    CampaignCsvReviewSelectionResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          allOf:
            -
              "$ref": "#/components/schemas/CampaignCsvReviewSession"
            -
              type: "object"
              properties:
                updated:
                  type: "integer"
                  description: "Rows whose selection changed."
      additionalProperties: true
    CampaignCsvReviewRow:
      type: "object"
      properties:
        id:
          type: "string"
        rowNo:
          type: "integer"
          description: "0-based data row index; the file line is `rowNo + 2`."
        category:
          "$ref": "#/components/schemas/CampaignCsvRowCategory"
        selected:
          type: "boolean"
        firstName:
          type: "string"
          nullable: true
        lastName:
          type: "string"
          nullable: true
        email:
          type: "string"
          nullable: true
        phone:
          type: "string"
          nullable: true
          description: "The number in E.164 form, or the cell as written on an invalid row."
        segmentId:
          type: "string"
          nullable: true
        ownedBy:
          type: "string"
          nullable: true
          description: "Names of the users the matched contact's conversations are assigned to."
        hasExistingConversation:
          type: "boolean"
        lastMessageDate:
          type: "string"
          format: "date-time"
          nullable: true
        protectedUntil:
          type: "string"
          format: "date-time"
          nullable: true
        reason:
          type: "string"
          nullable: true
          description: "Why a duplicate or invalid row is left out."
        duplicateOfRowNo:
          type: "integer"
          nullable: true
      additionalProperties: true
    CampaignCsvReviewRowsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "object"
          properties:
            rows:
              type: "array"
              items:
                "$ref": "#/components/schemas/CampaignCsvReviewRow"
            nextAfter:
              type: "integer"
              nullable: true
              description: "Send as `after` for the next page; null on the last page."
            previousBefore:
              type: "integer"
              nullable: true
              description: "Send as `before` for the previous page; null on the first page."
            matches:
              type: "object"
              description: "With `search` only: the rows of the group the search matches across every page, and how many of them are selected. Selecting the group with the same search changes exactly these rows."
              properties:
                total:
                  type: "integer"
                selected:
                  type: "integer"
      additionalProperties: true
    UpdateCampaignCsvRowSelectionRequest:
      type: "object"
      properties:
        rowIds:
          type: "array"
          items:
            type: "string"
          minItems: 1
          maxItems: 500
        selected:
          type: "boolean"
      required:
        - "rowIds"
        - "selected"
      example:
        rowIds:
          - "6710b2c4e8a1d4e001a0b2e5"
        selected: false
    UpdateCampaignCsvCategorySelectionRequest:
      type: "object"
      properties:
        category:
          type: "string"
          enum:
            - "new"
            - "existing"
            - "outbound"
            - "inbound"
            - "other_users"
        selected:
          type: "boolean"
        search:
          type: "string"
          maxLength: 100
          description: "Change only the rows this search matches: every word must match the first name, last name or number."
      required:
        - "category"
        - "selected"
      example:
        category: "other_users"
        selected: true
    LaunchCampaignCsvImportRequest:
      type: "object"
      properties:
        importId:
          type: "string"
          description: "The `ready` CSV review session whose selected rows become the recipients."
        name:
          type: "string"
        message:
          type: "string"
        scheduleDate:
          type: "string"
          format: "date-time"
        process:
          type: "string"
        status:
          type: "string"
        isAutopilot:
          type: "boolean"
        checkConsent:
          type: "boolean"
          description: "\"Check consent before sending\". Omitted means true: every send is checked and the campaign sends at the long code rate. False skips the check for sends from a short code and lets them go at the short code rate; sends from any other line are still checked; accepted only when the organization allows campaigns to skip the check."
        type:
          type: "string"
        segmentation:
          type: "object"
          additionalProperties: true
          description: "Segments with id, segmentNumber, contactCount and scheduledDate. The ids and sizes must match the review config."
        assignment:
          type: "object"
          additionalProperties: true
          description: "Must assign the same users as the review config."
        selectedPhoneNumberIds:
          type: "array"
          items:
            type: "string"
      required:
        - "importId"
        - "name"
        - "message"
      additionalProperties: true
      example:
        importId: "6710b2c4e8a1d4e001a0b2e0"
        name: "Spring promo"
        message: "Hi {{firstName}}, our spring offer is live."
        scheduleDate: "2026-10-12T15:00:00.000Z"
        selectedPhoneNumberIds:
          - "64d2f9c5e8a1d4e001a0b1d0"
    CampaignCsvImport:
      type: "object"
      description: "State and counts of the CSV import of a campaign."
      properties:
        status:
          type: "string"
          enum:
            - "queued"
            - "running"
            - "completed"
            - "failed"
        operationId:
          type: "string"
        fileName:
          type: "string"
        totalRows:
          type: "integer"
          description: "Selected review rows the import resolves."
        processedRows:
          type: "integer"
        recipients:
          type: "integer"
        created:
          type: "integer"
        matched:
          type: "integer"
        merged:
          type: "integer"
        sentToReview:
          type: "integer"
        invalidRows:
          type: "integer"
        duplicateRows:
          type: "integer"
        ownedByOthers:
          type: "integer"
          description: "Other users' contacts left unselected in the review."
        protectedContacts:
          type: "integer"
        outsideSegments:
          type: "integer"
        failedRows:
          type: "integer"
        workflowsStarted:
          type: "integer"
        workflowsFailed:
          type: "integer"
        error:
          type: "string"
        startedAt:
          type: "string"
          format: "date-time"
        completedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
    CampaignImportStartResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        message:
          type: "string"
        operationId:
          type: "string"
        data:
          "$ref": "#/components/schemas/CampaignDto"
      additionalProperties: true
    CampaignImportStatusResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "object"
          properties:
            campaignId:
              type: "string"
            campaignStatus:
              type: "string"
            recipientCount:
              type: "integer"
            failureReason:
              type: "string"
              nullable: true
            import:
              "$ref": "#/components/schemas/CampaignCsvImport"
            operation:
              type: "object"
              nullable: true
              properties:
                status:
                  type: "string"
                progress:
                  type: "object"
                  properties:
                    total:
                      type: "integer"
                    processed:
                      type: "integer"
                    succeeded:
                      type: "integer"
                    failed:
                      type: "integer"
                    skipped:
                      type: "integer"
                error:
                  type: "object"
                  nullable: true
                  additionalProperties: true
      additionalProperties: true
    UpdateCampaignRequest:
      type: "object"
      properties:
        name:
          type: "string"
          description: "Campaign display name shown in the campaigns list."
        message:
          type: "string"
          description: "SMS body used when `isAutopilot` is false; supports `{{firstName}}`-style placeholders."
        scheduleDate:
          type: "string"
          format: "date-time"
          description: "ISO timestamp when the campaign should fire; null sends immediately."
        isAutopilot:
          type: "boolean"
          description: "When true, the AI prompt drives the campaign instead of using the `message` body verbatim."
        checkConsent:
          type: "boolean"
          description: "\"Check consent before sending\". False is accepted only when the organization allows campaigns to skip the check."
        process:
          type: "string"
          description: "Prompt `_id` used to drive AI replies for this campaign."
        status:
          type: "string"
          description: "Lifecycle status: `scheduled`, `sent`, `failed`, `partial success`, or `cancelled`."
        segmentProcesses:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
          description: "Per-segment overrides keyed by stage `_id`."
        segmentStatuses:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
          description: "Per-segment overrides keyed by stage `_id`."
        segmentSchedules:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
          description: "Per-segment overrides keyed by stage `_id`."
      additionalProperties: true
      example:
        name: "Q2 Lead Gen (revised)"
        message: "Hi {{firstName}}, quick follow-up - let me know if a 10-min call works."
        scheduleDate: "2026-05-22T16:00:00.000Z"
        isAutopilot: false
    CampaignMutationResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        message:
          type: "string"
        data:
          "$ref": "#/components/schemas/CampaignDto"
      additionalProperties: true
      example:
        success: true
        message: "Campaign created"
        data:
          _id: "665f1a0c0e0a4b001a2c9f10"
          name: "Q2 Lead Gen"
          status: "scheduled"
          scheduleDate: "2026-05-20T15:00:00.000Z"
    CampaignDetailResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          "$ref": "#/components/schemas/CampaignDto"
      additionalProperties: true
      example:
        success: true
        data:
          _id: "665f1a0c0e0a4b001a2c9f10"
          name: "Q2 Lead Gen"
          status: "sent"
          stats:
            total: 250
            sent: 248
            failed: 2
            successRate: "99.2%"
    CampaignListResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/CampaignDto"
      additionalProperties: true
      example:
        success: true
        data:
          -
            _id: "665f1a0c0e0a4b001a2c9f10"
            name: "Q2 Lead Gen"
            status: "scheduled"
            scheduleDate: "2026-05-20T15:00:00.000Z"
    CampaignAnalyticsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "object"
          properties:
            totalCampaigns:
              type: "integer"
            scheduledCount:
              type: "integer"
            sentCount:
              type: "integer"
            failedCount:
              type: "integer"
            partialSuccessCount:
              type: "integer"
            cancelledCount:
              type: "integer"
            segmentedCount:
              type: "integer"
            segmentedPercentage:
              type: "string"
            totalMessages:
              type: "integer"
            sentMessages:
              type: "integer"
            scheduledMessages:
              type: "integer"
            failedMessages:
              type: "integer"
            overallSuccessRate:
              type: "string"
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        data:
          totalCampaigns: 42
          scheduledCount: 5
          sentCount: 30
          failedCount: 1
          partialSuccessCount: 4
          cancelledCount: 2
          segmentedCount: 8
          segmentedPercentage: "19.05%"
          totalMessages: 12450
          sentMessages: 12380
          scheduledMessages: 50
          failedMessages: 20
          overallSuccessRate: "99.4%"
    TeamPerformanceResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
      additionalProperties: true
      example:
        success: true
        data:
          -
            userId: "64ee9a8b1e7f2a0011223399"
            fullName: "Alex Rep"
            campaigns: 6
            sent: 1480
            successRate: "98.7%"
          -
            userId: "64ee9a8b1e7f2a001122339a"
            fullName: "Sam Closer"
            campaigns: 4
            sent: 920
            successRate: "99.5%"
    CreateScheduledMessageRequest:
      type: "object"
      properties:
        message:
          type: "string"
        scheduleDate:
          type: "string"
          format: "date-time"
        contactId:
          type: "string"
        process:
          type: "string"
        isAutopilot:
          type: "boolean"
        originalSettings:
          type: "object"
          additionalProperties: true
        channelType:
          type: "string"
        isInternal:
          type: "boolean"
          description: "Must be false - private notes cannot be scheduled"
      required:
        - "message"
        - "scheduleDate"
        - "contactId"
      additionalProperties: true
      example:
        message: "Hi Jamie, just following up on our chat."
        scheduleDate: "2026-05-19T14:30:00.000Z"
        contactId: "665f1a0c0e0a4b001a2c9f01"
        channelType: "sms"
        isAutopilot: false
        isInternal: false
    UpdateScheduledMessageRequest:
      type: "object"
      properties:
        message:
          type: "string"
        scheduleDate:
          type: "string"
          format: "date-time"
        process:
          type: "string"
        isAutopilot:
          type: "boolean"
        assignedTo:
          type: "string"
        isInternal:
          type: "boolean"
          description: "Must be false - private notes cannot be scheduled"
        contactStatus:
          type: "string"
      required:
        - "message"
        - "scheduleDate"
      additionalProperties: true
      example:
        message: "Hi Jamie, rescheduling - does Friday afternoon work?"
        scheduleDate: "2026-05-21T20:00:00.000Z"
        isAutopilot: false
    ScheduledMessageResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        message:
          type: "string"
        data:
          "$ref": "#/components/schemas/CampaignDto"
      additionalProperties: true
      example:
        success: true
        message: "Scheduled message created"
        data:
          _id: "665f1a0c0e0a4b001a2c9f20"
          scheduleDate: "2026-05-19T14:30:00.000Z"
          status: "scheduled"
    ScheduledMessagesListResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
      additionalProperties: true
      example:
        success: true
        data:
          -
            _id: "665f1a0c0e0a4b001a2c9f20"
            message: "Hi Jamie, just following up on our chat."
            scheduleDate: "2026-05-19T14:30:00.000Z"
            contactId: "665f1a0c0e0a4b001a2c9f01"
            status: "scheduled"
    AutoSegmentRequest:
      type: "object"
      properties:
        totalContacts:
          type: "integer"
          minimum: 1
        firstSegmentDate:
          type: "string"
          description: "Optional YYYY-MM-DD date in the user/browser local timezone for the first segment."
        firstSegmentTime:
          type: "string"
          description: "Optional HH:mm time in the user/browser local timezone. Defaults to 10:00 when omitted."
      required:
        - "totalContacts"
      additionalProperties: true
      example:
        totalContacts: 500
        firstSegmentDate: "2026-05-20"
        firstSegmentTime: "10:00"
    AutoSegmentSegment:
      type: "object"
      properties:
        id:
          type: "string"
        scheduledDate:
          type: "string"
          format: "date-time"
          description: "UTC ISO timestamp."
        contactCount:
          type: "integer"
      required:
        - "id"
        - "scheduledDate"
        - "contactCount"
      additionalProperties: false
      example:
        id: "seg-1"
        scheduledDate: "2026-05-20T17:00:00.000Z"
        contactCount: 100
    AutoSegmentResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        segments:
          type: "array"
          items:
            "$ref": "#/components/schemas/AutoSegmentSegment"
        totalSegments:
          type: "integer"
        warnings:
          type: "array"
          items:
            type: "string"
      required:
        - "success"
        - "segments"
        - "totalSegments"
        - "warnings"
      additionalProperties: true
      example:
        success: true
        segments:
          -
            id: "seg-1"
            scheduledDate: "2026-05-20T17:00:00.000Z"
            contactCount: 100
          -
            id: "seg-2"
            scheduledDate: "2026-05-21T17:00:00.000Z"
            contactCount: 100
        totalSegments: 5
        warnings:
          []
    NextAvailableSlotResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        isUnlimited:
          type: "boolean"
        timezone:
          type: "string"
        dailyLimit:
          type: "integer"
          nullable: true
        todayDate:
          type: "string"
          description: "Org-local YYYY-MM-DD."
        todayUsage:
          type: "integer"
        todayAvailableQuota:
          type: "integer"
          nullable: true
        nextAvailableDate:
          type: "string"
          description: "Org-local YYYY-MM-DD."
        availableQuota:
          type: "integer"
          nullable: true
        daysUntilAvailable:
          type: "integer"
        message:
          type: "string"
      additionalProperties: true
      example:
        success: true
        isUnlimited: false
        timezone: "America/Toronto"
        dailyLimit: 500
        todayDate: "2026-05-18"
        todayUsage: 480
        todayAvailableQuota: 20
        nextAvailableDate: "2026-05-19"
        availableQuota: 500
        daysUntilAvailable: 1
        message: "Next slot with full daily quota is tomorrow."
    UsageCalendarCampaignEntry:
      type: "object"
      properties:
        campaignId:
          type: "string"
        campaignName:
          type: "string"
        contactCount:
          type: "integer"
        status:
          type: "string"
        isSegmented:
          type: "boolean"
        segmentNumber:
          type: "integer"
        failedCount:
          type: "integer"
          description: "Failed recipients of the whole campaign. `failedDetails` lists at most the first 100."
        failedDetails:
          type: "array"
          items:
            type: "object"
            properties:
              phoneNumber:
                type: "string"
              reason:
                type: "string"
            additionalProperties: true
      additionalProperties: true
      example:
        campaignId: "665f1a0c0e0a4b001a2c9f10"
        campaignName: "Q2 Lead Gen"
        contactCount: 100
        status: "scheduled"
        isSegmented: true
        segmentNumber: 1
        failedDetails:
          []
    UsageCalendarDateEntry:
      type: "object"
      properties:
        sent:
          type: "integer"
        reserved:
          type: "integer"
        total:
          type: "integer"
        availableQuota:
          type: "integer"
        campaigns:
          type: "array"
          items:
            "$ref": "#/components/schemas/UsageCalendarCampaignEntry"
      required:
        - "sent"
        - "reserved"
        - "total"
        - "availableQuota"
        - "campaigns"
      additionalProperties: true
      example:
        sent: 0
        reserved: 100
        total: 100
        availableQuota: 400
        campaigns:
          -
            campaignId: "665f1a0c0e0a4b001a2c9f10"
            campaignName: "Q2 Lead Gen"
            contactCount: 100
            status: "scheduled"
            isSegmented: true
            segmentNumber: 1
    UsageCalendarResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "object"
          properties:
            timezone:
              type: "string"
            dailyLimit:
              type: "integer"
            isUnlimited:
              type: "boolean"
            plan:
              type: "string"
            dates:
              type: "object"
              description: "Map of org-local YYYY-MM-DD to that date's usage entry."
              additionalProperties:
                "$ref": "#/components/schemas/UsageCalendarDateEntry"
          required:
            - "timezone"
            - "dailyLimit"
            - "isUnlimited"
            - "dates"
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          timezone: "America/Toronto"
          dailyLimit: 500
          isUnlimited: false
          plan: "growth"
          dates:
            "2026-05-20":
              sent: 0
              reserved: 100
              total: 100
              availableQuota: 400
              campaigns:
                -
                  campaignId: "665f1a0c0e0a4b001a2c9f10"
                  campaignName: "Q2 Lead Gen"
                  contactCount: 100
                  status: "scheduled"
    ValidateContactsRequest:
      type: "object"
      properties:
        contacts:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
          description: "CSV-derived contact payloads; each must include a phone number."
        segmentationConfig:
          type: "object"
          additionalProperties: true
          description: "Optional segmentation config (enabled, contactDistribution, etc.)."
        assignmentConfig:
          type: "object"
          additionalProperties: true
          description: "Optional assignment config (isAssignmentEnabled, assignmentType, selectedUsers, segmentAssignments)."
      required:
        - "contacts"
      additionalProperties: true
      example:
        contacts:
          -
            firstName: "Jamie"
            phoneNumber: "+14155550133"
          -
            firstName: "Casey"
            phoneNumber: "+14155550144"
        segmentationConfig:
          enabled: false
        assignmentConfig:
          isAssignmentEnabled: false
    ContactValidationResult:
      type: "object"
      description: "Buckets each input contact falls into based on phone matching, ownership, message history, assignee status, and the org's contact protection period."
      properties:
        newContacts:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
        existingContacts:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
        assignedToOtherUsers:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
        alreadyMessagedOutbound:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
        alreadyMessagedInbound:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
        assignedToYouNotOwned:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
        protectedContacts:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
      required:
        - "newContacts"
        - "existingContacts"
        - "assignedToOtherUsers"
        - "alreadyMessagedOutbound"
        - "alreadyMessagedInbound"
        - "assignedToYouNotOwned"
        - "protectedContacts"
      additionalProperties: true
      example:
        newContacts:
          -
            firstName: "Jamie"
            phoneNumber: "+14155550133"
        existingContacts:
          -
            _id: "665f1a0c0e0a4b001a2c9f01"
            phoneNumber: "+14155550144"
        assignedToOtherUsers:
          []
        alreadyMessagedOutbound:
          []
        alreadyMessagedInbound:
          []
        assignedToYouNotOwned:
          []
        protectedContacts:
          []
    ValidateContactsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          "$ref": "#/components/schemas/ContactValidationResult"
        message:
          type: "string"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          newContacts:
            -
              firstName: "Jamie"
              phoneNumber: "+14155550133"
          existingContacts:
            []
          assignedToOtherUsers:
            []
          alreadyMessagedOutbound:
            []
          alreadyMessagedInbound:
            []
          assignedToYouNotOwned:
            []
          protectedContacts:
            []
    ValidateDateRequest:
      type: "object"
      properties:
        scheduledISO:
          type: "string"
          format: "date-time"
          description: "UTC ISO timestamp the campaign is scheduled for. The org-local date is derived from this."
        contactCount:
          type: "integer"
          minimum: 0
          description: "Number of contacts the campaign will message on the resolved date."
        excludeCampaignId:
          type: "string"
          description: "When editing an existing campaign, excludes its current reservation on this date from the quota check."
      required:
        - "scheduledISO"
        - "contactCount"
      additionalProperties: true
      example:
        scheduledISO: "2026-05-20T15:00:00.000Z"
        contactCount: 250
    ValidateDateResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        available:
          type: "boolean"
          description: "True when remaining quota >= contactCount (or when the org has unlimited quota)."
        remaining:
          type: "integer"
          nullable: true
          description: "Remaining SMS slots on the resolved date; null for unlimited plans."
        limit:
          type: "integer"
          nullable: true
          description: "Daily SMS cap for the org; null for unlimited plans."
        message:
          type: "string"
          description: "Human-readable explanation populated only when available=false."
      required:
        - "success"
        - "available"
      additionalProperties: true
      example:
        success: true
        available: true
        remaining: 250
        limit: 500
    CreateConditionalFieldRequest:
      type: "object"
      properties:
        name:
          type: "string"
          description: "Display name of the conditional field; shown in catalogs and UI."
        sectionId:
          type: "string"
          description: "Catalog section the field belongs to (e.g. `contact.identity`)."
        expression:
          type: "string"
          description: "Evaluator expression (e.g. `contact.age >= 18 && contact.country == \"US\"`). Validated against the catalog on save."
        status:
          type: "string"
          description: "Lifecycle state of the field, typically `active` or `draft`."
        outputType:
          type: "string"
          description: "Type returned by the expression: `boolean`, `string`, `number`."
        description:
          type: "string"
          description: "Free-form explanation of the field's intent; shown as helper text."
        type:
          type: "string"
          description: "Top-level scope the field applies to (e.g. `contact`, `application`)."
        sectionType:
          type: "string"
          description: "Where the field is surfaced (`contact`, `application`, etc.)."
      required:
        - "name"
        - "sectionId"
        - "expression"
      additionalProperties: true
      example:
        name: "Eligibility flag"
        sectionId: "contact.identity"
        expression: "contact.age >= 18 && contact.country == \"US\""
        status: "active"
        outputType: "boolean"
        description: "Set true when contact passes US adult eligibility checks"
        type: "contact"
        sectionType: "identity"
    UpdateConditionalFieldRequest:
      type: "object"
      properties:
        name:
          type: "string"
          description: "Display name of the conditional field; shown in catalogs and UI."
        sectionId:
          type: "string"
          description: "Catalog section the field belongs to (e.g. `contact.identity`)."
        expression:
          type: "string"
          description: "Evaluator expression (e.g. `contact.age >= 18 && contact.country == \"US\"`). Validated against the catalog on save."
        status:
          type: "string"
          description: "Lifecycle state of the field, typically `active` or `draft`."
        outputType:
          type: "string"
          description: "Type returned by the expression: `boolean`, `string`, `number`."
        description:
          type: "string"
          description: "Free-form explanation of the field's intent; shown as helper text."
        type:
          type: "string"
          description: "Top-level scope the field applies to (e.g. `contact`, `application`)."
        sectionType:
          type: "string"
          description: "Where the field is surfaced (`contact`, `application`, etc.)."
      required:
        - "name"
        - "sectionId"
        - "expression"
      additionalProperties: true
      example:
        name: "Eligibility flag"
        sectionId: "contact.identity"
        expression: "contact.age >= 21 && contact.country == \"US\""
        status: "active"
        outputType: "boolean"
    ValidateConditionalFieldRequest:
      type: "object"
      properties:
        id:
          type: "string"
          description: "Existing field `_id` when validating an edit; omitted for new fields so self-references are skipped."
        name:
          type: "string"
          description: "Display name of the conditional field; shown in catalogs and UI."
        sectionId:
          type: "string"
          description: "Catalog section the field belongs to (e.g. `contact.identity`)."
        expression:
          type: "string"
          description: "Evaluator expression (e.g. `contact.age >= 18 && contact.country == \"US\"`). Validated against the catalog on save."
        status:
          type: "string"
          description: "Lifecycle state of the field, typically `active` or `draft`."
        outputType:
          type: "string"
          description: "Type returned by the expression: `boolean`, `string`, `number`."
        description:
          type: "string"
          description: "Free-form explanation of the field's intent; shown as helper text."
        type:
          type: "string"
          description: "Top-level scope the field applies to (e.g. `contact`, `application`)."
        sectionType:
          type: "string"
          description: "Where the field is surfaced (`contact`, `application`, etc.)."
      required:
        - "name"
        - "sectionId"
        - "expression"
      additionalProperties: true
      example:
        name: "Eligibility flag"
        sectionId: "contact.identity"
        expression: "contact.age >= 18 && contact.country == \"US\""
        outputType: "boolean"
    ReorderConditionalFieldsRequest:
      type: "object"
      properties:
        order:
          type: "array"
          items:
            type: "string"
          description: "Field `_id`s in their target display order."
        type:
          type: "string"
          description: "Top-level scope being reordered (e.g. `contact`, `application`)."
        sectionType:
          type: "string"
          description: "Section where the reorder applies (`contact`, `application`, etc.)."
      required:
        - "order"
      additionalProperties: true
      example:
        order:
          - "66d0a0b0c0d0e0f0a0b0c0d0"
          - "66d0a0b0c0d0e0f0a0b0c0d1"
        type: "contact"
        sectionType: "identity"
    ConditionalFieldListResponse:
      type: "object"
      properties:
        data:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
      additionalProperties: true
      example:
        data:
          -
            _id: "66d0a0b0c0d0e0f0a0b0c0d0"
            name: "Eligibility flag"
            sectionId: "contact.identity"
            expression: "contact.age >= 18 && contact.country == \"US\""
            status: "active"
            outputType: "boolean"
    ConditionalFieldCatalogResponse:
      type: "object"
      properties:
        sections:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
        fields:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
      additionalProperties: true
      example:
        sections:
          -
            id: "contact.identity"
            name: "Identity"
        fields:
          -
            id: "contact.age"
            sectionId: "contact.identity"
            type: "number"
          -
            id: "contact.country"
            sectionId: "contact.identity"
            type: "string"
    ConditionalFieldResponse:
      type: "object"
      additionalProperties: true
      example:
        _id: "66d0a0b0c0d0e0f0a0b0c0d0"
        name: "Eligibility flag"
        sectionId: "contact.identity"
        expression: "contact.age >= 18 && contact.country == \"US\""
        status: "active"
        outputType: "boolean"
    ConditionalFieldErrorResponse:
      type: "object"
      description: "Error envelope returned by conditional-field endpoints. Mirrors `handleError` in the controller: `error` carries the human-readable message and `diagnostics` is set on validation failures."
      properties:
        error:
          type: "string"
        diagnostics:
          type: "object"
          additionalProperties: true
      required:
        - "error"
      additionalProperties: true
      example:
        error: "Expression validation failed"
        diagnostics:
          issues:
            -
              message: "Unknown field `contact.country2`"
              line: 1
              column: 22
    ContactAnalyticsErrorResponse:
      type: "object"
      description: "Error envelope returned by contact-analytics endpoints. Errors are returned as `{ error: <message> }`."
      properties:
        error:
          type: "string"
      additionalProperties: true
      example:
        error: "Contact not found"
    ContactAnalyticsEngagement:
      type: "object"
      properties:
        score:
          type: "integer"
          description: "0-100 engagement score (recency + activity vs baseline)."
        trend:
          type: "string"
          enum:
            - "warming"
            - "cooling"
            - "stable"
        label:
          type: "string"
          enum:
            - "Active"
            - "Moderate"
            - "Inactive"
        daysSinceLastInteraction:
          type: "integer"
          nullable: true
        baselinePerMonth:
          type: "number"
        recentInteractions:
          type: "integer"
        callsLast30d:
          type: "integer"
        messagesLast30d:
          type: "object"
          properties:
            inbound:
              type: "integer"
            outbound:
              type: "integer"
          additionalProperties: true
        messagesLast7d:
          type: "object"
          properties:
            inbound:
              type: "integer"
            outbound:
              type: "integer"
          additionalProperties: true
      additionalProperties: true
      example:
        score: 72
        trend: "warming"
        label: "Active"
        daysSinceLastInteraction: 2
        baselinePerMonth: 8.5
        recentInteractions: 14
        callsLast30d: 3
        messagesLast30d:
          inbound: 7
          outbound: 11
        messagesLast7d:
          inbound: 2
          outbound: 3
    ContactAnalyticsStageHistoryEntry:
      type: "object"
      properties:
        fromStage:
          type: "string"
        toStage:
          type: "string"
        enteredAt:
          type: "string"
          format: "date-time"
        exitedAt:
          type: "string"
          format: "date-time"
          nullable: true
        daysInStage:
          type: "integer"
        pipelineId:
          type: "string"
          nullable: true
      additionalProperties: true
      example:
        fromStage: "new"
        toStage: "qualified"
        enteredAt: "2026-04-05T10:00:00.000Z"
        exitedAt: "2026-04-12T15:30:00.000Z"
        daysInStage: 7
        pipelineId: "66f0a0b0c0d0e0f0a0b0c0d0"
    ContactAnalyticsPipeline:
      type: "object"
      properties:
        currentStage:
          type: "string"
          nullable: true
        currentPipelineId:
          type: "string"
          nullable: true
        daysInCurrentStage:
          type: "integer"
          nullable: true
        stageHistory:
          type: "array"
          items:
            "$ref": "#/components/schemas/ContactAnalyticsStageHistoryEntry"
      additionalProperties: true
      example:
        currentStage: "qualified"
        currentPipelineId: "66f0a0b0c0d0e0f0a0b0c0d0"
        daysInCurrentStage: 4
        stageHistory:
          -
            fromStage: "new"
            toStage: "qualified"
            enteredAt: "2026-04-05T10:00:00.000Z"
            exitedAt: "2026-04-12T15:30:00.000Z"
            daysInStage: 7
    ContactAnalyticsCalls:
      type: "object"
      properties:
        total:
          type: "integer"
        answered:
          type: "integer"
        unanswered:
          type: "integer"
        answerRate:
          type: "number"
          description: "0..1 fraction."
        totalDurationSeconds:
          type: "integer"
        avgDurationSeconds:
          type: "integer"
        inbound:
          type: "integer"
        outbound:
          type: "integer"
        answeredByHuman:
          type: "integer"
        answeredByMachine:
          type: "integer"
        peakReachabilityHour:
          type: "integer"
          nullable: true
          description: "0..23 hour of day with the most completed calls."
      additionalProperties: true
      example:
        total: 8
        answered: 5
        unanswered: 3
        answerRate: 0.625
        totalDurationSeconds: 1240
        avgDurationSeconds: 248
        inbound: 2
        outbound: 6
        answeredByHuman: 4
        answeredByMachine: 1
        peakReachabilityHour: 14
    ContactAnalyticsConversations:
      type: "object"
      properties:
        total:
          type: "integer"
        resolved:
          type: "integer"
        resolutionRate:
          type: "number"
          description: "0..1 fraction."
        avgResolutionHours:
          type: "number"
          nullable: true
        csatAverage:
          type: "number"
          nullable: true
        csatCount:
          type: "integer"
        autopilotHandled:
          type: "integer"
      additionalProperties: true
      example:
        total: 4
        resolved: 3
        resolutionRate: 0.75
        avgResolutionHours: 18.4
        csatAverage: 4.6
        csatCount: 2
        autopilotHandled: 2
    ContactAnalyticsChannels:
      type: "object"
      properties:
        preferred:
          type: "string"
          nullable: true
        ranked:
          type: "array"
          items:
            type: "string"
        breakdown:
          type: "object"
          description: "Channel → weighted-inbound count."
          additionalProperties:
            type: "integer"
      additionalProperties: true
      example:
        preferred: "sms"
        ranked:
          - "sms"
          - "email"
          - "webchat"
        breakdown:
          sms: 12
          email: 4
          webchat: 1
    ContactAnalyticsAiVsHuman:
      type: "object"
      properties:
        breakdown:
          type: "object"
          description: "Sender type → message count. Senders are normalised: `CONTACT` is reported as `HUMAN`."
          additionalProperties:
            type: "integer"
        escalationCount:
          type: "integer"
      additionalProperties: true
      example:
        breakdown:
          AI: 9
          HUMAN: 7
          SYSTEM: 1
        escalationCount: 1
    ContactAnalyticsTimelineEvent:
      type: "object"
      description: "Polymorphic timeline event. `type` discriminates the shape."
      properties:
        _id:
          type: "string"
        type:
          type: "string"
          enum:
            - "message"
            - "call"
            - "note"
            - "stage_change"
        createdAt:
          type: "string"
          format: "date-time"
        direction:
          type: "string"
          enum:
            - "inbound"
            - "outbound"
          description: "message/call only."
        channelType:
          type: "string"
          description: "message only."
        senderType:
          type: "string"
          description: "message only."
        preview:
          type: "string"
          nullable: true
          description: "message/note only - first 100 chars."
        status:
          type: "string"
          description: "call only."
        duration:
          type: "integer"
          description: "call only - seconds."
        fromStage:
          type: "string"
          description: "stage_change only."
        toStage:
          type: "string"
          description: "stage_change only."
      additionalProperties: true
      example:
        _id: "67a0a0b0c0d0e0f0a0b0c0d0"
        type: "message"
        createdAt: "2026-05-18T13:45:00.000Z"
        direction: "inbound"
        channelType: "sms"
        senderType: "HUMAN"
        preview: "Yes please, let's book the demo."
    ContactAnalyticsTimeline:
      type: "object"
      properties:
        total:
          type: "integer"
        page:
          type: "integer"
        limit:
          type: "integer"
        totalPages:
          type: "integer"
        events:
          type: "array"
          items:
            "$ref": "#/components/schemas/ContactAnalyticsTimelineEvent"
      additionalProperties: true
      example:
        total: 47
        page: 1
        limit: 25
        totalPages: 2
        events:
          -
            _id: "67a0a0b0c0d0e0f0a0b0c0d0"
            type: "message"
            createdAt: "2026-05-18T13:45:00.000Z"
            direction: "inbound"
            channelType: "sms"
            senderType: "HUMAN"
            preview: "Yes please, let's book the demo."
    ContactAnalyticsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            engagement:
              "$ref": "#/components/schemas/ContactAnalyticsEngagement"
            pipeline:
              "$ref": "#/components/schemas/ContactAnalyticsPipeline"
            calls:
              "$ref": "#/components/schemas/ContactAnalyticsCalls"
            conversations:
              "$ref": "#/components/schemas/ContactAnalyticsConversations"
            channels:
              "$ref": "#/components/schemas/ContactAnalyticsChannels"
            aiVsHuman:
              "$ref": "#/components/schemas/ContactAnalyticsAiVsHuman"
            timeline:
              "$ref": "#/components/schemas/ContactAnalyticsTimeline"
          required:
            - "engagement"
            - "pipeline"
            - "calls"
            - "conversations"
            - "channels"
            - "aiVsHuman"
            - "timeline"
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          engagement:
            score: 72
            trend: "warming"
            label: "Active"
            daysSinceLastInteraction: 2
          pipeline:
            currentStage: "qualified"
            daysInCurrentStage: 4
            stageHistory:
              []
          calls:
            total: 8
            answered: 5
            unanswered: 3
            answerRate: 0.625
          conversations:
            total: 4
            resolved: 3
            resolutionRate: 0.75
            csatAverage: 4.6
          channels:
            preferred: "sms"
            ranked:
              - "sms"
              - "email"
            breakdown:
              sms: 12
              email: 4
          aiVsHuman:
            breakdown:
              AI: 9
              HUMAN: 7
            escalationCount: 1
          timeline:
            total: 47
            page: 1
            limit: 25
            totalPages: 2
            events:
              []
    UpdateMetricsConfigRequest:
      type: "object"
      properties:
        categories:
          type: "array"
          items:
            type: "object"
            properties:
              name:
                type: "string"
              key:
                type: "string"
              statuses:
                type: "array"
                items:
                  type: "string"
              color:
                type: "string"
            required:
              - "name"
              - "key"
              - "statuses"
            additionalProperties: true
          description: "Category definitions used to bucket contacts on the analytics dashboard."
        allowMultipleCategories:
          type: "boolean"
          description: "When true, a contact can fall under more than one category at the same time."
        pipelineId:
          type: "string"
          description: "Pipeline `_id` the categories apply to."
      required:
        - "categories"
      additionalProperties: true
      example:
        categories:
          -
            name: "New"
            key: "new"
            statuses:
              - "new"
            color: "#3B82F6"
          -
            name: "Working"
            key: "working"
            statuses:
              - "qualified"
              - "in-progress"
            color: "#10B981"
          -
            name: "Closed"
            key: "closed"
            statuses:
              - "won"
              - "lost"
            color: "#6B7280"
        allowMultipleCategories: false
    ContactMetricsErrorResponse:
      type: "object"
      description: "Error envelope returned by contact-metrics endpoints. Errors are returned as `{ error: <message> }`."
      properties:
        error:
          type: "string"
      additionalProperties: true
      example:
        error: "Invalid pipeline ID"
    ContactMetricsCategoryConfig:
      type: "object"
      description: "A single category entry in `Organization.contactMetricsConfig.categories`."
      properties:
        name:
          type: "string"
        key:
          type: "string"
        statuses:
          type: "array"
          items:
            type: "string"
        color:
          type: "string"
        pipelineId:
          type: "string"
          nullable: true
      additionalProperties: true
      example:
        name: "Working"
        key: "working"
        statuses:
          - "qualified"
          - "in-progress"
        color: "#10B981"
        pipelineId: "66f0a0b0c0d0e0f0a0b0c0d0"
    ContactMetricsCategoryBucket:
      type: "object"
      description: "Per-category counts in the summary response."
      properties:
        name:
          type: "string"
        count:
          type: "integer"
        contacted:
          type: "integer"
        neverContacted:
          type: "integer"
        color:
          type: "string"
      additionalProperties: true
      example:
        name: "Working"
        count: 47
        contacted: 38
        neverContacted: 9
        color: "#10B981"
    ContactMetricsUncategorizedBucket:
      type: "object"
      properties:
        count:
          type: "integer"
        contacted:
          type: "integer"
        neverContacted:
          type: "integer"
      additionalProperties: true
      example:
        count: 12
        contacted: 4
        neverContacted: 8
    ContactMetricsSummaryResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            scope:
              type: "string"
              description: "Frontend label: \"All Organization\" | \"Department Contacts\" | \"Your Contacts\"."
            total:
              type: "integer"
            contacted:
              type: "integer"
            neverContacted:
              type: "integer"
            categories:
              type: "object"
              description: "Keyed by category `key`."
              additionalProperties:
                "$ref": "#/components/schemas/ContactMetricsCategoryBucket"
            uncategorized:
              "$ref": "#/components/schemas/ContactMetricsUncategorizedBucket"
            pipelineId:
              type: "string"
              nullable: true
            pipelineName:
              type: "string"
              nullable: true
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          scope: "Your Contacts"
          total: 124
          contacted: 91
          neverContacted: 33
          categories:
            new:
              name: "New"
              count: 22
              contacted: 0
              neverContacted: 22
              color: "#3B82F6"
            working:
              name: "Working"
              count: 47
              contacted: 38
              neverContacted: 9
              color: "#10B981"
            closed:
              name: "Closed"
              count: 43
              contacted: 43
              neverContacted: 0
              color: "#6B7280"
          uncategorized:
            count: 12
            contacted: 10
            neverContacted: 2
          pipelineId: "66f0a0b0c0d0e0f0a0b0c0d0"
          pipelineName: "Sales pipeline"
    ContactMetricsConfigResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            categories:
              type: "array"
              items:
                "$ref": "#/components/schemas/ContactMetricsCategoryConfig"
            allowMultipleCategories:
              type: "boolean"
            defaultMetricsPipelineId:
              type: "string"
              nullable: true
            pipelineId:
              type: "string"
              nullable: true
              description: "Set when GET is called with ?pipelineId=."
            pipelineName:
              type: "string"
              nullable: true
              description: "Set when GET is called with ?pipelineId=."
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          categories:
            -
              name: "New"
              key: "new"
              statuses:
                - "new"
              color: "#3B82F6"
            -
              name: "Working"
              key: "working"
              statuses:
                - "qualified"
                - "in-progress"
              color: "#10B981"
          allowMultipleCategories: false
          defaultMetricsPipelineId: "66f0a0b0c0d0e0f0a0b0c0d0"
          pipelineId: "66f0a0b0c0d0e0f0a0b0c0d0"
          pipelineName: "Sales pipeline"
    ContactMetricsConfigUpdateResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          description: "Updated `Organization.contactMetricsConfig` document."
          properties:
            categories:
              type: "array"
              items:
                "$ref": "#/components/schemas/ContactMetricsCategoryConfig"
            allowMultipleCategories:
              type: "boolean"
            defaultMetricsPipelineId:
              type: "string"
              nullable: true
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          categories:
            -
              name: "New"
              key: "new"
              statuses:
                - "new"
              color: "#3B82F6"
            -
              name: "Working"
              key: "working"
              statuses:
                - "qualified"
                - "in-progress"
              color: "#10B981"
          allowMultipleCategories: false
          defaultMetricsPipelineId: "66f0a0b0c0d0e0f0a0b0c0d0"
    ContactMetricsContactItem:
      type: "object"
      description: "Projected contact row returned by the contacts-by-category aggregation."
      properties:
        _id:
          type: "string"
        firstName:
          type: "string"
          nullable: true
        lastName:
          type: "string"
          nullable: true
        phoneNumber:
          nullable: true
          oneOf:
            -
              type: "string"
            -
              type: "array"
              items:
                type: "object"
                additionalProperties: true
        email:
          type: "string"
          nullable: true
        status:
          type: "string"
          nullable: true
        createdAt:
          type: "string"
          format: "date-time"
        lastMessageTime:
          type: "string"
          format: "date-time"
          nullable: true
        hasOutbound:
          type: "boolean"
        channelTypes:
          type: "array"
          items:
            type: "string"
        createdByUser:
          type: "object"
          nullable: true
          properties:
            _id:
              type: "string"
            fullName:
              type: "string"
          additionalProperties: true
      additionalProperties: true
      example:
        _id: "65c2d0e0f0a0b0c0d0e0f0a0"
        firstName: "Jane"
        lastName: "Doe"
        phoneNumber: "+14155550123"
        email: "jane@example.com"
        status: "qualified"
        createdAt: "2026-04-12T08:00:00.000Z"
        lastMessageTime: "2026-05-18T13:45:00.000Z"
        hasOutbound: true
        channelTypes:
          - "sms"
          - "email"
        createdByUser:
          _id: "65b1f0a2c3d4e5f6a7b8c9d0"
          fullName: "Alice Rivera"
    ContactsByCategoryResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            contacts:
              type: "array"
              items:
                "$ref": "#/components/schemas/ContactMetricsContactItem"
            total:
              type: "integer"
            page:
              type: "integer"
            limit:
              type: "integer"
            totalPages:
              type: "integer"
          required:
            - "contacts"
            - "total"
            - "page"
            - "limit"
            - "totalPages"
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          contacts:
            -
              _id: "65c2d0e0f0a0b0c0d0e0f0a0"
              firstName: "Jane"
              lastName: "Doe"
              phoneNumber: "+14155550123"
              status: "qualified"
              createdAt: "2026-04-12T08:00:00.000Z"
              hasOutbound: true
              channelTypes:
                - "sms"
          total: 47
          page: 1
          limit: 25
          totalPages: 2
    ContactMetricsUserCategoryBucket:
      type: "object"
      properties:
        total:
          type: "integer"
        contacted:
          type: "integer"
        neverContacted:
          type: "integer"
      additionalProperties: true
      example:
        total: 22
        contacted: 14
        neverContacted: 8
    ContactMetricsUserRow:
      type: "object"
      properties:
        userId:
          type: "string"
          nullable: true
        userName:
          type: "string"
        userEmail:
          type: "string"
          nullable: true
        total:
          type: "integer"
        contacted:
          type: "integer"
        neverContacted:
          type: "integer"
        categories:
          type: "object"
          description: "Keyed by category `key`."
          additionalProperties:
            "$ref": "#/components/schemas/ContactMetricsUserCategoryBucket"
        uncategorized:
          "$ref": "#/components/schemas/ContactMetricsUserCategoryBucket"
      additionalProperties: true
      example:
        userId: "65b1f0a2c3d4e5f6a7b8c9d0"
        userName: "Alice Rivera"
        userEmail: "alice@example.com"
        total: 47
        contacted: 38
        neverContacted: 9
        categories:
          new:
            total: 22
            contacted: 0
            neverContacted: 22
          working:
            total: 25
            contacted: 25
            neverContacted: 0
        uncategorized:
          total: 0
          contacted: 0
          neverContacted: 0
    ContactMetricsByUserResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            users:
              type: "array"
              items:
                "$ref": "#/components/schemas/ContactMetricsUserRow"
            categories:
              type: "array"
              items:
                type: "object"
                properties:
                  key:
                    type: "string"
                  name:
                    type: "string"
                  color:
                    type: "string"
                additionalProperties: true
            pipelineId:
              type: "string"
              nullable: true
            pipelineName:
              type: "string"
              nullable: true
          required:
            - "users"
            - "categories"
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          users:
            -
              userId: "65b1f0a2c3d4e5f6a7b8c9d0"
              userName: "Alice Rivera"
              userEmail: "alice@example.com"
              total: 47
              contacted: 38
              neverContacted: 9
              categories:
                new:
                  total: 22
                  contacted: 0
                  neverContacted: 22
                working:
                  total: 25
                  contacted: 25
                  neverContacted: 0
              uncategorized:
                total: 0
                contacted: 0
                neverContacted: 0
          categories:
            -
              key: "new"
              name: "New"
              color: "#3B82F6"
            -
              key: "working"
              name: "Working"
              color: "#10B981"
          pipelineId: "66f0a0b0c0d0e0f0a0b0c0d0"
          pipelineName: "Sales pipeline"
    CreateContactNoteRequest:
      type: "object"
      properties:
        contactId:
          type: "string"
          description: "Contact `_id` the note is attached to."
        note:
          type: "string"
          description: "Markdown/plain-text body of the note; may contain `@`-mention syntax."
        mentions:
          type: "array"
          items:
            type: "string"
          description: "User `_id`s @-mentioned in the note; trigger notification pings."
        attachments:
          type: "array"
          items:
            type: "object"
            properties:
              key:
                type: "string"
              name:
                type: "string"
              size:
                type: "number"
              type:
                type: "string"
            required:
              - "key"
            additionalProperties: true
          description: "R2 storage keys + content metadata for files attached to the note."
      required:
        - "contactId"
      additionalProperties: true
      example:
        contactId: "65c2d0e0f0a0b0c0d0e0f0a0"
        note: "@alice please review the W2 attached."
        mentions:
          - "65b1f0a2c3d4e5f6a7b8c9d0"
        attachments:
          -
            key: "orgs/65a0.../notes/w2.pdf"
            name: "w2.pdf"
            size: 121200
            type: "application/pdf"
    UpdateContactNoteRequest:
      type: "object"
      properties:
        note:
          type: "string"
          description: "Replacement body for the note; flips `isEdited` to true on save."
        mentions:
          type: "array"
          items:
            type: "string"
          description: "User `_id`s @-mentioned in the note; trigger notification pings."
        attachments:
          type: "array"
          items:
            type: "object"
            properties:
              key:
                type: "string"
              name:
                type: "string"
              size:
                type: "number"
              type:
                type: "string"
            required:
              - "key"
            additionalProperties: true
          description: "R2 storage keys + content metadata for files attached to the note; replaces the existing attachment list."
      additionalProperties: true
      example:
        note: "@alice please review the W2 attached. Updated copy."
    ToggleReactionRequest:
      type: "object"
      properties:
        emoji:
          type: "string"
          description: "Unicode emoji character; first toggle adds the reaction, second toggle removes it."
      required:
        - "emoji"
      additionalProperties: true
      example:
        emoji: "👍"
    ContactNotesErrorResponse:
      type: "object"
      description: "Error envelope returned by contact-notes endpoints. May include `error` (raw exception message) on 500 paths."
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
        error:
          type: "string"
      additionalProperties: true
      example:
        success: false
        message: "Contact note not found"
        error: "NOT_FOUND"
    ContactNoteAttachment:
      type: "object"
      description: "Attachment row. Stored items carry `key`; list responses replace `key` with a short-lived `signedUrl`."
      properties:
        key:
          type: "string"
        name:
          type: "string"
        size:
          type: "number"
        type:
          type: "string"
        signedUrl:
          type: "string"
          format: "uri"
          description: "Present only on GET list responses."
      additionalProperties: true
      example:
        name: "w2.pdf"
        size: 121200
        type: "application/pdf"
        signedUrl: "https://r2.example.com/orgs/65a0.../notes/w2.pdf?token=..."
    ContactNoteReaction:
      type: "object"
      properties:
        emoji:
          type: "string"
        users:
          type: "array"
          items:
            type: "string"
        count:
          type: "integer"
      required:
        - "emoji"
        - "users"
        - "count"
      additionalProperties: true
      example:
        emoji: "👍"
        users:
          - "65b1f0a2c3d4e5f6a7b8c9d0"
          - "65b1f0a2c3d4e5f6a7b8c9d1"
        count: 2
    ContactNoteAuthor:
      type: "object"
      nullable: true
      properties:
        _id:
          type: "string"
        fullName:
          type: "string"
        email:
          type: "string"
        avatarUrl:
          type: "string"
          nullable: true
      additionalProperties: true
      example:
        _id: "65b1f0a2c3d4e5f6a7b8c9d3"
        fullName: "Cory Tan"
        email: "cory@example.com"
        avatarUrl: "https://cdn.example.com/avatars/cory.png"
    ContactNoteItem:
      type: "object"
      description: "Populated note row. `userId` is populated to the user document (see ContactNoteAuthor) for notes a person wrote. Notes an AI agent wrote (call summaries, notes taken during an AI call) have no `userId`; `createdBy` then names the agent (`type: \"ai\"`, `label` = the agent persona or agent name). Org admins (ADMIN, SUPERADMIN) can edit and delete AI-written notes; every other note can only be edited or deleted by its author."
      properties:
        _id:
          type: "string"
        userId:
          allOf:
            -
              "$ref": "#/components/schemas/ContactNoteAuthor"
          description: "The person who wrote the note, populated. Absent or null for notes an AI agent wrote."
        createdBy:
          type: "object"
          nullable: true
          description: "Who or what wrote the note: a user (userId), an AI agent (promptId + label snapshot taken when the note was written), an automation or workflow run (automationId/workflowId + executionId), or the system. Older notes may not have it."
          properties:
            type:
              type: "string"
              enum:
                - "user"
                - "ai"
                - "automation"
                - "workflow"
                - "system"
            userId:
              type: "string"
            promptId:
              type: "string"
            automationId:
              type: "string"
            workflowId:
              type: "string"
            executionId:
              type: "string"
            label:
              type: "string"
          required:
            - "type"
          example:
            type: "ai"
            promptId: "65b1f0a2c3d4e5f6a7b8c9e1"
            label: "Riley"
        note:
          type: "string"
        attachments:
          type: "array"
          items:
            "$ref": "#/components/schemas/ContactNoteAttachment"
        reactions:
          type: "array"
          items:
            "$ref": "#/components/schemas/ContactNoteReaction"
        isEdited:
          type: "boolean"
        createdAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "67f0a0b0c0d0e0f0a0b0c0d0"
        userId:
          _id: "65b1f0a2c3d4e5f6a7b8c9d3"
          fullName: "Cory Tan"
          email: "cory@example.com"
        note: "@alice please review the W2 attached."
        attachments:
          -
            name: "w2.pdf"
            size: 121200
            type: "application/pdf"
            signedUrl: "https://r2.example.com/orgs/65a0.../notes/w2.pdf?token=..."
        reactions:
          -
            emoji: "👍"
            users:
              - "65b1f0a2c3d4e5f6a7b8c9d0"
            count: 1
        isEdited: false
        createdAt: "2026-05-18T14:00:00.000Z"
    ContactNotesListResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/ContactNoteItem"
        pagination:
          type: "object"
          properties:
            total:
              type: "integer"
            limit:
              type: "integer"
            offset:
              type: "integer"
            hasMore:
              type: "boolean"
          required:
            - "total"
            - "limit"
            - "offset"
            - "hasMore"
          additionalProperties: true
      required:
        - "success"
        - "data"
        - "pagination"
      additionalProperties: true
      example:
        success: true
        data:
          -
            _id: "67f0a0b0c0d0e0f0a0b0c0d0"
            userId:
              _id: "65b1f0a2c3d4e5f6a7b8c9d3"
              fullName: "Cory Tan"
              email: "cory@example.com"
            note: "Spoke briefly; will follow up tomorrow."
            attachments:
              []
            reactions:
              []
            isEdited: false
            createdAt: "2026-05-18T14:00:00.000Z"
        pagination:
          total: 1
          limit: 25
          offset: 0
          hasMore: false
    ContactNoteMutationResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        data:
          "$ref": "#/components/schemas/ContactNoteItem"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        message: "Contact note created"
        data:
          _id: "67f0a0b0c0d0e0f0a0b0c0d0"
          userId:
            _id: "65b1f0a2c3d4e5f6a7b8c9d3"
            fullName: "Cory Tan"
            email: "cory@example.com"
          note: "Spoke briefly; will follow up tomorrow."
          attachments:
            []
          reactions:
            []
          isEdited: false
          createdAt: "2026-05-18T14:00:00.000Z"
    ContactNoteDeleteResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
      required:
        - "success"
      additionalProperties: true
      example:
        success: true
        message: "Contact note deleted"
    ContactPhoneNumber:
      type: "object"
      properties:
        value:
          type: "string"
        isPrimary:
          type: "boolean"
      required:
        - "value"
      additionalProperties: true
      example:
        value: "+14165550100"
        isPrimary: true
    ContactEmail:
      type: "object"
      properties:
        value:
          type: "string"
          format: "email"
        isPrimary:
          type: "boolean"
      required:
        - "value"
      additionalProperties: false
      example:
        value: "jane.doe@example.com"
        isPrimary: true
    ContactDto:
      type: "object"
      properties:
        _id:
          type: "string"
        firstName:
          type: "string"
          nullable: true
        lastName:
          type: "string"
          nullable: true
        phoneNumber:
          nullable: true
          oneOf:
            -
              type: "string"
            -
              type: "array"
              items:
                "$ref": "#/components/schemas/ContactPhoneNumber"
        conflictingPhoneNumbers:
          type: "array"
          nullable: true
          items:
            type: "string"
        email:
          type: "string"
          nullable: true
        status:
          type: "string"
          nullable: true
        pipelineId:
          type: "string"
          nullable: true
        pipelineStage:
          type: "string"
          nullable: true
        organizationId:
          type: "string"
          nullable: true
        userId:
          type: "string"
          nullable: true
        createdBy:
          type: "object"
          nullable: true
          description: "Who or what created the record: a user (userId, populated with fullName on reads), an AI agent (promptId), an automation or workflow run (automationId/workflowId + executionId), or the system."
          properties:
            type:
              type: "string"
              enum:
                - "user"
                - "ai"
                - "automation"
                - "workflow"
                - "system"
            userId:
              {}
            promptId:
              type: "string"
            automationId:
              type: "string"
            workflowId:
              type: "string"
            executionId:
              type: "string"
            label:
              type: "string"
          required:
            - "type"
        assignees:
          type: "array"
          items:
            {}
        createdAt:
          type: "string"
          nullable: true
          format: "date-time"
        updatedAt:
          type: "string"
          nullable: true
          format: "date-time"
        existingConversationId:
          type: "string"
          nullable: true
          description: "Set on responses from /api/contacts/inactive when called with includeExisting=true. Identifies the caller-accessible conversation in the requested channel; clients should route to this conversation instead of creating a new one."
      additionalProperties: true
      example:
        _id: "64f0a1b2c3d4e5f6a7b8c9d0"
        firstName: "Jane"
        lastName: "Doe"
        phoneNumber:
          -
            value: "+14165550100"
            isPrimary: true
        conflictingPhoneNumbers:
          []
        email: "jane.doe@example.com"
        status: "New Lead"
        pipelineId: "64f0a1b2c3d4e5f6a7b8c9d1"
        pipelineStage: "64f0a1b2c3d4e5f6a7b8c9d2"
        organizationId: "64f0a1b2c3d4e5f6a7b8c9d3"
        userId: "64f0a1b2c3d4e5f6a7b8c9d4"
        createdBy:
          type: "user"
          userId: "64f0a1b2c3d4e5f6a7b8c9d4"
        assignees:
          - "64f0a1b2c3d4e5f6a7b8c9d4"
        createdAt: "2026-05-01T14:30:00.000Z"
        updatedAt: "2026-05-15T09:12:00.000Z"
    ApiErrorEnvelope:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
        error:
          type: "object"
          properties:
            code:
              type: "string"
            message:
              type: "string"
            details:
              {}
          required:
            - "message"
          additionalProperties: true
      required:
        - "success"
        - "error"
      additionalProperties: true
      example:
        success: false
        message: "Contact not found"
        error:
          code: "NOT_FOUND"
          message: "Contact not found"
    LegacyErrorResponse:
      type: "object"
      properties:
        error:
          type: "string"
        message:
          type: "string"
        data:
          {}
      additionalProperties: true
      example:
        error: "Attachment not found"
        message: "Attachment not found"
    MessageResponse:
      type: "object"
      properties:
        message:
          type: "string"
        data:
          {}
      additionalProperties: true
      example:
        message: "Conversation deleted"
    GenericObjectResponse:
      type: "object"
      additionalProperties: true
      example:
        success: true
        message: "Excess data mapped successfully"
    AddContactRequest:
      type: "object"
      description: "At least one of `phoneNumber` or `email` is required; all other fields are optional."
      properties:
        firstName:
          type: "string"
          description: "Contact first name; optional."
        lastName:
          type: "string"
          description: "Contact last name; optional."
        phoneNumber:
          type: "array"
          items:
            "$ref": "#/components/schemas/ContactPhoneNumber"
          description: "One or more phone-number entries; each `value` is normalized to E.164 server-side and must be unique within the organization."
        email:
          oneOf:
            -
              type: "string"
              format: "email"
            -
              type: "array"
              items:
                "$ref": "#/components/schemas/ContactEmail"
          description: "A single email string or one or more email entries; normalized server-side and unique within the organization."
        process:
          type: "string"
          description: "Optional process/workflow tag carried through to the created contact."
        status:
          type: "string"
          description: "Initial pipeline status name (e.g. `New Lead`). Defaults to the pipeline's first stage when omitted."
        pipelineStage:
          type: "string"
          description: "Stage `_id` within the pipeline. Resolved together with `status` server-side."
        pipelineId:
          type: "string"
          description: "Target Contact pipeline `_id`. Defaults to the org's active Contact pipeline when omitted."
      additionalProperties: true
      example:
        firstName: "Jane"
        lastName: "Doe"
        phoneNumber:
          -
            value: "+14165550100"
            isPrimary: true
        email: "jane.doe@example.com"
        status: "New Lead"
        pipelineId: "64f0a1b2c3d4e5f6a7b8c9d1"
    UpdateContactRequest:
      type: "object"
      properties:
        _id:
          type: "string"
          description: "Target contact `_id`; required to locate the document."
        fromHistoryModal:
          type: "boolean"
          description: "Suppresses side-effects (audit log, socket emit) when the update originates from the history viewer."
        status:
          type: "string"
          description: "New pipeline status name; resolved together with `pipelineStage`."
        pipelineStage:
          type: "string"
          nullable: true
          description: "Stage `_id`. Set to `null` to clear the stage assignment (legacy status-only update)."
        pipelineId:
          type: "string"
          description: "Optional pipeline `_id` used to scope stage resolution; inferred from the resolved stage when omitted."
      required:
        - "_id"
      additionalProperties: true
      example:
        _id: "64f0a1b2c3d4e5f6a7b8c9d0"
        status: "Qualified"
        pipelineStage: "64f0a1b2c3d4e5f6a7b8c9d2"
        pipelineId: "64f0a1b2c3d4e5f6a7b8c9d1"
    PatchContactRequest:
      type: "object"
      properties:
        status:
          type: "string"
          description: "New pipeline status name; resolved alongside `pipelineStage` and recorded as a pipeline transition."
        pipelineStage:
          type: "string"
          nullable: true
          description: "Stage `_id`. `null` clears the stage; legacy status updates without a resolvable stage fall back to null."
        pipelineId:
          type: "string"
          description: "Optional pipeline `_id` scoping stage/status resolution."
        phoneNumber:
          type: "array"
          items:
            "$ref": "#/components/schemas/ContactPhoneNumber"
          description: "Replacement phone-number list; normalized to E.164 and rejected if any value is a provisioned org SMS number."
      additionalProperties: true
      example:
        status: "Qualified"
        pipelineStage: "64f0a1b2c3d4e5f6a7b8c9d2"
    MarkMessageSeenRequest:
      type: "object"
      properties:
        conversationId:
          type: "string"
          description: "Conversation `_id` to mark as seen; clears its `isUpdated` flag and recomputes the parent contact's unread state."
      required:
        - "conversationId"
      additionalProperties: false
      example:
        conversationId: "64f0a1b2c3d4e5f6a7b8c9e0"
    MapExcessDataRequest:
      type: "object"
      properties:
        sourceText:
          type: "string"
          description: "Raw lead text the AI mapper should re-parse into structured contact fields."
        existingSchema:
          type: "object"
          additionalProperties: true
          description: "Field definitions describing the target schema the mapper should populate."
        mappedData:
          type: "object"
          additionalProperties: true
          description: "Already-mapped first-class fields; the server protects these from being overwritten when re-mapping."
        excessData:
          type: "object"
          additionalProperties: true
          description: "Previously-unmapped key/value pairs (from `misc`) to re-evaluate for promotion to first-class fields."
      additionalProperties: true
      example:
        sourceText: "Jane Doe, +1-416-555-0100, jane@example.com, lead from referral"
        existingSchema:
          firstName:
            type: "string"
          email:
            type: "string"
          phoneNumber:
            type: "string"
        mappedData:
          firstName: "Jane"
          email: "jane@example.com"
          phoneNumber: "+14165550100"
        excessData:
          note: "lead from referral"
    GetContactsPerStatusRequest:
      type: "object"
      properties:
        page:
          type: "object"
          additionalProperties:
            type: "integer"
          description: "Per-stage page numbers keyed by stage id or stage name (e.g. `{ \"New Lead\": 2 }`)."
        size:
          type: "integer"
          description: "Page size applied to every stage query."
        search:
          type: "string"
          description: "Case-insensitive substring match across first/last name, full name, and phone-number value."
        source:
          type: "string"
          description: "Filter to contacts whose `source` equals this value (Contacts pipeline only)."
        ownerFilter:
          type: "string"
          description: "Quick-tab owner scope: `my`, `all`, `team`, `unassigned`, or a specific user `_id`."
        owner:
          type: "array"
          items:
            type: "string"
          description: "Specific-tab owner ids - matches contacts where any listed user is creator, owner, or assignee. Overrides `ownerFilter`."
        assignee:
          type: "array"
          items:
            type: "string"
          description: "Restrict to contacts whose conversations have any of these users as assignees."
        pipelineType:
          type: "string"
          enum:
            - "Contact"
            - "Application"
          description: "Which model to query; defaults to `Contact`."
        pipelineId:
          type: "string"
          description: "Specific pipeline `_id` to query; falls back to the org's active pipeline of `pipelineType`."
        status:
          type: "string"
          description: "When set, restrict the result to this single stage (by name or id) instead of returning all stages."
        dateRange:
          type: "object"
          additionalProperties: true
          description: "Legacy `{ start, end }` createdAt window; kept for backward compatibility - prefer `createdDateRange`."
        createdDateRange:
          type: "object"
          additionalProperties: true
          description: "`{ start, end }` ISO range filtering on `createdAt`."
        customFilters:
          type: "object"
          additionalProperties: true
          description: "Map of custom-field key to value; string values use case-insensitive regex match."
        stages:
          type: "array"
          items:
            type: "string"
          description: "Client-provided stage names to avoid a pipeline lookup; ordering controls which stages get queried."
        stageIdByName:
          type: "object"
          additionalProperties:
            type: "string"
          description: "Optional stage-name to stage-id map enabling indexed `pipelineStage` queries instead of legacy status-name filters."
        bulkOnly:
          type: "boolean"
          description: "Restrict to contacts created via bulk import (`isBulkSms: true`)."
        messageStatus:
          type: "string"
          description: "Message engagement filter: `all`, `answered` (has any message), or `unanswered`."
        lastMessageTimeRange:
          type: "object"
          additionalProperties: true
          description: "`{ value, unit }` (hours/days) - returns contacts with NO messages within that recent window."
        lastMessageDateRange:
          type: "object"
          additionalProperties: true
          description: "`{ start, end }` window - returns contacts whose messages fall within this absolute date range."
      additionalProperties: true
      example:
        page:
          "New Lead": 1
          Qualified: 1
        size: 25
        search: "jane"
        ownerFilter: "my"
        pipelineType: "Contact"
        pipelineId: "64f0a1b2c3d4e5f6a7b8c9d1"
    GetContactsWithConversationsRequest:
      type: "object"
      properties:
        channelType:
          type: "string"
          description: "Restrict to contacts whose `channelTypes` includes this channel (e.g. `sms`, `webchat`, `email`, `voice`, `facebook`). Accepts JSON-array strings for multi-select."
        ownerFilter:
          type: "string"
          description: "Quick-tab owner scope: `my`, `all`, `team`, `unassigned`, or a specific user `_id`."
      additionalProperties: true
      example:
        channelType: "sms"
        ownerFilter: "my"
        page: 1
        size: 50
    GetContactCountsRequest:
      type: "object"
      properties:
        search:
          type: "string"
          description: "Case-insensitive substring matched literally against firstName, lastName, and phone-number value. Regex characters in the text are not interpreted."
        source:
          type: "string"
          description: "Exact-match filter on the contact `source` field."
        activeOnly:
          type: "boolean"
          description: "When `true`, count only contacts with conversation activity (`lastMessageTime` set), matching the Conversations list gate. Defaults to `false`, which counts every owned contact. For SUPERADMIN the activity gate is skipped on both buckets; `my` is still limited to contacts with a conversation assigned to the caller."
      additionalProperties: true
      example:
        search: "jane"
        source: "WebForm"
    GetContactByPhoneRequest:
      type: "object"
      properties:
        phoneNumber:
          type: "string"
          description: "Phone number to look up; normalized to E.164 before querying."
        targetUserId:
          type: "string"
          description: "Accepted for client compatibility; currently ignored by the server."
        context:
          type: "string"
          enum:
            - "contact-creation"
          description: "Set to `contact-creation` to check the whole organization for the number instead of the caller's visibility."
        selectedUser:
          type: "object"
          description: "When present, `_id` pins the lookup to that contact id."
          properties:
            _id:
              type: "string"
      required:
        - "phoneNumber"
      additionalProperties: false
      example:
        phoneNumber: "+14165550100"
    GetContactsByStatusRequest:
      type: "object"
      properties:
        status:
          type: "string"
          description: "Stage to query, identified by stage name or stage `_id`."
        pipelineId:
          type: "string"
          description: "Pipeline `_id` to query; falls back to the org's active Contact pipeline when omitted."
        page:
          type: "integer"
          description: "1-based page number for the requested stage."
        size:
          type: "integer"
          description: "Page size (default 50)."
        search:
          type: "string"
          description: "Case-insensitive substring match across name and phone number."
        showUnreadOnly:
          type: "boolean"
          description: "Restrict to contacts whose `isUpdated` flag is set."
        ownerFilter:
          type: "string"
          description: "Quick-tab owner scope: `my`, `all`, `team`, `unassigned`, or a specific user `_id`."
        bulkOnly:
          type: "boolean"
          description: "Restrict to contacts created via bulk import."
        showUnresolvedOnly:
          type: "boolean"
          description: "Restrict to contacts with at least one webchat conversation in a pending/unresolved state."
      required:
        - "status"
      additionalProperties: true
      example:
        status: "New Lead"
        pipelineId: "64f0a1b2c3d4e5f6a7b8c9d1"
        page: 1
        size: 50
        ownerFilter: "all"
    GetAllInitialContactsByStatusRequest:
      type: "object"
      properties:
        size:
          type: "integer"
          description: "Per-stage page size applied to every stage query."
        search:
          type: "string"
          description: "Case-insensitive substring match across name and phone number."
        pages:
          type: "object"
          additionalProperties:
            type: "integer"
          description: "Per-stage page numbers keyed by stage name (e.g. `{ \"New Lead\": 1 }`)."
        pipelineId:
          type: "string"
          description: "Specific pipeline `_id` to query; falls back to the org's active Contact pipeline."
        showUnreadOnly:
          type: "boolean"
          description: "Restrict to contacts whose `isUpdated` flag is set."
        channelType:
          type: "string"
          description: "Channel filter; `facebook` shows only Facebook contacts for the caller, otherwise Facebook contacts are excluded."
        source:
          type: "string"
          description: "Exact-match filter on the contact `source` field."
        ownerFilter:
          type: "string"
          description: "Quick-tab owner scope: `my`, `all`, `team`, `unassigned`, or a specific user `_id`."
        bulkOnly:
          type: "boolean"
          description: "Restrict to contacts created via bulk import."
        showUnresolvedOnly:
          type: "boolean"
          description: "Restrict to contacts with at least one webchat conversation in a pending/unresolved state."
      additionalProperties: true
      example:
        size: 25
        pipelineId: "64f0a1b2c3d4e5f6a7b8c9d1"
        ownerFilter: "my"
    BulkUpdateContactStatusRequest:
      type: "object"
      properties:
        contactIds:
          type: "array"
          items:
            type: "string"
          description: "Contact `_id`s to move; org-scoped unless the caller is SUPERADMIN."
        status:
          type: "string"
          description: "Target pipeline status name to assign to every contact."
        pipelineStageId:
          type: "string"
          description: "Target pipeline stage `_id`; resolved together with `status` to also infer `pipelineId`."
      required:
        - "contactIds"
        - "status"
        - "pipelineStageId"
      additionalProperties: false
      example:
        contactIds:
          - "64f0a1b2c3d4e5f6a7b8c9d0"
          - "64f0a1b2c3d4e5f6a7b8c9d5"
        status: "Qualified"
        pipelineStageId: "64f0a1b2c3d4e5f6a7b8c9d2"
    BulkDeleteContactsRequest:
      type: "object"
      properties:
        contactIds:
          type: "array"
          items:
            type: "string"
          description: "Contact `_id`s to cascade-delete (along with their conversations, messages, and notifications). Org-scoped unless caller is SUPERADMIN."
      required:
        - "contactIds"
      additionalProperties: false
      example:
        contactIds:
          - "64f0a1b2c3d4e5f6a7b8c9d0"
          - "64f0a1b2c3d4e5f6a7b8c9d5"
    GetContactsSuccessEnvelope:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            contacts:
              type: "array"
              items:
                "$ref": "#/components/schemas/ContactDto"
            total:
              type: "integer"
            page:
              type: "integer"
            size:
              type: "integer"
          required:
            - "contacts"
            - "total"
            - "page"
            - "size"
          additionalProperties: true
        meta:
          type: "object"
          additionalProperties: true
        contacts:
          type: "array"
          items:
            "$ref": "#/components/schemas/ContactDto"
        total:
          type: "integer"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          contacts:
            []
          total: 0
          page: 1
          size: 50
    GetContactByIdSuccessEnvelope:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          "$ref": "#/components/schemas/ContactDto"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          _id: "64f0a1b2c3d4e5f6a7b8c9d0"
          firstName: "Jane"
          lastName: "Doe"
          phoneNumber:
            -
              value: "+14165550100"
              isPrimary: true
    InvalidContactMethodResponse:
      type: "object"
      description: "400 envelope returned by the contact write routes when a phone number or email is not in the stored format. Phone numbers are normalized first (spaces and punctuation are removed for `+1` and `+91` numbers, and a doubled `+1` is repaired) and must then be `+1` or `+91` followed by 10 digits; emails must have the shape `name@domain.tld`. A value that is not a string (a number, a `null` entry, an entry with no `value`) is refused too. Blank entries are dropped, not refused. Nothing is written. `error.details.invalid` lists each offending field (`phoneNumber`, `email`, `conflictingPhoneNumbers` or `conflictingEmails`) with its values as normalized. On updates, a value that is already stored on the contact is not re-checked and is kept exactly as stored, so a record saved before this check can still be edited. The same code is returned for a body carrying `commandIdempotencyKey`; the check runs before the key is recorded, so the refused request does not consume it."
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
        error:
          type: "object"
          properties:
            code:
              type: "string"
              enum:
                - "INVALID_CONTACT_METHOD"
            message:
              type: "string"
            details:
              type: "object"
              properties:
                invalid:
                  type: "array"
                  items:
                    type: "object"
                    properties:
                      field:
                        type: "string"
                        enum:
                          - "phoneNumber"
                          - "email"
                          - "conflictingPhoneNumbers"
                          - "conflictingEmails"
                      values:
                        type: "array"
                        items:
                          type: "string"
                    required:
                      - "field"
                      - "values"
                    additionalProperties: false
              required:
                - "invalid"
              additionalProperties: false
          required:
            - "code"
            - "message"
            - "details"
          additionalProperties: true
      required:
        - "success"
        - "error"
      additionalProperties: true
      example:
        success: false
        message: "Invalid phone number \"12345\": use +1 or +91 followed by 10 digits."
        error:
          code: "INVALID_CONTACT_METHOD"
          message: "Invalid phone number \"12345\": use +1 or +91 followed by 10 digits."
          details:
            invalid:
              -
                field: "phoneNumber"
                values:
                  - "12345"
    ContactMethodConflictResponse:
      type: "object"
      description: "409 envelope returned by the update routes when an incoming phoneNumber or email is already held by another contact in the organization. Those values are unique per organization, so an update is rejected rather than partially applied. `error.details.conflictingContactId` identifies the current holder so callers can act without parsing the message. To move the value, either release it from the holder first or resend the entry with a `verifiedAt` timestamp to claim it. `POST /api/contact` does not reject on a held value - it creates the contact and reports the value in `data.warnings` - and only returns this envelope when the value was taken by a concurrent write."
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
        error:
          type: "object"
          properties:
            code:
              type: "string"
              enum:
                - "CONTACT_METHOD_CONFLICT"
            message:
              type: "string"
            details:
              type: "object"
              properties:
                field:
                  type: "string"
                  enum:
                    - "phoneNumber"
                    - "email"
                value:
                  type: "string"
                conflictingContactId:
                  type: "string"
                conflictingContactName:
                  type: "string"
              required:
                - "field"
                - "value"
                - "conflictingContactId"
              additionalProperties: true
          required:
            - "code"
            - "message"
          additionalProperties: true
      required:
        - "success"
        - "error"
      additionalProperties: true
      example:
        success: false
        message: "This phone number is already linked to Jane Doe."
        error:
          code: "CONTACT_METHOD_CONFLICT"
          message: "This phone number is already linked to Jane Doe. Release it from that contact first, or send it with a verifiedAt timestamp to claim it."
          details:
            field: "phoneNumber"
            value: "+15879207825"
            conflictingContactId: "6a4fe7db96a0ad3cd583bb11"
            conflictingContactName: "Jane Doe"
    ContactMutationSuccessEnvelope:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            contact:
              "$ref": "#/components/schemas/ContactDto"
            message:
              type: "string"
            outcome:
              type: "string"
              enum:
                - "created"
                - "matched"
                - "merged"
                - "sent_to_review"
              description: "Dedup outcome for contact creation; same vocabulary as the workflow create_contact action. `created` = new contact, `matched` = exact identity reuse, `merged` = fuzzy-merged into an existing contact, `sent_to_review` = ambiguous match parked in dedup review."
            dedupApplied:
              type: "boolean"
              description: "True when the organization dedup engine evaluated this write."
            mergedFromId:
              type: "string"
              description: "Present when `outcome` is `merged`: the id of the incoming contact that was merged away."
            reviewCandidates:
              type: "array"
              description: "Present when `outcome` is `sent_to_review`: the candidate contacts awaiting a manual dedup decision."
              items:
                type: "object"
                properties:
                  contactId:
                    type: "string"
                  firstName:
                    type: "string"
                    nullable: true
                  lastName:
                    type: "string"
                    nullable: true
                  score:
                    type: "number"
                required:
                  - "contactId"
                  - "score"
                additionalProperties: true
            warnings:
              type: "array"
              description: "Non-fatal notices about the write. Always present on `POST /api/contact` (empty when nothing was parked). Each entry names an incoming phone number or email that another contact in the organization already holds: the value was saved into `conflictingPhoneNumbers` / `conflictingEmails` on the new contact instead of its live identity array, and the pair was queued for dedup review. `meta` carries the same fields as the `CONTACT_METHOD_CONFLICT` error `details`. To claim the value for this contact, resend it on an update with a `verifiedAt` timestamp."
              items:
                "$ref": "#/components/schemas/ContactMethodWarning"
          required:
            - "contact"
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          contact:
            _id: "64f0a1b2c3d4e5f6a7b8c9d0"
            firstName: "Jane"
            lastName: "Doe"
            status: "New"
            email:
              -
                value: "jane@example.com"
                isPrimary: true
            phoneNumber:
              []
            conflictingPhoneNumbers:
              - "+15879207825"
            channelTypes:
              - "email"
          message: "Contact added successfully"
          outcome: "sent_to_review"
          dedupApplied: true
          reviewCandidates:
            -
              contactId: "6a4fe7db96a0ad3cd583bb11"
              firstName: "John"
              lastName: "Doe"
              score: 55
          warnings:
            -
              code: "CONTACT_METHOD_QUARANTINED"
              message: "The phone number +15879207825 is already linked to John Doe. It was saved as a conflicting phone number on this contact and queued for dedup review. To claim it, resend it on an update with a verifiedAt timestamp."
              meta:
                field: "phoneNumber"
                value: "+15879207825"
                conflictingContactId: "6a4fe7db96a0ad3cd583bb11"
                conflictingContactName: "John Doe"
    ContactMethodWarning:
      type: "object"
      description: "A phone number or email in the request was already held by another contact in the organization, so it was quarantined on the written contact rather than persisted as a live identity. The contact is created and usable on every channel that was not in conflict."
      properties:
        code:
          type: "string"
          enum:
            - "CONTACT_METHOD_QUARANTINED"
        message:
          type: "string"
        meta:
          type: "object"
          properties:
            field:
              type: "string"
              enum:
                - "phoneNumber"
                - "email"
            value:
              type: "string"
            conflictingContactId:
              type: "string"
            conflictingContactName:
              type: "string"
          required:
            - "field"
            - "value"
            - "conflictingContactId"
            - "conflictingContactName"
          additionalProperties: false
      required:
        - "code"
        - "message"
        - "meta"
      additionalProperties: false
    LegacyContactMutationResponse:
      type: "object"
      properties:
        message:
          type: "string"
        contact:
          "$ref": "#/components/schemas/ContactDto"
        data:
          {}
        success:
          type: "boolean"
      additionalProperties: true
      example:
        message: "Contact updated successfully"
        success: true
        contact:
          _id: "64f0a1b2c3d4e5f6a7b8c9d0"
          firstName: "Jane"
          lastName: "Doe"
    ActiveContactsResponse:
      type: "object"
      properties:
        data:
          type: "array"
          items:
            allOf:
              -
                "$ref": "#/components/schemas/ContactDto"
              -
                type: "object"
                properties:
                  conversationState:
                    type: "string"
                    nullable: true
                    enum:
                      - "resolved"
                      - "pending_agent_message"
                      - "pending_user_message"
                      - "pending_contact_message"
                      - null
                    description: "State of the contact's newest conversation visible to the caller, or null when none is known."
          description: "One page of contacts, newest activity first."
        total:
          type: "integer"
          description: "Number of contacts matching the filters across all pages."
      required:
        - "data"
        - "total"
      additionalProperties: false
      example:
        data:
          []
        total: 0
    ContactsArrayResponse:
      type: "object"
      properties:
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/ContactDto"
        total:
          type: "integer"
        status:
          type: "string"
        stageIdByName:
          type: "object"
          additionalProperties:
            type: "string"
        stageNameById:
          type: "object"
          additionalProperties:
            type: "string"
      additionalProperties: true
      example:
        data:
          []
        total: 0
    ContactsByStageResponse:
      type: "object"
      properties:
        data:
          type: "object"
          additionalProperties:
            type: "object"
            properties:
              contacts:
                type: "array"
                items:
                  "$ref": "#/components/schemas/ContactDto"
              total:
                type: "integer"
            additionalProperties: true
        dataByStatus:
          type: "object"
          additionalProperties: true
        stageIdByName:
          type: "object"
          additionalProperties:
            type: "string"
        stageNameById:
          type: "object"
          additionalProperties:
            type: "string"
      additionalProperties: true
      example:
        data:
          "New Lead":
            contacts:
              []
            total: 12
          Qualified:
            contacts:
              []
            total: 4
        stageIdByName:
          "New Lead": "64f0a1b2c3d4e5f6a7b8c9d2"
    ContactsByStatusResponse:
      type: "object"
      properties:
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/ContactDto"
        total:
          type: "integer"
        status:
          type: "string"
        pipelineStage:
          type: "string"
        stageIdByName:
          type: "object"
          additionalProperties:
            type: "string"
        stageNameById:
          type: "object"
          additionalProperties:
            type: "string"
      additionalProperties: true
      example:
        data:
          []
        total: 0
        status: "New Lead"
        pipelineStage: "64f0a1b2c3d4e5f6a7b8c9d2"
    ListGeneratorContact:
      type: "object"
      properties:
        id:
          type: "string"
        name:
          type: "string"
        phoneNumber:
          type: "string"
        email:
          type: "string"
        status:
          type: "string"
        pipelineStage:
          type: "string"
        lastMessageDate:
          type: "string"
          nullable: true
          format: "date-time"
        messageCount:
          type: "integer"
      additionalProperties: true
      example:
        id: "64f0a1b2c3d4e5f6a7b8c9d0"
        name: "Jane Doe"
        phoneNumber: "+14165550100"
        email: "jane.doe@example.com"
        status: "New Lead"
        pipelineStage: "64f0a1b2c3d4e5f6a7b8c9d2"
        lastMessageDate: "2026-05-15T09:12:00.000Z"
        messageCount: 3
    ListGeneratorResponse:
      type: "object"
      properties:
        contacts:
          type: "array"
          items:
            "$ref": "#/components/schemas/ListGeneratorContact"
        total:
          type: "integer"
        page:
          type: "integer"
        limit:
          type: "integer"
        totalPages:
          type: "integer"
      additionalProperties: true
      example:
        contacts:
          []
        total: 0
        page: 1
        limit: 10
        totalPages: 0
    ContactCountsResponse:
      type: "object"
      properties:
        all:
          type: "integer"
        my:
          type: "integer"
      required:
        - "all"
        - "my"
      additionalProperties: false
      example:
        all: 124
        my: 38
    ContactByPhoneResponse:
      type: "object"
      properties:
        data:
          "$ref": "#/components/schemas/ContactDto"
        message:
          type: "string"
        error:
          type: "string"
      additionalProperties: true
      example:
        data:
          _id: "64f0a1b2c3d4e5f6a7b8c9d0"
          firstName: "Jane"
          lastName: "Doe"
          phoneNumber:
            -
              value: "+14165550100"
              isPrimary: true
    BlockUnblockResponse:
      type: "object"
      properties:
        message:
          type: "string"
        data:
          type: "object"
          properties:
            contact:
              "$ref": "#/components/schemas/ContactDto"
            syncedDeviceIds:
              type: "array"
              items:
                type: "string"
            removedDeviceIds:
              type: "array"
              items:
                type: "string"
          additionalProperties: true
      additionalProperties: true
      example:
        message: "Contact blocked successfully"
        data:
          contact:
            _id: "64f0a1b2c3d4e5f6a7b8c9d0"
            firstName: "Jane"
            lastName: "Doe"
          syncedDeviceIds:
            - "device-abc123"
          removedDeviceIds:
            []
    BulkUpdateStatusResponse:
      type: "object"
      properties:
        message:
          type: "string"
        modifiedCount:
          type: "integer"
        matchedCount:
          type: "integer"
      additionalProperties: true
      example:
        message: "Bulk update completed"
        modifiedCount: 12
        matchedCount: 12
    BulkDeleteResponse:
      type: "object"
      properties:
        message:
          type: "string"
        deletedCount:
          type: "integer"
      additionalProperties: true
      example:
        message: "Contacts deleted"
        deletedCount: 5
    ExecuteAllCustomFieldsResponse:
      type: "object"
      properties:
        contact:
          type: "object"
          additionalProperties: true
        conversations:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
        applications:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
      additionalProperties: true
      example:
        contact:
          _id: "64f0a1b2c3d4e5f6a7b8c9d0"
          status: "Qualified"
        conversations:
          []
        applications:
          []
    ContactWrappedMutationResponse:
      type: "object"
      properties:
        message:
          type: "string"
        data:
          type: "object"
          properties:
            contact:
              "$ref": "#/components/schemas/ContactDto"
          required:
            - "contact"
          additionalProperties: true
      required:
        - "data"
      additionalProperties: true
      example:
        message: "Contact verified"
        data:
          contact:
            _id: "64f0a1b2c3d4e5f6a7b8c9d0"
            firstName: "Jane"
            lastName: "Doe"
    FindOrCreateContactByPhoneRequest:
      type: "object"
      properties:
        phoneNumber:
          type: "string"
          description: "Phone number to look up or create against; normalized to E.164 and used to dedupe within the caller's org."
      required:
        - "phoneNumber"
      additionalProperties: true
      example:
        phoneNumber: "+14165550100"
    FindOrCreateContactResponse:
      type: "object"
      properties:
        data:
          "$ref": "#/components/schemas/ContactDto"
        created:
          type: "boolean"
      required:
        - "data"
        - "created"
      additionalProperties: true
      example:
        data:
          _id: "64f0a1b2c3d4e5f6a7b8c9d0"
          firstName: "New Contact"
          phoneNumber:
            -
              value: "+14165550100"
              isPrimary: true
        created: true
    SetContactPhoneVerificationRequest:
      type: "object"
      properties:
        phoneNumber:
          type: "string"
          description: "Phone-number value (e.g. +14165551234) of the entry to update."
        verifiedAt:
          type: "string"
          format: "date-time"
          nullable: true
          description: "ISO date marking when the number was verified. Pass null to clear verification."
      required:
        - "phoneNumber"
      additionalProperties: true
      example:
        phoneNumber: "+14165550100"
        verifiedAt: "2026-05-15T09:12:00.000Z"
    VerifyContactRequest:
      type: "object"
      properties:
        verificationSource:
          type: "string"
          description: "Optional source tag for the verification (e.g. \"manual\", \"import\", \"third-party\")."
      additionalProperties: true
      example:
        verificationSource: "manual"
    ContactProtectionStatusResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            isProtected:
              type: "boolean"
            protectedUntil:
              type: "string"
              format: "date-time"
            ownerName:
              type: "string"
            ownerLastMessageAt:
              type: "string"
              format: "date-time"
          required:
            - "isProtected"
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          isProtected: true
          protectedUntil: "2026-05-22T09:12:00.000Z"
          ownerName: "Alex Rep"
          ownerLastMessageAt: "2026-05-15T09:12:00.000Z"
    ContactSeparationConversationSummary:
      type: "object"
      properties:
        _id:
          type: "string"
        channelType:
          type: "string"
        messageCount:
          type: "integer"
        lastMessageTime:
          type: "string"
          format: "date-time"
          nullable: true
        assignees:
          type: "array"
          items:
            type: "string"
      required:
        - "_id"
      additionalProperties: true
      example:
        _id: "64f0a1b2c3d4e5f6a7b8c9e0"
        channelType: "sms"
        messageCount: 12
        lastMessageTime: "2026-05-15T09:12:00.000Z"
        assignees:
          - "64f0a1b2c3d4e5f6a7b8c9d4"
    ContactSeparationApplicationSummary:
      type: "object"
      properties:
        _id:
          type: "string"
        status:
          type: "string"
          nullable: true
        pipelineStage:
          type: "string"
          nullable: true
        pipelineId:
          type: "string"
          nullable: true
        createdAt:
          type: "string"
          format: "date-time"
          nullable: true
      additionalProperties: true
      example:
        _id: "64f0a1b2c3d4e5f6a7b8c9f0"
        status: "Submitted"
        pipelineStage: "64f0a1b2c3d4e5f6a7b8c9f1"
        pipelineId: "64f0a1b2c3d4e5f6a7b8c9f2"
        createdAt: "2026-05-10T11:00:00.000Z"
    ContactSeparationNoteSummary:
      type: "object"
      properties:
        _id:
          type: "string"
        noteBody:
          type: "string"
          nullable: true
        userId:
          type: "string"
          nullable: true
        createdAt:
          type: "string"
          format: "date-time"
          nullable: true
      additionalProperties: true
      example:
        _id: "64f0a1b2c3d4e5f6a7b8c9f3"
        noteBody: "Left voicemail; called back from home number."
        userId: "64f0a1b2c3d4e5f6a7b8c9d4"
        createdAt: "2026-05-12T16:00:00.000Z"
    ContactSeparationReminderSummary:
      type: "object"
      properties:
        _id:
          type: "string"
        note:
          type: "string"
          nullable: true
        reminderDate:
          type: "string"
          format: "date-time"
          nullable: true
        assigneeId:
          type: "string"
          nullable: true
      additionalProperties: true
      example:
        _id: "64f0a1b2c3d4e5f6a7b8c9f4"
        note: "Follow up on insurance docs"
        reminderDate: "2026-05-20T17:00:00.000Z"
        assigneeId: "64f0a1b2c3d4e5f6a7b8c9d4"
    SeparationMessageSummary:
      type: "object"
      properties:
        _id:
          type: "string"
        body:
          type: "string"
        createdAt:
          type: "string"
          format: "date-time"
        isIncoming:
          type: "boolean"
        senderType:
          type: "string"
      required:
        - "_id"
        - "body"
        - "createdAt"
        - "isIncoming"
        - "senderType"
      additionalProperties: true
      example:
        _id: "64f0a1b2c3d4e5f6a7b8c9f6"
        body: "Thanks, I will call you back tomorrow."
        createdAt: "2026-05-14T15:30:00.000Z"
        isIncoming: true
        senderType: "contact"
    ContactSeparationDataResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            contact:
              "$ref": "#/components/schemas/ContactDto"
            conversations:
              type: "array"
              items:
                "$ref": "#/components/schemas/ContactSeparationConversationSummary"
            applications:
              type: "array"
              items:
                "$ref": "#/components/schemas/ContactSeparationApplicationSummary"
            contactNotes:
              type: "array"
              items:
                "$ref": "#/components/schemas/ContactSeparationNoteSummary"
            reminders:
              type: "array"
              items:
                "$ref": "#/components/schemas/ContactSeparationReminderSummary"
            conversationMessages:
              type: "object"
              additionalProperties:
                type: "array"
                items:
                  "$ref": "#/components/schemas/SeparationMessageSummary"
          required:
            - "contact"
            - "conversations"
            - "applications"
            - "contactNotes"
            - "reminders"
            - "conversationMessages"
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          contact:
            _id: "64f0a1b2c3d4e5f6a7b8c9d0"
            firstName: "Jane"
            lastName: "Doe"
          conversations:
            []
          applications:
            []
          contactNotes:
            []
          reminders:
            []
          conversationMessages:
            {}
    SeparationFieldOriginalNewString:
      type: "object"
      properties:
        original:
          type: "string"
        new:
          type: "string"
      required:
        - "original"
        - "new"
      additionalProperties: false
      example:
        original: "Jane"
        new: "Janet"
    SeparationFieldOriginalNewStringOptional:
      type: "object"
      properties:
        original:
          type: "string"
          nullable: true
        new:
          type: "string"
          nullable: true
      additionalProperties: false
      example:
        original: "jane.doe@example.com"
        new: "janet.doe@example.com"
    SeparationFieldDocuments:
      type: "object"
      properties:
        original:
          type: "array"
          items:
            type: "string"
        new:
          type: "array"
          items:
            type: "string"
      additionalProperties: false
      example:
        original:
          - "64f0a1b2c3d4e5f6a7b8ca10"
        new:
          - "64f0a1b2c3d4e5f6a7b8ca11"
    SeparationFieldMisc:
      type: "object"
      properties:
        original:
          type: "object"
          additionalProperties: true
        new:
          type: "object"
          additionalProperties: true
      additionalProperties: false
      example:
        original:
          creditScore: 720
        new:
          creditScore: 685
    SeparationTarget:
      type: "string"
      enum:
        - "original"
        - "new"
      example: "original"
    SeparateContactFieldSplit:
      type: "object"
      properties:
        firstName:
          "$ref": "#/components/schemas/SeparationFieldOriginalNewString"
        lastName:
          "$ref": "#/components/schemas/SeparationFieldOriginalNewString"
        email:
          "$ref": "#/components/schemas/SeparationFieldOriginalNewStringOptional"
        phoneNumber:
          "$ref": "#/components/schemas/SeparationFieldOriginalNewStringOptional"
        dateOfBirth:
          "$ref": "#/components/schemas/SeparationFieldOriginalNewStringOptional"
        documents:
          "$ref": "#/components/schemas/SeparationFieldDocuments"
        misc:
          "$ref": "#/components/schemas/SeparationFieldMisc"
        status:
          "$ref": "#/components/schemas/SeparationTarget"
        pipelineId:
          "$ref": "#/components/schemas/SeparationTarget"
        pipelineStage:
          "$ref": "#/components/schemas/SeparationTarget"
        assignees:
          "$ref": "#/components/schemas/SeparationTarget"
        outreachConfigId:
          "$ref": "#/components/schemas/SeparationTarget"
      required:
        - "firstName"
        - "lastName"
        - "status"
        - "pipelineId"
        - "pipelineStage"
        - "assignees"
        - "outreachConfigId"
      additionalProperties: true
      example:
        firstName:
          original: "Jane"
          new: "Janet"
        lastName:
          original: "Doe"
          new: "Doe"
        phoneNumber:
          original: "+14165550100"
          new: "+14165550199"
        status: "original"
        pipelineId: "original"
        pipelineStage: "original"
        assignees: "original"
        outreachConfigId: "original"
    SeparateContactChildRecordAssignment:
      type: "object"
      properties:
        conversations:
          type: "object"
          additionalProperties:
            "$ref": "#/components/schemas/SeparationTarget"
        applications:
          type: "object"
          additionalProperties:
            "$ref": "#/components/schemas/SeparationTarget"
        contactNotes:
          type: "object"
          additionalProperties:
            "$ref": "#/components/schemas/SeparationTarget"
        reminders:
          type: "object"
          additionalProperties:
            "$ref": "#/components/schemas/SeparationTarget"
      required:
        - "conversations"
        - "applications"
        - "contactNotes"
        - "reminders"
      additionalProperties: false
      example:
        conversations:
          "64f0a1b2c3d4e5f6a7b8c9e0": "original"
        applications:
          "64f0a1b2c3d4e5f6a7b8c9f0": "new"
        contactNotes:
          {}
        reminders:
          {}
    SeparateContactMessageDivider:
      type: "object"
      properties:
        conversationId:
          type: "string"
        dividerMessageId:
          type: "string"
        direction:
          type: "string"
          enum:
            - "before_to_original"
            - "before_to_new"
      required:
        - "conversationId"
        - "dividerMessageId"
        - "direction"
      additionalProperties: false
      example:
        conversationId: "64f0a1b2c3d4e5f6a7b8c9e0"
        dividerMessageId: "64f0a1b2c3d4e5f6a7b8c9f6"
        direction: "before_to_original"
    SeparateContactNewConversationMeta:
      type: "object"
      properties:
        conversationId:
          type: "string"
        assignees:
          type: "array"
          items:
            type: "string"
        status:
          type: "string"
      required:
        - "conversationId"
      additionalProperties: true
      example:
        conversationId: "64f0a1b2c3d4e5f6a7b8c9e1"
        assignees:
          - "64f0a1b2c3d4e5f6a7b8c9d4"
        status: "New Lead"
    SeparateContactRequest:
      type: "object"
      properties:
        fieldSplit:
          allOf:
            -
              "$ref": "#/components/schemas/SeparateContactFieldSplit"
          description: "How each contact field (name, phone, email, documents, misc, etc.) is divided between the original and the newly-created contact."
        childRecordAssignment:
          allOf:
            -
              "$ref": "#/components/schemas/SeparateContactChildRecordAssignment"
          description: "Per-record-type maps assigning each conversation/application/note/reminder id to either `original` or `new`."
        messageDividers:
          type: "array"
          items:
            "$ref": "#/components/schemas/SeparateContactMessageDivider"
          description: "Optional per-conversation message-split points indicating where to cut the message timeline between the two contacts."
        newConversationMeta:
          type: "array"
          items:
            "$ref": "#/components/schemas/SeparateContactNewConversationMeta"
          description: "Optional metadata (e.g. channel, assignees) for any brand-new conversations created on the separated contact."
      required:
        - "fieldSplit"
        - "childRecordAssignment"
      additionalProperties: true
      example:
        fieldSplit:
          firstName:
            original: "Jane"
            new: "Janet"
          lastName:
            original: "Doe"
            new: "Doe"
          status: "original"
          pipelineId: "original"
          pipelineStage: "original"
          assignees: "original"
          outreachConfigId: "original"
        childRecordAssignment:
          conversations:
            "64f0a1b2c3d4e5f6a7b8c9e0": "new"
          applications:
            {}
          contactNotes:
            {}
          reminders:
            {}
    SeparateContactResponseEnvelope:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            originalContactId:
              type: "string"
            newContactId:
              type: "string"
            summary:
              type: "object"
              properties:
                conversationsMoved:
                  type: "integer"
                applicationsMoved:
                  type: "integer"
                notesMoved:
                  type: "integer"
                remindersMoved:
                  type: "integer"
                messagesReassigned:
                  type: "integer"
              additionalProperties: true
          required:
            - "originalContactId"
            - "newContactId"
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          originalContactId: "64f0a1b2c3d4e5f6a7b8c9d0"
          newContactId: "64f0a1b2c3d4e5f6a7b8ca20"
          summary:
            conversationsMoved: 1
            applicationsMoved: 0
            notesMoved: 0
            remindersMoved: 0
            messagesReassigned: 4
    DedupReviewPhoneConflict:
      type: "object"
      properties:
        phoneNumber:
          type: "string"
      required:
        - "phoneNumber"
      additionalProperties: true
      example:
        phoneNumber: "+14165550100"
    DedupReviewDto:
      type: "object"
      properties:
        _id:
          type: "string"
        organizationId:
          type: "string"
          nullable: true
        sourceContactId:
          nullable: true
          oneOf:
            -
              type: "string"
            -
              "$ref": "#/components/schemas/ContactDto"
        candidateContactId:
          nullable: true
          oneOf:
            -
              type: "string"
            -
              "$ref": "#/components/schemas/ContactDto"
        reviewSource:
          type: "string"
          enum:
            - "fuzzy_match"
            - "phone_conflict"
            - "email_conflict"
            - "lost_all_identifiers"
        status:
          type: "string"
          enum:
            - "needs_review"
            - "merged"
            - "kept_separate"
            - "superseded"
        score:
          type: "number"
        thresholdSnapshot:
          type: "object"
          additionalProperties: true
        fieldBreakdown:
          type: "object"
          additionalProperties: true
        sourceSnapshot:
          type: "object"
          additionalProperties: true
        candidateSnapshot:
          type: "object"
          additionalProperties: true
        phoneConflict:
          "$ref": "#/components/schemas/DedupReviewPhoneConflict"
        resolution:
          type: "object"
          additionalProperties: true
        resolvedBy:
          nullable: true
          oneOf:
            -
              type: "string"
            -
              type: "object"
              properties:
                _id:
                  type: "string"
                fullName:
                  type: "string"
                  nullable: true
                email:
                  type: "string"
                  nullable: true
              additionalProperties: true
        resolvedAt:
          type: "string"
          format: "date-time"
          nullable: true
        createdAt:
          type: "string"
          format: "date-time"
          nullable: true
        updatedAt:
          type: "string"
          format: "date-time"
          nullable: true
      additionalProperties: true
      example:
        _id: "64f0a1b2c3d4e5f6a7b8ca30"
        organizationId: "64f0a1b2c3d4e5f6a7b8c9d3"
        sourceContactId: "64f0a1b2c3d4e5f6a7b8c9d0"
        candidateContactId: "64f0a1b2c3d4e5f6a7b8ca31"
        reviewSource: "fuzzy_match"
        status: "needs_review"
        score: 0.87
        createdAt: "2026-05-10T12:00:00.000Z"
    ContactDedupReviewListResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/ContactDedupReview"
        count:
          type: "integer"
        organizationId:
          type: "string"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          -
            _id: "5f7b1c2e8a1d4e0012c3b4b0"
            organizationId: "5f7b1c2e8a1d4e0012c3b400"
            reviewSource: "fuzzy_match"
            status: "needs_review"
            score: 86
            createdAt: "2026-05-18T14:30:00.000Z"
        count: 0
        organizationId: "64f0a1b2c3d4e5f6a7b8c9d3"
    DedupReviewGroupedCandidate:
      type: "object"
      properties:
        reviewId:
          type: "string"
        contact:
          "$ref": "#/components/schemas/ContactDto"
        candidateSnapshot:
          type: "object"
          additionalProperties: true
        score:
          type: "number"
        thresholdSnapshot:
          type: "object"
          additionalProperties: true
        fieldBreakdown:
          type: "object"
          additionalProperties: true
        reviewSource:
          type: "string"
          enum:
            - "fuzzy_match"
            - "phone_conflict"
            - "email_conflict"
            - "lost_all_identifiers"
        phoneConflict:
          "$ref": "#/components/schemas/DedupReviewPhoneConflict"
        createdAt:
          type: "string"
          format: "date-time"
          nullable: true
      required:
        - "reviewId"
      additionalProperties: true
      example:
        reviewId: "64f0a1b2c3d4e5f6a7b8ca30"
        score: 0.87
        reviewSource: "fuzzy_match"
        createdAt: "2026-05-10T12:00:00.000Z"
    DedupReviewGroupedEntry:
      type: "object"
      properties:
        sourceContactId:
          type: "string"
        source:
          "$ref": "#/components/schemas/ContactDto"
        sourceSnapshot:
          type: "object"
          additionalProperties: true
        candidates:
          type: "array"
          items:
            "$ref": "#/components/schemas/DedupReviewGroupedCandidate"
      required:
        - "sourceContactId"
        - "candidates"
      additionalProperties: true
      example:
        sourceContactId: "64f0a1b2c3d4e5f6a7b8c9d0"
        candidates:
          -
            reviewId: "64f0a1b2c3d4e5f6a7b8ca30"
            score: 0.87
            reviewSource: "fuzzy_match"
    ContactDedupReviewGroupedResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/DedupReviewGroupedEntry"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          []
    ContactDedupReviewResolutionBody:
      type: "object"
      properties:
        resolution:
          type: "object"
          additionalProperties: true
          description: "Free-form resolution payload persisted on the review (e.g. `fieldChoices` map of `source`/`candidate` selections that drive the merge)."
      additionalProperties: true
      example:
        resolution:
          firstName: "candidate"
          lastName: "candidate"
          email: "source"
    ContactDedupReviewMergeResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        data:
          "$ref": "#/components/schemas/DedupReviewDto"
        targetContact:
          "$ref": "#/components/schemas/ContactDto"
      required:
        - "success"
      additionalProperties: true
      example:
        success: true
        message: "Review merged"
        data:
          _id: "64f0a1b2c3d4e5f6a7b8ca30"
          status: "merged"
    ContactDedupReviewKeepSeparateResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        data:
          "$ref": "#/components/schemas/DedupReviewDto"
      required:
        - "success"
      additionalProperties: true
      example:
        success: true
        message: "Review kept separate"
        data:
          _id: "64f0a1b2c3d4e5f6a7b8ca30"
          status: "kept_separate"
    ContactDedupReviewBulkRequest:
      type: "object"
      properties:
        reviewIds:
          type: "array"
          items:
            type: "string"
          description: "Dedup-review `_id`s to resolve in this call; capped at the server-configured per-call limit."
        resolution:
          type: "object"
          additionalProperties: true
          description: "Shared resolution payload applied to every review in the batch (same shape as the single-review endpoint)."
      required:
        - "reviewIds"
      additionalProperties: true
      example:
        reviewIds:
          - "64f0a1b2c3d4e5f6a7b8ca30"
          - "64f0a1b2c3d4e5f6a7b8ca31"
    ContactDedupReviewBulkPairResult:
      type: "object"
      properties:
        reviewId:
          type: "string"
        ok:
          type: "boolean"
        status:
          type: "integer"
        error:
          type: "string"
        targetContactId:
          type: "string"
      required:
        - "reviewId"
        - "ok"
      additionalProperties: true
      example:
        reviewId: "64f0a1b2c3d4e5f6a7b8ca30"
        ok: true
        status: 200
        targetContactId: "64f0a1b2c3d4e5f6a7b8c9d0"
    ContactDedupReviewBulkResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        results:
          type: "array"
          items:
            "$ref": "#/components/schemas/ContactDedupReviewBulkPairResult"
        summary:
          type: "object"
          properties:
            total:
              type: "integer"
            succeeded:
              type: "integer"
            failed:
              type: "integer"
          required:
            - "total"
            - "succeeded"
            - "failed"
          additionalProperties: true
      required:
        - "success"
        - "results"
        - "summary"
      additionalProperties: true
      example:
        success: true
        results:
          -
            reviewId: "64f0a1b2c3d4e5f6a7b8ca30"
            ok: true
            status: 200
        summary:
          total: 1
          succeeded: 1
          failed: 0
    ContactDocumentDto:
      type: "object"
      properties:
        _id:
          type: "string"
        storageKey:
          type: "string"
        filename:
          type: "string"
        contentType:
          type: "string"
        size:
          type: "integer"
        documentType:
          type: "string"
        sourceMessageId:
          type: "string"
          nullable: true
        uploadedAt:
          type: "string"
          format: "date-time"
          nullable: true
        uploadedBy:
          type: "string"
          nullable: true
        notes:
          type: "string"
          nullable: true
        signedUrl:
          type: "string"
          nullable: true
          description: "Short-lived signed GET URL for the underlying R2 object."
      required:
        - "storageKey"
        - "filename"
        - "contentType"
        - "documentType"
      additionalProperties: true
      example:
        _id: "64f0a1b2c3d4e5f6a7b8ca40"
        storageKey: "org/64f0a1b2c3d4e5f6a7b8c9d3/contact/64f0a1b2c3d4e5f6a7b8c9d0/2026/id-proof.pdf"
        filename: "id-proof.pdf"
        contentType: "application/pdf"
        size: 184320
        documentType: "ID Proof"
        uploadedAt: "2026-05-12T10:00:00.000Z"
        uploadedBy: "64f0a1b2c3d4e5f6a7b8c9d4"
        notes: "Driver license, front + back"
        signedUrl: "https://example-r2.signed/.../id-proof.pdf?X-Amz-Expires=600"
    ContactDocumentsListResponse:
      type: "object"
      properties:
        documents:
          type: "array"
          items:
            "$ref": "#/components/schemas/ContactDocumentDto"
      required:
        - "documents"
      additionalProperties: true
      example:
        documents:
          []
    ContactDocumentMutationResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        document:
          "$ref": "#/components/schemas/ContactDocumentDto"
      required:
        - "success"
        - "document"
      additionalProperties: true
      example:
        success: true
        document:
          _id: "64f0a1b2c3d4e5f6a7b8ca40"
          storageKey: "org/64f0a1b2c3d4e5f6a7b8c9d3/contact/64f0a1b2c3d4e5f6a7b8c9d0/2026/id-proof.pdf"
          filename: "id-proof.pdf"
          contentType: "application/pdf"
          documentType: "ID Proof"
    SaveContactDocumentRequest:
      type: "object"
      properties:
        storageKey:
          type: "string"
          description: "R2 storage key of the already-uploaded object."
        filename:
          type: "string"
        contentType:
          type: "string"
        size:
          type: "integer"
          description: "File size in bytes. If missing or 0, the server will attempt to look it up from R2."
        documentType:
          type: "string"
          description: "Must match a name in the organization's configured documentTypes."
        sourceMessageId:
          type: "string"
          description: "Optional originating message id when the document was promoted from an attachment."
        notes:
          type: "string"
      required:
        - "storageKey"
        - "filename"
        - "contentType"
        - "documentType"
      additionalProperties: true
      example:
        storageKey: "org/64f0a1b2c3d4e5f6a7b8c9d3/contact/64f0a1b2c3d4e5f6a7b8c9d0/2026/id-proof.pdf"
        filename: "id-proof.pdf"
        contentType: "application/pdf"
        size: 184320
        documentType: "ID Proof"
        notes: "Driver license, front + back"
    UpdateContactDocumentRequest:
      type: "object"
      properties:
        documentType:
          type: "string"
          description: "New document type label; must match a name configured in the organization's `documentTypes`."
        notes:
          type: "string"
          nullable: true
          description: "Free-form note shown alongside the document; pass `null` to clear an existing note."
      additionalProperties: true
      example:
        documentType: "Proof of Address"
        notes: "Updated label after re-review"
    UploadContactDocumentForm:
      type: "object"
      properties:
        file:
          type: "string"
          format: "binary"
          description: "Document file (max 25 MB)."
        documentType:
          type: "string"
          description: "Must match a name in the organization's configured documentTypes."
        notes:
          type: "string"
      required:
        - "file"
        - "documentType"
      example:
        documentType: "ID Proof"
        notes: "Driver license front + back"
    SetContactMethodVerificationRequest:
      type: "object"
      description: "Toggle verification on a single phone or email entry. `value` must match an existing entry on the contact (phones are normalized to E.164; emails are lower-cased). Pass `verifiedAt` to mark verified; pass `null` (or omit) to clear."
      properties:
        type:
          type: "string"
          enum:
            - "phone"
            - "email"
        value:
          type: "string"
          description: "Phone (any format - normalized server-side) or email address."
        verifiedAt:
          description: "ISO 8601 timestamp to set, or `null` to clear all verification fields on this entry."
          type: "string"
          format: "date-time"
          nullable: true
        verificationSource:
          type: "string"
          description: "Free-form label of where the verification came from (e.g. `webchat`, `admin-manual`). Only stored when `verifiedAt` is set."
      required:
        - "type"
        - "value"
      additionalProperties: true
      example:
        type: "phone"
        value: "+14165550100"
        verifiedAt: "2026-05-20T15:04:01.135Z"
        verificationSource: "admin-manual"
    SetContactMethodVerificationResponse:
      type: "object"
      description: "Returned after a successful verify/unverify on a phone or email entry."
      properties:
        message:
          type: "string"
          description: "One of `Phone number verified`, `Phone number verification cleared`, `Email verified`, `Email verification cleared`."
        data:
          type: "object"
          properties:
            contact:
              type: "object"
              additionalProperties: true
              description: "Full updated Contact document."
          required:
            - "contact"
          additionalProperties: true
      required:
        - "message"
        - "data"
      additionalProperties: true
      example:
        message: "Phone number verified"
        data:
          contact:
            _id: "64b2c3d4e5f60012345678aa"
            firstName: "Alex"
            lastName: "Morgan"
            phoneNumber:
              -
                value: "+14165550100"
                isPrimary: true
                verifiedAt: "2026-05-20T15:04:01.135Z"
                verifiedBy: "64a1b2c3d4e5f60012345679"
                verificationSource: "admin-manual"
    ContactBulkJobStatusResponse:
      type: "object"
      description: "Progress snapshot for a background bulk job (currently `query-bulk-delete`). `processed` counts records cumulatively across all batches; `total` is set to the final count when the job completes."
      properties:
        jobId:
          type: "string"
        status:
          type: "string"
          enum:
            - "pending"
            - "completed"
            - "failed"
        processed:
          type: "integer"
        total:
          type: "integer"
        error:
          type: "string"
          description: "Present only when `status` is `failed`."
      required:
        - "jobId"
        - "status"
        - "processed"
        - "total"
      additionalProperties: true
      example:
        jobId: "b09c2c61-2f8f-4f02-9c1b-2f23a3a2f9c1"
        status: "pending"
        processed: 1500
        total: 0
    ContactBulkQueryFilter:
      type: "object"
      description: "Shared filter shape used by `query-count`, `query-bulk-move`, `query-bulk-delete`, and `query-bulk-export`. Either supply `stageIds[]` OR set `orgWide: true`. `pipelineType` selects whether the operation runs against the Contact or Application collection."
      properties:
        stageIds:
          type: "array"
          items:
            type: "string"
          description: "One or more pipeline-stage IDs. Required unless `orgWide` is `true`."
        pipelineType:
          type: "string"
          enum:
            - "Contact"
            - "Application"
          description: "Which collection to target. Defaults to `Contact`."
        orgWide:
          type: "boolean"
          description: "When `true`, ignore `stageIds` and run across the whole organization."
        ownerFilter:
          type: "string"
          description: "Owner-based scope (e.g. `owned`, `unowned`) - same semantics as the Contacts list view."
        advancedParams:
          type: "object"
          additionalProperties: true
          description: "Optional advanced filter object (same shape as the Contacts list view)."
      additionalProperties: true
      example:
        stageIds:
          - "64b2c3d4e5f60012345678aa"
        pipelineType: "Contact"
        ownerFilter: "unowned"
        advancedParams:
          createdAfter: "2026-01-01T00:00:00.000Z"
    ContactBulkQueryCountResponse:
      type: "object"
      properties:
        count:
          type: "integer"
      required:
        - "count"
      additionalProperties: true
      example:
        count: 1428
    ContactBulkQueryMoveRequest:
      allOf:
        -
          "$ref": "#/components/schemas/ContactBulkQueryFilter"
      type: "object"
      properties:
        targetStageId:
          type: "string"
          description: "Pipeline-stage ID to move matched contacts into."
        targetStatus:
          type: "string"
          description: "Status string to set alongside the new stage."
      required:
        - "targetStageId"
        - "targetStatus"
      additionalProperties: true
      example:
        stageIds:
          - "64b2c3d4e5f60012345678aa"
        orgWide: false
        targetStageId: "64b2c3d4e5f60012345678bb"
        targetStatus: "Contacted"
    ContactBulkQueryMoveResponse:
      type: "object"
      properties:
        message:
          type: "string"
        modifiedCount:
          type: "integer"
          description: "Number of contacts whose status/stage actually changed."
        matchedCount:
          type: "integer"
          description: "Total contacts matched by the filter."
      required:
        - "message"
        - "modifiedCount"
        - "matchedCount"
      additionalProperties: true
      example:
        message: "Successfully moved 1428 contact(s)"
        modifiedCount: 1428
        matchedCount: 1500
    ContactBulkQueryDeleteResponse:
      type: "object"
      description: "202 Accepted response - the delete runs in the background. Poll `GET /api/contacts/bulk-job/{jobId}` for progress."
      properties:
        jobId:
          type: "string"
          description: "UUID to use with `GET /api/contacts/bulk-job/{jobId}`."
        message:
          type: "string"
      required:
        - "jobId"
        - "message"
      additionalProperties: true
      example:
        jobId: "b09c2c61-2f8f-4f02-9c1b-2f23a3a2f9c1"
        message: "Bulk delete started"
    ConversationMonitorRow:
      type: "object"
      properties:
        conversationId:
          type: "string"
        contactId:
          type: "string"
        contactName:
          type: "string"
        contactPhone:
          type: "string"
          nullable: true
        channelType:
          type: "string"
        latestInboundMessageId:
          type: "string"
          nullable: true
        latestInboundAt:
          type: "string"
          format: "date-time"
          nullable: true
        category:
          type: "string"
          enum:
            - "ai_stuck"
            - "agent_abandoned"
        assigneeNames:
          type: "array"
          items:
            type: "string"
        hasAccess:
          type: "boolean"
      additionalProperties: true
      example:
        conversationId: "65d3e0f0a0b0c0d0e0f0a0b0"
        contactId: "65c2d0e0f0a0b0c0d0e0f0a0"
        contactName: "Jane Doe"
        contactPhone: "+14155550123"
        channelType: "sms"
        latestInboundMessageId: "65e3f0a0b0c0d0e0f0a0b0c0"
        latestInboundAt: "2026-05-18T13:45:00.000Z"
        category: "ai_stuck"
        assigneeNames:
          - "Alice Rivera"
        hasAccess: true
    ConversationMonitorPagination:
      type: "object"
      properties:
        page:
          type: "integer"
        limit:
          type: "integer"
        total:
          type: "integer"
        totalPages:
          type: "integer"
      required:
        - "page"
        - "limit"
        - "total"
        - "totalPages"
      additionalProperties: true
      example:
        page: 1
        limit: 25
        total: 42
        totalPages: 2
    ConversationMonitorReportResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            organizationId:
              type: "string"
            generatedAt:
              type: "string"
              format: "date-time"
              nullable: true
            thresholdMinutes:
              type: "number"
            totalCount:
              type: "integer"
            snapshotMissing:
              type: "boolean"
            pagination:
              "$ref": "#/components/schemas/ConversationMonitorPagination"
            rows:
              type: "array"
              items:
                "$ref": "#/components/schemas/ConversationMonitorRow"
          required:
            - "organizationId"
            - "thresholdMinutes"
            - "pagination"
            - "rows"
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
          generatedAt: "2026-05-18T14:00:00.000Z"
          thresholdMinutes: 30
          totalCount: 42
          snapshotMissing: false
          pagination:
            page: 1
            limit: 25
            total: 42
            totalPages: 2
          rows:
            -
              conversationId: "65d3e0f0a0b0c0d0e0f0a0b0"
              contactId: "65c2d0e0f0a0b0c0d0e0f0a0"
              contactName: "Jane Doe"
              contactPhone: "+14155550123"
              channelType: "sms"
              latestInboundAt: "2026-05-18T13:45:00.000Z"
              category: "ai_stuck"
              assigneeNames:
                - "Alice Rivera"
              hasAccess: true
    ConversationMonitorErrorResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
        error:
          type: "string"
      additionalProperties: true
      example:
        success: false
        message: "Organization not found"
        error: "NOT_FOUND"
    SuccessResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
      additionalProperties: true
      example:
        success: true
    SubmitWebchatCsatRequest:
      type: "object"
      properties:
        webchatId:
          type: "string"
        rating:
          type: "number"
          description: "Integer 1-5, or string parseable to integer 1-5"
        feedback:
          type: "string"
      required:
        - "webchatId"
        - "rating"
      additionalProperties: true
      example:
        webchatId: "67d3a0b0c0d0e0f0a0b0c0d0"
        rating: 5
        feedback: "Great help!"
    SubmitConversationCsatRequest:
      type: "object"
      properties:
        rating:
          type: "number"
          description: "Integer 1-5, or string parseable to integer 1-5"
        feedback:
          type: "string"
      required:
        - "rating"
      additionalProperties: true
      example:
        rating: 4
        feedback: "Resolved quickly."
    CsatSubmitResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        conversationId:
          type: "string"
        csatRating:
          type: "integer"
        csatSubmittedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        success: true
        conversationId: "65d3e0f0a0b0c0d0e0f0a0b0"
        csatRating: 5
        csatSubmittedAt: "2026-05-18T14:00:00.000Z"
    WebchatCsatStatusResponse:
      type: "object"
      properties:
        sessionStatus:
          type: "string"
          description: "One of: active, pending_csat, ended"
        hasPendingCsat:
          type: "boolean"
        conversationId:
          type: "string"
        shouldClearSession:
          type: "boolean"
      additionalProperties: true
      example:
        sessionStatus: "pending_csat"
        hasPendingCsat: true
        conversationId: "65d3e0f0a0b0c0d0e0f0a0b0"
        shouldClearSession: false
    ConversationsByContactResponse:
      type: "object"
      properties:
        conversations:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
      additionalProperties: true
      example:
        conversations:
          -
            _id: "65d3e0f0a0b0c0d0e0f0a0b0"
            contactId: "65c2d0e0f0a0b0c0d0e0f0a0"
            channelType: "sms"
            isAutopilot: true
            isResolved: false
            lastMessageTime: "2026-05-18T13:45:00.000Z"
    SidebarConversationsResponse:
      type: "object"
      properties:
        data:
          type: "array"
          items:
            type: "object"
            description: "A ListConversationsResponse item plus isUpdated, isBulkSms, stateRank, latestMessagePreview and the row contact."
        total:
          type: "number"
    ListConversationsResponse:
      type: "object"
      properties:
        conversations:
          type: "array"
          items:
            type: "object"
            properties:
              conversationId:
                type: "string"
              contactId:
                type: "string"
              organizationId:
                type: "string"
              channelType:
                type: "string"
              channelIdentifier:
                type: "string"
              phoneNumberId:
                type: "string"
                description: "The org FROM line (PhoneNumber resource id) the thread is on. SMS only."
              fromPhoneNumber:
                type: "string"
              fromPhoneLabel:
                type: "string"
              agentId:
                type: "string"
                description: "`Prompt._id` of the agent answering this conversation."
              applicationIds:
                type: "array"
                items:
                  type: "string"
              assignees:
                type: "array"
                items:
                  type: "string"
              direction:
                type: "string"
                description: "Voice: from the most recent linked Call doc. Non-voice: from the latest non-system, non-internal message."
              callStatus:
                type: "string"
                description: "Voice channel only. Sourced from the latest linked Call doc."
              conversationState:
                type: "string"
              isResolved:
                type: "boolean"
              isAutopilot:
                type: "boolean"
              lastMessageTime:
                type: "string"
                format: "date-time"
              latestActivity:
                type: "string"
                format: "date-time"
              createdAt:
                type: "string"
                format: "date-time"
              updatedAt:
                type: "string"
                format: "date-time"
              messageCount:
                type: "number"
              hasRecording:
                type: "boolean"
                description: "True if any linked Call doc has at least one recording. Voice only."
              recordingCount:
                type: "number"
            required:
              - "conversationId"
              - "contactId"
              - "organizationId"
              - "channelType"
              - "createdAt"
              - "updatedAt"
            additionalProperties: true
        hasMore:
          type: "boolean"
        nextCursor:
          type: "string"
          nullable: true
          description: "Opaque pagination cursor. Pass it back unmodified as `cursor`; the encoding is an implementation detail and is not a plain timestamp."
      required:
        - "conversations"
        - "hasMore"
        - "nextCursor"
      additionalProperties: true
      example:
        conversations:
          -
            conversationId: "65d3e0f0a0b0c0d0e0f0a0b0"
            contactId: "65c2d0e0f0a0b0c0d0e0f0a0"
            organizationId: "65a1b0c0d0e0f0a0b0c0d0e0"
            channelType: "sms"
            isAutopilot: true
            isResolved: false
            lastMessageTime: "2026-05-18T13:45:00.000Z"
            createdAt: "2026-05-18T13:00:00.000Z"
            updatedAt: "2026-05-18T13:45:00.000Z"
        hasMore: false
        nextCursor: null
    DeleteConversationRequest:
      type: "object"
      properties:
        conversationId:
          type: "string"
          description: "`_id` of the conversation to delete; the conversation must belong to the caller's organization."
      required:
        - "conversationId"
      additionalProperties: true
      example:
        conversationId: "65d3e0f0a0b0c0d0e0f0a0b0"
    MarkConversationAsUnseenRequest:
      type: "object"
      properties:
        conversationId:
          type: "string"
          description: "`_id` of the conversation to flip back to unseen for the calling user."
      required:
        - "conversationId"
      additionalProperties: true
      example:
        conversationId: "65d3e0f0a0b0c0d0e0f0a0b0"
    ConversationByIdResponse:
      type: "object"
      properties:
        data:
          type: "object"
          additionalProperties: true
      additionalProperties: true
      example:
        data:
          _id: "65d3e0f0a0b0c0d0e0f0a0b0"
          contactId: "65c2d0e0f0a0b0c0d0e0f0a0"
          channelType: "sms"
          isAutopilot: true
          isResolved: false
          assignees:
            - "65b1f0a2c3d4e5f6a7b8c9d0"
          lastMessageTime: "2026-05-18T13:45:00.000Z"
    UpdateConversationRequest:
      type: "object"
      properties:
        isAutopilot:
          type: "boolean"
          description: "When true, lets the configured AI agent respond automatically."
        process:
          type: "string"
          description: "Prompt `_id` driving the AI for this conversation."
        assignees:
          type: "array"
          items:
            type: "string"
          description: "User `_id`s assigned to this conversation; receives socket events and pings."
        fromHistoryModal:
          type: "boolean"
          description: "Suppresses side-effects (audit log, socket emit) when the update originates from the history viewer."
      additionalProperties: true
      example:
        isAutopilot: false
        assignees:
          - "65b1f0a2c3d4e5f6a7b8c9d0"
    ConversationUpdateResponse:
      type: "object"
      properties:
        message:
          type: "string"
        data:
          type: "object"
          additionalProperties: true
      additionalProperties: true
      example:
        message: "Conversation updated"
        data:
          _id: "65d3e0f0a0b0c0d0e0f0a0b0"
          isAutopilot: false
    ToggleResolveConversationRequest:
      type: "object"
      properties:
        isResolved:
          type: "boolean"
          description: "Target resolution state; `true` resolves the conversation (stamping `resolvedAt`/`resolvedBy` and may trigger a CSAT prompt), `false` reopens it."
      required:
        - "isResolved"
      additionalProperties: true
      example:
        isResolved: true
    ConversationResolveResponse:
      type: "object"
      properties:
        message:
          type: "string"
        data:
          type: "object"
          additionalProperties: true
      additionalProperties: true
      example:
        message: "Conversation resolved"
        data:
          _id: "65d3e0f0a0b0c0d0e0f0a0b0"
          isResolved: true
          resolvedAt: "2026-05-18T14:10:00.000Z"
    ConversationMessagesResponse:
      type: "object"
      properties:
        messages:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
        messageCount:
          type: "integer"
        callCount:
          type: "integer"
        resolution:
          type: "object"
          properties:
            isResolved:
              type: "boolean"
            resolvedAt:
              type: "string"
              format: "date-time"
            resolvedBy:
              type: "object"
              additionalProperties: true
            csatRating:
              type: "integer"
            csatFeedback:
              type: "string"
            csatSubmittedAt:
              type: "string"
              format: "date-time"
          additionalProperties: true
          description: "Null when conversation is not resolved"
      additionalProperties: true
      example:
        messages:
          -
            _id: "67e0a0b0c0d0e0f0a0b0c0d0"
            body: "Hi! How can we help?"
            senderType: "AI"
            direction: "outbound"
            createdAt: "2026-05-18T13:30:00.000Z"
        messageCount: 17
        callCount: 1
        resolution:
          isResolved: true
          resolvedAt: "2026-05-18T14:10:00.000Z"
          resolvedBy:
            userId: "65b1f0a2c3d4e5f6a7b8c9d0"
            fullName: "Alice Rivera"
          csatRating: 5
          csatFeedback: "Great help!"
          csatSubmittedAt: "2026-05-18T14:12:00.000Z"
    LinkApplicationsRequest:
      type: "object"
      properties:
        applicationIds:
          type: "array"
          items:
            type: "string"
          description: "Application `_id`s to attach to this conversation; each must be a valid ObjectId in the caller's organization."
      required:
        - "applicationIds"
      additionalProperties: true
      example:
        applicationIds:
          - "66b0a0b0c0d0e0f0a0b0c0d0"
    LinkApplicationsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        message:
          type: "string"
        data:
          type: "object"
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        message: "Applications linked"
        data:
          conversationId: "65d3e0f0a0b0c0d0e0f0a0b0"
          linked:
            - "66b0a0b0c0d0e0f0a0b0c0d0"
    UnlinkApplicationsRequest:
      type: "object"
      properties:
        applicationIds:
          type: "array"
          items:
            type: "string"
          description: "Application `_id`s to detach from this conversation; the Application records themselves are preserved."
      required:
        - "applicationIds"
      additionalProperties: true
      example:
        applicationIds:
          - "66b0a0b0c0d0e0f0a0b0c0d0"
    UnlinkApplicationsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        message:
          type: "string"
        data:
          type: "object"
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        message: "Applications unlinked"
        data:
          conversationId: "65d3e0f0a0b0c0d0e0f0a0b0"
          unlinked:
            - "66b0a0b0c0d0e0f0a0b0c0d0"
    SendMessageToConversationRequest:
      type: "object"
      properties:
        body:
          type: "string"
          description: "Message content"
        attachments:
          type: "array"
          items:
            type: "object"
            properties:
              url:
                type: "string"
              filename:
                type: "string"
              contentType:
                type: "string"
            required:
              - "filename"
            additionalProperties: true
        isInternal:
          type: "boolean"
          description: "Whether this is an internal/whisper message"
        expectedRevision:
          type: "integer"
          minimum: 0
          description: "Conversation revision the caller last saw. Sending this or `commandIdempotencyKey` routes the send through the revisioned command path, which needs both."
        commandIdempotencyKey:
          type: "string"
          minLength: 1
          maxLength: 200
          description: "Idempotency key for this exact request. Sending the same body again under the same key replays the first outcome; a different body under the same key is refused with `409 IDEMPOTENCY_KEY_REUSED`."
      required:
        - "body"
      additionalProperties: true
      example:
        body: "Thanks for confirming, we'll follow up tomorrow."
        attachments:
          -
            url: "https://r2.example.com/messages/.../quote.pdf"
            filename: "quote.pdf"
            contentType: "application/pdf"
        isInternal: false
    SendMessageToConversationResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        message:
          type: "object"
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        message:
          _id: "67e0a0b0c0d0e0f0a0b0c0d1"
          body: "Thanks for confirming, we'll follow up tomorrow."
          direction: "outbound"
          senderType: "HUMAN"
          createdAt: "2026-05-18T14:15:00.000Z"
    SmsTooLongErrorResponse:
      type: "object"
      description: "An SMS refused for going over 3 segments. Nothing was sent. `segments`, `encoding` and `maxCharacters` are present on the refusal itself and absent when the refusal is replayed under the same `commandIdempotencyKey`."
      properties:
        success:
          type: "boolean"
          enum:
            - false
        error:
          type: "object"
          properties:
            code:
              type: "string"
              enum:
                - "SMS_TOO_LONG"
            message:
              type: "string"
              description: "A sentence that can be shown to the person who wrote the message."
            segments:
              type: "integer"
              description: "Segments the message would have been split into."
            encoding:
              type: "string"
              enum:
                - "GSM-7"
                - "UCS-2"
              description: "Alphabet the message would be sent in. One character outside GSM-7 makes the whole message UCS-2."
            maxCharacters:
              type: "integer"
              description: "Units that fit in 3 segments for that encoding: 459 for GSM-7, 201 for UCS-2. A few characters cost two units, so this is a close guide rather than an exact character count. It is the whole budget: with a document attached, its link takes part of it, and `message` names what is left for the text."
          required:
            - "code"
            - "message"
          additionalProperties: false
      required:
        - "success"
        - "error"
      additionalProperties: false
      example:
        success: false
        error:
          code: "SMS_TOO_LONG"
          message: "This SMS is 4 segments. Carriers deliver more than 3 unreliably, so it has to fit about 459 characters. Nothing was sent."
          segments: 4
          encoding: "GSM-7"
          maxCharacters: 459
    ConversationApplicationsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
      additionalProperties: true
      example:
        success: true
        data:
          -
            _id: "66b0a0b0c0d0e0f0a0b0c0d0"
            name: "Refi 2026-05"
            status: "submitted"
            amount: 425000
    ConversationMessageSearchMatch:
      type: "object"
      properties:
        messageId:
          type: "string"
        createdAt:
          type: "string"
          format: "date-time"
      required:
        - "messageId"
        - "createdAt"
      additionalProperties: false
      example:
        messageId: "67e0a0b0c0d0e0f0a0b0c0d0"
        createdAt: "2026-05-18T13:30:00.000Z"
    ConversationMessageSearchResponse:
      type: "object"
      properties:
        matches:
          type: "array"
          items:
            "$ref": "#/components/schemas/ConversationMessageSearchMatch"
        total:
          type: "integer"
        truncated:
          type: "boolean"
          description: "True when results were capped at `limit`"
      required:
        - "matches"
        - "total"
        - "truncated"
      additionalProperties: true
      example:
        matches:
          -
            messageId: "67e0a0b0c0d0e0f0a0b0c0d0"
            createdAt: "2026-05-18T13:30:00.000Z"
          -
            messageId: "67e0a0b0c0d0e0f0a0b0c0d3"
            createdAt: "2026-05-18T13:45:00.000Z"
        total: 2
        truncated: false
    ContactMessageSearchMatch:
      type: "object"
      properties:
        messageId:
          type: "string"
        body:
          type: "string"
        createdAt:
          type: "string"
          format: "date-time"
      required:
        - "messageId"
        - "body"
        - "createdAt"
      additionalProperties: false
      example:
        messageId: "67e0a0b0c0d0e0f0a0b0c0d0"
        body: "Yes please, book the demo."
        createdAt: "2026-05-18T13:30:00.000Z"
    ContactMessageSearchGroup:
      type: "object"
      properties:
        conversationId:
          type: "string"
        channelType:
          type: "string"
        channelIdentifier:
          type: "string"
        subject:
          type: "string"
          nullable: true
        matches:
          type: "array"
          items:
            "$ref": "#/components/schemas/ContactMessageSearchMatch"
      required:
        - "conversationId"
        - "matches"
      additionalProperties: true
      example:
        conversationId: "65d3e0f0a0b0c0d0e0f0a0b0"
        channelType: "sms"
        channelIdentifier: "+14155550123"
        subject: null
        matches:
          -
            messageId: "67e0a0b0c0d0e0f0a0b0c0d0"
            body: "Yes please, book the demo."
            createdAt: "2026-05-18T13:30:00.000Z"
    ContactMessageSearchResponse:
      type: "object"
      properties:
        results:
          type: "array"
          items:
            "$ref": "#/components/schemas/ContactMessageSearchGroup"
        total:
          type: "integer"
        truncated:
          type: "boolean"
      required:
        - "results"
        - "total"
        - "truncated"
      additionalProperties: true
      example:
        results:
          -
            conversationId: "65d3e0f0a0b0c0d0e0f0a0b0"
            channelType: "sms"
            channelIdentifier: "+14155550123"
            matches:
              -
                messageId: "67e0a0b0c0d0e0f0a0b0c0d0"
                body: "Yes please, book the demo."
                createdAt: "2026-05-18T13:30:00.000Z"
        total: 1
        truncated: false
    DepartmentUserDto:
      type: "object"
      properties:
        _id:
          type: "string"
        fullName:
          type: "string"
        email:
          type: "string"
        accessRole:
          type: "string"
        departmentId:
          type: "string"
        phoneNumber:
          type: "string"
        designation:
          type: "string"
      additionalProperties: true
      example:
        _id: "65b1f0a2c3d4e5f6a7b8c9d0"
        fullName: "Alice Rivera"
        email: "alice@example.com"
        accessRole: "AGENT"
        departmentId: "65c1a0b0c0d0e0f0a0b0c0d1"
        phoneNumber: "+14155550100"
        designation: "Sales Rep"
    DepartmentDto:
      type: "object"
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        description:
          type: "string"
        organizationId:
          type: "string"
        managerIds:
          type: "array"
          items:
            "$ref": "#/components/schemas/DepartmentUserDto"
          description: "Populated user objects or string IDs"
        userIds:
          type: "array"
          items:
            "$ref": "#/components/schemas/DepartmentUserDto"
          description: "Populated user objects or string IDs"
        createdBy:
          type: "object"
          description: "Populated user object with fullName and email"
          additionalProperties: true
        updatedBy:
          type: "object"
          description: "Populated user object with fullName and email"
          additionalProperties: true
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "65c1a0b0c0d0e0f0a0b0c0d1"
        name: "Sales"
        description: "Inbound + outbound sales reps"
        organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
        managerIds:
          -
            _id: "65b1f0a2c3d4e5f6a7b8c9e0"
            fullName: "Brenda Lee"
            email: "brenda@example.com"
            accessRole: "ADMIN"
        userIds:
          -
            _id: "65b1f0a2c3d4e5f6a7b8c9d0"
            fullName: "Alice Rivera"
            email: "alice@example.com"
            accessRole: "AGENT"
        createdBy:
          _id: "65b1f0a2c3d4e5f6a7b8c9e0"
          fullName: "Brenda Lee"
          email: "brenda@example.com"
        updatedBy:
          _id: "65b1f0a2c3d4e5f6a7b8c9e0"
          fullName: "Brenda Lee"
          email: "brenda@example.com"
        createdAt: "2026-01-12T09:00:00.000Z"
        updatedAt: "2026-04-04T12:30:00.000Z"
    CreateDepartmentRequest:
      type: "object"
      properties:
        name:
          type: "string"
          description: "Department display name; unique within the organization."
        description:
          type: "string"
          description: "Free-text description of the department's purpose."
        managerIds:
          type: "array"
          items:
            type: "string"
          description: "User `_id`s with MANAGER role inside this department."
        userIds:
          type: "array"
          items:
            type: "string"
          description: "All members of the department (managers + agents)."
      required:
        - "name"
      additionalProperties: true
      example:
        name: "Sales"
        description: "Inbound + outbound sales reps"
        managerIds:
          - "65b1f0a2c3d4e5f6a7b8c9e0"
        userIds:
          - "65b1f0a2c3d4e5f6a7b8c9d0"
          - "65b1f0a2c3d4e5f6a7b8c9d1"
    UpdateDepartmentRequest:
      type: "object"
      properties:
        name:
          type: "string"
          description: "Department display name; unique within the organization."
        description:
          type: "string"
          description: "Free-text description of the department's purpose."
        managerIds:
          type: "array"
          items:
            type: "string"
          description: "User `_id`s with MANAGER role inside this department."
        userIds:
          type: "array"
          items:
            type: "string"
          description: "All members of the department (managers + agents)."
      additionalProperties: true
      example:
        description: "All sales reps, NA + EMEA"
        userIds:
          - "65b1f0a2c3d4e5f6a7b8c9d0"
          - "65b1f0a2c3d4e5f6a7b8c9d1"
          - "65b1f0a2c3d4e5f6a7b8c9d2"
    DepartmentResponse:
      type: "object"
      properties:
        department:
          "$ref": "#/components/schemas/DepartmentDto"
      additionalProperties: true
      example:
        department:
          _id: "65c1a0b0c0d0e0f0a0b0c0d1"
          name: "Sales"
          description: "Inbound + outbound sales reps"
          organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
          createdAt: "2026-01-12T09:00:00.000Z"
          updatedAt: "2026-04-04T12:30:00.000Z"
    DepartmentListResponse:
      type: "object"
      properties:
        departments:
          type: "array"
          items:
            "$ref": "#/components/schemas/DepartmentDto"
      additionalProperties: true
      example:
        departments:
          -
            _id: "65c1a0b0c0d0e0f0a0b0c0d1"
            name: "Sales"
            organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
          -
            _id: "65c1a0b0c0d0e0f0a0b0c0d2"
            name: "Support"
            organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
    DepartmentUsersResponse:
      type: "object"
      properties:
        users:
          type: "array"
          items:
            "$ref": "#/components/schemas/DepartmentUserDto"
        department:
          "$ref": "#/components/schemas/DepartmentDto"
      additionalProperties: true
      example:
        users:
          -
            _id: "65b1f0a2c3d4e5f6a7b8c9d0"
            fullName: "Alice Rivera"
            email: "alice@example.com"
            accessRole: "AGENT"
        department:
          _id: "65c1a0b0c0d0e0f0a0b0c0d1"
          name: "Sales"
          organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
    DepartmentMessageResponse:
      type: "object"
      properties:
        message:
          type: "string"
      additionalProperties: true
      example:
        message: "Department deleted"
    DepartmentErrorResponse:
      type: "object"
      properties:
        error:
          type: "string"
      additionalProperties: true
      example:
        error: "Department with this name already exists"
    TransferScanRequest:
      type: "object"
      properties:
        userId:
          type: "string"
          description: "User `_id` being moved out of their current department."
        targetDepartmentId:
          type: "string"
          description: "Destination department `_id` the user should be reassigned to."
      required:
        - "userId"
        - "targetDepartmentId"
      additionalProperties: false
      example:
        userId: "65b1f0a2c3d4e5f6a7b8c9d0"
        targetDepartmentId: "65c1a0b0c0d0e0f0a0b0c0d1"
    BulkTransferScanRequest:
      type: "object"
      properties:
        assignments:
          type: "array"
          description: "Set of `{ userId, targetDepartmentId }` pairs to scan together (typically every member of a department being deleted)."
          items:
            type: "object"
            properties:
              userId:
                type: "string"
                description: "User `_id` being moved out of their current department."
              targetDepartmentId:
                type: "string"
                description: "Destination department `_id` the user should be reassigned to."
            required:
              - "userId"
              - "targetDepartmentId"
      required:
        - "assignments"
      example:
        assignments:
          -
            userId: "65b1f0a2c3d4e5f6a7b8c9d0"
            targetDepartmentId: "65c1a0b0c0d0e0f0a0b0c0d1"
          -
            userId: "65b2f0a2c3d4e5f6a7b8c9d1"
            targetDepartmentId: "65c1a0b0c0d0e0f0a0b0c0d2"
    TransferExecuteRequest:
      type: "object"
      properties:
        scanVersion:
          type: "string"
          description: "Token from the prior scan; rejected if stale to prevent applying an out-of-date plan."
        assignments:
          type: "array"
          description: "Per-user transfer plan: source userId -> target department / new role / re-assignee."
          items:
            type: "object"
            additionalProperties: true
        deleteSourceDepartmentId:
          type: "string"
          description: "When set, the source department is deleted after the transfer succeeds (must be empty)."
      required:
        - "scanVersion"
        - "assignments"
      additionalProperties: true
      example:
        scanVersion: "v2026-05-18T12:00:00Z-abc123"
        assignments:
          -
            userId: "65b1f0a2c3d4e5f6a7b8c9d0"
            targetDepartmentId: "65c1a0b0c0d0e0f0a0b0c0d1"
        deleteSourceDepartmentId: "65c1a0b0c0d0e0f0a0b0c0d0"
    ScanResultResponse:
      type: "object"
      additionalProperties: true
      example:
        scanVersion: "v2026-05-18T12:00:00Z-abc123"
        summary:
          prompts: 4
          automations: 2
          conversations: 17
          approvalPolicies: 1
        conflicts:
          []
    TransferStatusResponse:
      type: "object"
      properties:
        transferId:
          type: "string"
        status:
          type: "string"
      additionalProperties: true
      example:
        transferId: "65d0a0b0c0d0e0f0a0b0c0d0"
        status: "running"
        progress:
          processed: 5
          total: 24
    TransferErrorResponse:
      type: "object"
      properties:
        error:
          type: "string"
      additionalProperties: true
      example:
        error: "Scan version is stale; please re-scan"
    EmailSyncMessagesRequest:
      type: "object"
      properties:
        accountId:
          type: "string"
          description: "EmailAccount `_id` to sync."
        maxResults:
          type: "number"
          description: "Cap on messages fetched per sync run."
        lookbackDays:
          type: "number"
          nullable: true
          description: "Optional override for the sync window; null = use account default."
      required:
        - "accountId"
      additionalProperties: true
      example:
        accountId: "665f1a0c0e0a4b001a2c9f50"
        maxResults: 500
        lookbackDays: 30
    EmailSendMessageRequest:
      type: "object"
      description: "Payload to send an email through a connected mailbox. The server resolves which mailbox to send from by matching `from` (and optionally `provider`) against the authenticated user's connected email accounts."
      properties:
        from:
          type: "string"
          format: "email"
          description: "Email address of the sending mailbox. Must belong to a mailbox the authenticated user has connected via the OAuth flow (Gmail or Outlook). Example: `aneesh@tetherai.ca`."
          example: "aneesh@tetherai.ca"
        provider:
          type: "string"
          enum:
            - "gmail"
            - "outlook"
          description: "Tie-breaker used only when the same `from` address is connected under more than one provider for the same user. Omit in the common case - the server resolves it automatically."
          example: "gmail"
        to:
          oneOf:
            -
              type: "string"
              format: "email"
            -
              type: "array"
              items:
                type: "string"
                format: "email"
          description: "Recipient address, or an array of recipient addresses. Each entry may be a bare email (`user@x.com`) or RFC 5322 formatted (`\"Name\" <user@x.com>`)."
          example:
            - "recipient@example.com"
        cc:
          type: "array"
          items:
            type: "string"
            format: "email"
          description: "Optional CC recipients. Same format rules as `to`."
        bcc:
          type: "array"
          items:
            type: "string"
            format: "email"
          description: "Optional BCC recipients. Same format rules as `to`."
        subject:
          type: "string"
          description: "Subject line. Optional - when omitted on a reply, the server reuses the subject from the conversation; when omitted on a new thread, `(no subject)` is used."
          example: "Weekly report"
        body:
          type: "string"
          description: "Message body. Plain text by default; set `isHtml: true` to send as HTML. Required."
          example: "Hi - here is the report you asked for."
        isHtml:
          type: "boolean"
          default: false
          description: "When `true`, `body` is sent as `text/html` instead of `text/plain`."
        threadId:
          type: "string"
          description: "Join key to continue an existing email thread. For Gmail this is the Gmail `threadId`; for Outlook it is the `conversationId`. Both are normalised to the same field.\n\n**New email:** omit this field. The server creates a new conversation and the provider assigns a brand-new thread.\n\n**Reply:** pass the thread id of the conversation you want to continue. The provider appends the reply to the same thread, and the server auto-fills `inReplyTo` / `references` from the latest message in that thread.\n\n**How to obtain it:**\n1. From the response of the first `POST /api/email/messages/send` - the body returns `threadId`. Persist it for future replies.\n2. From `GET /api/conversation` (or `/api/conversation/:id`) - the conversation's `channelIdentifier` field holds the email thread id for email-channel conversations.\n3. From a stored message - each email message carries `emailMetadata.threadId` on the Message document.\n\nRecipient address alone is **not** enough to continue a thread, because the same recipient can have multiple unrelated threads."
          example: "gthread-1902a9f3c4b1e0d5"
        inReplyTo:
          type: "string"
          description: "RFC 5322 `In-Reply-To` header - the `Message-ID` of the message being replied to (with angle brackets). Used for threading in recipient clients. If omitted on a reply, the server fills it from the latest message in the thread."
        references:
          type: "string"
          description: "RFC 5322 `References` header - space-separated `Message-ID`s forming the reply chain. If omitted on a reply, the server fills it from the latest message in the thread."
        isInternal:
          type: "boolean"
          description: "Reserved. Must be `false` or omitted on this endpoint. Private notes are posted through the messages endpoint, not the email send endpoint. Sending `true` here returns `400`."
        attachments:
          type: "array"
          description: "File attachments to include. Each entry must supply either `storageKey` (preferred - an R2 storage key produced by the upload endpoint) or a pre-signed `url` the server can GET."
          items:
            type: "object"
            properties:
              storageKey:
                type: "string"
                description: "R2 storage key returned by the upload endpoint. Preferred over `url`. When provided, the server generates a signed URL internally and streams the bytes to the provider."
              url:
                type: "string"
                format: "uri"
                description: "HTTPS URL the server can fetch the attachment bytes from. Use only when `storageKey` is not available (e.g. re-sending an attachment referenced by external URL)."
              filename:
                type: "string"
                description: "File name shown to the recipient. Defaults to `attachment` if omitted."
              contentType:
                type: "string"
                description: "MIME type (e.g. `application/pdf`). If omitted, the server infers it from `filename`."
              size:
                type: "number"
                description: "Size of the attachment in bytes. Informational; the server measures the actual stream."
            additionalProperties: true
      required:
        - "from"
        - "to"
        - "body"
      additionalProperties: true
      example:
        from: "ops@acme.example"
        to:
          - "jamie.lee@example.com"
        subject: "Weekly report"
        body: "Hi Jamie - attaching this week's report."
        isHtml: false
    EmailCreateDraftRequest:
      type: "object"
      properties:
        accountId:
          type: "string"
        contactId:
          type: "string"
          minLength: 1
          description: "Contact `_id` to bind the draft to. When set, the draft is created on this contact instead of resolving one by the `to` address — pass it whenever the contact is already known, since an address shared by several contacts resolves ambiguously."
        to:
          oneOf:
            -
              type: "string"
            -
              type: "array"
              items:
                type: "string"
          description: "String or array of strings"
        subject:
          type: "string"
        cc:
          type: "array"
          items:
            type: "string"
        bcc:
          type: "array"
          items:
            type: "string"
        process:
          type: "string"
          minLength: 1
          description: "Agent/process `_id` to stamp on the draft conversation. Must be a Prompt in the caller’s organization. Defaults to the contact’s process, then the organization default."
        isAutopilot:
          type: "boolean"
          description: "Whether the draft conversation starts with autopilot enabled. Omitted leaves the conversation default."
      required:
        - "accountId"
        - "to"
      additionalProperties: true
      example:
        accountId: "665f1a0c0e0a4b001a2c9f50"
        to: "jamie.lee@example.com"
        subject: "Quick follow-up"
    EmailRehydrateAttachmentsRequest:
      type: "object"
      properties:
        messageId:
          type: "string"
          description: "Tether Message `_id` whose attachments should be re-downloaded from the provider."
      required:
        - "messageId"
      additionalProperties: true
      example:
        messageId: "665f1a0c0e0a4b001a2c9f60"
    EmailWebhookRequest:
      type: "object"
      properties:
        message:
          type: "object"
          description: "Pub/Sub push envelope wrapping the Gmail notification; decoded server-side to identify the affected mailbox."
          properties:
            data:
              type: "string"
              description: "Base64-encoded Pub/Sub notification payload from Gmail."
          additionalProperties: true
      additionalProperties: true
      example:
        message:
          data: "eyJlbWFpbEFkZHJlc3MiOiJvcHNAYWNtZS5leGFtcGxlIiwiaGlzdG9yeUlkIjoxMjM0NTZ9"
    EmailAttachmentStored:
      type: "object"
      description: "An attachment stored on a sent/received email message."
      properties:
        url:
          type: "string"
          description: "R2 storage key (for uploads) or URL of the attachment as persisted on the message."
        originalUrl:
          type: "string"
          description: "Signed URL used to deliver the attachment to the provider at send time. Short-lived."
        contentType:
          type: "string"
          description: "MIME type."
        size:
          type: "number"
          description: "Size in bytes."
        filename:
          type: "string"
          description: "File name shown to the recipient."
      additionalProperties: true
      example:
        url: "org/64ee9a8b1e7f2a0011223344/attachments/report.pdf"
        contentType: "application/pdf"
        size: 184320
        filename: "report.pdf"
    EmailMessageHeaders:
      type: "object"
      description: "RFC 5322 header fields captured on the message."
      properties:
        messageId:
          type: "string"
          description: "RFC 5322 `Message-ID` header of this email (with angle brackets)."
        inReplyTo:
          type: "string"
          description: "RFC 5322 `In-Reply-To` header."
        references:
          type: "string"
          description: "RFC 5322 `References` header (space-separated Message-IDs)."
      additionalProperties: true
      example:
        messageId: "<CAEvDmF0xyz@mail.gmail.com>"
        inReplyTo: "<CAEvDmF0abc@mail.gmail.com>"
        references: "<CAEvDmF0abc@mail.gmail.com> <CAEvDmF0def@mail.gmail.com>"
    EmailMessageEmailMetadata:
      type: "object"
      description: "Email-specific fields attached to a Message when `channelType` is `email`."
      properties:
        accountId:
          type: "string"
          description: "Internal id of the EmailAccount that sent or received this message. Not part of the public API surface - use `from` to identify the mailbox."
        externalMessageId:
          type: "string"
          description: "Provider-side message id (Gmail `id` or Outlook `id`). Use together with the provider to re-fetch the raw message."
        from:
          type: "string"
          format: "email"
          description: "Sender address."
        to:
          type: "array"
          items:
            type: "string"
            format: "email"
          description: "Recipient addresses."
        cc:
          type: "array"
          items:
            type: "string"
            format: "email"
        bcc:
          type: "array"
          items:
            type: "string"
            format: "email"
        snippet:
          type: "string"
          description: "Short plain-text preview of the message body, produced by the provider."
        subject:
          type: "string"
          description: "Subject line of this specific email message. May differ from the conversation subject if the subject changed mid-thread."
        bodyHtml:
          type: "string"
          description: "HTML body of the message (if available)."
        headers:
          "$ref": "#/components/schemas/EmailMessageHeaders"
      additionalProperties: true
      example:
        accountId: "665f1a0c0e0a4b001a2c9f50"
        externalMessageId: "1902a9f3c4b1e0d5"
        from: "ops@acme.example"
        to:
          - "jamie.lee@example.com"
        cc:
          []
        bcc:
          []
        snippet: "Hi Jamie - attaching this week's report..."
        subject: "Weekly report"
    EmailMessage:
      type: "object"
      description: "Stored email message document (the `message` field on the send response)."
      properties:
        _id:
          type: "string"
          description: "Internal message id (MongoDB ObjectId)."
        organizationId:
          type: "string"
        conversationId:
          type: "string"
          description: "Conversation the message belongs to."
        contactId:
          type: "string"
          description: "Contact (recipient) the conversation is bound to."
        userId:
          type: "string"
          description: "Owning user."
        channelType:
          type: "string"
          enum:
            - "email"
          description: "Always `email` for this endpoint."
        isIncoming:
          type: "boolean"
          description: "Always `false` for messages produced by this endpoint (outbound)."
        isInternal:
          type: "boolean"
          description: "Always `false` on this endpoint. Private notes use a different route."
        status:
          type: "string"
          enum:
            - "pending"
            - "sending"
            - "queued"
            - "dispatched"
            - "delivered"
            - "failed"
            - "rejected"
            - "aborted"
          description: "Delivery status. `delivered` on a successful send."
        body:
          type: "string"
          description: "Plain-text body persisted on the message (parsed from the provider response)."
        attachments:
          type: "array"
          items:
            "$ref": "#/components/schemas/EmailAttachmentStored"
        emailMetadata:
          "$ref": "#/components/schemas/EmailMessageEmailMetadata"
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "665f1a0c0e0a4b001a2c9f60"
        organizationId: "64ee9a8b1e7f2a0011223344"
        conversationId: "665f1a0c0e0a4b001a2c9f70"
        contactId: "665f1a0c0e0a4b001a2c9f01"
        userId: "64ee9a8b1e7f2a0011223399"
        channelType: "email"
        isIncoming: false
        isInternal: false
        status: "delivered"
        body: "Hi Jamie - attaching this week's report."
        attachments:
          []
        createdAt: "2026-05-18T12:34:56.000Z"
        updatedAt: "2026-05-18T12:34:56.000Z"
    EmailOAuthCallbackErrorResponse:
      type: "object"
      description: "Error envelope returned by `GET /api/email/oauth/callback` only on the pre-redirect validation failures (missing/invalid `code` or `state`). Downstream provider exchange failures redirect with `status=error` instead of returning JSON."
      properties:
        message:
          type: "string"
        error:
          type: "string"
      additionalProperties: true
      example:
        message: "Missing code or state"
        error: "bad_request"
    EmailAuthorizeUrlResponse:
      type: "object"
      description: "Response from `GET /api/email/oauth/authorize`."
      properties:
        authUrl:
          type: "string"
          format: "uri"
          description: "Fully-qualified provider-hosted authorization URL. Frontends open this in a new window or top-level navigation; the provider will redirect to `/api/email/oauth/callback` once the user consents."
      required:
        - "authUrl"
      additionalProperties: true
      example:
        authUrl: "https://accounts.google.com/o/oauth2/v2/auth?client_id=...&redirect_uri=https%3A%2F%2Frelay.example%2Fapi%2Femail%2Foauth%2Fcallback&scope=...&state=..."
    EmailProviderAvailabilityResponse:
      type: "object"
      description: "Boolean map indicating which email providers have OAuth credentials configured on this backend. Absent or `false` means the provider cannot be used for new connections (the relay was deployed without that provider's client id/secret)."
      properties:
        gmail:
          type: "boolean"
          description: "Gmail OAuth is configured."
        outlook:
          type: "boolean"
          description: "Outlook OAuth is configured."
      required:
        - "gmail"
        - "outlook"
      additionalProperties: true
      example:
        gmail: true
        outlook: false
    EmailAccountDto:
      type: "object"
      description: "A connected mailbox. Returned by `GET /api/email/accounts`. OAuth `tokens` are intentionally stripped from this projection."
      properties:
        _id:
          type: "string"
          description: "Internal `EmailAccount` id."
        organizationId:
          type: "string"
        provider:
          type: "string"
          enum:
            - "gmail"
            - "outlook"
          description: "Email provider this account is connected through."
        providerAccountId:
          type: "string"
          description: "Stable provider-side identifier for this mailbox (Google sub / Microsoft id)."
        emailAddress:
          type: "string"
          format: "email"
          description: "Normalised (lowercase) mailbox address."
        isActive:
          type: "boolean"
          description: "`true` while the account participates in sync."
        historyId:
          type: "string"
          description: "Gmail history cursor or Outlook subscription id used for incremental sync / push-notification wiring."
        watchExpiration:
          type: "string"
          format: "date-time"
          description: "When the mailbox watch / subscription expires and must be renewed."
        linkedType:
          type: "string"
          enum:
            - "user"
            - "group"
          description: "Which link field is set. The link is the inbound destination."
        linkedUserId:
          type: "string"
        linkedGroupId:
          type: "string"
        connectedByUserId:
          type: "string"
          description: "Who connected the mailbox."
        via:
          type: "string"
          nullable: true
          enum:
            - "link"
            - "group"
            - "grant"
            - null
          description: "How the caller reaches this mailbox for sending: `link` (linked to them or connected by them), `group` (linked to a group they belong to) or `grant` (shared with them, their department or one of their groups). `null` on a mailbox an admin sees only because of their role. Returned by `GET /api/email/accounts` only."
        verbs:
          type: "array"
          items:
            type: "string"
            enum:
              - "send"
          description: "The verbs the caller holds on this mailbox through `via`. Mailboxes take send grants only, and a link or connection gives send, so this is `[\"send\"]` whenever `via` is set and `[]` when `via` is `null` (an admin row, sendable through the role). Returned by `GET /api/email/accounts` only."
        grants:
          type: "array"
          items:
            "$ref": "#/components/schemas/ResourceGrant"
          description: "Who else may send from this mailbox (send grants only). Absent on a mailbox that predates grants."
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "665f1a0c0e0a4b001a2c9f50"
        organizationId: "64ee9a8b1e7f2a0011223344"
        provider: "gmail"
        providerAccountId: "107834928382923743821"
        emailAddress: "ops@acme.example"
        isActive: true
        historyId: "123456"
        watchExpiration: "2026-05-25T00:00:00.000Z"
        createdAt: "2026-05-01T09:00:00.000Z"
        updatedAt: "2026-05-18T12:00:00.000Z"
    EmailAccountListResponse:
      type: "object"
      description: "Response from `GET /api/email/accounts`."
      properties:
        accounts:
          type: "array"
          items:
            "$ref": "#/components/schemas/EmailAccountDto"
          description: "Active connected mailboxes for the authenticated user, newest-first."
      required:
        - "accounts"
      additionalProperties: true
      example:
        accounts:
          -
            _id: "665f1a0c0e0a4b001a2c9f50"
            provider: "gmail"
            emailAddress: "ops@acme.example"
            isActive: true
            via: "grant"
            verbs:
              - "send"
    OrgEmailAccountRow:
      allOf:
        -
          "$ref": "#/components/schemas/EmailAccountDto"
        -
          type: "object"
          properties:
            linkedUserName:
              type: "string"
              nullable: true
            linkedUserEmail:
              type: "string"
              nullable: true
            linkedGroupName:
              type: "string"
              nullable: true
    OrgEmailAccountListResponse:
      type: "object"
      description: "Response from `GET /api/organizations/{organizationId}/email-accounts`."
      properties:
        accounts:
          type: "array"
          items:
            "$ref": "#/components/schemas/OrgEmailAccountRow"
      required:
        - "accounts"
      additionalProperties: true
      example:
        accounts:
          -
            _id: "665f1a0c0e0a4b001a2c9f50"
            provider: "gmail"
            emailAddress: "leasing@acme.example"
            isActive: true
            linkedType: "group"
            linkedGroupId: "6650a1b2c3d4e5f6a7b8c9d2"
            linkedGroupName: "Leasing"
            grants:
              -
                principalType: "department"
                principalId: "6650a1b2c3d4e5f6a7b8c9d3"
                key: "dept:6650a1b2c3d4e5f6a7b8c9d3"
                verbs:
                  - "send"
                grantedBy:
                  type: "user"
                  userId: "6650a1b2c3d4e5f6a7b8c9d0"
                grantedAt: "2026-09-30T12:00:00.000Z"
    UpdateOrgEmailAccountRequest:
      type: "object"
      properties:
        grants:
          type: "array"
          maxItems: 200
          items:
            "$ref": "#/components/schemas/ResourceGrantInput"
          description: "The complete grant list. Replaces what is stored; `[]` removes every grant; omit to change nothing. Each grant's `verbs` must be `[\"send\"]`: mailboxes do not accept `read` grants yet. `key`, `grantedBy` and `grantedAt` are set by the server and ignored if sent."
      additionalProperties: true
      example:
        grants:
          -
            principalType: "user"
            principalId: "6650a1b2c3d4e5f6a7b8c9d4"
            verbs:
              - "send"
          -
            principalType: "department"
            principalId: "6650a1b2c3d4e5f6a7b8c9d3"
            verbs:
              - "send"
    OrgEmailAccountUpdateResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        account:
          "$ref": "#/components/schemas/EmailAccountDto"
      required:
        - "success"
        - "account"
      additionalProperties: true
    EmailAccountDisconnectResponse:
      type: "object"
      description: "Response from `DELETE /api/email/accounts/{accountId}`."
      properties:
        success:
          type: "boolean"
          enum:
            - true
      required:
        - "success"
      additionalProperties: true
      example:
        success: true
    EmailSyncStatusResponse:
      type: "object"
      description: "Response from `GET /api/email/messages/sync/status`."
      properties:
        accountId:
          type: "string"
          description: "The account this status belongs to."
        inProgress:
          type: "boolean"
          description: "True while a historical sync is currently running."
        lastSyncedAt:
          type: "string"
          format: "date-time"
          nullable: true
          description: "Timestamp of the most recent successful sync, or `null` if none has completed."
        messagesProcessed:
          type: "integer"
          description: "Cumulative count of messages persisted by the latest sync run."
        totalEstimated:
          type: "integer"
          nullable: true
          description: "Best-effort estimate of total messages the sync will touch, or `null` when the provider does not expose a count."
        error:
          type: "string"
          nullable: true
          description: "Last error message if the most recent run failed; otherwise omitted."
      additionalProperties: true
      example:
        accountId: "665f1a0c0e0a4b001a2c9f50"
        inProgress: false
        lastSyncedAt: "2026-05-18T12:00:00.000Z"
        messagesProcessed: 423
        totalEstimated: 423
        error: null
    EmailSendMessageResponse:
      type: "object"
      description: "Success response for `POST /api/email/messages/send`."
      properties:
        message:
          "$ref": "#/components/schemas/EmailMessage"
        conversationId:
          type: "string"
          description: "Internal id of the conversation the message was appended to (or created, on a new thread). Use this with `GET /api/conversation/:id` to fetch the full conversation."
        threadId:
          type: "string"
          description: "Provider-side thread id for this email (Gmail `threadId` / Outlook `conversationId`). **Save this** - pass it back as `threadId` on subsequent `POST /api/email/messages/send` calls to continue the same thread."
          example: "gthread-1902a9f3c4b1e0d5"
      required:
        - "message"
        - "conversationId"
      additionalProperties: true
      example:
        message:
          _id: "665f1a0c0e0a4b001a2c9f60"
          channelType: "email"
          status: "delivered"
          body: "Hi Jamie - attaching this week's report."
        conversationId: "665f1a0c0e0a4b001a2c9f70"
        threadId: "gthread-1902a9f3c4b1e0d5"
    EmailErrorResponse:
      type: "object"
      description: "Error envelope returned by Email feature endpoints. Most paths only set `error`; a few include `code` for diagnostic context (e.g. provider mismatches)."
      properties:
        error:
          type: "string"
        message:
          type: "string"
        code:
          type: "string"
      required:
        - "error"
      additionalProperties: true
      example:
        error: "Email account not found"
    EmailSyncStartedResponse:
      type: "object"
      description: "Returned immediately after `POST /api/email/messages/sync` kicks off the historical sync. Poll `GET /api/email/messages/sync/status` for progress."
      properties:
        status:
          type: "string"
          enum:
            - "running"
      required:
        - "status"
      additionalProperties: true
      example:
        status: "running"
    EmailDraftConversation:
      type: "object"
      description: "Draft conversation document returned after creating an email draft. Marked with `isDraft:true` until the user sends."
      properties:
        _id:
          type: "string"
        organizationId:
          type: "string"
        contactId:
          type: "string"
        userId:
          type: "string"
        channelType:
          type: "string"
          enum:
            - "email"
        emailAccountId:
          type: "string"
        isDraft:
          type: "boolean"
          enum:
            - true
        subject:
          type: "string"
        provider:
          type: "string"
        participants:
          type: "object"
          properties:
            from:
              type: "string"
            to:
              type: "array"
              items:
                type: "string"
            cc:
              type: "array"
              items:
                type: "string"
            bcc:
              type: "array"
              items:
                type: "string"
          additionalProperties: true
        lastMessageTime:
          type: "string"
          format: "date-time"
        source:
          type: "string"
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      required:
        - "_id"
        - "channelType"
        - "isDraft"
        - "subject"
        - "participants"
      additionalProperties: true
      example:
        _id: "665f1a0c0e0a4b001a2c9f70"
        organizationId: "64a1b2c3d4e5f60012345678"
        contactId: "64b2c3d4e5f60012345678aa"
        userId: "64a1b2c3d4e5f60012345679"
        channelType: "email"
        emailAccountId: "64d2f9c5e8a1d4e001a0b1c2"
        isDraft: true
        subject: "Follow-up: Maple Court"
        provider: "gmail"
        participants:
          from: "leasing@acme.example"
          to:
            - "alex.morgan@example.com"
        source: "New Email"
        createdAt: "2026-05-20T15:04:01.135Z"
        updatedAt: "2026-05-20T15:04:01.135Z"
    EmailCreateDraftResponse:
      type: "object"
      description: "Returned after `POST /api/email/messages/draft` creates a draft conversation."
      properties:
        conversationId:
          type: "string"
        conversation:
          "$ref": "#/components/schemas/EmailDraftConversation"
      required:
        - "conversationId"
        - "conversation"
      additionalProperties: true
      example:
        conversationId: "665f1a0c0e0a4b001a2c9f70"
        conversation:
          _id: "665f1a0c0e0a4b001a2c9f70"
          channelType: "email"
          isDraft: true
          subject: "Follow-up: Maple Court"
          participants:
            from: "leasing@acme.example"
            to:
              - "alex.morgan@example.com"
    EmailRehydrateAttachmentsResponse:
      type: "object"
      description: "Returned after `POST /api/email/messages/attachments/rehydrate` re-uploads provider-side attachments into R2. Includes the updated message and the count of re-uploaded attachments."
      properties:
        message:
          type: "object"
          description: "Updated email message document with refreshed attachment URLs."
          additionalProperties: true
        rehydrated:
          type: "integer"
          description: "Number of attachments re-uploaded."
      required:
        - "message"
        - "rehydrated"
      additionalProperties: true
      example:
        message:
          _id: "665f1a0c0e0a4b001a2c9f60"
          conversationId: "665f1a0c0e0a4b001a2c9f70"
          channelType: "email"
          body: "Attached the signed lease for review."
          attachments:
            -
              url: "https://r2.tetherai.ca/org-64a1b/email/lease.pdf?signature=..."
              contentType: "application/pdf"
              size: 184320
              filename: "lease.pdf"
        rehydrated: 1
    EscalationDashboardError:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
        error:
          type: "string"
      required:
        - "success"
        - "message"
      additionalProperties: true
      example:
        success: false
        message: "Access denied"
    EscalationPagination:
      type: "object"
      properties:
        page:
          type: "integer"
        limit:
          type: "integer"
        total:
          type: "integer"
        totalPages:
          type: "integer"
      required:
        - "page"
        - "limit"
        - "total"
        - "totalPages"
      additionalProperties: false
      example:
        page: 1
        limit: 20
        total: 143
        totalPages: 8
    EscalationStats:
      type: "object"
      properties:
        onlineAgents:
          type: "integer"
        availableAgents:
          type: "integer"
        queueLength:
          type: "integer"
        assignedToday:
          type: "integer"
        avgWaitTimeMs:
          type: "integer"
          description: "Rolling 7-day average wait-time in milliseconds for queue-sourced assignments."
      required:
        - "onlineAgents"
        - "availableAgents"
        - "queueLength"
        - "assignedToday"
        - "avgWaitTimeMs"
      additionalProperties: false
      example:
        onlineAgents: 7
        availableAgents: 3
        queueLength: 4
        assignedToday: 28
        avgWaitTimeMs: 84500
    EscalationStatsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          "$ref": "#/components/schemas/EscalationStats"
      required:
        - "success"
        - "data"
      additionalProperties: false
      example:
        success: true
        data:
          onlineAgents: 7
          availableAgents: 3
          queueLength: 4
          assignedToday: 28
          avgWaitTimeMs: 84500
    AgentStatus:
      type: "object"
      properties:
        _id:
          type: "string"
        fullName:
          type: "string"
        email:
          type: "string"
        avatarUrl:
          type: "string"
          nullable: true
        departmentId:
          type: "string"
          nullable: true
        departmentName:
          type: "string"
          nullable: true
        isOnline:
          type: "boolean"
        isAvailable:
          type: "boolean"
        unresolvedChats:
          type: "integer"
        maxChats:
          type: "integer"
          nullable: true
          description: "null = unlimited (org has maxUnresolvedChatsPerAgent set to 0 or below)."
        lastAssignedAt:
          type: "string"
          format: "date-time"
          nullable: true
        lastAvailableAt:
          type: "string"
          format: "date-time"
          nullable: true
      required:
        - "_id"
        - "fullName"
        - "email"
        - "isOnline"
        - "isAvailable"
        - "unresolvedChats"
      additionalProperties: true
      example:
        _id: "5f7b1c2e8a1d4e0012c3b4a5"
        fullName: "Sam Patel"
        email: "sam.patel@acme.example"
        avatarUrl: "https://r2.example.com/avatars/sam.png"
        departmentId: "6a8c2d3f9b1e5a0023d4c5b6"
        departmentName: "Customer Success"
        isOnline: true
        isAvailable: true
        unresolvedChats: 2
        maxChats: 5
        lastAssignedAt: "2026-05-18T14:31:02.000Z"
        lastAvailableAt: "2026-05-18T13:00:00.000Z"
    AgentStatusesResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/AgentStatus"
      required:
        - "success"
        - "data"
      additionalProperties: false
      example:
        success: true
        data:
          -
            _id: "5f7b1c2e8a1d4e0012c3b4a5"
            fullName: "Sam Patel"
            email: "sam.patel@acme.example"
            isOnline: true
            isAvailable: true
            unresolvedChats: 2
            maxChats: 5
            lastAssignedAt: "2026-05-18T14:31:02.000Z"
    AvailabilityTimelineState:
      type: "string"
      enum:
        - "available"
        - "at_capacity"
        - "online"
        - "offline"
        - "mixed"
      example: "available"
    AvailabilityAggregateBucket:
      type: "object"
      properties:
        state:
          "$ref": "#/components/schemas/AvailabilityTimelineState"
        onlineUserIds:
          type: "array"
          items:
            type: "string"
        availableUserIds:
          type: "array"
          items:
            type: "string"
        atCapacityUserIds:
          type: "array"
          items:
            type: "string"
        userDurations:
          type: "array"
          items:
            type: "object"
            properties:
              userId:
                type: "string"
              onlineMs:
                type: "integer"
              availableMs:
                type: "integer"
              atCapacityMs:
                type: "integer"
            required:
              - "userId"
              - "onlineMs"
              - "availableMs"
              - "atCapacityMs"
            additionalProperties: false
      required:
        - "state"
        - "onlineUserIds"
        - "availableUserIds"
        - "atCapacityUserIds"
        - "userDurations"
      additionalProperties: false
      example:
        state: "available"
        onlineUserIds:
          - "5f7b1c2e8a1d4e0012c3b4a5"
          - "6a8c2d3f9b1e5a0023d4c5b6"
        availableUserIds:
          - "5f7b1c2e8a1d4e0012c3b4a5"
        atCapacityUserIds:
          []
        userDurations:
          -
            userId: "5f7b1c2e8a1d4e0012c3b4a5"
            onlineMs: 900000
            availableMs: 720000
            atCapacityMs: 0
    AvailabilityTimelineUser:
      type: "object"
      properties:
        _id:
          type: "string"
        fullName:
          type: "string"
        email:
          type: "string"
      required:
        - "_id"
        - "fullName"
        - "email"
      additionalProperties: false
      example:
        _id: "5f7b1c2e8a1d4e0012c3b4a5"
        fullName: "Sam Patel"
        email: "sam.patel@acme.example"
    AvailabilityTimelineData:
      type: "object"
      properties:
        start:
          type: "string"
          format: "date-time"
        end:
          type: "string"
          format: "date-time"
        bucketMinutes:
          type: "integer"
        buckets:
          type: "array"
          items:
            type: "string"
            format: "date-time"
          description: "ISO-8601 timestamps for the start of each bucket."
        agents:
          type: "object"
          description: "Map of userId -> dominant TimelineState per bucket (same length as `buckets`)."
          additionalProperties:
            type: "array"
            items:
              "$ref": "#/components/schemas/AvailabilityTimelineState"
        aggregate:
          type: "array"
          items:
            "$ref": "#/components/schemas/AvailabilityAggregateBucket"
        users:
          type: "array"
          items:
            "$ref": "#/components/schemas/AvailabilityTimelineUser"
      required:
        - "start"
        - "end"
        - "bucketMinutes"
        - "buckets"
        - "agents"
        - "aggregate"
        - "users"
      additionalProperties: false
      example:
        start: "2026-05-18T00:00:00.000Z"
        end: "2026-05-18T15:00:00.000Z"
        bucketMinutes: 15
        buckets:
          - "2026-05-18T14:30:00.000Z"
          - "2026-05-18T14:45:00.000Z"
        agents:
          "5f7b1c2e8a1d4e0012c3b4a5":
            - "available"
            - "at_capacity"
        aggregate:
          -
            state: "available"
            onlineUserIds:
              - "5f7b1c2e8a1d4e0012c3b4a5"
            availableUserIds:
              - "5f7b1c2e8a1d4e0012c3b4a5"
            atCapacityUserIds:
              []
            userDurations:
              []
        users:
          -
            _id: "5f7b1c2e8a1d4e0012c3b4a5"
            fullName: "Sam Patel"
            email: "sam.patel@acme.example"
    AvailabilityTimelineResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          "$ref": "#/components/schemas/AvailabilityTimelineData"
      required:
        - "success"
        - "data"
      additionalProperties: false
      example:
        success: true
        data:
          start: "2026-05-18T00:00:00.000Z"
          end: "2026-05-18T15:00:00.000Z"
          bucketMinutes: 15
          buckets:
            - "2026-05-18T14:30:00.000Z"
          agents:
            "5f7b1c2e8a1d4e0012c3b4a5":
              - "available"
          aggregate:
            []
          users:
            []
    AvailabilityEvent:
      type: "object"
      properties:
        _id:
          type: "string"
        userId:
          type: "string"
        userName:
          type: "string"
        userEmail:
          type: "string"
          nullable: true
        category:
          type: "string"
          enum:
            - "connection"
            - "availability"
            - "capacity"
        value:
          type: "string"
          enum:
            - "online"
            - "offline"
            - "available"
            - "unavailable"
            - "at_capacity"
            - "has_capacity"
        source:
          type: "string"
          nullable: true
          enum:
            - "socket"
            - "toggle"
            - "auto_away"
            - "assignment"
            - "resolution"
            - "system"
            - null
        occurredAt:
          type: "string"
          format: "date-time"
      required:
        - "_id"
        - "userId"
        - "userName"
        - "category"
        - "value"
        - "occurredAt"
      additionalProperties: false
      example:
        _id: "7b2c4e0d9f1a3b4e5c6d7e8f9012"
        userId: "5f7b1c2e8a1d4e0012c3b4a5"
        userName: "Sam Patel"
        userEmail: "sam.patel@acme.example"
        category: "availability"
        value: "available"
        source: "toggle"
        occurredAt: "2026-05-18T14:31:02.000Z"
    AvailabilityEventsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            events:
              type: "array"
              items:
                "$ref": "#/components/schemas/AvailabilityEvent"
            pagination:
              "$ref": "#/components/schemas/EscalationPagination"
          required:
            - "events"
            - "pagination"
          additionalProperties: false
      required:
        - "success"
        - "data"
      additionalProperties: false
      example:
        success: true
        data:
          events:
            -
              _id: "7b2c4e0d9f1a3b4e5c6d7e8f9012"
              userId: "5f7b1c2e8a1d4e0012c3b4a5"
              userName: "Sam Patel"
              category: "availability"
              value: "available"
              source: "toggle"
              occurredAt: "2026-05-18T14:31:02.000Z"
          pagination:
            page: 1
            limit: 50
            total: 143
            totalPages: 3
    EscalationQueueItem:
      type: "object"
      properties:
        conversationId:
          type: "string"
        contactId:
          type: "string"
        contactName:
          type: "string"
        contactPhone:
          type: "string"
          nullable: true
        automationId:
          type: "string"
        automationName:
          type: "string"
        queuedAt:
          type: "string"
          format: "date-time"
        waitTimeMs:
          type: "integer"
        hasAccess:
          type: "boolean"
          description: "True when the caller has permission to open the conversation (ownership/assignment/role)."
      required:
        - "conversationId"
        - "contactId"
        - "contactName"
        - "automationId"
        - "automationName"
        - "queuedAt"
        - "waitTimeMs"
        - "hasAccess"
      additionalProperties: false
      example:
        conversationId: "8c3d4e0f9a1b3c4d5e6f7a8b9c01"
        contactId: "9d4e5f1a2b3c4d5e6f7a8b9c0d12"
        contactName: "Alex Morgan"
        contactPhone: "+14165550100"
        automationId: "5f7b1c2e8a1d4e0012c3b4a5"
        automationName: "Inbound Support"
        queuedAt: "2026-05-18T14:25:31.000Z"
        waitTimeMs: 331000
        hasAccess: true
    EscalationQueueResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/EscalationQueueItem"
      required:
        - "success"
        - "data"
      additionalProperties: false
      example:
        success: true
        data:
          -
            conversationId: "8c3d4e0f9a1b3c4d5e6f7a8b9c01"
            contactId: "9d4e5f1a2b3c4d5e6f7a8b9c0d12"
            contactName: "Alex Morgan"
            contactPhone: "+14165550100"
            automationId: "5f7b1c2e8a1d4e0012c3b4a5"
            automationName: "Inbound Support"
            queuedAt: "2026-05-18T14:25:31.000Z"
            waitTimeMs: 331000
            hasAccess: true
    AssignmentHistoryItem:
      type: "object"
      properties:
        _id:
          type: "string"
        conversationId:
          type: "string"
        contactId:
          type: "string"
        contactName:
          type: "string"
        contactPhone:
          type: "string"
          nullable: true
        assigneeId:
          type: "string"
        assigneeName:
          type: "string"
        assigneeAvatarUrl:
          type: "string"
          nullable: true
        automationId:
          type: "string"
        automationName:
          type: "string"
        source:
          type: "string"
          enum:
            - "direct"
            - "queue"
          description: "`direct` = assigned immediately, `queue` = pulled from the waiting queue."
        assignedAt:
          type: "string"
          format: "date-time"
        waitTimeMs:
          type: "integer"
          nullable: true
        firstHumanMessageAt:
          type: "string"
          format: "date-time"
          nullable: true
        firstHumanResponseMs:
          type: "integer"
          nullable: true
        departmentName:
          type: "string"
          nullable: true
        hasAccess:
          type: "boolean"
      required:
        - "_id"
        - "conversationId"
        - "contactId"
        - "contactName"
        - "assigneeId"
        - "assigneeName"
        - "automationId"
        - "automationName"
        - "source"
        - "assignedAt"
        - "hasAccess"
      additionalProperties: false
      example:
        _id: "ab12cd34ef56789012345678"
        conversationId: "8c3d4e0f9a1b3c4d5e6f7a8b9c01"
        contactId: "9d4e5f1a2b3c4d5e6f7a8b9c0d12"
        contactName: "Alex Morgan"
        contactPhone: "+14165550100"
        assigneeId: "5f7b1c2e8a1d4e0012c3b4a5"
        assigneeName: "Sam Patel"
        assigneeAvatarUrl: "https://r2.example.com/avatars/sam.png"
        automationId: "5f7b1c2e8a1d4e0012c3b4a5"
        automationName: "Inbound Support"
        source: "queue"
        assignedAt: "2026-05-18T14:31:02.000Z"
        waitTimeMs: 331000
        firstHumanMessageAt: "2026-05-18T14:32:12.000Z"
        firstHumanResponseMs: 70000
        departmentName: "Customer Success"
        hasAccess: true
    AssignmentHistoryResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            assignments:
              type: "array"
              items:
                "$ref": "#/components/schemas/AssignmentHistoryItem"
            pagination:
              "$ref": "#/components/schemas/EscalationPagination"
          required:
            - "assignments"
            - "pagination"
          additionalProperties: false
      required:
        - "success"
        - "data"
      additionalProperties: false
      example:
        success: true
        data:
          assignments:
            -
              _id: "ab12cd34ef56789012345678"
              conversationId: "8c3d4e0f9a1b3c4d5e6f7a8b9c01"
              contactId: "9d4e5f1a2b3c4d5e6f7a8b9c0d12"
              contactName: "Alex Morgan"
              assigneeId: "5f7b1c2e8a1d4e0012c3b4a5"
              assigneeName: "Sam Patel"
              automationId: "5f7b1c2e8a1d4e0012c3b4a5"
              automationName: "Inbound Support"
              source: "queue"
              assignedAt: "2026-05-18T14:31:02.000Z"
              hasAccess: true
          pagination:
            page: 1
            limit: 20
            total: 143
            totalPages: 8
    FilterOptionsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            users:
              type: "array"
              items:
                type: "object"
                properties:
                  _id:
                    type: "string"
                  fullName:
                    type: "string"
                required:
                  - "_id"
                  - "fullName"
                additionalProperties: false
            automations:
              type: "array"
              items:
                type: "object"
                properties:
                  _id:
                    type: "string"
                  name:
                    type: "string"
                required:
                  - "_id"
                  - "name"
                additionalProperties: false
            departments:
              type: "array"
              description: "Empty for non-ADMIN/SUPERADMIN callers."
              items:
                type: "object"
                properties:
                  _id:
                    type: "string"
                  name:
                    type: "string"
                required:
                  - "_id"
                  - "name"
                additionalProperties: false
          required:
            - "users"
            - "automations"
            - "departments"
          additionalProperties: false
      required:
        - "success"
        - "data"
      additionalProperties: false
      example:
        success: true
        data:
          users:
            -
              _id: "5f7b1c2e8a1d4e0012c3b4a5"
              fullName: "Sam Patel"
          automations:
            -
              _id: "5f7b1c2e8a1d4e0012c3b4a5"
              name: "Inbound Support"
          departments:
            -
              _id: "6a8c2d3f9b1e5a0023d4c5b6"
              name: "Customer Success"
    AgentConversationRow:
      type: "object"
      properties:
        conversationId:
          type: "string"
        contactId:
          type: "string"
          nullable: true
        contactName:
          type: "string"
        contactPhone:
          type: "string"
          nullable: true
        channelType:
          type: "string"
        lastMessageTime:
          type: "string"
          format: "date-time"
          nullable: true
        lastMessagePreview:
          type: "string"
          nullable: true
          description: "Truncated to 80 characters."
        conversationState:
          type: "string"
          description: "Derived conversation state (e.g. autopilot / awaiting-human / resolved)."
        hasAccess:
          type: "boolean"
      required:
        - "conversationId"
        - "contactName"
        - "channelType"
        - "conversationState"
        - "hasAccess"
      additionalProperties: true
      example:
        conversationId: "8c3d4e0f9a1b3c4d5e6f7a8b9c01"
        contactId: "9d4e5f1a2b3c4d5e6f7a8b9c0d12"
        contactName: "Alex Morgan"
        contactPhone: "+14165550100"
        channelType: "sms"
        lastMessageTime: "2026-05-18T14:32:12.000Z"
        lastMessagePreview: "Thanks! That worked."
        conversationState: "awaiting-human"
        hasAccess: true
    AgentConversationsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            rows:
              type: "array"
              items:
                "$ref": "#/components/schemas/AgentConversationRow"
            pagination:
              "$ref": "#/components/schemas/EscalationPagination"
          required:
            - "rows"
            - "pagination"
          additionalProperties: false
      required:
        - "success"
        - "data"
      additionalProperties: false
      example:
        success: true
        data:
          rows:
            -
              conversationId: "8c3d4e0f9a1b3c4d5e6f7a8b9c01"
              contactId: "9d4e5f1a2b3c4d5e6f7a8b9c0d12"
              contactName: "Alex Morgan"
              contactPhone: "+14165550100"
              channelType: "sms"
              lastMessageTime: "2026-05-18T14:32:12.000Z"
              lastMessagePreview: "Thanks! That worked."
              conversationState: "awaiting-human"
              hasAccess: true
          pagination:
            page: 1
            limit: 20
            total: 12
            totalPages: 1
    EventLogDto:
      type: "object"
      description: "A persisted EventLog record. Most fields come straight from the EventLog model; `contactFirstName`/`contactLastName` are joined in by the controller for the list view."
      properties:
        _id:
          type: "string"
        organizationId:
          type: "string"
        userId:
          type: "string"
        contactId:
          type: "string"
          nullable: true
        conversationId:
          type: "string"
          nullable: true
        direction:
          type: "string"
          description: "Direction or category of the logged event (e.g. inbound/outbound)."
        automationTriggered:
          type: "boolean"
        eventType:
          type: "string"
        payload:
          type: "object"
          additionalProperties: true
          description: "Raw event payload - shape varies by event type."
        contactFirstName:
          type: "string"
          nullable: true
          description: "Joined-in contact first name (list view only)."
        contactLastName:
          type: "string"
          nullable: true
          description: "Joined-in contact last name (list view only)."
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "65e0a0b0c0d0e0f0a0b0c0d0"
        organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
        userId: "65b1f0a2c3d4e5f6a7b8c9d0"
        contactId: "65c2d0e0f0a0b0c0d0e0f0a0"
        conversationId: "65d3e0f0a0b0c0d0e0f0a0b0"
        direction: "inbound"
        automationTriggered: true
        eventType: "message.received"
        payload:
          channelType: "sms"
          body: "Yes please!"
        contactFirstName: "Jane"
        contactLastName: "Doe"
        createdAt: "2026-05-18T14:30:00.000Z"
        updatedAt: "2026-05-18T14:30:00.000Z"
    EventLogPagination:
      type: "object"
      properties:
        currentPage:
          type: "integer"
        totalPages:
          type: "integer"
        totalCount:
          type: "integer"
        hasNext:
          type: "boolean"
        hasPrev:
          type: "boolean"
      required:
        - "currentPage"
        - "totalPages"
        - "totalCount"
        - "hasNext"
        - "hasPrev"
      additionalProperties: true
      example:
        currentPage: 1
        totalPages: 7
        totalCount: 312
        hasNext: true
        hasPrev: false
    EventLogListResponse:
      type: "object"
      description: "Response from `GET /api/event-logs`."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/EventLogDto"
        pagination:
          "$ref": "#/components/schemas/EventLogPagination"
      required:
        - "success"
        - "data"
        - "pagination"
      additionalProperties: true
      example:
        success: true
        data:
          -
            _id: "65e0a0b0c0d0e0f0a0b0c0d0"
            organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
            userId: "65b1f0a2c3d4e5f6a7b8c9d0"
            eventType: "message.received"
            direction: "inbound"
            automationTriggered: true
            createdAt: "2026-05-18T14:30:00.000Z"
        pagination:
          currentPage: 1
          totalPages: 7
          totalCount: 312
          hasNext: true
          hasPrev: false
    EventLogSingleResponse:
      type: "object"
      description: "Response from `GET /api/event-logs/{id}`."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          "$ref": "#/components/schemas/EventLogDto"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          _id: "65e0a0b0c0d0e0f0a0b0c0d0"
          organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
          userId: "65b1f0a2c3d4e5f6a7b8c9d0"
          eventType: "message.received"
          payload:
            channelType: "sms"
            body: "Yes please!"
          createdAt: "2026-05-18T14:30:00.000Z"
    EventLogErrorResponse:
      type: "object"
      description: "Error envelope returned by event-log endpoints."
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
        error:
          type: "string"
      required:
        - "success"
        - "message"
      additionalProperties: true
      example:
        success: false
        message: "Event log not found"
        error: "NOT_FOUND"
    GoogleSheetsErrorResponse:
      type: "object"
      properties:
        error:
          type: "string"
        detail:
          type: "string"
      additionalProperties: true
      example:
        error: "Google Sheets service unavailable"
        detail: "Upstream connection refused"
    LeadManagementDto:
      type: "object"
      properties:
        _id:
          type: "string"
        organizationId:
          type: "string"
        userId:
          type: "string"
        configurationName:
          type: "string"
        name:
          type: "string"
          nullable: true
        description:
          type: "string"
          nullable: true
        source:
          type: "string"
        inboundEmail:
          type: "string"
          nullable: true
        initialStage:
          type: "string"
        defaultProcess:
          type: "string"
          description: "Prompt ID used as the default process."
        isAutopilot:
          type: "boolean"
        allowRecontact:
          type: "boolean"
        starterMessage:
          type: "string"
          nullable: true
        costPerLead:
          type: "number"
          minimum: 0
        status:
          type: "string"
          enum:
            - "active"
            - "inactive"
        pipelineId:
          type: "string"
          nullable: true
        pipelineStage:
          type: "string"
          nullable: true
        createApplication:
          type: "boolean"
        applicationName:
          type: "string"
          nullable: true
        applicationStatus:
          type: "string"
          nullable: true
        applicationPipelineId:
          type: "string"
          nullable: true
        applicationPipelineStage:
          type: "string"
          nullable: true
        phoneNumberId:
          type: "string"
          nullable: true
        forwardToOutreach:
          type: "boolean"
        useWorkflowOnly:
          type: "boolean"
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "665f1a0c0e0a4b001a2c9f40"
        organizationId: "64ee9a8b1e7f2a0011223344"
        userId: "64ee9a8b1e7f2a0011223399"
        configurationName: "Facebook Lead Ad Funnel"
        name: "FB Lead Ad"
        description: "Routes Facebook Lead Ad submissions through the warm-up sequence."
        source: "Facebook Lead Ad"
        inboundEmail: "leads+fb@inbound.example.com"
        initialStage: "New Lead"
        defaultProcess: "64eea1110000000000000001"
        isAutopilot: true
        allowRecontact: false
        starterMessage: "Hi {{firstName}}, thanks for your interest!"
        costPerLead: 12.5
        status: "active"
        pipelineId: "64eea1110000000000000010"
        pipelineStage: "New Lead"
        createApplication: false
        forwardToOutreach: true
        useWorkflowOnly: false
        createdAt: "2026-05-01T09:00:00.000Z"
        updatedAt: "2026-05-10T15:23:00.000Z"
    CreateLeadManagementRequest:
      type: "object"
      properties:
        configurationName:
          type: "string"
        name:
          type: "string"
        description:
          type: "string"
        source:
          type: "string"
          default: "Unassigned"
        inboundEmail:
          type: "string"
          format: "email"
        initialStage:
          type: "string"
        defaultProcess:
          type: "string"
          description: "Prompt ID (must exist)."
        isAutopilot:
          type: "boolean"
          default: false
        allowRecontact:
          type: "boolean"
          default: false
        starterMessage:
          type: "string"
        costPerLead:
          type: "number"
          minimum: 0
          default: 0
        status:
          type: "string"
          enum:
            - "active"
            - "inactive"
          default: "active"
        pipelineId:
          type: "string"
        pipelineStage:
          type: "string"
        createApplication:
          type: "boolean"
          default: false
        applicationName:
          type: "string"
        applicationStatus:
          type: "string"
        applicationPipelineId:
          type: "string"
        applicationPipelineStage:
          type: "string"
        phoneNumberId:
          type: "string"
          nullable: true
          description: "The org SMS line outreach for this configuration sends from. Leads' SMS threads are the contact's thread on this line (created when the contact has none there). Must be an active SMS line of the organization on its active SMS provider, or the request fails with 400. When unset, outreach sends from the API key user's line, else the organization's default line."
        forwardToOutreach:
          type: "boolean"
          default: true
        useWorkflowOnly:
          type: "boolean"
          default: false
      required:
        - "configurationName"
        - "initialStage"
        - "defaultProcess"
      additionalProperties: true
      example:
        configurationName: "Facebook Lead Ad Funnel"
        source: "Facebook Lead Ad"
        inboundEmail: "leads+fb@inbound.example.com"
        initialStage: "New Lead"
        defaultProcess: "64eea1110000000000000001"
        isAutopilot: true
        starterMessage: "Hi {{firstName}}, thanks for your interest!"
        costPerLead: 12.5
        status: "active"
        forwardToOutreach: true
    UpdateLeadManagementRequest:
      type: "object"
      properties:
        configurationName:
          type: "string"
          description: "Internal identifier for the Lead Management config."
        name:
          type: "string"
          description: "Human-friendly display name surfaced in the UI."
        description:
          type: "string"
          description: "Free-form notes describing this lead routing setup."
        source:
          type: "string"
          description: "Lead source label attached to contacts matched by this config (e.g. `Facebook Lead Ad`)."
        inboundEmail:
          type: "string"
          format: "email"
          description: "Inbox address that ingests external emails for this configuration."
        initialStage:
          type: "string"
          description: "Pipeline stage `_id` new leads enter when matched."
        defaultProcess:
          type: "string"
          description: "Prompt `_id` used to drive the AI on matched leads."
        isAutopilot:
          type: "boolean"
          description: "When true, the AI runs autonomously without rep approval on new leads."
        allowRecontact:
          type: "boolean"
          description: "When true, allow re-contacting leads already in the system."
        starterMessage:
          type: "string"
          description: "First outbound message sent on lead match; supports placeholders."
        costPerLead:
          type: "number"
          minimum: 0
          description: "Cost (USD) attributed to each lead; powers the outreach metrics dashboard."
        status:
          type: "string"
          enum:
            - "active"
            - "inactive"
          description: "Whether this config is currently routing leads."
        pipelineId:
          type: "string"
          description: "Pipeline `_id` matched contacts are placed into."
        pipelineStage:
          type: "string"
          description: "Pipeline stage matched contacts are placed into."
        createApplication:
          type: "boolean"
          description: "When true, also creates an `Application` alongside the contact."
        applicationName:
          type: "string"
          description: "Display name for the auto-created application."
        applicationStatus:
          type: "string"
          description: "Initial status for the auto-created application."
        applicationPipelineId:
          type: "string"
          description: "Pipeline `_id` the auto-created application is placed into."
        applicationPipelineStage:
          type: "string"
          description: "Pipeline stage the auto-created application enters."
        phoneNumberId:
          type: "string"
          nullable: true
          description: "The org SMS line outreach for this configuration sends from. Leads' SMS threads are the contact's thread on this line (created when the contact has none there). Must be an active SMS line of the organization on its active SMS provider, or the request fails with 400. When unset, outreach sends from the API key user's line, else the organization's default line. An empty value or null clears it."
        forwardToOutreach:
          type: "boolean"
          description: "When true, forwards leads to the outreach trigger pipeline."
        useWorkflowOnly:
          type: "boolean"
          description: "When true, only execute matching workflows; skip the legacy autopilot path."
      additionalProperties: true
      example:
        isAutopilot: false
        costPerLead: 15
        status: "inactive"
    LeadManagementListResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/LeadManagementDto"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          -
            _id: "665f1a0c0e0a4b001a2c9f40"
            configurationName: "Facebook Lead Ad Funnel"
            source: "Facebook Lead Ad"
            initialStage: "New Lead"
            isAutopilot: true
            status: "active"
    LeadManagementDetailResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          "$ref": "#/components/schemas/LeadManagementDto"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          _id: "665f1a0c0e0a4b001a2c9f40"
          configurationName: "Facebook Lead Ad Funnel"
          source: "Facebook Lead Ad"
          initialStage: "New Lead"
          status: "active"
    LeadManagementMutationResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        message:
          type: "string"
        data:
          "$ref": "#/components/schemas/LeadManagementDto"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        message: "Lead management configuration created"
        data:
          _id: "665f1a0c0e0a4b001a2c9f40"
          configurationName: "Facebook Lead Ad Funnel"
          status: "active"
    LeadManagementMessageResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        message:
          type: "string"
      required:
        - "success"
        - "message"
      additionalProperties: true
      example:
        success: true
        message: "Lead management configuration deleted"
    LeadManagementErrorResponse:
      type: "object"
      description: "Error envelope for `/api/lead-management` endpoints."
      properties:
        error:
          type: "string"
        message:
          type: "string"
        success:
          type: "boolean"
          enum:
            - false
      required:
        - "error"
      additionalProperties: true
      example:
        error: "Lead management configuration not found"
    PublishItemRequest:
      type: "object"
      properties:
        itemType:
          type: "string"
          enum:
            - "prompt"
            - "template"
          description: "What's being published: `prompt` or `template`."
        itemId:
          type: "string"
          description: "Mongo ObjectId of the source prompt or template the caller owns and wants to publish."
        scopes:
          type: "object"
          description: "Per-scope publish settings (`organization`, `marketplace`) - each carries `enabled`, `shareType`, `isContentVisible`, `allowEditableReferences`."
          properties:
            organization:
              type: "object"
              description: "Publish settings for the caller's organization scope; only visible to members of the publisher's org."
              properties:
                enabled:
                  type: "boolean"
                  description: "When true, create (or keep) an organization-scope listing for this item."
                shareType:
                  type: "string"
                  enum:
                    - "reference"
                    - "copy"
                  description: "`reference` (acquirer gets a live link) or `copy` (acquirer gets an editable duplicate)."
                isContentVisible:
                  type: "boolean"
                  description: "When false, marketplace browsers see metadata only - body is hidden until acquired."
                allowEditableReferences:
                  type: "boolean"
                  description: "For `reference` listings, allow acquirers to edit the linked item; ignored for `copy` listings."
            marketplace:
              type: "object"
              description: "Publish settings for the global marketplace scope; visible to every Tether organization."
              properties:
                enabled:
                  type: "boolean"
                  description: "When true, create (or keep) a marketplace-scope listing for this item."
                shareType:
                  type: "string"
                  enum:
                    - "reference"
                    - "copy"
                  description: "`reference` (acquirer gets a live link) or `copy` (acquirer gets an editable duplicate)."
                isContentVisible:
                  type: "boolean"
                  description: "When false, marketplace browsers see metadata only - body is hidden until acquired."
                allowEditableReferences:
                  type: "boolean"
                  description: "For `reference` listings, allow acquirers to edit the linked item; ignored for `copy` listings."
        metadata:
          type: "object"
          description: "Optional display overrides for the listing; when omitted the underlying item's own name/description are used."
          properties:
            name:
              type: "string"
              description: "Display name shown in marketplace listings; falls back to the source item's name."
            description:
              type: "string"
              description: "Short blurb shown on the listing card; falls back to the source item's description."
            usageInformation:
              type: "string"
              description: "Guidance shown to acquirers (e.g., required variables, setup steps)."
      required:
        - "itemType"
        - "itemId"
        - "scopes"
      additionalProperties: true
      example:
        itemType: "prompt"
        itemId: "5f7b1c2e8a1d4e0012c3b4a5"
        scopes:
          organization:
            enabled: true
            shareType: "copy"
            isContentVisible: true
            allowEditableReferences: false
          marketplace:
            enabled: false
            shareType: "reference"
            isContentVisible: false
            allowEditableReferences: false
        metadata:
          name: "Acme Inbound Triage Prompt"
          description: "Routes inbound SMS to the right department."
          usageInformation: "Set the {{org_name}} variable before applying."
    UpdatePublishSettingsRequest:
      type: "object"
      properties:
        shareType:
          type: "string"
          enum:
            - "reference"
            - "copy"
          description: "`reference` (acquirer gets a live link) or `copy` (acquirer gets an editable duplicate)."
        isContentVisible:
          type: "boolean"
          description: "When false, marketplace browsers see metadata only - body is hidden until acquired."
        allowEditableReferences:
          type: "boolean"
          description: "For `reference` listings on organization scope, allow acquirers to edit the linked item; only applied when shareType stays `reference`."
      additionalProperties: true
      example:
        shareType: "reference"
        isContentVisible: true
        allowEditableReferences: true
    AcquireItemRequest:
      type: "object"
      properties:
        requestEditable:
          type: "boolean"
          description: "When true and the listing permits editable references, the acquired link allows the recipient to edit."
      additionalProperties: true
      example:
        requestEditable: true
    ImportTemplateToAutomationsRequest:
      type: "object"
      properties:
        automationIds:
          type: "array"
          items:
            type: "string"
          minItems: 1
          maxItems: 50
          description: "Mongo ObjectIds of caller-owned automations to receive the template body; each must be SMS-enabled and is processed in a single Mongo transaction."
      required:
        - "automationIds"
      additionalProperties: true
      example:
        automationIds:
          - "5f7b1c2e8a1d4e0012c3b4a5"
          - "6a8c2d3f9b1e5a0023d4c5b6"
    MarketplaceErrorResponse:
      type: "object"
      description: "Generic error envelope returned by Marketplace endpoints."
      properties:
        error:
          type: "string"
        details:
          type: "string"
      required:
        - "error"
      additionalProperties: true
      example:
        error: "Marketplace item not found"
    MarketplacePublisher:
      type: "object"
      properties:
        id:
          type: "string"
          nullable: true
        name:
          type: "string"
        organization:
          type: "string"
      required:
        - "name"
        - "organization"
      additionalProperties: true
      example:
        id: "5f7b1c2e8a1d4e0012c3b4a5"
        name: "Sam Patel"
        organization: "Acme Corp"
    MarketplaceBrowseItem:
      type: "object"
      description: "Marketplace listing summary returned by GET /api/marketplace."
      properties:
        id:
          type: "string"
        itemType:
          type: "string"
          enum:
            - "prompt"
            - "template"
        itemId:
          type: "string"
        name:
          type: "string"
        description:
          type: "string"
        usageInformation:
          type: "string"
        publisher:
          "$ref": "#/components/schemas/MarketplacePublisher"
        scope:
          type: "string"
          enum:
            - "organization"
            - "marketplace"
        shareType:
          type: "string"
          enum:
            - "reference"
            - "copy"
        allowEditableReferences:
          type: "boolean"
        isContentVisible:
          type: "boolean"
        status:
          type: "string"
        usageCount:
          type: "integer"
        isAcquired:
          type: "boolean"
        publishedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        id: "7b2c4e0d9f1a3b4e5c6d7e8f9012"
        itemType: "prompt"
        itemId: "5f7b1c2e8a1d4e0012c3b4a5"
        name: "Acme Inbound Triage Prompt"
        description: "Routes inbound SMS to the right department."
        usageInformation: "Set the {{org_name}} variable before applying."
        publisher:
          id: "5f7b1c2e8a1d4e0012c3b4a5"
          name: "Sam Patel"
          organization: "Acme Corp"
        scope: "marketplace"
        shareType: "copy"
        allowEditableReferences: false
        isContentVisible: true
        status: "active"
        usageCount: 12
        isAcquired: false
        publishedAt: "2026-05-01T09:15:00.000Z"
    MarketplaceBrowseResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          example: true
        data:
          type: "object"
          properties:
            items:
              type: "array"
              items:
                "$ref": "#/components/schemas/MarketplaceBrowseItem"
            pagination:
              type: "object"
              properties:
                page:
                  type: "integer"
                limit:
                  type: "integer"
                total:
                  type: "integer"
                pages:
                  type: "integer"
              required:
                - "page"
                - "limit"
                - "total"
                - "pages"
              additionalProperties: false
          required:
            - "items"
            - "pagination"
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          items:
            -
              id: "7b2c4e0d9f1a3b4e5c6d7e8f9012"
              itemType: "prompt"
              itemId: "5f7b1c2e8a1d4e0012c3b4a5"
              name: "Acme Inbound Triage Prompt"
              description: "Routes inbound SMS to the right department."
              publisher:
                name: "Sam Patel"
                organization: "Acme Corp"
              scope: "marketplace"
              shareType: "copy"
              isContentVisible: true
              status: "active"
              usageCount: 12
              isAcquired: false
              publishedAt: "2026-05-01T09:15:00.000Z"
          pagination:
            page: 1
            limit: 20
            total: 47
            pages: 3
    MarketplacePublishedItemDetail:
      type: "object"
      description: "Full marketplace listing detail returned by GET /api/marketplace/{id}. Same shape as the browse item plus an optional `content` payload when the listing is content-visible."
      properties:
        id:
          type: "string"
        itemType:
          type: "string"
          enum:
            - "prompt"
            - "template"
        itemId:
          type: "string"
        name:
          type: "string"
        description:
          type: "string"
        usageInformation:
          type: "string"
        content:
          nullable: true
          description: "Prompt body or template text when isContentVisible; null otherwise."
          oneOf:
            -
              type: "string"
            -
              type: "object"
              additionalProperties: true
        publisher:
          "$ref": "#/components/schemas/MarketplacePublisher"
        scope:
          type: "string"
          enum:
            - "organization"
            - "marketplace"
        shareType:
          type: "string"
          enum:
            - "reference"
            - "copy"
        allowEditableReferences:
          type: "boolean"
        isContentVisible:
          type: "boolean"
        status:
          type: "string"
        usageCount:
          type: "integer"
        isAcquired:
          type: "boolean"
        publishedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        id: "7b2c4e0d9f1a3b4e5c6d7e8f9012"
        itemType: "prompt"
        itemId: "5f7b1c2e8a1d4e0012c3b4a5"
        name: "Acme Inbound Triage Prompt"
        description: "Routes inbound SMS to the right department."
        usageInformation: "Set the {{org_name}} variable before applying."
        content: "You are a helpful triage assistant for {{org_name}}…"
        publisher:
          name: "Sam Patel"
          organization: "Acme Corp"
        scope: "marketplace"
        shareType: "copy"
        allowEditableReferences: false
        isContentVisible: true
        status: "active"
        usageCount: 12
        isAcquired: false
        publishedAt: "2026-05-01T09:15:00.000Z"
    MarketplacePublishedItemResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          example: true
        data:
          "$ref": "#/components/schemas/MarketplacePublishedItemDetail"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          id: "7b2c4e0d9f1a3b4e5c6d7e8f9012"
          itemType: "prompt"
          itemId: "5f7b1c2e8a1d4e0012c3b4a5"
          name: "Acme Inbound Triage Prompt"
          description: "Routes inbound SMS to the right department."
          content: "You are a helpful triage assistant for {{org_name}}…"
          publisher:
            name: "Sam Patel"
            organization: "Acme Corp"
          scope: "marketplace"
          shareType: "copy"
          isContentVisible: true
          status: "active"
          usageCount: 12
          isAcquired: false
          publishedAt: "2026-05-01T09:15:00.000Z"
    MarketplacePublishedItemSummary:
      type: "object"
      description: "Raw PublishedItem document as returned by GET /api/marketplace/my-published. Fields mirror the Mongoose model."
      properties:
        _id:
          type: "string"
        itemType:
          type: "string"
          enum:
            - "prompt"
            - "template"
        itemId:
          type: "string"
        name:
          type: "string"
        description:
          type: "string"
        usageInformation:
          type: "string"
        publishedBy:
          type: "string"
        organizationId:
          type: "string"
        scope:
          type: "string"
          enum:
            - "organization"
            - "marketplace"
        shareType:
          type: "string"
          enum:
            - "reference"
            - "copy"
        allowEditableReferences:
          type: "boolean"
        isContentVisible:
          type: "boolean"
        status:
          type: "string"
        usageCount:
          type: "integer"
        publishedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "7b2c4e0d9f1a3b4e5c6d7e8f9012"
        itemType: "prompt"
        itemId: "5f7b1c2e8a1d4e0012c3b4a5"
        name: "Acme Inbound Triage Prompt"
        description: "Routes inbound SMS to the right department."
        publishedBy: "5f7b1c2e8a1d4e0012c3b4a5"
        organizationId: "5f7b1c2e8a1d4e0012c3b4a5"
        scope: "marketplace"
        shareType: "copy"
        allowEditableReferences: false
        isContentVisible: true
        status: "active"
        usageCount: 12
        publishedAt: "2026-05-01T09:15:00.000Z"
    MarketplaceMyPublishedItemsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          example: true
        data:
          type: "object"
          properties:
            items:
              type: "array"
              items:
                "$ref": "#/components/schemas/MarketplacePublishedItemSummary"
          required:
            - "items"
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          items:
            -
              _id: "7b2c4e0d9f1a3b4e5c6d7e8f9012"
              itemType: "prompt"
              itemId: "5f7b1c2e8a1d4e0012c3b4a5"
              name: "Acme Inbound Triage Prompt"
              publishedBy: "5f7b1c2e8a1d4e0012c3b4a5"
              organizationId: "5f7b1c2e8a1d4e0012c3b4a5"
              scope: "marketplace"
              shareType: "copy"
              isContentVisible: true
              status: "active"
              usageCount: 12
              publishedAt: "2026-05-01T09:15:00.000Z"
    MarketplaceAcquiredItem:
      type: "object"
      description: "Acquisition record returned by GET /api/marketplace/acquired. `marketplaceItem` is null when the underlying PublishedItem has been removed."
      properties:
        acquisitionId:
          type: "string"
        itemType:
          type: "string"
        type:
          type: "string"
          enum:
            - "reference"
            - "copy"
        acquiredAt:
          type: "string"
          format: "date-time"
        originalItemId:
          type: "string"
        copiedItemId:
          type: "string"
          nullable: true
        marketplaceItem:
          nullable: true
          type: "object"
          properties:
            id:
              type: "string"
            name:
              type: "string"
            description:
              type: "string"
            publisher:
              "$ref": "#/components/schemas/MarketplacePublisher"
            scope:
              type: "string"
              enum:
                - "organization"
                - "marketplace"
            status:
              type: "string"
            isContentVisible:
              type: "boolean"
          additionalProperties: true
      additionalProperties: true
      example:
        acquisitionId: "8c3d4e0f9a1b3c4d5e6f7a8b9c01"
        itemType: "prompt"
        type: "copy"
        acquiredAt: "2026-05-10T17:42:00.000Z"
        originalItemId: "5f7b1c2e8a1d4e0012c3b4a5"
        copiedItemId: "9d4e5f1a2b3c4d5e6f7a8b9c0d12"
        marketplaceItem:
          id: "7b2c4e0d9f1a3b4e5c6d7e8f9012"
          name: "Acme Inbound Triage Prompt"
          description: "Routes inbound SMS to the right department."
          publisher:
            name: "Sam Patel"
            organization: "Acme Corp"
          scope: "marketplace"
          status: "active"
          isContentVisible: true
    MarketplaceAcquiredItemsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          example: true
        data:
          type: "object"
          properties:
            items:
              type: "array"
              items:
                "$ref": "#/components/schemas/MarketplaceAcquiredItem"
          required:
            - "items"
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          items:
            -
              acquisitionId: "8c3d4e0f9a1b3c4d5e6f7a8b9c01"
              itemType: "prompt"
              type: "copy"
              acquiredAt: "2026-05-10T17:42:00.000Z"
              originalItemId: "5f7b1c2e8a1d4e0012c3b4a5"
              copiedItemId: "9d4e5f1a2b3c4d5e6f7a8b9c0d12"
              marketplaceItem:
                id: "7b2c4e0d9f1a3b4e5c6d7e8f9012"
                name: "Acme Inbound Triage Prompt"
                publisher:
                  name: "Sam Patel"
                  organization: "Acme Corp"
                scope: "marketplace"
                status: "active"
                isContentVisible: true
    MarketplaceAutomationSmsStatus:
      type: "object"
      properties:
        automationId:
          type: "string"
        automationName:
          type: "string"
        hasSmsEnabled:
          type: "boolean"
        phoneNumber:
          type: "string"
        message:
          type: "string"
      required:
        - "automationId"
        - "automationName"
        - "hasSmsEnabled"
      additionalProperties: true
      example:
        automationId: "5f7b1c2e8a1d4e0012c3b4a5"
        automationName: "Inbound Support"
        hasSmsEnabled: true
        phoneNumber: "+12362320246"
        message: "SMS-ready"
    MarketplaceAutomationsSmsStatusResponse:
      type: "array"
      items:
        "$ref": "#/components/schemas/MarketplaceAutomationSmsStatus"
      example:
        -
          automationId: "5f7b1c2e8a1d4e0012c3b4a5"
          automationName: "Inbound Support"
          hasSmsEnabled: true
          phoneNumber: "+12362320246"
          message: "SMS-ready"
        -
          automationId: "6a8c2d3f9b1e5a0023d4c5b6"
          automationName: "Outreach Campaign"
          hasSmsEnabled: false
          phoneNumber: ""
          message: "No SMS number provisioned"
    MarketplaceUnpublishResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          example: true
        message:
          type: "string"
      required:
        - "success"
        - "message"
      additionalProperties: true
      example:
        success: true
        message: "Marketplace listing removed and 3 acquisitions cleaned up"
    MarketplacePublishedSummary:
      type: "object"
      description: "One published-scope summary returned after a publish call."
      properties:
        id:
          type: "string"
        scope:
          type: "string"
          enum:
            - "organization"
            - "marketplace"
        shareType:
          type: "string"
          enum:
            - "reference"
            - "copy"
        isContentVisible:
          type: "boolean"
        status:
          type: "string"
          enum:
            - "active"
      required:
        - "id"
        - "scope"
        - "shareType"
        - "status"
      additionalProperties: true
      example:
        id: "64d2f9c5e8a1d4e001a0b1c2"
        scope: "marketplace"
        shareType: "reference"
        isContentVisible: true
        status: "active"
    MarketplacePublishResponse:
      type: "object"
      description: "Returned after `POST /api/marketplace/publish`. `published[]` contains one summary per enabled scope."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            published:
              type: "array"
              items:
                "$ref": "#/components/schemas/MarketplacePublishedSummary"
          required:
            - "published"
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          published:
            -
              id: "64d2f9c5e8a1d4e001a0b1c2"
              scope: "organization"
              shareType: "copy"
              isContentVisible: true
              status: "active"
            -
              id: "64d2f9c5e8a1d4e001a0b1c3"
              scope: "marketplace"
              shareType: "reference"
              isContentVisible: false
              status: "active"
    MarketplaceUpdatePublishSettingsResponse:
      type: "object"
      description: "Returned after a publish-settings PATCH. Wraps the updated marketplace item."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            marketplaceItem:
              type: "object"
              description: "Updated PublishedItem document."
              additionalProperties: true
          required:
            - "marketplaceItem"
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          marketplaceItem:
            _id: "64d2f9c5e8a1d4e001a0b1c2"
            itemType: "prompt"
            itemId: "64a1b2c3d4e5f6001234567a"
            publishedBy: "64a1b2c3d4e5f60012345679"
            scope: "marketplace"
            shareType: "reference"
            allowEditableReferences: false
            isContentVisible: true
            name: "Maple Court - Tour Confirm"
            status: "active"
            usageCount: 12
    MarketplaceAcquireSummary:
      type: "object"
      description: "Acquisition outcome returned after acquiring a marketplace prompt. `type=copy` indicates a duplicate prompt was created; `type=reference` indicates only a UserAcquiredItem link was recorded."
      properties:
        id:
          type: "string"
        itemType:
          type: "string"
          enum:
            - "prompt"
        type:
          type: "string"
          enum:
            - "copy"
            - "reference"
        isEditable:
          type: "boolean"
        publishedItemId:
          type: "string"
        originalItemId:
          type: "string"
        copiedItemId:
          type: "string"
          nullable: true
          description: "Set when `type=copy`, null when `type=reference`."
        acquiredAt:
          type: "string"
          format: "date-time"
      required:
        - "id"
        - "itemType"
        - "type"
        - "publishedItemId"
        - "originalItemId"
        - "acquiredAt"
      additionalProperties: true
      example:
        id: "64d2f9c5e8a1d4e001a0b1c5"
        itemType: "prompt"
        type: "copy"
        isEditable: true
        publishedItemId: "64d2f9c5e8a1d4e001a0b1c2"
        originalItemId: "64a1b2c3d4e5f6001234567a"
        copiedItemId: "64a1b2c3d4e5f60012345700"
        acquiredAt: "2026-05-20T15:04:01.135Z"
    MarketplaceAcquireResponse:
      type: "object"
      description: "Returned after `POST /api/marketplace/{id}/acquire`. Templates cannot be acquired via this endpoint - see `import-to-automations`."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            acquired:
              "$ref": "#/components/schemas/MarketplaceAcquireSummary"
          required:
            - "acquired"
          additionalProperties: true
        message:
          type: "string"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        message: "Prompt copied to your library"
        data:
          acquired:
            id: "64d2f9c5e8a1d4e001a0b1c5"
            itemType: "prompt"
            type: "copy"
            isEditable: true
            publishedItemId: "64d2f9c5e8a1d4e001a0b1c2"
            originalItemId: "64a1b2c3d4e5f6001234567a"
            copiedItemId: "64a1b2c3d4e5f60012345700"
            acquiredAt: "2026-05-20T15:04:01.135Z"
    MarketplaceImportAutomationResult:
      type: "object"
      description: "Per-automation outcome from a template import."
      properties:
        automationId:
          type: "string"
        automationName:
          type: "string"
        success:
          type: "boolean"
        changes:
          type: "object"
          description: "Applied changes when `success` is true."
          properties:
            smsEnabled:
              type: "boolean"
            phoneNumber:
              type: "string"
            message:
              type: "string"
          additionalProperties: true
        error:
          type: "string"
          description: "Failure reason when `success` is false."
      required:
        - "automationId"
        - "automationName"
        - "success"
      additionalProperties: true
      example:
        automationId: "64a1b2c3d4e5f6001234567a"
        automationName: "New lead - first reply"
        success: true
        changes:
          smsEnabled: true
          phoneNumber: "+14165550100"
          message: "Hi {{contact.firstName}} - thanks for reaching out!"
    MarketplaceImportToAutomationsResponse:
      type: "object"
      description: "Mixed success/partial-success/all-failure envelope. HTTP 200 = all imported; HTTP 207 = some imported; HTTP 400 = none imported. Inspect `stats` and per-target `results[]` for detail."
      properties:
        success:
          type: "boolean"
        message:
          type: "string"
        results:
          type: "array"
          items:
            "$ref": "#/components/schemas/MarketplaceImportAutomationResult"
        stats:
          type: "object"
          properties:
            total:
              type: "integer"
            successful:
              type: "integer"
            failed:
              type: "integer"
          required:
            - "total"
            - "successful"
            - "failed"
          additionalProperties: true
      required:
        - "success"
        - "results"
        - "stats"
      additionalProperties: true
      example:
        success: true
        message: "Template imported to 2 of 3 automations"
        results:
          -
            automationId: "64a1b2c3d4e5f6001234567a"
            automationName: "New lead - first reply"
            success: true
            changes:
              smsEnabled: true
              phoneNumber: "+14165550100"
              message: "Hi {{contact.firstName}}!"
          -
            automationId: "64a1b2c3d4e5f6001234567b"
            automationName: "Tour follow-up"
            success: false
            error: "SMS notification already enabled and conflicts with existing settings"
        stats:
          total: 3
          successful: 2
          failed: 1
    RateLimitResponse:
      type: "object"
      properties:
        error:
          type: "string"
        limit:
          type: "integer"
        currentCount:
          type: "integer"
        resetIn:
          type: "integer"
          description: "Seconds until rate limit resets"
        message:
          type: "string"
      additionalProperties: true
      example:
        error: "Too many requests"
        limit: 20
        currentCount: 21
        resetIn: 42
        message: "Please wait before uploading more attachments"
    UploadAttachmentResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        attachment:
          type: "object"
          properties:
            storageKey:
              type: "string"
            filename:
              type: "string"
            contentType:
              type: "string"
            size:
              type: "integer"
          additionalProperties: false
      additionalProperties: true
      example:
        success: true
        attachment:
          storageKey: "messages/65a0e0e0e0e0e0e0e0e0e0e0/msg_67b0/photo.jpg"
          filename: "photo.jpg"
          contentType: "image/jpeg"
          size: 184221
    AttachmentSignedUrlResponse:
      type: "object"
      properties:
        url:
          type: "string"
        storageKey:
          type: "string"
        remappedFrom:
          type: "string"
          description: "Present when the key was remapped from a stale email attachment key"
      additionalProperties: true
      example:
        url: "https://r2.example.com/messages/65a0.../photo.jpg?token=..."
        storageKey: "messages/65a0e0e0e0e0e0e0e0e0e0e0/msg_67b0/photo.jpg"
    WebchatMessagesResponse:
      type: "object"
      properties:
        messages:
          type: "array"
          items:
            type: "object"
            properties:
              id:
                type: "string"
              text:
                type: "string"
              sender:
                type: "string"
                description: "Either \"user\" or \"bot\""
              timestamp:
                type: "number"
              attachments:
                type: "array"
                items:
                  type: "object"
                  additionalProperties: true
              senderInfo:
                type: "object"
                properties:
                  type:
                    type: "string"
                    description: "Either \"AI\" or \"HUMAN\""
                  name:
                    type: "string"
                additionalProperties: false
                description: "Null when showSenderNameInWebchat is disabled or message is incoming"
            additionalProperties: true
      additionalProperties: true
      example:
        messages:
          -
            id: "67c0a0b0c0d0e0f0a0b0c0d0"
            text: "Hi! How can we help?"
            sender: "bot"
            timestamp: 1747571400000
            attachments:
              []
            senderInfo:
              type: "AI"
              name: "Tether AI"
          -
            id: "67c0a0b0c0d0e0f0a0b0c0d1"
            text: "I need a refund."
            sender: "user"
            timestamp: 1747571410000
    SendQuickBulkSmsRequest:
      type: "object"
      properties:
        contactIds:
          type: "array"
          items:
            type: "string"
          maxItems: 50000
          description: "Recipients to text, at most 50,000. More than 500 distinct contacts are queued as a bulk SMS operation (202)."
        message:
          type: "string"
          description: "SMS body; ignored when `templateId` is supplied."
        templateId:
          type: "string"
          description: "Template `_id` whose body is used; takes precedence over `message`."
        phoneNumberId:
          type: "string"
          description: "Org line to send from. A named line is used exactly: a recipient it cannot send to fails, with no fallback to another line."
      required:
        - "contactIds"
      description: "Either message or templateId must be provided, but not both"
      additionalProperties: true
      example:
        contactIds:
          - "65c2d0e0f0a0b0c0d0e0f0a0"
          - "65c2d0e0f0a0b0c0d0e0f0a1"
        message: "Hi {{firstName}}, our team will be in touch shortly."
    MessagesDownloadErrorResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
        error:
          type: "string"
      additionalProperties: true
      example:
        success: false
        message: "Storage key is required"
        error: "BAD_REQUEST"
    SmsLimitsResponse:
      type: "object"
      properties:
        documentLinkLength:
          type: "integer"
          description: "Characters one document link adds to an SMS body."
      required:
        - "documentLinkLength"
      additionalProperties: false
      example:
        documentLinkLength: 60
    QuickBulkSmsQueuedResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        queued:
          type: "boolean"
          enum:
            - true
        operationId:
          type: "string"
          description: "The bulk SMS async operation that sends the messages."
        jobId:
          type: "string"
          description: "Same value as `operationId`."
        status:
          type: "string"
          description: "Status of the operation when it was queued."
        summary:
          type: "object"
          properties:
            total:
              type: "integer"
              description: "Contacts the operation will send to."
            success:
              type: "integer"
            failed:
              type: "integer"
          additionalProperties: false
        results:
          type: "array"
          maxItems: 0
          items:
            type: "object"
      additionalProperties: true
      example:
        success: true
        queued: true
        operationId: "6710b2c4e8a1d4e001a0b3a0"
        jobId: "6710b2c4e8a1d4e001a0b3a0"
        status: "queued"
        summary:
          total: 1200
          success: 0
          failed: 0
        results:
          []
    QuickBulkSmsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        summary:
          type: "object"
          properties:
            total:
              type: "integer"
            success:
              type: "integer"
            failed:
              type: "integer"
          additionalProperties: false
        results:
          type: "array"
          items:
            type: "object"
            properties:
              contactId:
                type: "string"
              success:
                type: "boolean"
              name:
                type: "string"
              messageId:
                type: "string"
              messageDocId:
                type: "string"
              status:
                type: "string"
              error:
                type: "string"
            additionalProperties: true
      additionalProperties: true
      example:
        success: true
        summary:
          total: 2
          success: 1
          failed: 1
        results:
          -
            contactId: "65c2d0e0f0a0b0c0d0e0f0a0"
            success: true
            name: "Jane Doe"
            messageId: "SMxxx"
            messageDocId: "67d0a0b0c0d0e0f0a0b0c0d0"
            status: "queued"
          -
            contactId: "65c2d0e0f0a0b0c0d0e0f0a1"
            success: false
            name: "John Smith"
            error: "Invalid phone number"
    NotificationSendMentionsRequest:
      type: "object"
      properties:
        contactId:
          type: "string"
          description: "Contact the note relates to (links the notification back to the timeline)."
        mentions:
          type: "array"
          items:
            type: "string"
          description: "User `_id`s @-mentioned in the note; each receives a ping."
        noteContent:
          type: "string"
          description: "Plain-text excerpt rendered inside the notification body."
        authorName:
          type: "string"
          description: "Display name of the user who authored the note."
      required:
        - "contactId"
        - "mentions"
      additionalProperties: true
      example:
        contactId: "65c2d0e0f0a0b0c0d0e0f0a0"
        mentions:
          - "65b1f0a2c3d4e5f6a7b8c9d0"
          - "65b1f0a2c3d4e5f6a7b8c9d1"
        noteContent: "@alice @brenda please review this lead"
        authorName: "Cory Tan"
    NotificationErrorResponse:
      type: "object"
      description: "Error envelope returned by notification endpoints. 500 paths return `{ error }`; mention-send failures may also include `details`."
      properties:
        success:
          type: "boolean"
          enum:
            - false
        error:
          type: "string"
        details:
          type: "string"
      additionalProperties: true
      example:
        success: false
        error: "Notification not found"
    NotificationListItem:
      type: "object"
      description: "Transformed notification row returned to the UI. Built from `Notification` doc + per-user `status` from `User.notifications`."
      properties:
        id:
          type: "string"
        title:
          type: "string"
        message:
          type: "string"
        category:
          type: "string"
        createdAt:
          type: "string"
          format: "date-time"
        status:
          type: "string"
          description: "Per-user status from `User.notifications[].status` (defaults to `unread`)."
        notificationType:
          type: "string"
          description: "e.g. `mention`, `assignment`, `other`."
        contactId:
          type: "string"
          nullable: true
        contactName:
          type: "string"
          nullable: true
        phoneNumber:
          type: "string"
          nullable: true
        userId:
          type: "string"
          nullable: true
        mentionedBy:
          type: "string"
          nullable: true
        campaignId:
          type: "string"
          nullable: true
        messageId:
          type: "string"
          nullable: true
      required:
        - "id"
      additionalProperties: true
      example:
        id: "66e0a0b0c0d0e0f0a0b0c0d0"
        title: "Cory Tan mentioned you"
        message: "@alice please review this lead"
        category: "mention"
        createdAt: "2026-05-18T14:30:00.000Z"
        status: "unread"
        notificationType: "mention"
        contactId: "65c2d0e0f0a0b0c0d0e0f0a0"
        contactName: "Jane Doe"
        phoneNumber: "+14155550123"
        mentionedBy: "65b1f0a2c3d4e5f6a7b8c9d3"
    NotificationListResponse:
      type: "array"
      description: "Raw array - the GET handler returns the list directly without a `{ success, data }` envelope. If the user has no notifications the array is empty."
      items:
        "$ref": "#/components/schemas/NotificationListItem"
      example:
        -
          id: "66e0a0b0c0d0e0f0a0b0c0d0"
          title: "Cory Tan mentioned you"
          message: "@alice please review this lead"
          category: "mention"
          createdAt: "2026-05-18T14:30:00.000Z"
          status: "unread"
          notificationType: "mention"
          contactId: "65c2d0e0f0a0b0c0d0e0f0a0"
          contactName: "Jane Doe"
          phoneNumber: "+14155550123"
    NotificationDeleteAllResponse:
      type: "object"
      properties:
        message:
          type: "string"
        count:
          type: "integer"
          description: "Number of notifications deleted. Omitted when there were no notifications to delete."
      required:
        - "message"
      additionalProperties: true
      example:
        message: "All notifications marked as read and deleted"
        count: 12
    NotificationDeleteOneResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        notificationId:
          type: "string"
      required:
        - "success"
        - "message"
        - "notificationId"
      additionalProperties: true
      example:
        success: true
        message: "Notification deleted"
        notificationId: "66e0a0b0c0d0e0f0a0b0c0d0"
    NotificationMentionsSentResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        notifications:
          type: "integer"
          description: "Count of notifications successfully created (excludes the author and any failures)."
        recipients:
          type: "array"
          description: "Mentioned userIds the handler attempted to notify, with the author filtered out."
          items:
            type: "string"
      required:
        - "success"
        - "notifications"
        - "recipients"
      additionalProperties: true
      example:
        success: true
        message: "Mention notifications sent"
        notifications: 2
        recipients:
          - "65b1f0a2c3d4e5f6a7b8c9d0"
          - "65b1f0a2c3d4e5f6a7b8c9d1"
    UpdateNotificationPreferencesRequest:
      type: "object"
      properties:
        enabled:
          type: "boolean"
          description: "When true, the client plays the notification sound on new messages."
        volume:
          type: "number"
          minimum: 0
          maximum: 1
          description: "Output volume 0-1."
      additionalProperties: false
      anyOf:
        -
          required:
            - "enabled"
        -
          required:
            - "volume"
      example:
        enabled: true
        volume: 0.75
    NotificationSoundsErrorResponse:
      type: "object"
      description: "Error envelope used by notification-sounds endpoints."
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
      additionalProperties: true
      example:
        success: false
        message: "User not found"
    NotificationSoundsListResponse:
      type: "object"
      description: "List of notification sounds. Currently returns an empty array - backend `NotificationConfig` model is not yet implemented (TODO in controller)."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            type: "object"
            description: "Placeholder shape; concrete fields will be defined once NotificationConfig lands."
            additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          []
    NotificationPreferencesResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            enabled:
              type: "boolean"
              description: "Defaults to true when not explicitly disabled on the user."
            volume:
              type: "number"
              minimum: 0
              maximum: 1
              description: "Defaults to 1.0."
          required:
            - "enabled"
            - "volume"
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          enabled: true
          volume: 0.75
    OrgSnapshotErrorResponse:
      type: "object"
      properties:
        error:
          type: "string"
        message:
          type: "string"
        details:
          {}
      additionalProperties: true
      example:
        error: "Snapshot not found"
        message: "No snapshot exists with the given id"
    OrgSnapshotMessageResponse:
      type: "object"
      properties:
        message:
          type: "string"
      additionalProperties: true
      example:
        message: "Snapshot deleted"
    OrgSnapshotCounts:
      type: "object"
      properties:
        pipelines:
          type: "integer"
        automations:
          type: "integer"
        prompts:
          type: "integer"
        templates:
          type: "integer"
      additionalProperties: true
      example:
        pipelines: 3
        automations: 12
        prompts: 20
        templates: 30
    OrgSnapshotSummary:
      type: "object"
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        description:
          type: "string"
          nullable: true
        sourceOrgName:
          type: "string"
          nullable: true
        sourceUserEmail:
          type: "string"
          nullable: true
        sourceUserName:
          type: "string"
          nullable: true
        counts:
          "$ref": "#/components/schemas/OrgSnapshotCounts"
        createdByName:
          type: "string"
          nullable: true
        createdAt:
          type: "string"
          format: "date-time"
          nullable: true
        updatedAt:
          type: "string"
          format: "date-time"
          nullable: true
      additionalProperties: true
      example:
        _id: "665f1a0c0e0a4b001a2c9f90"
        name: "Production baseline 2026-05"
        description: "Reference Acme Corp configuration for new-tenant onboarding."
        sourceOrgName: "Acme Corp"
        sourceUserEmail: "alex@acme.example"
        sourceUserName: "Alex Rep"
        counts:
          pipelines: 3
          automations: 12
          prompts: 20
          templates: 30
        createdByName: "Pat Superadmin"
        createdAt: "2026-05-15T09:00:00.000Z"
        updatedAt: "2026-05-15T09:00:00.000Z"
    OrgSnapshotDetail:
      allOf:
        -
          "$ref": "#/components/schemas/OrgSnapshotSummary"
        -
          type: "object"
          properties:
            sourceOrgId:
              type: "string"
              nullable: true
            sourceUserId:
              type: "string"
              nullable: true
            pipelines:
              type: "array"
              items:
                type: "object"
                additionalProperties: true
            automations:
              type: "array"
              items:
                type: "object"
                additionalProperties: true
            prompts:
              type: "array"
              items:
                type: "object"
                additionalProperties: true
            templates:
              type: "array"
              items:
                type: "object"
                additionalProperties: true
          additionalProperties: true
      example:
        _id: "665f1a0c0e0a4b001a2c9f90"
        name: "Production baseline 2026-05"
        counts:
          pipelines: 3
          automations: 12
          prompts: 20
          templates: 30
        sourceOrgId: "64ee9a8b1e7f2a0011223344"
        sourceUserId: "64ee9a8b1e7f2a0011223399"
        pipelines:
          -
            name: "Sales Funnel"
        automations:
          -
            name: "Move to Contacted on first reply"
        prompts:
          -
            name: "Default warm-up prompt"
        templates:
          -
            name: "Intro - new lead"
            type: "sms"
    OrgSnapshotListResponse:
      type: "object"
      properties:
        snapshots:
          type: "array"
          items:
            "$ref": "#/components/schemas/OrgSnapshotSummary"
      required:
        - "snapshots"
      additionalProperties: true
      example:
        snapshots:
          -
            _id: "665f1a0c0e0a4b001a2c9f90"
            name: "Production baseline 2026-05"
            sourceOrgName: "Acme Corp"
            counts:
              pipelines: 3
              automations: 12
              prompts: 20
              templates: 30
    OrgSnapshotDetailResponse:
      type: "object"
      properties:
        snapshot:
          "$ref": "#/components/schemas/OrgSnapshotDetail"
      required:
        - "snapshot"
      additionalProperties: true
      example:
        snapshot:
          _id: "665f1a0c0e0a4b001a2c9f90"
          name: "Production baseline 2026-05"
          counts:
            pipelines: 3
            automations: 12
            prompts: 20
            templates: 30
    OrgSnapshotCreateResponse:
      type: "object"
      properties:
        message:
          type: "string"
        snapshot:
          "$ref": "#/components/schemas/OrgSnapshotSummary"
      required:
        - "snapshot"
      additionalProperties: true
      example:
        message: "Snapshot created"
        snapshot:
          _id: "665f1a0c0e0a4b001a2c9f90"
          name: "Production baseline 2026-05"
          sourceOrgName: "Acme Corp"
          counts:
            pipelines: 3
            automations: 12
            prompts: 20
            templates: 30
    CreateOrgSnapshotRequest:
      type: "object"
      properties:
        name:
          type: "string"
          minLength: 1
          maxLength: 120
          description: "Snapshot display name shown in the snapshot picker."
        description:
          type: "string"
          maxLength: 500
          description: "Free-form notes describing what this snapshot captures."
        sourceOrgId:
          type: "string"
          description: "Organization whose state is being captured."
        sourceUserId:
          type: "string"
          description: "User triggering the snapshot (recorded for audit)."
      required:
        - "name"
        - "sourceOrgId"
        - "sourceUserId"
      additionalProperties: false
      example:
        name: "Production baseline 2026-05"
        description: "Reference Acme Corp configuration for new-tenant onboarding."
        sourceOrgId: "64ee9a8b1e7f2a0011223344"
        sourceUserId: "64ee9a8b1e7f2a0011223399"
    ApplyOrgSnapshotFirstUser:
      type: "object"
      properties:
        email:
          type: "string"
          format: "email"
        password:
          type: "string"
          minLength: 8
        fullName:
          type: "string"
        phoneNumber:
          type: "string"
          description: "Optional E.164-style phone (must start with +1 or +91 followed by 10 digits)."
        designation:
          type: "string"
      required:
        - "email"
        - "password"
        - "fullName"
      additionalProperties: false
      example:
        email: "admin@neworg.example"
        password: "TempPass!2026"
        fullName: "Morgan Admin"
        phoneNumber: "+14155550111"
        designation: "Operations Lead"
    ApplyOrgSnapshotRequest:
      type: "object"
      properties:
        orgName:
          type: "string"
        orgPhone:
          type: "string"
          description: "Organization phone (must start with +1 or +91 followed by 10 digits)."
        orgAddress:
          type: "string"
        firstUser:
          "$ref": "#/components/schemas/ApplyOrgSnapshotFirstUser"
      required:
        - "orgName"
        - "orgPhone"
        - "orgAddress"
      additionalProperties: false
      example:
        orgName: "NewOrg Holdings"
        orgPhone: "+14155550100"
        orgAddress: "100 King St W, Toronto, ON"
        firstUser:
          email: "admin@neworg.example"
          password: "TempPass!2026"
          fullName: "Morgan Admin"
          designation: "Operations Lead"
    ApplyOrgSnapshotResponse:
      type: "object"
      properties:
        message:
          type: "string"
        result:
          type: "object"
          properties:
            organizationId:
              type: "string"
            organizationName:
              type: "string"
            userId:
              type: "string"
              nullable: true
            userEmail:
              type: "string"
              nullable: true
            cloned:
              type: "object"
              properties:
                pipelines:
                  type: "integer"
                automations:
                  type: "integer"
                prompts:
                  type: "integer"
                templates:
                  type: "integer"
              additionalProperties: true
          additionalProperties: true
      additionalProperties: true
      example:
        message: "Snapshot applied"
        result:
          organizationId: "64ee9a8b1e7f2a0011223400"
          organizationName: "NewOrg Holdings"
          userId: "64ee9a8b1e7f2a0011223499"
          userEmail: "admin@neworg.example"
          cloned:
            pipelines: 3
            automations: 12
            prompts: 20
            templates: 30
    OrgSnapshotOrgUserItem:
      type: "object"
      properties:
        _id:
          type: "string"
        fullName:
          type: "string"
          nullable: true
        email:
          type: "string"
          nullable: true
        accessRole:
          type: "string"
          nullable: true
      additionalProperties: true
      example:
        _id: "64ee9a8b1e7f2a0011223399"
        fullName: "Alex Rep"
        email: "alex@acme.example"
        accessRole: "DEPARTMENT_HEAD"
    OrgSnapshotOrgUsersResponse:
      type: "object"
      properties:
        users:
          type: "array"
          items:
            "$ref": "#/components/schemas/OrgSnapshotOrgUserItem"
      required:
        - "users"
      additionalProperties: true
      example:
        users:
          -
            _id: "64ee9a8b1e7f2a0011223399"
            fullName: "Alex Rep"
            email: "alex@acme.example"
            accessRole: "DEPARTMENT_HEAD"
    OrganizationErrorResponse:
      type: "object"
      properties:
        error:
          type: "string"
        details:
          type: "string"
      additionalProperties: true
      example:
        error: "Organization not found"
        details: "No organization exists with the provided id"
    OrganizationMessageResponse:
      type: "object"
      properties:
        message:
          type: "string"
      additionalProperties: true
      example:
        message: "Organization details updated successfully"
    ContactDedupReviewContact:
      type: "object"
      properties:
        _id:
          type: "string"
        firstName:
          type: "string"
        lastName:
          type: "string"
        email:
          type: "string"
        phoneNumber:
          oneOf:
            -
              type: "string"
            -
              type: "array"
              items:
                "$ref": "#/components/schemas/ContactPhoneNumber"
        conflictingPhoneNumbers:
          type: "array"
          items:
            type: "string"
        conflictingEmails:
          type: "array"
          items:
            type: "string"
        isProvisional:
          type: "boolean"
      additionalProperties: true
      example:
        _id: "5f7b1c2e8a1d4e0012c3b4a5"
        firstName: "Jane"
        lastName: "Doe"
        email: "jane.doe@acme.example"
        phoneNumber:
          -
            value: "+14165550100"
            isPrimary: true
        conflictingPhoneNumbers:
          - "+14165550101"
        isProvisional: false
    ContactDedupReviewResolvedBy:
      type: "object"
      properties:
        _id:
          type: "string"
        fullName:
          type: "string"
        email:
          type: "string"
      additionalProperties: true
      example:
        _id: "5f7b1c2e8a1d4e0012c3b4a6"
        fullName: "Ops Admin"
        email: "ops@acme.example"
    ContactDedupReview:
      type: "object"
      properties:
        _id:
          type: "string"
        organizationId:
          type: "string"
        sourceContactId:
          oneOf:
            -
              type: "string"
            -
              "$ref": "#/components/schemas/ContactDedupReviewContact"
        candidateContactId:
          oneOf:
            -
              type: "string"
            -
              "$ref": "#/components/schemas/ContactDedupReviewContact"
        reviewSource:
          type: "string"
          enum:
            - "fuzzy_match"
            - "phone_conflict"
            - "email_conflict"
            - "lost_all_identifiers"
        status:
          type: "string"
          enum:
            - "needs_review"
            - "merged"
            - "kept_separate"
            - "superseded"
        score:
          type: "number"
        thresholdSnapshot:
          type: "object"
          additionalProperties: true
        fieldBreakdown:
          type: "object"
          additionalProperties: true
        sourceSnapshot:
          type: "object"
          additionalProperties: true
        candidateSnapshot:
          type: "object"
          additionalProperties: true
        resolution:
          type: "object"
          additionalProperties: true
        resolvedBy:
          oneOf:
            -
              type: "string"
            -
              "$ref": "#/components/schemas/ContactDedupReviewResolvedBy"
        resolvedAt:
          type: "string"
          format: "date-time"
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      required:
        - "reviewSource"
        - "status"
      additionalProperties: true
      example:
        _id: "5f7b1c2e8a1d4e0012c3b4b0"
        organizationId: "5f7b1c2e8a1d4e0012c3b400"
        sourceContactId: "5f7b1c2e8a1d4e0012c3b4a5"
        candidateContactId: "5f7b1c2e8a1d4e0012c3b4a7"
        reviewSource: "fuzzy_match"
        status: "needs_review"
        score: 86
        thresholdSnapshot:
          thresholdPercent: 90
          reviewThresholdPercent: 70
        fieldBreakdown:
          firstName: 100
          lastName: 80
          email: 75
        createdAt: "2026-05-18T14:30:00.000Z"
        updatedAt: "2026-05-18T14:30:00.000Z"
    ContactDedupReviewResolutionRequest:
      type: "object"
      properties:
        resolution:
          type: "object"
          additionalProperties: true
          description: "Freeform resolution payload recorded on the review; for merges, may include fieldChoices (source/candidate per field) and other reviewer-chosen metadata persisted with the merge audit entry."
      additionalProperties: true
      example:
        resolution:
          keepContactId: "5f7b1c2e8a1d4e0012c3b4a5"
          mergedFields:
            - "email"
            - "phoneNumber"
    ContactDedupReviewMutationResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        data:
          "$ref": "#/components/schemas/ContactDedupReview"
      required:
        - "success"
        - "message"
        - "data"
      additionalProperties: true
      example:
        success: true
        message: "Contact dedup review marked as merged"
        data:
          _id: "5f7b1c2e8a1d4e0012c3b4b0"
          organizationId: "5f7b1c2e8a1d4e0012c3b400"
          reviewSource: "fuzzy_match"
          status: "merged"
          resolvedAt: "2026-05-18T14:35:00.000Z"
    AdminDetailsInput:
      type: "object"
      properties:
        email:
          type: "string"
        password:
          type: "string"
        fullName:
          type: "string"
        phoneNumber:
          type: "string"
        designation:
          type: "string"
      required:
        - "email"
        - "password"
        - "fullName"
      additionalProperties: true
      example:
        email: "admin@acme.example"
        password: "CorrectHorseBatteryStaple9!"
        fullName: "Alex Admin"
        phoneNumber: "+14165550100"
        designation: "Operations Lead"
    CredsInput:
      type: "object"
      properties:
        anthropicApiKey:
          type: "string"
        sinchServicePlanId:
          type: "string"
        sinchApiToken:
          type: "string"
        sinchMmsApiKey:
          type: "string"
        sinchMmsServiceId:
          type: "string"
      additionalProperties: true
      example:
        anthropicApiKey: "sk-ant-api03-EXAMPLE-key-redacted"
        sinchServicePlanId: "srv-plan-example-123"
        sinchApiToken: "sinch-token-example-redacted"
        sinchMmsApiKey: "sinch-mms-key-example"
        sinchMmsServiceId: "sinch-mms-service-example"
    CreateOrganizationRequest:
      type: "object"
      properties:
        name:
          type: "string"
          description: "Organization display name shown across UI and templates."
        phoneNumber:
          type: "string"
          description: "Primary organization phone number in E.164 format (must start with +1 or +91 followed by 10 digits)."
        address:
          type: "string"
          description: "Mailing/business address for the organization."
        creds:
          "$ref": "#/components/schemas/CredsInput"
          description: "Optional third-party API credentials (Anthropic, Sinch SMS/MMS) provisioned for the new organization."
        adminDetails:
          "$ref": "#/components/schemas/AdminDetailsInput"
          description: "Initial admin user created alongside the organization; email and password seed the first login."
      required:
        - "name"
        - "phoneNumber"
        - "adminDetails"
      additionalProperties: true
      example:
        name: "Acme Corp"
        phoneNumber: "+14165550100"
        address: "123 Yonge St, Toronto, ON"
        adminDetails:
          email: "admin@acme.example"
          password: "CorrectHorseBatteryStaple9!"
          fullName: "Alex Admin"
    CreateOrganizationResponse:
      type: "object"
      properties:
        message:
          type: "string"
        data:
          type: "object"
          additionalProperties: true
      additionalProperties: true
      example:
        message: "Organization with admin user created successfully"
        data:
          _id: "5f7b1c2e8a1d4e0012c3b400"
          name: "Acme Corp"
          phoneNumber: "+14165550100"
    OrganizationDto:
      type: "object"
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        phoneNumber:
          type: "string"
        address:
          type: "string"
        logoUrl:
          type: "string"
        loginDisabled:
          type: "boolean"
        contactProtectionPeriod:
          type: "number"
      additionalProperties: true
      example:
        _id: "5f7b1c2e8a1d4e0012c3b400"
        name: "Acme Corp"
        phoneNumber: "+14165550100"
        address: "123 Yonge St, Toronto, ON"
        logoUrl: "https://cdn.example.com/logos/acme.png?sig=..."
        loginDisabled: false
        contactProtectionPeriod: 24
    OrganizationListResponse:
      type: "object"
      properties:
        organizations:
          type: "array"
          items:
            "$ref": "#/components/schemas/OrganizationDto"
      additionalProperties: true
      example:
        organizations:
          -
            _id: "5f7b1c2e8a1d4e0012c3b400"
            name: "Acme Corp"
            phoneNumber: "+14165550100"
            address: "123 Yonge St, Toronto, ON"
            loginDisabled: false
            contactProtectionPeriod: 24
    OrganizationDetailsResponse:
      type: "object"
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        phoneNumber:
          type: "string"
        address:
          type: "string"
        logoUrl:
          type: "string"
      additionalProperties: true
      example:
        _id: "5f7b1c2e8a1d4e0012c3b400"
        name: "Acme Corp"
        phoneNumber: "+14165550100"
        address: "123 Yonge St, Toronto, ON"
        logoUrl: "https://cdn.example.com/logos/acme.png?sig=..."
    UpdateOrganizationDetailsRequest:
      type: "object"
      properties:
        name:
          type: "string"
          description: "Updated organization display name."
        phoneNumber:
          type: "string"
          description: "Updated primary organization phone number in E.164 format."
        address:
          type: "string"
          description: "Updated mailing/business address."
        logoUrl:
          type: "string"
          description: "New logo image; accepts a data URI (e.g. base64 PNG) which the server uploads and stores as a hosted URL."
      additionalProperties: true
      example:
        name: "Acme Corp"
        phoneNumber: "+14165550100"
        address: "123 Yonge St, Toronto, ON"
        logoUrl: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..."
    GetApiKeysRequest:
      type: "object"
      properties:
        id:
          type: "string"
          description: "Organization ID whose third-party API credentials should be returned."
      additionalProperties: true
      example:
        id: "5f7b1c2e8a1d4e0012c3b400"
    UpdateApiKeysRequest:
      type: "object"
      properties:
        id:
          type: "string"
          description: "Organization ID whose details and credentials should be updated."
        name:
          type: "string"
          description: "Updated organization display name."
        phoneNumber:
          type: "string"
          description: "Updated primary organization phone number in E.164 format."
        address:
          type: "string"
          description: "Updated mailing/business address."
        logoUrl:
          type: "string"
          description: "Optional logo image; accepts a data URI which the server uploads and stores."
        creds:
          "$ref": "#/components/schemas/CredsInput"
          description: "Replacement third-party API credentials (Anthropic, Sinch SMS/MMS) attached to the organization."
      required:
        - "id"
        - "creds"
      additionalProperties: true
      example:
        id: "5f7b1c2e8a1d4e0012c3b400"
        name: "Acme Corp"
        phoneNumber: "+14165550100"
        address: "123 Yonge St, Toronto, ON"
        creds:
          anthropicApiKey: "sk-ant-api03-EXAMPLE-key-redacted"
          sinchServicePlanId: "srv-plan-example-123"
    ApiKeysResponse:
      type: "object"
      properties:
        _id:
          type: "string"
        anthropicApiKey:
          type: "string"
        sinchServicePlanId:
          type: "string"
        sinchApiToken:
          type: "string"
        sinchMmsApiKey:
          type: "string"
        sinchMmsServiceId:
          type: "string"
      additionalProperties: true
      example:
        _id: "5f7b1c2e8a1d4e0012c3b410"
        anthropicApiKey: "sk-ant-api03-EXAMPLE-key-redacted"
        sinchServicePlanId: "srv-plan-example-123"
        sinchApiToken: "sinch-token-example-redacted"
        sinchMmsApiKey: "sinch-mms-key-example"
        sinchMmsServiceId: "sinch-mms-service-example"
    OrganizationDeleteResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        message:
          type: "string"
        error:
          type: "string"
        details:
          type: "string"
      additionalProperties: true
      example:
        success: true
        message: "Organization deleted successfully"
    UpdateEscalationSettingsRequest:
      type: "object"
      properties:
        maxUnresolvedChatsPerAgent:
          type: "number"
          description: "Per-agent cap on concurrent unresolved chats before new conversations are queued instead of auto-assigned (default 3)."
      additionalProperties: true
      example:
        maxUnresolvedChatsPerAgent: 5
    EscalationSettingsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "object"
          properties:
            maxUnresolvedChatsPerAgent:
              type: "number"
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        data:
          maxUnresolvedChatsPerAgent: 3
    EscalationSettingsUpdateResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        message:
          type: "string"
        data:
          type: "object"
          properties:
            maxUnresolvedChatsPerAgent:
              type: "number"
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        message: "Escalation settings updated"
        data:
          maxUnresolvedChatsPerAgent: 5
    UpdateWebchatSettingsRequest:
      type: "object"
      properties:
        showSenderNameInWebchat:
          type: "boolean"
          description: "When true, webchat reveals the sender name on each message (agent persona name for humans, the configured assistant name for autopilot)."
        aiAssistantName:
          type: "string"
          description: "Display name shown for AI/autopilot messages in webchat; falls back to \"AI Assistant\" when empty."
      additionalProperties: true
      example:
        showSenderNameInWebchat: true
        aiAssistantName: "Acme Assistant"
    WebchatSettingsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "object"
          properties:
            showSenderNameInWebchat:
              type: "boolean"
            aiAssistantName:
              type: "string"
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        data:
          showSenderNameInWebchat: true
          aiAssistantName: "Acme Assistant"
    WebchatSettingsUpdateResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        message:
          type: "string"
        data:
          type: "object"
          properties:
            showSenderNameInWebchat:
              type: "boolean"
            aiAssistantName:
              type: "string"
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        message: "Webchat settings updated"
        data:
          showSenderNameInWebchat: true
          aiAssistantName: "Acme Assistant"
    UpdateAiCostSettingsRequest:
      type: "object"
      required:
        - "elevenlabsUsdPerCredit"
      properties:
        elevenlabsUsdPerCredit:
          type: "number"
          nullable: true
          minimum: 0
          exclusiveMinimum: true
          maximum: 0.01
          description: "USD per ElevenLabs credit; null goes back to the default (0.0001)."
      additionalProperties: false
      example:
        elevenlabsUsdPerCredit: 0.00012
    VoiceRepriceStatus:
      type: "object"
      description: "The latest run that rebuilt the voice rows after the rate changed."
      properties:
        jobId:
          type: "string"
        status:
          type: "string"
          enum:
            - "queued"
            - "running"
            - "done"
            - "failed"
        usdPerCredit:
          type: "number"
        requestedAt:
          type: "string"
          format: "date-time"
        startedAt:
          type: "string"
          format: "date-time"
          nullable: true
        progressAt:
          type: "string"
          format: "date-time"
          nullable: true
          description: "Last time the run finished a batch of calls."
        finishedAt:
          type: "string"
          format: "date-time"
          nullable: true
        calls:
          type: "integer"
          nullable: true
        inserted:
          type: "integer"
          nullable: true
        rewritten:
          type: "integer"
          nullable: true
        error:
          type: "string"
          nullable: true
    AiCostSettings:
      type: "object"
      properties:
        elevenlabsUsdPerCredit:
          type: "number"
          nullable: true
        effectiveUsdPerCredit:
          type: "number"
        defaultUsdPerCredit:
          type: "number"
        maxUsdPerCredit:
          type: "number"
        voiceReprice:
          allOf:
            -
              "$ref": "#/components/schemas/VoiceRepriceStatus"
          nullable: true
    AiCostSettingsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          "$ref": "#/components/schemas/AiCostSettings"
      example:
        success: true
        data:
          elevenlabsUsdPerCredit: 0.00012
          effectiveUsdPerCredit: 0.00012
          defaultUsdPerCredit: 0.0001
          maxUsdPerCredit: 0.01
          voiceReprice:
            jobId: "voice-reprice-6a0d978d0000000000000a01-1793300000000-6a0d978d0000000000000b01"
            status: "done"
            usdPerCredit: 0.00012
            requestedAt: "2026-10-29T10:00:00.000Z"
            startedAt: "2026-10-29T10:00:01.000Z"
            progressAt: "2026-10-29T10:00:05.000Z"
            finishedAt: "2026-10-29T10:00:06.000Z"
            calls: 108
            inserted: 207
            rewritten: 7
    AiCostSettingsUpdateResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        repriceQueued:
          type: "boolean"
        data:
          "$ref": "#/components/schemas/AiCostSettings"
      example:
        success: true
        repriceQueued: true
        data:
          elevenlabsUsdPerCredit: 0.00012
          effectiveUsdPerCredit: 0.00012
          defaultUsdPerCredit: 0.0001
          maxUsdPerCredit: 0.01
          voiceReprice:
            jobId: "voice-reprice-6a0d978d0000000000000a01-1793300000000-6a0d978d0000000000000b01"
            status: "queued"
            usdPerCredit: 0.00012
            requestedAt: "2026-10-29T10:00:00.000Z"
    UpdateSessionSettingsRequest:
      type: "object"
      properties:
        enabled:
          type: "boolean"
          nullable: true
        idleTimeoutMinutes:
          type: "number"
          nullable: true
        tokenExpiryHours:
          type: "number"
          nullable: true
        warningTimeMinutes:
          type: "number"
          nullable: true
        idleTrackingEnabled:
          type: "boolean"
          nullable: true
        ssoSilentRenewalEnabled:
          type: "boolean"
          nullable: true
        ssoFallbackBehavior:
          type: "string"
          nullable: true
          enum:
            - "reauth-button"
            - "force-logout"
          description: "Set to null to revert to global default"
        passwordSilentRenewalEnabled:
          type: "boolean"
          nullable: true
        passwordFallbackBehavior:
          type: "string"
          nullable: true
          enum:
            - "reauth-modal"
            - "force-logout"
          description: "Set to null to revert to global default"
      additionalProperties: true
      example:
        enabled: true
        idleTimeoutMinutes: 30
        tokenExpiryHours: 12
        warningTimeMinutes: 2
        idleTrackingEnabled: true
        ssoSilentRenewalEnabled: true
        ssoFallbackBehavior: "reauth-button"
        passwordSilentRenewalEnabled: false
        passwordFallbackBehavior: "reauth-modal"
    SessionSettingsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "object"
          properties:
            enabled:
              type: "boolean"
              nullable: true
            idleTimeoutMinutes:
              type: "number"
              nullable: true
            tokenExpiryHours:
              type: "number"
              nullable: true
            warningTimeMinutes:
              type: "number"
              nullable: true
            idleTrackingEnabled:
              type: "boolean"
              nullable: true
            ssoSilentRenewalEnabled:
              type: "boolean"
              nullable: true
            ssoFallbackBehavior:
              type: "string"
              nullable: true
            passwordSilentRenewalEnabled:
              type: "boolean"
              nullable: true
            passwordFallbackBehavior:
              type: "string"
              nullable: true
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        data:
          enabled: true
          idleTimeoutMinutes: 30
          tokenExpiryHours: 12
          warningTimeMinutes: 2
          idleTrackingEnabled: true
          ssoSilentRenewalEnabled: true
          ssoFallbackBehavior: "reauth-button"
          passwordSilentRenewalEnabled: false
          passwordFallbackBehavior: "reauth-modal"
    SessionSettingsUpdateResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        message:
          type: "string"
        data:
          type: "object"
          properties:
            enabled:
              type: "boolean"
              nullable: true
            idleTimeoutMinutes:
              type: "number"
              nullable: true
            tokenExpiryHours:
              type: "number"
              nullable: true
            warningTimeMinutes:
              type: "number"
              nullable: true
            idleTrackingEnabled:
              type: "boolean"
              nullable: true
            ssoSilentRenewalEnabled:
              type: "boolean"
              nullable: true
            ssoFallbackBehavior:
              type: "string"
              nullable: true
            passwordSilentRenewalEnabled:
              type: "boolean"
              nullable: true
            passwordFallbackBehavior:
              type: "string"
              nullable: true
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        message: "Session settings updated"
        data:
          enabled: true
          idleTimeoutMinutes: 30
          tokenExpiryHours: 12
          warningTimeMinutes: 2
          idleTrackingEnabled: true
          ssoSilentRenewalEnabled: true
          ssoFallbackBehavior: "reauth-button"
          passwordSilentRenewalEnabled: false
          passwordFallbackBehavior: "reauth-modal"
    BlockedIPsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "object"
          properties:
            blockedIPs:
              type: "array"
              items:
                type: "string"
            ipBlockedMessage:
              type: "string"
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        data:
          blockedIPs:
            - "203.0.113.42"
            - "198.51.100.7"
          ipBlockedMessage: "Due to previous violations your IP has been blocked"
    AddBlockedIPRequest:
      type: "object"
      properties:
        ip:
          type: "string"
          description: "IPv4 or IPv6 address to add to the organization's blocklist; webchat requests from this address are rejected with the configured block message."
      required:
        - "ip"
      additionalProperties: true
      example:
        ip: "203.0.113.42"
    BlockedIPMutationResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        message:
          type: "string"
        data:
          type: "object"
          properties:
            blockedIPs:
              type: "array"
              items:
                type: "string"
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        message: "IP blocked successfully"
        data:
          blockedIPs:
            - "203.0.113.42"
    UpdateIPBlockedMessageRequest:
      type: "object"
      properties:
        message:
          type: "string"
          description: "User-facing message shown when a blocked IP attempts to start a webchat session."
      required:
        - "message"
      additionalProperties: true
      example:
        message: "Access from your network is currently restricted. Please contact support."
    IPBlockedMessageResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "object"
          properties:
            ipBlockedMessage:
              type: "string"
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        data:
          ipBlockedMessage: "Access from your network is currently restricted. Please contact support."
    DashboardUserDto:
      type: "object"
      properties:
        _id:
          type: "string"
        fullName:
          type: "string"
        email:
          type: "string"
        phoneNumber:
          type: "string"
        designation:
          type: "string"
        accessRole:
          type: "string"
        loginDisabled:
          type: "boolean"
        isPasswordDisabled:
          type: "boolean"
      additionalProperties: true
      example:
        _id: "5f7b1c2e8a1d4e0012c3b4a6"
        fullName: "Alex Admin"
        email: "admin@acme.example"
        phoneNumber: "+14165550100"
        designation: "Operations Lead"
        accessRole: "ADMIN"
        loginDisabled: false
        isPasswordDisabled: false
    DashboardOrganizationDto:
      type: "object"
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        address:
          type: "string"
        phoneNumber:
          type: "string"
        logoUrl:
          type: "string"
        loginDisabled:
          type: "boolean"
        users:
          type: "array"
          items:
            "$ref": "#/components/schemas/DashboardUserDto"
      additionalProperties: true
      example:
        _id: "5f7b1c2e8a1d4e0012c3b400"
        name: "Acme Corp"
        address: "123 Yonge St, Toronto, ON"
        phoneNumber: "+14165550100"
        logoUrl: "https://cdn.example.com/logos/acme.png?sig=..."
        loginDisabled: false
        users:
          -
            _id: "5f7b1c2e8a1d4e0012c3b4a6"
            fullName: "Alex Admin"
            email: "admin@acme.example"
            accessRole: "ADMIN"
    DashboardResponse:
      type: "object"
      properties:
        stats:
          type: "object"
          properties:
            totalOrganizations:
              type: "integer"
            totalUsers:
              type: "integer"
            totalAdmins:
              type: "integer"
          additionalProperties: true
        organizations:
          type: "array"
          items:
            "$ref": "#/components/schemas/DashboardOrganizationDto"
      additionalProperties: true
      example:
        stats:
          totalOrganizations: 12
          totalUsers: 84
          totalAdmins: 18
        organizations:
          -
            _id: "5f7b1c2e8a1d4e0012c3b400"
            name: "Acme Corp"
            address: "123 Yonge St, Toronto, ON"
            phoneNumber: "+14165550100"
            loginDisabled: false
            users:
              -
                _id: "5f7b1c2e8a1d4e0012c3b4a6"
                fullName: "Alex Admin"
                email: "admin@acme.example"
                accessRole: "ADMIN"
    OrganizationStatusErrorResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
      additionalProperties: true
      example:
        success: false
        message: "Access denied"
    OrganizationByIdResponse:
      type: "object"
      description: "Full organization document (Mongo-shaped) with populated credentials and a resolved logoUrl. Shape is intentionally permissive because the document is returned as-is from Mongo."
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        phoneNumber:
          type: "string"
        address:
          type: "string"
        logoUrl:
          type: "string"
          nullable: true
        credentials:
          type: "object"
          additionalProperties: true
      additionalProperties: true
      example:
        _id: "5f7b1c2e8a1d4e0012c3b400"
        name: "Acme Corp"
        phoneNumber: "+14165550100"
        address: "123 Yonge St, Toronto, ON"
        logoUrl: "https://cdn.example.com/logos/acme.png?sig=..."
        credentials:
          _id: "5f7b1c2e8a1d4e0012c3b410"
          anthropicApiKey: "sk-ant-api03-EXAMPLE-key-redacted"
          sinchServicePlanId: "srv-plan-example-123"
    AutopilotMonitorSettingsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            thresholdMinutes:
              type: "integer"
              minimum: 1
              default: 5
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        data:
          thresholdMinutes: 5
    UpdateAutopilotMonitorSettingsRequest:
      type: "object"
      properties:
        thresholdMinutes:
          type: "integer"
          minimum: 1
          description: "Minutes a conversation may remain stalled on autopilot before the monitor flags it for human attention (default 5)."
      required:
        - "thresholdMinutes"
      additionalProperties: true
      example:
        thresholdMinutes: 10
    AutopilotMonitorSettingsUpdateResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        data:
          type: "object"
          properties:
            thresholdMinutes:
              type: "integer"
              minimum: 1
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        message: "Autopilot monitor settings updated"
        data:
          thresholdMinutes: 10
    OrgBusinessHoursDay:
      type: "object"
      properties:
        enabled:
          type: "boolean"
        start:
          type: "string"
          description: "HH:mm 24h time"
        end:
          type: "string"
          description: "HH:mm 24h time"
      required:
        - "enabled"
        - "start"
        - "end"
      additionalProperties: true
      example:
        enabled: true
        start: "09:00"
        end: "17:00"
    OrgBusinessHoursSchedule:
      type: "object"
      properties:
        monday:
          "$ref": "#/components/schemas/OrgBusinessHoursDay"
        tuesday:
          "$ref": "#/components/schemas/OrgBusinessHoursDay"
        wednesday:
          "$ref": "#/components/schemas/OrgBusinessHoursDay"
        thursday:
          "$ref": "#/components/schemas/OrgBusinessHoursDay"
        friday:
          "$ref": "#/components/schemas/OrgBusinessHoursDay"
        saturday:
          "$ref": "#/components/schemas/OrgBusinessHoursDay"
        sunday:
          "$ref": "#/components/schemas/OrgBusinessHoursDay"
      additionalProperties: false
      example:
        monday:
          enabled: true
          start: "09:00"
          end: "17:00"
        tuesday:
          enabled: true
          start: "09:00"
          end: "17:00"
        wednesday:
          enabled: true
          start: "09:00"
          end: "17:00"
        thursday:
          enabled: true
          start: "09:00"
          end: "17:00"
        friday:
          enabled: true
          start: "09:00"
          end: "17:00"
        saturday:
          enabled: false
          start: "09:00"
          end: "17:00"
        sunday:
          enabled: false
          start: "09:00"
          end: "17:00"
    OrgBusinessHoursHoliday:
      type: "object"
      properties:
        date:
          type: "string"
          description: "YYYY-MM-DD"
        label:
          type: "string"
      required:
        - "date"
      additionalProperties: true
      example:
        date: "2026-12-25"
        label: "Christmas Day"
    OrgBusinessHoursException:
      type: "object"
      properties:
        date:
          type: "string"
          description: "YYYY-MM-DD"
        closed:
          type: "boolean"
        start:
          type: "string"
          description: "HH:mm when not closed"
        end:
          type: "string"
          description: "HH:mm when not closed"
        label:
          type: "string"
      required:
        - "date"
      additionalProperties: true
      example:
        date: "2026-12-24"
        closed: false
        start: "09:00"
        end: "13:00"
        label: "Christmas Eve early close"
    OrgBusinessHoursData:
      type: "object"
      properties:
        timezone:
          type: "string"
          nullable: true
        businessHours:
          nullable: true
          allOf:
            -
              "$ref": "#/components/schemas/OrgBusinessHoursSchedule"
        holidays:
          type: "array"
          items:
            "$ref": "#/components/schemas/OrgBusinessHoursHoliday"
        exceptionalHours:
          type: "array"
          items:
            "$ref": "#/components/schemas/OrgBusinessHoursException"
        allowUserBusinessHoursOverride:
          type: "boolean"
      additionalProperties: true
      example:
        timezone: "America/New_York"
        businessHours:
          monday:
            enabled: true
            start: "09:00"
            end: "17:00"
          friday:
            enabled: true
            start: "09:00"
            end: "15:00"
        holidays:
          -
            date: "2026-12-25"
            label: "Christmas Day"
        exceptionalHours:
          -
            date: "2026-12-24"
            closed: false
            start: "09:00"
            end: "13:00"
            label: "Christmas Eve"
        allowUserBusinessHoursOverride: false
    OrgBusinessHoursResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          "$ref": "#/components/schemas/OrgBusinessHoursData"
      additionalProperties: true
      example:
        success: true
        data:
          timezone: "America/New_York"
          businessHours:
            monday:
              enabled: true
              start: "09:00"
              end: "17:00"
          holidays:
            -
              date: "2026-12-25"
              label: "Christmas Day"
          exceptionalHours:
            []
          allowUserBusinessHoursOverride: false
    UpdateOrgBusinessHoursRequest:
      type: "object"
      properties:
        timezone:
          type: "string"
          description: "IANA timezone (e.g. America/New_York)"
        businessHours:
          nullable: true
          description: "Weekly schedule keyed by lowercase day name; pass null to clear."
          allOf:
            -
              "$ref": "#/components/schemas/OrgBusinessHoursSchedule"
        holidays:
          type: "array"
          items:
            "$ref": "#/components/schemas/OrgBusinessHoursHoliday"
          maxItems: 200
        exceptionalHours:
          type: "array"
          items:
            "$ref": "#/components/schemas/OrgBusinessHoursException"
          maxItems: 200
        allowUserBusinessHoursOverride:
          type: "boolean"
      additionalProperties: true
      example:
        timezone: "America/New_York"
        businessHours:
          monday:
            enabled: true
            start: "09:00"
            end: "17:00"
          tuesday:
            enabled: true
            start: "09:00"
            end: "17:00"
          wednesday:
            enabled: true
            start: "09:00"
            end: "17:00"
          thursday:
            enabled: true
            start: "09:00"
            end: "17:00"
          friday:
            enabled: true
            start: "09:00"
            end: "15:00"
        holidays:
          -
            date: "2026-12-25"
            label: "Christmas Day"
        exceptionalHours:
          []
        allowUserBusinessHoursOverride: false
    ContactFuzzyMergeCustomFieldRule:
      type: "object"
      properties:
        field:
          type: "string"
        weight:
          type: "number"
          minimum: 0
          maximum: 100
        matchMode:
          type: "string"
          enum:
            - "exact_normalized"
            - "fuzzy_string"
      required:
        - "field"
        - "weight"
        - "matchMode"
      additionalProperties: true
      example:
        field: "address.streetAddress"
        weight: 25
        matchMode: "fuzzy_string"
    ContactFuzzyMergeSettingsData:
      type: "object"
      properties:
        candidateLimit:
          type: "integer"
          minimum: 1
          maximum: 200
        thresholdPercent:
          type: "number"
          minimum: 0
          maximum: 100
        reviewThresholdPercent:
          type: "number"
          minimum: 0
          maximum: 100
        customFields:
          type: "array"
          items:
            "$ref": "#/components/schemas/ContactFuzzyMergeCustomFieldRule"
        lookupTriggerFields:
          type: "array"
          items:
            type: "string"
        instantMergeFields:
          type: "array"
          items:
            type: "string"
        conflictResolutionRules:
          type: "object"
          additionalProperties: true
          description: "Per-field conflict resolution rules keyed by field name."
      additionalProperties: true
      example:
        candidateLimit: 50
        thresholdPercent: 90
        reviewThresholdPercent: 70
        customFields:
          -
            field: "address.streetAddress"
            weight: 25
            matchMode: "fuzzy_string"
        lookupTriggerFields:
          - "email"
          - "phoneNumber"
        instantMergeFields:
          - "email"
        conflictResolutionRules:
          email: "prefer_newer"
    ContactFuzzyMergeSettingsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          "$ref": "#/components/schemas/ContactFuzzyMergeSettingsData"
      additionalProperties: true
      example:
        success: true
        data:
          candidateLimit: 50
          thresholdPercent: 90
          reviewThresholdPercent: 70
          customFields:
            []
          lookupTriggerFields:
            - "email"
            - "phoneNumber"
          instantMergeFields:
            - "email"
          conflictResolutionRules:
            {}
    UpdateContactFuzzyMergeSettingsRequest:
      type: "object"
      properties:
        candidateLimit:
          type: "integer"
          minimum: 1
          maximum: 200
        thresholdPercent:
          type: "number"
          minimum: 0
          maximum: 100
        reviewThresholdPercent:
          type: "number"
          minimum: 0
          maximum: 100
        threshold:
          type: "integer"
          minimum: 0
          description: "Optional absolute threshold; converted to thresholdPercent against the max possible score."
        reviewThreshold:
          type: "integer"
          minimum: 0
          description: "Optional absolute review threshold; converted to reviewThresholdPercent against the max possible score."
        customFields:
          type: "array"
          items:
            "$ref": "#/components/schemas/ContactFuzzyMergeCustomFieldRule"
        lookupTriggerFields:
          type: "array"
          items:
            type: "string"
        instantMergeFields:
          type: "array"
          items:
            type: "string"
        conflictResolutionRules:
          type: "object"
          additionalProperties: true
      additionalProperties: true
      example:
        candidateLimit: 100
        thresholdPercent: 92
        reviewThresholdPercent: 75
        customFields:
          -
            field: "address.streetAddress"
            weight: 20
            matchMode: "fuzzy_string"
        lookupTriggerFields:
          - "email"
          - "phoneNumber"
        instantMergeFields:
          - "email"
    ContactFuzzyMergeSettingsUpdateResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        data:
          "$ref": "#/components/schemas/ContactFuzzyMergeSettingsData"
      additionalProperties: true
      example:
        success: true
        message: "Contact fuzzy merge settings updated"
        data:
          candidateLimit: 100
          thresholdPercent: 92
          reviewThresholdPercent: 75
          customFields:
            []
          lookupTriggerFields:
            - "email"
            - "phoneNumber"
          instantMergeFields:
            - "email"
          conflictResolutionRules:
            {}
    ContactProtectionSettingsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            contactProtectionPeriod:
              type: "integer"
              minimum: 0
              maximum: 720
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        data:
          contactProtectionPeriod: 24
    UpdateContactProtectionSettingsRequest:
      type: "object"
      properties:
        contactProtectionPeriod:
          type: "integer"
          minimum: 0
          maximum: 720
          description: "Hours; capped at 720 (30 days)"
      required:
        - "contactProtectionPeriod"
      additionalProperties: true
      example:
        contactProtectionPeriod: 48
    ContactProtectionSettingsUpdateResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        data:
          type: "object"
          properties:
            contactProtectionPeriod:
              type: "integer"
              minimum: 0
              maximum: 720
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        message: "Contact protection settings updated"
        data:
          contactProtectionPeriod: 48
    OrgDocumentType:
      type: "object"
      properties:
        name:
          type: "string"
        isRequired:
          type: "boolean"
        description:
          type: "string"
      required:
        - "name"
      additionalProperties: true
      example:
        name: "Paystub"
        isRequired: true
        description: "Most recent two paystubs"
    OrgDocumentTypesResponse:
      type: "object"
      properties:
        documentTypes:
          type: "array"
          items:
            "$ref": "#/components/schemas/OrgDocumentType"
      additionalProperties: true
      example:
        documentTypes:
          -
            name: "Credit Bureau"
            isRequired: true
          -
            name: "Paystub"
            isRequired: true
          -
            name: "Bank Statement"
            isRequired: false
    UpdateOrgDocumentTypesRequest:
      type: "object"
      properties:
        documentTypes:
          type: "array"
          items:
            "$ref": "#/components/schemas/OrgDocumentType"
          description: "Full replacement list of document types the organization collects from contacts; each entry carries a name, required flag, and optional description."
      required:
        - "documentTypes"
      additionalProperties: true
      example:
        documentTypes:
          -
            name: "Credit Bureau"
            isRequired: true
          -
            name: "Paystub"
            isRequired: true
    OrgDocumentTypesUpdateResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        documentTypes:
          type: "array"
          items:
            "$ref": "#/components/schemas/OrgDocumentType"
      additionalProperties: true
      example:
        success: true
        documentTypes:
          -
            name: "Credit Bureau"
            isRequired: true
          -
            name: "Paystub"
            isRequired: true
    ExtractionRule:
      type: "object"
      properties:
        mode:
          type: "string"
          enum:
            - "allowlist"
            - "blacklist"
        values:
          type: "array"
          items:
            type: "string"
        regex:
          type: "array"
          items:
            type: "string"
        prompt:
          type: "string"
          maxLength: 500
        backgroundExtractable:
          type: "boolean"
      additionalProperties: true
      example:
        mode: "allowlist"
        values:
          - "ON"
          - "QC"
          - "BC"
          - "AB"
        regex:
          - "^[A-Z]{2}$"
        prompt: "Two-letter Canadian province code"
    ExtractionRulesResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            builtInFields:
              type: "object"
              additionalProperties:
                "$ref": "#/components/schemas/ExtractionRule"
            customFields:
              type: "object"
              additionalProperties:
                "$ref": "#/components/schemas/ExtractionRule"
            backgroundExtractionMode:
              type: "string"
              enum:
                - "inbound"
                - "outbound"
                - "all"
              description: "Org-level toggle: which text-channel message directions the background extractor runs on. Defaults to \"all\"."
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        data:
          backgroundExtractionMode: "all"
          builtInFields:
            province:
              mode: "allowlist"
              values:
                - "ON"
                - "QC"
                - "BC"
                - "AB"
              regex:
                - "^[A-Z]{2}$"
          customFields:
            creditScore:
              mode: "allowlist"
              values:
                []
              regex:
                - "^\\d{3}$"
              prompt: "Three-digit credit score"
    UpdateExtractionRulesRequest:
      type: "object"
      properties:
        builtInFields:
          type: "object"
          description: "Only allowed when type=Contact. Keys must be one of the built-in extraction field names; pass an empty / null rule to clear."
          additionalProperties:
            nullable: true
            allOf:
              -
                "$ref": "#/components/schemas/ExtractionRule"
        customFields:
          type: "object"
          description: "Custom field keys (must exist in DynamicProperties for the given type)."
          additionalProperties:
            nullable: true
            allOf:
              -
                "$ref": "#/components/schemas/ExtractionRule"
        backgroundExtractionMode:
          type: "string"
          enum:
            - "inbound"
            - "outbound"
            - "all"
          description: "Org-level toggle (org-wide, independent of ?type): which text-channel message directions the background extractor runs on."
      additionalProperties: true
      example:
        backgroundExtractionMode: "inbound"
        builtInFields:
          province:
            mode: "allowlist"
            values:
              - "ON"
              - "QC"
              - "BC"
              - "AB"
            regex:
              []
        customFields:
          creditScore: null
    ExtractionRulesUpdateResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        data:
          type: "object"
          properties:
            builtInFields:
              type: "object"
              additionalProperties:
                "$ref": "#/components/schemas/ExtractionRule"
            customFields:
              type: "object"
              additionalProperties:
                "$ref": "#/components/schemas/ExtractionRule"
            backgroundExtractionMode:
              type: "string"
              enum:
                - "inbound"
                - "outbound"
                - "all"
              description: "Org-level toggle: which text-channel message directions the background extractor runs on."
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        message: "Extraction rules updated"
        data:
          backgroundExtractionMode: "inbound"
          builtInFields:
            province:
              mode: "allowlist"
              values:
                - "ON"
                - "QC"
              regex:
                []
          customFields:
            {}
    MissedCallMessageResponse:
      type: "object"
      properties:
        missedCallMessage:
          type: "string"
          maxLength: 500
          nullable: true
        missedCallAutoMessageEnabled:
          type: "boolean"
      additionalProperties: true
      example:
        missedCallMessage: "Hi {{contactName}}, sorry we missed your call. We'll get back to you shortly."
        missedCallAutoMessageEnabled: true
    UpdateMissedCallMessageRequest:
      type: "object"
      properties:
        missedCallMessage:
          type: "string"
          maxLength: 500
          description: "SMS auto-reply sent after a missed inbound call; supports placeholder tokens like {{contactName}} and {{agentName}}."
        missedCallAutoMessageEnabled:
          type: "boolean"
          description: "Master toggle: when false, no missed-call auto-message is sent even if the template is populated."
      additionalProperties: true
      example:
        missedCallMessage: "Hi {{contactName}}, sorry we missed your call. We'll get back to you shortly."
        missedCallAutoMessageEnabled: true
    MissedCallPlaceholdersResponse:
      type: "object"
      properties:
        placeholders:
          type: "array"
          description: "List of supported placeholder tokens. Shape is defined by helpers/placeholder-processor.getAvailablePlaceholders()."
          items:
            type: "object"
            additionalProperties: true
      additionalProperties: true
      example:
        placeholders:
          -
            token: "{{contactName}}"
            label: "Contact full name"
          -
            token: "{{agentName}}"
            label: "Assigned agent name"
          -
            token: "{{organizationName}}"
            label: "Organization display name"
    OutreachCloseStagesResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            type: "string"
      additionalProperties: true
      example:
        success: true
        data:
          - "Closed Won"
          - "Funded"
    UpdateOutreachCloseStagesRequest:
      type: "object"
      properties:
        stages:
          type: "array"
          items:
            type: "string"
          description: "Pipeline stage names treated as \"closed\" outcomes (e.g. \"Closed Won\", \"Funded\") for outreach conversion/ROI metrics."
      required:
        - "stages"
      additionalProperties: true
      example:
        stages:
          - "Closed Won"
          - "Funded"
    OutreachGrossProfitConfig:
      type: "object"
      properties:
        entityType:
          type: "string"
          enum:
            - "Contact"
        propertyKey:
          type: "string"
      required:
        - "entityType"
        - "propertyKey"
      additionalProperties: true
      example:
        entityType: "Contact"
        propertyKey: "loanGrossProfit"
    OutreachGrossProfitConfigResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          nullable: true
          allOf:
            -
              "$ref": "#/components/schemas/OutreachGrossProfitConfig"
      additionalProperties: true
      example:
        success: true
        data:
          entityType: "Contact"
          propertyKey: "loanGrossProfit"
    UpdateOutreachGrossProfitConfigRequest:
      type: "object"
      description: "Pass null or {} to clear the config; otherwise must include entityType=\"Contact\" and a non-empty propertyKey."
      properties:
        entityType:
          type: "string"
          enum:
            - "Contact"
          description: "Entity holding the gross-profit value; currently only `Contact` is supported."
        propertyKey:
          type: "string"
          description: "Dynamic-property key on the entity whose numeric value is summed for outreach ROI calculation."
      nullable: true
      additionalProperties: true
      example:
        entityType: "Contact"
        propertyKey: "loanGrossProfit"
    UpdateOrganizationPlanRequest:
      type: "object"
      properties:
        plan:
          type: "string"
          enum:
            - "skip"
            - "essentials"
            - "fasttrack"
            - "partner"
            - "unlimited"
          description: "Subscription plan tier assigned to the organization; gates feature access and quotas."
      required:
        - "plan"
      additionalProperties: true
      example:
        plan: "fasttrack"
    UpdateOrganizationPlanResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        plan:
          type: "string"
          enum:
            - "skip"
            - "essentials"
            - "fasttrack"
            - "partner"
            - "unlimited"
      additionalProperties: true
      example:
        success: true
        plan: "fasttrack"
    OrgTimezoneResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            timezone:
              type: "string"
              description: "IANA timezone (defaults to \"UTC\")"
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        data:
          timezone: "America/New_York"
    UpdateOrgTimezoneRequest:
      type: "object"
      properties:
        timezone:
          type: "string"
          description: "IANA timezone (e.g. America/New_York)"
      required:
        - "timezone"
      additionalProperties: true
      example:
        timezone: "America/New_York"
    SectionsOptionsResponse:
      type: "object"
      properties:
        fieldChanges:
          type: "object"
          additionalProperties: true
        applicationFieldChanges:
          type: "object"
          additionalProperties: true
        conversationFieldChanges:
          type: "object"
          additionalProperties: true
      additionalProperties: true
      example:
        fieldChanges:
          email:
            -
              value: "jane.new@acme.example"
              source: "conversation"
              confidence: 0.92
        applicationFieldChanges:
          {}
        conversationFieldChanges:
          {}
    OrgSectionTypeConfigEntry:
      type: "object"
      properties:
        _id:
          type: "string"
        type:
          type: "string"
      required:
        - "_id"
        - "type"
      additionalProperties: true
      example:
        _id: "5f7b1c2e8a1d4e0012c3b500"
        type: "Contact"
    OrgPropertyUsageResponse:
      type: "object"
      properties:
        count:
          type: "integer"
          description: "Owner records holding a non-empty value for this property."
        paths:
          type: "array"
          items:
            type: "string"
          description: "Dotted paths probed on the owner documents, canonical key first, then legacy aliases. Diagnostic."
      required:
        - "count"
        - "paths"
      additionalProperties: false
      example:
        count: 2
        paths:
          - "vehicleFinancing.loanAmount"
          - "vehicleFinancing.Loan Amount"
    OrgSectionTypesResponse:
      type: "object"
      properties:
        builtIn:
          type: "array"
          items:
            type: "string"
        custom:
          type: "array"
          items:
            type: "string"
        all:
          type: "array"
          items:
            type: "string"
        configs:
          type: "array"
          items:
            "$ref": "#/components/schemas/OrgSectionTypeConfigEntry"
      additionalProperties: true
      example:
        builtIn:
          - "Contact"
          - "Application"
          - "Conversation"
        custom:
          - "Vehicle"
        all:
          - "Contact"
          - "Application"
          - "Conversation"
          - "Vehicle"
        configs:
          -
            _id: "5f7b1c2e8a1d4e0012c3b500"
            type: "Contact"
          -
            _id: "5f7b1c2e8a1d4e0012c3b501"
            type: "Vehicle"
    OrgSectionProperty:
      type: "object"
      description: "A DynamicProperties property entry. Either a leaf (dataType + optional options/formula/extractionRule/format/decimalPlaces) or a branch (linkId / linkTargetType pointing at another DynamicProperties doc)."
      properties:
        name:
          type: "string"
        isHidden:
          type: "boolean"
        isArray:
          type: "boolean"
          description: "Marks the property as a list. dataType stays the element type; valid on both leaf and branch properties."
        isProtected:
          type: "boolean"
          description: "Seeded default property; its definition cannot be changed or deleted."
        _id:
          type: "string"
        dataType:
          type: "string"
        format:
          type: "string"
          enum:
            - "MMM D, YYYY"
            - "YYYY-MM-DD"
            - "MM/DD/YYYY"
            - "DD/MM/YYYY"
          description: "Display format for a temporal leaf (dataType Date or DateTime). Presentational only - the stored value always follows the storage contract for the declared type (Date persists a timezone-free YYYY-MM-DD, DateTime a full ISO-8601 instant). Unrecognized tokens are dropped on write; absent means the type default."
        timeFormat:
          type: "string"
          enum:
            - "12h"
            - "24h"
          description: "Clock convention for the time half of a DateTime. Not persisted for date-only properties. Absent means the type default."
        decimalPlaces:
          type: "integer"
          enum:
            - 0
            - 1
            - 2
            - 3
            - 4
          description: "Decimal places a numeric leaf displays with (dataType number/integer/float/decimal/currency, or a computed field whose outputType is number). Presentational only - the stored value is untouched. Unrecognized values are dropped on write; absent means unformatted, i.e. the number renders as stored."
        options:
          type: "array"
          items:
            {}
        dropdownType:
          type: "string"
        expression:
          type: "string"
        canonicalExpression:
          type: "string"
        outputType:
          type: "string"
        dependencies:
          type: "array"
          items:
            type: "string"
        status:
          type: "string"
        formula:
          type: "object"
          additionalProperties: true
        extractionRule:
          "$ref": "#/components/schemas/ExtractionRule"
        linkId:
          type: "string"
        linkTargetType:
          type: "string"
      additionalProperties: true
      example:
        name: "First Name"
        dataType: "string"
        isHidden: false
    OrgSection:
      type: "object"
      properties:
        name:
          type: "string"
        isHidden:
          type: "boolean"
        properties:
          type: "object"
          additionalProperties:
            "$ref": "#/components/schemas/OrgSectionProperty"
      required:
        - "name"
      additionalProperties: true
      example:
        name: "Personal Information"
        isHidden: false
        properties:
          firstName:
            name: "First Name"
            dataType: "string"
            isHidden: false
          lastName:
            name: "Last Name"
            dataType: "string"
            isHidden: false
          email:
            name: "Email"
            dataType: "string"
            isHidden: false
    OrgSectionsResponse:
      type: "object"
      properties:
        sections:
          type: "array"
          items:
            "$ref": "#/components/schemas/OrgSection"
        message:
          type: "string"
      additionalProperties: true
      example:
        sections:
          -
            name: "Personal Information"
            isHidden: false
            properties:
              firstName:
                name: "First Name"
                dataType: "string"
                isHidden: false
              email:
                name: "Email"
                dataType: "string"
                isHidden: false
    UpdateOrgSectionsRequest:
      type: "object"
      properties:
        sections:
          type: "array"
          items:
            "$ref": "#/components/schemas/OrgSection"
      required:
        - "sections"
      additionalProperties: true
      example:
        sections:
          -
            name: "Personal Information"
            isHidden: false
            properties:
              firstName:
                name: "First Name"
                dataType: "string"
                isHidden: false
              lastName:
                name: "Last Name"
                dataType: "string"
                isHidden: false
    UpdateOrgSectionsResponse:
      type: "object"
      properties:
        message:
          type: "string"
        organization:
          type: "object"
          additionalProperties: true
          description: "Updated DynamicProperties document."
        renamedProperties:
          type: "object"
          additionalProperties:
            type: "string"
          description: "Map from old property name to new property name."
      additionalProperties: true
      example:
        message: "Sections updated successfully"
        organization:
          _id: "5f7b1c2e8a1d4e0012c3b500"
          organizationId: "5f7b1c2e8a1d4e0012c3b400"
          type: "Contact"
        renamedProperties:
          firstname: "firstName"
    DeleteOrgSectionResponse:
      type: "object"
      properties:
        message:
          type: "string"
        type:
          type: "string"
      additionalProperties: true
      example:
        message: "Entity type deleted"
        type: "Vehicle"
    DeleteOrgSectionConflictResponse:
      type: "object"
      properties:
        error:
          type: "string"
        references:
          type: "array"
          items:
            type: "string"
      additionalProperties: true
      example:
        error: "Entity type is referenced by other configs"
        references:
          - "Contact.linkedVehicle"
          - "Application.vehicles"
    OrgTransferPreviewRequest:
      type: "object"
      properties:
        userId:
          type: "string"
          description: "User being moved out of the source organization; the preview counts the resources currently owned by this user."
        targetOrganizationId:
          type: "string"
          description: "Organization the user would be transferred into; used to identify cross-org references in the preview."
      required:
        - "userId"
        - "targetOrganizationId"
      additionalProperties: true
      example:
        userId: "5f7b1c2e8a1d4e0012c3b4a6"
        targetOrganizationId: "5f7b1c2e8a1d4e0012c3b401"
    OrgTransferPreviewResponse:
      type: "object"
      properties:
        contacts:
          type: "integer"
          description: "Distinct contacts reached through the conversations the user is assigned to. Contacts are not owned; they follow their conversations to the reassignee."
        conversations:
          type: "integer"
        assigneeConversations:
          type: "integer"
        automations:
          type: "integer"
        workflows:
          type: "integer"
        webchatConfigurations:
          type: "integer"
        acquiredItems:
          type: "integer"
        emailAccounts:
          type: "integer"
        calendarConnections:
          type: "integer"
        calendarToolConfigurations:
          type: "integer"
        googleSheetsTokens:
          type: "integer"
        unfiredReminders:
          type: "integer"
        promptCount:
          type: "integer"
        automationKeys:
          type: "integer"
      additionalProperties: true
      example:
        contacts: 1240
        conversations: 3580
        assigneeConversations: 412
        automations: 7
        workflows: 3
        webchatConfigurations: 2
        acquiredItems: 18
        emailAccounts: 1
        calendarConnections: 1
        calendarToolConfigurations: 1
        googleSheetsTokens: 0
        unfiredReminders: 22
        promptCount: 15
        automationKeys: 4
    OrgTransferScanRequest:
      type: "object"
      properties:
        userId:
          type: "string"
          description: "User being transferred out of the source organization."
        targetOrganizationId:
          type: "string"
          description: "Destination organization the user will move into."
        reassigneeUserId:
          type: "string"
          description: "User in the source org who will inherit the transferring user's contacts, conversations, automations, workflows, and prompts; used to compute the scan version and surface their existing agents."
      required:
        - "userId"
        - "targetOrganizationId"
        - "reassigneeUserId"
      additionalProperties: true
      example:
        userId: "5f7b1c2e8a1d4e0012c3b4a6"
        targetOrganizationId: "5f7b1c2e8a1d4e0012c3b401"
        reassigneeUserId: "5f7b1c2e8a1d4e0012c3b4a8"
    OrgTransferScanWarning:
      type: "object"
      properties:
        code:
          type: "string"
        message:
          type: "string"
        meta:
          type: "object"
          additionalProperties: true
      required:
        - "code"
        - "message"
      additionalProperties: true
      example:
        code: "AGENT_NOT_IN_TARGET_ORG"
        message: "User owns automations referencing an agent not present in the target org"
        meta:
          agentId: "5f7b1c2e8a1d4e0012c3b610"
          count: 3
    OrgTransferAgentUsage:
      type: "object"
      properties:
        agentId:
          type: "string"
        agentName:
          type: "string"
        total:
          type: "integer"
        autopilot:
          type: "integer"
        isDeleted:
          type: "boolean"
      required:
        - "agentId"
        - "agentName"
        - "total"
        - "autopilot"
        - "isDeleted"
      additionalProperties: true
      example:
        agentId: "5f7b1c2e8a1d4e0012c3b610"
        agentName: "Sales Outbound Agent"
        total: 124
        autopilot: 80
        isDeleted: false
    OrgTransferReassigneeAgent:
      type: "object"
      properties:
        agentId:
          type: "string"
        agentName:
          type: "string"
        agentDescription:
          type: "string"
        updatedAt:
          type: "string"
          format: "date-time"
      required:
        - "agentId"
        - "agentName"
      additionalProperties: true
      example:
        agentId: "5f7b1c2e8a1d4e0012c3b611"
        agentName: "Reassignee Default Agent"
        agentDescription: "Default agent for reassigned conversations"
        updatedAt: "2026-05-18T14:30:00.000Z"
    OrgTransferScanResponse:
      type: "object"
      properties:
        scanVersion:
          type: "string"
        scannedAt:
          type: "string"
          format: "date-time"
        userId:
          type: "string"
        fromOrganizationId:
          type: "string"
        toOrganizationId:
          type: "string"
        warnings:
          type: "array"
          items:
            "$ref": "#/components/schemas/OrgTransferScanWarning"
        ownedCounts:
          type: "object"
          properties:
            contacts:
              type: "integer"
            conversations:
              type: "integer"
            assigneeConversations:
              type: "integer"
            emailAccounts:
              type: "integer"
            calendarConnections:
              type: "integer"
            calendarToolConfigurations:
              type: "integer"
            googleSheetsTokens:
              type: "integer"
            unfiredReminders:
              type: "integer"
            automations:
              type: "integer"
            workflows:
              type: "integer"
            webchatConfigurations:
              type: "integer"
            acquiredItems:
              type: "integer"
            promptCount:
              type: "integer"
            automationKeys:
              type: "integer"
          additionalProperties: true
        agentUsage:
          type: "array"
          items:
            "$ref": "#/components/schemas/OrgTransferAgentUsage"
        reassigneeAgents:
          type: "array"
          items:
            "$ref": "#/components/schemas/OrgTransferReassigneeAgent"
        isSourceDepartmentManager:
          type: "boolean"
        isSuperadmin:
          type: "boolean"
      additionalProperties: true
      example:
        scanVersion: "scan-2026-05-18T14:30:00Z-abc123"
        scannedAt: "2026-05-18T14:30:00.000Z"
        userId: "5f7b1c2e8a1d4e0012c3b4a6"
        fromOrganizationId: "5f7b1c2e8a1d4e0012c3b400"
        toOrganizationId: "5f7b1c2e8a1d4e0012c3b401"
        warnings:
          []
        ownedCounts:
          contacts: 1240
          conversations: 3580
          assigneeConversations: 412
          automations: 7
          workflows: 3
        agentUsage:
          -
            agentId: "5f7b1c2e8a1d4e0012c3b610"
            agentName: "Sales Outbound Agent"
            total: 124
            autopilot: 80
            isDeleted: false
        reassigneeAgents:
          []
        isSourceDepartmentManager: false
        isSuperadmin: true
    OrgTransferAgentRemap:
      type: "object"
      properties:
        fromAgentId:
          type: "string"
        toAgentId:
          type: "string"
      required:
        - "fromAgentId"
        - "toAgentId"
      additionalProperties: true
      example:
        fromAgentId: "5f7b1c2e8a1d4e0012c3b610"
        toAgentId: "5f7b1c2e8a1d4e0012c3b611"
    OrgTransferExecuteRequest:
      type: "object"
      properties:
        scanVersion:
          type: "string"
          minLength: 1
          description: "Version token returned by the prior scan call; rejected if stale to prevent applying an out-of-date transfer plan."
        userId:
          type: "string"
          description: "User being transferred; must match the userId from the matching scan."
        targetOrganizationId:
          type: "string"
          description: "Destination organization for the user; must match the targetOrganizationId from the matching scan."
        targetDepartmentId:
          type: "string"
          description: "Optional department within the target organization the user joins; the user is added as a manager when newAccessRole is DEPARTMENT_HEAD, otherwise as a member."
        newAccessRole:
          type: "string"
          enum:
            - "ADMIN"
            - "DEPARTMENT_HEAD"
            - "SALES_REP"
          description: "Access role the user receives in the target organization."
        reassigneeUserId:
          type: "string"
          description: "User in the source org who inherits the transferring user's owned resources (contacts, conversations, automations, workflows, webchat configs, prompts); must differ from userId."
        agentRemaps:
          type: "array"
          items:
            "$ref": "#/components/schemas/OrgTransferAgentRemap"
          default:
            []
          description: "Optional remappings applied to the transferring user's automations so each fromAgentId is swapped to the corresponding toAgentId owned by the reassignee."
      required:
        - "scanVersion"
        - "userId"
        - "targetOrganizationId"
        - "newAccessRole"
        - "reassigneeUserId"
      additionalProperties: true
      example:
        scanVersion: "scan-2026-05-18T14:30:00Z-abc123"
        userId: "5f7b1c2e8a1d4e0012c3b4a6"
        targetOrganizationId: "5f7b1c2e8a1d4e0012c3b401"
        targetDepartmentId: "5f7b1c2e8a1d4e0012c3b510"
        newAccessRole: "SALES_REP"
        reassigneeUserId: "5f7b1c2e8a1d4e0012c3b4a8"
        agentRemaps:
          -
            fromAgentId: "5f7b1c2e8a1d4e0012c3b610"
            toAgentId: "5f7b1c2e8a1d4e0012c3b611"
    OrgTransferExecuteResponse:
      type: "object"
      properties:
        transferId:
          type: "string"
        status:
          type: "string"
          enum:
            - "in_progress"
      required:
        - "transferId"
        - "status"
      additionalProperties: true
      example:
        transferId: "5f7b1c2e8a1d4e0012c3b900"
        status: "in_progress"
    OrgTransferStatusResponse:
      type: "object"
      properties:
        transferId:
          type: "string"
        status:
          type: "string"
          enum:
            - "in_progress"
            - "completed"
            - "failed"
        action:
          type: "string"
        startedAt:
          type: "string"
          format: "date-time"
          nullable: true
        completedAt:
          type: "string"
          format: "date-time"
          nullable: true
        error:
          type: "string"
          nullable: true
        payload:
          type: "object"
          additionalProperties: true
      required:
        - "transferId"
        - "status"
      additionalProperties: true
      example:
        transferId: "5f7b1c2e8a1d4e0012c3b900"
        status: "completed"
        action: "org_transfer_execute"
        startedAt: "2026-05-18T14:30:00.000Z"
        completedAt: "2026-05-18T14:34:12.000Z"
        error: null
        payload:
          userId: "5f7b1c2e8a1d4e0012c3b4a6"
          targetOrganizationId: "5f7b1c2e8a1d4e0012c3b401"
    OutreachTriggerRequest:
      type: "object"
      properties:
        phoneNumber:
          type: "string"
          description: "Lead phone number; normalized to E.164 server-side. Required unless `contactId`/`_id`/`id` is supplied."
        email:
          type: "string"
          description: "Lead email; normalized to lowercase."
        firstName:
          type: "string"
          description: "Lead first name used when creating a new contact."
        lastName:
          type: "string"
          description: "Lead last name used when creating a new contact."
        name:
          type: "string"
          description: "Single-field display name fallback when `firstName`/`lastName` are not supplied."
        contactId:
          type: "string"
          description: "Contact `_id` for an existing contact; bypasses the create-or-merge lookup."
        _id:
          type: "string"
          description: "Contact `_id` for an existing contact; bypasses the create-or-merge lookup."
        id:
          type: "string"
          description: "Contact `_id` for an existing contact; bypasses the create-or-merge lookup."
      description: "Lead data payload. Accepts arbitrary additional fields that are mapped to contact dynamic properties. The sending line is the configuration's `phoneNumberId`, else the API key user's line, else the org default line; the payload never sets it. The SMS conversation is the contact's thread on that line, else a line-less legacy thread (moved onto the line), else a new thread on the line. A thread on another line is never reused or moved, including one named by `conversations._id`. When no line resolves at all, the contact's most recent SMS conversation is used."
      additionalProperties: true
      example:
        firstName: "Jamie"
        lastName: "Lee"
        phoneNumber: "+14155550133"
        email: "jamie.lee@example.com"
        source: "Facebook Lead Ad"
    OutreachMessageResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        message:
          type: "string"
      additionalProperties: true
      example:
        success: true
        message: "Cache cleared"
    OutreachStageCount:
      type: "object"
      properties:
        stage:
          type: "string"
        count:
          type: "integer"
      required:
        - "stage"
        - "count"
      additionalProperties: false
      example:
        stage: "Contacted"
        count: 42
    OutreachSourceMetrics:
      type: "object"
      properties:
        source:
          type: "string"
        leads:
          type: "integer"
        cost:
          type: "number"
        costPerLead:
          type: "number"
          description: "Average cost per lead for contacts under this source."
        contactPercentage:
          type: "number"
          description: "Percentage of leads that have at least one outbound message."
        closePercentage:
          type: "number"
          description: "Percentage of leads whose status matches the org's outreachCloseStages."
        stageDistribution:
          type: "array"
          items:
            "$ref": "#/components/schemas/OutreachStageCount"
        grossProfit:
          type: "number"
        roi:
          type: "number"
          description: "grossProfit / cost (0 when cost is 0)."
      required:
        - "source"
        - "leads"
        - "cost"
        - "costPerLead"
        - "contactPercentage"
        - "closePercentage"
        - "stageDistribution"
        - "grossProfit"
        - "roi"
      additionalProperties: true
      example:
        source: "Facebook Lead Ad"
        leads: 120
        cost: 1500
        costPerLead: 12.5
        contactPercentage: 75
        closePercentage: 18
        stageDistribution:
          -
            stage: "New Lead"
            count: 30
          -
            stage: "Contacted"
            count: 60
          -
            stage: "Closed Won"
            count: 22
        grossProfit: 4400
        roi: 2.93
    OutreachMetricsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/OutreachSourceMetrics"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          -
            source: "Facebook Lead Ad"
            leads: 120
            cost: 1500
            costPerLead: 12.5
            contactPercentage: 75
            closePercentage: 18
            stageDistribution:
              -
                stage: "Contacted"
                count: 60
            grossProfit: 4400
            roi: 2.93
    OutreachMetricsHistoryEntry:
      type: "object"
      properties:
        period:
          type: "string"
          description: "Period key formatted per groupBy (YYYY-MM-DD, YYYY-WW, YYYY-MM)."
        stage:
          type: "string"
          description: "Destination pipeline stage of the transition."
        source:
          type: "string"
          description: "Lead source attributed to the transition."
        count:
          type: "integer"
      required:
        - "period"
        - "stage"
        - "source"
        - "count"
      additionalProperties: false
      example:
        period: "2026-05-17"
        stage: "Contacted"
        source: "Facebook Lead Ad"
        count: 12
    OutreachMetricsHistoryResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/OutreachMetricsHistoryEntry"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          -
            period: "2026-05-17"
            stage: "Contacted"
            source: "Facebook Lead Ad"
            count: 12
          -
            period: "2026-05-17"
            stage: "Closed Won"
            source: "Facebook Lead Ad"
            count: 3
    OutreachSourceDto:
      type: "object"
      properties:
        _id:
          type: "string"
          nullable: true
          description: "Null for the synthetic \"Any\" entry."
        name:
          type: "string"
        isActive:
          type: "boolean"
        isProtected:
          type: "boolean"
          description: "True for the \"Any\" source."
        createdAt:
          type: "string"
          format: "date-time"
      required:
        - "name"
        - "isActive"
      additionalProperties: true
      example:
        _id: "665f1a0c0e0a4b001a2c9f30"
        name: "Facebook Lead Ad"
        isActive: true
        isProtected: false
        createdAt: "2026-05-01T09:00:00.000Z"
    OutreachSourceListResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/OutreachSourceDto"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          -
            _id: null
            name: "Any"
            isActive: true
            isProtected: true
          -
            _id: "665f1a0c0e0a4b001a2c9f30"
            name: "Facebook Lead Ad"
            isActive: true
            isProtected: false
          -
            _id: "665f1a0c0e0a4b001a2c9f31"
            name: "Google Ads"
            isActive: true
            isProtected: false
    CreateOutreachSourceRequest:
      type: "object"
      properties:
        name:
          type: "string"
          description: "New source name. Must not be \"Any\" and must be unique (case-insensitive) within the organization."
      required:
        - "name"
      additionalProperties: false
      example:
        name: "Facebook Lead Ad"
    OutreachSourceMutationResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          "$ref": "#/components/schemas/OutreachSourceDto"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          _id: "665f1a0c0e0a4b001a2c9f30"
          name: "Facebook Lead Ad"
          isActive: true
          isProtected: false
          createdAt: "2026-05-18T12:34:56.000Z"
    OutreachErrorResponse:
      type: "object"
      description: "Error envelope returned by `/api/outreach`."
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
        error:
          type: "string"
          description: "Stack/detail string for 500 paths."
      required:
        - "success"
        - "message"
      additionalProperties: true
      example:
        success: false
        message: "Configuration is inactive and cannot process outreach requests"
    OutreachTriggerResponse:
      type: "object"
      description: "Returned by `POST /api/outreach`. `data` carries resolved IDs the caller may need to follow up."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        data:
          type: "object"
          properties:
            contactId:
              type: "string"
            applicationId:
              type: "string"
            conversationId:
              type: "string"
              description: "The selected conversation. For SMS, the thread on the sending line."
            phoneNumberId:
              type: "string"
              description: "The org phone line the selected SMS conversation is on, when it has one."
            mergeOutcome:
              type: "string"
              enum:
                - "merged"
                - "created"
            starterMessage:
              "$ref": "#/components/schemas/OutreachStarterMessageOutcome"
          additionalProperties: true
      required:
        - "success"
        - "message"
      additionalProperties: true
      example:
        success: true
        message: "Data processed successfully"
        data:
          contactId: "64b2c3d4e5f60012345678aa"
          applicationId: "64d2f9c5e8a1d4e001a0b1c2"
          conversationId: "64d2f9c5e8a1d4e001a0b1c3"
          phoneNumberId: "64d2f9c5e8a1d4e001a0b1d0"
          mergeOutcome: "created"
          starterMessage:
            status: "sent"
            phoneNumberId: "64d2f9c5e8a1d4e001a0b1d0"
            fromPhoneNumber: "+15550000002"
    OutreachStarterMessageOutcome:
      type: "object"
      description: "What happened to the configuration's starter message. Reported on every 200: a starter message that is not sent never fails the request, because the contact, application and workflows have already been processed."
      properties:
        status:
          type: "string"
          enum:
            - "sent"
            - "skipped"
            - "failed"
            - "not_configured"
        code:
          type: "string"
          description: "Why it was skipped (NOT_ELIGIBLE, EMAIL_CONVERSATION, NO_PHONE_NUMBER, EMPTY_MESSAGE, NO_CONVERSATION, NO_CONTACT) or failed (NO_SENDING_NUMBER, OUTBOUND_BLOCKED, VALIDATION_RULE_FAILED, PHONE_NUMBER_NOT_GRANTED, SEND_FAILED)."
        message:
          type: "string"
          description: "Why the send failed. Set when `status` is failed."
        phoneNumberId:
          type: "string"
          description: "The line the message was sent from."
        fromPhoneNumber:
          type: "string"
          description: "The number of that line (E.164)."
      required:
        - "status"
      additionalProperties: false
      example:
        status: "failed"
        code: "OUTBOUND_BLOCKED"
        message: "This contact is blocked."
    SelfSendFromListResponse:
      type: "object"
      properties:
        phoneNumbers:
          type: "array"
          items:
            type: "object"
            properties:
              phoneNumberId:
                type: "string"
              provider:
                type: "string"
              phoneNumber:
                type: "string"
              numberType:
                type: "string"
                enum:
                  - "longcode"
                  - "tollfree"
                  - "shortcode"
                default: "longcode"
                description: "The kind of number. A `shortcode` is a 5 or 6 digit SMS-only sender stored as its plain digits (no `+`); it must have `capabilities: [\"sms\"]` (the default when a short code is created without `capabilities`), no AI or call routing, no forward number, no ElevenLabs id or AI agent, and cannot be the org default. A missing value on a stored line means `longcode`."
              capabilities:
                type: "array"
                items:
                  type: "string"
                  enum:
                    - "sms"
                    - "voice"
              status:
                type: "string"
                enum:
                  - "active"
                  - "inactive"
                  - "released"
              label:
                type: "string"
              via:
                type: "string"
                enum:
                  - "link"
                  - "group"
                  - "grant"
                  - "orgDefault"
                description: "How the caller reaches the number: `link` (linked to them), `group` (linked to a group they belong to), `grant` (a send grant to them, their department or one of their groups), `orgDefault` (the org default line, only on /api/phone-numbers/org)."
              verbs:
                type: "array"
                items:
                  type: "string"
                  enum:
                    - "send"
                    - "read"
                description: "Every verb the caller holds on this line: `send` through its link or a send grant, `read` through a read grant only. A row without `send` appears only with `?verb=read` and must not be offered as a send-from option."
            required:
              - "phoneNumberId"
              - "phoneNumber"
              - "via"
              - "verbs"
            additionalProperties: true
        orgDefaultAvailable:
          type: "boolean"
          description: "The organization has a usable default line for the requested channel (false when no channel was requested)."
      required:
        - "phoneNumbers"
        - "orgDefaultAvailable"
      additionalProperties: true
      example:
        phoneNumbers:
          -
            phoneNumberId: "6650a1b2c3d4e5f6a7b8c9d1"
            provider: "twilio"
            phoneNumber: "+14165550102"
            capabilities:
              - "sms"
              - "voice"
            status: "active"
            label: "Leasing team line"
            via: "grant"
            verbs:
              - "send"
              - "read"
        orgDefaultAvailable: true
    ForUsersSendFromListResponse:
      type: "object"
      properties:
        phoneNumbers:
          type: "array"
          items:
            type: "object"
            properties:
              phoneNumberId:
                type: "string"
              provider:
                type: "string"
              phoneNumber:
                type: "string"
              numberType:
                type: "string"
                enum:
                  - "longcode"
                  - "tollfree"
                  - "shortcode"
                default: "longcode"
                description: "The kind of number. A `shortcode` is a 5 or 6 digit SMS-only sender stored as its plain digits (no `+`); it must have `capabilities: [\"sms\"]` (the default when a short code is created without `capabilities`), no AI or call routing, no forward number, no ElevenLabs id or AI agent, and cannot be the org default. A missing value on a stored line means `longcode`."
              capabilities:
                type: "array"
                items:
                  type: "string"
                  enum:
                    - "sms"
                    - "voice"
              status:
                type: "string"
                enum:
                  - "active"
                  - "inactive"
                  - "released"
              label:
                type: "string"
              routing:
                type: "object"
                additionalProperties: true
              linkedUserId:
                type: "string"
                nullable: true
                description: "The inbound owner of the number (not necessarily a listed user)."
              userIds:
                type: "array"
                items:
                  type: "string"
                description: "The listed users who may send from this number."
              via:
                type: "string"
                enum:
                  - "link"
                  - "group"
                  - "grant"
                  - "orgDefault"
                description: "How the caller reaches the number: `link` (linked to them), `group` (linked to a group they belong to), `grant` (a send grant to them, their department or one of their groups), `orgDefault` (the org default line, only on /api/phone-numbers/org)."
            required:
              - "phoneNumberId"
              - "phoneNumber"
              - "userIds"
              - "via"
            additionalProperties: true
        orgDefaultAvailable:
          type: "boolean"
      required:
        - "phoneNumbers"
        - "orgDefaultAvailable"
      additionalProperties: true
    OrgSendFromListResponse:
      type: "object"
      properties:
        phoneNumbers:
          type: "array"
          items:
            type: "object"
            properties:
              phoneNumberId:
                type: "string"
              provider:
                type: "string"
              phoneNumber:
                type: "string"
              numberType:
                type: "string"
                enum:
                  - "longcode"
                  - "tollfree"
                  - "shortcode"
                default: "longcode"
                description: "The kind of number. A `shortcode` is a 5 or 6 digit SMS-only sender stored as its plain digits (no `+`); it must have `capabilities: [\"sms\"]` (the default when a short code is created without `capabilities`), no AI or call routing, no forward number, no ElevenLabs id or AI agent, and cannot be the org default. A missing value on a stored line means `longcode`."
              capabilities:
                type: "array"
                items:
                  type: "string"
                  enum:
                    - "sms"
                    - "voice"
              status:
                type: "string"
                enum:
                  - "active"
                  - "inactive"
                  - "released"
              label:
                type: "string"
              routing:
                type: "object"
                additionalProperties: true
              linkedType:
                type: "string"
                enum:
                  - "user"
                  - "group"
                nullable: true
              linkedUserId:
                type: "string"
                nullable: true
              linkedGroupId:
                type: "string"
                nullable: true
              groupName:
                type: "string"
                nullable: true
              userName:
                type: "string"
              via:
                type: "string"
                enum:
                  - "link"
                  - "group"
                  - "grant"
                  - "orgDefault"
                description: "How the caller reaches the number: `link` (linked to them), `group` (linked to a group they belong to), `grant` (a send grant to them, their department or one of their groups), `orgDefault` (the org default line, only on /api/phone-numbers/org)."
                nullable: true
            required:
              - "phoneNumberId"
              - "phoneNumber"
            additionalProperties: true
      required:
        - "phoneNumbers"
      additionalProperties: true
    ResourceGrantInput:
      type: "object"
      description: "One access grant as an admin sends it. Shared by phone numbers and email accounts."
      properties:
        principalType:
          type: "string"
          enum:
            - "user"
            - "group"
            - "department"
          description: "Who the grant is for. Department membership is the user department; group membership is the user group member list."
        principalId:
          type: "string"
          pattern: "^[0-9a-fA-F]{24}$"
          description: "Id of the user, user group or department. Must belong to the organization."
        verbs:
          type: "array"
          minItems: 1
          items:
            type: "string"
            enum:
              - "send"
              - "read"
          description: "`send`: may use the resource to send. `read`: may see conversations that came through it."
      required:
        - "principalType"
        - "principalId"
        - "verbs"
      example:
        principalType: "department"
        principalId: "6650a1b2c3d4e5f6a7b8c9d3"
        verbs:
          - "read"
    ResourceGrant:
      type: "object"
      description: "A stored access grant, as returned by the admin APIs."
      properties:
        principalType:
          type: "string"
          enum:
            - "user"
            - "group"
            - "department"
        principalId:
          type: "string"
        key:
          type: "string"
          description: "Derived match key: `user:<id>`, `group:<id>` or `dept:<id>`. Always set by the server."
        verbs:
          type: "array"
          items:
            type: "string"
            enum:
              - "send"
              - "read"
        grantedBy:
          type: "object"
          description: "Who made the grant: `{ type: \"user\", userId }` for an admin, `{ type: \"system\", label }` for a backfill."
          properties:
            type:
              type: "string"
              enum:
                - "user"
                - "ai"
                - "automation"
                - "workflow"
                - "system"
            userId:
              type: "string"
            label:
              type: "string"
          additionalProperties: true
        grantedAt:
          type: "string"
          format: "date-time"
      required:
        - "principalType"
        - "principalId"
        - "key"
        - "verbs"
      example:
        principalType: "group"
        principalId: "6650a1b2c3d4e5f6a7b8c9d2"
        key: "group:6650a1b2c3d4e5f6a7b8c9d2"
        verbs:
          - "send"
          - "read"
        grantedBy:
          type: "user"
          userId: "6650a1b2c3d4e5f6a7b8c9d0"
        grantedAt: "2026-09-30T12:00:00.000Z"
    PhoneNumberRoutingInput:
      type: "object"
      description: "Per-leg routing policy. Every field is optional; on update only the fields sent change."
      properties:
        inbound:
          type: "object"
          properties:
            enabled:
              type: "boolean"
            ai:
              type: "boolean"
            forwardToNumber:
              type: "string"
              nullable: true
          additionalProperties: false
        outbound:
          type: "object"
          properties:
            enabled:
              type: "boolean"
            ai:
              type: "boolean"
          additionalProperties: false
      additionalProperties: false
    CreateOrgPhoneNumberRequest:
      type: "object"
      properties:
        provider:
          type: "string"
          enum:
            - "sinch"
            - "twilio"
            - "bland"
            - "textgrid"
        phoneNumber:
          type: "string"
          description: "Stored in canonical E.164 form; a `shortcode` is stored as its plain 5 or 6 digits and is refused with a leading `+`."
        numberType:
          type: "string"
          enum:
            - "longcode"
            - "tollfree"
            - "shortcode"
          default: "longcode"
          description: "The kind of number. A `shortcode` is a 5 or 6 digit SMS-only sender stored as its plain digits (no `+`); it must have `capabilities: [\"sms\"]` (the default when a short code is created without `capabilities`), no AI or call routing, no forward number, no ElevenLabs id or AI agent, and cannot be the org default. A missing value on a stored line means `longcode`."
        capabilities:
          type: "array"
          items:
            type: "string"
            enum:
              - "sms"
              - "voice"
        label:
          type: "string"
        routing:
          "$ref": "#/components/schemas/PhoneNumberRoutingInput"
        aiAgentId:
          type: "string"
          nullable: true
        elevenlabsPhoneNumberId:
          type: "string"
          nullable: true
        status:
          type: "string"
          enum:
            - "active"
            - "inactive"
            - "released"
        isOrgDefault:
          type: "boolean"
          description: "Make this the org fallback sending line for its provider. Must be unlinked and open to human outbound."
        linkedUserId:
          type: "string"
          nullable: true
          description: "Inbound destination user. At most one of linkedUserId / linkedGroupId."
        linkedGroupId:
          type: "string"
          nullable: true
          description: "Inbound destination group. At most one of linkedUserId / linkedGroupId."
        grants:
          type: "array"
          maxItems: 200
          items:
            "$ref": "#/components/schemas/ResourceGrantInput"
          description: "Who else may send from and/or read this number, beyond its link. The link stays the inbound destination and always implies send (never read) for the linked user (or linked group members); reading the number's conversations beyond what assignment shows needs an explicit `read` grant, for the linked user too. Each principal is a user, a user group or a department of this organization, and may appear once. `key`, `grantedBy` and `grantedAt` are set by the server and ignored if sent. A `send` grant on the org default number is rejected (everyone can already send from it); `read` grants on it are allowed."
      required:
        - "provider"
        - "phoneNumber"
      additionalProperties: true
      example:
        provider: "twilio"
        phoneNumber: "+14165550102"
        capabilities:
          - "sms"
          - "voice"
        label: "Leasing team line"
        linkedGroupId: "6650a1b2c3d4e5f6a7b8c9d2"
        grants:
          -
            principalType: "department"
            principalId: "6650a1b2c3d4e5f6a7b8c9d3"
            verbs:
              - "read"
    UpdateOrgPhoneNumberRequest:
      type: "object"
      description: "Partial update. Only fields present change; `null` on a link field clears it (both null unlinks the number)."
      properties:
        provider:
          type: "string"
          enum:
            - "sinch"
            - "twilio"
            - "bland"
            - "textgrid"
        phoneNumber:
          type: "string"
        numberType:
          type: "string"
          enum:
            - "longcode"
            - "tollfree"
            - "shortcode"
          default: "longcode"
          description: "The kind of number. A `shortcode` is a 5 or 6 digit SMS-only sender stored as its plain digits (no `+`); it must have `capabilities: [\"sms\"]` (the default when a short code is created without `capabilities`), no AI or call routing, no forward number, no ElevenLabs id or AI agent, and cannot be the org default. A missing value on a stored line means `longcode`."
        capabilities:
          type: "array"
          items:
            type: "string"
            enum:
              - "sms"
              - "voice"
        label:
          type: "string"
          nullable: true
        routing:
          "$ref": "#/components/schemas/PhoneNumberRoutingInput"
        aiAgentId:
          type: "string"
          nullable: true
        elevenlabsPhoneNumberId:
          type: "string"
          nullable: true
        status:
          type: "string"
          enum:
            - "active"
            - "inactive"
            - "released"
        isOrgDefault:
          type: "boolean"
        linkedUserId:
          type: "string"
          nullable: true
        linkedGroupId:
          type: "string"
          nullable: true
        grants:
          type: "array"
          maxItems: 200
          items:
            "$ref": "#/components/schemas/ResourceGrantInput"
          description: "Who else may send from and/or read this number, beyond its link. The link stays the inbound destination and always implies send (never read) for the linked user (or linked group members); reading the number's conversations beyond what assignment shows needs an explicit `read` grant, for the linked user too. Each principal is a user, a user group or a department of this organization, and may appear once. `key`, `grantedBy` and `grantedAt` are set by the server and ignored if sent. A `send` grant on the org default number is rejected (everyone can already send from it); `read` grants on it are allowed. Replaces the whole list; omit to leave grants unchanged."
      additionalProperties: true
      example:
        grants:
          -
            principalType: "user"
            principalId: "6650a1b2c3d4e5f6a7b8c9d4"
            verbs:
              - "send"
              - "read"
    OrgPhoneNumberRow:
      type: "object"
      description: "One number in the admin list."
      properties:
        phoneNumberId:
          type: "string"
        provider:
          type: "string"
        phoneNumber:
          type: "string"
        numberType:
          type: "string"
          enum:
            - "longcode"
            - "tollfree"
            - "shortcode"
          default: "longcode"
          description: "The kind of number. A `shortcode` is a 5 or 6 digit SMS-only sender stored as its plain digits (no `+`); it must have `capabilities: [\"sms\"]` (the default when a short code is created without `capabilities`), no AI or call routing, no forward number, no ElevenLabs id or AI agent, and cannot be the org default. A missing value on a stored line means `longcode`."
        label:
          type: "string"
        capabilities:
          type: "array"
          items:
            type: "string"
            enum:
              - "sms"
              - "voice"
        status:
          type: "string"
          enum:
            - "active"
            - "inactive"
            - "released"
        routing:
          type: "object"
          additionalProperties: true
        aiAgentId:
          type: "string"
          nullable: true
        elevenlabsPhoneNumberId:
          type: "string"
          nullable: true
          description: "Set once the number is imported into the AI voice provider."
        isOrgDefault:
          type: "boolean"
        linkedType:
          type: "string"
          enum:
            - "user"
            - "group"
          nullable: true
        linkedUserId:
          type: "string"
          nullable: true
        linkedGroupId:
          type: "string"
          nullable: true
        groupName:
          type: "string"
          nullable: true
        grants:
          type: "array"
          items:
            "$ref": "#/components/schemas/ResourceGrant"
          description: "Access grants. Omitted for a number that predates grants (only the link applies); `[]` means no grants."
        userId:
          type: "string"
          nullable: true
          description: "Legacy alias of linkedUserId."
        userName:
          type: "string"
        userEmail:
          type: "string"
      additionalProperties: true
      example:
        phoneNumberId: "6650a1b2c3d4e5f6a7b8c9d1"
        provider: "twilio"
        phoneNumber: "+14165550102"
        label: "Leasing team line"
        capabilities:
          - "sms"
          - "voice"
        status: "active"
        isOrgDefault: false
        linkedType: "group"
        linkedUserId: null
        linkedGroupId: "6650a1b2c3d4e5f6a7b8c9d2"
        groupName: "Leasing"
        grants:
          -
            principalType: "group"
            principalId: "6650a1b2c3d4e5f6a7b8c9d2"
            key: "group:6650a1b2c3d4e5f6a7b8c9d2"
            verbs:
              - "send"
              - "read"
            grantedBy:
              type: "user"
              userId: "6650a1b2c3d4e5f6a7b8c9d0"
            grantedAt: "2026-09-30T12:00:00.000Z"
        userId: null
        userName: ""
        userEmail: ""
    OrgPhoneNumberListResponse:
      type: "object"
      properties:
        assignments:
          type: "array"
          items:
            "$ref": "#/components/schemas/OrgPhoneNumberRow"
        coverage:
          type: "object"
          properties:
            orgUserCount:
              type: "integer"
            usersWithNumberCount:
              type: "integer"
              description: "Users with a DIRECTLY linked active SMS number."
            usersWithoutNumberCount:
              type: "integer"
            orgDefaultProviders:
              type: "array"
              items:
                type: "string"
              description: "Providers that have a usable org default line."
            hasOrgDefault:
              type: "boolean"
            claimableCount:
              type: "integer"
              description: "Unlinked numbers auto-assignment could hand out on the active provider. Short codes are never counted."
            activeSmsProvider:
              type: "string"
              nullable: true
          additionalProperties: true
      required:
        - "assignments"
      additionalProperties: true
    OrgPhoneNumberMutationResult:
      type: "object"
      description: "The stored PhoneNumber document after the write (including `grants` with their derived keys and stamps)."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        phoneNumber:
          type: "object"
          additionalProperties: true
          properties:
            _id:
              type: "string"
            organizationId:
              type: "string"
            provider:
              type: "string"
            phoneNumber:
              type: "string"
            isOrgDefault:
              type: "boolean"
            linkedType:
              type: "string"
              enum:
                - "user"
                - "group"
            linkedUserId:
              type: "string"
            linkedGroupId:
              type: "string"
            grants:
              type: "array"
              items:
                "$ref": "#/components/schemas/ResourceGrant"
      required:
        - "success"
        - "phoneNumber"
      additionalProperties: true
    OrgPhoneNumberDeleteResult:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        softDisabled:
          type: "boolean"
          description: "True when the number was disabled rather than removed."
        clearedOrgDefault:
          type: "boolean"
          description: "Present when the number was the org default sending line."
        message:
          type: "string"
      required:
        - "success"
        - "message"
      additionalProperties: true
    PhoneNumberErrorResponse:
      type: "object"
      properties:
        error:
          description: "A message string. When the path params or body fail contract validation it is instead `{ code: \"VALIDATION_ERROR\", message, details: [{ path, message }] }` (with `success: false`)."
      required:
        - "error"
      additionalProperties: true
      example:
        error: "Grant principal not found in this organization: user 6650a1b2c3d4e5f6a7b8c9d4"
    PipelineStageItem:
      type: "object"
      properties:
        _id:
          type: "string"
          description: "Existing stage id; include to update/rename a stage, omit to create a new one."
        name:
          type: "string"
          description: "Stage display name; must be unique within the pipeline."
        color:
          type: "string"
          description: "Hex color used to render the stage chip in the pipeline UI."
        position:
          type: "number"
          description: "Zero-based sort order within the pipeline; defaults to array index when omitted."
      additionalProperties: true
      example:
        _id: "67f0a0b0c0d0e0f0a0b0c0d0"
        name: "Qualified"
        color: "#10B981"
        position: 1
    LegacyStageItem:
      type: "object"
      properties:
        oldStage:
          type: "string"
          description: "Previous stage name; existing records with this `status` are migrated to `newStage`."
        newStage:
          type: "string"
          description: "New stage name to apply; becomes the stored stage and the migrated `status` value."
        color:
          type: "string"
          description: "Hex color used to render the stage chip in the pipeline UI."
      additionalProperties: true
      example:
        oldStage: "New Lead"
        newStage: "New"
        color: "#3B82F6"
    UpdatePipelineRequest:
      type: "object"
      properties:
        name:
          type: "string"
          description: "Pipeline display name; trimmed and unique within the organization."
        description:
          type: "string"
          description: "Optional human-readable summary of the pipeline's purpose."
        pipelineId:
          type: "string"
          description: "Pipeline to update; if omitted, the org's default pipeline for the given `type` is updated."
        stages:
          type: "array"
          description: "Legacy stage-rename mapping - pairs of `oldStage` -> `newStage` used to migrate existing records. Prefer `pipelineStages`."
          items:
            "$ref": "#/components/schemas/LegacyStageItem"
        pipelineStages:
          type: "array"
          description: "Stage definitions with `_id` (for updates), `name`, `color`, and `position`; omitted stages are deactivated."
          items:
            "$ref": "#/components/schemas/PipelineStageItem"
      additionalProperties: true
      example:
        name: "Sales pipeline"
        description: "NA sales pipeline"
        pipelineId: "66f0a0b0c0d0e0f0a0b0c0d0"
        pipelineStages:
          -
            name: "New"
            color: "#3B82F6"
            position: 0
          -
            name: "Qualified"
            color: "#10B981"
            position: 1
          -
            name: "Won"
            color: "#F59E0B"
            position: 2
    CreatePipelineRequest:
      type: "object"
      properties:
        name:
          type: "string"
          description: "Pipeline display name; required and unique within the organization."
        description:
          type: "string"
          description: "Optional human-readable summary of the pipeline's purpose."
        isDefault:
          type: "boolean"
          description: "When true, becomes the org's default pipeline for its `type` (the previous default loses the flag)."
        stages:
          type: "array"
          description: "Legacy stage list used when `pipelineStages` is not provided; entries are mapped to new pipeline stages by `newStage` name."
          items:
            "$ref": "#/components/schemas/LegacyStageItem"
        pipelineStages:
          type: "array"
          description: "Stage definitions with `name`, `color`, and `position` (sort order); takes precedence over `stages` and must be non-empty."
          items:
            "$ref": "#/components/schemas/PipelineStageItem"
      required:
        - "name"
      additionalProperties: true
      example:
        name: "EMEA sales pipeline"
        description: "EMEA-specific sales funnel"
        isDefault: false
        pipelineStages:
          -
            name: "New"
            color: "#3B82F6"
            position: 0
          -
            name: "Discovery"
            color: "#8B5CF6"
            position: 1
    SetDefaultPipelineRequest:
      type: "object"
      properties:
        pipelineId:
          type: "string"
          description: "Pipeline to promote to default for its `type`; previously-default pipelines on the same `type` lose the flag."
      required:
        - "pipelineId"
      additionalProperties: true
      example:
        pipelineId: "66f0a0b0c0d0e0f0a0b0c0d0"
    PipelineDto:
      type: "object"
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        description:
          type: "string"
        organizationId:
          type: "string"
        type:
          type: "string"
          enum:
            - "Contact"
            - "Application"
        isDefault:
          type: "boolean"
        isActive:
          type: "boolean"
        stages:
          type: "array"
          items:
            type: "object"
            properties:
              name:
                type: "string"
              color:
                type: "string"
            additionalProperties: true
        pipelineStageIds:
          type: "array"
          items:
            type: "string"
        pipelineStages:
          type: "array"
          items:
            "$ref": "#/components/schemas/PipelineStageItem"
        createdBy:
          type: "string"
          description: "User ID or populated user object"
        updatedBy:
          type: "string"
          description: "User ID or populated user object"
      additionalProperties: true
      example:
        _id: "66f0a0b0c0d0e0f0a0b0c0d0"
        name: "Sales pipeline"
        description: "NA sales pipeline"
        organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
        type: "Contact"
        isDefault: true
        isActive: true
        stages:
          -
            name: "New"
            color: "#3B82F6"
          -
            name: "Qualified"
            color: "#10B981"
        pipelineStageIds:
          - "67f0a0b0c0d0e0f0a0b0c0d0"
          - "67f0a0b0c0d0e0f0a0b0c0d1"
        pipelineStages:
          -
            _id: "67f0a0b0c0d0e0f0a0b0c0d0"
            name: "New"
            color: "#3B82F6"
            position: 0
          -
            _id: "67f0a0b0c0d0e0f0a0b0c0d1"
            name: "Qualified"
            color: "#10B981"
            position: 1
        createdBy: "65b1f0a2c3d4e5f6a7b8c9d0"
        updatedBy: "65b1f0a2c3d4e5f6a7b8c9d0"
    PipelineResponse:
      type: "object"
      properties:
        pipeline:
          "$ref": "#/components/schemas/PipelineDto"
      additionalProperties: true
      example:
        pipeline:
          _id: "66f0a0b0c0d0e0f0a0b0c0d0"
          name: "Sales pipeline"
          type: "Contact"
          isDefault: true
          pipelineStages:
            -
              _id: "67f0a0b0c0d0e0f0a0b0c0d0"
              name: "New"
              color: "#3B82F6"
              position: 0
            -
              _id: "67f0a0b0c0d0e0f0a0b0c0d1"
              name: "Qualified"
              color: "#10B981"
              position: 1
    PipelineListResponse:
      type: "object"
      properties:
        pipelines:
          type: "array"
          items:
            "$ref": "#/components/schemas/PipelineDto"
      additionalProperties: true
      example:
        pipelines:
          -
            _id: "66f0a0b0c0d0e0f0a0b0c0d0"
            name: "Sales pipeline"
            type: "Contact"
            isDefault: true
          -
            _id: "66f0a0b0c0d0e0f0a0b0c0d1"
            name: "EMEA sales pipeline"
            type: "Contact"
            isDefault: false
    PipelineMutationResponse:
      type: "object"
      properties:
        message:
          type: "string"
        pipeline:
          "$ref": "#/components/schemas/PipelineDto"
        contactsMigrated:
          type: "object"
          additionalProperties:
            type: "number"
      additionalProperties: true
      example:
        message: "Pipeline updated"
        pipeline:
          _id: "66f0a0b0c0d0e0f0a0b0c0d0"
          name: "Sales pipeline"
          type: "Contact"
          isDefault: true
        contactsMigrated:
          "New Lead -> New": 14
          "Qualified Lead -> Qualified": 8
    PipelineMigrationErrorResponse:
      type: "object"
      properties:
        message:
          type: "string"
        pipeline:
          "$ref": "#/components/schemas/PipelineDto"
        migrationError:
          type: "string"
        contactsMigrated:
          type: "object"
          additionalProperties:
            type: "number"
      additionalProperties: true
      example:
        message: "Pipeline updated with partial migration failure"
        pipeline:
          _id: "66f0a0b0c0d0e0f0a0b0c0d0"
          name: "Sales pipeline"
        migrationError: "Some records failed to migrate from \"Stalled\" -> \"Lost\""
        contactsMigrated:
          "New Lead -> New": 14
    PipelineErrorResponse:
      type: "object"
      properties:
        error:
          type: "string"
      additionalProperties: true
      example:
        error: "Pipeline not found"
    DeletePipelineRequest:
      type: "object"
      properties:
        targetPipelineId:
          type: "string"
          description: "Required when the pipeline still has assigned contacts or applications. Records are migrated to the first active stage of this destination pipeline before deletion."
      additionalProperties: true
      example:
        targetPipelineId: "66f0a0b0c0d0e0f0a0b0c0d1"
    PipelineDeletionAlternative:
      type: "object"
      properties:
        id:
          type: "string"
        name:
          type: "string"
      additionalProperties: true
      example:
        id: "66f0a0b0c0d0e0f0a0b0c0d1"
        name: "EMEA sales pipeline"
    DeletePipelineResponse:
      type: "object"
      properties:
        message:
          type: "string"
        pipelineId:
          type: "string"
        recordsTransferred:
          type: "number"
        movedToPipeline:
          nullable: true
          type: "object"
          properties:
            id:
              type: "string"
            name:
              type: "string"
          additionalProperties: true
        movedToStage:
          nullable: true
          type: "object"
          properties:
            id:
              type: "string"
            name:
              type: "string"
          additionalProperties: true
      additionalProperties: true
      example:
        message: "Pipeline deleted"
        pipelineId: "66f0a0b0c0d0e0f0a0b0c0d0"
        recordsTransferred: 22
        movedToPipeline:
          id: "66f0a0b0c0d0e0f0a0b0c0d1"
          name: "EMEA sales pipeline"
        movedToStage:
          id: "67f0a0b0c0d0e0f0a0b0c0e0"
          name: "New"
    PipelineUsageResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        pipelineId:
          type: "string"
        pipelineName:
          type: "string"
        pipelineType:
          type: "string"
          enum:
            - "Contact"
            - "Application"
        isInUse:
          type: "boolean"
        recordsCount:
          type: "number"
        hasAlternatives:
          type: "boolean"
        alternatives:
          type: "array"
          items:
            "$ref": "#/components/schemas/PipelineDeletionAlternative"
      additionalProperties: true
      example:
        success: true
        pipelineId: "66f0a0b0c0d0e0f0a0b0c0d0"
        pipelineName: "Sales pipeline"
        pipelineType: "Contact"
        isInUse: true
        recordsCount: 22
        hasAlternatives: true
        alternatives:
          -
            id: "66f0a0b0c0d0e0f0a0b0c0d1"
            name: "EMEA sales pipeline"
    PipelineStageUsageAlternative:
      type: "object"
      properties:
        id:
          type: "string"
        name:
          type: "string"
        color:
          type: "string"
      additionalProperties: true
      example:
        id: "67f0a0b0c0d0e0f0a0b0c0d1"
        name: "Qualified"
        color: "#10B981"
    PipelineStageUsageResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        stageId:
          type: "string"
        stageName:
          type: "string"
        pipelineType:
          type: "string"
          enum:
            - "Contact"
            - "Application"
        isInUse:
          type: "boolean"
        recordsCount:
          type: "number"
        hasAlternatives:
          type: "boolean"
        alternatives:
          type: "array"
          items:
            "$ref": "#/components/schemas/PipelineStageUsageAlternative"
      additionalProperties: true
      example:
        success: true
        stageId: "67f0a0b0c0d0e0f0a0b0c0d0"
        stageName: "New"
        pipelineType: "Contact"
        isInUse: true
        recordsCount: 7
        hasAlternatives: true
        alternatives:
          -
            id: "67f0a0b0c0d0e0f0a0b0c0d1"
            name: "Qualified"
            color: "#10B981"
    ReassignPipelineStageRequest:
      type: "object"
      properties:
        sourceStageId:
          type: "string"
          description: "Stage being retired - its contacts/applications are moved to `targetStageId` and the stage is deactivated."
        targetStageId:
          type: "string"
          description: "Destination stage that receives the source stage's records; must belong to the same pipeline and be active."
      required:
        - "sourceStageId"
        - "targetStageId"
      additionalProperties: true
      example:
        sourceStageId: "67f0a0b0c0d0e0f0a0b0c0d0"
        targetStageId: "67f0a0b0c0d0e0f0a0b0c0d1"
    ReassignPipelineStageResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        recordsTransferred:
          type: "number"
        sourceStage:
          type: "object"
          properties:
            id:
              type: "string"
            name:
              type: "string"
          additionalProperties: true
        targetStage:
          type: "object"
          properties:
            id:
              type: "string"
            name:
              type: "string"
          additionalProperties: true
      additionalProperties: true
      example:
        success: true
        recordsTransferred: 7
        sourceStage:
          id: "67f0a0b0c0d0e0f0a0b0c0d0"
          name: "New"
        targetStage:
          id: "67f0a0b0c0d0e0f0a0b0c0d1"
          name: "Qualified"
    ProcessGetForSelectedUserRequest:
      type: "object"
      properties:
        selectedUser:
          type: "object"
          properties:
            userId:
              type: "string"
          required:
            - "userId"
          additionalProperties: true
          description: "User `_id` whose prompts/processes the caller wants to read (admin-scoped)."
      required:
        - "selectedUser"
      additionalProperties: true
      example:
        selectedUser:
          userId: "65b1f0a2c3d4e5f6a7b8c9d0"
    ProcessDto:
      type: "object"
      description: "A \"process\" is a populated Prompt document attached to a user. Legacy naming - the underlying entity is `Prompt`. Shape is forwarded as-is from the populated Mongoose document."
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        prompt:
          type: "string"
        responseTime:
          type: "number"
        description:
          type: "string"
        isHidden:
          type: "boolean"
        temperature:
          type: "number"
        createdBy:
          type: "string"
        organizationId:
          type: "string"
        voiceAI:
          type: "object"
          additionalProperties: true
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "65b2a1c3d4e5f6a7b8c9d0e1"
        name: "Lead qualification"
        prompt: "You are a friendly intake specialist..."
        responseTime: 5
        description: "Qualifies inbound leads and sets disposition."
        isHidden: false
        temperature: 0.4
        createdBy: "65b1f0a2c3d4e5f6a7b8c9d0"
        organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
        createdAt: "2026-04-01T10:00:00.000Z"
        updatedAt: "2026-05-15T18:24:11.000Z"
    ProcessListResponse:
      type: "object"
      description: "Response from `GET /api/processes` and `POST /api/processes`."
      properties:
        message:
          type: "string"
        processes:
          type: "array"
          items:
            "$ref": "#/components/schemas/ProcessDto"
          description: "The user's populated prompts. May be empty when the user has none assigned."
      required:
        - "processes"
      additionalProperties: true
      example:
        message: "Processes fetched successfully"
        processes:
          -
            _id: "65b2a1c3d4e5f6a7b8c9d0e1"
            name: "Lead qualification"
            prompt: "You are a friendly intake specialist..."
            responseTime: 5
            isHidden: false
            temperature: 0.4
            createdBy: "65b1f0a2c3d4e5f6a7b8c9d0"
            organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
            createdAt: "2026-04-01T10:00:00.000Z"
            updatedAt: "2026-05-15T18:24:11.000Z"
    ProcessErrorResponse:
      type: "object"
      description: "Error envelope returned by process endpoints."
      properties:
        message:
          type: "string"
        error:
          type: "string"
      required:
        - "message"
      additionalProperties: true
      example:
        message: "User not found"
        error: "NOT_FOUND"
    PromptCreateRequest:
      type: "object"
      properties:
        name:
          type: "string"
          description: "Human-readable prompt name shown in pickers and lists."
        prompt:
          type: "string"
          description: "XML prompt body driving the AI agent."
        responseTime:
          type: "number"
          description: "Target reply latency in seconds; the engine throttles streaming to roughly this duration."
        description:
          type: "string"
          description: "Short summary of the prompt's purpose; surfaced in summary lists and pickers."
        isHidden:
          type: "boolean"
          description: "Hidden prompts are excluded from non-admin lists and approval flows."
        temperature:
          type: "number"
          description: "Sampling temperature (0-1). Lower = more deterministic."
      required:
        - "name"
      additionalProperties: true
      example:
        name: "Leasing follow-up assistant"
        prompt: "<prompt><role>Leasing assistant</role><goal>Re-engage leads 24h after their last reply.</goal></prompt>"
        description: "Follow up with leads 24h after their last response."
        temperature: 0.7
        responseTime: 45
        isHidden: false
    PromptUpdateRequest:
      type: "object"
      properties:
        name:
          type: "string"
          description: "Human-readable prompt name shown in pickers and lists."
        prompt:
          type: "string"
          description: "XML prompt body driving the AI agent."
        responseTime:
          type: "number"
          description: "Target reply latency in seconds; the engine throttles streaming to roughly this duration."
        description:
          type: "string"
          description: "Short summary of the prompt's purpose; surfaced in summary lists and pickers."
        temperature:
          type: "number"
          description: "Sampling temperature (0-1). Lower = more deterministic."
        tools:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
          description: "Enabled tool keys (e.g. `getContact`, `sendSms`, `transfer`)."
        toolConfigs:
          type: "object"
          additionalProperties: true
          description: "Per-tool config overrides keyed by tool name."
      additionalProperties: true
      example:
        name: "Leasing follow-up assistant (v2)"
        prompt: "<prompt><role>Leasing assistant</role><goal>Be friendly, concise, and confirm next steps.</goal></prompt>"
        description: "Refined tone; clearer next-step CTA."
        temperature: 0.6
        responseTime: 30
        tools:
          -
            name: "book_tour"
        toolConfigs:
          book_tour:
            requireApproval: true
    PromptReassignRequest:
      type: "object"
      properties:
        promptId:
          type: "string"
          description: "Source prompt `_id` whose contacts and conversations will be moved; this prompt is then deleted."
        targetPromptId:
          type: "string"
          description: "Destination prompt `_id` that will receive the reassigned contacts and conversations."
      required:
        - "promptId"
        - "targetPromptId"
      additionalProperties: true
      example:
        promptId: "5f7b1c2e8a1d4e0012c3b4a5"
        targetPromptId: "5f7b1c2e8a1d4e0012c3b4a6"
    PromptVersionSummary:
      type: "object"
      properties:
        _id:
          type: "string"
        version:
          type: "integer"
        label:
          type: "string"
          nullable: true
        displayVersion:
          type: "string"
          nullable: true
        title:
          type: "string"
          nullable: true
        description:
          type: "string"
          nullable: true
        source:
          type: "string"
          enum:
            - "manual_save"
            - "ai_apply"
            - "checkpoint"
        createdAt:
          type: "string"
          format: "date-time"
        matchesCurrentPrompt:
          type: "boolean"
        preview:
          type: "string"
      additionalProperties: true
      example:
        _id: "65f9b1c2e8a1d4e001a0b1c3"
        version: 4
        label: "Friendlier tone"
        displayVersion: "v1.3"
        title: "Tone update"
        description: "Softened the opening line."
        source: "manual_save"
        createdAt: "2026-04-22T10:14:00.000Z"
        matchesCurrentPrompt: true
        preview: "<prompt><role>Leasing assistant</role>..."
    PromptVersionListResponse:
      type: "object"
      properties:
        versions:
          type: "array"
          items:
            "$ref": "#/components/schemas/PromptVersionSummary"
        total:
          type: "integer"
        limit:
          type: "integer"
        skip:
          type: "integer"
      required:
        - "versions"
        - "total"
        - "limit"
        - "skip"
      additionalProperties: true
      example:
        versions:
          -
            _id: "65f9b1c2e8a1d4e001a0b1c3"
            version: 4
            displayVersion: "v1.3"
            source: "manual_save"
            createdAt: "2026-04-22T10:14:00.000Z"
            matchesCurrentPrompt: true
            preview: "<prompt>..."
        total: 7
        limit: 20
        skip: 0
    PromptVersionCheckpointRequest:
      type: "object"
      properties:
        prompt:
          type: "string"
          description: "Optional override; defaults to current prompt body when omitted"
        label:
          type: "string"
        displayVersion:
          type: "string"
          nullable: true
        title:
          type: "string"
          nullable: true
        description:
          type: "string"
          nullable: true
        source:
          type: "string"
          enum:
            - "manual_save"
            - "ai_apply"
            - "checkpoint"
      additionalProperties: true
      example:
        label: "Pre-launch checkpoint"
        displayVersion: "v1.4"
        title: "Pre-launch"
        description: "Snapshot before rolling out to production."
        source: "manual_save"
    PromptVersionCheckpointResponse:
      type: "object"
      properties:
        message:
          type: "string"
        skipped:
          type: "boolean"
        version:
          type: "integer"
        versionId:
          type: "string"
        versionSnapshot:
          "$ref": "#/components/schemas/PromptVersionSummary"
      additionalProperties: true
      example:
        message: "Version saved"
        skipped: false
        version: 5
        versionId: "65f9b1c2e8a1d4e001a0b1c4"
    PromptVersionMetadataUpdateRequest:
      type: "object"
      properties:
        displayVersion:
          type: "string"
          nullable: true
          description: "Human label shown in the version dropdown (e.g. `v1.4`); pass null to clear."
        title:
          type: "string"
          nullable: true
          description: "Short label shown on the version timeline entry; pass null to clear."
        description:
          type: "string"
          nullable: true
          description: "Longer description shown on the version timeline entry; pass null to clear."
      additionalProperties: true
      example:
        displayVersion: "v1.5"
        title: "Tone tweak"
        description: "Softened opening line based on feedback."
    AdminPromptListItem:
      type: "object"
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        description:
          type: "string"
        organizationId:
          type: "string"
        organizationName:
          type: "string"
        createdBy:
          type: "string"
        isHidden:
          type: "boolean"
        isPublished:
          type: "boolean"
        updatedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "5f7b1c2e8a1d4e0012c3b4a5"
        name: "Leasing follow-up assistant"
        description: "Follow up with leads 24h after their last response."
        organizationId: "64a1b2c3d4e5f60012345678"
        organizationName: "Maple Property Group"
        createdBy: "64a1b2c3d4e5f60012345679"
        isHidden: false
        isPublished: true
        updatedAt: "2026-04-22T10:14:00.000Z"
    AdminPromptListResponse:
      type: "object"
      properties:
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/AdminPromptListItem"
        totalCount:
          type: "integer"
        hiddenCount:
          type: "integer"
        visibleCount:
          type: "integer"
        currentPage:
          type: "integer"
        hasNextPage:
          type: "boolean"
      required:
        - "data"
        - "totalCount"
        - "currentPage"
        - "hasNextPage"
      additionalProperties: true
      example:
        data:
          -
            _id: "5f7b1c2e8a1d4e0012c3b4a5"
            name: "Leasing follow-up assistant"
            organizationId: "64a1b2c3d4e5f60012345678"
            organizationName: "Maple Property Group"
            isHidden: false
            isPublished: true
            updatedAt: "2026-04-22T10:14:00.000Z"
        totalCount: 27
        hiddenCount: 4
        visibleCount: 23
        currentPage: 1
        hasNextPage: true
    PromptErrorResponse:
      type: "object"
      description: "Generic error envelope returned by Prompt endpoints."
      properties:
        error:
          type: "string"
        details:
          type: "string"
      required:
        - "error"
      additionalProperties: true
      example:
        error: "Prompt not found"
        details: "No prompt with id 5f7b1c2e8a1d4e0012c3b4a5 belongs to this user."
    PromptDocument:
      type: "object"
      description: "Prompt document as stored in the Prompt collection. Returned shape varies slightly per endpoint (some list/summary endpoints project a subset of fields)."
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        prompt:
          type: "string"
          description: "Prompt body. Omitted (i.e. stripped) for non-admin callers when `isHidden` is true."
        description:
          type: "string"
        temperature:
          type: "number"
        responseTime:
          type: "number"
        isHidden:
          type: "boolean"
        tools:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
        toolConfigs:
          type: "object"
          additionalProperties: true
        organizationId:
          type: "string"
        userId:
          type: "string"
        copiedFrom:
          type: "string"
          nullable: true
        copiedFromName:
          type: "string"
          nullable: true
        copiedFromOrg:
          type: "string"
          nullable: true
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "5f7b1c2e8a1d4e0012c3b4a5"
        name: "Leasing follow-up assistant"
        prompt: "<prompt><role>Leasing assistant</role><goal>Re-engage leads 24h after their last reply.</goal></prompt>"
        description: "Follow up with leads 24h after their last response."
        temperature: 0.7
        responseTime: 45
        isHidden: false
        tools:
          -
            name: "book_tour"
        toolConfigs:
          book_tour:
            requireApproval: true
        organizationId: "64a1b2c3d4e5f60012345678"
        userId: "64a1b2c3d4e5f60012345679"
        createdAt: "2026-03-12T14:22:10.000Z"
        updatedAt: "2026-04-22T10:14:00.000Z"
    PromptUserPromptsResponse:
      description: "Returned by GET /api/prompts/user. An array of the caller's prompts (with hidden bodies stripped for non-admins), OR an empty object `{}` when the user has no prompts."
      oneOf:
        -
          type: "array"
          items:
            "$ref": "#/components/schemas/PromptDocument"
        -
          type: "object"
          description: "Returned when the user has no prompts."
          additionalProperties: false
      example:
        -
          _id: "5f7b1c2e8a1d4e0012c3b4a5"
          name: "Leasing follow-up assistant"
          prompt: "<prompt>...</prompt>"
          description: "Follow up with leads 24h after their last response."
          temperature: 0.7
          responseTime: 45
          isHidden: false
          organizationId: "64a1b2c3d4e5f60012345678"
          userId: "64a1b2c3d4e5f60012345679"
    PromptWithAccessMetadataResponse:
      type: "object"
      description: "Prompt document spread with marketplace-access metadata, returned by GET /api/prompts/{promptId}."
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        prompt:
          type: "string"
        description:
          type: "string"
        temperature:
          type: "number"
        responseTime:
          type: "number"
        isHidden:
          type: "boolean"
        _isReference:
          type: "boolean"
        _isEditableReference:
          type: "boolean"
        _isOwned:
          type: "boolean"
      required:
        - "_isReference"
        - "_isEditableReference"
        - "_isOwned"
      additionalProperties: true
      example:
        _id: "5f7b1c2e8a1d4e0012c3b4a5"
        name: "Leasing follow-up assistant"
        prompt: "<prompt><role>Leasing assistant</role><goal>Re-engage leads.</goal></prompt>"
        description: "Follow up with leads 24h after their last response."
        temperature: 0.7
        responseTime: 45
        isHidden: false
        _isReference: false
        _isEditableReference: false
        _isOwned: true
    PromptDeleteResponse:
      type: "object"
      properties:
        message:
          type: "string"
          example: "Prompt deleted successfully"
      required:
        - "message"
      additionalProperties: false
      example:
        message: "Prompt deleted successfully"
    PromptDeletePublishedErrorResponse:
      type: "object"
      description: "Returned with HTTP 400 when the caller attempts to delete a prompt that is currently published to the marketplace."
      properties:
        error:
          type: "string"
        isPublished:
          type: "boolean"
          example: true
      required:
        - "error"
      additionalProperties: true
      example:
        error: "Cannot delete a published prompt"
        isPublished: true
    PromptUsageAlternative:
      type: "object"
      properties:
        id:
          type: "string"
        name:
          type: "string"
        description:
          type: "string"
      required:
        - "id"
        - "name"
      additionalProperties: true
      example:
        id: "5f7b1c2e8a1d4e0012c3b4a6"
        name: "Standard follow-up assistant"
        description: "Generic follow-up prompt suitable as a replacement."
    PromptUsageResponse:
      type: "object"
      properties:
        promptId:
          type: "string"
        promptName:
          type: "string"
        isInUse:
          type: "boolean"
        contactsCount:
          type: "integer"
        conversationsCount:
          type: "integer"
        totalUsageCount:
          type: "integer"
        hasAlternatives:
          type: "boolean"
        alternatives:
          type: "array"
          items:
            "$ref": "#/components/schemas/PromptUsageAlternative"
      required:
        - "promptId"
        - "isInUse"
        - "contactsCount"
        - "conversationsCount"
        - "totalUsageCount"
      additionalProperties: true
      example:
        promptId: "5f7b1c2e8a1d4e0012c3b4a5"
        promptName: "Leasing follow-up assistant"
        isInUse: true
        contactsCount: 24
        conversationsCount: 31
        totalUsageCount: 55
        hasAlternatives: true
        alternatives:
          -
            id: "5f7b1c2e8a1d4e0012c3b4a6"
            name: "Standard follow-up assistant"
            description: "Generic follow-up prompt."
    PromptSummarizedOwnPrompt:
      type: "object"
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        description:
          type: "string"
        temperature:
          type: "number"
        responseTime:
          type: "number"
        updatedAt:
          type: "string"
          format: "date-time"
        isHidden:
          type: "boolean"
        isReference:
          type: "boolean"
          example: false
        isOwned:
          type: "boolean"
          example: true
        isPublished:
          type: "boolean"
        isCopied:
          type: "boolean"
        copiedFromName:
          type: "string"
          nullable: true
        copiedFromOrg:
          type: "string"
          nullable: true
      additionalProperties: true
      example:
        _id: "5f7b1c2e8a1d4e0012c3b4a5"
        name: "Leasing follow-up assistant"
        description: "Follow up with leads 24h after their last response."
        temperature: 0.7
        responseTime: 45
        updatedAt: "2026-04-22T10:14:00.000Z"
        isHidden: false
        isReference: false
        isOwned: true
        isPublished: false
        isCopied: false
    PromptSummarizedReferencePrompt:
      type: "object"
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        description:
          type: "string"
        temperature:
          type: "number"
        responseTime:
          type: "number"
        updatedAt:
          type: "string"
          format: "date-time"
        isReference:
          type: "boolean"
          example: true
        isEditableReference:
          type: "boolean"
        isOwned:
          type: "boolean"
          example: false
        publisherOrg:
          type: "string"
        isContentVisible:
          type: "boolean"
      additionalProperties: true
      example:
        _id: "5f7b1c2e8a1d4e0012c3b4a7"
        name: "Tether published - Leasing starter"
        description: "Marketplace starter prompt for leasing follow-up."
        temperature: 0.6
        responseTime: 30
        updatedAt: "2026-04-10T09:30:00.000Z"
        isReference: true
        isEditableReference: false
        isOwned: false
        publisherOrg: "Tether AI"
        isContentVisible: true
    PromptSummarizedPromptListResponse:
      type: "array"
      description: "Flat list mixing own-prompt summaries and acquired reference-prompt summaries; discriminated by the `isReference`/`isOwned` flags."
      items:
        oneOf:
          -
            "$ref": "#/components/schemas/PromptSummarizedOwnPrompt"
          -
            "$ref": "#/components/schemas/PromptSummarizedReferencePrompt"
      example:
        -
          _id: "5f7b1c2e8a1d4e0012c3b4a5"
          name: "Leasing follow-up assistant"
          description: "Follow up with leads 24h after their last response."
          isReference: false
          isOwned: true
          isPublished: false
        -
          _id: "5f7b1c2e8a1d4e0012c3b4a7"
          name: "Tether published - Leasing starter"
          description: "Marketplace starter prompt."
          isReference: true
          isOwned: false
          isContentVisible: true
    PromptVersionDocument:
      type: "object"
      description: "Full prompt-version document including the prompt body."
      properties:
        _id:
          type: "string"
        promptId:
          type: "string"
        prompt:
          type: "string"
        version:
          type: "integer"
        label:
          type: "string"
          nullable: true
        displayVersion:
          type: "string"
          nullable: true
        title:
          type: "string"
          nullable: true
        description:
          type: "string"
          nullable: true
        source:
          type: "string"
          enum:
            - "manual_save"
            - "ai_apply"
            - "checkpoint"
        createdBy:
          type: "string"
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "65f9b1c2e8a1d4e001a0b1c4"
        promptId: "5f7b1c2e8a1d4e0012c3b4a5"
        prompt: "<prompt><role>Leasing assistant</role><goal>Re-engage leads 24h after their last reply.</goal></prompt>"
        version: 5
        label: "Pre-launch checkpoint"
        displayVersion: "v1.4"
        title: "Pre-launch"
        description: "Snapshot before rolling out to production."
        source: "manual_save"
        createdBy: "64a1b2c3d4e5f60012345679"
        createdAt: "2026-04-25T10:14:00.000Z"
        updatedAt: "2026-04-25T10:14:00.000Z"
    PromptCreateResponse:
      type: "object"
      description: "Returned by `POST /api/prompts/create`."
      properties:
        message:
          type: "string"
        prompt:
          "$ref": "#/components/schemas/PromptDocument"
      required:
        - "message"
        - "prompt"
      additionalProperties: true
      example:
        message: "Prompt created successfully"
        prompt:
          _id: "64d2f9c5e8a1d4e001a0b1c2"
          name: "Maple Court - Tour confirm"
          description: "Confirms a tour booking and proposes alternates."
          prompt: "<prompt><role>Leasing assistant</role><goal>Confirm tour.</goal></prompt>"
          temperature: 0.3
          responseTime: 30
          isHidden: false
          voiceAI:
            enabled: false
          createdBy: "64a1b2c3d4e5f60012345679"
          organizationId: "64a1b2c3d4e5f60012345678"
          createdAt: "2026-05-20T15:04:01.135Z"
          updatedAt: "2026-05-20T15:04:01.135Z"
    PromptUpdateResponse:
      type: "object"
      description: "`versionSnapshot` is only present when the update created a version checkpoint as a side-effect (e.g. autosave thresholds)."
      properties:
        message:
          type: "string"
        prompt:
          "$ref": "#/components/schemas/PromptDocument"
        versionSnapshot:
          "$ref": "#/components/schemas/PromptVersionSummary"
      required:
        - "message"
        - "prompt"
      additionalProperties: true
      example:
        message: "Prompt updated successfully"
        prompt:
          _id: "64d2f9c5e8a1d4e001a0b1c2"
          name: "Maple Court - Tour confirm"
          prompt: "<prompt>updated body</prompt>"
          temperature: 0.4
          lastEditedAt: "2026-05-20T15:04:01.135Z"
        versionSnapshot:
          _id: "64d2f9c5e8a1d4e001a0b1d8"
          version: 6
          displayVersion: "v1.5"
          createdAt: "2026-05-20T15:04:01.135Z"
    PromptSmsApprovalConflictAlternative:
      type: "object"
      description: "A suggested alternative prompt the caller can reassign to when an SMS-approval conflict blocks the update."
      properties:
        id:
          type: "string"
        name:
          type: "string"
        description:
          type: "string"
      required:
        - "id"
        - "name"
      additionalProperties: true
      example:
        id: "64d2f9c5e8a1d4e001a0b1c3"
        name: "Maple Court - Tour confirm (no approval)"
        description: "Variant without approval-required tools."
    PromptSmsApprovalConflictResponse:
      type: "object"
      description: "409 envelope returned when updating a prompt would change its set of approval-required tools while the prompt is bound to active SMS conversations. The client surfaces this to ask the user to reassign or pick an alternate."
      properties:
        error:
          type: "string"
        code:
          type: "string"
          enum:
            - "SMS_APPROVAL_CONFLICT"
        conflict:
          type: "object"
          properties:
            promptId:
              type: "string"
            promptName:
              type: "string"
            newlyApprovalRequiredTools:
              type: "array"
              items:
                type: "string"
            conversationsCount:
              type: "integer"
            contactsCount:
              type: "integer"
            hasAlternatives:
              type: "boolean"
            alternatives:
              type: "array"
              items:
                "$ref": "#/components/schemas/PromptSmsApprovalConflictAlternative"
          required:
            - "promptId"
            - "promptName"
            - "conversationsCount"
            - "contactsCount"
          additionalProperties: true
      required:
        - "error"
        - "code"
        - "conflict"
      additionalProperties: true
      example:
        error: "This agent is currently assigned to one or more SMS conversations and the newly required approval tools would change its surface."
        code: "SMS_APPROVAL_CONFLICT"
        conflict:
          promptId: "64d2f9c5e8a1d4e001a0b1c2"
          promptName: "Maple Court - Tour confirm"
          newlyApprovalRequiredTools:
            - "sendSms"
            - "transferCall"
          conversationsCount: 12
          contactsCount: 9
          hasAlternatives: true
          alternatives:
            -
              id: "64d2f9c5e8a1d4e001a0b1c3"
              name: "Maple Court - Tour confirm (no approval)"
              description: "Variant without approval-required tools."
    PromptReassignResponse:
      type: "object"
      description: "Returned by `POST /api/prompts/reassign`."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        contactsUpdated:
          type: "integer"
        conversationsUpdated:
          type: "integer"
        totalUpdated:
          type: "integer"
      required:
        - "success"
        - "message"
        - "contactsUpdated"
        - "conversationsUpdated"
        - "totalUpdated"
      additionalProperties: true
      example:
        success: true
        message: "Successfully reassigned 14 items and deleted prompt"
        contactsUpdated: 9
        conversationsUpdated: 5
        totalUpdated: 14
    PromptVersionUpdateResponse:
      type: "object"
      description: "Returned by `PATCH /api/prompts/{promptId}/versions/{versionId}`."
      properties:
        message:
          type: "string"
        version:
          "$ref": "#/components/schemas/PromptVersionSummary"
      required:
        - "message"
        - "version"
      additionalProperties: true
      example:
        message: "Prompt version updated successfully"
        version:
          _id: "64d2f9c5e8a1d4e001a0b1d8"
          version: 5
          label: "Pre-launch checkpoint (renamed)"
          displayVersion: "v1.4"
          title: "Pre-launch - final"
          description: "Renamed during launch retro."
          source: "manual_save"
          createdAt: "2026-04-25T10:14:00.000Z"
    RecordFieldMetadataDto:
      type: "object"
      properties:
        field:
          type: "string"
          description: "Dotted path, entity-relative."
        customEntityType:
          type: "string"
          nullable: true
        customEntityInstanceId:
          type: "string"
          description: "Empty for the record's own fields."
        firstSetAt:
          type: "string"
          format: "date-time"
        firstSetBy:
          "$ref": "#/components/schemas/RecordLogActor"
        lastSetAt:
          type: "string"
          format: "date-time"
        lastSetBy:
          "$ref": "#/components/schemas/RecordLogActor"
      required:
        - "field"
        - "customEntityInstanceId"
        - "firstSetAt"
        - "firstSetBy"
        - "lastSetAt"
        - "lastSetBy"
    RecordFieldMetadataResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "object"
          properties:
            entityType:
              type: "string"
              enum:
                - "Contact"
                - "Application"
                - "Conversation"
            entityId:
              type: "string"
            fields:
              type: "array"
              items:
                "$ref": "#/components/schemas/RecordFieldMetadataDto"
          required:
            - "entityType"
            - "entityId"
            - "fields"
      required:
        - "success"
        - "data"
    RecordLogActor:
      type: "object"
      properties:
        type:
          type: "string"
          enum:
            - "user"
            - "ai"
            - "system"
            - "automation"
            - "workflow"
        userId:
          type: "string"
          nullable: true
        label:
          type: "string"
          nullable: true
      required:
        - "type"
      additionalProperties: true
    RecordLogDto:
      type: "object"
      description: "A persisted RecordLog row. Change rows carry field/old/new/changeCategory; action rows carry action/properties; custom-entity rows carry the parent linkage."
      properties:
        _id:
          type: "string"
        organizationId:
          type: "string"
        timestamp:
          type: "string"
          format: "date-time"
        kind:
          type: "string"
          enum:
            - "change"
            - "action"
        entityType:
          type: "string"
          enum:
            - "Contact"
            - "Application"
            - "Conversation"
            - "CustomEntity"
        entityId:
          type: "string"
        contactId:
          type: "string"
          description: "Root contact this log rolls up to (hub key)."
        actor:
          "$ref": "#/components/schemas/RecordLogActor"
        field:
          type: "string"
          nullable: true
        fieldLabel:
          type: "string"
          nullable: true
        oldValue:
          description: "Previous value (any type)."
          nullable: true
        newValue:
          description: "New value (any type)."
          nullable: true
        changeCategory:
          type: "string"
          enum:
            - "state"
            - "field"
          nullable: true
        action:
          type: "string"
          nullable: true
        properties:
          type: "object"
          additionalProperties: true
          nullable: true
        parentEntityType:
          type: "string"
          enum:
            - "Contact"
            - "Application"
            - "Conversation"
          nullable: true
        parentEntityId:
          type: "string"
          nullable: true
        customEntityType:
          type: "string"
          nullable: true
        customEntityInstanceId:
          type: "string"
          nullable: true
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "6a3b6b9b0b9ea0c1d6da9359"
        organizationId: "68d504c9aa4c0ca510f46fed"
        timestamp: "2026-06-25T06:43:40.825Z"
        kind: "change"
        entityType: "Contact"
        entityId: "6a390f4ac5cd810bd491c8fe"
        contactId: "6a390f4ac5cd810bd491c8fe"
        actor:
          type: "user"
          userId: "68cd6b13f5b13e3d2da22e8f"
        field: "status"
        oldValue: "QA 11"
        newValue: "QA 22"
        changeCategory: "state"
    RecordLogMeta:
      type: "object"
      properties:
        total:
          type: "integer"
        page:
          type: "integer"
        size:
          type: "integer"
      required:
        - "total"
        - "page"
        - "size"
      additionalProperties: true
      example:
        total: 312
        page: 1
        size: 50
    RecordLogListResponse:
      type: "object"
      description: "Response from `GET /api/record-logs`."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/RecordLogDto"
        meta:
          "$ref": "#/components/schemas/RecordLogMeta"
      required:
        - "success"
        - "data"
        - "meta"
      additionalProperties: true
    RecordLogErrorResponse:
      type: "object"
      description: "Error envelope returned by record-log endpoints."
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
        error:
          type: "string"
      required:
        - "success"
        - "message"
      additionalProperties: true
      example:
        success: false
        message: "Access denied"
    CreateReminderRequest:
      type: "object"
      properties:
        contactId:
          type: "string"
        note:
          type: "string"
        reminderDate:
          type: "string"
          format: "date-time"
          description: "ISO timestamp; must be in the future"
        localTimestamp:
          type: "string"
          description: "Caller-supplied local-time representation (optional)"
        channelType:
          type: "string"
          default: "sms"
        phoneNumber:
          type: "string"
        messengerId:
          type: "string"
        webchatId:
          type: "string"
        contactName:
          type: "string"
        assigneeId:
          type: "string"
          nullable: true
          description: "User notified when the reminder fires. Defaults to the calling user; null creates a silent reminder."
        notifyContactAssignees:
          type: "boolean"
          description: "When the reminder has no assignee, notify the contact's assignees instead of nobody. The string forms \"true\"/\"false\", \"1\"/\"0\", \"yes\"/\"no\" and \"on\"/\"off\" are accepted; any other string is a 400."
        applicationId:
          type: "string"
          description: "Application this reminder is attached to. Must be in the caller organization."
        conversationId:
          type: "string"
          description: "Conversation this reminder is attached to. Must be in the caller organization."
        action:
          type: "string"
          description: "Free-form action tag, matched by the Reminder Due trigger's action filter."
      required:
        - "contactId"
        - "note"
        - "reminderDate"
      additionalProperties: true
      example:
        contactId: "65c2d0e0f0a0b0c0d0e0f0a0"
        note: "Follow up on demo booking"
        reminderDate: "2026-05-22T15:00:00.000Z"
        localTimestamp: "2026-05-22 11:00 EDT"
        channelType: "sms"
        phoneNumber: "+14155550123"
        contactName: "Jane Doe"
    ReminderDto:
      type: "object"
      properties:
        _id:
          type: "string"
        contactId:
          type: "string"
        organizationId:
          type: "string"
        createdBy:
          type: "string"
          description: "Audit provenance: who or what booked the reminder. Not a recipient."
        assigneeId:
          type: "string"
          description: "The user notified when the reminder fires. Absent = silent reminder."
        notifyContactAssignees:
          type: "boolean"
        note:
          type: "string"
        reminderDate:
          type: "string"
          format: "date-time"
        localTimestamp:
          type: "string"
        channelType:
          type: "string"
        phoneNumber:
          type: "string"
        messengerId:
          type: "string"
        webchatId:
          type: "string"
        contactName:
          type: "string"
        applicationId:
          type: "string"
          description: "Application the reminder is attached to, when it has one."
        conversationId:
          type: "string"
          description: "Conversation the reminder is attached to, when it has one."
        action:
          type: "string"
          description: "Action tag set at creation."
        workflowId:
          type: "string"
          description: "Workflow that booked the reminder, when one did. Absent on UI-created reminders."
        fired:
          type: "boolean"
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "65f0a0b0c0d0e0f0a0b0c0d0"
        contactId: "65c2d0e0f0a0b0c0d0e0f0a0"
        organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
        createdBy: "65b1f0a2c3d4e5f6a7b8c9d0"
        assigneeId: "65b1f0a2c3d4e5f6a7b8c9d0"
        note: "Follow up on demo booking"
        reminderDate: "2026-05-22T15:00:00.000Z"
        channelType: "sms"
        phoneNumber: "+14155550123"
        contactName: "Jane Doe"
        fired: false
        createdAt: "2026-05-18T12:00:00.000Z"
        updatedAt: "2026-05-18T12:00:00.000Z"
    ReminderListResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/ReminderDto"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          -
            _id: "65f0a0b0c0d0e0f0a0b0c0d0"
            contactId: "65c2d0e0f0a0b0c0d0e0f0a0"
            organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
            createdBy: "65b1f0a2c3d4e5f6a7b8c9d0"
            assigneeId: "65b1f0a2c3d4e5f6a7b8c9d0"
            note: "Follow up on demo booking"
            reminderDate: "2026-05-22T15:00:00.000Z"
            channelType: "sms"
            fired: false
            createdAt: "2026-05-18T12:00:00.000Z"
            updatedAt: "2026-05-18T12:00:00.000Z"
    ReminderMutationResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        data:
          "$ref": "#/components/schemas/ReminderDto"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        message: "Reminder created successfully"
        data:
          _id: "65f0a0b0c0d0e0f0a0b0c0d0"
          contactId: "65c2d0e0f0a0b0c0d0e0f0a0"
          organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
          createdBy: "65b1f0a2c3d4e5f6a7b8c9d0"
          assigneeId: "65b1f0a2c3d4e5f6a7b8c9d0"
          note: "Follow up on demo booking"
          reminderDate: "2026-05-22T15:00:00.000Z"
          channelType: "sms"
          fired: false
          createdAt: "2026-05-18T12:00:00.000Z"
          updatedAt: "2026-05-18T12:00:00.000Z"
    ReminderDeleteResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
      required:
        - "success"
      additionalProperties: true
      example:
        success: true
        message: "Reminder deleted successfully"
    ReminderErrorResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
        error:
          type: "string"
      required:
        - "success"
      additionalProperties: true
      example:
        success: false
        message: "Contact not found"
        error: "NOT_FOUND"
    SmsProviderName:
      type: "string"
      enum:
        - "twilio"
        - "sinch"
        - "textgrid"
      description: "Supported SMS providers. `twilio` and `textgrid` use the Twilio-compatible REST API; `sinch` uses Sinch Conversation API for SMS and a separate MMS service."
      example: "twilio"
    SmsActiveProviderResponse:
      type: "object"
      description: "Response from `GET /api/sms/providers`."
      properties:
        provider:
          nullable: true
          allOf:
            -
              "$ref": "#/components/schemas/SmsProviderName"
          description: "Active SMS provider for the organization. `null` when no provider is configured or selected."
      required:
        - "provider"
      additionalProperties: true
      example:
        provider: "twilio"
    SmsProviderConfigEntry:
      type: "object"
      description: "Per-provider configuration row returned by `GET /api/sms/providers/config`. Credential fields are present only for providers that are configured; absent fields mean the credential was never saved (NOT that it is empty-string)."
      properties:
        provider:
          "$ref": "#/components/schemas/SmsProviderName"
        isEnabled:
          type: "boolean"
          description: "`true` when the provider has credentials and has not been explicitly disabled. Effectively `isConfigured && !disabled`."
        isConfigured:
          type: "boolean"
          description: "`true` when at least the required credentials for this provider are present."
        twilioAccountSid:
          type: "string"
          description: "Twilio Account SID (e.g. `ACxxxxxxxx...`)."
        twilioAuthToken:
          type: "string"
          description: "Twilio Auth Token."
        twilioMessagingServiceSid:
          type: "string"
          description: "Twilio Messaging Service SID (e.g. `MGxxxxxxxx...`). Optional but recommended."
        sinchServicePlanId:
          type: "string"
          description: "Sinch Service Plan ID used for SMS."
        sinchApiToken:
          type: "string"
          description: "Sinch SMS API token."
        sinchMmsApiKey:
          type: "string"
          description: "Sinch MMS API key (separate from SMS credentials)."
        sinchMmsServiceId:
          type: "string"
          description: "Sinch MMS service identifier."
        textGridAccountSid:
          type: "string"
          description: "TextGrid Account SID."
        textGridAuthToken:
          type: "string"
          description: "TextGrid Auth Token."
      required:
        - "provider"
        - "isEnabled"
        - "isConfigured"
      additionalProperties: true
      example:
        provider: "twilio"
        isEnabled: true
        isConfigured: true
        twilioAccountSid: "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
        twilioAuthToken: "••••••••••••••••••••••••••••••••"
        twilioMessagingServiceSid: "MGxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    SmsProviderConfigResponse:
      type: "object"
      description: "Response from `GET /api/sms/providers/config`."
      properties:
        activeProvider:
          nullable: true
          allOf:
            -
              "$ref": "#/components/schemas/SmsProviderName"
          description: "Currently-active provider for the org. May be `null` even when providers are configured but none has been promoted."
        providers:
          type: "array"
          items:
            "$ref": "#/components/schemas/SmsProviderConfigEntry"
          description: "One entry per supported provider - `twilio`, `sinch`, `textgrid` - regardless of whether it is configured. Frontends iterate this list to render the settings UI."
      required:
        - "providers"
      additionalProperties: true
      example:
        activeProvider: "twilio"
        providers:
          -
            provider: "twilio"
            isEnabled: true
            isConfigured: true
            twilioAccountSid: "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
            twilioAuthToken: "••••••••••••••••••••••••••••••••"
            twilioMessagingServiceSid: "MGxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
          -
            provider: "sinch"
            isEnabled: false
            isConfigured: false
          -
            provider: "textgrid"
            isEnabled: false
            isConfigured: false
    SmsMutationResponse:
      type: "object"
      description: "Shared response for save / set-active / delete operations."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
          description: "Human-readable confirmation (e.g. \"twilio SMS configuration saved\")."
      required:
        - "success"
      additionalProperties: true
      example:
        success: true
        message: "twilio SMS configuration saved"
    SmsSaveProviderConfigRequest:
      type: "object"
      description: "Save credentials for a single SMS provider. Only the fields relevant to `provider` are read; others may be present but are ignored. All credential strings are trimmed before persistence."
      properties:
        provider:
          "$ref": "#/components/schemas/SmsProviderName"
        twilioAccountSid:
          type: "string"
          description: "Required when `provider` is `twilio`."
        twilioAuthToken:
          type: "string"
          description: "Required when `provider` is `twilio`."
        twilioMessagingServiceSid:
          type: "string"
          description: "Optional but recommended when `provider` is `twilio`."
        sinchServicePlanId:
          type: "string"
          description: "Required when `provider` is `sinch`."
        sinchApiToken:
          type: "string"
          description: "Required when `provider` is `sinch`."
        sinchMmsApiKey:
          type: "string"
          description: "Optional Sinch MMS API key."
        sinchMmsServiceId:
          type: "string"
          description: "Optional Sinch MMS service identifier."
        textGridAccountSid:
          type: "string"
          description: "Required when `provider` is `textgrid`."
        textGridAuthToken:
          type: "string"
          description: "Required when `provider` is `textgrid`."
      required:
        - "provider"
      additionalProperties: true
      example:
        provider: "twilio"
        twilioAccountSid: "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
        twilioAuthToken: "your-twilio-auth-token"
        twilioMessagingServiceSid: "MGxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    SmsSetActiveProviderRequest:
      type: "object"
      properties:
        provider:
          allOf:
            -
              "$ref": "#/components/schemas/SmsProviderName"
          description: "SMS provider to activate: `sinch`, `twilio`, or `textgrid`."
      required:
        - "provider"
      additionalProperties: true
      example:
        provider: "twilio"
    SmsErrorResponse:
      type: "object"
      description: "Error envelope for `/api/sms/*` endpoints (provider configuration)."
      properties:
        error:
          type: "string"
        message:
          type: "string"
        success:
          type: "boolean"
          enum:
            - false
      required:
        - "error"
      additionalProperties: true
      example:
        error: "Provider configuration not found"
    ForwardTracesRequest:
      type: "object"
      description: "OpenTelemetry trace payload (any shape). The body is forwarded verbatim to the configured collector (Axiom) - Tether does not parse it, so any OTLP-JSON or vendor-extended structure works."
      additionalProperties: true
      example:
        resourceSpans:
          -
            resource:
              attributes:
                -
                  key: "service.name"
                  value:
                    stringValue: "tether-web"
                -
                  key: "service.version"
                  value:
                    stringValue: "2026.05.20"
            scopeSpans:
              -
                spans:
                  -
                    traceId: "4bf92f3577b34da6a3ce929d0e0e4736"
                    spanId: "00f067aa0ba902b7"
                    name: "POST /api/messages"
                    kind: 3
                    startTimeUnixNano: "1763624641135000000"
                    endTimeUnixNano: "1763624641311000000"
                    attributes:
                      -
                        key: "http.status_code"
                        value:
                          intValue: 200
    ReportClientErrorsRequest:
      type: "object"
      required:
        - "events"
      properties:
        events:
          type: "array"
          minItems: 1
          maxItems: 20
          items:
            type: "object"
            required:
              - "kind"
              - "message"
              - "route"
              - "sessionId"
              - "occurredAt"
            properties:
              kind:
                type: "string"
                enum:
                  - "uncaught"
                  - "unhandledrejection"
                  - "react-boundary"
                  - "route-error"
                  - "service-worker"
                  - "handled"
              name:
                type: "string"
              message:
                type: "string"
                maxLength: 2000
              stack:
                type: "string"
              componentStack:
                type: "string"
              route:
                type: "string"
                description: "Pathname only, no query string"
              appVersion:
                type: "string"
              environment:
                type: "string"
              sessionId:
                type: "string"
              occurredAt:
                type: "string"
                format: "date-time"
              context:
                type: "object"
                additionalProperties: true
      example:
        events:
          -
            kind: "uncaught"
            name: "TypeError"
            message: "Cannot read properties of undefined (reading 'id')"
            route: "/conversations"
            sessionId: "6f1c2f4e-0b0a-4a8e-9a36-1c1f2d3e4f50"
            occurredAt: "2026-09-29T10:00:00.000Z"
    ForwardTracesResponse:
      type: "object"
      properties:
        status:
          type: "string"
          enum:
            - "accepted"
          description: "Always `accepted` - the API queues the payload synchronously and returns; downstream collector failures are not surfaced."
      required:
        - "status"
      additionalProperties: true
      example:
        status: "accepted"
    CreateTemplateRequest:
      type: "object"
      properties:
        name:
          type: "string"
          description: "Template display name shown in the template picker."
        template:
          type: "string"
          description: "Template body with `{{firstName}}`-style placeholders resolved at send time."
        type:
          type: "string"
          description: "Template kind: `sms`, `email`, `campaign`, `script`, `automation`."
        category:
          type: "string"
          description: "Grouping label for filtering; required unless `type === \"automation\"`."
      required:
        - "name"
        - "template"
        - "type"
      additionalProperties: true
      example:
        name: "Demo follow-up"
        template: "Hi {{firstName}}, thanks for the demo today!"
        type: "message"
        category: "sales-followup"
    UpdateTemplateRequest:
      type: "object"
      properties:
        name:
          type: "string"
          description: "Template display name shown in the template picker."
        template:
          type: "string"
          description: "Template body with `{{firstName}}`-style placeholders resolved at send time."
        type:
          type: "string"
          description: "Template kind: `sms`, `email`, `campaign`, `script`, `automation`."
        category:
          type: "string"
          description: "Grouping label for filtering; required unless `type === \"automation\"`."
      additionalProperties: true
      example:
        template: "Hi {{firstName}}, just checking in after our chat!"
    TemplatesErrorResponse:
      type: "object"
      description: "Error envelope used by templates endpoints."
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
      additionalProperties: true
      example:
        success: false
        message: "Template not found"
    TemplateItem:
      type: "object"
      description: "Mongoose `Template` document. `category` is omitted when `type === \"automation\"`."
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        template:
          type: "string"
        type:
          type: "string"
        category:
          type: "string"
          nullable: true
        userId:
          type: "string"
        organizationId:
          type: "string"
        createdBy:
          type: "string"
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "66a0a0b0c0d0e0f0a0b0c0d0"
        name: "Demo follow-up"
        template: "Hi {{firstName}}, thanks for the demo today!"
        type: "message"
        category: "sales-followup"
        userId: "65b1f0a2c3d4e5f6a7b8c9d0"
        organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
        createdBy: "65b1f0a2c3d4e5f6a7b8c9d0"
        createdAt: "2026-04-12T08:00:00.000Z"
        updatedAt: "2026-04-12T08:00:00.000Z"
    TemplatesListResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/TemplateItem"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          -
            _id: "66a0a0b0c0d0e0f0a0b0c0d0"
            name: "Demo follow-up"
            template: "Hi {{firstName}}, thanks for the demo today!"
            type: "message"
            category: "sales-followup"
            organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
            createdBy: "65b1f0a2c3d4e5f6a7b8c9d0"
            createdAt: "2026-04-12T08:00:00.000Z"
            updatedAt: "2026-04-12T08:00:00.000Z"
    TemplateMutationResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          "$ref": "#/components/schemas/TemplateItem"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          _id: "66a0a0b0c0d0e0f0a0b0c0d0"
          name: "Demo follow-up"
          template: "Hi {{firstName}}, thanks for the demo today!"
          type: "message"
          category: "sales-followup"
          organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
          createdBy: "65b1f0a2c3d4e5f6a7b8c9d0"
          createdAt: "2026-04-12T08:00:00.000Z"
          updatedAt: "2026-04-12T08:00:00.000Z"
    TemplateDeleteResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
      required:
        - "success"
        - "message"
      additionalProperties: true
      example:
        success: true
        message: "Template deleted"
    GetToolsResponse:
      type: "object"
      properties:
        tools:
          type: "object"
          additionalProperties:
            type: "object"
            properties:
              name:
                type: "string"
              description:
                type: "string"
              type:
                type: "string"
                enum:
                  - "read"
                  - "mutation"
                  - "realtime"
              dedupDefault:
                type: "object"
                description: "The tool's effective duplicate-call policy with no author override: its type default plus any registry policy."
                properties:
                  key:
                    type: "string"
                    enum:
                      - "name"
                      - "name+args"
                      - "idempotency-key"
                  scope:
                    type: "string"
                    enum:
                      - "generation-turn"
                      - "conversation"
                      - "time-window"
                  partition:
                    type: "string"
                    enum:
                      - "shared"
                      - "per-agent"
                  onRepeat:
                    type: "string"
                    enum:
                      - "block"
                      - "skip-silently"
                      - "return-prior-result"
                      - "allow"
                  windowSeconds:
                    type: "integer"
                    minimum: 1
              replayDefault:
                type: "boolean"
                description: "Whether a completed call is replayed into later turns when the agent sets nothing."
              dedupMaxSeconds:
                type: "integer"
                minimum: 1
                description: "How long a 'conversation'-scoped duplicate-call record lasts: the read-cache TTL for read tools, one hour otherwise."
            required:
              - "name"
              - "description"
            additionalProperties: true
      required:
        - "tools"
      additionalProperties: true
      example:
        tools:
          send_message:
            name: "send_message"
            description: "Send an outbound message to the contact on the current channel."
            type: "mutation"
            dedupDefault:
              key: "name"
              scope: "conversation"
              partition: "shared"
              onRepeat: "block"
              windowSeconds: 30
            replayDefault: true
            dedupMaxSeconds: 3600
          escalate_to_human:
            name: "escalate_to_human"
            description: "Escalate the conversation to a human agent."
    UploadFileDto:
      type: "object"
      properties:
        key:
          type: "string"
          description: "R2 storage key"
        type:
          type: "string"
          description: "MIME type"
        name:
          type: "string"
          description: "Original filename"
        size:
          type: "integer"
        signedUrl:
          type: "string"
          description: "Short-lived signed URL for immediate access"
        bucket:
          type: "string"
      required:
        - "key"
        - "type"
        - "name"
        - "size"
        - "signedUrl"
        - "bucket"
      additionalProperties: true
      example:
        key: "orgs/65b1f0a2c3d4e5f6a7b8c9d0/uploads/2026-05-18/invoice.pdf"
        type: "application/pdf"
        name: "invoice.pdf"
        size: 184221
        signedUrl: "https://r2.example.com/orgs/65b1.../invoice.pdf?token=..."
        bucket: "tether-uploads"
    UploadFilesResponse:
      type: "object"
      properties:
        files:
          type: "array"
          items:
            "$ref": "#/components/schemas/UploadFileDto"
      required:
        - "files"
      additionalProperties: true
      example:
        files:
          -
            key: "orgs/65b1f0a2c3d4e5f6a7b8c9d0/uploads/2026-05-18/invoice.pdf"
            type: "application/pdf"
            name: "invoice.pdf"
            size: 184221
            signedUrl: "https://r2.example.com/orgs/65b1.../invoice.pdf?token=..."
            bucket: "tether-uploads"
    UploadErrorResponse:
      type: "object"
      properties:
        error:
          type: "string"
        message:
          type: "string"
      additionalProperties: true
      example:
        error: "NO_FILES"
        message: "No files uploaded"
    UserUpdateProfileRequest:
      type: "object"
      properties:
        fullName:
          type: "string"
          description: "Display name shown across the UI and on outbound messages signed by this user."
        email:
          type: "string"
          format: "email"
          description: "Primary login email; must be unique across all users - endpoint returns 409 if already taken."
        phoneNumber:
          type: "string"
          description: "Personal mobile number (E.164 preferred); rejected if it collides with a provisioned organization SMS number."
        designation:
          type: "string"
          description: "Free-form job title (e.g., \"Senior Account Executive\"); used for display only."
        departmentId:
          type: "string"
          description: "ObjectId of the Department the user belongs to; controls team visibility and routing."
        accessRole:
          type: "string"
          description: "Role granted to the user: `SUPERADMIN`, `ADMIN`, `DEPARTMENT_HEAD`, `SALES_REP`."
        automations:
          type: "object"
          additionalProperties: true
          description: "Per-user automation toggles and configuration (free-form map persisted as `Mixed` on the User document)."
        callForwardingEnabled:
          type: "boolean"
          description: "Whether inbound calls should be forwarded to the user personal phone when they are offline or busy."
        notificationPreferences:
          type: "object"
          additionalProperties: true
          description: "Per-category notification toggles (aiResponses, automationTriggers, escalations, calls, etc.). See `UserNotificationPreferences`."
        persona:
          type: "object"
          description: "Persona fields written to the user linked `Persona` document; created on first set, otherwise merged. `businessHours`/`timezone` require the org-level override flag."
          properties:
            user:
              type: "string"
              description: "Display name used when the AI signs messages on behalf of this rep."
            position:
              type: "string"
              description: "Title the AI uses in its signature/identity (e.g., \"Leasing Manager\")."
            userEmail:
              type: "string"
              description: "Contact email surfaced by the AI persona (may differ from the login email)."
            organization:
              type: "string"
              description: "Organization name the AI persona introduces itself with."
            organizationAddress:
              type: "string"
              description: "Physical address the AI may share when prospects ask for location."
            leadProvider:
              type: "string"
              description: "Source of leads being worked (e.g., \"Facebook Lead Ads\") - informs AI context."
            organizationWebsite:
              type: "string"
              description: "Public website URL the AI may share with contacts."
            organizationCity:
              type: "string"
              description: "City the organization operates from; used for localization in AI responses."
            region:
              type: "string"
              description: "State/province/region used for localization and compliance hints."
            timezone:
              type: "string"
              description: "IANA timezone (e.g., `America/Toronto`); requires `allowUserBusinessHoursOverride` to be enabled at the org."
            businessHours:
              type: "string"
              description: "Per-day availability windows for the AI; requires `allowUserBusinessHoursOverride` to be enabled at the org."
          additionalProperties: true
      additionalProperties: true
      example:
        fullName: "Alex Rep"
        email: "alex@acme.example"
        phoneNumber: "+14155550199"
        designation: "Senior Account Executive"
        callForwardingEnabled: true
    UserUpdateChatAvailabilityRequest:
      type: "object"
      properties:
        isAvailable:
          type: "boolean"
          description: "New availability flag; when set to `true` the escalation queue is processed and the user becomes eligible for round-robin chat assignment."
      required:
        - "isAvailable"
      additionalProperties: false
      example:
        isAvailable: true
    UserUpdateNotificationPreferencesRequest:
      type: "object"
      properties:
        notificationPreferences:
          type: "object"
          description: "Per-category notification toggles (aiResponses, automationTriggers, escalations, calls, etc.). See `UserNotificationPreferences`."
          properties:
            aiResponses:
              type: "boolean"
              description: "Notify when the AI sends a response on the user behalf."
            inboundInAutopilot:
              type: "boolean"
              description: "Notify on inbound messages while the conversation is in autopilot (AI is handling)."
            automationTriggers:
              type: "boolean"
              description: "Notify when an automation rule fires for one of the user conversations."
            emailSync:
              type: "boolean"
              description: "Notify on email-channel sync events (inbound email synced into a conversation)."
            escalations:
              type: "boolean"
              description: "Notify when a conversation is escalated from AI to a human agent."
            assignments:
              type: "boolean"
              description: "Notify when a conversation is assigned to or transferred to the user."
            calls:
              type: "boolean"
              description: "Notify on inbound voice calls and missed-call events."
            campaigns:
              type: "boolean"
              description: "Notify on campaign-related events (launch, completion, replies)."
            other:
              type: "boolean"
              description: "Catch-all toggle for regular inbound messages and @mentions not covered by other categories."
          additionalProperties: true
      required:
        - "notificationPreferences"
      additionalProperties: true
      example:
        notificationPreferences:
          aiResponses: true
          escalations: true
          assignments: true
          calls: false
          campaigns: true
          other: false
    UserListByTeamRequest:
      type: "object"
      properties:
        organizationId:
          type: "string"
          description: "Restrict results to this organization; non-superadmins are silently scoped to their own org regardless of value."
        departmentId:
          type: "string"
          description: "Restrict results to users in this department; omitted/empty falls back to the caller department (for `DEPARTMENT_HEAD`/`SALES_REP`)."
      additionalProperties: true
      example:
        organizationId: "64ee9a8b1e7f2a0011223344"
        departmentId: "64eea1110000000000000020"
    UserUpdateByIdRequest:
      type: "object"
      properties:
        fullName:
          type: "string"
          description: "Display name shown across the UI for the target user."
        email:
          type: "string"
          format: "email"
          description: "New login email; endpoint returns 409 if another user already has this email."
        phoneNumber:
          type: "string"
          description: "Target user personal mobile number (E.164 preferred)."
        designation:
          type: "string"
          description: "Free-form job title (e.g., \"Senior Account Executive\"); display only."
        accessRole:
          type: "string"
          description: "Role granted to the user: `SUPERADMIN`, `ADMIN`, `DEPARTMENT_HEAD`, `SALES_REP`. Only `SUPERADMIN` callers may change this field."
        departmentId:
          type: "string"
          description: "ObjectId of the Department the user belongs to; changes are mirrored to the department `managerIds` list for `DEPARTMENT_HEAD` users."
      additionalProperties: true
      example:
        fullName: "Alex Rep"
        accessRole: "DEPARTMENT_HEAD"
        departmentId: "64eea1110000000000000020"
    UserResetPasswordRequest:
      type: "object"
      properties:
        userId:
          type: "string"
          description: "ObjectId of the user whose password is being reset."
        newPassword:
          type: "string"
          description: "Replacement password (plain text over TLS); hashed before storage and immediately invalidates the previous credential."
      required:
        - "userId"
        - "newPassword"
      additionalProperties: false
      example:
        userId: "64ee9a8b1e7f2a0011223399"
        newPassword: "NewStr0ng!Pass"
    UserCreateSmsTemplateRequest:
      type: "object"
      properties:
        name:
          type: "string"
          description: "Human-readable template title shown in the composer picker (e.g., \"Intro - new lead\")."
        template:
          type: "string"
          description: "Template body containing `{{firstName}}`-style placeholders resolved against the contact at send time."
        type:
          type: "string"
          description: "Template kind: `sms`, `campaign`, `script`, or `automation`. Automation templates ignore `category`."
        category:
          type: "string"
          description: "Category slug (matches `TemplateCategory.name`) used to group templates in the picker; defaults to `other` when omitted for non-automation types."
      required:
        - "name"
        - "template"
        - "type"
      additionalProperties: true
      example:
        name: "Intro - new lead"
        template: "Hi {{firstName}}, thanks for reaching out - when is a good time to chat?"
        type: "sms"
        category: "introduction"
    UserUpdateSmsTemplateRequest:
      type: "object"
      properties:
        name:
          type: "string"
          description: "New human-readable template title; omit to leave unchanged."
        template:
          type: "string"
          description: "New template body with `{{firstName}}`-style placeholders; omit to leave unchanged."
        type:
          type: "string"
          description: "New template kind (`sms`, `campaign`, `script`, `automation`); switching to/from `automation` clears the `category` field."
        category:
          type: "string"
          description: "New category slug; ignored when the template type is `automation`."
      additionalProperties: true
      example:
        name: "Intro - new lead (v2)"
        template: "Hi {{firstName}}, just checking in - got a sec to chat today?"
    UserGetTemplateWithDataRequest:
      type: "object"
      properties:
        phoneNumber:
          type: "string"
          description: "Contact phone number used to locate the contact record for SMS/voice placeholder resolution; formatted before lookup."
        selectedUser:
          type: "object"
          description: "Channel target used to locate the contact when not addressing them by phone (e.g., Facebook Messenger)."
          properties:
            channelType:
              type: "string"
              description: "Conversation channel: `sms`, `facebook`, etc. When `facebook`, lookup is by `messengerId` instead of `phoneNumber`."
            messengerId:
              type: "string"
              description: "Channel-specific contact identifier (e.g., Facebook Page-scoped user id) used to find the contact when `channelType` is non-SMS."
          additionalProperties: true
      additionalProperties: true
      example:
        phoneNumber: "+14155550133"
        selectedUser:
          channelType: "sms"
          messengerId: "+14155550133"
    UserCreateTemplateCategoryRequest:
      type: "object"
      properties:
        name:
          type: "string"
          description: "Internal slug for the category; lower-cased and trimmed on save, and must be unique across all categories."
        displayName:
          type: "string"
          description: "Human-readable label shown to users in the template picker (e.g., \"Introduction\")."
        description:
          type: "string"
          description: "Optional short blurb describing when to use this category."
        color:
          type: "string"
          description: "Tailwind class string (or hex) used for the category badge; defaults to `bg-gray-100 text-gray-800` when omitted."
      required:
        - "name"
        - "displayName"
      additionalProperties: true
      example:
        name: "introduction"
        displayName: "Introduction"
        description: "First-touch templates for new leads."
        color: "#3B82F6"
    UserUpdateTemplateCategoryRequest:
      type: "object"
      properties:
        name:
          type: "string"
          description: "New internal slug; lower-cased and trimmed before uniqueness check - endpoint returns 400 if it collides with another category."
        displayName:
          type: "string"
          description: "New human-readable label shown in the template picker."
        description:
          type: "string"
          description: "New blurb describing the category; pass an empty string to clear."
        color:
          type: "string"
          description: "New Tailwind class string (or hex) for the category badge."
        isActive:
          type: "boolean"
          description: "Whether the category should appear in pickers and lists; setting `false` soft-hides without deleting."
      additionalProperties: true
      example:
        displayName: "Introduction"
        color: "#2563EB"
        isActive: true
    UserReorderTemplateCategoriesRequest:
      type: "object"
      properties:
        categoryIds:
          type: "array"
          items:
            type: "string"
          description: "Category `_id`s in their desired display order; the first id becomes `sortOrder: 0`."
      required:
        - "categoryIds"
      additionalProperties: false
      example:
        categoryIds:
          - "64eea1110000000000000031"
          - "64eea1110000000000000032"
          - "64eea1110000000000000033"
    UserErrorResponse:
      type: "object"
      description: "Generic error envelope returned by Users endpoints. Most paths only include `error`; some add `details` for diagnostic context."
      properties:
        error:
          type: "string"
        details:
          type: "string"
      required:
        - "error"
      additionalProperties: true
      example:
        error: "User not found"
        details: "No user with id 64ee9a8b1e7f2a0011223399"
    UserAdminErrorResponse:
      type: "object"
      description: "Error envelope returned by admin user-management endpoints (delete/update/toggle-password-auth). Adds `success: false` to the standard `error`/`details` shape."
      properties:
        success:
          type: "boolean"
          example: false
        error:
          type: "string"
        details:
          type: "string"
      required:
        - "error"
      additionalProperties: true
      example:
        success: false
        error: "Unauthorized"
        details: "ADMIN role required"
    UserPersona:
      type: "object"
      description: "Persona document linked to a user (may be null when unset)."
      properties:
        _id:
          type: "string"
        user:
          type: "string"
        position:
          type: "string"
        userEmail:
          type: "string"
        organization:
          type: "string"
        organizationAddress:
          type: "string"
        leadProvider:
          type: "string"
        organizationWebsite:
          type: "string"
        organizationCity:
          type: "string"
        region:
          type: "string"
        timezone:
          type: "string"
        businessHours:
          type: "string"
      additionalProperties: true
      example:
        _id: "64eea1110000000000000040"
        user: "Alex Rep"
        position: "Senior Account Executive"
        userEmail: "alex@acme.example"
        organization: "Acme Corp"
        organizationAddress: "500 Bay St, Toronto, ON"
        leadProvider: "Facebook Lead Ads"
        organizationWebsite: "https://acme.example"
        organizationCity: "Toronto"
        region: "Ontario"
        timezone: "America/Toronto"
        businessHours: "9am-6pm Mon-Fri"
    UserProfile:
      type: "object"
      description: "Authenticated user profile document. Fields are projected from `User` and may vary slightly depending on which controller served the request."
      properties:
        _id:
          type: "string"
        accessRole:
          type: "string"
        departmentId:
          type: "string"
          nullable: true
        fullName:
          type: "string"
        email:
          type: "string"
          format: "email"
        phoneNumber:
          type: "string"
        designation:
          type: "string"
        callForwardingEnabled:
          type: "boolean"
        persona:
          type: "string"
          nullable: true
        conversationOpenPreference:
          type: "string"
        organizationId:
          type: "string"
      additionalProperties: true
      example:
        _id: "64ee9a8b1e7f2a0011223399"
        accessRole: "DEPARTMENT_HEAD"
        departmentId: "64eea1110000000000000020"
        fullName: "Alex Rep"
        email: "alex@acme.example"
        phoneNumber: "+14155550199"
        designation: "Senior Account Executive"
        callForwardingEnabled: true
        persona: "64eea1110000000000000040"
        conversationOpenPreference: "always"
        organizationId: "64ee9a8b1e7f2a0011223344"
    UserProfileResponse:
      type: "object"
      description: "Returned by GET /api/user/profile. `user` is the projected User document; `persona` is the resolved Persona (or null when the user has none)."
      properties:
        user:
          "$ref": "#/components/schemas/UserProfile"
        persona:
          nullable: true
          allOf:
            -
              "$ref": "#/components/schemas/UserPersona"
      required:
        - "user"
      additionalProperties: true
      example:
        user:
          _id: "64ee9a8b1e7f2a0011223399"
          fullName: "Alex Rep"
          email: "alex@acme.example"
          accessRole: "DEPARTMENT_HEAD"
          organizationId: "64ee9a8b1e7f2a0011223344"
        persona:
          _id: "64eea1110000000000000040"
          organization: "Acme Corp"
          timezone: "America/Toronto"
    UserApiKeyResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          example: true
        data:
          type: "object"
          properties:
            apiKey:
              type: "string"
          required:
            - "apiKey"
          additionalProperties: false
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          apiKey: "tk_live_4f1a2c9f10b8d5a2c9f10b8d5a2c9f10b8d5"
    UserApiKeyRegenerateResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          example: true
        message:
          type: "string"
        data:
          type: "object"
          properties:
            apiKey:
              type: "string"
          required:
            - "apiKey"
          additionalProperties: false
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        message: "API key regenerated"
        data:
          apiKey: "tk_live_7c2b3d8e21a9f6c2b3d8e21a9f6c2b3d8e21"
    UserChatAvailability:
      type: "object"
      properties:
        isAvailable:
          type: "boolean"
        lastStatusChange:
          type: "string"
          format: "date-time"
          nullable: true
      required:
        - "isAvailable"
      additionalProperties: true
      example:
        isAvailable: true
        lastStatusChange: "2026-05-18T10:00:00.000Z"
    UserChatAvailabilityResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          example: true
        data:
          "$ref": "#/components/schemas/UserChatAvailability"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          isAvailable: true
          lastStatusChange: "2026-05-18T10:00:00.000Z"
    UserNotificationPreferences:
      type: "object"
      properties:
        aiResponses:
          type: "boolean"
        inboundInAutopilot:
          type: "boolean"
        automationTriggers:
          type: "boolean"
        emailSync:
          type: "boolean"
        escalations:
          type: "boolean"
        autopilotMonitor:
          type: "boolean"
        humanMonitor:
          type: "boolean"
        assignments:
          type: "boolean"
        calls:
          type: "boolean"
        campaigns:
          type: "boolean"
        other:
          type: "boolean"
      additionalProperties: true
      example:
        aiResponses: true
        inboundInAutopilot: true
        automationTriggers: false
        emailSync: true
        escalations: true
        autopilotMonitor: false
        humanMonitor: true
        assignments: true
        calls: false
        campaigns: true
        other: false
    UserNotificationPreferencesResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          example: true
        data:
          "$ref": "#/components/schemas/UserNotificationPreferences"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          aiResponses: true
          escalations: true
          assignments: true
          calls: false
          campaigns: true
    UserListItem:
      type: "object"
      description: "Projected User row returned by /api/user/list. Includes only fields the controller selects from the User collection."
      properties:
        _id:
          type: "string"
        fullName:
          type: "string"
        email:
          type: "string"
          format: "email"
        phoneNumber:
          type: "string"
        designation:
          type: "string"
        accessRole:
          type: "string"
        organizationId:
          type: "string"
        departmentId:
          type: "string"
          nullable: true
        loginDisabled:
          type: "boolean"
      additionalProperties: true
      example:
        _id: "64ee9a8b1e7f2a0011223399"
        fullName: "Alex Rep"
        email: "alex@acme.example"
        phoneNumber: "+14155550199"
        designation: "Senior Account Executive"
        accessRole: "DEPARTMENT_HEAD"
        organizationId: "64ee9a8b1e7f2a0011223344"
        departmentId: "64eea1110000000000000020"
        loginDisabled: false
    UserListResponse:
      type: "array"
      items:
        "$ref": "#/components/schemas/UserListItem"
      example:
        -
          _id: "64ee9a8b1e7f2a0011223399"
          fullName: "Alex Rep"
          email: "alex@acme.example"
          accessRole: "DEPARTMENT_HEAD"
          organizationId: "64ee9a8b1e7f2a0011223344"
    UserDeleteResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          example: true
        message:
          type: "string"
      required:
        - "success"
        - "message"
      additionalProperties: true
      example:
        success: true
        message: "User deleted"
    UserTogglePasswordAuthResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          example: true
        message:
          type: "string"
        data:
          type: "object"
          properties:
            userId:
              type: "string"
            isPasswordDisabled:
              type: "boolean"
          required:
            - "userId"
            - "isPasswordDisabled"
          additionalProperties: false
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        message: "Password auth disabled"
        data:
          userId: "64ee9a8b1e7f2a0011223399"
          isPasswordDisabled: true
    UserSmsTemplate:
      type: "object"
      description: "Template document as stored under the Template collection. Includes the populated `createdBy` reference when returned via list endpoints."
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        template:
          type: "string"
        type:
          type: "string"
          enum:
            - "sms"
            - "campaign"
            - "script"
            - "automation"
        category:
          type: "string"
        organizationId:
          type: "string"
        userId:
          type: "string"
        createdBy:
          type: "object"
          properties:
            _id:
              type: "string"
            fullName:
              type: "string"
            email:
              type: "string"
              format: "email"
          additionalProperties: true
        updatedBy:
          type: "string"
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "64eea1110000000000000050"
        name: "Intro - new lead"
        template: "Hi {{firstName}}, thanks for reaching out - when is a good time to chat?"
        type: "sms"
        category: "introduction"
        organizationId: "64ee9a8b1e7f2a0011223344"
        userId: "64ee9a8b1e7f2a0011223399"
        createdBy:
          _id: "64ee9a8b1e7f2a0011223399"
          fullName: "Alex Rep"
          email: "alex@acme.example"
        createdAt: "2026-05-01T09:00:00.000Z"
        updatedAt: "2026-05-10T15:23:00.000Z"
    UserSmsTemplateListResponse:
      type: "array"
      items:
        "$ref": "#/components/schemas/UserSmsTemplate"
      example:
        -
          _id: "64eea1110000000000000050"
          name: "Intro - new lead"
          template: "Hi {{firstName}}, thanks for reaching out - when is a good time to chat?"
          type: "sms"
          category: "introduction"
    UserSmsTemplateDeleteResponse:
      type: "object"
      properties:
        message:
          type: "string"
      required:
        - "message"
      additionalProperties: true
      example:
        message: "Template deleted"
    UserTemplateCategory:
      type: "object"
      description: "Template category document. `createdBy` is populated with a thin User reference when returned by list endpoints."
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        displayName:
          type: "string"
        description:
          type: "string"
        color:
          type: "string"
        sortOrder:
          type: "integer"
        isActive:
          type: "boolean"
        createdBy:
          type: "object"
          properties:
            _id:
              type: "string"
            fullName:
              type: "string"
            email:
              type: "string"
              format: "email"
          additionalProperties: true
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "64eea1110000000000000031"
        name: "introduction"
        displayName: "Introduction"
        description: "First-touch templates for new leads."
        color: "#3B82F6"
        sortOrder: 0
        isActive: true
        createdBy:
          _id: "64ee9a8b1e7f2a0011223399"
          fullName: "Alex Rep"
          email: "alex@acme.example"
        createdAt: "2026-05-01T09:00:00.000Z"
        updatedAt: "2026-05-10T15:23:00.000Z"
    UserTemplateCategoryListResponse:
      type: "array"
      items:
        "$ref": "#/components/schemas/UserTemplateCategory"
      example:
        -
          _id: "64eea1110000000000000031"
          name: "introduction"
          displayName: "Introduction"
          sortOrder: 0
          isActive: true
    UserTemplateCategoryDeleteResponse:
      type: "object"
      properties:
        message:
          type: "string"
      required:
        - "message"
      additionalProperties: true
      example:
        message: "Category deleted"
    UserSimpleMessageResponse:
      type: "object"
      description: "Generic single-message success envelope used for reset-password / reorder / etc."
      properties:
        message:
          type: "string"
      required:
        - "message"
      additionalProperties: true
      example:
        message: "Password reset successfully"
    UserUpdateProfileResponse:
      type: "object"
      description: "Returned after `PUT /api/user/profile`. Returns the refreshed user plus the updated persona side-by-side."
      properties:
        user:
          type: "object"
          additionalProperties: true
          description: "Refreshed User document, without the password or the legacy per-user phone fields (sinchPhoneNumber, voicePhoneNumbers, twilioPhoneNumber)."
        persona:
          "$ref": "#/components/schemas/UserPersona"
      required:
        - "user"
        - "persona"
      additionalProperties: true
      example:
        user:
          _id: "5f7b1c2e8a1d4e0012c3b4a5"
          email: "admin@acme.example"
          fullName: "Acme Admin"
          phoneNumber: "+14165550100"
          organizationId: "64a1b2c3d4e5f60012345678"
          accessRole: "ADMIN"
        persona:
          position: "Leasing Manager"
          region: "Toronto"
          timezone: "America/Toronto"
    UserUpdateChatAvailabilityResponse:
      type: "object"
      description: "Returned after `PUT /api/user/chat-availability` toggles the user's availability flag."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        data:
          type: "object"
          properties:
            isAvailable:
              type: "boolean"
            lastStatusChange:
              type: "string"
              format: "date-time"
          required:
            - "isAvailable"
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        message: "Chat availability enabled"
        data:
          isAvailable: true
          lastStatusChange: "2026-05-20T15:04:01.135Z"
    UserUpdateNotificationPreferencesResponse:
      type: "object"
      description: "Returned after `PUT /api/user/notification-preferences`."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        data:
          "$ref": "#/components/schemas/UserNotificationPreferences"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        message: "Notification preferences updated successfully"
        data:
          aiResponses: true
          inboundInAutopilot: false
          automationTriggers: true
          emailSync: true
          escalations: true
          autopilotMonitor: false
          humanMonitor: true
          assignments: true
          calls: true
          campaigns: true
          other: true
    UserListSummary:
      type: "object"
      description: "Compact user payload returned by `POST /api/user/list` (bare array - no envelope)."
      properties:
        _id:
          type: "string"
        fullName:
          type: "string"
        email:
          type: "string"
          format: "email"
        phoneNumber:
          type: "string"
        designation:
          type: "string"
        accessRole:
          type: "string"
        organizationId:
          type: "string"
        departmentId:
          type: "string"
        loginDisabled:
          type: "boolean"
      required:
        - "_id"
        - "email"
        - "organizationId"
        - "accessRole"
      additionalProperties: true
      example:
        _id: "5f7b1c2e8a1d4e0012c3b4a6"
        fullName: "Sam Patel"
        email: "sam.patel@acme.example"
        phoneNumber: "+14165550100"
        accessRole: "AGENT"
        organizationId: "64a1b2c3d4e5f60012345678"
        loginDisabled: false
    UserListByTeamResponse:
      type: "array"
      description: "Bare array of `UserListSummary` - no top-level envelope."
      items:
        "$ref": "#/components/schemas/UserListSummary"
      example:
        -
          _id: "5f7b1c2e8a1d4e0012c3b4a6"
          fullName: "Sam Patel"
          email: "sam.patel@acme.example"
          accessRole: "AGENT"
          organizationId: "64a1b2c3d4e5f60012345678"
    UserAdminMutationResponse:
      type: "object"
      description: "Returned by admin `PUT /api/user/{id}`. `data` is the updated user, without the password or the legacy per-user phone fields (sinchPhoneNumber, voicePhoneNumbers, twilioPhoneNumber)."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        data:
          "$ref": "#/components/schemas/UserListSummary"
      required:
        - "success"
        - "message"
        - "data"
      additionalProperties: true
      example:
        success: true
        message: "User updated successfully"
        data:
          _id: "5f7b1c2e8a1d4e0012c3b4a6"
          fullName: "Sam Patel"
          email: "sam.patel.new@acme.example"
          accessRole: "AGENT"
          organizationId: "64a1b2c3d4e5f60012345678"
          loginDisabled: false
    UserSmsTemplateDocument:
      type: "object"
      description: "A reusable template (`type`: sms / campaign / script / automation). Returned by create/update template endpoints."
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        template:
          type: "string"
          description: "Template body with `{{firstName}}`-style placeholders."
        type:
          type: "string"
          enum:
            - "sms"
            - "email"
            - "campaign"
            - "script"
            - "automation"
        category:
          type: "string"
        organizationId:
          type: "string"
        userId:
          type: "string"
        createdBy:
          type: "string"
        updatedBy:
          type: "string"
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      required:
        - "_id"
        - "name"
        - "template"
        - "type"
      additionalProperties: true
      example:
        _id: "64d2f9c5e8a1d4e001a0b1c2"
        name: "Tour confirm - Maple Court"
        template: "Hi {{firstName}}! Confirming your tour for {{tour.date}} at {{tour.time}}."
        type: "sms"
        category: "tours"
        organizationId: "64a1b2c3d4e5f60012345678"
        userId: "64a1b2c3d4e5f60012345679"
        createdBy: "64a1b2c3d4e5f60012345679"
        createdAt: "2026-05-18T12:34:56.000Z"
        updatedAt: "2026-05-18T12:34:56.000Z"
    UserResolvedTemplateResponse:
      type: "object"
      description: "Template body with placeholders resolved against the supplied contact context. Returned by `POST /api/user/sms-templates/{templateId}`."
      properties:
        message:
          type: "string"
          description: "The fully-resolved message body."
        type:
          type: "string"
          enum:
            - "sms"
            - "email"
            - "automation"
        category:
          type: "string"
      required:
        - "message"
        - "type"
      additionalProperties: true
      example:
        message: "Hi Alex! Confirming your tour for Friday at 2:00pm."
        type: "sms"
        category: "tours"
    UserTemplateCategoryDocument:
      type: "object"
      description: "Template category record used to group SMS / campaign / script / automation templates. Returned by category create/update."
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        displayName:
          type: "string"
        description:
          type: "string"
        color:
          type: "string"
        sortOrder:
          type: "integer"
        isActive:
          type: "boolean"
        createdBy:
          type: "object"
          properties:
            fullName:
              type: "string"
            email:
              type: "string"
              format: "email"
          additionalProperties: true
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      required:
        - "_id"
        - "name"
      additionalProperties: true
      example:
        _id: "64d2f9c5e8a1d4e001a0b1c2"
        name: "tours"
        displayName: "Tours"
        description: "Tour-confirmation and follow-up templates."
        color: "#3B82F6"
        sortOrder: 0
        isActive: true
        createdBy:
          fullName: "Acme Admin"
          email: "admin@acme.example"
        createdAt: "2026-05-18T12:34:56.000Z"
        updatedAt: "2026-05-18T12:34:56.000Z"
    UserSnapshotErrorResponse:
      type: "object"
      properties:
        error:
          type: "string"
        message:
          type: "string"
        details:
          {}
      additionalProperties: true
      example:
        error: "Snapshot not found"
        message: "No snapshot exists with the given id"
    UserSnapshotMessageResponse:
      type: "object"
      properties:
        message:
          type: "string"
      additionalProperties: true
      example:
        message: "Snapshot deleted"
    UserSnapshotCounts:
      type: "object"
      properties:
        automations:
          type: "integer"
        prompts:
          type: "integer"
        templates:
          type: "integer"
      additionalProperties: true
      example:
        automations: 5
        prompts: 8
        templates: 12
    UserSnapshotPipelineStageRef:
      type: "object"
      properties:
        automationName:
          type: "string"
        field:
          type: "string"
        value:
          type: "string"
        refType:
          type: "string"
          enum:
            - "pipelineStage"
            - "agent"
        triggerLogicType:
          type: "string"
          nullable: true
        fieldLocation:
          type: "string"
          enum:
            - "actions"
            - "conditions"
      required:
        - "automationName"
        - "field"
        - "value"
        - "refType"
      additionalProperties: true
      example:
        automationName: "Move to Contacted on first reply"
        field: "targetStage"
        value: "Contacted"
        refType: "pipelineStage"
        fieldLocation: "actions"
    UserSnapshotSummary:
      type: "object"
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        description:
          type: "string"
          nullable: true
        sourceOrgId:
          type: "string"
          nullable: true
        sourceOrgName:
          type: "string"
          nullable: true
        sourceUserEmail:
          type: "string"
          nullable: true
        sourceUserName:
          type: "string"
          nullable: true
        counts:
          "$ref": "#/components/schemas/UserSnapshotCounts"
        createdBy:
          type: "string"
          nullable: true
        createdByName:
          type: "string"
          nullable: true
        createdByRole:
          type: "string"
          nullable: true
        isGlobal:
          type: "boolean"
        assignedOrgIds:
          type: "array"
          items:
            type: "string"
        createdAt:
          type: "string"
          format: "date-time"
          nullable: true
        updatedAt:
          type: "string"
          format: "date-time"
          nullable: true
      additionalProperties: true
      example:
        _id: "665f1a0c0e0a4b001a2c9f80"
        name: "Top performer baseline 2026-05"
        description: "Senior AE automations and prompts for Q2 rollout."
        sourceOrgId: "64ee9a8b1e7f2a0011223344"
        sourceOrgName: "Acme Corp"
        sourceUserEmail: "alex@acme.example"
        sourceUserName: "Alex Rep"
        counts:
          automations: 5
          prompts: 8
          templates: 12
        createdBy: "64ee9a8b1e7f2a001122339b"
        createdByName: "Pat Admin"
        createdByRole: "ADMIN"
        isGlobal: false
        assignedOrgIds:
          - "64ee9a8b1e7f2a0011223344"
        createdAt: "2026-05-15T09:00:00.000Z"
        updatedAt: "2026-05-15T09:00:00.000Z"
    UserSnapshotDetail:
      allOf:
        -
          "$ref": "#/components/schemas/UserSnapshotSummary"
        -
          type: "object"
          properties:
            automations:
              type: "array"
              items:
                type: "object"
                additionalProperties: true
            prompts:
              type: "array"
              items:
                type: "object"
                additionalProperties: true
            templates:
              type: "array"
              items:
                type: "object"
                additionalProperties: true
            sourcePipelineStageRefs:
              type: "array"
              items:
                "$ref": "#/components/schemas/UserSnapshotPipelineStageRef"
          additionalProperties: true
      example:
        _id: "665f1a0c0e0a4b001a2c9f80"
        name: "Top performer baseline 2026-05"
        counts:
          automations: 5
          prompts: 8
          templates: 12
        automations:
          -
            name: "Move to Contacted on first reply"
        prompts:
          -
            name: "Default warm-up prompt"
        templates:
          -
            name: "Intro - new lead"
            type: "sms"
        sourcePipelineStageRefs:
          -
            automationName: "Move to Contacted on first reply"
            field: "targetStage"
            value: "Contacted"
            refType: "pipelineStage"
            fieldLocation: "actions"
    UserSnapshotListResponse:
      type: "object"
      properties:
        snapshots:
          type: "array"
          items:
            "$ref": "#/components/schemas/UserSnapshotSummary"
      required:
        - "snapshots"
      additionalProperties: true
      example:
        snapshots:
          -
            _id: "665f1a0c0e0a4b001a2c9f80"
            name: "Top performer baseline 2026-05"
            sourceOrgName: "Acme Corp"
            sourceUserEmail: "alex@acme.example"
            counts:
              automations: 5
              prompts: 8
              templates: 12
            isGlobal: false
    UserSnapshotDetailResponse:
      type: "object"
      properties:
        snapshot:
          "$ref": "#/components/schemas/UserSnapshotDetail"
      required:
        - "snapshot"
      additionalProperties: true
      example:
        snapshot:
          _id: "665f1a0c0e0a4b001a2c9f80"
          name: "Top performer baseline 2026-05"
          counts:
            automations: 5
            prompts: 8
            templates: 12
    UserSnapshotCreateResponse:
      type: "object"
      properties:
        message:
          type: "string"
        snapshot:
          "$ref": "#/components/schemas/UserSnapshotSummary"
      required:
        - "snapshot"
      additionalProperties: true
      example:
        message: "Snapshot created"
        snapshot:
          _id: "665f1a0c0e0a4b001a2c9f80"
          name: "Top performer baseline 2026-05"
          counts:
            automations: 5
            prompts: 8
            templates: 12
          isGlobal: false
    CreateUserSnapshotRequest:
      type: "object"
      properties:
        name:
          type: "string"
          minLength: 1
          maxLength: 120
          description: "Snapshot display name shown in the snapshot picker."
        description:
          type: "string"
          maxLength: 500
          description: "Free-form notes describing what this snapshot captures."
        sourceOrgId:
          type: "string"
          description: "Organization containing the user being snapshotted."
        sourceUserId:
          type: "string"
          description: "User whose state is being captured."
      required:
        - "name"
        - "sourceOrgId"
        - "sourceUserId"
      additionalProperties: false
      example:
        name: "Top performer baseline 2026-05"
        description: "Senior AE automations and prompts for Q2 rollout."
        sourceOrgId: "64ee9a8b1e7f2a0011223344"
        sourceUserId: "64ee9a8b1e7f2a0011223399"
    AssignUserSnapshotRequest:
      type: "object"
      properties:
        assignedOrgIds:
          type: "array"
          items:
            type: "string"
          description: "Superadmin only. Replace the snapshot assigned organization list."
        isGlobal:
          type: "boolean"
          description: "When true, makes the snapshot visible to all organizations."
      additionalProperties: false
      example:
        assignedOrgIds:
          - "64ee9a8b1e7f2a0011223344"
          - "64ee9a8b1e7f2a0011223345"
        isGlobal: false
    AssignUserSnapshotResponse:
      type: "object"
      properties:
        message:
          type: "string"
        snapshot:
          type: "object"
          properties:
            _id:
              type: "string"
            assignedOrgIds:
              type: "array"
              items:
                type: "string"
            isGlobal:
              type: "boolean"
          additionalProperties: true
      additionalProperties: true
      example:
        message: "Snapshot access updated"
        snapshot:
          _id: "665f1a0c0e0a4b001a2c9f80"
          assignedOrgIds:
            - "64ee9a8b1e7f2a0011223344"
          isGlobal: false
    ApplyUserSnapshotNewUser:
      type: "object"
      properties:
        email:
          type: "string"
          format: "email"
        password:
          type: "string"
          minLength: 8
        fullName:
          type: "string"
        phoneNumber:
          type: "string"
          pattern: "^(\\+1|\\+91)\\d{10}$"
          description: "Optional E.164-style phone (must start with +1 or +91 followed by 10 digits)."
        designation:
          type: "string"
        accessRole:
          type: "string"
          enum:
            - "ADMIN"
            - "DEPARTMENT_HEAD"
            - "SALES_REP"
      required:
        - "email"
        - "password"
        - "fullName"
        - "accessRole"
      additionalProperties: false
      example:
        email: "casey@acme.example"
        password: "TempPass!2026"
        fullName: "Casey New"
        phoneNumber: "+14155550177"
        designation: "Account Executive"
        accessRole: "SALES_REP"
    ApplyUserSnapshotRequest:
      type: "object"
      properties:
        pipelineMapping:
          type: "object"
          additionalProperties:
            type: "object"
            additionalProperties:
              type: "string"
          description: "Per-automation map of source pipeline stage value → target stage value."
        sourceStatusesMapping:
          type: "object"
          additionalProperties:
            type: "array"
            items:
              type: "string"
          description: "Per-automation override for sourceStatuses array (mapped target stages)."
        agentMapping:
          type: "object"
          additionalProperties:
            type: "object"
            additionalProperties:
              type: "string"
          description: "Per-automation map of source agent name/id → target agent _id."
        selectedPromptNames:
          type: "array"
          items:
            type: "string"
          description: "Same-org apply only: subset of snapshot prompt names to clone."
        applyAutomations:
          type: "boolean"
          default: true
        applyPrompts:
          type: "boolean"
          default: true
        applyTemplates:
          type: "boolean"
          default: true
        newUser:
          "$ref": "#/components/schemas/ApplyUserSnapshotNewUser"
      required:
        - "newUser"
      additionalProperties: false
      example:
        pipelineMapping:
          "Move to Contacted on first reply":
            Contacted: "Reached Out"
        agentMapping:
          {}
        applyAutomations: true
        applyPrompts: true
        applyTemplates: true
        newUser:
          email: "casey@acme.example"
          password: "TempPass!2026"
          fullName: "Casey New"
          accessRole: "SALES_REP"
    ApplyUserSnapshotResponse:
      type: "object"
      properties:
        message:
          type: "string"
        result:
          type: "object"
          properties:
            userId:
              type: "string"
            userEmail:
              type: "string"
            cloned:
              type: "object"
              properties:
                automations:
                  type: "integer"
                prompts:
                  type: "integer"
                templates:
                  type: "integer"
              additionalProperties: true
            mapped:
              type: "object"
              properties:
                prompts:
                  type: "integer"
              additionalProperties: true
            skipped:
              type: "object"
              properties:
                automations:
                  type: "integer"
                templates:
                  type: "integer"
              additionalProperties: true
          additionalProperties: true
      additionalProperties: true
      example:
        message: "Snapshot applied"
        result:
          userId: "64ee9a8b1e7f2a001122339c"
          userEmail: "casey@acme.example"
          cloned:
            automations: 5
            prompts: 8
            templates: 12
          mapped:
            prompts: 0
          skipped:
            automations: 0
            templates: 0
    UserSnapshotApplyRefsResponse:
      type: "object"
      properties:
        stageRefs:
          type: "array"
          items:
            "$ref": "#/components/schemas/UserSnapshotPipelineStageRef"
        agentRefs:
          type: "array"
          items:
            "$ref": "#/components/schemas/UserSnapshotPipelineStageRef"
        targetPipelines:
          type: "array"
          items:
            type: "object"
            properties:
              _id:
                type: "string"
              name:
                type: "string"
              stages:
                type: "array"
                items:
                  type: "object"
                  properties:
                    name:
                      type: "string"
                    color:
                      type: "string"
                      nullable: true
                  additionalProperties: true
            additionalProperties: true
        targetAgents:
          type: "array"
          items:
            type: "object"
            properties:
              _id:
                type: "string"
              name:
                type: "string"
              description:
                type: "string"
                nullable: true
              updatedAt:
                type: "string"
                format: "date-time"
                nullable: true
            additionalProperties: true
      additionalProperties: true
      example:
        stageRefs:
          -
            automationName: "Move to Contacted on first reply"
            field: "targetStage"
            value: "Contacted"
            refType: "pipelineStage"
            fieldLocation: "actions"
        agentRefs:
          []
        targetPipelines:
          -
            _id: "64eea1110000000000000010"
            name: "Sales Funnel"
            stages:
              -
                name: "New Lead"
                color: "#3B82F6"
              -
                name: "Reached Out"
                color: "#F59E0B"
              -
                name: "Closed Won"
                color: "#10B981"
        targetAgents:
          -
            _id: "64eea1110000000000000060"
            name: "Default Agent"
            description: "Standard AI agent."
    UserSnapshotOrgUserItem:
      type: "object"
      properties:
        _id:
          type: "string"
        fullName:
          type: "string"
          nullable: true
        email:
          type: "string"
          nullable: true
        accessRole:
          type: "string"
          nullable: true
      additionalProperties: true
      example:
        _id: "64ee9a8b1e7f2a0011223399"
        fullName: "Alex Rep"
        email: "alex@acme.example"
        accessRole: "DEPARTMENT_HEAD"
    UserSnapshotOrgUsersResponse:
      type: "object"
      properties:
        users:
          type: "array"
          items:
            "$ref": "#/components/schemas/UserSnapshotOrgUserItem"
      required:
        - "users"
      additionalProperties: true
      example:
        users:
          -
            _id: "64ee9a8b1e7f2a0011223399"
            fullName: "Alex Rep"
            email: "alex@acme.example"
            accessRole: "DEPARTMENT_HEAD"
          -
            _id: "64ee9a8b1e7f2a001122339a"
            fullName: "Sam Closer"
            email: "sam@acme.example"
            accessRole: "SALES_REP"
    VaultCreateSecretRequest:
      type: "object"
      properties:
        name:
          type: "string"
        value:
          type: "string"
        workosOrganizationId:
          type: "string"
          description: "WorkOS organization ID (format: \"org_...\")"
      required:
        - "name"
        - "value"
      additionalProperties: true
      example:
        name: "TWILIO_AUTH_TOKEN"
        value: "sk_live_REDACTED"
        workosOrganizationId: "org_01HXYZ123ABCDEFG"
    VaultUpdateSecretRequest:
      type: "object"
      properties:
        value:
          type: "string"
        workosOrganizationId:
          type: "string"
          description: "WorkOS organization ID (format: \"org_...\")"
      required:
        - "value"
      additionalProperties: true
      example:
        value: "sk_live_REPLACED"
        workosOrganizationId: "org_01HXYZ123ABCDEFG"
    VaultDeleteSecretRequest:
      type: "object"
      properties:
        workosOrganizationId:
          type: "string"
          description: "WorkOS organization ID (format: \"org_...\")"
      additionalProperties: true
      example:
        workosOrganizationId: "org_01HXYZ123ABCDEFG"
    VaultUpsertSecretRequest:
      type: "object"
      properties:
        name:
          type: "string"
        value:
          type: "string"
        workosOrganizationId:
          type: "string"
          description: "WorkOS organization ID (format: \"org_...\")"
      required:
        - "name"
        - "value"
      additionalProperties: true
      example:
        name: "OPENAI_API_KEY"
        value: "sk-REDACTED"
        workosOrganizationId: "org_01HXYZ123ABCDEFG"
    VaultSecretSummary:
      type: "object"
      description: "Lightweight projection of a vault secret. Values are never included in list responses."
      properties:
        name:
          type: "string"
      required:
        - "name"
      additionalProperties: true
      example:
        name: "TWILIO_AUTH_TOKEN"
    VaultListResponse:
      type: "object"
      description: "Response from `GET /api/vault`."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/VaultSecretSummary"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          -
            name: "TWILIO_AUTH_TOKEN"
          -
            name: "OPENAI_API_KEY"
          -
            name: "STRIPE_SECRET"
    VaultMutationResponse:
      type: "object"
      description: "Response from create / update / upsert vault secret endpoints."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        data:
          "$ref": "#/components/schemas/VaultSecretSummary"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        message: "Secret created successfully"
        data:
          name: "TWILIO_AUTH_TOKEN"
    VaultDeleteResponse:
      type: "object"
      description: "Response from `DELETE /api/vault/{secretName}`."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
      required:
        - "success"
        - "message"
      additionalProperties: true
      example:
        success: true
        message: "Secret deleted successfully"
    VaultErrorResponse:
      type: "object"
      description: "Error envelope returned by vault endpoints."
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
        error:
          type: "string"
        documentation:
          type: "string"
          description: "Optional link to relevant documentation."
      required:
        - "success"
        - "message"
      additionalProperties: true
      example:
        success: false
        message: "WorkOS is not enabled"
        error: "WORKOS_DISABLED"
    VerticalCreateRequest:
      type: "object"
      properties:
        name:
          type: "string"
          description: "Vertical display name (e.g. `Property Management`, `Auto Sales`); used to scope onboarding defaults."
      required:
        - "name"
      additionalProperties: false
      example:
        name: "TetherAI"
    VerticalDto:
      type: "object"
      description: "The single vertical configured for this deployment. On the fallback path (no record exists yet) only `name` is populated."
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      required:
        - "name"
      additionalProperties: true
      example:
        _id: "65b1f0a2c3d4e5f6a7b8c9d0"
        name: "TetherAI"
        createdAt: "2026-01-12T09:15:00.000Z"
        updatedAt: "2026-04-04T17:42:00.000Z"
    VerticalGetResponse:
      type: "object"
      description: "Response from `GET /api/vertical`."
      properties:
        vertical:
          "$ref": "#/components/schemas/VerticalDto"
      required:
        - "vertical"
      additionalProperties: true
      example:
        vertical:
          _id: "65b1f0a2c3d4e5f6a7b8c9d0"
          name: "TetherAI"
          createdAt: "2026-01-12T09:15:00.000Z"
          updatedAt: "2026-04-04T17:42:00.000Z"
    VerticalMutationResponse:
      type: "object"
      description: "Response from `POST /api/vertical`."
      properties:
        message:
          type: "string"
        vertical:
          "$ref": "#/components/schemas/VerticalDto"
      required:
        - "vertical"
      additionalProperties: true
      example:
        message: "Vertical created"
        vertical:
          _id: "65b1f0a2c3d4e5f6a7b8c9d0"
          name: "TetherAI"
          createdAt: "2026-05-18T12:00:00.000Z"
          updatedAt: "2026-05-18T12:00:00.000Z"
    VerticalErrorResponse:
      type: "object"
      description: "Error envelope returned by vertical endpoints."
      properties:
        message:
          type: "string"
        error:
          type: "string"
      required:
        - "message"
      additionalProperties: true
      example:
        message: "Vertical already exists"
        error: "CONFLICT"
    CreateWebchatRequest:
      type: "object"
      properties:
        name:
          type: "string"
          description: "Display name for the webchat configuration in the admin UI."
        description:
          type: "string"
          description: "Free-form notes describing this widget configuration."
        starterMessage:
          type: "string"
          description: "Greeting bubble shown to the visitor before they send a message."
        backgroundColor:
          type: "string"
          description: "Hex color for the widget chat panel background."
        primaryColor:
          type: "string"
          description: "Hex color for the widget primary accent (header/buttons)."
        secondaryColor:
          type: "string"
          description: "Hex color for the widget secondary accent (outbound bubbles)."
        icon:
          type: "string"
          description: "Storage key or signed URL for the widget icon."
        headerTextColor:
          type: "string"
          description: "Hex color for text inside the widget header."
        statusText:
          type: "string"
          description: "Status line shown under the title (e.g. `We typically reply in minutes`)."
        statusTextColor:
          type: "string"
          description: "Hex color for the status text."
        timestampColor:
          type: "string"
          description: "Hex color for message timestamps."
        csatBackgroundColor:
          type: "string"
          description: "Hex color for the CSAT survey panel background."
        csatTextColor:
          type: "string"
          description: "Hex color for CSAT survey text."
        csatThankYouMessage:
          type: "string"
          description: "Message shown after the visitor submits a CSAT response."
        promptId:
          type: "string"
          description: "AI prompt `_id` driving the agent for this widget."
        allowedDomains:
          type: "array"
          items:
            type: "string"
          description: "Hostnames permitted to embed this widget. Empty array disables host check."
        pipelineId:
          type: "string"
          description: "Pipeline `_id` new webchat contacts are placed into."
        pipelineStage:
          type: "string"
          description: "Pipeline stage new webchat contacts are placed into."
        initialStage:
          type: "string"
          description: "Pipeline stage new webchat contacts enter."
        isAutopilot:
          type: "boolean"
          description: "When true, the AI replies autonomously without rep approval."
        isEnabled:
          type: "boolean"
          description: "When true, the widget is active and accepts new sessions."
      required:
        - "name"
        - "backgroundColor"
        - "primaryColor"
        - "secondaryColor"
        - "promptId"
        - "allowedDomains"
        - "initialStage"
      additionalProperties: true
      example:
        name: "Marketing site widget"
        description: "Bottom-right widget on the marketing site"
        starterMessage: "Hi! Looking for pricing?"
        backgroundColor: "#FFFFFF"
        primaryColor: "#1F2937"
        secondaryColor: "#3B82F6"
        headerTextColor: "#FFFFFF"
        statusText: "We typically reply within minutes"
        statusTextColor: "#6B7280"
        timestampColor: "#9CA3AF"
        csatBackgroundColor: "#F3F4F6"
        csatTextColor: "#111827"
        csatThankYouMessage: "Thanks for your feedback!"
        promptId: "65b2a1c3d4e5f6a7b8c9d0e1"
        allowedDomains:
          - "https://example.com"
        pipelineId: "66f0a0b0c0d0e0f0a0b0c0d0"
        pipelineStage: "67f0a0b0c0d0e0f0a0b0c0d0"
        initialStage: "new"
        isAutopilot: true
        isEnabled: true
    UpdateWebchatRequest:
      type: "object"
      properties:
        name:
          type: "string"
        description:
          type: "string"
        starterMessage:
          type: "string"
        backgroundColor:
          type: "string"
        primaryColor:
          type: "string"
        secondaryColor:
          type: "string"
        icon:
          type: "string"
          nullable: true
          description: "Set to empty string or null to remove icon"
        headerTextColor:
          type: "string"
        statusText:
          type: "string"
        statusTextColor:
          type: "string"
        timestampColor:
          type: "string"
        csatBackgroundColor:
          type: "string"
        csatTextColor:
          type: "string"
        csatThankYouMessage:
          type: "string"
        promptId:
          type: "string"
        allowedDomains:
          type: "array"
          items:
            type: "string"
        pipelineId:
          type: "string"
        pipelineStage:
          type: "string"
        initialStage:
          type: "string"
        isAutopilot:
          type: "boolean"
        isEnabled:
          type: "boolean"
      additionalProperties: true
      example:
        starterMessage: "Hi! Looking for help today?"
        isEnabled: true
        allowedDomains:
          - "https://example.com"
          - "https://help.example.com"
    WebchatDto:
      type: "object"
      description: "Stored webchat configuration document. The `icon` field, when present, is a freshly-signed URL pointing at the R2-hosted asset (the database stores the storage key)."
      properties:
        _id:
          type: "string"
        organizationId:
          type: "string"
        userId:
          type: "string"
          description: "Contact owner. Inbound contacts created from this webchat are routed to this user."
        createdBy:
          type: "string"
        name:
          type: "string"
        description:
          type: "string"
        starterMessage:
          type: "string"
        backgroundColor:
          type: "string"
        primaryColor:
          type: "string"
        secondaryColor:
          type: "string"
        icon:
          type: "string"
          nullable: true
          description: "Signed R2 URL for the icon image. `null` when no icon is configured."
        headerTextColor:
          type: "string"
        statusText:
          type: "string"
        statusTextColor:
          type: "string"
        timestampColor:
          type: "string"
        csatBackgroundColor:
          type: "string"
        csatTextColor:
          type: "string"
        csatThankYouMessage:
          type: "string"
        promptId:
          type: "string"
        allowedDomains:
          type: "array"
          items:
            type: "string"
        pipelineId:
          type: "string"
          nullable: true
        pipelineStage:
          type: "string"
          nullable: true
        initialStage:
          type: "string"
        isAutopilot:
          type: "boolean"
        isEnabled:
          type: "boolean"
        position:
          type: "string"
        offsetX:
          type: "number"
        offsetY:
          type: "number"
        zIndex:
          type: "number"
        initialState:
          type: "string"
        autoOpenDelay:
          type: "number"
        autoOpenOnScroll:
          type: "number"
        mobileBreakpoint:
          type: "number"
        allowedPages:
          type: "array"
          items:
            type: "string"
        headless:
          type: "boolean"
        pageContext:
          type: "boolean"
        pageContextPrompt:
          type: "string"
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      additionalProperties: true
      example:
        _id: "67d3a0b0c0d0e0f0a0b0c0d0"
        organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
        userId: "65b1f0a2c3d4e5f6a7b8c9d0"
        createdBy: "65b1f0a2c3d4e5f6a7b8c9d0"
        name: "Marketing site widget"
        description: "Bottom-right widget on the marketing site"
        starterMessage: "Hi! Looking for pricing?"
        backgroundColor: "#FFFFFF"
        primaryColor: "#1F2937"
        secondaryColor: "#3B82F6"
        icon: "https://r2.example.com/orgs/65a0.../webchat/icon.png?token=..."
        promptId: "65b2a1c3d4e5f6a7b8c9d0e1"
        allowedDomains:
          - "https://example.com"
        pipelineId: "66f0a0b0c0d0e0f0a0b0c0d0"
        initialStage: "new"
        isAutopilot: true
        isEnabled: true
        position: "bottom-right"
        offsetX: 24
        offsetY: 24
        zIndex: 9999
        createdAt: "2026-03-12T10:00:00.000Z"
        updatedAt: "2026-05-18T14:00:00.000Z"
    WebchatListResponse:
      type: "object"
      description: "Response from `GET /api/webchats`."
      properties:
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/WebchatDto"
          description: "Webchat configurations in the calling organization, newest-first."
      required:
        - "data"
      additionalProperties: true
      example:
        data:
          -
            _id: "67d3a0b0c0d0e0f0a0b0c0d0"
            name: "Marketing site widget"
            organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
            isEnabled: true
            primaryColor: "#1F2937"
    WebchatSingleResponse:
      type: "object"
      description: "Response from `GET /api/webchats/{id}`."
      properties:
        data:
          "$ref": "#/components/schemas/WebchatDto"
      required:
        - "data"
      additionalProperties: true
      example:
        data:
          _id: "67d3a0b0c0d0e0f0a0b0c0d0"
          name: "Marketing site widget"
          organizationId: "65a0e0e0e0e0e0e0e0e0e0e0"
          isEnabled: true
          primaryColor: "#1F2937"
    WebchatMutationResponse:
      type: "object"
      description: "Response from `POST /api/webchats` and `PUT /api/webchats/{id}`."
      properties:
        message:
          type: "string"
        data:
          "$ref": "#/components/schemas/WebchatDto"
      required:
        - "data"
      additionalProperties: true
      example:
        message: "Webchat configuration created"
        data:
          _id: "67d3a0b0c0d0e0f0a0b0c0d0"
          name: "Marketing site widget"
          isEnabled: true
    WebchatMessageResponse:
      type: "object"
      description: "Response from `DELETE /api/webchats/{id}`."
      properties:
        message:
          type: "string"
      required:
        - "message"
      additionalProperties: true
      example:
        message: "Webchat configuration deleted"
    WebchatErrorResponse:
      type: "object"
      description: "Error envelope returned by webchat endpoints."
      properties:
        error:
          type: "string"
        details:
          type: "string"
      required:
        - "error"
      additionalProperties: true
      example:
        error: "Webchat configuration not found"
        details: "NOT_FOUND"
    SmsWebhookRequest:
      type: "object"
      properties:
        id:
          type: "string"
          description: "Sinch-assigned inbound message id; echoed back in the ack for log correlation."
        from:
          type: "string"
          description: "Sender phone number (Sinch may omit the `+`; the handler normalizes to E.164)."
        to:
          type: "string"
          description: "Tether-provisioned recipient number that received the SMS."
        body:
          type: "string"
          description: "SMS text content as delivered by the carrier."
        operator_id:
          type: "string"
          description: "Sinch carrier/operator identifier for the originating network."
        received_at:
          type: "string"
          description: "ISO-8601 timestamp at which Sinch ingested the message."
        type:
          type: "string"
          description: "Sinch event type, e.g. `mo_text` for an inbound text message."
      required:
        - "id"
        - "from"
        - "to"
        - "body"
      additionalProperties: true
      example:
        id: "01K608PQBF3H41EQS64AH7CE11"
        from: "14165550100"
        to: "12362320246"
        body: "Hey, can you call me back?"
        operator_id: "310010"
        received_at: "2026-05-18T15:04:01.135Z"
        type: "mo_text"
    MmsWebhookRequest:
      type: "object"
      properties:
        id:
          type: "string"
          description: "Sinch-assigned MMS message id; echoed back in the ack for log correlation."
        origin:
          type: "string"
          description: "Sinch traffic direction marker - `MMS_MO` for inbound (mobile-originated) MMS."
        from:
          type: "string"
          description: "Sender phone number in E.164."
        to:
          type: "string"
          description: "Tether-provisioned recipient number that received the MMS."
        body:
          type: "string"
          description: "Optional text content sent alongside the media."
        media:
          description: "Attached media items. Each is downloaded from Sinch and re-uploaded to R2 before persistence."
          type: "array"
          items:
            type: "object"
            properties:
              url:
                type: "string"
                description: "Sinch-hosted media URL (short-lived; fetched server-side)."
              content_type:
                type: "string"
                description: "MIME type of the attachment, e.g. `image/jpeg`."
              size:
                type: "number"
                description: "Attachment size in bytes as reported by Sinch."
            additionalProperties: true
      additionalProperties: true
      example:
        id: "01K608PMMS001H41EQS64AH7CE"
        origin: "MMS_MO"
        from: "+14165550100"
        to: "+12362320246"
        body: "Photo of the issue"
        media:
          -
            url: "https://sinch-mms.s3.amazonaws.com/media/12345/image1.jpg"
            content_type: "image/jpeg"
            size: 184221
    SinchDeliveryReceiptRequest:
      type: "object"
      description: "A Sinch SMS delivery report. Batch reports (`delivery_report_sms`, summary or full) carry `statuses`; full reports list `recipients` on each status. Per-recipient reports (`recipient_delivery_report_sms`) are flat and carry `recipient`, `status` and `code` instead. Either kind may carry `client_reference`: when it is the id of a Message of this batch, and the report covers one message and one recipient, that Message is updated. Other fields are accepted as sent."
      properties:
        batch_id:
          type: "string"
          description: "Sinch batch identifier returned when the outbound SMS was submitted. A batch with several recipients has one Message per recipient, so the recipient or `client_reference` picks the Message."
        statuses:
          description: "One entry per delivery state in this batch; each contains the affected recipients and current status."
          type: "array"
          items:
            type: "object"
            properties:
              code:
                type: "number"
                description: "Numeric Sinch delivery status code."
              status:
                type: "string"
                description: "Status label, e.g. `Delivered`, `Failed`, `Expired`."
              count:
                type: "number"
                description: "Number of recipients in this status bucket."
              recipients:
                type: "array"
                items:
                  type: "string"
                description: "Recipient phone numbers this status applies to."
            additionalProperties: true
      additionalProperties: true
      example:
        batch_id: "01FC66621XXXXX119Z8PMV1QPQ"
        statuses:
          -
            code: 0
            status: "Delivered"
            count: 1
            recipients:
              - "14165550100"
    MmsDeliveryReceiptRequest:
      type: "object"
      properties:
        origin:
          type: "string"
          description: "Sinch traffic direction marker - `MMS_MT` for outbound (mobile-terminated) delivery receipts."
        code:
          type: "string"
          description: "Sinch MMS status code: `N101` sent, `N102` delivered, `N103` expired, `E101` sending failure, `E102` delivery failure."
        message_id:
          type: "string"
          description: "Sinch MMS id returned when the outbound message was submitted; used to locate the matching Message."
        status:
          type: "string"
          description: "Human-readable status label corresponding to `code` (e.g. `Delivered`, `Failed`)."
        to:
          type: "string"
          description: "Recipient phone number this receipt is for."
      additionalProperties: true
      example:
        origin: "MMS_MT"
        code: "N102"
        message_id: "01K608PMMS001H41EQS64AH7CE"
        status: "Delivered"
        to: "14165550100"
    WebchatWebhookRequest:
      type: "object"
      properties:
        webchatId:
          type: "string"
          description: "Per-conversation widget session identifier generated client-side."
        webchatConfigId:
          type: "string"
          description: "WebchatConfig `_id` that identifies which embedded widget sent the message."
        message:
          type: "string"
          description: "Visitor message body."
        clientMessageId:
          type: "string"
          minLength: 1
          maxLength: 128
          pattern: "^[A-Za-z0-9_-]{1,128}$"
          description: "Widget-generated idempotency key for this send, unique per webchat session. Retries reuse it; the API answers a replay with the already-stored row and `duplicate: true` instead of creating a second message. Optional for older widgets."
        deviceId:
          type: "string"
          description: "Stable per-browser device identifier used to deduplicate visitors across sessions."
        visitorName:
          type: "string"
          description: "Optional visitor display name captured by the widget pre-chat form."
        visitorEmail:
          type: "string"
          description: "Optional visitor email captured by the widget pre-chat form."
        visitorPhone:
          type: "string"
          description: "Optional visitor phone number captured by the widget pre-chat form."
        metadata:
          type: "object"
          additionalProperties: true
          description: "Free-form context the widget attaches (referrer, page URL, UTM params, etc.)."
      required:
        - "webchatId"
        - "webchatConfigId"
        - "message"
      additionalProperties: true
      example:
        webchatId: "wc_8f3d1b9c-2e7a-4f0b-9a4d-2c1e6e2f8c01"
        webchatConfigId: "5f7b1c2e8a1d4e0012c3b4a5"
        message: "Hi, do you ship to Canada?"
        deviceId: "dev_4f9a-8c1b-2e3d-7a01"
        visitorName: "Alex Morgan"
        visitorEmail: "alex@example.com"
        visitorPhone: "+14165550100"
        metadata:
          page: "/pricing"
          referrer: "https://google.com"
    TwilioInboundSmsRequest:
      type: "object"
      properties:
        From:
          type: "string"
          description: "Sender phone number in E.164 (e.g. `+14165550100`)."
        To:
          type: "string"
          description: "Tether-provisioned Twilio number that received the message."
        Body:
          type: "string"
          description: "SMS/MMS text content."
        MessageSid:
          type: "string"
          description: "Twilio-assigned message identifier (`SM…` for SMS, `MM…` for MMS)."
        NumMedia:
          type: "string"
          description: "Count of attached media items as a string; `0` for plain SMS."
        MediaUrl0:
          type: "string"
          description: "URL of the first media attachment (Twilio CDN); additional `MediaUrlN` fields appear when NumMedia > 1."
        MediaContentType0:
          type: "string"
          description: "MIME type of the first media attachment, e.g. `image/jpeg`."
      additionalProperties: true
      example:
        From: "+14165550100"
        To: "+12362320246"
        Body: "Hey, can you call me back?"
        MessageSid: "SM5f7b1c2e8a1d4e0012c3b4a5"
        NumMedia: "0"
    TwilioSmsStatusRequest:
      type: "object"
      properties:
        MessageSid:
          type: "string"
          description: "Twilio-assigned message identifier whose status is being reported."
        MessageStatus:
          type: "string"
          description: "Delivery state: `queued`, `sent`, `delivered`, `failed`, `undelivered`."
        To:
          type: "string"
          description: "Recipient phone number for the outbound message."
        From:
          type: "string"
          description: "Tether-provisioned Twilio number the message was sent from."
        ErrorCode:
          type: "string"
          description: "Twilio error code when delivery failed (e.g. `30003`)."
        ErrorMessage:
          type: "string"
          description: "Human-readable error description paired with `ErrorCode`."
      additionalProperties: true
      example:
        MessageSid: "SM5f7b1c2e8a1d4e0012c3b4a5"
        MessageStatus: "delivered"
        To: "+14165550100"
        From: "+12362320246"
    SinchCallWebhookRequest:
      type: "object"
      properties:
        event:
          type: "string"
          description: "Voice event discriminator: `ice` (incoming call), `ace` (answered), `dice` (disconnect)."
        callId:
          type: "string"
          description: "Sinch-assigned call identifier used to correlate ICE/ACE/DiCE events for one call."
        callResourceUrl:
          type: "string"
          description: "Sinch REST URL for the call resource - used for follow-up API operations (e.g. hangup)."
      additionalProperties: true
      example:
        event: "ice"
        callId: "a8d3c4e0-9b2f-4e1a-b3c4-5f6a7b8c9d01"
        callResourceUrl: "https://calling.api.sinch.com/v1/calls/a8d3c4e0-9b2f-4e1a-b3c4-5f6a7b8c9d01"
    TwilioCallWebhookRequest:
      type: "object"
      properties:
        CallSid:
          type: "string"
          description: "Twilio-assigned call identifier (`CA…`)."
        CallStatus:
          type: "string"
          description: "Twilio call state, e.g. `ringing`, `in-progress`, `completed`, `busy`, `no-answer`, `failed`."
        From:
          type: "string"
          description: "Calling party phone number in E.164."
        To:
          type: "string"
          description: "Called party phone number in E.164."
        Direction:
          type: "string"
          description: "Call direction reported by Twilio: `inbound`, `outbound-api`, `outbound-dial`."
      additionalProperties: true
      example:
        CallSid: "CA5f7b1c2e8a1d4e0012c3b4a5"
        CallStatus: "completed"
        From: "+14165550100"
        To: "+12362320246"
        Direction: "inbound"
    TwilioInboundCallRequest:
      type: "object"
      properties:
        To:
          type: "string"
          description: "Tether-provisioned Twilio number that was dialed; used to resolve the owning org/user."
        From:
          type: "string"
          description: "Caller phone number in E.164."
        CallSid:
          type: "string"
          description: "Twilio-assigned call identifier (`CA…`) for the inbound leg."
        CallStatus:
          type: "string"
          description: "Twilio call state at webhook time, typically `ringing` for the inbound trigger."
      additionalProperties: true
      example:
        To: "+12362320246"
        From: "+14165550100"
        CallSid: "CA5f7b1c2e8a1d4e0012c3b4a5"
        CallStatus: "ringing"
    TwilioOutboundCallRequest:
      type: "object"
      properties:
        To:
          type: "string"
          description: "PSTN destination the agent is dialing in E.164."
        From:
          type: "string"
          description: "Tether-provisioned Twilio number to use as caller ID."
        CallSid:
          type: "string"
          description: "Twilio-assigned call identifier (`CA…`) for the browser leg."
      additionalProperties: true
      example:
        To: "+14165550100"
        From: "+12362320246"
        CallSid: "CA5f7b1c2e8a1d4e0012c3b4a5"
    TwilioCallStatusRequest:
      type: "object"
      properties:
        CallSid:
          type: "string"
          description: "Twilio-assigned call identifier (`CA…`) whose status is being reported."
        CallStatus:
          type: "string"
          description: "Final or transitional state: `queued`, `ringing`, `in-progress`, `completed`, `busy`, `no-answer`, `failed`."
        CallDuration:
          type: "string"
          description: "Total call duration in seconds (as a string), populated when the call ends."
        Duration:
          type: "string"
          description: "Per-leg duration in seconds as Twilio reports it; usually mirrors `CallDuration` for single-leg dials."
        From:
          type: "string"
          description: "Calling party phone number in E.164."
        To:
          type: "string"
          description: "Called party phone number in E.164."
      additionalProperties: true
      example:
        CallSid: "CA5f7b1c2e8a1d4e0012c3b4a5"
        CallStatus: "completed"
        CallDuration: "42"
        Duration: "1"
        From: "+14165550100"
        To: "+12362320246"
    TwilioRecordingStatusRequest:
      type: "object"
      properties:
        CallSid:
          type: "string"
          description: "Twilio call identifier (`CA…`) the recording belongs to."
        RecordingSid:
          type: "string"
          description: "Twilio-assigned recording identifier (`RE…`)."
        RecordingUrl:
          type: "string"
          description: "Twilio-hosted recording URL; downloaded server-side and re-uploaded to R2."
        RecordingStatus:
          type: "string"
          description: "Recording lifecycle state, typically `completed` once the audio is ready."
        RecordingDuration:
          type: "string"
          description: "Recording length in seconds (as a string)."
      additionalProperties: true
      example:
        CallSid: "CA5f7b1c2e8a1d4e0012c3b4a5"
        RecordingSid: "RE9c2d4e0b1f3a4e5b6c7d8e9f0"
        RecordingUrl: "https://api.twilio.com/2010-04-01/Accounts/AC.../Recordings/RE9c2d4e0b1f3a4e5b6c7d8e9f0"
        RecordingStatus: "completed"
        RecordingDuration: "42"
    TwilioAmdStatusRequest:
      type: "object"
      properties:
        CallSid:
          type: "string"
          description: "Twilio call identifier (`CA…`) AMD classified."
        AnsweredBy:
          type: "string"
          description: "AMD classification: `human`, `machine_start`, `machine_end_beep`, `machine_end_silence`, `machine_end_other`, `fax`, or `unknown`."
        MachineDetectionDuration:
          type: "string"
          description: "Milliseconds Twilio spent classifying the answer (as a string)."
      additionalProperties: true
      example:
        CallSid: "CA5f7b1c2e8a1d4e0012c3b4a5"
        AnsweredBy: "machine_start"
        MachineDetectionDuration: "2400"
    OutreachWebhookRequest:
      type: "object"
      description: "Arbitrary outreach payload forwarded to outreach trigger handler"
      additionalProperties: true
      example:
        apiKey: "tk_live_5f7b1c2e8a1d4e0012c3b4a5"
        contact:
          firstName: "Alex"
          lastName: "Morgan"
          phoneNumber: "+14165550100"
          email: "alex@example.com"
        automationId: "5f7b1c2e8a1d4e0012c3b4a5"
    TextGridInboundSmsRequest:
      type: "object"
      description: "TextGrid inbound SMS/MMS payload. Shape matches Twilio - additional MediaUrlN / MediaContentTypeN fields appear when NumMedia > 0."
      properties:
        AccountSid:
          type: "string"
          description: "TextGrid account identifier that owns the receiving number."
        MessageSid:
          type: "string"
          description: "TextGrid-assigned message identifier."
        From:
          type: "string"
          description: "Sender phone number in E.164."
        To:
          type: "string"
          description: "Tether-provisioned TextGrid number that received the message."
        Body:
          type: "string"
          description: "SMS/MMS text content."
        NumMedia:
          type: "string"
          description: "Count of attached media items as a string; `0` for plain SMS."
        MediaUrl0:
          type: "string"
          description: "URL of the first media attachment; additional `MediaUrlN` fields appear when NumMedia > 1."
        MediaContentType0:
          type: "string"
          description: "MIME type of the first media attachment, e.g. `image/jpeg`."
      additionalProperties: true
      example:
        AccountSid: "AC8a1d4e0012c3b4a55f7b1c2e8a"
        MessageSid: "TG5f7b1c2e8a1d4e0012c3b4a5"
        From: "+14165550100"
        To: "+12362320246"
        Body: "Picking up at 5pm, thanks!"
        NumMedia: "0"
    TextGridSmsStatusRequest:
      type: "object"
      description: "TextGrid delivery status callback. Only `delivered` and `undelivered` are sent."
      properties:
        MessageSid:
          type: "string"
          description: "TextGrid message identifier whose status is being reported."
        SmsSid:
          type: "string"
          description: "Twilio-compatible alias of `MessageSid`; usually identical."
        MessageStatus:
          type: "string"
          description: "Delivery state: `delivered` or `undelivered`."
        From:
          type: "string"
          description: "Tether-provisioned TextGrid number the message was sent from."
        To:
          type: "string"
          description: "Recipient phone number for the outbound message."
        ErrorCode:
          type: "string"
          description: "TextGrid error code when delivery failed."
        ErrorMessage:
          type: "string"
          description: "Human-readable error description paired with `ErrorCode`."
      additionalProperties: true
      example:
        MessageSid: "TG5f7b1c2e8a1d4e0012c3b4a5"
        SmsSid: "TG5f7b1c2e8a1d4e0012c3b4a5"
        MessageStatus: "delivered"
        From: "+12362320246"
        To: "+14165550100"
    OutlookWebhookRequest:
      type: "object"
      description: "Microsoft Graph change notification batch."
      properties:
        value:
          description: "Array of change notifications Microsoft Graph batches into one request."
          type: "array"
          items:
            type: "object"
            properties:
              subscriptionId:
                type: "string"
                description: "Graph subscription this notification originates from; maps to the Tether mailbox connection."
              subscriptionExpirationDateTime:
                type: "string"
                description: "ISO-8601 timestamp when the Graph subscription expires - used to trigger renewal."
              changeType:
                type: "string"
                description: "Type of change, e.g. `created`, `updated`, `deleted`."
              resource:
                type: "string"
                description: "Graph resource path for the changed item (e.g. `Users/{id}/Messages/{id}`)."
              resourceData:
                description: "Lightweight pointer to the changed entity (id + @odata.type); the full message is fetched separately via Graph."
                type: "object"
                additionalProperties: true
              clientState:
                type: "string"
                description: "Opaque token supplied at subscription time and echoed back to verify the notification is genuine."
              tenantId:
                type: "string"
                description: "Azure AD tenant id the mailbox belongs to."
            additionalProperties: true
      additionalProperties: true
      example:
        value:
          -
            subscriptionId: "7f4b2c1d-9e0a-4b3c-8d5e-6f7a8b9c0d1e"
            subscriptionExpirationDateTime: "2026-05-20T15:04:01.135Z"
            changeType: "created"
            resource: "Users/ops@acme.example/Messages/AAMkAGI2T..=="
            resourceData:
              "@odata.type": "#Microsoft.Graph.Message"
              "@odata.id": "Users/ops@acme.example/Messages/AAMkAGI2T..=="
              id: "AAMkAGI2T..=="
            clientState: "tether-outlook-secret"
            tenantId: "5f7b1c2e-8a1d-4e00-12c3-b4a55f7b1c2e"
    ElevenLabsPostCallWebhookRequest:
      type: "object"
      description: "ElevenLabs post-call webhook payload. The `type` field discriminates between `post_call_transcription`, `post_call_audio`, and `call_initiation_failure`. The bulk of the data lives under `data` (or sometimes top-level for older payload shapes)."
      properties:
        type:
          type: "string"
          enum:
            - "post_call_transcription"
            - "post_call_audio"
            - "call_initiation_failure"
          description: "Event discriminator selecting how the handler processes `data`: transcript+summary, recording upload, or missed-call record."
        event_timestamp:
          type: "number"
          description: "Unix epoch seconds when ElevenLabs emitted the event."
        data:
          description: "Event payload; field set depends on `type`. Older payloads sometimes inline these fields at top level."
          type: "object"
          properties:
            conversation_id:
              type: "string"
            agent_id:
              type: "string"
            call_duration_secs:
              type: "number"
            transcript:
              description: "ElevenLabs transcript array - opaque, forwarded as-is."
            analysis:
              type: "object"
              additionalProperties: true
              properties:
                transcript_summary:
                  type: "string"
            metadata:
              type: "object"
              additionalProperties: true
              properties:
                caller_id:
                  type: "string"
                called_id:
                  type: "string"
                phone_call:
                  type: "object"
                  additionalProperties: true
                  properties:
                    direction:
                      type: "string"
                      enum:
                        - "inbound"
                        - "outbound"
                    external_number:
                      type: "string"
                    agent_number:
                      type: "string"
            full_audio:
              type: "string"
              description: "Base64-encoded MP3 - only present on post_call_audio events."
            reason:
              type: "string"
            error:
              type: "string"
          additionalProperties: true
      required:
        - "type"
      additionalProperties: true
      example:
        type: "post_call_transcription"
        event_timestamp: 1747580641
        data:
          conversation_id: "conv_8f3d1b9c2e7a4f0b9a4d2c1e6e2f8c01"
          agent_id: "agent_a8d3c4e09b2f4e1ab3c45f6a7b8c9d01"
          call_duration_secs: 42
          transcript:
            -
              role: "agent"
              message: "Thanks for calling Acme Corp, how can I help?"
            -
              role: "user"
              message: "I need to update my address."
          analysis:
            transcript_summary: "Caller asked to update their shipping address."
          metadata:
            caller_id: "+14165550100"
            called_id: "+12362320246"
            phone_call:
              direction: "inbound"
              external_number: "+14165550100"
              agent_number: "+12362320246"
    ElevenLabsPostCallWebhookResponse:
      type: "object"
      properties:
        received:
          type: "boolean"
        callId:
          type: "string"
        deduplicated:
          type: "boolean"
        skipped:
          type: "boolean"
        reason:
          type: "string"
        error:
          type: "string"
      additionalProperties: true
      example:
        received: true
        callId: "5f7b1c2e8a1d4e0012c3b4a5"
    ElevenLabsPersonalizationRequest:
      type: "object"
      properties:
        conversation_id:
          type: "string"
        caller_id:
          type: "string"
          description: "External caller phone number"
        called_id:
          type: "string"
          description: "Tether AI-enabled number that was called"
        agent_id:
          type: "string"
      required:
        - "conversation_id"
      additionalProperties: true
      example:
        conversation_id: "conv_8f3d1b9c2e7a4f0b9a4d2c1e6e2f8c01"
        caller_id: "+14165550100"
        called_id: "+12362320246"
        agent_id: "agent_a8d3c4e09b2f4e1ab3c45f6a7b8c9d01"
    ElevenLabsPersonalizationResponse:
      type: "object"
      description: "Dynamic variables returned to ElevenLabs for prompt injection. Empty `{}` is returned when no caller match is found so the call still proceeds."
      properties:
        caller_name:
          type: "string"
        caller_number:
          type: "string"
        org_name:
          type: "string"
      additionalProperties: true
      example:
        caller_name: "Alex Morgan"
        caller_number: "+14165550100"
        org_name: "Acme Corp"
    ElevenLabsToolCallRequest:
      type: "object"
      description: "Common shape ElevenLabs uses to invoke a server tool mid-call. `called_id`/`called_number` lets the handler resolve the user inside the calling org."
      properties:
        conversation_id:
          type: "string"
          description: "ElevenLabs conversation id; used to correlate with the cached personalization context."
        agent_id:
          type: "string"
          description: "ElevenLabs agent id that is invoking the tool."
        caller_id:
          type: "string"
          description: "External caller phone number."
        called_id:
          type: "string"
          description: "Tether AI-enabled number that was called; used to resolve owning org/user."
        called_number:
          type: "string"
          description: "Alternate key for `called_id` (older ElevenLabs payloads use this name)."
      additionalProperties: true
      example:
        conversation_id: "conv_8f3d1b9c2e7a4f0b9a4d2c1e6e2f8c01"
        agent_id: "agent_a8d3c4e09b2f4e1ab3c45f6a7b8c9d01"
        caller_id: "+14165550100"
        called_id: "+12362320246"
        called_number: "+12362320246"
    ElevenLabsCheckBusinessHoursResponse:
      type: "object"
      properties:
        is_open:
          type: "boolean"
        current_time:
          type: "string"
          description: "Formatted as `<weekday> <hour>:<minute>` in the org timezone"
        timezone:
          type: "string"
        organization_name:
          type: "string"
      required:
        - "is_open"
      additionalProperties: true
      example:
        is_open: true
        current_time: "Monday 14:32"
        timezone: "America/Toronto"
        organization_name: "Acme Corp"
    ElevenLabsGetContactRequest:
      type: "object"
      description: "Tool args for contact lookup. Either `phone_number` or `caller_id` should be set."
      properties:
        phone_number:
          type: "string"
          description: "Phone number to look up (E.164 preferred); takes precedence over `caller_id`."
        caller_id:
          type: "string"
          description: "Fallback caller phone number when `phone_number` is not supplied by the agent."
        called_id:
          type: "string"
          description: "Tether AI-enabled number that was called; used to scope the lookup to the right org."
        conversation_id:
          type: "string"
          description: "ElevenLabs conversation id used to correlate with cached call context."
      additionalProperties: true
      example:
        phone_number: "+14165550100"
        caller_id: "+14165550100"
        called_id: "+12362320246"
        conversation_id: "conv_8f3d1b9c2e7a4f0b9a4d2c1e6e2f8c01"
    ElevenLabsGetContactResponse:
      type: "object"
      properties:
        found:
          type: "boolean"
        contact_name:
          type: "string"
        phone_number:
          type: "string"
        email:
          type: "string"
        status:
          type: "string"
        message:
          type: "string"
      required:
        - "found"
      additionalProperties: true
      example:
        found: true
        contact_name: "Alex Morgan"
        phone_number: "+14165550100"
        email: "alex@example.com"
        status: "active"
    ElevenLabsCheckAvailabilityResponse:
      type: "object"
      properties:
        agents_available:
          type: "boolean"
        available_count:
          type: "integer"
        online_count:
          type: "integer"
      required:
        - "agents_available"
      additionalProperties: true
      example:
        agents_available: true
        available_count: 2
        online_count: 4
    ElevenLabsTransferRequest:
      type: "object"
      properties:
        reason:
          type: "string"
          description: "Free-form transfer reason supplied by the AI agent"
        conversation_id:
          type: "string"
        called_id:
          type: "string"
      additionalProperties: true
      example:
        reason: "Caller asked for a human supervisor"
        conversation_id: "conv_8f3d1b9c2e7a4f0b9a4d2c1e6e2f8c01"
        called_id: "+12362320246"
    ElevenLabsTransferResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        message:
          type: "string"
      required:
        - "success"
      additionalProperties: true
      example:
        success: false
        message: "Transfer is not yet implemented - please ask the caller to hold while a human agent joins."
    ElevenLabsUpdateContactRequest:
      type: "object"
      description: "ElevenLabs update-contact tool args. `phone_number` identifies the contact; at least one of `first_name`/`last_name`/`email` must be set. Phone numbers themselves cannot be changed via this endpoint."
      properties:
        phone_number:
          type: "string"
          description: "Contact phone number (E.164 preferred)."
        first_name:
          type: "string"
        last_name:
          type: "string"
        email:
          type: "string"
          format: "email"
          description: "Appended to the contact's email[] (history preserved); becomes primary if none is set."
        called_id:
          type: "string"
          description: "Twilio/Sinch called number - used by ElevenLabs to route auth context."
        called_number:
          type: "string"
          description: "Alternative key for called_id."
      required:
        - "phone_number"
      additionalProperties: true
      example:
        phone_number: "+14165550100"
        first_name: "Alex"
        last_name: "Morgan"
        email: "alex.morgan@example.com"
        called_id: "+12362320246"
    ElevenLabsUpdateContactResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        message:
          type: "string"
        updated_fields:
          type: "array"
          items:
            type: "string"
          description: "Mongo field paths that were $set (e.g. `firstName`, `lastName`, `email`)."
        error:
          type: "string"
          description: "Present when `success` is false."
      required:
        - "success"
      additionalProperties: true
      example:
        success: true
        message: "Contact updated"
        updated_fields:
          - "firstName"
          - "lastName"
          - "email"
    ElevenLabsCreateNoteRequest:
      type: "object"
      description: "ElevenLabs create-note tool args. `phone_number` identifies the contact within the org."
      properties:
        phone_number:
          type: "string"
        note:
          type: "string"
          description: "Free-form note text. Trimmed and stored as `type: ai_summary`."
        called_id:
          type: "string"
        called_number:
          type: "string"
      required:
        - "phone_number"
        - "note"
      additionalProperties: true
      example:
        phone_number: "+14165550100"
        note: "Caller asked about availability for the corner unit at Maple Court; promised a callback by Friday."
        called_id: "+12362320246"
    ElevenLabsCreateNoteResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        note_id:
          type: "string"
        error:
          type: "string"
      required:
        - "success"
      additionalProperties: true
      example:
        success: true
        note_id: "64d2f9c5e8a1d4e001a0b1c2"
    ElevenLabsSendSmsRequest:
      type: "object"
      description: "ElevenLabs send-sms tool args. `phone_number` identifies the contact within the org."
      properties:
        phone_number:
          type: "string"
        message:
          type: "string"
          description: "SMS body. Trimmed; the SMS is marked AI-authored and `skipAutomation`."
        called_id:
          type: "string"
        called_number:
          type: "string"
        conversation_id:
          type: "string"
          description: "The live ElevenLabs conversation id, injected by ElevenLabs (system__conversation_id). Picks the line the SMS is sent from."
        agent_id:
          type: "string"
          description: "The ElevenLabs agent id, injected by ElevenLabs (system__agent_id). Picks the agent line when the call cannot be found."
      required:
        - "phone_number"
        - "message"
      additionalProperties: true
      example:
        phone_number: "+14165550100"
        message: "Hi Alex - here's the application link we just talked about: https://app.tetherai.ca/a/MZ4K. Let me know if you have any trouble."
        called_id: "+12362320246"
    ElevenLabsSendSmsResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        message:
          type: "string"
        error:
          type: "string"
      required:
        - "success"
      additionalProperties: true
      example:
        success: true
        message: "SMS sent"
    WorkflowWebhookIngressRequest:
      type: "object"
      description: "`webhookId` is required and must match a `WebhookTrigger.data.webhookId` on at least one workflow in the caller's org. Every other property is forwarded verbatim as the trigger node's `payload` output."
      properties:
        webhookId:
          type: "string"
          description: "Identifier configured on a workflow `WebhookTrigger` node; the caller's org is scanned for matching triggers to enqueue."
      required:
        - "webhookId"
      additionalProperties: true
      example:
        webhookId: "wh_64d2f9c5e8a1d4e001a0b1c3"
        source: "zillow"
        lead:
          name: "Alex Nguyen"
          email: "alex.nguyen@example.com"
          phone: "+14155551234"
    WorkflowWebhookIngressResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        data:
          type: "object"
          properties:
            webhookId:
              type: "string"
            matchedCount:
              type: "integer"
              description: "Number of workflows enqueued. 0 = no trigger matched."
          required:
            - "webhookId"
            - "matchedCount"
          additionalProperties: true
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        message: "Webhook accepted"
        data:
          webhookId: "wh_64d2f9c5e8a1d4e001a0b1c3"
          matchedCount: 2
    InboxDropEmailData:
      type: "object"
      description: "Parsed inbound email payload produced by a provider adapter (e.g. SendGrid Inbound Parse)."
      properties:
        from:
          type: "string"
        to:
          description: "Recipient(s). Single string is normalized to a one-element array server-side."
          oneOf:
            -
              type: "string"
            -
              type: "array"
              items:
                type: "string"
        subject:
          type: "string"
        body:
          type: "string"
          description: "Plain text body."
        bodyHtml:
          type: "string"
        headers:
          type: "object"
          additionalProperties: true
        attachments:
          type: "array"
          items:
            type: "object"
            properties:
              filename:
                type: "string"
              url:
                type: "string"
                format: "uri"
            required:
              - "filename"
            additionalProperties: true
      required:
        - "from"
        - "to"
        - "subject"
      additionalProperties: true
      example:
        from: "alex.nguyen@example.com"
        to: "inbound+org-64a1b@inbound.tetherai.ca"
        subject: "Maple Court availability"
        body: "Hi - could you confirm the corner unit is still listed for next month?"
        bodyHtml: "<p>Hi - could you confirm the corner unit is still listed for next month?</p>"
        headers:
          Message-ID: "<abc123@mail.example.com>"
        attachments:
          []
    InboxDropRequest:
      type: "object"
      description: "Internal-service request body sent by inbound-email adapters (SendGrid, etc.) to fan out to matching workflows."
      properties:
        organizationId:
          type: "string"
        userId:
          type: "string"
          description: "Optional. Falls back to the workflow's owning user when missing."
        emailData:
          "$ref": "#/components/schemas/InboxDropEmailData"
        metadata:
          type: "object"
          properties:
            receivedAt:
              type: "string"
              format: "date-time"
            source:
              type: "string"
              description: "Defaults to \"inbox_drop\" if omitted."
            leadManagementId:
              type: "string"
          additionalProperties: true
      required:
        - "organizationId"
        - "emailData"
      additionalProperties: true
      example:
        organizationId: "64a1b2c3d4e5f60012345678"
        userId: "64a1b2c3d4e5f60012345679"
        emailData:
          from: "alex.nguyen@example.com"
          to:
            - "inbound+org-64a1b@inbound.tetherai.ca"
          subject: "Maple Court availability"
          body: "Hi - could you confirm the corner unit is still listed?"
        metadata:
          receivedAt: "2026-05-20T15:04:01.135Z"
          source: "sendgrid_inbound"
    InboxDropResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        matchedCount:
          type: "integer"
          description: "Number of workflows whose InboxDropTrigger matched this email. 0 = no match; the adapter may fall back to a non-workflow handler."
      required:
        - "success"
        - "matchedCount"
      additionalProperties: true
      example:
        success: true
        matchedCount: 1
    InboxDropValidationErrorResponse:
      type: "object"
      description: "Validation error envelope returned when `emailData` fails the from/to/subject checks."
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
        errors:
          type: "array"
          items:
            type: "string"
          description: "Per-field error strings (only populated when individual email fields failed validation)."
      required:
        - "success"
        - "message"
      additionalProperties: true
      example:
        success: false
        message: "Invalid email data"
        errors:
          - "emailData.from is required"
          - "emailData.subject is required"
    WebhookAssetErrorResponse:
      type: "object"
      description: "Error envelope returned by the static-asset webhook routes (`/api/webhook/webchat-script` and `/api/webhook/notification-sound`). The 200 path serves binary/script content; only failure responses are JSON."
      properties:
        error:
          type: "string"
        message:
          type: "string"
      additionalProperties: true
      example:
        error: "Webchat configuration not found"
    WebhookErrorResponse:
      type: "object"
      description: "Error envelope used across provider webhook routes. Most failures only carry `error`; a few (ElevenLabs tool errors, ingress validation) add `success:false`, `message`, or a `code`. Many of these endpoints respond 200 with `success:false` for recoverable cases (especially the ElevenLabs server tools) - only hard failures use 4xx/5xx."
      properties:
        error:
          type: "string"
        message:
          type: "string"
        success:
          type: "boolean"
          enum:
            - false
        code:
          type: "string"
        details:
          description: "Optional diagnostic detail (stack snippet, validation issues, etc.)."
      additionalProperties: true
      example:
        error: "Webhook processing failed"
    SmsWebhookAckResponse:
      type: "object"
      description: "Immediate ack returned to Sinch for an inbound SMS. Tether persists + routes the message asynchronously."
      properties:
        message:
          type: "string"
        messageId:
          type: "string"
          description: "Sinch message id from the inbound payload, echoed back for log correlation."
      required:
        - "message"
        - "messageId"
      additionalProperties: true
      example:
        message: "Webhook received"
        messageId: "01K608PQBF3H41EQS64AH7CE11"
    MmsWebhookAckResponse:
      type: "object"
      description: "Immediate ack returned to Sinch for an inbound MMS."
      properties:
        message:
          type: "string"
        messageId:
          type: "string"
      required:
        - "message"
        - "messageId"
      additionalProperties: true
      example:
        message: "MMS MO webhook received"
        messageId: "01K608PMMS001H41EQS64AH7CE"
    SinchDeliveryReceiptAckResponse:
      type: "object"
      description: "Ack returned after a Sinch SMS delivery receipt is consumed."
      properties:
        message:
          type: "string"
        batch_id:
          type: "string"
      required:
        - "message"
        - "batch_id"
      additionalProperties: true
      example:
        message: "Delivery receipt received"
        batch_id: "01K608PQBF3H41EQS64AH7CE11"
    SinchMmsDeliveryReceiptAckResponse:
      type: "object"
      description: "Ack returned after a Sinch MMS delivery receipt is consumed. `code` is the Sinch status code (N101 sent, N102 delivered, N103 expired, E101/E102 failure)."
      properties:
        message:
          type: "string"
        mmsId:
          type: "string"
        code:
          type: "string"
          description: "Sinch MMS status code (e.g. `N102`)."
      required:
        - "message"
        - "mmsId"
        - "code"
      additionalProperties: true
      example:
        message: "MMS delivery receipt received"
        mmsId: "01K608PMMS001H41EQS64AH7CE"
        code: "N102"
    WebchatWebhookAckResponse:
      type: "object"
      description: "Acknowledgment for an inbound webchat message. For customer messages it is returned only after the Message row is persisted; page-context system emits (isSystemContext) are acknowledged as handled and may not persist a Message row. The socket server relays it to the widget, which flips the customer-message bubble from pending to sent on it."
      properties:
        ok:
          type: "boolean"
          enum:
            - true
        messageId:
          type: "string"
          description: "Stored Message id."
        conversationId:
          type: "string"
        duplicate:
          type: "boolean"
          description: "True when this send was a replay of a clientMessageId already stored for the same webchat session."
      required:
        - "ok"
      additionalProperties: false
      example:
        ok: true
        messageId: "6ab29740f7ebee5395fbb598"
        conversationId: "6ab297364fe62a69debc5ae7"
        duplicate: false
    WebchatWebhookRefusedResponse:
      type: "object"
      description: "The message was NOT stored. `retryable` tells the caller whether a later identical send may succeed."
      properties:
        ok:
          type: "boolean"
          enum:
            - false
        code:
          type: "string"
          enum:
            - "conversation_resolved"
            - "contact_blocked"
            - "ingest_in_progress"
            - "webchat_config_not_found"
            - "user_not_found"
            - "page_context_disabled"
            - "page_context_rejected"
            - "internal_error"
            - "not_persisted"
        retryable:
          type: "boolean"
        conversationId:
          type: "string"
      required:
        - "ok"
        - "code"
        - "retryable"
      additionalProperties: false
      example:
        ok: false
        code: "conversation_resolved"
        retryable: false
    SinchCallSvamlAction:
      type: "object"
      description: "One SVAML action (Sinch Voice Application Markup Language) instructing Sinch how to route the call."
      properties:
        name:
          type: "string"
          description: "Action name: `connectConf`, `hangup`, `playAudio`, etc."
      required:
        - "name"
      additionalProperties: true
      example:
        name: "connectConf"
    SinchCallWebhookSvamlResponse:
      type: "object"
      description: "SVAML response Sinch interprets to route the call. Only Incoming Call Event (ICE) returns a populated `action`; ACE / DiCE branches return an empty object or omit `action`."
      properties:
        action:
          "$ref": "#/components/schemas/SinchCallSvamlAction"
      additionalProperties: true
      example:
        action:
          name: "connectConf"
          conferenceId: "org-64a1b-room-42"
          cli: "+12362320246"
    WorkflowsErrorResponse:
      type: "object"
      description: "Standard error envelope for Workflows endpoints."
      properties:
        success:
          type: "boolean"
          enum:
            - false
        message:
          type: "string"
      required:
        - "success"
      additionalProperties: true
      example:
        success: false
        message: "Workflow not found"
    WorkflowConflictResponse:
      type: "object"
      description: "Stable 409 envelope for stale authoring counters, archived definitions, and command-key payload conflicts."
      properties:
        success:
          type: "boolean"
          enum:
            - false
        code:
          type: "string"
          enum:
            - "WORKFLOW_REVISION_CONFLICT"
            - "WORKFLOW_GRAPH_VERSION_CONFLICT"
            - "WORKFLOW_COMMAND_CONFLICT"
            - "WORKFLOW_ARCHIVED"
        message:
          type: "string"
        expected:
          type: "integer"
          minimum: 0
        current:
          type: "integer"
          minimum: 0
      required:
        - "success"
        - "code"
        - "message"
      additionalProperties: false
      example:
        success: false
        code: "WORKFLOW_REVISION_CONFLICT"
        message: "Workflow revision changed; reload before retrying."
        expected: 3
        current: 4
    WorkflowsSimpleSuccessResponse:
      type: "object"
      description: "Generic success envelope used for delete endpoints."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
      required:
        - "success"
      additionalProperties: true
      example:
        success: true
        message: "Workflow deleted successfully"
    WorkflowDocument:
      type: "object"
      description: "A `Workflow` document - visual builder canvas (nodes + edges) plus enabled flag and metadata."
      properties:
        _id:
          type: "string"
        name:
          type: "string"
        description:
          type: "string"
        organizationId:
          type: "string"
        userId:
          type: "string"
        nodes:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
        edges:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
        viewport:
          type: "object"
          properties:
            x:
              type: "number"
            y:
              type: "number"
            zoom:
              type: "number"
          additionalProperties: true
        enabled:
          type: "boolean"
        revision:
          type: "integer"
          minimum: 0
          description: "Resource revision advanced by every authoring mutation."
        version:
          type: "integer"
          minimum: 1
          description: "Graph version advanced only by execution-affecting node, edge, or variable changes."
        kind:
          type: "string"
          enum:
            - "general"
            - "automation"
            - "agent_flow"
          description: "Server-derived persisted workflow classification."
        isArchived:
          type: "boolean"
        archivedAt:
          type: "string"
          format: "date-time"
          nullable: true
        archivedByPrincipalIdentity:
          type: "string"
          nullable: true
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      required:
        - "revision"
        - "version"
        - "kind"
        - "isArchived"
      additionalProperties: true
      example:
        _id: "64d2f9c5e8a1d4e001a0b1c2"
        name: "New Lead Welcome"
        description: "Greet new leads and assign them to a leasing agent."
        organizationId: "64a1b2c3d4e5f60012345678"
        userId: "64a1b2c3d4e5f60012345679"
        nodes:
          -
            id: "n1"
            type: "trigger"
            position:
              x: 50
              y: 50
            data:
              event: "application.created"
          -
            id: "n2"
            type: "sendMessage"
            position:
              x: 250
              y: 50
            data:
              template: "welcome-sms"
        edges:
          -
            id: "e1"
            source: "n1"
            target: "n2"
        viewport:
          x: 0
          y: 0
          zoom: 1
        enabled: true
        revision: 2
        version: 2
        kind: "automation"
        isArchived: false
        createdAt: "2026-04-12T14:22:10.000Z"
        updatedAt: "2026-04-22T10:14:00.000Z"
    WorkflowsListResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/WorkflowDocument"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          -
            _id: "64d2f9c5e8a1d4e001a0b1c2"
            name: "New Lead Welcome"
            description: "Greet new leads and assign them to a leasing agent."
            enabled: true
    WorkflowSingleResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          "$ref": "#/components/schemas/WorkflowDocument"
      required:
        - "success"
        - "data"
      additionalProperties: true
      example:
        success: true
        data:
          _id: "64d2f9c5e8a1d4e001a0b1c2"
          name: "New Lead Welcome"
          description: "Greet new leads and assign them to a leasing agent."
          enabled: true
          nodes:
            []
          edges:
            []
    WorkflowCreateRequest:
      type: "object"
      properties:
        folderId:
          type: "string"
          nullable: true
          description: "Folder to create the workflow in; absent/null = top level."
        commandKey:
          type: "string"
          minLength: 1
          maxLength: 200
          description: "Stable caller-owned key reused for an exact retry."
        name:
          type: "string"
          description: "Human-readable workflow name. Must be unique within the caller organization."
        description:
          type: "string"
          description: "Free-text description shown in the workflows list and builder header."
        nodes:
          type: "array"
          description: "Visual builder nodes - each carries `id`, `type`, `position`, and node-specific `data`."
          items:
            type: "object"
            additionalProperties: true
        edges:
          type: "array"
          description: "Directed connections between nodes (`source` → `target` ids) defining execution flow."
          items:
            type: "object"
            additionalProperties: true
        viewport:
          type: "object"
          description: "Camera state for the canvas (`x`, `y`, `zoom`). Defaults to `{ x: 0, y: 0, zoom: 1 }` when omitted."
          properties:
            x:
              type: "number"
              description: "Horizontal pan offset of the canvas."
            y:
              type: "number"
              description: "Vertical pan offset of the canvas."
            zoom:
              type: "number"
              description: "Canvas zoom factor (1 = 100%)."
          additionalProperties: false
        enabled:
          type: "boolean"
          description: "When false, the trigger system skips this workflow even when conditions match. Defaults to false on create."
      required:
        - "commandKey"
        - "name"
      additionalProperties: true
      example:
        commandKey: "workflow-create-01J2YQ6P0M9M4J6YBZ8QJX7B9Q"
        name: "New Lead Welcome"
        description: "Greet new leads and assign them to a leasing agent."
        nodes:
          -
            id: "n1"
            type: "trigger"
            position:
              x: 50
              y: 50
            data:
              event: "application.created"
          -
            id: "n2"
            type: "sendMessage"
            position:
              x: 250
              y: 50
            data:
              template: "welcome-sms"
        edges:
          -
            id: "e1"
            source: "n1"
            target: "n2"
        viewport:
          x: 0
          y: 0
          zoom: 1
        enabled: true
    WorkflowUpdateRequest:
      type: "object"
      description: "Partial update - only the supplied fields are written; omitted fields are left untouched."
      properties:
        commandKey:
          type: "string"
          minLength: 1
          maxLength: 200
          description: "Stable caller-owned key reused for an exact retry."
        expectedRevision:
          type: "integer"
          minimum: 0
          description: "Exact current resource revision."
        expectedGraphVersion:
          type: "integer"
          minimum: 1
          description: "Exact current graph version for trusted editor replacement."
        name:
          type: "string"
          description: "New workflow name. Must remain unique within the caller organization."
        description:
          type: "string"
          description: "Replacement free-text description. Send an empty string to clear."
        nodes:
          type: "array"
          description: "Replacement node array - fully overwrites the current canvas nodes when supplied."
          items:
            type: "object"
            additionalProperties: true
        edges:
          type: "array"
          description: "Replacement edge array - fully overwrites the current canvas edges when supplied."
          items:
            type: "object"
            additionalProperties: true
        viewport:
          type: "object"
          description: "Replacement camera state (`x`, `y`, `zoom`) for the canvas."
          properties:
            x:
              type: "number"
              description: "Horizontal pan offset of the canvas."
            y:
              type: "number"
              description: "Vertical pan offset of the canvas."
            zoom:
              type: "number"
              description: "Canvas zoom factor (1 = 100%)."
          additionalProperties: false
        enabled:
          type: "boolean"
          description: "When false, the trigger system skips this workflow even when conditions match."
      required:
        - "commandKey"
        - "expectedRevision"
        - "expectedGraphVersion"
      additionalProperties: true
      example:
        commandKey: "workflow-save-01J2YQ8V6C4Y2QJ58C2HNGK4F1"
        expectedRevision: 2
        expectedGraphVersion: 2
        name: "New Lead Welcome (v2)"
        description: "Greet new leads, assign an agent, and create a follow-up task."
        enabled: true
    WorkflowFolder:
      type: "object"
      properties:
        _id:
          type: "string"
        name:
          type: "string"
          maxLength: 100
        parentFolderId:
          type: "string"
          nullable: true
          description: "null = top level."
        revision:
          type: "integer"
          minimum: 0
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      required:
        - "_id"
        - "name"
        - "parentFolderId"
        - "revision"
    WorkflowFolderListResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/WorkflowFolder"
    WorkflowFolderResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          "$ref": "#/components/schemas/WorkflowFolder"
        message:
          type: "string"
    WorkflowFolderDeleteResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "object"
          properties:
            _id:
              type: "string"
        message:
          type: "string"
    WorkflowFolderCreateRequest:
      type: "object"
      properties:
        name:
          type: "string"
          minLength: 1
          maxLength: 100
        parentFolderId:
          type: "string"
          nullable: true
      required:
        - "name"
      additionalProperties: false
      example:
        name: "Inbound"
        parentFolderId: "66b1f0c2a1b2c3d4e5f60718"
    WorkflowFolderUpdateRequest:
      type: "object"
      description: "At least one of name or parentFolderId."
      properties:
        name:
          type: "string"
          minLength: 1
          maxLength: 100
        parentFolderId:
          type: "string"
          nullable: true
      additionalProperties: false
      example:
        parentFolderId: null
    WorkflowMoveRequest:
      type: "object"
      properties:
        workflowIds:
          type: "array"
          items:
            type: "string"
          minItems: 1
          maxItems: 500
        folderId:
          type: "string"
          nullable: true
          description: "null = top level."
      required:
        - "workflowIds"
        - "folderId"
      additionalProperties: false
      example:
        workflowIds:
          - "66b1f0c2a1b2c3d4e5f60719"
        folderId: null
    WorkflowMoveResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
        data:
          type: "object"
          properties:
            workflowIds:
              type: "array"
              items:
                type: "string"
            folderId:
              type: "string"
              nullable: true
        message:
          type: "string"
    WorkflowToggleRequest:
      type: "object"
      properties:
        commandKey:
          type: "string"
          minLength: 1
          maxLength: 200
          description: "Stable caller-owned key reused for an exact retry."
        expectedRevision:
          type: "integer"
          minimum: 0
          description: "Exact current resource revision."
        enabled:
          type: "boolean"
          description: "New enabled state. When false, the trigger system skips this workflow even when conditions match."
      required:
        - "commandKey"
        - "expectedRevision"
        - "enabled"
      additionalProperties: true
      example:
        commandKey: "workflow-toggle-01J2YQAX9XTT1F6XHY98BR3V5K"
        expectedRevision: 3
        enabled: false
    WorkflowArchiveRequest:
      type: "object"
      properties:
        commandKey:
          type: "string"
          minLength: 1
          maxLength: 200
          description: "Stable caller-owned key reused for an exact retry."
        expectedRevision:
          type: "integer"
          minimum: 0
          description: "Exact current resource revision."
      required:
        - "commandKey"
        - "expectedRevision"
      additionalProperties: false
      example:
        commandKey: "workflow-archive-01J2YQCDV9JXQEM3PB9RJK3WMN"
        expectedRevision: 4
    WorkflowExecuteRequest:
      type: "object"
      description: "Optional scoping for a manual run. Forwarded to the queued job as `trigger.contactId` / `trigger.conversationId` so workflow nodes can reference an existing contact/conversation."
      properties:
        contactId:
          type: "string"
          description: "Optional Contact `_id` to bind the run to - workflow nodes can read this from the trigger context."
        conversationId:
          type: "string"
          description: "Optional Conversation `_id` to bind the run to - workflow nodes can read this from the trigger context."
      additionalProperties: true
      example:
        contactId: "64b2c3d4e5f60012345678aa"
        conversationId: "64d2f9c5e8a1d4e001a0b1c2"
    SendGridInboundEmailPayload:
      type: "object"
      properties:
        from:
          type: "string"
        to:
          oneOf:
            -
              type: "string"
            -
              type: "array"
              items:
                type: "string"
        subject:
          type: "string"
        body:
          type: "string"
        bodyHtml:
          type: "string"
        headers:
          type: "object"
          additionalProperties: true
        attachments:
          type: "array"
          items:
            type: "object"
            additionalProperties: true
      required:
        - "from"
        - "to"
        - "subject"
      additionalProperties: true
      example:
        from: "alex.nguyen@example.com"
        to:
          - "inbound+org-64a1b@inbound.tetherai.ca"
        subject: "Question about Maple Court"
        body: "Hi - could you confirm the unit availability for next month?"
        bodyHtml: "<p>Hi - could you confirm the unit availability for next month?</p>"
        headers:
          Message-ID: "<abc123@mail.example.com>"
        attachments:
          []
    WorkflowNodeDefinitionSummary:
      type: "object"
      description: "Serialized form of a workflow `NodeDefinition`. `configJsonSchema` is a JSON Schema converted from the node's Zod `configSchema`; `outputShape` keys are the fields downstream nodes can reference; `sampleInput` is an optional example payload trigger nodes can be tested against."
      properties:
        type:
          type: "string"
        category:
          type: "string"
          description: "Node category: `trigger`, `action`, `condition`, `transform`, etc."
        label:
          type: "string"
        description:
          type: "string"
        icon:
          type: "string"
        configJsonSchema:
          description: "JSON Schema for the node `data`. `null` when the Zod schema could not be serialized."
          nullable: true
        outputShape:
          type: "object"
          additionalProperties:
            type: "string"
          description: "Keys = field names exposed to downstream nodes; values = declared type."
        sampleInput:
          type: "object"
          additionalProperties: true
      required:
        - "type"
        - "category"
        - "label"
        - "description"
        - "icon"
      additionalProperties: true
      example:
        type: "WebhookTrigger"
        category: "trigger"
        label: "Webhook"
        description: "Triggers the workflow when a request hits /api/webhook/workflow with the configured webhookId."
        icon: "webhook"
        configJsonSchema:
          type: "object"
          properties:
            webhookId:
              type: "string"
          required:
            - "webhookId"
        outputShape:
          webhookId: "string"
          payload: "object"
        sampleInput:
          webhookId: "wh_64d2f9c5e8a1d4e001a0b1c3"
          payload:
            lead:
              name: "Alex Nguyen"
    WorkflowNodeCatalogResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/WorkflowNodeDefinitionSummary"
        count:
          type: "integer"
      required:
        - "success"
        - "data"
        - "count"
      additionalProperties: true
      example:
        success: true
        count: 2
        data:
          -
            type: "WebhookTrigger"
            category: "trigger"
            label: "Webhook"
            description: "Triggers when /api/webhook/workflow receives a matching webhookId."
            icon: "webhook"
            configJsonSchema:
              type: "object"
              properties:
                webhookId:
                  type: "string"
            outputShape:
              webhookId: "string"
              payload: "object"
          -
            type: "SendMessage"
            category: "action"
            label: "Send Message"
            description: "Sends an SMS or email via the org messaging provider."
            icon: "message-square"
            configJsonSchema:
              type: "object"
              properties:
                template:
                  type: "string"
            outputShape:
              messageId: "string"
    WorkflowNodeTestRequest:
      type: "object"
      description: "`config` is parsed against the node's `configSchema`. `input` is consumed by (a) trigger-category nodes - flattened into an `ExecutionContext` so fields like `contactId`/`messageId`/`from`/`to`/`subject` are read from the top level - and (b) `AIExtractNode` and `AIGenerateNode`, where it is serialized as JSON and fed to the LLM as the sample context (this bypasses DB-backed context sources for test mode). For other non-trigger nodes, `input` is ignored and a mocked `outputShape` is returned."
      properties:
        config:
          description: "Node-specific configuration to validate."
        input:
          description: "Trigger input payload, or - for `AIExtractNode`/`AIGenerateNode` - the sample text/object to use as the LLM context."
      additionalProperties: true
      example:
        config:
          webhookId: "wh_64d2f9c5e8a1d4e001a0b1c3"
        input:
          webhookId: "wh_64d2f9c5e8a1d4e001a0b1c3"
          payload:
            lead:
              name: "Alex Nguyen"
              email: "alex.nguyen@example.com"
    WorkflowNodeTestIssue:
      type: "object"
      description: "One entry from a Zod `safeParse` error (`config` failed validation)."
      properties:
        code:
          type: "string"
        path:
          type: "array"
          items:
            oneOf:
              -
                type: "string"
              -
                type: "integer"
        message:
          type: "string"
      required:
        - "code"
        - "message"
      additionalProperties: true
      example:
        code: "invalid_type"
        path:
          - "webhookId"
        message: "Required"
    WorkflowNodeTestResponse:
      type: "object"
      description: "Response body returned with HTTP 200 in the typical case. Inspect both the HTTP status code and the body's `success` field - the endpoint can also return 404 for an unknown node type or 500 for an unhandled executor error (see the operation's response codes). When `success: true` → trigger executed, `AIExtractNode`/`AIGenerateNode` produced a real LLM result, or a non-trigger returned a mocked `outputShape`. When `success: false` → config validation failed (issues array populated), `WebhookTrigger` boundary-check failed, or an AI node could not run (no model assignment / API key - `code:'AI_SETUP_REQUIRED'`)."
      properties:
        success:
          type: "boolean"
        output:
          description: "For triggers: real trigger output. For `AIExtractNode`: the structured extraction (top-level field keys are flattened so authors can reference `{{node.output.<key>}}` directly; `extracted` is the same bag nested; `confidence`/`missingFields`/`branch` describe model self-assessment and routing; `usage`/`provider`/`model` describe the AI call). For `AIGenerateNode`: the generated text on `output.text`; plus `branch` (`success`/`failed`) and `usage`/`provider`/`model`. For side-effecting non-trigger nodes: mocked `outputShape` keys tagged with their declared type."
          type: "object"
          additionalProperties: true
        message:
          type: "string"
        code:
          type: "string"
          description: "Stable error code for machine-readable failure modes. Currently emitted: `AI_SETUP_REQUIRED` when `AIExtractNode` or `AIGenerateNode` test is invoked without a configured model assignment (`dataExtraction` and `messageGeneration`, respectively)."
        issues:
          type: "array"
          items:
            "$ref": "#/components/schemas/WorkflowNodeTestIssue"
        durationMs:
          type: "integer"
      required:
        - "success"
        - "durationMs"
      additionalProperties: true
      example:
        success: true
        output:
          webhookId: "wh_64d2f9c5e8a1d4e001a0b1c3"
          payload:
            lead:
              name: "Alex Nguyen"
              email: "alex.nguyen@example.com"
        durationMs: 4
    WorkflowSendGridInboundRequest:
      type: "object"
      description: "Internal service payload forwarded by an inbound-email adapter (e.g. `services/sendgrid-inbound`). The workflow is run against the supplied email under the specified organization."
      properties:
        organizationId:
          type: "string"
          description: "Owning organization for the run - must match the workflow's `organizationId`."
        userId:
          type: "string"
          description: "Optional User `_id` to attribute the run to. Falls back to the workflow's creator when omitted."
        emailData:
          type: "object"
          description: "Parsed inbound email payload. Either supply the flat fields (`from`/`to`/`subject`/…) or a nested `email` object - `from`, `to`, and `subject` are required."
          properties:
            email:
              description: "Nested form of the parsed email payload (alternative to the flat sibling fields)."
              "$ref": "#/components/schemas/SendGridInboundEmailPayload"
            from:
              type: "string"
              description: "RFC-5322 sender address of the inbound email."
            to:
              description: "Recipient address(es) the email was delivered to - string or array of strings."
              oneOf:
                -
                  type: "string"
                -
                  type: "array"
                  items:
                    type: "string"
            subject:
              type: "string"
              description: "Email subject line - used by `InboxDropTrigger` subject-match filters."
            body:
              type: "string"
              description: "Plain-text body of the email."
            bodyHtml:
              type: "string"
              description: "HTML body of the email when provided by the upstream parser."
            headers:
              type: "object"
              description: "Raw email headers map (e.g. `Message-ID`, `In-Reply-To`)."
              additionalProperties: true
            attachments:
              type: "array"
              description: "Parsed attachment descriptors - typically `{ filename, url }` references to provider-hosted blobs."
              items:
                type: "object"
                additionalProperties: true
            metadata:
              type: "object"
              description: "Adapter-supplied context (e.g. `receivedAt`, `source`, `leadManagementId`) forwarded to the trigger."
              additionalProperties: true
          additionalProperties: true
      required:
        - "organizationId"
        - "emailData"
      additionalProperties: true
      example:
        organizationId: "64a1b2c3d4e5f60012345678"
        userId: "64a1b2c3d4e5f60012345679"
        emailData:
          email:
            from: "alex.nguyen@example.com"
            to: "inbound+org-64a1b@inbound.tetherai.ca"
            subject: "Question about Maple Court"
            body: "Hi - could you confirm the unit availability for next month?"
          metadata:
            messageId: "sg_msg_1234567890"
    WorkflowMutationResponse:
      type: "object"
      description: "Returned by create/update/toggle. Wraps the resulting `WorkflowDocument` plus a status message."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        data:
          "$ref": "#/components/schemas/WorkflowDocument"
      required:
        - "success"
        - "message"
        - "data"
      additionalProperties: true
      example:
        success: true
        message: "Workflow created successfully"
        data:
          _id: "64d2f9c5e8a1d4e001a0b1c2"
          name: "New Lead Welcome"
          description: "Greet new leads and assign them to a leasing agent."
          organizationId: "64a1b2c3d4e5f60012345678"
          userId: "64a1b2c3d4e5f60012345679"
          nodes:
            []
          edges:
            []
          viewport:
            x: 0
            y: 0
            zoom: 1
          enabled: false
          createdAt: "2026-04-12T14:22:10.000Z"
          updatedAt: "2026-04-12T14:22:10.000Z"
    WorkflowExecuteQueuedResponse:
      type: "object"
      description: "Returned by `POST /api/workflows/{id}/execute`. The handler enqueues a BullMQ job; actual execution happens asynchronously on the workflow-runner service. Inspect the WorkflowExecution collection by `workflowId` to follow the run."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
        queued:
          type: "boolean"
          enum:
            - true
      required:
        - "success"
        - "message"
        - "queued"
      additionalProperties: true
      example:
        success: true
        message: "Workflow execution queued"
        queued: true
    WorkflowExecutionListItem:
      type: "object"
      description: "A single execution row returned by the list endpoint. `nodeExecutions` and `variables` are intentionally omitted here for payload size - fetch them via `GET /api/workflows/executions/{executionId}`."
      properties:
        _id:
          type: "string"
        workflowId:
          type: "string"
        workflowName:
          type: "string"
          nullable: true
          description: "Joined from the workflow record at list time. Null when the workflow has been deleted but the execution row was retained."
        handledError:
          type: "boolean"
          description: "True when the run completed and an error exit or a retry caught a failure on any node, on any visit. Every surface shows such a run as \"Completed (handled error)\"."
        organizationId:
          type: "string"
        triggeredBy:
          type: "string"
          enum:
            - "message"
            - "timer"
            - "webhook"
            - "manual"
            - "schedule"
            - "contact_created"
            - "contact_updated"
            - "application_created"
            - "application_updated"
            - "conversation_started"
            - "email"
            - "sendgrid_inbound"
        triggerData:
          type: "object"
          additionalProperties: true
          description: "Shape varies by trigger. For `application_created`, expect at minimum `applicationId` and `source`."
        contactId:
          type: "string"
          nullable: true
        conversationId:
          type: "string"
          nullable: true
        messageId:
          type: "string"
          nullable: true
        status:
          type: "string"
          enum:
            - "pending"
            - "running"
            - "completed"
            - "failed"
            - "cancelled"
            - "waiting"
        startedAt:
          type: "string"
          format: "date-time"
        completedAt:
          type: "string"
          format: "date-time"
          nullable: true
        duration:
          type: "number"
          description: "Total run duration in ms"
          nullable: true
        error:
          type: "string"
          nullable: true
        createdAt:
          type: "string"
          format: "date-time"
        updatedAt:
          type: "string"
          format: "date-time"
      required:
        - "_id"
        - "workflowId"
        - "organizationId"
        - "triggeredBy"
        - "status"
        - "startedAt"
        - "createdAt"
      additionalProperties: true
    WorkflowExecutionsListResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          type: "array"
          items:
            "$ref": "#/components/schemas/WorkflowExecutionListItem"
        pagination:
          type: "object"
          properties:
            page:
              type: "integer"
            limit:
              type: "integer"
            total:
              type: "integer"
            totalPages:
              type: "integer"
          required:
            - "page"
            - "limit"
            - "total"
            - "totalPages"
      required:
        - "success"
        - "data"
        - "pagination"
    NodeExecutionLog:
      type: "object"
      description: "One entry from the per-node execution trace. Mirrors the `NodeExecutionLog` sub-schema on the `WorkflowExecution` document."
      properties:
        nodeId:
          type: "string"
        nodeType:
          type: "string"
        nodeName:
          type: "string"
        status:
          type: "string"
          enum:
            - "pending"
            - "running"
            - "success"
            - "failed"
            - "skipped"
            - "waiting"
        startedAt:
          type: "string"
          format: "date-time"
        completedAt:
          type: "string"
          format: "date-time"
          nullable: true
        duration:
          type: "number"
          nullable: true
        input:
          type: "object"
          additionalProperties: true
          nullable: true
        output:
          type: "object"
          additionalProperties: true
          nullable: true
        error:
          type: "string"
          nullable: true
        retryCount:
          type: "integer"
          nullable: true
        attempts:
          type: "array"
          description: "Each attempt a Retry made at this node, in order. A failed attempt keeps its error; a Run Workflow attempt names the sub-workflow run it started (`childExecutionId`), failed attempts included."
          items:
            type: "object"
            additionalProperties: false
            properties:
              status:
                type: "string"
                enum:
                  - "pending"
                  - "running"
                  - "success"
                  - "failed"
                  - "skipped"
                  - "waiting"
              startedAt:
                type: "string"
                format: "date-time"
              completedAt:
                type: "string"
                format: "date-time"
                nullable: true
              duration:
                type: "number"
                nullable: true
              error:
                type: "string"
              errorCode:
                type: "string"
              errorCategory:
                type: "string"
              childExecutionId:
                type: "string"
            required:
              - "status"
        placeholders:
          type: "array"
          description: "Every `{{token}}` the node resolved while it ran, with a bounded copy of the value it got. `empty` is true when it resolved to nothing. Vault tokens carry `secret: true` and never a value. Absent on runs recorded before placeholder capture."
          items:
            type: "object"
            additionalProperties: false
            properties:
              token:
                type: "string"
              value:
                {}
              empty:
                type: "boolean"
              secret:
                type: "boolean"
            required:
              - "token"
              - "empty"
        visits:
          type: "array"
          description: "Earlier visits of a node a loop ran more than once, oldest first and size-capped; the entry itself is the latest visit."
          items:
            type: "object"
            additionalProperties: false
            properties:
              status:
                type: "string"
                enum:
                  - "pending"
                  - "running"
                  - "success"
                  - "failed"
                  - "skipped"
                  - "waiting"
              startedAt:
                type: "string"
                format: "date-time"
              completedAt:
                type: "string"
                format: "date-time"
                nullable: true
              duration:
                type: "number"
                nullable: true
              output:
                type: "object"
                additionalProperties: true
                nullable: true
              outputHandle:
                type: "string"
              error:
                type: "string"
              handled:
                type: "boolean"
              attempts:
                type: "array"
                description: "This visit's attempts when a Retry re-ran it. A failed attempt keeps its error; a Run Workflow attempt names the sub-workflow run it started (`childExecutionId`), failed attempts included."
                items:
                  type: "object"
                  additionalProperties: false
                  properties:
                    status:
                      type: "string"
                      enum:
                        - "pending"
                        - "running"
                        - "success"
                        - "failed"
                        - "skipped"
                        - "waiting"
                    startedAt:
                      type: "string"
                      format: "date-time"
                    completedAt:
                      type: "string"
                      format: "date-time"
                      nullable: true
                    duration:
                      type: "number"
                      nullable: true
                    error:
                      type: "string"
                    errorCode:
                      type: "string"
                    errorCategory:
                      type: "string"
                    childExecutionId:
                      type: "string"
                  required:
                    - "status"
              placeholders:
                type: "array"
                items:
                  type: "object"
                  additionalProperties: false
                  properties:
                    token:
                      type: "string"
                    value:
                      {}
                    empty:
                      type: "boolean"
                    secret:
                      type: "boolean"
                  required:
                    - "token"
                    - "empty"
              step:
                type: "integer"
              cameFrom:
                type: "object"
                additionalProperties: false
                properties:
                  nodeId:
                    type: "string"
                  edgeId:
                    type: "string"
                  handle:
                    type: "string"
                required:
                  - "nodeId"
            required:
              - "status"
              - "startedAt"
        visitCount:
          type: "integer"
          description: "Total visits, including any that fell out of `visits`."
        step:
          type: "integer"
          description: "The node's place in the run's order: a per-run counter taken when it started (each loop visit takes its own; a Merge takes one when it completes). Absent on runs recorded before it was kept."
        handledEarlier:
          type: "boolean"
          description: "An earlier visit of this node (a loop pass) failed and was caught, even if a later visit succeeded or that visit fell out of `visits`."
        failedEarlier:
          type: "boolean"
          description: "An earlier visit of this node (a loop pass) failed with nothing to catch it, even if a later visit succeeded or that visit fell out of `visits`."
        arrivedEarlier:
          type: "array"
          description: "Every distinct edge an earlier visit of this node arrived by (up to 20), kept when those visits fall out of `visits`."
          items:
            type: "object"
            additionalProperties: false
            properties:
              nodeId:
                type: "string"
              edgeId:
                type: "string"
              handle:
                type: "string"
            required:
              - "nodeId"
        firstStep:
          type: "integer"
          description: "A node a loop ran more than once: its first visit's step, kept even when the earliest visits fall out of `visits`."
        splitNodeId:
          type: "string"
          description: "The Split node whose branch (`branchId`) this node ran in; branch ids repeat between Splits. Absent outside a branch and on runs recorded before it was kept."
        branchesInTurn:
          type: "boolean"
          description: "A SplitNode only: true when its branches ran one after the other (two or more hold a loop), false when they ran side by side. Absent on runs recorded before it was kept."
        cameFrom:
          type: "object"
          additionalProperties: false
          description: "The node and edge this visit arrived by. Absent for a trigger, a node a run resumed at, and a Merge."
          properties:
            nodeId:
              type: "string"
            edgeId:
              type: "string"
            handle:
              type: "string"
              description: "The exit of `nodeId` the edge leaves from."
          required:
            - "nodeId"
      required:
        - "nodeId"
        - "nodeType"
        - "status"
        - "startedAt"
      additionalProperties: true
    WorkflowExecutionDetailResponse:
      type: "object"
      properties:
        success:
          type: "boolean"
          enum:
            - true
        data:
          allOf:
            -
              "$ref": "#/components/schemas/WorkflowExecutionListItem"
            -
              type: "object"
              properties:
                nodeExecutions:
                  type: "array"
                  items:
                    "$ref": "#/components/schemas/NodeExecutionLog"
                variables:
                  type: "object"
                  additionalProperties: true
                  description: "Workflow-scope variables set during the run."
                workflowVersion:
                  type: "integer"
                  description: "The workflow version this run executed."
                workflowGraph:
                  type: "object"
                  nullable: true
                  description: "The run's workflow graph as it is now (`nodes`, `edges`, `version`, `revision`, `name`), node config redacted like a node's input. `archived: true` when the workflow was deleted since (deleting archives it); null only when its record is gone. Compare `version` with the run's `workflowVersion` to tell whether it changed since the run."
                  additionalProperties: true
              required:
                - "nodeExecutions"
      required:
        - "success"
        - "data"
    WorkflowExecuteSendGridInboundResponse:
      type: "object"
      description: "Returned by `POST /api/workflows/{id}/execute/sendgrid-inbound` after the internal service hands off the email payload to the workflow engine."
      properties:
        success:
          type: "boolean"
          enum:
            - true
        message:
          type: "string"
      required:
        - "success"
        - "message"
      additionalProperties: true
      example:
        success: true
        message: "Workflow executed successfully"
