openapi: 3.0.3
info:
  title: Cognipeer Console Client API
  version: 1.0.0
  description: |-
    End-user Client API for Cognipeer Console — the API-token authenticated surface served under `/api/client/v1`.

    This specification documents the endpoints available to integrations that authenticate with a Console API token (`Authorization: Bearer cpeer_...`). Tokens are created in the dashboard under **Settings → API Tokens** and are scoped to a single project.

    It does **not** cover the JWT/session-authenticated dashboard (internal) API. Feature availability may depend on the deployment's license tier; endpoints gated behind a license return `403`.

    ## Authentication
    All endpoints require a Bearer token: `Authorization: Bearer <token>`.

    ## Conventions
    - Content-Type is `application/json` unless a request is a file upload (`multipart/form-data`) or a response is binary/streamed.
    - Successful responses are typically wrapped as `{ "data": ... }`; OpenAI-compatible endpoints (chat, embeddings, moderations, responses) return the provider-shaped object directly.
    - Errors return `{ "error": "..." }` (string or object).
    - Requests may include an optional `request_id` for correlation.

    ## Official SDK
    For TypeScript/JavaScript integrations, use the official [Cognipeer Console SDK](https://cognipeer.github.io/console-sdk/).
  contact:
    name: Cognipeer Support
    url: https://github.com/Cognipeer/cognipeer-console
  license:
    name: AGPL-3.0-only
    url: https://www.gnu.org/licenses/agpl-3.0.html
servers:
  - url: https://console.cognipeer.com/api/client/v1
    description: Cognipeer managed service
  - url: "{gatewayUrl}/api/client/v1"
    description: Self-hosted / on-premise gateway
    variables:
      gatewayUrl:
        default: http://localhost:3000
        description: Scheme and host of your Console gateway
security:
  - BearerAuth: []
tags:
  - name: Chat
    description: OpenAI-compatible chat completions with streaming and tool calling
  - name: Embeddings
    description: OpenAI-compatible text embeddings
  - name: Moderations
    description: Content moderation / safety classification
  - name: Audio
    description: Speech-to-text (transcriptions, translations) and text-to-speech
  - name: OCR
    description: Synchronous OCR and asynchronous OCR jobs
  - name: Batches
    description: Asynchronous batch processing of inference requests
  - name: Spend
    description: Spend reporting and budget management
  - name: Agents
    description: Agent discovery, OpenAI-compatible Responses execution, and A2A protocol
  - name: Tools
    description: OpenAPI-backed tools and action execution
  - name: MCP
    description: Model Context Protocol servers (execute, SSE, message transports)
  - name: Browser
    description: Managed browser automation sessions and actions
  - name: Automations
    description: Scheduled and triggered automation workflows
  - name: Crawler
    description: Web crawler configurations, runs, and results
  - name: Web Search
    description: Web search across configured providers
  - name: Red Team
    description: Red-team probes, campaigns, and scan runs
  - name: Vector
    description: Vector database providers and indexes
  - name: Files
    description: File storage providers, buckets, and objects
  - name: Config
    description: Remote configuration groups, items, and resolution
  - name: Memory
    description: Persistent memory stores for agents
  - name: Prompts
    description: Prompt template management, rendering, and deployments
  - name: Knowledge Engine
    description: Retrieval-Augmented Generation (RAG) modules and documents
  - name: Guardrails
    description: Content safety and policy evaluation
  - name: PII
    description: PII detection, redaction, masking, tokenization, and detokenization
  - name: Reranker
    description: Document reranking
  - name: Evaluation
    description: Evaluation suites and runs
  - name: Tracing
    description: "Agent tracing: OTLP ingestion, sessions, and streaming traces"
  - name: Realtime
    description: Realtime voice/streaming sessions (WebSocket) and realtime model config. Enterprise.
  - name: Sandbox
    description: "Managed code sandboxes: lifecycle, exec/code, snapshots, files, port preview, and the in-sandbox toolbox (filesystem, git, shell sessions). Enterprise."
  - name: MCP Hubs
    description: Curated MCP hub discovery (read-only). Enterprise.
  - name: Aegis
    description: "Aegis enforcement plane: policy evaluation and shield audit. Enterprise."
  - name: Analytics
    description: Usage analytics and dashboard overview (project-scoped).
  - name: Audit
    description: Security and administrative audit log (read; owner/admin tokens).
  - name: Monitoring
    description: Inference server monitoring metrics (owner/admin tokens).
paths:
  /a2a/{agentKey}:
    post:
      tags:
        - Agents
      summary: Invoke an agent over A2A (JSON-RPC 2.0)
      description: |-
        Inbound Agent2Agent (A2A) endpoint exposing an agent to external A2A clients over JSON-RPC 2.0 (protocol v1.0). Exposure is opt-in per agent (`agent.metadata.a2a`); agents that are not exposed respond 404 (indistinguishable from missing agents). The request body is a JSON-RPC envelope `{jsonrpc, id, method, params}`.

        Supported methods:
        - `message/send` — send a user message. `params.message.parts` must contain text. Omit `params.message.contextId` to start a new conversation, or supply a prior `contextId` (equal to the conversation id) to continue one. Returns a terminal `completed` task whose `id` encodes the conversation and assistant-message index and whose artifacts carry the assistant reply text. Optional caller-supplied runtime headers may be provided via `params.message.metadata.runtime_context`.
        - `tasks/get` — retrieve a previously completed task by its `params.id`; rebuilds the task from the stored conversation.
        - `tasks/cancel` — always rejected (`-32004`): tasks complete synchronously and cannot be canceled.

        Protocol-level failures (parse error, invalid params, unknown method, internal error) are returned as HTTP 200 with a JSON-RPC error object. HTTP 400/404 are returned before dispatch when the target agent is inactive or not exposed.
      operationId: invokeAgentA2a
      parameters:
        - name: agentKey
          in: path
          required: true
          description: Unique agent key of the A2A-exposed agent.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/AgentA2aRpcRequest"
      responses:
        "200":
          description: A JSON-RPC 2.0 response envelope. Contains `result` (a completed A2A task) on success, or `error` for protocol-level failures.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AgentA2aRpcResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /a2a/{agentKey}/.well-known/agent-card.json:
    get:
      tags:
        - Agents
      summary: Get A2A agent card
      description: Return the Agent-to-Agent (A2A) protocol Agent Card for an exposed agent — the discovery document describing the agent's identity, transport, capabilities, skills, and security schemes. Served at the A2A well-known path.
      operationId: getA2aAgentCard
      parameters:
        - name: agentKey
          in: path
          required: true
          schema:
            type: string
          description: Key of an A2A-exposed agent.
      responses:
        "200":
          description: The A2A Agent Card.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AgentCard"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /aegis/evaluate:
    post:
      tags:
        - Aegis
      summary: Evaluate a call against a shield
      description: Enterprise / license-gated. Evaluates a tool call, retrieval, or model I/O against an Aegis shield's policy (tool allow/deny, egress/path rules, side-effect classes, DLP). Returns a decision of `allow`, `redact`, `require_approval`, `sandbox`, or `block`; every decision is recorded on the shield's audit trail. When `shieldId` is omitted the built-in `default` shield is used. A `require_approval` decision returns an `approval.approvalId` — after a human approves it in the Console, re-run the SAME call with `context.approvalToken`.
      operationId: aegisEvaluate
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/AegisEvaluateRequest"
      responses:
        "200":
          description: The evaluation result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AegisEvaluation"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /aegis/shields:
    get:
      tags:
        - Aegis
      summary: List shields
      description: Enterprise / license-gated. Lists the tenant's Aegis shields (including the built-in `default` shield). Read-only — shields are created and configured in the Console dashboard.
      operationId: listAegisShields
      responses:
        "200":
          description: The tenant's shields.
          content:
            application/json:
              schema:
                type: object
                properties:
                  shields:
                    type: array
                    items:
                      $ref: "#/components/schemas/AegisShield"
                required:
                  - shields
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
  /aegis/shields/{id}/audit:
    get:
      tags:
        - Aegis
      summary: Read a shield's audit trail
      description: Enterprise / license-gated. Reads a shield's decision audit trail, newest first. Optional `decision` filter narrows to a single decision class.
      operationId: getAegisShieldAudit
      parameters:
        - name: id
          in: path
          required: true
          description: Shield id (`default` for the built-in shield).
          schema:
            type: string
        - name: limit
          in: query
          required: false
          description: Maximum number of audit events to return (defaults to 100).
          schema:
            type: integer
            default: 100
        - name: decision
          in: query
          required: false
          description: Filter to a single decision class.
          schema:
            type: string
            enum:
              - allow
              - redact
              - require_approval
              - sandbox
              - block
      responses:
        "200":
          description: The shield's audit events.
          content:
            application/json:
              schema:
                type: object
                properties:
                  events:
                    type: array
                    items:
                      $ref: "#/components/schemas/AegisAuditEvent"
                required:
                  - events
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /agents:
    get:
      tags:
        - Agents
      summary: List agents
      description: List the agents available to the authenticated API token's project. Each entry exposes the agent key, name, description, status, creation time, and the resolved model configuration (modelKey, temperature, topP, maxTokens).
      operationId: listAgents
      parameters:
        - name: status
          in: query
          required: false
          description: Filter the returned agents by lifecycle status.
          schema:
            type: string
            enum:
              - active
              - inactive
              - draft
      responses:
        "200":
          description: The list of agents visible to the token's project.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AgentListResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      tags:
        - Agents
      summary: Create an agent
      description: Create a new agent definition (native model-backed or connected external agent). Inline API keys are encrypted at rest and redacted from the response. Requires an API token with `write` permission for this service.
      operationId: createAgent
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/AgentCreateInput"
      responses:
        "201":
          description: The created agent (secrets redacted).
          content:
            application/json:
              schema:
                type: object
                properties:
                  agent:
                    $ref: "#/components/schemas/AgentRecord"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
  /agents/responses:
    post:
      tags:
        - Agents
      summary: Invoke an agent (published version)
      description: Invoke an agent using the OpenAI Responses API request/response format, running the PUBLISHED version of the agent. The agent is identified by the `model` field (agent key). Pass `input` as a plain string or an array of message items; use `previous_response_id` (`resp_{conversationId}`) to continue a prior conversation, and `version` to pin a specific published version. The gateway tracks conversation history server-side. This endpoint returns a single completed response object; it does not stream.
      operationId: invokeAgentResponsePublished
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/AgentResponsesRequest"
      responses:
        "200":
          description: The completed agent response in OpenAI Responses format.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AgentResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /agents/{agentKey}:
    get:
      tags:
        - Agents
      summary: Get an agent
      description: Fetch a single agent by its unique key within the authenticated token's project.
      operationId: getAgent
      parameters:
        - name: agentKey
          in: path
          required: true
          description: Unique agent key.
          schema:
            type: string
      responses:
        "200":
          description: The requested agent.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AgentDetailResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    patch:
      tags:
        - Agents
      summary: Update an agent
      description: Partially update an agent definition resolved by key within the token's project. Native config never clobbers a stored connected agent; omitting a connection API key preserves the stored one. Requires an API token with `write` permission for this service.
      operationId: updateAgent
      parameters:
        - name: agentKey
          in: path
          required: true
          description: Unique agent key.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/AgentUpdateInput"
      responses:
        "200":
          description: The updated agent (secrets redacted).
          content:
            application/json:
              schema:
                type: object
                properties:
                  agent:
                    $ref: "#/components/schemas/AgentRecord"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - Agents
      summary: Delete an agent
      description: Delete an agent definition resolved by key within the token's project. Requires an API token with `write` permission for this service.
      operationId: deleteAgent
      parameters:
        - name: agentKey
          in: path
          required: true
          description: Unique agent key.
          schema:
            type: string
      responses:
        "200":
          description: The agent was deleted.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                    description: Always true when the resource was deleted.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /agents/{agentKey}/publish:
    post:
      tags:
        - Agents
      summary: Publish an agent version
      description: Snapshot the agent's current config as a new immutable, monotonically-numbered version. Requires an API token with `write` permission for this service.
      operationId: publishAgent
      parameters:
        - name: agentKey
          in: path
          required: true
          description: Unique agent key.
          schema:
            type: string
      requestBody:
        required: false
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/AgentPublishInput"
      responses:
        "201":
          description: The newly published version.
          content:
            application/json:
              schema:
                type: object
                properties:
                  version:
                    $ref: "#/components/schemas/AgentVersionRecord"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /analytics/overview:
    get:
      tags:
        - Analytics
      summary: Dashboard rollup
      description: "Returns the dashboard rollup for the token's project: aggregate stats, recent tracing sessions, and a daily series. Project-scoped: a token that is not scoped to a project returns 400. RBAC maps this path to the (non-admin) `models` service; a token lacking read permission is rejected with 403."
      operationId: getAnalyticsOverview
      parameters:
        - name: from
          in: query
          required: false
          description: Inclusive lower bound as an ISO 8601 date/date-time. Invalid values return 400.
          schema:
            type: string
            format: date-time
        - name: to
          in: query
          required: false
          description: Inclusive upper bound as an ISO 8601 date/date-time. Invalid values return 400.
          schema:
            type: string
            format: date-time
      responses:
        "200":
          description: Dashboard overview rollup.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AnalyticsOverview"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
  /analytics/usage:
    get:
      tags:
        - Analytics
      summary: Usage time-series and breakdowns
      description: "Returns usage/spend analytics derived from the same data that backs the dashboard. Project-scoped: reads are strictly bound to the token's tenant and project. A token that is not scoped to a project returns 400. The response body shape depends on `group_by`: `model` returns a per-model breakdown plus an interval time-series; `user`/`token` return per-entity attribution from the usage rollup; `service` returns a per-service breakdown. RBAC maps this path to the (non-admin) `models` service, so any token with `models:read` may call it; a token whose role/grants lack read permission is rejected with 403."
      operationId: getAnalyticsUsage
      parameters:
        - name: from
          in: query
          required: false
          description: Inclusive lower bound as an ISO 8601 date/date-time. Invalid values return 400.
          schema:
            type: string
            format: date-time
        - name: to
          in: query
          required: false
          description: Inclusive upper bound as an ISO 8601 date/date-time. Invalid values return 400.
          schema:
            type: string
            format: date-time
        - name: group_by
          in: query
          required: false
          description: Breakdown dimension. Defaults to `model`. Selects which response envelope is returned.
          schema:
            type: string
            enum:
              - model
              - user
              - token
              - service
            default: model
        - name: interval
          in: query
          required: false
          description: Time-series bucket granularity. Only applies when `group_by=model`. Defaults to `day`.
          schema:
            type: string
            enum:
              - hour
              - day
              - month
            default: day
        - name: model
          in: query
          required: false
          description: Optional model key filter (applied for `group_by=model|user|token`).
          schema:
            type: string
      responses:
        "200":
          description: Usage analytics. The body is one of three envelopes selected by `group_by`.
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/AnalyticsUsageModel"
                  - $ref: "#/components/schemas/AnalyticsUsageEntity"
                  - $ref: "#/components/schemas/AnalyticsUsageService"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
  /audio/speech:
    post:
      tags:
        - Audio
      summary: Synthesize speech (text-to-speech)
      description: Synthesizes spoken audio from input text and returns raw audio bytes. The response Content-Type reflects the produced audio format, and X-Request-Id carries the request correlation ID.
      operationId: createAudioSpeech
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/AudioSpeechRequest"
      responses:
        "200":
          description: Raw synthesized audio bytes. The Content-Type header reflects the requested response_format (audio/mpeg for mp3, etc.).
          headers:
            Content-Length:
              description: Byte length of the audio.
              schema:
                type: integer
            X-Request-Id:
              description: Request correlation ID.
              schema:
                type: string
          content:
            audio/mpeg:
              schema:
                type: string
                format: binary
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"
  /audio/transcriptions:
    post:
      tags:
        - Audio
      summary: Transcribe audio
      description: Transcribes audio into text in the source language. Accepts either a multipart file upload or a JSON body with base64-encoded audio.
      operationId: createAudioTranscription
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              $ref: "#/components/schemas/AudioTranscriptionMultipartRequest"
          application/json:
            schema:
              $ref: "#/components/schemas/AudioTranscriptionJsonRequest"
      responses:
        "200":
          description: Transcription result. The exact shape depends on the requested response_format.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AudioTranscriptionResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"
  /audio/translations:
    post:
      tags:
        - Audio
      summary: Translate audio to English
      description: Transcribes audio and translates it into English. Same input handling as transcriptions, but the language and timestamp_granularities fields are not used.
      operationId: createAudioTranslation
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              $ref: "#/components/schemas/AudioTranslationMultipartRequest"
          application/json:
            schema:
              $ref: "#/components/schemas/AudioTranslationJsonRequest"
      responses:
        "200":
          description: English translation result. The exact shape depends on the requested response_format.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AudioTranslationResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"
  /audit/logs:
    get:
      tags:
        - Audit
      summary: List audit logs
      description: "Returns filtered, paginated security/administrative audit events. Tenant-scoped (NOT project-scoped): the query is tenant-wide. `audit` is an admin RBAC service, so only owner/admin tokens or tokens with an explicit `audit:read` grant may call it; insufficient permission returns 403."
      operationId: listAuditLogs
      parameters:
        - name: action
          in: query
          required: false
          description: Filter by audit action.
          schema:
            type: string
        - name: actorUserId
          in: query
          required: false
          description: Filter by the acting user's id.
          schema:
            type: string
        - name: from
          in: query
          required: false
          description: Inclusive lower bound (ISO 8601). Unparseable values are ignored.
          schema:
            type: string
            format: date-time
        - name: to
          in: query
          required: false
          description: Inclusive upper bound (ISO 8601). Unparseable values are ignored.
          schema:
            type: string
            format: date-time
        - name: method
          in: query
          required: false
          description: Filter by HTTP method (upper-cased server-side).
          schema:
            type: string
        - name: outcome
          in: query
          required: false
          description: Filter by outcome. Only `success`, `failure`, or `denied` are honoured; other values are ignored.
          schema:
            type: string
            enum:
              - success
              - failure
              - denied
        - name: q
          in: query
          required: false
          description: Free-text search over event/path/actor fields.
          schema:
            type: string
        - name: service
          in: query
          required: false
          description: Filter by the RBAC service slug.
          schema:
            type: string
        - name: limit
          in: query
          required: false
          description: Maximum events to return. Defaults to 100, capped at 1000.
          schema:
            type: integer
            default: 100
            maximum: 1000
        - name: skip
          in: query
          required: false
          description: Number of events to skip for pagination. Defaults to 0.
          schema:
            type: integer
            default: 0
      responses:
        "200":
          description: A list of sanitized audit log entries.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AuditLogList"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
  /automations:
    get:
      tags:
        - Automations
      summary: List automations
      description: Returns every platform automation (background scheduler / maintenance job) with its current derived state and metrics.
      operationId: listAutomations
      parameters: []
      responses:
        "200":
          description: All automations and their live state.
          content:
            application/json:
              schema:
                type: object
                required:
                  - automations
                properties:
                  automations:
                    type: array
                    items:
                      $ref: "#/components/schemas/AutomationView"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /automations/{key}:
    get:
      tags:
        - Automations
      summary: Get automation
      description: Returns a single automation and its current state, addressed by its stable key.
      operationId: getAutomation
      parameters:
        - name: key
          in: path
          required: true
          description: Stable automation key.
          schema:
            type: string
            enum:
              - alert-evaluation
              - browser-session-reaper
              - browser-session-reconciliation
              - inference-monitoring-poll
      responses:
        "200":
          description: The automation view.
          content:
            application/json:
              schema:
                type: object
                required:
                  - automation
                properties:
                  automation:
                    $ref: "#/components/schemas/AutomationView"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /automations/{key}/pause:
    post:
      tags:
        - Automations
      summary: Pause automation
      description: Pauses the automation's scheduler so it will not run on its cadence until resumed. In-flight runs are not interrupted. No request body is required. Only valid for automations with supportsPause=true; calling it on browser-session-reconciliation returns an error.
      operationId: pauseAutomation
      parameters:
        - name: key
          in: path
          required: true
          description: Stable automation key.
          schema:
            type: string
            enum:
              - alert-evaluation
              - browser-session-reaper
              - browser-session-reconciliation
              - inference-monitoring-poll
      responses:
        "200":
          description: The automation view after being paused.
          content:
            application/json:
              schema:
                type: object
                required:
                  - automation
                properties:
                  automation:
                    $ref: "#/components/schemas/AutomationView"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /automations/{key}/resume:
    post:
      tags:
        - Automations
      summary: Resume automation
      description: Resumes a paused scheduler so it runs on its cadence again. No request body is required. Only valid for pausable automations; calling it on browser-session-reconciliation returns an error.
      operationId: resumeAutomation
      parameters:
        - name: key
          in: path
          required: true
          description: Stable automation key.
          schema:
            type: string
            enum:
              - alert-evaluation
              - browser-session-reaper
              - browser-session-reconciliation
              - inference-monitoring-poll
      responses:
        "200":
          description: The automation view after being resumed.
          content:
            application/json:
              schema:
                type: object
                required:
                  - automation
                properties:
                  automation:
                    $ref: "#/components/schemas/AutomationView"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /automations/{key}/run:
    post:
      tags:
        - Automations
      summary: Run automation
      description: Triggers an immediate out-of-band run of the automation and waits for it to finish before responding. No request body is required. The returned view reflects the freshly updated last-run timestamps, duration, metrics, and error.
      operationId: runAutomation
      parameters:
        - name: key
          in: path
          required: true
          description: Stable automation key.
          schema:
            type: string
            enum:
              - alert-evaluation
              - browser-session-reaper
              - browser-session-reconciliation
              - inference-monitoring-poll
      responses:
        "200":
          description: The automation view after the run completed.
          content:
            application/json:
              schema:
                type: object
                required:
                  - automation
                properties:
                  automation:
                    $ref: "#/components/schemas/AutomationView"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /batches:
    get:
      tags:
        - Batches
      summary: List batches
      description: List the batch jobs created by the calling API token's project, newest first. Optionally filter by status and cap the page size.
      operationId: listBatches
      parameters:
        - name: status
          in: query
          required: false
          description: Optional batch status filter (e.g. `in_progress`, `completed`, `cancelled`).
          schema:
            type: string
        - name: limit
          in: query
          required: false
          description: Page size. Defaults to 50, clamped to the range 1-500.
          schema:
            type: integer
            default: 50
            minimum: 1
            maximum: 500
      responses:
        "200":
          description: A list of batch objects.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/BatchList"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      tags:
        - Batches
      summary: Create a batch
      description: Create an asynchronous bulk-inference batch. Provide request lines inline via `requests`, or point at a JSONL object stored in a Document Store bucket via `input_file` (mutually exclusive). Every line runs against a single target `endpoint` as a non-streaming request. The batch starts in `in_progress` and items execute via per-item queue fan-out, each consuming the submitting token's budget quota.
      operationId: createBatch
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/BatchCreateRequest"
      responses:
        "201":
          description: The created batch object.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/BatchObject"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /batches/{batchId}:
    get:
      tags:
        - Batches
      summary: Retrieve a batch
      description: Fetch a single batch object by id. Poll this endpoint for `status` and `request_counts` to track progress.
      operationId: getBatch
      parameters:
        - name: batchId
          in: path
          required: true
          description: The batch id.
          schema:
            type: string
      responses:
        "200":
          description: The batch object.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/BatchObject"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /batches/{batchId}/cancel:
    post:
      tags:
        - Batches
      summary: Cancel a batch
      description: "Cooperative cancel: pending items drain as `cancelled` without running, while items already running finish normally. The batch moves to `cancelling` and is finalized to `cancelled` once the counters drain. Only `in_progress` / `validating` batches can be cancelled, otherwise a 400 is returned. Returns the updated batch object."
      operationId: cancelBatch
      parameters:
        - name: batchId
          in: path
          required: true
          description: The batch id.
          schema:
            type: string
      responses:
        "200":
          description: The updated batch object.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/BatchObject"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /batches/{batchId}/items:
    get:
      tags:
        - Batches
      summary: List batch items
      description: Per-line execution status for a batch. Supports filtering by item status and offset/limit pagination.
      operationId: listBatchItems
      parameters:
        - name: batchId
          in: path
          required: true
          description: The batch id.
          schema:
            type: string
        - name: status
          in: query
          required: false
          description: "Optional item status filter: `pending`, `running`, `succeeded`, `failed`, or `cancelled`."
          schema:
            type: string
            enum:
              - pending
              - running
              - succeeded
              - failed
              - cancelled
        - name: limit
          in: query
          required: false
          description: Page size. Defaults to 100, clamped to the range 1-1000.
          schema:
            type: integer
            default: 100
            minimum: 1
            maximum: 1000
        - name: skip
          in: query
          required: false
          description: Number of items to skip for pagination (offset).
          schema:
            type: integer
            minimum: 0
      responses:
        "200":
          description: A list of batch item objects.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/BatchItemList"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /batches/{batchId}/results:
    get:
      tags:
        - Batches
      summary: Download batch results (JSONL)
      description: Returns the finished items (`succeeded` and `failed`) as a JSONL document in OpenAI batch-output format, one JSON object per line. On success `response.body` holds the model output and `error` is null; on failure `response.body` is null and `error` is `{ code, message }`. The optional `status` query filters which item statuses are included.
      operationId: getBatchResults
      parameters:
        - name: batchId
          in: path
          required: true
          description: The batch id.
          schema:
            type: string
        - name: status
          in: query
          required: false
          description: Optional item status filter limiting which finished items are emitted (e.g. `succeeded`, `failed`).
          schema:
            type: string
            enum:
              - succeeded
              - failed
      responses:
        "200":
          description: "JSONL document (`Content-Type: application/jsonl; charset=utf-8`) with one OpenAI batch-output object per line."
          content:
            application/jsonl:
              schema:
                type: string
                description: 'Newline-delimited JSON. Each line is an object of shape `{ "id": string, "custom_id": string|null, "response": { "status_code": integer, "body": object|null }, "error": { "code": string, "message": string }|null }`.'
                example: |-
                  {"id":"batch_req_665f","custom_id":"req-1","response":{"status_code":200,"body":{}},"error":null}
                  {"id":"batch_req_6660","custom_id":"req-2","response":{"status_code":500,"body":null},"error":{"code":"failed","message":"..."}}
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /browser/browsers:
    get:
      tags:
        - Browser
      summary: List browser profiles
      description: Returns all browser profiles scoped to the token's tenant/project. Browser profiles are reusable containers holding shared defaults (session config, artifact bucket, default model/runtime metadata).
      operationId: listBrowsers
      parameters:
        - name: status
          in: query
          required: false
          description: Filter profiles by status.
          schema:
            type: string
            enum:
              - active
              - disabled
        - name: search
          in: query
          required: false
          description: Free-text search across profile name/key.
          schema:
            type: string
      responses:
        "200":
          description: List of browser profiles.
          content:
            application/json:
              schema:
                type: object
                properties:
                  browsers:
                    type: array
                    items:
                      $ref: "#/components/schemas/BrowserProfile"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      tags:
        - Browser
      summary: Create a browser profile
      description: Creates a new browser profile. The profile stores shared defaults such as the default session configuration, artifact bucket and default model/runtime options.
      operationId: createBrowser
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/BrowserCreateRequest"
            example:
              name: research-browser
              defaultSessionConfig:
                headless: true
                viewport:
                  width: 1440
                  height: 900
                idleTimeoutMs: 120000
      responses:
        "201":
          description: Browser profile created.
          content:
            application/json:
              schema:
                type: object
                properties:
                  browser:
                    $ref: "#/components/schemas/BrowserProfile"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /browser/browsers/{idOrKey}:
    get:
      tags:
        - Browser
      summary: Get a browser profile
      description: Fetches a single browser profile by its database id or its URL-friendly key.
      operationId: getBrowser
      parameters:
        - name: idOrKey
          in: path
          required: true
          description: Browser profile id or key.
          schema:
            type: string
      responses:
        "200":
          description: The browser profile.
          content:
            application/json:
              schema:
                type: object
                properties:
                  browser:
                    $ref: "#/components/schemas/BrowserProfile"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    patch:
      tags:
        - Browser
      summary: Update a browser profile
      description: Updates mutable fields on a browser profile. All fields are optional; only supplied fields are changed.
      operationId: updateBrowser
      parameters:
        - name: idOrKey
          in: path
          required: true
          description: Browser profile id or key.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/BrowserUpdateRequest"
      responses:
        "200":
          description: The updated browser profile.
          content:
            application/json:
              schema:
                type: object
                properties:
                  browser:
                    $ref: "#/components/schemas/BrowserProfile"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - Browser
      summary: Delete a browser profile
      description: Deletes a browser profile by id or key. Returns 204 No Content on success.
      operationId: deleteBrowser
      parameters:
        - name: idOrKey
          in: path
          required: true
          description: Browser profile id or key.
          schema:
            type: string
      responses:
        "204":
          description: Browser profile deleted.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /browser/sessions:
    get:
      tags:
        - Browser
      summary: List browser sessions
      description: Lists browser sessions for the token's tenant/project, optionally filtered by status, agent, parent browser or free text.
      operationId: listBrowserSessions
      parameters:
        - name: status
          in: query
          required: false
          description: Filter by session status.
          schema:
            type: string
            enum:
              - pending
              - running
              - idle
              - closed
              - errored
              - expired
        - name: agentId
          in: query
          required: false
          description: Filter by owning agent id.
          schema:
            type: string
        - name: browserId
          in: query
          required: false
          description: Filter by parent browser profile id.
          schema:
            type: string
        - name: search
          in: query
          required: false
          description: Free-text search across session name/key.
          schema:
            type: string
        - name: limit
          in: query
          required: false
          description: Maximum number of sessions to return.
          schema:
            type: integer
      responses:
        "200":
          description: List of browser sessions.
          content:
            application/json:
              schema:
                type: object
                properties:
                  sessions:
                    type: array
                    items:
                      $ref: "#/components/schemas/BrowserSession"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      tags:
        - Browser
      summary: Create a browser session
      description: Opens a new browser session under a browser profile. A session is the direct Playwright-backed automation surface and always belongs to a browser profile.
      operationId: createBrowserSession
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/BrowserSessionCreateRequest"
            example:
              browserId: brw_123
              name: akbank-research
      responses:
        "201":
          description: Browser session created.
          content:
            application/json:
              schema:
                type: object
                properties:
                  session:
                    $ref: "#/components/schemas/BrowserSession"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /browser/sessions/by-id/{sessionId}:
    delete:
      tags:
        - Browser
      summary: Delete a browser session
      description: Permanently deletes a browser session by its database id. The manager-side session is closed first (best effort), then the record is removed.
      operationId: deleteBrowserSessionById
      parameters:
        - name: sessionId
          in: path
          required: true
          description: Browser session database id.
          schema:
            type: string
      responses:
        "200":
          description: Session deleted.
          content:
            application/json:
              schema:
                type: object
                properties:
                  deleted:
                    type: boolean
                    example: true
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /browser/sessions/{sessionId}:
    get:
      tags:
        - Browser
      summary: Get a browser session
      description: Fetches a single browser session by its database id.
      operationId: getBrowserSession
      parameters:
        - name: sessionId
          in: path
          required: true
          description: Browser session database id.
          schema:
            type: string
      responses:
        "200":
          description: The browser session.
          content:
            application/json:
              schema:
                type: object
                properties:
                  session:
                    $ref: "#/components/schemas/BrowserSession"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /browser/sessions/{sessionId}/events:
    get:
      tags:
        - Browser
      summary: List browser session events
      description: Returns the recorded event timeline (actions, extracts, screenshots, errors) for a browser session, ordered by sequence.
      operationId: listBrowserSessionEvents
      parameters:
        - name: sessionId
          in: path
          required: true
          description: Browser session database id.
          schema:
            type: string
        - name: limit
          in: query
          required: false
          description: Maximum number of events to return.
          schema:
            type: integer
        - name: skip
          in: query
          required: false
          description: Number of events to skip (pagination offset).
          schema:
            type: integer
      responses:
        "200":
          description: List of session events.
          content:
            application/json:
              schema:
                type: object
                properties:
                  events:
                    type: array
                    items:
                      $ref: "#/components/schemas/BrowserSessionEvent"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /browser/sessions/{sessionKey}:
    delete:
      tags:
        - Browser
      summary: Close a browser session
      description: Closes a live browser session identified by its stable session key. The session record is marked closed; the underlying browser context is torn down.
      operationId: closeBrowserSession
      parameters:
        - name: sessionKey
          in: path
          required: true
          description: Stable session key exposed to clients.
          schema:
            type: string
      responses:
        "200":
          description: Close result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/BrowserCloseResult"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /browser/sessions/{sessionKey}/actions:
    post:
      tags:
        - Browser
      summary: Run a browser action
      description: Executes a single browser action (goto, click, hover, type, press, wait or scroll) against the live session and returns the post-action page state.
      operationId: runBrowserAction
      parameters:
        - name: sessionKey
          in: path
          required: true
          description: Stable session key exposed to clients.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/BrowserAction"
            example:
              type: goto
              url: https://www.akbank.com
              waitUntil: networkidle
      responses:
        "200":
          description: Action result.
          content:
            application/json:
              schema:
                type: object
                properties:
                  result:
                    $ref: "#/components/schemas/BrowserActionResult"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /browser/sessions/{sessionKey}/extract:
    post:
      tags:
        - Browser
      summary: Extract content from the page
      description: Extracts text, HTML or an attribute value from one or more elements on the current page. Either `selector` or `ref` is required; `attribute` is required when `mode` is `attr`.
      operationId: extractFromBrowser
      parameters:
        - name: sessionKey
          in: path
          required: true
          description: Stable session key exposed to clients.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/BrowserExtractRequest"
            example:
              selector: h1
              mode: text
              multiple: true
      responses:
        "200":
          description: Extraction result.
          content:
            application/json:
              schema:
                type: object
                properties:
                  result:
                    $ref: "#/components/schemas/BrowserExtractResult"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /browser/sessions/{sessionKey}/pdf:
    post:
      tags:
        - Browser
      summary: Export the page to PDF
      description: Renders the current page to a PDF (headless mode only), persists it to the session's artifact bucket, and returns an artifact reference with a download URL.
      operationId: exportBrowserSessionPdf
      parameters:
        - name: sessionKey
          in: path
          required: true
          description: Stable session key exposed to clients.
          schema:
            type: string
      requestBody:
        required: false
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/BrowserPdfRequest"
      responses:
        "201":
          description: PDF persisted; artifact reference returned.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/BrowserArtifactResult"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /browser/sessions/{sessionKey}/screenshot:
    post:
      tags:
        - Browser
      summary: Capture and persist a screenshot
      description: Captures a full-page or element screenshot, persists it to the session's artifact bucket, and returns an artifact reference with a download URL.
      operationId: captureBrowserScreenshot
      parameters:
        - name: sessionKey
          in: path
          required: true
          description: Stable session key exposed to clients.
          schema:
            type: string
      requestBody:
        required: false
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/BrowserScreenshotRequest"
      responses:
        "201":
          description: Screenshot persisted; artifact reference returned.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/BrowserArtifactResult"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /browser/sessions/{sessionKey}/screenshot/live:
    get:
      tags:
        - Browser
      summary: Stream a live screenshot
      description: Captures a screenshot of the live session and streams the raw image bytes without persisting them. Intended for low-latency UI polling. The response `Content-Type` reflects the captured image format (image/png by default; image/jpeg is possible) and `Cache-Control` is `no-store`.
      operationId: captureLiveBrowserScreenshot
      parameters:
        - name: sessionKey
          in: path
          required: true
          description: Stable session key exposed to clients.
          schema:
            type: string
        - name: fullPage
          in: query
          required: false
          description: When `true`, capture the full scrollable page rather than the viewport.
          schema:
            type: string
            enum:
              - "true"
              - "false"
      responses:
        "200":
          description: Raw screenshot image bytes.
          content:
            image/png:
              schema:
                type: string
                format: binary
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /browser/sessions/{sessionKey}/snapshot:
    get:
      tags:
        - Browser
      summary: Capture an aria snapshot
      description: Captures an aria-snapshot (YAML) of the current page together with its URL. Refs returned in the snapshot can be used for subsequent click/hover/type actions.
      operationId: captureBrowserSnapshot
      parameters:
        - name: sessionKey
          in: path
          required: true
          description: Stable session key exposed to clients.
          schema:
            type: string
      responses:
        "200":
          description: Aria snapshot and current URL.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/BrowserSnapshotResult"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /browser/{browserKey}/mcp/message:
    post:
      tags:
        - Browser
      summary: Send a browser MCP JSON-RPC message
      description: "Sends a JSON-RPC 2.0 message to a browser profile's MCP server. Supported methods: `initialize`, `notifications/initialized`, `ping`, `tools/list`, `tools/call`. When `sessionId` matches an open SSE session the JSON-RPC response is delivered over that stream and this call returns 202 Accepted; otherwise the JSON-RPC response is returned inline (200). The browser toolset mirrors the Browser Use tools (browser_navigate, browser_click, browser_type, browser_snapshot, browser_screenshot, browser_pdf, browser_close, …)."
      operationId: sendBrowserMcpMessage
      parameters:
        - name: browserKey
          in: path
          required: true
          description: Browser profile id or key.
          schema:
            type: string
        - name: sessionId
          in: query
          required: false
          description: MCP session id returned by the SSE stream. Required for `tools/call`; when present, responses are dispatched over the SSE stream and this call returns 202.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/BrowserJsonRpcRequest"
            example:
              jsonrpc: "2.0"
              id: 1
              method: tools/list
      responses:
        "200":
          description: Inline JSON-RPC response (non-SSE requests).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/BrowserJsonRpcResponse"
        "202":
          description: Accepted. The request was a notification, or its JSON-RPC response was dispatched over the bound SSE stream.
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /browser/{browserKey}/mcp/sse:
    get:
      tags:
        - Browser
      summary: Open browser MCP SSE stream
      description: Opens a Server-Sent Events stream for a browser profile's MCP server. The response carries an `X-Mcp-Session-Id` header and emits an `endpoint` SSE event containing the browser-scoped JSON-RPC message URL (with the MCP `sessionId` query bound). The browser must have status `active`.
      operationId: openBrowserMcpSse
      parameters:
        - name: browserKey
          in: path
          required: true
          description: Browser profile id or key.
          schema:
            type: string
      responses:
        "200":
          description: SSE stream. Emits an `endpoint` event with the JSON-RPC message URL; subsequent JSON-RPC responses are delivered as `message` events.
          content:
            text/event-stream:
              schema:
                type: string
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /budgets:
    get:
      tags:
        - Spend
      summary: List budgets
      description: Returns every quota policy in the project that has a daily or monthly USD spend limit set. Other (non-budget) quota policies are filtered out.
      operationId: listBudgets
      responses:
        "200":
          description: A list of budget objects.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SpendBudgetList"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      tags:
        - Spend
      summary: Create a budget
      description: Create a budget policy (a quota policy with `limits.budget` set) that the quota guard enforces on live inference, embedding, and batch paths. Requires an owner or admin API token (otherwise 403). At least one of `daily_limit_usd` or `monthly_limit_usd` must be supplied; use `-1` for a limit to mean unlimited.
      operationId: createBudget
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/SpendBudgetCreateRequest"
      responses:
        "201":
          description: The created budget object.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SpendBudget"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
  /budgets/status:
    get:
      tags:
        - Spend
      summary: Get budget status
      description: Returns current spend versus the configured limits for each window (day / month), keyed the same way enforcement counts spend. When a window has no configured limit, `limit_usd` and `remaining_usd` are null while `used_usd` still reports actual spend. `configured` is false when no budget exists for the resolved scope.
      operationId: getBudgetStatus
      parameters:
        - name: domain
          in: query
          required: false
          description: Quota domain to report. Defaults to `llm`. Invalid value returns 400.
          schema:
            type: string
            enum:
              - global
              - llm
              - embedding
              - vector
              - file
              - tracing
              - stt
              - tts
              - ocr
            default: llm
        - name: model
          in: query
          required: false
          description: Narrows the counter to a single resource (model) key.
          schema:
            type: string
        - name: scope
          in: query
          required: false
          description: "`scope=token` narrows the counter to the calling API token. Any other value reports the tenant-level window."
          schema:
            type: string
      responses:
        "200":
          description: Current usage versus configured limits per window.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SpendBudgetStatus"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /budgets/{budgetId}:
    patch:
      tags:
        - Spend
      summary: Update a budget
      description: Update a budget policy. Requires an owner or admin token. Only the supplied fields are changed; omitted fields keep their existing value. The `-1`-for-unlimited rule applies to the limit fields. A `budgetId` that does not resolve to a budget policy in the project returns 404.
      operationId: updateBudget
      parameters:
        - name: budgetId
          in: path
          required: true
          description: The budget policy id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/SpendBudgetUpdateRequest"
      responses:
        "200":
          description: The updated budget object.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SpendBudget"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - Spend
      summary: Delete a budget
      description: Remove a budget policy. Requires an owner or admin token. Returns 404 if the id is not a budget policy in the project.
      operationId: deleteBudget
      parameters:
        - name: budgetId
          in: path
          required: true
          description: The budget policy id.
          schema:
            type: string
      responses:
        "200":
          description: Deletion confirmation.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SpendBudgetDeleteResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /chat/completions:
    post:
      tags:
        - Chat
      summary: Create chat completion
      description: "OpenAI-compatible chat completion endpoint. Supports function/tool calling and standard OpenAI sampling parameters. When `stream` is `true` the response is a `text/event-stream` of `chat.completion.chunk` SSE events terminated by a `data: [DONE]` line; otherwise a single JSON `chat.completion` object is returned."
      operationId: createChatCompletion
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ChatCompletionRequest"
            examples:
              basic:
                summary: Basic chat completion
                value:
                  model: gpt-4
                  messages:
                    - role: system
                      content: You are a helpful assistant.
                    - role: user
                      content: What is the capital of France?
                  temperature: 0.7
                  max_tokens: 1000
              streaming:
                summary: Streaming completion
                value:
                  model: gpt-4
                  messages:
                    - role: user
                      content: Tell me a story
                  stream: true
      responses:
        "200":
          description: Successful completion. A JSON `chat.completion` object when not streaming, or a Server-Sent Events stream when `stream` is `true`.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ChatCompletionResponse"
            text/event-stream:
              schema:
                type: string
                description: "Server-sent events stream of `chat.completion.chunk` objects, one per `data:` line, ending with `data: [DONE]`."
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"
  /config/groups:
    get:
      tags:
        - Config
      summary: List config groups
      description: Lists configuration groups scoped to the authenticated tenant and project. Supports optional filtering by search term and tags.
      operationId: listConfigGroups
      parameters:
        - name: search
          in: query
          required: false
          description: Search by name, key, or description.
          schema:
            type: string
        - name: tags
          in: query
          required: false
          description: Comma-separated tag filter.
          schema:
            type: string
      responses:
        "200":
          description: List of config groups.
          content:
            application/json:
              schema:
                type: object
                properties:
                  groups:
                    type: array
                    items:
                      $ref: "#/components/schemas/ConfigGroup"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      tags:
        - Config
      summary: Create config group
      description: Creates a new configuration group. A `key` is auto-generated from the name if omitted.
      operationId: createConfigGroup
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ConfigGroupCreateRequest"
      responses:
        "201":
          description: The created config group.
          content:
            application/json:
              schema:
                type: object
                properties:
                  group:
                    $ref: "#/components/schemas/ConfigGroup"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "409":
          $ref: "#/components/responses/Conflict"
        "500":
          $ref: "#/components/responses/InternalError"
  /config/groups/{groupKey}:
    get:
      tags:
        - Config
      summary: Get config group with items
      description: Returns the config group identified by `groupKey` along with all of its items. Secret values are masked.
      operationId: getConfigGroup
      parameters:
        - name: groupKey
          in: path
          required: true
          description: Unique key of the config group.
          schema:
            type: string
      responses:
        "200":
          description: The config group with its items.
          content:
            application/json:
              schema:
                type: object
                properties:
                  group:
                    $ref: "#/components/schemas/ConfigGroupWithItems"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    patch:
      tags:
        - Config
      summary: Update config group
      description: Updates mutable fields of the config group identified by `groupKey`. All fields are optional.
      operationId: updateConfigGroup
      parameters:
        - name: groupKey
          in: path
          required: true
          description: Unique key of the config group.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ConfigGroupUpdateRequest"
      responses:
        "200":
          description: The updated config group.
          content:
            application/json:
              schema:
                type: object
                properties:
                  group:
                    $ref: "#/components/schemas/ConfigGroup"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - Config
      summary: Delete config group
      description: Permanently removes the config group identified by `groupKey` and all of its items. Audit log entries are recorded.
      operationId: deleteConfigGroup
      parameters:
        - name: groupKey
          in: path
          required: true
          description: Unique key of the config group.
          schema:
            type: string
      responses:
        "200":
          description: Deletion succeeded.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /config/groups/{groupKey}/items:
    get:
      tags:
        - Config
      summary: List items in a group
      description: Lists the config items that belong to the group identified by `groupKey`. Supports filtering by secret flag, tags, and search term.
      operationId: listConfigGroupItems
      parameters:
        - name: groupKey
          in: path
          required: true
          description: Unique key of the config group.
          schema:
            type: string
        - name: isSecret
          in: query
          required: false
          description: Filter by secret / non-secret items.
          schema:
            type: boolean
        - name: tags
          in: query
          required: false
          description: Comma-separated tag filter.
          schema:
            type: string
        - name: search
          in: query
          required: false
          description: Search by name, key, or description.
          schema:
            type: string
      responses:
        "200":
          description: List of config items in the group.
          content:
            application/json:
              schema:
                type: object
                properties:
                  items:
                    type: array
                    items:
                      $ref: "#/components/schemas/ConfigItem"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      tags:
        - Config
      summary: Create config item
      description: Creates a config item inside the group identified by `groupKey`. A `key` is auto-generated from the name if omitted. Secret values are encrypted at rest.
      operationId: createConfigItem
      parameters:
        - name: groupKey
          in: path
          required: true
          description: Unique key of the config group.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ConfigItemCreateRequest"
      responses:
        "201":
          description: The created config item.
          content:
            application/json:
              schema:
                type: object
                properties:
                  item:
                    $ref: "#/components/schemas/ConfigItem"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          $ref: "#/components/responses/Conflict"
        "500":
          $ref: "#/components/responses/InternalError"
  /config/items:
    get:
      tags:
        - Config
      summary: List config items
      description: Lists config items across the tenant and project. Supports filtering by group, secret flag, tags, and search term. Secret values are masked.
      operationId: listConfigItems
      parameters:
        - name: groupId
          in: query
          required: false
          description: Filter items by the parent group id.
          schema:
            type: string
        - name: isSecret
          in: query
          required: false
          description: Filter by secret / non-secret items.
          schema:
            type: boolean
        - name: tags
          in: query
          required: false
          description: Comma-separated tag filter.
          schema:
            type: string
        - name: search
          in: query
          required: false
          description: Search by name, key, or description.
          schema:
            type: string
      responses:
        "200":
          description: List of config items.
          content:
            application/json:
              schema:
                type: object
                properties:
                  items:
                    type: array
                    items:
                      $ref: "#/components/schemas/ConfigItem"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /config/items/{key}:
    get:
      tags:
        - Config
      summary: Get config item
      description: Returns the config item identified by `key`. Secret values are masked (shown as bullet characters).
      operationId: getConfigItem
      parameters:
        - name: key
          in: path
          required: true
          description: Unique key of the config item.
          schema:
            type: string
      responses:
        "200":
          description: The config item.
          content:
            application/json:
              schema:
                type: object
                properties:
                  item:
                    $ref: "#/components/schemas/ConfigItem"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    patch:
      tags:
        - Config
      summary: Update config item
      description: Updates mutable fields of the config item identified by `key`. All fields are optional. When updating a secret value, the new value is encrypted automatically.
      operationId: updateConfigItem
      parameters:
        - name: key
          in: path
          required: true
          description: Unique key of the config item.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ConfigItemUpdateRequest"
      responses:
        "200":
          description: The updated config item.
          content:
            application/json:
              schema:
                type: object
                properties:
                  item:
                    $ref: "#/components/schemas/ConfigItem"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - Config
      summary: Delete config item
      description: Permanently removes the config item identified by `key`. An audit log entry is recorded.
      operationId: deleteConfigItem
      parameters:
        - name: key
          in: path
          required: true
          description: Unique key of the config item.
          schema:
            type: string
      responses:
        "200":
          description: Deletion succeeded.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /config/items/{key}/audit:
    get:
      tags:
        - Config
      summary: List config item audit logs
      description: Returns the audit trail for the config item identified by `key`, including create, read, update, and delete actions.
      operationId: listConfigItemAudit
      parameters:
        - name: key
          in: path
          required: true
          description: Unique key of the config item.
          schema:
            type: string
        - name: limit
          in: query
          required: false
          description: Maximum number of log entries to return (capped at 100).
          schema:
            type: integer
            default: 50
            maximum: 100
        - name: skip
          in: query
          required: false
          description: Number of log entries to skip for pagination.
          schema:
            type: integer
            default: 0
      responses:
        "200":
          description: Audit log entries for the config item.
          content:
            application/json:
              schema:
                type: object
                properties:
                  logs:
                    type: array
                    items:
                      $ref: "#/components/schemas/ConfigAuditLog"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /config/resolve:
    post:
      tags:
        - Config
      summary: Resolve config values
      description: Returns decrypted values for the requested config keys. Maximum 50 keys per request. Read actions are recorded in the audit trail.
      operationId: resolveConfigValues
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ConfigResolveRequest"
      responses:
        "200":
          description: Map of config key to its resolved value.
          content:
            application/json:
              schema:
                type: object
                properties:
                  configs:
                    type: object
                    additionalProperties:
                      $ref: "#/components/schemas/ConfigResolvedValue"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /crawler/crawlers:
    get:
      tags:
        - Crawler
      summary: List crawlers
      description: Lists saved crawler profiles for the token's tenant/project, optionally filtered by status and a name/key search.
      operationId: listCrawlers
      parameters:
        - name: status
          in: query
          required: false
          description: Filter by crawler status.
          schema:
            type: string
            enum:
              - active
              - disabled
        - name: search
          in: query
          required: false
          description: Match on crawler name or key.
          schema:
            type: string
      responses:
        "200":
          description: The matching crawlers.
          content:
            application/json:
              schema:
                type: object
                required:
                  - crawlers
                properties:
                  crawlers:
                    type: array
                    items:
                      $ref: "#/components/schemas/Crawler"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      tags:
        - Crawler
      summary: Create crawler
      description: Creates a saved crawler profile holding crawl configuration (engine, depth/page limits, scope filters, HTTP options, Knowledge Engine binding, webhook, schedule).
      operationId: createCrawler
      parameters: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CrawlerCreateInput"
      responses:
        "201":
          description: The created crawler.
          content:
            application/json:
              schema:
                type: object
                required:
                  - crawler
                properties:
                  crawler:
                    $ref: "#/components/schemas/Crawler"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /crawler/crawlers/{idOrKey}:
    get:
      tags:
        - Crawler
      summary: Get crawler
      description: Fetches a single crawler by its id or its key.
      operationId: getCrawler
      parameters:
        - name: idOrKey
          in: path
          required: true
          description: The crawler id or its key.
          schema:
            type: string
      responses:
        "200":
          description: The crawler.
          content:
            application/json:
              schema:
                type: object
                required:
                  - crawler
                properties:
                  crawler:
                    $ref: "#/components/schemas/Crawler"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    patch:
      tags:
        - Crawler
      summary: Update crawler
      description: Partial update of a crawler. Accepts the same fields as create plus status. Set rag, webhook, or schedule to null to clear them.
      operationId: updateCrawler
      parameters:
        - name: idOrKey
          in: path
          required: true
          description: The crawler id or its key.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CrawlerUpdateInput"
      responses:
        "200":
          description: The updated crawler.
          content:
            application/json:
              schema:
                type: object
                required:
                  - crawler
                properties:
                  crawler:
                    $ref: "#/components/schemas/Crawler"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - Crawler
      summary: Delete crawler
      description: Deletes a crawler by its id or key.
      operationId: deleteCrawler
      parameters:
        - name: idOrKey
          in: path
          required: true
          description: The crawler id or its key.
          schema:
            type: string
      responses:
        "204":
          description: The crawler was deleted.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /crawler/crawlers/{idOrKey}/crawl:
    post:
      tags:
        - Crawler
      summary: Crawl URLs on a crawler
      description: Crawls an explicit set of URLs using a saved crawler's config - 'give me the Markdown for these URLs'. Functionally a run with required urls. Defaults to async (202 + jobId); pass mode=sync to block until the crawl finishes and inline the final job state and results.
      operationId: crawlOnContainer
      parameters:
        - name: idOrKey
          in: path
          required: true
          description: The crawler id or its key.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CrawlerCrawlInput"
      responses:
        "200":
          description: "Sync mode: the finished job state with its results inlined."
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CrawlerRunSyncResult"
        "202":
          description: "Async mode: the job was enqueued."
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CrawlerRunAccepted"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /crawler/crawlers/{idOrKey}/run:
    post:
      tags:
        - Crawler
      summary: Run crawler
      description: Runs a saved crawler, enqueuing a job using the crawler's config. Optionally override the saved URL list for this run. Defaults to async (202 + jobId); pass mode=sync to block until the crawl finishes and inline the final job state and results.
      operationId: runCrawler
      parameters:
        - name: idOrKey
          in: path
          required: true
          description: The crawler id or its key.
          schema:
            type: string
      requestBody:
        required: false
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CrawlerRunOptions"
      responses:
        "200":
          description: "Sync mode: the finished job state with its results inlined."
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CrawlerRunSyncResult"
        "202":
          description: "Async mode: the job was enqueued."
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CrawlerRunAccepted"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /crawler/crawlers/{idOrKey}/urls:
    get:
      tags:
        - Crawler
      summary: List crawler URLs
      description: Lists the crawler's saved URL list. A crawler is a container, so URLs can be managed independently of runs.
      operationId: listCrawlerUrls
      parameters:
        - name: idOrKey
          in: path
          required: true
          description: The crawler id or its key.
          schema:
            type: string
      responses:
        "200":
          description: The crawler's saved URL list.
          content:
            application/json:
              schema:
                type: object
                required:
                  - urls
                properties:
                  urls:
                    type: array
                    items:
                      type: string
                      format: uri
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      tags:
        - Crawler
      summary: Add crawler URLs
      description: Adds URLs to the crawler's saved URL list and returns the updated list.
      operationId: addCrawlerUrls
      parameters:
        - name: idOrKey
          in: path
          required: true
          description: The crawler id or its key.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CrawlerUrlsBody"
      responses:
        "200":
          description: The updated URL list.
          content:
            application/json:
              schema:
                type: object
                required:
                  - urls
                properties:
                  urls:
                    type: array
                    items:
                      type: string
                      format: uri
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - Crawler
      summary: Remove crawler URLs
      description: Removes URLs from the crawler's saved URL list and returns the updated list.
      operationId: removeCrawlerUrls
      parameters:
        - name: idOrKey
          in: path
          required: true
          description: The crawler id or its key.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CrawlerUrlsBody"
      responses:
        "200":
          description: The updated URL list.
          content:
            application/json:
              schema:
                type: object
                required:
                  - urls
                properties:
                  urls:
                    type: array
                    items:
                      type: string
                      format: uri
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /crawler/jobs:
    get:
      tags:
        - Crawler
      summary: List jobs
      description: Lists crawl jobs for the token's tenant/project, optionally filtered by parent crawler, status, and a result limit.
      operationId: listCrawlJobs
      parameters:
        - name: crawlerKey
          in: query
          required: false
          description: Filter by parent crawler key.
          schema:
            type: string
        - name: status
          in: query
          required: false
          description: Filter by job status.
          schema:
            type: string
            enum:
              - queued
              - running
              - succeeded
              - partial
              - failed
              - canceled
        - name: limit
          in: query
          required: false
          description: Maximum number of jobs to return.
          schema:
            type: integer
      responses:
        "200":
          description: The matching jobs.
          content:
            application/json:
              schema:
                type: object
                required:
                  - jobs
                properties:
                  jobs:
                    type: array
                    items:
                      $ref: "#/components/schemas/CrawlerJob"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /crawler/jobs/{jobId}:
    get:
      tags:
        - Crawler
      summary: Get job
      description: Returns a single crawl job including counters, its frozen planSnapshot, and any errorMessage.
      operationId: getCrawlJob
      parameters:
        - name: jobId
          in: path
          required: true
          description: The crawl job id.
          schema:
            type: string
      responses:
        "200":
          description: The crawl job.
          content:
            application/json:
              schema:
                type: object
                required:
                  - job
                properties:
                  job:
                    $ref: "#/components/schemas/CrawlerJob"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /crawler/jobs/{jobId}/cancel:
    post:
      tags:
        - Crawler
      summary: Cancel job
      description: Requests cancellation of a queued or running job. Returns 404 if the job is missing or not cancelable.
      operationId: cancelCrawlJob
      parameters:
        - name: jobId
          in: path
          required: true
          description: The crawl job id.
          schema:
            type: string
      responses:
        "200":
          description: Cancellation was requested.
          content:
            application/json:
              schema:
                type: object
                required:
                  - ok
                properties:
                  ok:
                    type: boolean
                    example: true
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /crawler/jobs/{jobId}/results:
    get:
      tags:
        - Crawler
      summary: List job results
      description: Lists the results (fetched pages/files) for a crawl job. Each html result carries its extracted bodyMarkdown.
      operationId: listCrawlJobResults
      parameters:
        - name: jobId
          in: path
          required: true
          description: The crawl job id.
          schema:
            type: string
        - name: type
          in: query
          required: false
          description: Filter by result type.
          schema:
            type: string
            enum:
              - html
              - file
              - error
        - name: limit
          in: query
          required: false
          description: Page size.
          schema:
            type: integer
            default: 100
        - name: skip
          in: query
          required: false
          description: Offset.
          schema:
            type: integer
            default: 0
      responses:
        "200":
          description: The job's results.
          content:
            application/json:
              schema:
                type: object
                required:
                  - results
                properties:
                  results:
                    type: array
                    items:
                      $ref: "#/components/schemas/CrawlerResult"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /crawler/jobs/{jobId}/results/{resultId}:
    get:
      tags:
        - Crawler
      summary: Get job result
      description: Returns a single crawl result by its id.
      operationId: getCrawlResult
      parameters:
        - name: jobId
          in: path
          required: true
          description: The crawl job id.
          schema:
            type: string
        - name: resultId
          in: path
          required: true
          description: The result id.
          schema:
            type: string
      responses:
        "200":
          description: The crawl result.
          content:
            application/json:
              schema:
                type: object
                required:
                  - result
                properties:
                  result:
                    $ref: "#/components/schemas/CrawlerResult"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /crawler/run:
    post:
      tags:
        - Crawler
      summary: Ad-hoc crawl
      description: Starts a one-off crawl without saving a crawler. The resulting job has no crawlerKey. Always enqueues (202); pass mode=sync to request a blocking run.
      operationId: runAdhocCrawl
      parameters: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/CrawlerAdhocRunInput"
      responses:
        "202":
          description: The ad-hoc job was enqueued.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/CrawlerRunAccepted"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /embeddings:
    post:
      tags:
        - Embeddings
      summary: Create embeddings
      description: OpenAI-compatible embeddings endpoint that converts one or more text inputs into vector representations. Returns a single non-streaming JSON `list` object containing one embedding per input.
      operationId: createEmbeddings
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/EmbedEmbeddingRequest"
            examples:
              single:
                summary: Single input
                value:
                  model: text-embedding-3-small
                  input: The quick brown fox jumps over the lazy dog
              batch:
                summary: Batch input
                value:
                  model: text-embedding-3-small
                  input:
                    - Hello world
                    - How are you?
                    - Embedding example
      responses:
        "200":
          description: Successful embedding response.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/EmbedEmbeddingResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"
  /evaluation/runs:
    get:
      tags:
        - Evaluation
      summary: List evaluation runs
      description: List evaluation runs for the token's project, newest first. Returns run summaries (aggregate only, no per-item breakdown). Fetch a single run by id for the full per-item scores.
      operationId: listEvaluationRuns
      parameters:
        - name: suite_key
          in: query
          required: false
          description: Filter runs to a single suite by its key.
          schema:
            type: string
        - name: limit
          in: query
          required: false
          description: Maximum number of runs to return. Positive integers only; clamped to a maximum of 200.
          schema:
            type: integer
            minimum: 1
            maximum: 200
      responses:
        "200":
          description: Evaluation run summaries.
          content:
            application/json:
              schema:
                type: object
                properties:
                  runs:
                    type: array
                    items:
                      $ref: "#/components/schemas/EvalRunSummary"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
  /evaluation/runs/{id}:
    get:
      tags:
        - Evaluation
      summary: Get an evaluation run
      description: Fetch a single evaluation run by id, including its aggregate and the full per-item scores.
      operationId: getEvaluationRun
      parameters:
        - name: id
          in: path
          required: true
          description: Evaluation run identifier.
          schema:
            type: string
      responses:
        "200":
          description: The evaluation run with per-item scores.
          content:
            application/json:
              schema:
                type: object
                properties:
                  run:
                    $ref: "#/components/schemas/EvalRun"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /evaluation/suites:
    get:
      tags:
        - Evaluation
      summary: List evaluation suites
      description: List the evaluation suites configured for the token's project. A suite binds a target (what to test) + a dataset (the test cases) + one or more scorers. Read- and trigger-oriented surface for CI/automation; suite authoring stays on the dashboard surface. Fields are snake_case.
      operationId: listEvaluationSuites
      responses:
        "200":
          description: The configured evaluation suites.
          content:
            application/json:
              schema:
                type: object
                properties:
                  suites:
                    type: array
                    items:
                      $ref: "#/components/schemas/EvalSuite"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
  /evaluation/suites/{key}/run:
    post:
      tags:
        - Evaluation
      summary: Run an evaluation suite
      description: Run the named suite synchronously over its dataset and return the completed, scored run. Unlike the asynchronous dashboard surface, this token-authenticated client surface blocks until the run finishes and returns HTTP 201 with the completed run (aggregate + per-item scores). The suite, its target and its dataset must already exist. A target/judge error on an item is recorded on that item and counted in aggregate.failed; it does not abort the run.
      operationId: runEvaluationSuite
      parameters:
        - name: key
          in: path
          required: true
          description: Key of the suite to run.
          schema:
            type: string
      responses:
        "201":
          description: The completed evaluation run.
          content:
            application/json:
              schema:
                type: object
                properties:
                  run:
                    $ref: "#/components/schemas/EvalRun"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /files/buckets:
    get:
      tags:
        - Files
      summary: List file buckets
      description: List all file storage buckets for the current tenant/project.
      operationId: listFileBuckets
      responses:
        "200":
          description: List of buckets
          content:
            application/json:
              schema:
                type: object
                properties:
                  buckets:
                    type: array
                    items:
                      $ref: "#/components/schemas/FileBucket"
                  count:
                    type: integer
                    example: 3
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /files/buckets/{bucketKey}:
    get:
      tags:
        - Files
      summary: Get file bucket
      description: Get details of a specific file bucket.
      operationId: getFileBucket
      parameters:
        - name: bucketKey
          in: path
          required: true
          description: Unique bucket identifier.
          schema:
            type: string
      responses:
        "200":
          description: Bucket details
          content:
            application/json:
              schema:
                type: object
                properties:
                  bucket:
                    $ref: "#/components/schemas/FileBucket"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /files/buckets/{bucketKey}/objects:
    get:
      tags:
        - Files
      summary: List files in bucket
      description: List files in a specific bucket with cursor-based pagination and optional search filtering.
      operationId: listFiles
      parameters:
        - name: bucketKey
          in: path
          required: true
          description: Unique bucket identifier.
          schema:
            type: string
        - name: search
          in: query
          required: false
          description: Search term to filter files.
          schema:
            type: string
        - name: limit
          in: query
          required: false
          description: Maximum number of files to return. Defaults to 50.
          schema:
            type: integer
            default: 50
        - name: cursor
          in: query
          required: false
          description: Pagination cursor returned as `nextCursor` from a previous response.
          schema:
            type: string
      responses:
        "200":
          description: List of files
          content:
            application/json:
              schema:
                type: object
                properties:
                  files:
                    type: array
                    items:
                      $ref: "#/components/schemas/FileObject"
                  count:
                    type: integer
                    example: 12
                  nextCursor:
                    type: string
                    nullable: true
                    example: def
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      tags:
        - Files
      summary: Upload file
      description: Upload a file to a bucket as multipart/form-data. Optionally convert supported documents (PDF, DOCX, PPTX, HTML, plain text) to Markdown for the Knowledge Engine pipeline.
      operationId: uploadFile
      parameters:
        - name: bucketKey
          in: path
          required: true
          description: Unique bucket identifier.
          schema:
            type: string
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              $ref: "#/components/schemas/FileUploadRequest"
      responses:
        "201":
          description: File uploaded
          content:
            application/json:
              schema:
                type: object
                properties:
                  file:
                    $ref: "#/components/schemas/FileObject"
                  message:
                    type: string
                    example: File uploaded successfully
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"
  /files/buckets/{bucketKey}/objects/{objectKey}:
    get:
      tags:
        - Files
      summary: Get file metadata
      description: Get metadata for a specific file object in a bucket.
      operationId: getFileObject
      parameters:
        - name: bucketKey
          in: path
          required: true
          description: Unique bucket identifier.
          schema:
            type: string
        - name: objectKey
          in: path
          required: true
          description: Unique key of the file object.
          schema:
            type: string
      responses:
        "200":
          description: File metadata
          content:
            application/json:
              schema:
                type: object
                properties:
                  file:
                    $ref: "#/components/schemas/FileObject"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - Files
      summary: Delete file
      description: Delete a specific file object from a bucket.
      operationId: deleteFile
      parameters:
        - name: bucketKey
          in: path
          required: true
          description: Unique bucket identifier.
          schema:
            type: string
        - name: objectKey
          in: path
          required: true
          description: Unique key of the file object.
          schema:
            type: string
      responses:
        "200":
          description: File deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  message:
                    type: string
                    example: File deleted successfully
                  bucketKey:
                    type: string
                  objectKey:
                    type: string
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /files/buckets/{bucketKey}/objects/{objectKey}/download:
    get:
      tags:
        - Files
      summary: Download file
      description: Download the binary content of a file object. Use the `variant` query parameter to download the original file or its Markdown conversion (if available). Response headers include `Content-Type`, `Content-Disposition`, `Content-Length`, `ETag`, and `X-File-Metadata`.
      operationId: downloadFile
      parameters:
        - name: bucketKey
          in: path
          required: true
          description: Unique bucket identifier.
          schema:
            type: string
        - name: objectKey
          in: path
          required: true
          description: Unique key of the file object.
          schema:
            type: string
        - name: variant
          in: query
          required: false
          description: Which representation to download. `original` returns the original file; `markdown` returns the Markdown conversion if available. Defaults to `original`.
          schema:
            type: string
            enum:
              - original
              - markdown
            default: original
      responses:
        "200":
          description: Binary file content
          headers:
            Content-Disposition:
              description: Attachment disposition with the URL-encoded file name.
              schema:
                type: string
            ETag:
              description: Entity tag of the file content, when available.
              schema:
                type: string
            X-File-Metadata:
              description: JSON-serialized file metadata, when available.
              schema:
                type: string
          content:
            application/octet-stream:
              schema:
                type: string
                format: binary
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /files/providers:
    get:
      tags:
        - Files
      summary: List file providers
      description: List all file storage providers configured for the current tenant/project. Optionally filter by driver and status.
      operationId: listFileProviders
      parameters:
        - name: driver
          in: query
          required: false
          description: Filter providers by driver identifier (e.g. `s3`).
          schema:
            type: string
            example: s3
        - name: status
          in: query
          required: false
          description: Filter providers by status.
          schema:
            type: string
            enum:
              - active
              - inactive
              - error
            example: active
      responses:
        "200":
          description: List of file providers
          content:
            application/json:
              schema:
                type: object
                properties:
                  providers:
                    type: array
                    items:
                      $ref: "#/components/schemas/FileProvider"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      tags:
        - Files
      summary: Create file provider
      description: Create a new file storage provider configuration for the current project. Requires `key`, `driver`, `label`, and `credentials`.
      operationId: createFileProvider
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/FileCreateProviderRequest"
            example:
              key: s3-prod
              driver: s3
              label: Production Storage
              credentials:
                accessKeyId: AKIA...
                secretAccessKey: ...
              settings:
                region: us-east-1
      responses:
        "201":
          description: File provider created
          content:
            application/json:
              schema:
                type: object
                properties:
                  provider:
                    $ref: "#/components/schemas/FileProvider"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "409":
          $ref: "#/components/responses/Conflict"
        "500":
          $ref: "#/components/responses/InternalError"
  /guardrails:
    post:
      tags:
        - Guardrails
      summary: Create a guardrail
      description: Create a preset or custom (LLM-evaluated) guardrail definition. Requires an API token with `write` permission for this service.
      operationId: createGuardrail
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/GuardCreateInput"
      responses:
        "201":
          description: The created guardrail.
          content:
            application/json:
              schema:
                type: object
                properties:
                  guardrail:
                    $ref: "#/components/schemas/GuardRecord"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
  /guardrails/evaluate:
    post:
      tags:
        - Guardrails
      summary: Evaluate content against a guardrail
      description: Evaluate arbitrary content against a stored guardrail (PII detection, content moderation, prompt shield, or custom LLM prompt). Returns the configured action, any findings, and whether the content passed. When the guardrail redacts, `redacted_text` holds the transformed text.
      operationId: evaluateGuardrail
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/GuardEvaluateRequest"
      responses:
        "200":
          description: Evaluation result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/GuardEvaluateResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /guardrails/{key}:
    patch:
      tags:
        - Guardrails
      summary: Update a guardrail
      description: Partially update a guardrail resolved by key within the token's project. Requires an API token with `write` permission for this service.
      operationId: updateGuardrail
      parameters:
        - name: key
          in: path
          required: true
          description: Unique guardrail key.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/GuardUpdateInput"
      responses:
        "200":
          description: The updated guardrail.
          content:
            application/json:
              schema:
                type: object
                properties:
                  guardrail:
                    $ref: "#/components/schemas/GuardRecord"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - Guardrails
      summary: Delete a guardrail
      description: Delete a guardrail resolved by key within the token's project. Requires an API token with `write` permission for this service.
      operationId: deleteGuardrail
      parameters:
        - name: key
          in: path
          required: true
          description: Unique guardrail key.
          schema:
            type: string
      responses:
        "200":
          description: The guardrail was deleted.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                    description: Always true when the resource was deleted.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /mcp:
    post:
      tags:
        - MCP
      summary: Create an MCP server
      description: Create an MCP server definition from an OpenAPI spec, a remote MCP endpoint, or a stdio (npx/uvx) package. Upstream secrets are masked in the response. Requires an API token with `write` permission for this service.
      operationId: createMcpServer
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/McpCreateInput"
      responses:
        "201":
          description: The created MCP server (secrets masked).
          content:
            application/json:
              schema:
                type: object
                properties:
                  server:
                    $ref: "#/components/schemas/McpServer"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "402":
          description: Payment Required — persistent sandbox execution requires an active Enterprise license.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
  /mcp/console/execute:
    get:
      tags:
        - MCP
      summary: List built-in console MCP tools
      description: List the tools exposed by the built-in `console` MCP server. This server is project-scoped and backed by agent-observability tools; authentication and project context come from the API token, so no per-server configuration is required.
      operationId: listConsoleMcpTools
      responses:
        "200":
          description: Built-in console server metadata and its tools.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/McpConsoleListResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      tags:
        - MCP
      summary: Execute a built-in console MCP tool (REST)
      description: Execute a tool on the built-in `console` MCP server via a direct REST call. The `tool` field names the tool and `arguments` supplies its parameters.
      operationId: executeConsoleMcpTool
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/McpConsoleExecuteRequest"
      responses:
        "200":
          description: Tool executed successfully.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/McpConsoleExecuteResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /mcp/console/message:
    post:
      tags:
        - MCP
      summary: Send a built-in console MCP JSON-RPC message
      description: "Send an MCP JSON-RPC 2.0 message to the built-in `console` MCP server. When a `sessionId` for an open SSE stream is supplied, the response is pushed through that stream and the HTTP call returns 202 Accepted; otherwise (stateless mode) the JSON-RPC response is returned directly in the HTTP body. Supported methods: `initialize` (returns capabilities and server info, protocol version 2024-11-05), `notifications/initialized` (acknowledgment, no response body — 202), `ping`, `tools/list`, and `tools/call` (execute a tool named by `params.name` with `params.arguments`)."
      operationId: sendConsoleMcpMessage
      parameters:
        - name: sessionId
          in: query
          required: false
          description: SSE session id from an open stream. When present, the JSON-RPC response is delivered over the SSE stream and this call returns 202 Accepted.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/McpJsonRpcRequest"
      responses:
        "200":
          description: JSON-RPC response (stateless mode, no active SSE session).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/McpJsonRpcResponse"
        "202":
          description: Accepted. The response was pushed over the SSE stream, or the message was a notification requiring no response.
        "400":
          description: JSON-RPC parse error or invalid request (e.g. missing `method`), returned in stateless mode.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/McpJsonRpcResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /mcp/console/sse:
    get:
      tags:
        - MCP
      summary: Open built-in console MCP SSE stream
      description: Open a Server-Sent Events stream for the built-in `console` MCP server. The stream immediately emits an `endpoint` event whose data is the URL the client must POST JSON-RPC messages to, including the generated `sessionId` query parameter. The session id is also returned in the `X-Mcp-Session-Id` response header.
      operationId: openConsoleMcpSse
      responses:
        "200":
          description: "SSE stream opened. The first event is `event: endpoint` whose data is the JSON-RPC message endpoint URL."
          headers:
            X-Mcp-Session-Id:
              description: Generated SSE session id, also embedded in the endpoint URL.
              schema:
                type: string
            Cache-Control:
              description: no-cache, no-transform
              schema:
                type: string
          content:
            text/event-stream:
              schema:
                type: string
                description: "Server-Sent Events stream. Opens with `event: endpoint` followed by JSON-RPC response payloads pushed as they are produced."
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /mcp/hubs:
    get:
      tags:
        - MCP Hubs
      summary: List MCP hubs
      description: Enterprise / license-gated (module `mcp-hub`). Lists the curated MCP hubs (server catalogs) visible to this API token. Because the token is the caller's identity, both `token`- and `public`-exposure active hubs are returned. Read-only discovery surface — execution is not proxied here.
      operationId: listMcpHubs
      responses:
        "200":
          description: Hubs visible to the token.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/McpHubList"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
  /mcp/hubs/{hubKey}:
    get:
      tags:
        - MCP Hubs
      summary: Get an MCP hub
      description: Enterprise / license-gated (module `mcp-hub`). Returns the hub summary plus the first page of its server catalog (MCP-Registry-style envelope). Only `active` hubs are returned. Supports the same search/pagination query params as the servers listing.
      operationId: getMcpHub
      parameters:
        - name: hubKey
          in: path
          required: true
          description: Stable hub key.
          schema:
            type: string
        - name: search
          in: query
          required: false
          description: Free-text filter over catalog member servers.
          schema:
            type: string
        - name: cursor
          in: query
          required: false
          description: Opaque pagination cursor from a previous page's `metadata.nextCursor`.
          schema:
            type: string
        - name: limit
          in: query
          required: false
          description: Maximum number of catalog entries to return.
          schema:
            type: integer
      responses:
        "200":
          description: Hub info plus the first catalog page.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/McpHubDetail"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /mcp/hubs/{hubKey}/servers:
    get:
      tags:
        - MCP Hubs
      summary: List / search an MCP hub's servers
      description: Enterprise / license-gated (module `mcp-hub`). Lists (or searches) the member servers of a hub, cursor-paginated. Responses follow the MCP-Registry envelope (`{ servers, metadata }`) and are whitelist-serialized — no upstream auth, stdio env, or vault material is exposed. Catalog entries point at the existing per-server endpoints for execution.
      operationId: listMcpHubServers
      parameters:
        - name: hubKey
          in: path
          required: true
          description: Stable hub key.
          schema:
            type: string
        - name: search
          in: query
          required: false
          description: Free-text filter over catalog member servers.
          schema:
            type: string
        - name: cursor
          in: query
          required: false
          description: Opaque pagination cursor from a previous page's `metadata.nextCursor`.
          schema:
            type: string
        - name: limit
          in: query
          required: false
          description: Maximum number of catalog entries to return.
          schema:
            type: integer
      responses:
        "200":
          description: A page of the hub's server catalog.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/McpHubCatalogPage"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /mcp/{serverKey}:
    patch:
      tags:
        - MCP
      summary: Update an MCP server
      description: Partially update an MCP server definition resolved by key within the token's project. Requires an API token with `write` permission for this service.
      operationId: updateMcpServer
      parameters:
        - name: serverKey
          in: path
          required: true
          description: Unique MCP server key.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/McpUpdateInput"
      responses:
        "200":
          description: The updated MCP server (secrets masked).
          content:
            application/json:
              schema:
                type: object
                properties:
                  server:
                    $ref: "#/components/schemas/McpServer"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "402":
          description: Payment Required — persistent sandbox execution requires an active Enterprise license.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Error"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - MCP
      summary: Delete an MCP server
      description: Delete an MCP server definition resolved by key within the token's project. Requires an API token with `write` permission for this service.
      operationId: deleteMcpServer
      parameters:
        - name: serverKey
          in: path
          required: true
          description: Unique MCP server key.
          schema:
            type: string
      responses:
        "200":
          description: The MCP server was deleted.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                    description: Always true when the resource was deleted.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /mcp/{serverKey}/execute:
    get:
      tags:
        - MCP
      summary: List MCP server tools
      description: Return the MCP server's metadata and its enabled tools (name, description and input schema). Scoped to the API token's project.
      operationId: listMcpServerTools
      parameters:
        - name: serverKey
          in: path
          required: true
          description: MCP server key.
          schema:
            type: string
      responses:
        "200":
          description: MCP server metadata and available tools.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/McpListToolsResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      tags:
        - MCP
      summary: Execute an MCP tool (REST)
      description: Execute a tool on the MCP server via a direct REST call (streamable-http exposure must be enabled). The `tool` field names the tool to run and `arguments` supplies its parameters. Caller-supplied runtime headers may be passed under `runtime_context` and are forwarded upstream when permitted by the server's header policy.
      operationId: executeMcpServerTool
      parameters:
        - name: serverKey
          in: path
          required: true
          description: MCP server key.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/McpExecuteRequest"
      responses:
        "200":
          description: Tool executed successfully.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/McpExecuteResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
        "502":
          description: Upstream tool execution failed.
          content:
            application/json:
              schema:
                type: object
                properties:
                  error:
                    type: string
  /mcp/{serverKey}/message:
    post:
      tags:
        - MCP
      summary: Send an MCP JSON-RPC message
      description: "Send an MCP JSON-RPC 2.0 message to the server. When a `sessionId` for an open SSE stream is supplied, the response is pushed through that stream and the HTTP call returns 202 Accepted; otherwise (stateless mode) the JSON-RPC response is returned directly in the HTTP body. Supported methods: `initialize` (returns capabilities and server info, protocol version 2025-03-26), `notifications/initialized` (acknowledgment, no response body — 202), `ping` (health check), `tools/list` (list enabled tools with schemas), and `tools/call` (execute a tool named by `params.name` with `params.arguments`; request-scoped runtime context may ride in `params._meta.runtime_context`)."
      operationId: sendMcpServerMessage
      parameters:
        - name: serverKey
          in: path
          required: true
          description: MCP server key.
          schema:
            type: string
        - name: sessionId
          in: query
          required: false
          description: SSE session id from an open stream. When present, the JSON-RPC response is delivered over the SSE stream and this call returns 202 Accepted.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/McpJsonRpcRequest"
      responses:
        "200":
          description: JSON-RPC response (stateless mode, no active SSE session).
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/McpJsonRpcResponse"
        "202":
          description: Accepted. The response was pushed over the SSE stream, or the message was a notification requiring no response.
        "400":
          description: JSON-RPC parse error or invalid request (e.g. missing `method`), returned in stateless mode.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/McpJsonRpcResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /mcp/{serverKey}/refresh-tools:
    post:
      tags:
        - MCP
      summary: Refresh MCP tools
      description: Re-run tool discovery against the server's source and persist the refreshed tool set. Requires an API token with `write` permission for this service.
      operationId: refreshMcpServerTools
      parameters:
        - name: serverKey
          in: path
          required: true
          description: Unique MCP server key.
          schema:
            type: string
      responses:
        "200":
          description: The MCP server with its refreshed tools.
          content:
            application/json:
              schema:
                type: object
                properties:
                  server:
                    $ref: "#/components/schemas/McpServer"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /mcp/{serverKey}/sse:
    get:
      tags:
        - MCP
      summary: Open MCP SSE stream
      description: Open a Server-Sent Events stream implementing the MCP protocol over SSE transport (the server's `sse` exposure must be enabled). The stream immediately emits an `endpoint` event whose data is the URL the client must POST JSON-RPC messages to, including the generated `sessionId` query parameter. The session id is also returned in the `X-Mcp-Session-Id` response header.
      operationId: openMcpServerSse
      parameters:
        - name: serverKey
          in: path
          required: true
          description: MCP server key.
          schema:
            type: string
      responses:
        "200":
          description: "SSE stream opened. The first event is `event: endpoint` whose data is the JSON-RPC message endpoint URL."
          headers:
            X-Mcp-Session-Id:
              description: Generated SSE session id, also embedded in the endpoint URL.
              schema:
                type: string
            Cache-Control:
              description: no-cache, no-transform
              schema:
                type: string
          content:
            text/event-stream:
              schema:
                type: string
                description: "Server-Sent Events stream. Opens with `event: endpoint` followed by JSON-RPC response payloads pushed as they are produced."
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /memory/stores:
    get:
      tags:
        - Memory
      summary: List memory stores
      description: Lists memory stores scoped to the authenticated tenant and project. Supports optional filtering by search term and status.
      operationId: listMemoryStores
      parameters:
        - name: search
          in: query
          required: false
          description: Search stores by name or description.
          schema:
            type: string
        - name: status
          in: query
          required: false
          description: Filter by store status.
          schema:
            type: string
            enum:
              - active
              - inactive
              - error
      responses:
        "200":
          description: List of memory stores.
          content:
            application/json:
              schema:
                type: object
                properties:
                  stores:
                    type: array
                    items:
                      $ref: "#/components/schemas/MemoryStore"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      tags:
        - Memory
      summary: Create memory store
      description: Creates a new memory store bound to a vector provider and embedding model.
      operationId: createMemoryStore
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MemoryStoreCreateRequest"
      responses:
        "201":
          description: The created memory store.
          content:
            application/json:
              schema:
                type: object
                properties:
                  store:
                    $ref: "#/components/schemas/MemoryStore"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "409":
          $ref: "#/components/responses/Conflict"
        "500":
          $ref: "#/components/responses/InternalError"
  /memory/stores/{storeKey}:
    get:
      tags:
        - Memory
      summary: Get memory store
      description: Returns the memory store identified by `storeKey`.
      operationId: getMemoryStore
      parameters:
        - name: storeKey
          in: path
          required: true
          description: Unique key of the memory store.
          schema:
            type: string
      responses:
        "200":
          description: The memory store.
          content:
            application/json:
              schema:
                type: object
                properties:
                  store:
                    $ref: "#/components/schemas/MemoryStore"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    patch:
      tags:
        - Memory
      summary: Update memory store
      description: Updates mutable fields of the memory store identified by `storeKey`. All fields are optional.
      operationId: updateMemoryStore
      parameters:
        - name: storeKey
          in: path
          required: true
          description: Unique key of the memory store.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MemoryStoreUpdateRequest"
      responses:
        "200":
          description: The updated memory store.
          content:
            application/json:
              schema:
                type: object
                properties:
                  store:
                    $ref: "#/components/schemas/MemoryStore"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - Memory
      summary: Delete memory store
      description: Deletes the memory store identified by `storeKey` and its vector index.
      operationId: deleteMemoryStore
      parameters:
        - name: storeKey
          in: path
          required: true
          description: Unique key of the memory store.
          schema:
            type: string
      responses:
        "200":
          description: Deletion succeeded.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /memory/stores/{storeKey}/memories:
    get:
      tags:
        - Memory
      summary: List memories
      description: Lists memory items in the store identified by `storeKey`. Supports scope, tag, status, search, and pagination filters.
      operationId: listMemoryItems
      parameters:
        - name: storeKey
          in: path
          required: true
          description: Unique key of the memory store.
          schema:
            type: string
        - name: scope
          in: query
          required: false
          description: Filter by memory scope.
          schema:
            type: string
            enum:
              - user
              - agent
              - session
              - global
        - name: scopeId
          in: query
          required: false
          description: Filter by scope id.
          schema:
            type: string
        - name: tags
          in: query
          required: false
          description: Comma-separated tag filter.
          schema:
            type: string
        - name: status
          in: query
          required: false
          description: Filter by memory status.
          schema:
            type: string
            enum:
              - active
              - archived
              - expired
        - name: search
          in: query
          required: false
          description: Full-text search in content.
          schema:
            type: string
        - name: limit
          in: query
          required: false
          description: Page size (default 50).
          schema:
            type: integer
            default: 50
        - name: skip
          in: query
          required: false
          description: Offset for pagination.
          schema:
            type: integer
      responses:
        "200":
          description: Paginated list of memory items.
          content:
            application/json:
              schema:
                type: object
                properties:
                  items:
                    type: array
                    items:
                      $ref: "#/components/schemas/MemoryItem"
                  total:
                    type: integer
                    description: Total number of matching items.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      tags:
        - Memory
      summary: Add memory
      description: Adds a single memory item to the store identified by `storeKey`. The embedding is generated automatically from the content.
      operationId: addMemory
      parameters:
        - name: storeKey
          in: path
          required: true
          description: Unique key of the memory store.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MemoryCreateRequest"
      responses:
        "201":
          description: The created memory item.
          content:
            application/json:
              schema:
                type: object
                properties:
                  memory:
                    $ref: "#/components/schemas/MemoryItem"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - Memory
      summary: Bulk delete memories
      description: Delete memories in a store in bulk, optionally filtered by scope, scope id, and/or tags. With no filters, clears the entire store.
      operationId: bulkDeleteMemories
      parameters:
        - name: storeKey
          in: path
          required: true
          schema:
            type: string
          description: Memory store key.
        - name: scope
          in: query
          required: false
          schema:
            type: string
            enum:
              - user
              - agent
              - session
              - global
          description: Only delete memories in this scope.
        - name: scopeId
          in: query
          required: false
          schema:
            type: string
          description: Only delete memories with this scope id (e.g. a specific user or session id).
        - name: tags
          in: query
          required: false
          schema:
            type: string
          description: Comma-separated tags; only delete memories matching all of them.
      responses:
        "200":
          description: Number of memories deleted.
          content:
            application/json:
              schema:
                type: object
                properties:
                  deleted:
                    type: integer
                    description: Count of deleted memories.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /memory/stores/{storeKey}/memories/batch:
    post:
      tags:
        - Memory
      summary: Add memories in batch
      description: Adds up to 100 memory items to the store identified by `storeKey` in a single request. Each memory must include a `content` field.
      operationId: addMemoryBatch
      parameters:
        - name: storeKey
          in: path
          required: true
          description: Unique key of the memory store.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MemoryBatchRequest"
      responses:
        "201":
          description: Result of the batch insert.
          content:
            application/json:
              schema:
                type: object
                description: Batch insert result containing the created memory items and counts.
                additionalProperties: true
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /memory/stores/{storeKey}/memories/{memoryId}:
    get:
      tags:
        - Memory
      summary: Get memory
      description: Returns the memory item identified by `memoryId` within the store identified by `storeKey`.
      operationId: getMemoryItem
      parameters:
        - name: storeKey
          in: path
          required: true
          description: Unique key of the memory store.
          schema:
            type: string
        - name: memoryId
          in: path
          required: true
          description: Identifier of the memory item.
          schema:
            type: string
      responses:
        "200":
          description: The memory item.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MemoryItem"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    patch:
      tags:
        - Memory
      summary: Update memory
      description: Updates the memory item identified by `memoryId`. Only `content`, `metadata`, `tags`, `importance`, and `status` may be updated. If content changes, the embedding is regenerated automatically. At least one valid field must be supplied.
      operationId: updateMemoryItem
      parameters:
        - name: storeKey
          in: path
          required: true
          description: Unique key of the memory store.
          schema:
            type: string
        - name: memoryId
          in: path
          required: true
          description: Identifier of the memory item.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MemoryUpdateRequest"
      responses:
        "200":
          description: The updated memory item.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MemoryItem"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - Memory
      summary: Delete memory
      description: Deletes the memory item identified by `memoryId` from the store identified by `storeKey`.
      operationId: deleteMemoryItem
      parameters:
        - name: storeKey
          in: path
          required: true
          description: Unique key of the memory store.
          schema:
            type: string
        - name: memoryId
          in: path
          required: true
          description: Identifier of the memory item.
          schema:
            type: string
      responses:
        "200":
          description: Deletion succeeded.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /memory/stores/{storeKey}/recall:
    post:
      tags:
        - Memory
      summary: Recall memories for chat
      description: Performs a semantic recall against the store identified by `storeKey` and returns a formatted context string plus the matching memories, suitable for injecting into a chat prompt. Snake_case aliases (`max_tokens`, `scope_id`, `top_k`) are also accepted.
      operationId: recallMemories
      parameters:
        - name: storeKey
          in: path
          required: true
          description: Unique key of the memory store.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MemoryRecallRequest"
      responses:
        "200":
          description: Recall result with a formatted context string and matching memories.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MemoryRecallResult"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /memory/stores/{storeKey}/search:
    post:
      tags:
        - Memory
      summary: Semantic search
      description: Performs a semantic similarity search against the store identified by `storeKey`. Snake_case aliases (`min_score`, `scope_id`, `top_k`) are also accepted.
      operationId: searchMemories
      parameters:
        - name: storeKey
          in: path
          required: true
          description: Unique key of the memory store.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/MemorySearchRequest"
      responses:
        "200":
          description: Search result with matching memories.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MemorySearchResult"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /moderations:
    post:
      tags:
        - Moderations
      summary: Create moderation
      description: OpenAI-compatible moderation endpoint that classifies text against a console guardrail. The `model` field selects the guardrail key to evaluate against; when omitted, the tenant's first enabled preset guardrail with an active moderation policy is used. Returns a single non-streaming JSON object with one result per input.
      operationId: createModeration
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ModModerationRequest"
            example:
              input: Text to classify
              model: default-moderation
      responses:
        "200":
          description: Moderation classification result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ModModerationResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /monitoring/inference:
    get:
      tags:
        - Monitoring
      summary: Inference server metrics summary
      description: Returns a per-server latest-metrics snapshot plus an aggregate overview for the tenant's inference servers. Tenant-scoped (inference servers are not project-scoped). Server `apiKey` values are stripped from the response. `inference-monitoring` is an admin RBAC service, so only owner/admin tokens or tokens with an explicit `inference-monitoring:read` grant may call it; insufficient permission returns 403.
      operationId: getMonitoringInference
      parameters:
        - name: from
          in: query
          required: false
          description: Inclusive lower bound for the metrics window (ISO 8601 or dashboard relative range).
          schema:
            type: string
            format: date-time
        - name: to
          in: query
          required: false
          description: Inclusive upper bound for the metrics window (ISO 8601 or dashboard relative range).
          schema:
            type: string
            format: date-time
      responses:
        "200":
          description: Inference monitoring summary.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/MonitoringInference"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
  /ocr:
    post:
      tags:
        - OCR
      summary: Extract a document (synchronous OCR)
      description: Extracts text, tables, and structured data from a single document in one request, returning the provider result inline. Accepts either a multipart file upload or a JSON body with a document URL or base64 bytes.
      operationId: createOcrExtraction
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              $ref: "#/components/schemas/OcrMultipartRequest"
          application/json:
            schema:
              $ref: "#/components/schemas/OcrRequest"
      responses:
        "200":
          description: Extracted document result with request_id merged in. Exact fields depend on the model and requested features.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/OcrResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"
  /ocr-jobs:
    get:
      tags:
        - OCR
      summary: List OCR jobs
      description: Lists OCR jobs for the authenticated project, optionally filtered by status and capped by limit.
      operationId: listOcrJobs
      parameters:
        - name: status
          in: query
          required: false
          description: Filter jobs by status (e.g. active, paused, archived).
          schema:
            type: string
        - name: limit
          in: query
          required: false
          description: Maximum number of jobs to return.
          schema:
            type: integer
      responses:
        "200":
          description: List of OCR jobs.
          content:
            application/json:
              schema:
                type: object
                properties:
                  jobs:
                    type: array
                    items:
                      $ref: "#/components/schemas/OcrJob"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      tags:
        - OCR
      summary: Create an OCR job
      description: Creates a persistent OCR job container holding processing rules, a storage bucket, and an optional callback. Files are added to the job over time and processed per-file.
      operationId: createOcrJob
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/OcrCreateJobRequest"
      responses:
        "201":
          description: The created OCR job.
          content:
            application/json:
              schema:
                type: object
                properties:
                  job:
                    $ref: "#/components/schemas/OcrJob"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /ocr-jobs/{id}:
    get:
      tags:
        - OCR
      summary: Get an OCR job
      description: Returns a single OCR job with live progress and rolling usage/cost totals, doubling as the status endpoint.
      operationId: getOcrJob
      parameters:
        - name: id
          in: path
          required: true
          description: OCR job ID.
          schema:
            type: string
      responses:
        "200":
          description: The OCR job.
          content:
            application/json:
              schema:
                type: object
                properties:
                  job:
                    $ref: "#/components/schemas/OcrJob"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    patch:
      tags:
        - OCR
      summary: Update an OCR job
      description: Updates any subset of an OCR job's fields, such as name, status, models, outputs, or callback settings.
      operationId: updateOcrJob
      parameters:
        - name: id
          in: path
          required: true
          description: OCR job ID.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/OcrUpdateJobRequest"
      responses:
        "200":
          description: The updated OCR job.
          content:
            application/json:
              schema:
                type: object
                properties:
                  job:
                    $ref: "#/components/schemas/OcrJob"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - OCR
      summary: Delete an OCR job
      description: Deletes an OCR job.
      operationId: deleteOcrJob
      parameters:
        - name: id
          in: path
          required: true
          description: OCR job ID.
          schema:
            type: string
      responses:
        "200":
          description: Deletion acknowledgement.
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok:
                    type: boolean
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /ocr-jobs/{id}/export:
    get:
      tags:
        - OCR
      summary: Export OCR job results
      description: Downloads all items of an OCR job in the requested format as an attachment.
      operationId: exportOcrJob
      parameters:
        - name: id
          in: path
          required: true
          description: OCR job ID.
          schema:
            type: string
        - name: format
          in: query
          required: false
          description: Export format. Defaults to json.
          schema:
            type: string
            enum:
              - json
              - jsonl
              - csv
            default: json
      responses:
        "200":
          description: The exported job results as a downloadable attachment. Content-Type depends on the requested format.
          content:
            application/json:
              schema:
                type: object
                properties:
                  job:
                    $ref: "#/components/schemas/OcrJob"
                  items:
                    type: array
                    items:
                      $ref: "#/components/schemas/OcrJobItem"
            application/x-ndjson:
              schema:
                type: string
                description: One serialized item per line (JSONL).
            text/csv:
              schema:
                type: string
                description: "CSV with columns: index, file_name, status, full_text, summary, structured, total_tokens, cost_total."
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /ocr-jobs/{id}/files:
    post:
      tags:
        - OCR
      summary: Add files to an OCR job
      description: Adds one or more files to an OCR job. Files sent with mode sync are processed before the response returns (200); mode async (default) queues them and returns immediately (202). Accepts multipart uploads or a JSON items array.
      operationId: addOcrJobFiles
      parameters:
        - name: id
          in: path
          required: true
          description: OCR job ID.
          schema:
            type: string
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              $ref: "#/components/schemas/OcrAddFilesMultipartRequest"
          application/json:
            schema:
              $ref: "#/components/schemas/OcrAddFilesRequest"
      responses:
        "200":
          description: Files processed synchronously; the created items are returned.
          content:
            application/json:
              schema:
                type: object
                properties:
                  items:
                    type: array
                    items:
                      $ref: "#/components/schemas/OcrJobItem"
        "202":
          description: Files queued for asynchronous processing; the created items are returned.
          content:
            application/json:
              schema:
                type: object
                properties:
                  items:
                    type: array
                    items:
                      $ref: "#/components/schemas/OcrJobItem"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"
  /ocr-jobs/{id}/items:
    get:
      tags:
        - OCR
      summary: List OCR job items
      description: Lists the items (per-file results) of an OCR job, optionally paginated and filtered by status.
      operationId: listOcrJobItems
      parameters:
        - name: id
          in: path
          required: true
          description: OCR job ID.
          schema:
            type: string
        - name: limit
          in: query
          required: false
          description: Maximum number of items to return.
          schema:
            type: integer
        - name: skip
          in: query
          required: false
          description: Number of items to skip (for pagination).
          schema:
            type: integer
        - name: status
          in: query
          required: false
          description: Filter items by status (e.g. queued, succeeded, failed).
          schema:
            type: string
      responses:
        "200":
          description: List of OCR job items.
          content:
            application/json:
              schema:
                type: object
                properties:
                  items:
                    type: array
                    items:
                      $ref: "#/components/schemas/OcrJobItem"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /ocr-jobs/{id}/items/{itemId}:
    get:
      tags:
        - OCR
      summary: Get an OCR job item
      description: Returns a single item (per-file result) of an OCR job.
      operationId: getOcrJobItem
      parameters:
        - name: id
          in: path
          required: true
          description: OCR job ID.
          schema:
            type: string
        - name: itemId
          in: path
          required: true
          description: OCR job item ID.
          schema:
            type: string
      responses:
        "200":
          description: The OCR job item.
          content:
            application/json:
              schema:
                type: object
                properties:
                  item:
                    $ref: "#/components/schemas/OcrJobItem"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /ocr-jobs/{id}/pause:
    post:
      tags:
        - OCR
      summary: Pause an OCR job
      description: Sets the job status to paused, holding intake and processing until resumed.
      operationId: pauseOcrJob
      parameters:
        - name: id
          in: path
          required: true
          description: OCR job ID.
          schema:
            type: string
      responses:
        "200":
          description: The paused OCR job.
          content:
            application/json:
              schema:
                type: object
                properties:
                  job:
                    $ref: "#/components/schemas/OcrJob"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /ocr-jobs/{id}/resume:
    post:
      tags:
        - OCR
      summary: Resume an OCR job
      description: Sets the job status back to active, resuming intake and processing.
      operationId: resumeOcrJob
      parameters:
        - name: id
          in: path
          required: true
          description: OCR job ID.
          schema:
            type: string
      responses:
        "200":
          description: The resumed OCR job.
          content:
            application/json:
              schema:
                type: object
                properties:
                  job:
                    $ref: "#/components/schemas/OcrJob"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /ocr-jobs/{id}/usage:
    get:
      tags:
        - OCR
      summary: Get OCR job usage
      description: Returns aggregate token and cost accounting for an OCR job, along with item progress counters.
      operationId: getOcrJobUsage
      parameters:
        - name: id
          in: path
          required: true
          description: OCR job ID.
          schema:
            type: string
      responses:
        "200":
          description: Aggregate usage and cost for the job.
          content:
            application/json:
              schema:
                type: object
                properties:
                  usage:
                    $ref: "#/components/schemas/OcrJobUsageDetail"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /pii/detect:
    post:
      tags:
        - PII
      summary: Detect PII against a policy
      description: Return findings without transforming the text, using the stored policy's enabled categories, custom patterns, languages and severities. The action is pinned to `detect`, so `output_text` equals the input.
      operationId: piiDetect
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/PiiPolicyRequest"
      responses:
        "200":
          description: Detection result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/PiiScanResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /pii/detokenize:
    post:
      tags:
        - PII
      summary: Detokenize text using a vault
      description: Reverse a prior `/pii/tokenize` call, restoring original values from the vault. No `policy_key` is needed — the vault fully determines the reversal. Tokens absent from the vault are left untouched. The call is stateless; no PII is persisted server-side.
      operationId: piiDetokenize
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/PiiDetokenizeRequest"
      responses:
        "200":
          description: Text with tokens replaced by their original values.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/PiiDetokenizeResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /pii/mask:
    post:
      tags:
        - PII
      summary: Mask PII against a policy
      description: Partially obfuscate each match while preserving recognizable edges (e.g. `j*******@acme.com`), using the stored policy's configuration. The action is pinned to `mask`.
      operationId: piiMask
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/PiiPolicyRequest"
      responses:
        "200":
          description: Masking result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/PiiScanResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /pii/policies:
    post:
      tags:
        - PII
      summary: Create a PII policy
      description: Create a PII detection policy (categories, custom patterns, languages, default action) referenced by the `/pii/*` detection endpoints. Requires an API token with `write` permission for this service.
      operationId: createPiiPolicy
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/PiiPolicyCreateInput"
      responses:
        "201":
          description: The created PII policy.
          content:
            application/json:
              schema:
                type: object
                properties:
                  policy:
                    $ref: "#/components/schemas/PiiPolicyRecord"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
  /pii/policies/{key}:
    patch:
      tags:
        - PII
      summary: Update a PII policy
      description: Partially update a PII policy resolved by key within the token's project. Requires an API token with `write` permission for this service.
      operationId: updatePiiPolicy
      parameters:
        - name: key
          in: path
          required: true
          description: Unique PII policy key.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/PiiPolicyUpdateInput"
      responses:
        "200":
          description: The updated PII policy.
          content:
            application/json:
              schema:
                type: object
                properties:
                  policy:
                    $ref: "#/components/schemas/PiiPolicyRecord"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - PII
      summary: Delete a PII policy
      description: Delete a PII policy resolved by key within the token's project. Requires an API token with `write` permission for this service.
      operationId: deletePiiPolicy
      parameters:
        - name: key
          in: path
          required: true
          description: Unique PII policy key.
          schema:
            type: string
      responses:
        "200":
          description: The PII policy was deleted.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                    description: Always true when the resource was deleted.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /pii/redact:
    post:
      tags:
        - PII
      summary: Redact PII against a policy
      description: Replace each match with `[REDACTED_<CATEGORY>]` using the stored policy's configuration. The action is pinned to `redact`.
      operationId: piiRedact
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/PiiPolicyRequest"
      responses:
        "200":
          description: Redaction result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/PiiScanResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /pii/scan:
    post:
      tags:
        - PII
      summary: Scan PII with a policy (action chosen by policy or override)
      description: Like the named endpoints, but the applied action comes from the policy's default unless an explicit `action` override is supplied. When the effective action is `tokenize`, the response includes a `vault`.
      operationId: piiScan
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/PiiPolicyRequest"
      responses:
        "200":
          description: Scan result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/PiiScanResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /pii/tokenize:
    post:
      tags:
        - PII
      summary: Tokenize PII (reversible masking) against a policy
      description: Replace each match with a unique, reversible token (`[EMAIL_1]`, `[IPADDRESS_1]`, …) and return a `vault` mapping every token back to its original value. Identical values share one token. Use with `/pii/detokenize` to round-trip text through an LLM without exposing PII. The action is pinned to `tokenize`.
      operationId: piiTokenize
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/PiiPolicyRequest"
      responses:
        "200":
          description: Tokenization result, including the `vault`.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/PiiScanResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /prompts:
    post:
      tags:
        - Prompts
      summary: Create a prompt
      description: Create a prompt template. The initial content becomes version 1. Requires an API token with `write` permission for this service.
      operationId: createPrompt
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/PromptCreateInput"
      responses:
        "201":
          description: The created prompt.
          content:
            application/json:
              schema:
                type: object
                properties:
                  prompt:
                    $ref: "#/components/schemas/PromptView"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
    get:
      tags:
        - Prompts
      summary: List prompts
      description: Returns all prompt templates in the token's project. Optionally filter by name or key using the `search` query parameter.
      operationId: listPrompts
      parameters:
        - name: search
          in: query
          required: false
          description: Case-insensitive filter applied to prompt name and key.
          schema:
            type: string
      responses:
        "200":
          description: List of prompts.
          content:
            application/json:
              schema:
                type: object
                properties:
                  prompts:
                    type: array
                    items:
                      $ref: "#/components/schemas/PromptView"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /prompts/{key}:
    patch:
      tags:
        - Prompts
      summary: Update a prompt
      description: Partially update a prompt resolved by key within the token's project. Changing the template creates a new version. Requires an API token with `write` permission for this service.
      operationId: updatePrompt
      parameters:
        - name: key
          in: path
          required: true
          description: Unique prompt key.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/PromptUpdateInput"
      responses:
        "200":
          description: The updated prompt.
          content:
            application/json:
              schema:
                type: object
                properties:
                  prompt:
                    $ref: "#/components/schemas/PromptView"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - Prompts
      summary: Delete a prompt
      description: Delete a prompt (and its versions) resolved by key within the token's project. Requires an API token with `write` permission for this service.
      operationId: deletePrompt
      parameters:
        - name: key
          in: path
          required: true
          description: Unique prompt key.
          schema:
            type: string
      responses:
        "200":
          description: The prompt was deleted.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                    description: Always true when the resource was deleted.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    get:
      tags:
        - Prompts
      summary: Get a prompt by key
      description: Resolves a single prompt by its key. When `environment` is supplied the version currently deployed to that environment is resolved; when `version` is supplied that specific version is resolved. Without either, the prompt's current/latest version is returned.
      operationId: getPromptByKey
      parameters:
        - name: key
          in: path
          required: true
          description: Unique key of the prompt.
          schema:
            type: string
        - name: environment
          in: query
          required: false
          description: Resolve the version deployed to this environment.
          schema:
            type: string
            enum:
              - dev
              - staging
              - prod
        - name: version
          in: query
          required: false
          description: Resolve a specific version number (must be a positive integer).
          schema:
            type: integer
            minimum: 1
      responses:
        "200":
          description: Prompt with its resolved version.
          content:
            application/json:
              schema:
                type: object
                properties:
                  prompt:
                    $ref: "#/components/schemas/PromptView"
                  resolvedVersion:
                    nullable: true
                    allOf:
                      - $ref: "#/components/schemas/PromptResolvedVersion"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /prompts/{key}/compare:
    get:
      tags:
        - Prompts
      summary: Compare two prompt versions
      description: Returns a side-by-side comparison of two versions of a prompt, including a line-level template diff, a metadata diff, deployment history, and comments.
      operationId: comparePromptVersions
      parameters:
        - name: key
          in: path
          required: true
          description: Unique key of the prompt.
          schema:
            type: string
        - name: fromVersionId
          in: query
          required: true
          description: Identifier of the base version to compare from.
          schema:
            type: string
        - name: toVersionId
          in: query
          required: true
          description: Identifier of the target version to compare to.
          schema:
            type: string
      responses:
        "200":
          description: Version comparison.
          content:
            application/json:
              schema:
                type: object
                properties:
                  comparison:
                    $ref: "#/components/schemas/PromptCompare"
                  prompt:
                    type: object
                    properties:
                      id:
                        type: string
                      key:
                        type: string
                      name:
                        type: string
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /prompts/{key}/deployments:
    get:
      tags:
        - Prompts
      summary: List prompt deployments
      description: Returns the current deployment state for each environment plus the deployment event history for the prompt.
      operationId: listPromptDeployments
      parameters:
        - name: key
          in: path
          required: true
          description: Unique key of the prompt.
          schema:
            type: string
      responses:
        "200":
          description: Deployment state and history.
          content:
            application/json:
              schema:
                type: object
                properties:
                  deployments:
                    $ref: "#/components/schemas/PromptDeployments"
                  prompt:
                    type: object
                    properties:
                      id:
                        type: string
                      key:
                        type: string
                      name:
                        type: string
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      tags:
        - Prompts
      summary: Mutate a prompt deployment
      description: "Performs a deployment action for a prompt in a given environment. Supported actions: `promote` (set a version active — requires `versionId`), `plan` (schedule a version for later activation — requires `versionId`), `activate` (activate a planned deployment), and `rollback` (revert to the previous version)."
      operationId: mutatePromptDeployment
      parameters:
        - name: key
          in: path
          required: true
          description: Unique key of the prompt.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - action
                - environment
              properties:
                action:
                  type: string
                  enum:
                    - promote
                    - plan
                    - activate
                    - rollback
                  description: Deployment action to perform.
                environment:
                  type: string
                  enum:
                    - dev
                    - staging
                    - prod
                  description: Target environment for the action.
                versionId:
                  type: string
                  description: Version to deploy. Required for `promote` and `plan` actions.
                note:
                  type: string
                  description: Optional note recorded on the deployment event.
      responses:
        "200":
          description: Updated prompt and deployment state.
          content:
            application/json:
              schema:
                type: object
                properties:
                  deployments:
                    $ref: "#/components/schemas/PromptDeployments"
                  prompt:
                    $ref: "#/components/schemas/PromptView"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          $ref: "#/components/responses/Conflict"
        "500":
          $ref: "#/components/responses/InternalError"
  /prompts/{key}/render:
    post:
      tags:
        - Prompts
      summary: Render a prompt template
      description: Resolves the prompt (optionally for a given environment/version) and renders its Mustache template with the supplied variables. Variables may be passed under a `data` object; if `data` is omitted the request body itself is used as the variable map.
      operationId: renderPrompt
      parameters:
        - name: key
          in: path
          required: true
          description: Unique key of the prompt.
          schema:
            type: string
        - name: environment
          in: query
          required: false
          description: Resolve the version deployed to this environment before rendering.
          schema:
            type: string
            enum:
              - dev
              - staging
              - prod
        - name: version
          in: query
          required: false
          description: Render a specific version number (must be a positive integer).
          schema:
            type: integer
            minimum: 1
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                data:
                  type: object
                  additionalProperties: true
                  description: Template variables to interpolate into the Mustache template.
                  example:
                    name: Alice
                    company: Acme Corp
              additionalProperties: true
      responses:
        "200":
          description: Rendered prompt.
          content:
            application/json:
              schema:
                type: object
                properties:
                  rendered:
                    type: string
                    description: The template rendered with the supplied variables.
                    example: Hello Alice, welcome to Acme Corp!
                  prompt:
                    type: object
                    properties:
                      key:
                        type: string
                      name:
                        type: string
                      version:
                        type: integer
                      environment:
                        type: string
                        nullable: true
                        enum:
                          - dev
                          - staging
                          - prod
                          - null
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /prompts/{key}/versions:
    post:
      tags:
        - Prompts
      summary: Set the latest prompt version
      description: Re-point the prompt's `latest` pointer to an existing version id. Requires an API token with `write` permission for this service.
      operationId: setPromptLatestVersion
      parameters:
        - name: key
          in: path
          required: true
          description: Unique prompt key.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/PromptSetLatestInput"
      responses:
        "200":
          description: The prompt with its updated latest pointer.
          content:
            application/json:
              schema:
                type: object
                properties:
                  prompt:
                    $ref: "#/components/schemas/PromptView"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    get:
      tags:
        - Prompts
      summary: List prompt versions
      description: Returns the version history for a prompt, newest first, along with a minimal reference to the parent prompt.
      operationId: listPromptVersions
      parameters:
        - name: key
          in: path
          required: true
          description: Unique key of the prompt.
          schema:
            type: string
      responses:
        "200":
          description: Prompt version history.
          content:
            application/json:
              schema:
                type: object
                properties:
                  prompt:
                    type: object
                    properties:
                      key:
                        type: string
                      name:
                        type: string
                  versions:
                    type: array
                    items:
                      $ref: "#/components/schemas/PromptVersionSummary"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /rag/modules:
    post:
      tags:
        - Knowledge Engine
      summary: Create a RAG module
      description: Create a Knowledge Engine (RAG) module wiring an embedding model, vector store and chunking config. Requires an API token with `write` permission for this service.
      operationId: createRagModule
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RagCreateInput"
      responses:
        "201":
          description: The created RAG module.
          content:
            application/json:
              schema:
                type: object
                properties:
                  module:
                    $ref: "#/components/schemas/RagModule"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
    get:
      tags:
        - Knowledge Engine
      summary: List Knowledge Engine modules
      description: Returns all Knowledge Engine (RAG) modules available to the token's tenant.
      operationId: listRagModules
      responses:
        "200":
          description: List of Knowledge Engine modules.
          content:
            application/json:
              schema:
                type: object
                properties:
                  modules:
                    type: array
                    items:
                      $ref: "#/components/schemas/RagModule"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /rag/modules/{key}:
    patch:
      tags:
        - Knowledge Engine
      summary: Update a RAG module
      description: Partially update a RAG module resolved by key within the token's project. Requires an API token with `write` permission for this service.
      operationId: updateRagModule
      parameters:
        - name: key
          in: path
          required: true
          description: Unique RAG module key.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RagUpdateInput"
      responses:
        "200":
          description: The updated RAG module.
          content:
            application/json:
              schema:
                type: object
                properties:
                  module:
                    $ref: "#/components/schemas/RagModule"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    get:
      tags:
        - Knowledge Engine
      summary: Get a Knowledge Engine module
      description: Returns a single Knowledge Engine module by its key.
      operationId: getRagModule
      parameters:
        - name: key
          in: path
          required: true
          description: Unique key of the Knowledge Engine module.
          schema:
            type: string
      responses:
        "200":
          description: The Knowledge Engine module.
          content:
            application/json:
              schema:
                type: object
                properties:
                  module:
                    $ref: "#/components/schemas/RagModule"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - Knowledge Engine
      summary: Delete a Knowledge Engine module
      description: Deletes a Knowledge Engine module by its key, along with its documents and vectors.
      operationId: deleteRagModule
      parameters:
        - name: key
          in: path
          required: true
          description: Unique key of the Knowledge Engine module.
          schema:
            type: string
      responses:
        "200":
          description: Module deleted.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /rag/modules/{key}/documents:
    get:
      tags:
        - Knowledge Engine
      summary: List Knowledge Engine documents
      description: Returns the documents ingested into a Knowledge Engine module.
      operationId: listRagDocuments
      parameters:
        - name: key
          in: path
          required: true
          description: Unique key of the Knowledge Engine module.
          schema:
            type: string
      responses:
        "200":
          description: List of documents.
          content:
            application/json:
              schema:
                type: object
                properties:
                  documents:
                    type: array
                    items:
                      $ref: "#/components/schemas/RagDocument"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /rag/modules/{key}/documents/{documentId}:
    post:
      tags:
        - Knowledge Engine
      summary: Re-ingest a Knowledge Engine document
      description: Re-chunks and re-embeds an existing document. Optionally provide updated `content`, a new `data`/`base64` file, `contentType`, `fileName`, or `metadata`. Send an empty body to re-ingest with the existing content and current chunking settings.
      operationId: reingestRagDocument
      parameters:
        - name: key
          in: path
          required: true
          description: Unique key of the Knowledge Engine module.
          schema:
            type: string
        - name: documentId
          in: path
          required: true
          description: Identifier of the document to re-ingest.
          schema:
            type: string
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                content:
                  type: string
                  description: Updated raw text content.
                data:
                  type: string
                  description: Updated base64-encoded (or data-URI) file content.
                base64:
                  type: string
                  description: "Alias for `data`: updated base64-encoded file content."
                contentType:
                  type: string
                  description: MIME type of the supplied content or file.
                fileName:
                  type: string
                  description: Updated document file name.
                metadata:
                  type: object
                  additionalProperties: true
                  description: Updated metadata for the document.
                  example:
                    version: "3.0"
      responses:
        "200":
          description: Re-ingested document.
          content:
            application/json:
              schema:
                type: object
                properties:
                  document:
                    $ref: "#/components/schemas/RagDocument"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - Knowledge Engine
      summary: Delete a Knowledge Engine document
      description: Deletes a document record and all of its associated vectors from the vector store.
      operationId: deleteRagDocument
      parameters:
        - name: key
          in: path
          required: true
          description: Unique key of the Knowledge Engine module.
          schema:
            type: string
        - name: documentId
          in: path
          required: true
          description: Identifier of the document to delete.
          schema:
            type: string
      responses:
        "200":
          description: Document deleted.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    get:
      tags:
        - Knowledge Engine
      summary: Get a RAG document
      description: Fetch a single ingested document from a Knowledge Engine (RAG) module by its document id.
      operationId: getRagDocument
      parameters:
        - name: key
          in: path
          required: true
          schema:
            type: string
          description: Module key.
        - name: documentId
          in: path
          required: true
          schema:
            type: string
          description: Document identifier.
      responses:
        "200":
          description: The document.
          content:
            application/json:
              schema:
                type: object
                properties:
                  document:
                    $ref: "#/components/schemas/RagDocument"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /rag/modules/{key}/ingest:
    post:
      tags:
        - Knowledge Engine
      summary: Ingest a document into a Knowledge Engine module
      description: Ingests a document into a Knowledge Engine module. Provide `content` for raw text, or `data` for a base64-encoded (or data-URI) binary file which is converted to Markdown before chunking and embedding. `fileName` is always required.
      operationId: ingestRagDocument
      parameters:
        - name: key
          in: path
          required: true
          description: Unique key of the Knowledge Engine module.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - fileName
              properties:
                fileName:
                  type: string
                  description: Name of the document file.
                  example: faq.txt
                content:
                  type: string
                  description: Raw text content of the document. Mutually exclusive with `data`.
                data:
                  type: string
                  description: Base64-encoded file content (optionally as a `data:` URI). Mutually exclusive with `content`; converted to Markdown before chunking.
                contentType:
                  type: string
                  description: MIME type of the supplied content or file.
                  example: text/plain
                metadata:
                  type: object
                  additionalProperties: true
                  description: Arbitrary metadata stored with the document and its chunks.
                  example:
                    source: docs
                    version: "2.0"
      responses:
        "201":
          description: Ingested document.
          content:
            application/json:
              schema:
                type: object
                properties:
                  document:
                    $ref: "#/components/schemas/RagDocument"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"
  /rag/modules/{key}/query:
    post:
      tags:
        - Knowledge Engine
      summary: Query a Knowledge Engine module
      description: Runs a semantic retrieval query against a Knowledge Engine module and returns the most relevant chunk matches.
      operationId: queryRagModule
      parameters:
        - name: key
          in: path
          required: true
          description: Unique key of the Knowledge Engine module.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - query
              properties:
                query:
                  type: string
                  description: Natural-language query text.
                  example: How do I reset my password?
                topK:
                  type: integer
                  description: Maximum number of matches to return.
                  example: 5
                filter:
                  type: object
                  additionalProperties: true
                  description: Metadata filter applied to candidate chunks.
                  example:
                    source: docs
      responses:
        "200":
          description: Query results.
          content:
            application/json:
              schema:
                type: object
                properties:
                  result:
                    $ref: "#/components/schemas/RagQueryResult"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"
  /realtime:
    get:
      tags:
        - Realtime
      summary: Open a realtime session (WebSocket)
      description: |-
        **WebSocket endpoint (HTTP Upgrade required).** Enterprise / license-gated. Opens a bidirectional realtime session for streaming chat with an optional voice round-trip (STT on committed audio, TTS on responses). This is NOT a normal HTTP request — the client must perform a WebSocket handshake (`Upgrade: websocket`).

        `?model=` accepts either a realtime model key (a named preset bundling chat model or agent + STT + TTS + voice + instructions) or a raw chat model key for an ad-hoc session; `?agent=` starts an ad-hoc session generated by that agent. Authentication is resolved in order: `Authorization: Bearer cpeer_...`, `?api_key=`, or (for the dashboard playground) the same-origin session cookie. On auth/lookup failure the server sends a JSON `error` event and closes the socket with code `4401`.

        **Message protocol:** after the socket opens, the client sends JSON client events (`session.update`, `conversation.item.create`, `input_audio_buffer.append`/`commit`/`clear`, `response.create`, `response.cancel`) and receives JSON server events (`response.output_text.delta/done`, `response.audio.delta`, `response.done`, `error`, tool-status events). The response generator (model/agent) locks once the conversation starts.
      operationId: realtimeConnect
      parameters:
        - name: model
          in: query
          required: false
          description: Realtime model key (named preset) or a raw chat model key for an ad-hoc session. Used at handshake time to resolve the session preset.
          schema:
            type: string
        - name: agent
          in: query
          required: false
          description: Agent key — responses are generated by this agent instead of a raw model. Ignored when `model` resolves to a preset.
          schema:
            type: string
        - name: api_key
          in: query
          required: false
          description: "Client API token (`cpeer_...`) used as an alternative to the `Authorization: Bearer` header, since browser WebSocket clients cannot set custom headers."
          schema:
            type: string
      responses:
        "101":
          description: Switching Protocols — WebSocket connection established. The realtime event protocol runs over the upgraded connection.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /realtime/models:
    get:
      tags:
        - Realtime
      summary: List realtime models
      description: Enterprise / license-gated. Lists the realtime model presets (named session configs bundling chat model or agent + STT + TTS + voice + instructions) visible to the API token's project.
      operationId: listRealtimeModels
      responses:
        "200":
          description: List of realtime model presets.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RealtimeModelList"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      tags:
        - Realtime
      summary: Create a realtime model
      description: Enterprise / license-gated. Creates a realtime model preset. Provide either `chat_model_key` or `agent_key` as the response generator; add `stt_model_key`/`tts_model_key`/`voice` for voice or telephony sessions. `key` is auto-slugged from `name` when omitted.
      operationId: createRealtimeModel
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RealtimeModelCreateRequest"
      responses:
        "201":
          description: The created realtime model preset.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RealtimeModel"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
  /realtime/models/{id}:
    get:
      tags:
        - Realtime
      summary: Retrieve a realtime model
      description: Enterprise / license-gated. Fetches a single realtime model preset by its id.
      operationId: getRealtimeModel
      parameters:
        - name: id
          in: path
          required: true
          description: Realtime model id.
          schema:
            type: string
      responses:
        "200":
          description: The realtime model preset.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RealtimeModel"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    patch:
      tags:
        - Realtime
      summary: Update a realtime model
      description: Enterprise / license-gated. Partially updates a realtime model preset. Only supplied fields are changed; `key` cannot be changed. `status` toggles the preset between `active` and `disabled`.
      operationId: updateRealtimeModel
      parameters:
        - name: id
          in: path
          required: true
          description: Realtime model id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RealtimeModelUpdateRequest"
      responses:
        "200":
          description: The updated realtime model preset.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RealtimeModel"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - Realtime
      summary: Delete a realtime model
      description: Enterprise / license-gated. Permanently deletes a realtime model preset.
      operationId: deleteRealtimeModel
      parameters:
        - name: id
          in: path
          required: true
          description: Realtime model id.
          schema:
            type: string
      responses:
        "200":
          description: Deletion confirmation.
          content:
            application/json:
              schema:
                type: object
                properties:
                  deleted:
                    type: boolean
                    example: true
                  id:
                    type: string
                    description: Id of the deleted realtime model.
                required:
                  - deleted
                  - id
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /realtime/twilio:
    get:
      tags:
        - Realtime
      summary: Twilio Media Streams bridge (WebSocket)
      description: |-
        **WebSocket endpoint (HTTP Upgrade required).** Enterprise / license-gated. Bridges a Twilio Media Streams call to a realtime session for inbound/outbound phone calls. Paste the URL into TwiML: `<Connect><Stream url="wss://<host>/api/client/v1/realtime/twilio?api_key=KEY&model=support-line"/></Connect>`.

        `?model=` MUST resolve to a realtime model key (a preset) that has both `stt_model_key` and `tts_model_key` configured — telephony needs STT + TTS and raw PCM out of TTS so the bridge can transcode to G.711. Requests missing a valid telephony-capable preset are rejected and the socket is closed with code `4401`. Authentication order: `Authorization: Bearer`, `?api_key=`, or the session cookie.

        **Message protocol:** the client (Twilio) sends Media Streams JSON frames (`start`, `media`, `stop`); the bridge streams synthesized audio back as `media` frames and manages turn detection via the preset's silence settings.
      operationId: realtimeTwilioBridge
      parameters:
        - name: model
          in: query
          required: true
          description: Realtime model key (preset) with `stt_model_key` and `tts_model_key` configured. Required for the telephony bridge; a missing or non-telephony preset closes the socket with 4401.
          schema:
            type: string
        - name: api_key
          in: query
          required: false
          description: "Client API token (`cpeer_...`) used as an alternative to the `Authorization: Bearer` header (Twilio connects with this in the `<Stream url>`)."
          schema:
            type: string
      responses:
        "101":
          description: Switching Protocols — WebSocket connection established. Twilio Media Streams frames flow over the upgraded connection.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
  /redteam/campaigns:
    get:
      tags:
        - Red Team
      summary: List campaigns
      description: Lists the red-team campaigns configured in the token's project. Authoring of campaigns stays on the dashboard surface.
      operationId: listRedTeamCampaigns
      parameters: []
      responses:
        "200":
          description: Campaigns configured in the token's project.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RedTeamCampaignsResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /redteam/campaigns/{key}/scan:
    post:
      tags:
        - Red Team
      summary: Launch a scan
      description: Enqueues an asynchronous scan for the campaign identified by `key` and returns immediately with a `pending` run. No request body is required. Poll the run-detail endpoint to watch it finish. If a scan for the same campaign is already in progress, the request is rejected with 409.
      operationId: runRedTeamCampaignScan
      parameters:
        - name: key
          in: path
          required: true
          description: Campaign key to scan.
          schema:
            type: string
      responses:
        "202":
          description: Scan enqueued; a pending run is returned.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RedTeamScanResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          $ref: "#/components/responses/Conflict"
        "500":
          $ref: "#/components/responses/InternalError"
  /redteam/probes:
    get:
      tags:
        - Red Team
      summary: List built-in probes
      description: Returns the built-in probe catalog. `custom` is `false` for every entry here; custom probes are not advertised on the client surface (though they still run when selected on a campaign).
      operationId: listRedTeamProbes
      parameters: []
      responses:
        "200":
          description: Built-in probe catalog.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RedTeamProbesResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /redteam/runs:
    get:
      tags:
        - Red Team
      summary: List runs
      description: Returns run summaries (no per-attempt detail), newest first, scoped to the token's project.
      operationId: listRedTeamRuns
      parameters:
        - name: campaign_key
          in: query
          required: false
          description: Filter runs to a single campaign.
          schema:
            type: string
        - name: limit
          in: query
          required: false
          description: Maximum number of rows to return; clamped to 1..200.
          schema:
            type: integer
            minimum: 1
            maximum: 200
      responses:
        "200":
          description: Run summaries, newest first.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RedTeamRunsResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /redteam/runs/{id}:
    get:
      tags:
        - Red Team
      summary: Get run detail
      description: Returns the run summary plus `progress`, any fatal `error`, and the per-attempt verdicts.
      operationId: getRedTeamRun
      parameters:
        - name: id
          in: path
          required: true
          description: Run identifier.
          schema:
            type: string
      responses:
        "200":
          description: Run detail with per-attempt verdicts.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RedTeamRunResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /rerank:
    post:
      tags:
        - Reranker
      summary: Create a reranker
      description: Create a reranker definition. Registered on the `/rerank` collection (the run endpoint is `POST /rerank/{key}`). Requires an API token with `write` permission for this service.
      operationId: createReranker
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RerankCreateInput"
      responses:
        "201":
          description: The created reranker.
          content:
            application/json:
              schema:
                type: object
                properties:
                  reranker:
                    $ref: "#/components/schemas/Reranker"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
  /rerank/{key}:
    get:
      tags:
        - Reranker
      summary: Get a reranker by key
      description: Fetch a single configured reranker by its key.
      operationId: getReranker
      parameters:
        - name: key
          in: path
          required: true
          description: Key of the reranker.
          schema:
            type: string
      responses:
        "200":
          description: The requested reranker.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RerankGetResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      tags:
        - Reranker
      summary: Run a reranker (Cohere-compatible)
      description: Rerank a set of documents against a query using the configured reranker. The request shape mirrors Cohere's `/v2/rerank`, and the response is Cohere-shaped with `results` in descending relevance-score order.
      operationId: runReranker
      parameters:
        - name: key
          in: path
          required: true
          description: Key of the reranker to run.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RerankRunRequest"
      responses:
        "200":
          description: Cohere-shaped rerank result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RerankRunResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    patch:
      tags:
        - Reranker
      summary: Update a reranker
      description: Partially update a reranker resolved by key within the token's project. Requires an API token with `write` permission for this service.
      operationId: updateReranker
      parameters:
        - name: key
          in: path
          required: true
          description: Unique reranker key.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/RerankUpdateInput"
      responses:
        "200":
          description: The updated reranker.
          content:
            application/json:
              schema:
                type: object
                properties:
                  reranker:
                    $ref: "#/components/schemas/Reranker"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - Reranker
      summary: Delete a reranker
      description: Delete a reranker resolved by key within the token's project. Requires an API token with `write` permission for this service.
      operationId: deleteReranker
      parameters:
        - name: key
          in: path
          required: true
          description: Unique reranker key.
          schema:
            type: string
      responses:
        "200":
          description: The reranker was deleted.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                    description: Always true when the resource was deleted.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /rerankers:
    get:
      tags:
        - Reranker
      summary: List rerankers
      description: List the rerankers visible to the API token's tenant.
      operationId: listRerankers
      responses:
        "200":
          description: Rerankers visible to the token.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/RerankListResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /responses:
    post:
      tags:
        - Agents
      summary: Invoke an agent (draft version)
      description: Invoke an agent using the OpenAI Responses API request/response format, running the DRAFT (current unpublished) version of the agent. Identical request/response shape to `POST /agents/responses`, but executes the draft configuration for testing. The agent is identified by the `model` field (agent key). Use `previous_response_id` (`resp_{conversationId}`) for multi-turn conversations and `version` to pin a published version. This endpoint returns a single completed response object; it does not stream.
      operationId: invokeAgentResponseDraft
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/AgentResponsesRequest"
      responses:
        "200":
          description: The completed agent response in OpenAI Responses format.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AgentResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes:
    post:
      tags:
        - Sandbox
      summary: Create a sandbox
      description: Enterprise (license-gated) Agent Sandbox endpoint. Spins up an isolated runtime container from a template. The sandbox starts automatically; poll `GET /sandbox/sandboxes/{id}` until its status is `running`. If no template is resolvable the built-in template library is auto-seeded for the tenant on first use.
      operationId: createSandbox
      requestBody:
        required: false
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/SandboxCreateRequest"
      responses:
        "201":
          description: Sandbox created.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxLifecycleResult"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
    get:
      tags:
        - Sandbox
      summary: List sandboxes
      description: Enterprise (license-gated) endpoint. Lists sandboxes visible to the API token (scoped to the token's project).
      operationId: listSandboxes
      responses:
        "200":
          description: Sandboxes for the token's project.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxListResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}:
    get:
      tags:
        - Sandbox
      summary: Get a sandbox
      description: Enterprise (license-gated) endpoint. Returns a sandbox's current status, resource allocation and preview configuration (previewable ports and their proxy URLs).
      operationId: getSandbox
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      responses:
        "200":
          description: Sandbox detail.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxDetail"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - Sandbox
      summary: Delete a sandbox
      description: Enterprise (license-gated) endpoint. Stops and removes the sandbox's container.
      operationId: deleteSandbox
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      responses:
        "200":
          description: Sandbox deleted.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxDeleteResult"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/code:
    post:
      tags:
        - Sandbox
      summary: Run a code snippet
      description: Enterprise (license-gated) endpoint. Runs a code snippet with the appropriate interpreter inside the running sandbox and returns its exit code, stdout and stderr.
      operationId: runSandboxCode
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/SandboxCodeRunRequest"
      responses:
        "200":
          description: Code execution result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxExecResult"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/exec:
    post:
      tags:
        - Sandbox
      summary: Run a shell command
      description: Enterprise (license-gated) endpoint. Runs a shell command synchronously inside the running sandbox and returns its exit code, stdout and stderr.
      operationId: execSandboxCommand
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/SandboxExecRequest"
      responses:
        "200":
          description: Command result.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxExecResult"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/files:
    post:
      tags:
        - Sandbox
      summary: Upload files to the sandbox volume
      description: "Enterprise (license-gated) endpoint. Bulk-uploads files to the sandbox's attached volume (object storage). Works whether or not the container is running; the sandbox must have a volume attached. Each file's `data` is base64 (a bare base64 string or a data-URL — the prefix before the first comma is stripped). Provide either a `files` array or a single `path`+`data` pair. NOTE: the handler reads a JSON body with base64-encoded file contents (not multipart/form-data)."
      operationId: uploadSandboxFiles
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/SandboxFileUploadRequest"
      responses:
        "201":
          description: Files uploaded to the volume.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxFileUploadResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    get:
      tags:
        - Sandbox
      summary: List files in the sandbox volume
      description: Enterprise (license-gated) endpoint. Lists files in the sandbox's attached volume (paths are volume-relative). Supports cursor-based pagination. The sandbox must have a volume attached.
      operationId: listSandboxFiles
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
        - name: cursor
          in: query
          required: false
          description: Opaque pagination cursor returned as `nextCursor` from a previous page.
          schema:
            type: string
        - name: limit
          in: query
          required: false
          description: Maximum number of files to return.
          schema:
            type: integer
      responses:
        "200":
          description: Files in the volume.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxFileListResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/files/download:
    get:
      tags:
        - Sandbox
      summary: Download a file from the sandbox volume
      description: "Enterprise (license-gated) endpoint. Downloads a single file from the sandbox's attached volume by its volume-relative path. Returns the raw file bytes with a `Content-Disposition: attachment` header. The sandbox must have a volume attached."
      operationId: downloadSandboxFile
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
        - name: path
          in: query
          required: true
          description: Volume-relative path of the file to download.
          schema:
            type: string
      responses:
        "200":
          description: Raw file bytes.
          content:
            application/octet-stream:
              schema:
                type: string
                format: binary
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/fork:
    post:
      tags:
        - Sandbox
      summary: Fork a sandbox
      description: Enterprise (license-gated) endpoint. Forks a sandbox into a new independent copy.
      operationId: forkSandbox
      parameters:
        - name: id
          in: path
          required: true
          description: Source sandbox instance id.
          schema:
            type: string
      requestBody:
        required: false
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/SandboxForkRequest"
      responses:
        "201":
          description: Forked sandbox created.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxLifecycleResult"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/fs/delete:
    post:
      tags:
        - Sandbox
      summary: Delete a file or directory
      description: "Enterprise (EE) sandbox toolbox operation. Removes a file, or a directory tree when 'recursive' is true, inside the running sandbox. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxFsDelete
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - path
              properties:
                path:
                  type: string
                  description: Absolute path to remove.
                recursive:
                  type: boolean
                  default: false
                  description: Remove directories and their contents recursively (rm -rf).
      responses:
        "200":
          description: Path deleted.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolOk"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/fs/find:
    post:
      tags:
        - Sandbox
      summary: Find a fixed string in files
      description: "Enterprise (EE) sandbox toolbox operation. Recursively searches under a path for a fixed (non-regex) string, skipping binaries, returning up to 1000 matches. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxFsFind
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - path
                - pattern
              properties:
                path:
                  type: string
                  description: Absolute directory to search under.
                pattern:
                  type: string
                  description: Fixed string to match (treated literally, not as a regex).
      responses:
        "200":
          description: Matching lines.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolFindResult"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/fs/info:
    post:
      tags:
        - Sandbox
      summary: Get file or directory metadata
      description: "Enterprise (EE) sandbox toolbox operation. Returns metadata (size, mode, permissions, modification time) for a path inside the running sandbox. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxFsInfo
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - path
              properties:
                path:
                  type: string
                  description: Absolute path inside the sandbox.
      responses:
        "200":
          description: File/directory metadata.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolFileInfo"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/fs/list:
    post:
      tags:
        - Sandbox
      summary: List directory entries
      description: "Enterprise (EE) sandbox toolbox operation. Lists the immediate entries of a directory inside the running sandbox. Requests are Aegis-enforced: the policy engine evaluates the call (pre/post stages) and may hold it for approval (202) or block it (403). On success the response carries Aegis decision headers."
      operationId: sandboxFsList
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - path
              properties:
                path:
                  type: string
                  description: Absolute directory path inside the sandbox.
      responses:
        "200":
          description: Directory entries.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision (e.g. allow).
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision (empty when no post evaluation ran).
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolListResult"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/fs/mkdir:
    post:
      tags:
        - Sandbox
      summary: Create a directory
      description: "Enterprise (EE) sandbox toolbox operation. Creates a directory (recursively) inside the running sandbox, optionally applying a chmod mode. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxFsMkdir
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - path
              properties:
                path:
                  type: string
                  description: Absolute directory path to create.
                mode:
                  type: string
                  description: Optional octal chmod mode (e.g. '755').
      responses:
        "200":
          description: Directory created.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolOk"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/fs/move:
    post:
      tags:
        - Sandbox
      summary: Move or rename a path
      description: "Enterprise (EE) sandbox toolbox operation. Moves or renames a path inside the running sandbox, creating the destination's parent directory as needed. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxFsMove
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - source
                - destination
              properties:
                source:
                  type: string
                  description: Absolute source path.
                destination:
                  type: string
                  description: Absolute destination path.
      responses:
        "200":
          description: Path moved.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolOk"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/fs/permissions:
    post:
      tags:
        - Sandbox
      summary: Set path permissions and ownership
      description: "Enterprise (EE) sandbox toolbox operation. Applies chmod (mode) and/or chown (owner/group) to a path inside the running sandbox. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxFsPermissions
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - path
              properties:
                path:
                  type: string
                  description: Absolute path to modify.
                mode:
                  type: string
                  description: Octal chmod mode (e.g. '644').
                owner:
                  type: string
                  description: New owner (chown user).
                group:
                  type: string
                  description: New group (chown group).
      responses:
        "200":
          description: Permissions applied.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolOk"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/fs/read:
    post:
      tags:
        - Sandbox
      summary: Read a file
      description: "Enterprise (EE) sandbox toolbox operation. Reads a file (up to a 10 MiB limit) as UTF-8 or base64; binary content is automatically returned base64-encoded. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxFsRead
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - path
              properties:
                path:
                  type: string
                  description: Absolute file path inside the sandbox.
                encoding:
                  type: string
                  enum:
                    - utf8
                    - base64
                  default: utf8
                  description: Desired content encoding. Anything other than 'base64' is treated as 'utf8'.
      responses:
        "200":
          description: File content.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolReadResult"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/fs/replace:
    post:
      tags:
        - Sandbox
      summary: Replace a string across files
      description: "Enterprise (EE) sandbox toolbox operation. Performs a literal find-and-replace of a string across an explicit list of files, reporting per-file success. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxFsReplace
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - files
                - pattern
                - newValue
              properties:
                files:
                  type: array
                  items:
                    type: string
                  description: Absolute file paths to edit.
                pattern:
                  type: string
                  description: Literal string to find.
                newValue:
                  type: string
                  description: Replacement string.
      responses:
        "200":
          description: Per-file replace results.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolReplaceResult"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/fs/write:
    post:
      tags:
        - Sandbox
      summary: Write a file
      description: "Enterprise (EE) sandbox toolbox operation. Creates or overwrites a file inside the running sandbox, creating parent directories as needed. Content may be supplied as UTF-8 text or base64. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxFsWrite
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - path
                - content
              properties:
                path:
                  type: string
                  description: Absolute file path inside the sandbox.
                content:
                  type: string
                  description: File content (UTF-8 text, or base64 when encoding=base64).
                encoding:
                  type: string
                  enum:
                    - utf8
                    - base64
                  default: utf8
                  description: Interpretation of 'content'. Anything other than 'base64' is treated as 'utf8'.
      responses:
        "200":
          description: Bytes written.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolWriteResult"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/git/add:
    post:
      tags:
        - Sandbox
      summary: Stage files for commit
      description: "Enterprise (EE) sandbox toolbox operation. Stages files in a repository (git add); when no files are supplied, stages all changes (-A). Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxGitAdd
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - path
              properties:
                path:
                  type: string
                  description: Repository directory inside the sandbox.
                files:
                  type: array
                  items:
                    type: string
                  description: Paths to stage. When empty or omitted, all changes are staged (git add -A).
      responses:
        "200":
          description: Files staged.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolOk"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/git/branch:
    post:
      tags:
        - Sandbox
      summary: Create a git branch
      description: "Enterprise (EE) sandbox toolbox operation. Creates a new local branch in a repository inside the sandbox. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxGitBranchCreate
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - path
                - name
              properties:
                path:
                  type: string
                  description: Repository directory inside the sandbox.
                name:
                  type: string
                  description: New branch name.
      responses:
        "200":
          description: Branch created.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolOk"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/git/branch/delete:
    post:
      tags:
        - Sandbox
      summary: Delete a git branch
      description: "Enterprise (EE) sandbox toolbox operation. Force-deletes a local branch (git branch -D) in a repository inside the sandbox. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxGitBranchDelete
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - path
                - name
              properties:
                path:
                  type: string
                  description: Repository directory inside the sandbox.
                name:
                  type: string
                  description: Branch name to delete.
      responses:
        "200":
          description: Branch deleted.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolOk"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/git/branches:
    post:
      tags:
        - Sandbox
      summary: List git branches
      description: "Enterprise (EE) sandbox toolbox operation. Lists local branches of a repository inside the sandbox. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxGitBranches
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - path
              properties:
                path:
                  type: string
                  description: Repository directory inside the sandbox.
      responses:
        "200":
          description: Branch names.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolBranchesResult"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/git/checkout:
    post:
      tags:
        - Sandbox
      summary: Checkout a git branch
      description: "Enterprise (EE) sandbox toolbox operation. Checks out a branch (or ref) in a repository inside the sandbox. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxGitCheckout
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - path
                - branch
              properties:
                path:
                  type: string
                  description: Repository directory inside the sandbox.
                branch:
                  type: string
                  description: Branch or ref to check out.
      responses:
        "200":
          description: Branch checked out.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolOk"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/git/clone:
    post:
      tags:
        - Sandbox
      summary: Clone a git repository
      description: "Enterprise (EE) sandbox toolbox operation. Clones a git repository into the sandbox, optionally checking out a branch and injecting basic-auth credentials into https/http URLs. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxGitClone
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - url
                - path
              properties:
                url:
                  type: string
                  description: Repository URL to clone.
                path:
                  type: string
                  description: Destination directory inside the sandbox.
                branch:
                  type: string
                  description: Optional branch to check out (git clone -b).
                username:
                  type: string
                  description: Optional basic-auth username (http/https only).
                password:
                  type: string
                  description: Optional basic-auth password/token (http/https only).
      responses:
        "200":
          description: Repository cloned.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolCloneResult"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/git/commit:
    post:
      tags:
        - Sandbox
      summary: Create a git commit
      description: "Enterprise (EE) sandbox toolbox operation. Commits staged changes with a supplied author/email, optionally allowing an empty commit, and returns the resulting commit hash. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxGitCommit
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - path
                - message
                - author
                - email
              properties:
                path:
                  type: string
                  description: Repository directory inside the sandbox.
                message:
                  type: string
                  description: Commit message.
                author:
                  type: string
                  description: Commit author name (git -c user.name).
                email:
                  type: string
                  description: Commit author email (git -c user.email).
                allowEmpty:
                  type: boolean
                  default: false
                  description: Allow creating a commit with no staged changes (--allow-empty).
      responses:
        "200":
          description: Commit created.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolCommitResult"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/git/log:
    post:
      tags:
        - Sandbox
      summary: Read git commit log
      description: "Enterprise (EE) sandbox toolbox operation. Returns recent commits (hash, author, email, date, message) for a repository; the limit is clamped between 1 and 500 (default 30). Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxGitLog
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - path
              properties:
                path:
                  type: string
                  description: Repository directory inside the sandbox.
                limit:
                  type: integer
                  default: 30
                  minimum: 1
                  maximum: 500
                  description: Maximum number of commits to return (clamped 1–500).
      responses:
        "200":
          description: Commit log.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolGitLogResult"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/git/pull:
    post:
      tags:
        - Sandbox
      summary: Pull from a git remote
      description: "Enterprise (EE) sandbox toolbox operation. Pulls from origin, optionally injecting basic-auth credentials into the remote URL for the duration of the pull. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxGitPull
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - path
              properties:
                path:
                  type: string
                  description: Repository directory inside the sandbox.
                username:
                  type: string
                  description: Optional basic-auth username for the remote.
                password:
                  type: string
                  description: Optional basic-auth password/token for the remote.
      responses:
        "200":
          description: Pull completed.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolOk"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/git/push:
    post:
      tags:
        - Sandbox
      summary: Push to a git remote
      description: "Enterprise (EE) sandbox toolbox operation. Pushes the current branch to origin, optionally injecting basic-auth credentials into the remote URL for the duration of the push. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxGitPush
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - path
              properties:
                path:
                  type: string
                  description: Repository directory inside the sandbox.
                username:
                  type: string
                  description: Optional basic-auth username for the remote.
                password:
                  type: string
                  description: Optional basic-auth password/token for the remote.
      responses:
        "200":
          description: Push completed.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolOk"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/git/status:
    post:
      tags:
        - Sandbox
      summary: Get git working-tree status
      description: "Enterprise (EE) sandbox toolbox operation. Returns the porcelain status of a repository: current branch, ahead/behind counts and changed files. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxGitStatus
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - path
              properties:
                path:
                  type: string
                  description: Repository directory inside the sandbox.
      responses:
        "200":
          description: Working-tree status.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolGitStatus"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/preview:
    patch:
      tags:
        - Sandbox
      summary: Update preview settings
      description: "Enterprise (license-gated) endpoint. Toggles the sandbox's preview settings: `enabled` (preview on/off) and `public` (allow session-less share links vs private/login-only). Applied live with no container restart."
      operationId: updateSandboxPreview
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: false
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/SandboxPreviewSettingsUpdate"
      responses:
        "200":
          description: Updated preview settings.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxPreviewSettings"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/preview-listening:
    get:
      tags:
        - Sandbox
      summary: List listening ports
      description: Enterprise (license-gated) endpoint. Returns the TCP ports currently LISTENing inside the running sandbox, so an agent can discover what it started and whether it is reachable. `loopbackOnly` services must be restarted bound to 0.0.0.0 to be previewable. Returns an empty list when the sandbox is not running.
      operationId: listSandboxListeningPorts
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      responses:
        "200":
          description: Ports currently listening inside the sandbox.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxListeningPortsResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/preview-tokens:
    post:
      tags:
        - Sandbox
      summary: Create a preview share link
      description: Enterprise (license-gated) endpoint. Mints a short-lived, session-less share link for a sandbox port so a running app can be opened without an API token. Requires the sandbox to have preview enabled and set to public, and the platform to be configured with a preview signing secret.
      operationId: createSandboxPreviewToken
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/SandboxPreviewTokenRequest"
      responses:
        "201":
          description: Signed preview share link.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxPreviewShareLink"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "409":
          $ref: "#/components/responses/Conflict"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/preview/{port}:
    get:
      tags:
        - Sandbox
      summary: Proxy a request to a sandbox port
      description: Enterprise (license-gated) preview proxy. Proxies an HTTP request to a service the user started inside the sandbox on the given port, riding the console origin under a path (no ingress/subdomain needed). Although documented here as GET, the underlying route accepts ANY HTTP method (GET/POST/PUT/PATCH/DELETE/...) and forwards it verbatim to the port. A wildcard variant `/sandbox/sandboxes/{id}/preview/{port}/*` proxies deeper inner paths in the same way. The response body and content-type mirror the upstream service. Requires preview to be enabled on the sandbox.
      operationId: proxySandboxPreview
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
        - name: port
          in: path
          required: true
          description: Port number of the service listening inside the sandbox.
          schema:
            type: integer
      responses:
        "200":
          description: Proxied HTTP response from the service listening on the port inside the sandbox. The status, headers, body and content-type mirror the upstream service.
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/sessions:
    post:
      tags:
        - Sandbox
      summary: Create a command session
      description: "Enterprise (EE) sandbox toolbox operation. Creates a session (a directory grouping background commands) inside the sandbox; a client-supplied id may be provided, otherwise one is generated. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxSessionCreate
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: false
        content:
          application/json:
            schema:
              type: object
              properties:
                sessionId:
                  type: string
                  description: Optional session id (safe token, 1–128 of [A-Za-z0-9_-]); generated when omitted.
      responses:
        "200":
          description: Session created.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolSessionCreateResult"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    get:
      tags:
        - Sandbox
      summary: List command sessions
      description: "Enterprise (EE) sandbox toolbox operation. Lists the ids of active command sessions in the sandbox. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxSessionList
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      responses:
        "200":
          description: Session ids.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolSessionListResult"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/sessions/{sid}:
    delete:
      tags:
        - Sandbox
      summary: Delete a command session
      description: "Enterprise (EE) sandbox toolbox operation. Deletes a command session and its recorded logs from the sandbox. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxSessionDelete
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
        - name: sid
          in: path
          required: true
          description: Session id.
          schema:
            type: string
      responses:
        "200":
          description: Session deleted.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolOk"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/sessions/{sid}/commands/{cmdId}/logs:
    get:
      tags:
        - Sandbox
      summary: Get or stream session command logs
      description: Enterprise (EE) sandbox toolbox operation. Returns a one-shot snapshot of a session command's stdout/stderr/exit state, or — when 'follow=true' — streams new output as Server-Sent Events (stdout/stderr/exit/error events) until the command exits. This log endpoint is served directly (not through the Aegis tool interceptor), so it does not emit Aegis decision headers or a 202 approval response.
      operationId: sandboxSessionCommandLogs
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
        - name: sid
          in: path
          required: true
          description: Session id.
          schema:
            type: string
        - name: cmdId
          in: path
          required: true
          description: Command id returned by the session exec call.
          schema:
            type: string
        - name: follow
          in: query
          required: false
          description: When 'true', stream logs as Server-Sent Events until the command exits; otherwise return a one-shot snapshot.
          schema:
            type: string
            enum:
              - "true"
      responses:
        "200":
          description: Log snapshot (application/json) or an SSE stream (text/event-stream) when follow=true.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolSessionLogs"
            text/event-stream:
              schema:
                type: string
                description: "Server-Sent Events: 'stdout'/'stderr' data chunks, an 'exit' event with the exit code, or an 'error' event."
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/sessions/{sid}/exec:
    post:
      tags:
        - Sandbox
      summary: Run a command in a session
      description: "Enterprise (EE) sandbox toolbox operation. Launches a command detached inside a session (stdout/stderr/exit are captured to files) and returns a command id for later log retrieval. Aegis-enforced: may return 202 (approval required) or 403 (blocked); success responses carry Aegis decision headers."
      operationId: sandboxSessionExec
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
        - name: sid
          in: path
          required: true
          description: Session id.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - command
              properties:
                command:
                  type: string
                  description: Shell command to run (executed via sh -c).
                cwd:
                  type: string
                  default: /workspace
                  description: Working directory for the command.
      responses:
        "200":
          description: Command launched.
          headers:
            x-aegis-trace-id:
              description: Aegis evaluation trace id.
              schema:
                type: string
            x-aegis-decision:
              description: Aegis pre-stage decision.
              schema:
                type: string
            x-aegis-post-decision:
              description: Aegis post-stage decision.
              schema:
                type: string
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolExecResult"
        "202":
          description: Aegis approval required — the operation is held pending policy/human approval.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxToolAegisRejection"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/snapshot:
    post:
      tags:
        - Sandbox
      summary: Capture a snapshot
      description: Enterprise (license-gated) endpoint. Captures a snapshot of the sandbox's current state, optionally exporting it.
      operationId: createSandboxSnapshot
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      requestBody:
        required: false
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/SandboxSnapshotRequest"
      responses:
        "201":
          description: Snapshot created.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxSnapshotResult"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/start:
    post:
      tags:
        - Sandbox
      summary: Start a sandbox
      description: Enterprise (license-gated) endpoint. Starts (resumes) a stopped, persistent sandbox.
      operationId: startSandbox
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      responses:
        "200":
          description: Sandbox starting.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxLifecycleResult"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/sandboxes/{id}/stop:
    post:
      tags:
        - Sandbox
      summary: Stop a sandbox
      description: Enterprise (license-gated) endpoint. Stops a running sandbox (it is kept around if persistent).
      operationId: stopSandbox
      parameters:
        - name: id
          in: path
          required: true
          description: Sandbox instance id.
          schema:
            type: string
      responses:
        "200":
          description: Sandbox stopping.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxLifecycleResult"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/snapshots:
    get:
      tags:
        - Sandbox
      summary: List snapshots
      description: Enterprise (license-gated) endpoint. Lists snapshots visible to the API token (scoped to the token's project).
      operationId: listSandboxSnapshots
      responses:
        "200":
          description: Snapshots for the token's project.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxSnapshotListResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
  /sandbox/snapshots/{id}/restore:
    post:
      tags:
        - Sandbox
      summary: Restore a snapshot
      description: Enterprise (license-gated) endpoint. Resumes a new sandbox from a snapshot.
      operationId: restoreSandboxSnapshot
      parameters:
        - name: id
          in: path
          required: true
          description: Snapshot id to restore from.
          schema:
            type: string
      requestBody:
        required: false
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/SandboxRestoreRequest"
      responses:
        "201":
          description: Sandbox restored from snapshot.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/SandboxLifecycleResult"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /spend/report:
    get:
      tags:
        - Spend
      summary: Get spend report
      description: Read-side cost report for the calling token's project. By default returns totals, a per-model breakdown, and a merged timeseries rolled up from the per-model usage logs (`spend.report`). When `group_by_entity` is set to `user` or `api_key`, returns a per-user / per-API-token breakdown read from the cross-service `usage_daily` rollup instead (`spend.breakdown`). This endpoint never enforces anything.
      operationId: getSpendReport
      parameters:
        - name: from
          in: query
          required: false
          description: Window start as an ISO date string. Invalid value returns 400.
          schema:
            type: string
            format: date-time
        - name: to
          in: query
          required: false
          description: Window end as an ISO date string. Invalid value returns 400.
          schema:
            type: string
            format: date-time
        - name: group_by
          in: query
          required: false
          description: Timeseries bucket granularity. Defaults to `day`.
          schema:
            type: string
            enum:
              - hour
              - day
              - month
            default: day
        - name: group_by_entity
          in: query
          required: false
          description: When set, switches the response to a per-entity breakdown from the usage_daily rollup. `user` groups by user id; `api_key` groups by API token id.
          schema:
            type: string
            enum:
              - user
              - api_key
        - name: model
          in: query
          required: false
          description: Restrict the report to a single model key.
          schema:
            type: string
      responses:
        "200":
          description: The spend report (`spend.report`), or the per-entity breakdown (`spend.breakdown`) when `group_by_entity` is supplied.
          content:
            application/json:
              schema:
                oneOf:
                  - $ref: "#/components/schemas/SpendReport"
                  - $ref: "#/components/schemas/SpendBreakdown"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /tools:
    post:
      tags:
        - Tools
      summary: Create a tool
      description: Create a tool definition from an OpenAPI/Postman spec or an MCP endpoint. Actions are discovered from the source. Requires an API token with `write` permission for this service.
      operationId: createTool
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ToolCreateInput"
      responses:
        "201":
          description: The created tool.
          content:
            application/json:
              schema:
                type: object
                properties:
                  tool:
                    $ref: "#/components/schemas/ToolSerialized"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
    get:
      tags:
        - Tools
      summary: List tools
      description: List tools available to the caller's project from the unified tool system. Tools are backed by an OpenAPI specification or an MCP server and expose discrete actions that can be invoked independently. Results are scoped to the API token's project.
      operationId: listTools
      parameters:
        - name: status
          in: query
          required: false
          description: Filter tools by lifecycle status.
          schema:
            type: string
            enum:
              - active
              - disabled
        - name: type
          in: query
          required: false
          description: Filter tools by source type.
          schema:
            type: string
            enum:
              - openapi
              - mcp
      responses:
        "200":
          description: List of tools with their actions.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ToolListResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /tools/{toolKey}:
    patch:
      tags:
        - Tools
      summary: Update a tool
      description: Partially update a tool definition resolved by key within the token's project. Requires an API token with `write` permission for this service.
      operationId: updateTool
      parameters:
        - name: toolKey
          in: path
          required: true
          description: Unique tool key.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ToolUpdateInput"
      responses:
        "200":
          description: The updated tool.
          content:
            application/json:
              schema:
                type: object
                properties:
                  tool:
                    $ref: "#/components/schemas/ToolSerialized"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - Tools
      summary: Delete a tool
      description: Delete a tool definition resolved by key within the token's project. Requires an API token with `write` permission for this service.
      operationId: deleteTool
      parameters:
        - name: toolKey
          in: path
          required: true
          description: Unique tool key.
          schema:
            type: string
      responses:
        "200":
          description: The tool was deleted.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                    description: Always true when the resource was deleted.
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    get:
      tags:
        - Tools
      summary: Get a tool
      description: Retrieve a single tool by its key, including its actions and their input schemas. Scoped to the API token's project.
      operationId: getTool
      parameters:
        - name: toolKey
          in: path
          required: true
          description: Unique tool key.
          schema:
            type: string
      responses:
        "200":
          description: The requested tool.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ToolDetailResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /tools/{toolKey}/actions/{actionKey}/execute:
    post:
      tags:
        - Tools
      summary: Execute a tool action
      description: Execute a specific action on a tool. The tool must be active. Arguments are passed under `arguments` (or the alias `args`). Execution is logged with latency, arguments, results, and errors.
      operationId: executeToolAction
      parameters:
        - name: toolKey
          in: path
          required: true
          description: Tool key.
          schema:
            type: string
        - name: actionKey
          in: path
          required: true
          description: Action key within the tool.
          schema:
            type: string
      requestBody:
        required: false
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/ToolExecuteRequest"
      responses:
        "200":
          description: Action executed successfully.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/ToolExecuteResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /tools/{toolKey}/sync:
    post:
      tags:
        - Tools
      summary: Sync tool actions
      description: Re-discover the tool's actions from its source (OpenAPI spec or MCP endpoint) and persist the refreshed action set. Requires an API token with `write` permission for this service.
      operationId: syncTool
      parameters:
        - name: toolKey
          in: path
          required: true
          description: Unique tool key.
          schema:
            type: string
      responses:
        "200":
          description: The tool with its refreshed actions.
          content:
            application/json:
              schema:
                type: object
                properties:
                  tool:
                    $ref: "#/components/schemas/ToolSerialized"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /traces:
    post:
      tags:
        - Tracing
      summary: Ingest OTLP traces
      description: OpenTelemetry OTLP/HTTP JSON trace ingestion endpoint. Accepts a standard OTLP ExportTraceServiceRequest (resourceSpans[]) and maps the spans into Cognipeer agent tracing sessions and events, deduplicating events by span/id fingerprint. Persistence happens asynchronously after validation and quota checks; the response is immediate. The request body must not exceed the configured tracing body-size limit (TRACING_MAX_BODY_SIZE_MB, default 10MB).
      operationId: ingestClientOtlpTraces
      requestBody:
        required: true
        description: OTLP/HTTP JSON export payload.
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/TraceOtlpRequest"
      responses:
        "200":
          description: Traces accepted for ingestion.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  sessionsIngested:
                    type: integer
                    description: Number of sessions derived from the payload.
                  spansProcessed:
                    type: integer
                    description: Total number of spans found across all resourceSpans.
                  eventsStored:
                    type: integer
                    description: Number of tracing events mapped from the spans.
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"
  /tracing/sessions:
    post:
      tags:
        - Tracing
      summary: Ingest a tracing session (batch)
      description: "Custom-protocol batch ingestion: send a complete agent tracing session with all of its events in one request. The session (identified by sessionId) is upserted and its events replaced; models/tools used and token/byte totals are aggregated. Persistence happens asynchronously (fire-and-forget), so the response is immediate. The request body must not exceed the configured tracing body-size limit (TRACING_MAX_BODY_SIZE_MB, default 10MB)."
      operationId: ingestTracingSession
      requestBody:
        required: true
        description: The tracing session with its events.
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/TraceSessionRequest"
            example:
              sessionId: sess-abc123
              threadId: thread-456
              traceId: 4bf92f3577b34da6a3ce929d0e0e4736
              rootSpanId: 00f067aa0ba902b7
              agent:
                name: research-agent
                version: 1.0.0
                model: gpt-4
              status: completed
              startedAt: 2025-01-15T10:00:00Z
              endedAt: 2025-01-15T10:00:03Z
              durationMs: 3500
              summary:
                totalInputTokens: 500
                totalOutputTokens: 200
                totalCachedInputTokens: 0
              events:
                - id: evt-1
                  type: llm_call
                  label: Generate response
                  sequence: 1
                  traceId: 4bf92f3577b34da6a3ce929d0e0e4736
                  spanId: b7ad6b7169203331
                  parentSpanId: 00f067aa0ba902b7
                  sections:
                    - type: input
                      content: User query...
                    - type: output
                      content: Assistant response...
                  inputTokens: 500
                  outputTokens: 200
      responses:
        "200":
          description: Session accepted for ingestion.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  sessionId:
                    type: string
                  eventsStored:
                    type: integer
                    description: Number of events submitted with the session.
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"
  /tracing/sessions/stream/{sessionId}/end:
    post:
      tags:
        - Tracing
      summary: End a streaming tracing session
      description: "Custom streaming-trace protocol (end step). Finalizes an in-progress streaming session: sets its final status, endedAt and duration, and merges the provided summary/errors with what was accumulated during streaming. The session must already exist, otherwise 404 is returned. The update is applied asynchronously."
      operationId: endTracingSessionStream
      parameters:
        - name: sessionId
          in: path
          required: true
          description: Identifier of the streaming session to finalize.
          schema:
            type: string
      requestBody:
        required: false
        description: Final status and summary for the session.
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/TraceStreamEndRequest"
            example:
              status: completed
              endedAt: 2025-01-15T10:00:03Z
              durationMs: 3500
              summary:
                totalDurationMs: 3500
                totalInputTokens: 500
                totalOutputTokens: 200
      responses:
        "200":
          description: Session finalized.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  sessionId:
                    type: string
                  status:
                    type: string
                    description: Final session status (defaults to success when not supplied).
                    example: completed
                  durationMs:
                    type: integer
                    description: Final session duration in milliseconds.
                  totalEvents:
                    type: integer
                    description: Total events recorded on the session.
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"
  /tracing/sessions/stream/{sessionId}/events:
    post:
      tags:
        - Tracing
      summary: Append an event to a streaming tracing session
      description: Custom streaming-trace protocol (event step). Appends a single tracing event to an already-started session and incrementally updates the session's running totals (event counts, models/tools used, token totals). The session must already exist (created via /start), otherwise 404 is returned. Event persistence and session update happen asynchronously.
      operationId: appendTracingSessionEvent
      parameters:
        - name: sessionId
          in: path
          required: true
          description: Identifier of the streaming session created via /start.
          schema:
            type: string
      requestBody:
        required: true
        description: Wrapper carrying the single event to append.
        content:
          application/json:
            schema:
              type: object
              required:
                - event
              properties:
                event:
                  $ref: "#/components/schemas/TraceEvent"
            example:
              event:
                id: evt-2
                type: tool_call
                label: Search API
                traceId: 4bf92f3577b34da6a3ce929d0e0e4736
                spanId: 5b8aa5a2d2d3e13c
                parentSpanId: 00f067aa0ba902b7
                sections:
                  - type: input
                    content: '{"query": "..."}'
                  - type: output
                    content: '{"results": [...]}'
                inputTokens: 50
                outputTokens: 100
      responses:
        "200":
          description: Event accepted and appended.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  sessionId:
                    type: string
                  eventId:
                    type: string
                    description: Echoes the submitted event id, if any.
                    nullable: true
                  totalEvents:
                    type: integer
                    description: Running count of events on the session after appending.
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"
  /tracing/sessions/stream/{sessionId}/start:
    post:
      tags:
        - Tracing
      summary: Start a streaming tracing session
      description: Custom streaming-trace protocol (start step). Opens a long-running tracing session for the given sessionId with status in_progress, so events can be streamed in one at a time via the /events step and finalized with /end. The session is upserted from the optional metadata body (agent, thread/trace ids, startedAt, config). Persistence is asynchronous.
      operationId: startTracingSessionStream
      parameters:
        - name: sessionId
          in: path
          required: true
          description: Client-chosen identifier for the streaming session.
          schema:
            type: string
      requestBody:
        required: false
        description: Optional session metadata to record at start.
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/TraceStreamStartRequest"
            example:
              threadId: thread-456
              traceId: 4bf92f3577b34da6a3ce929d0e0e4736
              rootSpanId: 00f067aa0ba902b7
              agent:
                name: research-agent
                version: 1.0.0
              startedAt: 2025-01-15T10:00:00Z
      responses:
        "200":
          description: Streaming session started.
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                  sessionId:
                    type: string
                  status:
                    type: string
                    description: Always in_progress for a freshly started session.
                    example: in_progress
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"
  /tracing/threads:
    get:
      tags:
        - Tracing
      summary: List tracing threads
      description: Lists agent tracing threads (sessions grouped by `threadId`) for the token's project. Strictly tenant + project scoped. RBAC maps this path to the `tracing` service at read level.
      operationId: listTracingThreads
      parameters:
        - name: agent
          in: query
          required: false
          description: Case-insensitive filter matching a thread's agent name.
          schema:
            type: string
        - name: status
          in: query
          required: false
          description: Filter by the thread's latest status (e.g. `success`, `error`, `in_progress`).
          schema:
            type: string
        - name: threadId
          in: query
          required: false
          description: Case-insensitive substring filter on the thread id.
          schema:
            type: string
        - name: from
          in: query
          required: false
          description: Inclusive lower bound on thread start time (ISO 8601).
          schema:
            type: string
            format: date-time
        - name: to
          in: query
          required: false
          description: Inclusive upper bound on thread start time (ISO 8601).
          schema:
            type: string
            format: date-time
        - name: limit
          in: query
          required: false
          description: Maximum threads to return. Defaults to 50.
          schema:
            type: integer
            default: 50
        - name: skip
          in: query
          required: false
          description: Number of threads to skip for pagination. Defaults to 0.
          schema:
            type: integer
            default: 0
      responses:
        "200":
          description: Paginated list of tracing threads.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/TracingThreadList"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /tracing/threads/{threadId}:
    get:
      tags:
        - Tracing
      summary: Get tracing thread detail
      description: Returns a single tracing thread with aggregated stats and its constituent sessions. Strictly tenant + project scoped. Returns 404 when no sessions belong to the given `threadId`. RBAC maps this path to the `tracing` service at read level.
      operationId: getTracingThread
      parameters:
        - name: threadId
          in: path
          required: true
          description: The thread id to fetch.
          schema:
            type: string
      responses:
        "200":
          description: Tracing thread detail.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/TracingThreadDetail"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /vector/providers:
    get:
      tags:
        - Vector
      summary: List vector providers
      description: List all vector database providers configured for the current tenant/project. Optionally filter by driver and status.
      operationId: listVectorProviders
      parameters:
        - name: driver
          in: query
          required: false
          description: Filter providers by driver identifier (e.g. `pinecone`).
          schema:
            type: string
            example: pinecone
        - name: status
          in: query
          required: false
          description: Filter providers by status.
          schema:
            type: string
            enum:
              - active
              - inactive
              - error
            example: active
      responses:
        "200":
          description: List of vector providers
          content:
            application/json:
              schema:
                type: object
                properties:
                  providers:
                    type: array
                    items:
                      $ref: "#/components/schemas/VectorProvider"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      tags:
        - Vector
      summary: Create vector provider
      description: Create a new vector database provider configuration for the current project. Requires `key`, `driver`, `label`, and `credentials`.
      operationId: createVectorProvider
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/VectorCreateProviderRequest"
            example:
              key: pinecone-prod
              driver: pinecone
              label: Production Vectors
              credentials:
                apiKey: pk-...
              settings:
                environment: gcp-starter
      responses:
        "201":
          description: Vector provider created
          content:
            application/json:
              schema:
                type: object
                properties:
                  provider:
                    $ref: "#/components/schemas/VectorProvider"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "409":
          $ref: "#/components/responses/Conflict"
        "500":
          $ref: "#/components/responses/InternalError"
  /vector/providers/drivers:
    get:
      tags:
        - Vector
      summary: List vector provider drivers
      description: Return the available provider driver descriptors for the given domain (defaults to `vector`).
      operationId: listVectorProviderDrivers
      parameters:
        - name: domain
          in: query
          required: false
          description: Provider domain to list drivers for. Defaults to `vector`.
          schema:
            type: string
            default: vector
            example: vector
      responses:
        "200":
          description: Available driver descriptors
          content:
            application/json:
              schema:
                type: object
                properties:
                  drivers:
                    type: array
                    items:
                      $ref: "#/components/schemas/VectorDriverDescriptor"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "500":
          $ref: "#/components/responses/InternalError"
  /vector/providers/drivers/{driverId}/form:
    get:
      tags:
        - Vector
      summary: Get vector driver form schema
      description: Return the credential/settings form schema and descriptor for a specific vector driver, used for UI rendering.
      operationId: getVectorProviderDriverForm
      parameters:
        - name: driverId
          in: path
          required: true
          description: Driver identifier (e.g. `pinecone`).
          schema:
            type: string
      responses:
        "200":
          description: Driver form schema
          content:
            application/json:
              schema:
                type: object
                properties:
                  descriptor:
                    $ref: "#/components/schemas/VectorDriverDescriptor"
                  driverId:
                    type: string
                  schema:
                    $ref: "#/components/schemas/VectorProviderFormSchema"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /vector/providers/{providerKey}/indexes:
    get:
      tags:
        - Vector
      summary: List vector indexes
      description: List all indexes for a specific vector provider.
      operationId: listVectorIndexes
      parameters:
        - name: providerKey
          in: path
          required: true
          description: Unique key of the vector provider.
          schema:
            type: string
      responses:
        "200":
          description: List of vector indexes
          content:
            application/json:
              schema:
                type: object
                properties:
                  indexes:
                    type: array
                    items:
                      $ref: "#/components/schemas/VectorIndex"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    post:
      tags:
        - Vector
      summary: Create vector index
      description: "Create a new vector index. If an index with the same normalized name already exists it is reused and returned with `reused: true` and a `200` status; otherwise a new index is created and returned with `201`."
      operationId: createVectorIndex
      parameters:
        - name: providerKey
          in: path
          required: true
          description: Unique key of the vector provider.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/VectorCreateIndexRequest"
            example:
              name: Product Embeddings
              dimension: 1536
              metric: cosine
      responses:
        "200":
          description: Existing index reused (same normalized name)
          content:
            application/json:
              schema:
                type: object
                properties:
                  index:
                    $ref: "#/components/schemas/VectorIndex"
                  reused:
                    type: boolean
                    example: true
        "201":
          description: Vector index created
          content:
            application/json:
              schema:
                type: object
                properties:
                  index:
                    $ref: "#/components/schemas/VectorIndex"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"
  /vector/providers/{providerKey}/indexes/{externalId}:
    get:
      tags:
        - Vector
      summary: Get vector index
      description: Retrieve details of a specific vector index along with its provider.
      operationId: getVectorIndex
      parameters:
        - name: providerKey
          in: path
          required: true
          description: Unique key of the vector provider.
          schema:
            type: string
        - name: externalId
          in: path
          required: true
          description: External identifier (key) of the vector index.
          schema:
            type: string
      responses:
        "200":
          description: Vector index details
          content:
            application/json:
              schema:
                type: object
                properties:
                  index:
                    $ref: "#/components/schemas/VectorIndex"
                  provider:
                    $ref: "#/components/schemas/VectorProvider"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    patch:
      tags:
        - Vector
      summary: Update vector index
      description: Update the name and/or metadata of an existing vector index. At least one updatable field must be provided.
      operationId: updateVectorIndex
      parameters:
        - name: providerKey
          in: path
          required: true
          description: Unique key of the vector provider.
          schema:
            type: string
        - name: externalId
          in: path
          required: true
          description: External identifier (key) of the vector index.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/VectorUpdateIndexRequest"
            example:
              name: Updated Name
              metadata:
                description: Updated metadata
      responses:
        "200":
          description: Vector index updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  index:
                    $ref: "#/components/schemas/VectorIndex"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
    delete:
      tags:
        - Vector
      summary: Delete vector index
      description: Delete a vector index and all of its stored data.
      operationId: deleteVectorIndex
      parameters:
        - name: providerKey
          in: path
          required: true
          description: Unique key of the vector provider.
          schema:
            type: string
        - name: externalId
          in: path
          required: true
          description: External identifier (key) of the vector index.
          schema:
            type: string
      responses:
        "200":
          description: Vector index deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
  /vector/providers/{providerKey}/indexes/{externalId}/query:
    post:
      tags:
        - Vector
      summary: Query vectors
      description: Search for the most similar vectors in the index using a query vector, optional `topK` and provider-specific `filter`.
      operationId: queryVectors
      parameters:
        - name: providerKey
          in: path
          required: true
          description: Unique key of the vector provider.
          schema:
            type: string
        - name: externalId
          in: path
          required: true
          description: External identifier (key) of the vector index.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/VectorQueryRequest"
            example:
              query:
                vector:
                  - 0.1
                  - 0.2
                  - 0.3
                topK: 10
                filter:
                  category: electronics
      responses:
        "200":
          description: Query results
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/VectorQueryResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"
  /vector/providers/{providerKey}/indexes/{externalId}/upsert:
    post:
      tags:
        - Vector
      summary: Upsert vectors
      description: Insert or update vectors in the index. Each vector must include a string `id` and a numeric `values` array.
      operationId: upsertVectors
      parameters:
        - name: providerKey
          in: path
          required: true
          description: Unique key of the vector provider.
          schema:
            type: string
        - name: externalId
          in: path
          required: true
          description: External identifier (key) of the vector index.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/VectorUpsertRequest"
            example:
              vectors:
                - id: vec-1
                  values:
                    - 0.1
                    - 0.2
                  metadata:
                    category: electronics
                - id: vec-2
                  values:
                    - 0.3
                    - 0.4
                  metadata:
                    category: books
      responses:
        "200":
          description: Vectors upserted
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"
  /vector/providers/{providerKey}/indexes/{externalId}/vectors:
    delete:
      tags:
        - Vector
      summary: Delete vectors
      description: Delete specific vectors by ID from the index. Provide a non-empty `ids` array of vector identifiers.
      operationId: deleteVectors
      parameters:
        - name: providerKey
          in: path
          required: true
          description: Unique key of the vector provider.
          schema:
            type: string
        - name: externalId
          in: path
          required: true
          description: External identifier (key) of the vector index.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/VectorDeleteVectorsRequest"
            example:
              ids:
                - vec-1
                - vec-2
      responses:
        "200":
          description: Vectors deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "404":
          $ref: "#/components/responses/NotFound"
        "429":
          $ref: "#/components/responses/TooManyRequests"
        "500":
          $ref: "#/components/responses/InternalError"
  /websearch/providers:
    get:
      tags:
        - Web Search
      summary: List web search instances
      description: Returns the web search instances (providers) visible to the token's project. `aiAnswer` reports whether AI answers are enabled on the instance. Gated by the `websearch` RBAC service.
      operationId: listWebSearchProviders
      parameters: []
      responses:
        "200":
          description: Web search instances visible to the token.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebSearchProvidersResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
  /websearch/search:
    post:
      tags:
        - Web Search
      summary: Run a web search
      description: Runs a web search against the project's single active instance, or against the instance named in the `provider` body field. Gated by the `websearch` RBAC service. `include_answer` requires the instance to have AI answers enabled, otherwise the request fails.
      operationId: runWebSearch
      parameters: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/WebSearchRequest"
      responses:
        "200":
          description: Normalized search result across drivers.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebSearchResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "500":
          $ref: "#/components/responses/InternalError"
  /websearch/{key}/search:
    post:
      tags:
        - Web Search
      summary: Run a web search on a named instance
      description: Runs a web search on the web search instance identified by `key`. The instance is taken from the path; any `provider` field in the body is ignored. Gated by the `websearch` RBAC service. `include_answer` requires the instance to have AI answers enabled, otherwise the request fails.
      operationId: runWebSearchWithInstance
      parameters:
        - name: key
          in: path
          required: true
          description: Web search instance key to search with.
          schema:
            type: string
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/WebSearchRequest"
      responses:
        "200":
          description: Normalized search result across drivers.
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/WebSearchResponse"
        "400":
          $ref: "#/components/responses/BadRequest"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"
        "404":
          $ref: "#/components/responses/NotFound"
        "500":
          $ref: "#/components/responses/InternalError"
components:
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: opaque
      description: "Console API token. Create one in the dashboard under Settings → API Tokens. Format: `cpeer_...`"
  schemas:
    AegisAuditEvent:
      type: object
      description: One recorded shield decision.
      properties:
        traceId:
          type: string
        shieldId:
          type: string
        actorId:
          type: string
        stage:
          type: string
          enum:
            - input.pre
            - retrieval.pre
            - retrieval.post
            - tool.pre
            - tool.post
            - output.pre
        resourceName:
          type: string
        decision:
          type: string
          enum:
            - allow
            - redact
            - require_approval
            - sandbox
            - block
        riskScore:
          type: number
        reasons:
          type: array
          items:
            type: string
        policyVersion:
          type: string
        at:
          type: string
      required:
        - traceId
        - shieldId
        - actorId
        - stage
        - resourceName
        - decision
        - riskScore
        - reasons
        - policyVersion
        - at
    AegisEvaluateRequest:
      type: object
      description: A call to evaluate against a shield's policy.
      properties:
        stage:
          type: string
          enum:
            - input.pre
            - retrieval.pre
            - retrieval.post
            - tool.pre
            - tool.post
            - output.pre
          description: Pipeline stage being evaluated.
        actor:
          type: object
          description: Who is making the call. Defaults `id` to the token's user when omitted.
          properties:
            id:
              type: string
            roles:
              type: array
              items:
                type: string
        resource:
          type: object
          description: The tool call / content under evaluation.
          properties:
            type:
              type: string
            name:
              type: string
            arguments:
              type: object
              additionalProperties: true
            content: {}
            result: {}
          required:
            - type
            - name
        shieldId:
          type: string
          description: Target shield; defaults to the built-in `default` shield.
        traceId:
          type: string
          description: Optional trace correlation id (one is generated when omitted).
        context:
          type: object
          description: Evaluation context. Additional keys are allowed.
          additionalProperties: true
          properties:
            projectId:
              type: string
            model:
              type: string
            agent:
              type: string
            approvalToken:
              type: string
              description: Token minted by an approved `require_approval` decision.
            sandboxAvailable:
              type: boolean
              description: When true, side-effectful calls decide `sandbox` instead of `require_approval`.
      required:
        - stage
        - resource
    AegisEvaluation:
      type: object
      description: The result of evaluating a call against a shield.
      properties:
        traceId:
          type: string
        shieldId:
          type: string
        shieldMode:
          type: string
          enum:
            - enforce
            - simulate
            - disabled
        decision:
          type: string
          enum:
            - allow
            - redact
            - require_approval
            - sandbox
            - block
        enforced:
          type: boolean
          description: False when the shield is simulating/disabled — the decision is advisory.
        riskScore:
          type: number
        reasons:
          type: array
          items:
            type: string
        policyVersion:
          type: string
        findings:
          type: array
          items:
            $ref: "#/components/schemas/AegisFinding"
        mutations:
          type: array
          items:
            type: object
            properties:
              path:
                type: string
              action:
                type: string
                enum:
                  - redact
                  - remove
              replacement:
                type: string
            required:
              - path
              - action
        sanitizedResource:
          type: object
          description: The resource with sensitive values redacted — execute with THIS, not the original.
          additionalProperties: true
        approval:
          type: object
          description: "Present on `require_approval`: approve in the Console, then re-run with `context.approvalToken`."
          properties:
            approvalId:
              type: string
            expiresAt:
              type: string
            scope:
              type: string
              enum:
                - call_bound
          required:
            - approvalId
            - expiresAt
            - scope
      required:
        - traceId
        - shieldId
        - shieldMode
        - decision
        - enforced
        - riskScore
        - reasons
        - policyVersion
        - findings
        - mutations
    AegisFinding:
      type: object
      properties:
        code:
          type: string
        severity:
          type: string
          enum:
            - low
            - medium
            - high
            - critical
        reason:
          type: string
        path:
          type: string
      required:
        - code
        - severity
        - reason
    AegisShield:
      type: object
      description: An Aegis enforcement instance — one protected surface with its own policy and DLP settings.
      properties:
        id:
          type: string
        name:
          type: string
        description:
          type: string
        mode:
          type: string
          enum:
            - enforce
            - simulate
            - disabled
        rules:
          $ref: "#/components/schemas/AegisToolRule"
        dlp:
          type: object
          properties:
            redactSecrets:
              type: boolean
            redactPii:
              type: boolean
            semantic:
              type: boolean
          required:
            - redactSecrets
            - redactPii
        llm:
          type: object
          properties:
            modelKey:
              type: string
            judge:
              type: object
              properties:
                enabled:
                  type: boolean
                stages:
                  type: array
                  items:
                    type: string
                    enum:
                      - input.pre
                      - retrieval.pre
                      - retrieval.post
                      - tool.pre
                      - tool.post
                      - output.pre
                threshold:
                  type: number
                failMode:
                  type: string
                  enum:
                    - open
                    - closed
                onlyHighRisk:
                  type: boolean
        createdAt:
          type: string
        updatedAt:
          type: string
      required:
        - id
        - name
        - mode
        - rules
        - dlp
        - createdAt
        - updatedAt
    AegisToolRule:
      type: object
      description: A shield's tool/egress/path policy.
      properties:
        allow:
          type: array
          items:
            type: string
        deny:
          type: array
          items:
            type: string
        sideEffects:
          type: object
          additionalProperties:
            type: string
            enum:
              - none
              - read
              - write
              - destructive
              - external
        allowedRoles:
          type: object
          additionalProperties:
            type: array
            items:
              type: string
        allowedDomains:
          type: array
          items:
            type: string
        deniedDomains:
          type: array
          items:
            type: string
          description: Deny wins over allow and also matches subdomains.
        allowedPathPrefixes:
          type: array
          items:
            type: string
        deniedPathPrefixes:
          type: array
          items:
            type: string
        argumentSchemas:
          type: object
          additionalProperties: true
        limits:
          type: object
          properties:
            perActorPerMinute:
              type: integer
            perToolPerMinute:
              type: integer
            maxArgBytes:
              type: integer
            maxResultBytes:
              type: integer
    AgentA2aArtifact:
      type: object
      description: An A2A task artifact carrying the assistant reply.
      properties:
        artifactId:
          type: string
        name:
          type: string
        parts:
          type: array
          items:
            $ref: "#/components/schemas/AgentA2aPart"
    AgentA2aMessage:
      type: object
      description: An inbound A2A message.
      properties:
        role:
          type: string
          description: Message role (e.g. `user`).
        parts:
          type: array
          description: Message parts; text parts are concatenated into the user message.
          items:
            $ref: "#/components/schemas/AgentA2aPart"
        messageId:
          type: string
        contextId:
          type: string
          description: Conversation/context id to continue an existing conversation. Omit to start a new one.
        metadata:
          type: object
          additionalProperties: true
          description: Optional metadata. `runtime_context` here is forwarded to downstream targets (see AgentRuntimeContext).
    AgentA2aPart:
      type: object
      description: An A2A message/artifact part. Only text parts (`kind` `text` or omitted) are read.
      properties:
        kind:
          type: string
          description: Part kind, e.g. `text`.
        text:
          type: string
          description: Text content of the part.
    AgentA2aRpcError:
      type: object
      description: JSON-RPC error object.
      properties:
        code:
          type: integer
          description: JSON-RPC / A2A error code (e.g. -32601 method not found, -32602 invalid params, -32001 task not found, -32004 unsupported operation, -32603 internal error, -32700 parse error).
        message:
          type: string
    AgentA2aRpcParams:
      type: object
      description: Method-dependent JSON-RPC params. `message` is used by `message/send`; `id` is used by `tasks/get` and `tasks/cancel`.
      properties:
        message:
          $ref: "#/components/schemas/AgentA2aMessage"
        id:
          type: string
          description: Task id for `tasks/get` / `tasks/cancel` (format `task_{conversationId}_{messageIndex}`).
    AgentA2aRpcRequest:
      type: object
      description: JSON-RPC 2.0 request envelope for the A2A endpoint.
      properties:
        jsonrpc:
          type: string
          enum:
            - "2.0"
        id:
          description: Request id echoed back on the response.
          nullable: true
          oneOf:
            - type: string
            - type: integer
        method:
          type: string
          enum:
            - message/send
            - tasks/get
            - tasks/cancel
          description: A2A method to invoke.
        params:
          $ref: "#/components/schemas/AgentA2aRpcParams"
      required:
        - jsonrpc
        - method
    AgentA2aRpcResponse:
      type: object
      description: JSON-RPC 2.0 response envelope. Exactly one of `result` or `error` is present.
      properties:
        jsonrpc:
          type: string
          enum:
            - "2.0"
        id:
          nullable: true
          oneOf:
            - type: string
            - type: integer
        result:
          $ref: "#/components/schemas/AgentA2aTask"
        error:
          $ref: "#/components/schemas/AgentA2aRpcError"
    AgentA2aTask:
      type: object
      description: A completed A2A task returned by `message/send` and `tasks/get`.
      properties:
        kind:
          type: string
          enum:
            - task
        id:
          type: string
          description: Task id (format `task_{conversationId}_{messageIndex}`).
        contextId:
          type: string
          description: Conversation/context id (equals the conversation id).
        status:
          $ref: "#/components/schemas/AgentA2aTaskStatus"
        artifacts:
          type: array
          items:
            $ref: "#/components/schemas/AgentA2aArtifact"
    AgentA2aTaskStatus:
      type: object
      description: Terminal task status.
      properties:
        state:
          type: string
          enum:
            - completed
        timestamp:
          type: string
          format: date-time
    AgentCard:
      type: object
      description: A2A Agent Card (discovery document) as defined by the Agent-to-Agent protocol.
      properties:
        protocolVersion:
          type: string
          description: A2A protocol version.
        name:
          type: string
        description:
          type: string
        url:
          type: string
          description: JSON-RPC endpoint for this agent.
        preferredTransport:
          type: string
          example: JSONRPC
        provider:
          type: object
          properties:
            organization:
              type: string
            url:
              type: string
        version:
          type: string
          description: Published agent version ("0" if unpublished).
        capabilities:
          type: object
          properties:
            streaming:
              type: boolean
            pushNotifications:
              type: boolean
            stateTransitionHistory:
              type: boolean
        defaultInputModes:
          type: array
          items:
            type: string
          example:
            - text/plain
        defaultOutputModes:
          type: array
          items:
            type: string
          example:
            - text/plain
        skills:
          type: array
          items:
            type: object
            properties:
              id:
                type: string
              name:
                type: string
              description:
                type: string
              tags:
                type: array
                items:
                  type: string
              inputModes:
                type: array
                items:
                  type: string
              outputModes:
                type: array
                items:
                  type: string
        securitySchemes:
          type: object
          description: Empty for public agents; otherwise a bearer scheme requiring a Cognipeer API token.
          additionalProperties: true
        security:
          type: array
          items:
            type: object
            additionalProperties: true
    AgentConfig:
      type: object
      description: Resolved model configuration for an agent.
      properties:
        modelKey:
          type: string
          description: Key of the underlying model the agent runs on.
        temperature:
          type: number
          nullable: true
          description: Sampling temperature override.
        topP:
          type: number
          nullable: true
          description: Nucleus sampling (top-p) override.
        maxTokens:
          type: integer
          nullable: true
          description: Maximum output tokens.
    AgentConfigInput:
      type: object
      additionalProperties: true
      description: "Agent configuration. For native agents `modelKey` is required; for connected agents set `kind: external` and supply `connection`."
      properties:
        kind:
          type: string
          enum:
            - external
          nullable: true
          description: Set to `external` for a connected agent. Omit for a native (model-backed) agent.
        modelKey:
          type: string
          description: Key of the model to run on. Required for native agents.
        connection:
          $ref: "#/components/schemas/AgentConnectionInput"
        temperature:
          type: number
          nullable: true
          description: Sampling temperature override.
        topP:
          type: number
          nullable: true
          description: Nucleus sampling (top-p) override.
        maxTokens:
          type: integer
          nullable: true
          description: Maximum output tokens.
        systemPrompt:
          type: string
          description: System prompt / instructions for the agent.
    AgentConnectionInput:
      type: object
      additionalProperties: true
      description: Connection descriptor for an external ("connected") agent. On update, omit `apiKey` to keep the stored credential.
      properties:
        provider:
          type: string
          description: Upstream provider identifier for the connected agent.
        baseUrl:
          type: string
          description: Base URL of the external agent endpoint.
        apiKey:
          type: string
          description: Inline API key. Encrypted at rest and never returned; the response exposes only `hasApiKey`.
    AgentCreateInput:
      type: object
      required:
        - name
        - config
      description: Create an agent definition.
      properties:
        name:
          type: string
          description: Human-readable agent name.
          example: Support Triage
        description:
          type: string
          description: Optional description.
        status:
          type: string
          enum:
            - active
            - inactive
            - draft
          description: Initial status. Defaults to the service default when omitted.
        config:
          $ref: "#/components/schemas/AgentConfigInput"
    AgentDetailResponse:
      type: object
      description: Response body for a single agent lookup.
      properties:
        agent:
          $ref: "#/components/schemas/AgentSummary"
    AgentInputContentPart:
      type: object
      description: A structured content part within a message item.
      properties:
        type:
          type: string
          enum:
            - input_text
          description: Content part type; only `input_text` is read.
        text:
          type: string
          description: The text content of the part.
      required:
        - type
        - text
    AgentInputMessage:
      type: object
      description: A single message item. The most recent item with role `user` is used as the user message.
      properties:
        role:
          type: string
          description: Message role; only `user` items are read for the input message.
        content:
          description: "Message content: a plain string, or an array of structured content parts."
          oneOf:
            - type: string
            - type: array
              items:
                $ref: "#/components/schemas/AgentInputContentPart"
      required:
        - role
        - content
    AgentListResponse:
      type: object
      description: Response body for listing agents.
      properties:
        agents:
          type: array
          description: The agents visible to the token's project.
          items:
            $ref: "#/components/schemas/AgentSummary"
    AgentPublishInput:
      type: object
      description: Publish the current draft config as a new immutable version.
      properties:
        changelog:
          type: string
          description: Optional changelog note recorded on the published version.
    AgentRecord:
      type: object
      additionalProperties: true
      description: A stored agent definition with secret material redacted.
      properties:
        _id:
          type: string
          description: Internal agent id.
        key:
          type: string
          description: Stable agent key (used as the `model` field when running the agent).
          example: support-triage
        name:
          type: string
        description:
          type: string
        status:
          type: string
          enum:
            - active
            - inactive
            - draft
        tenantId:
          type: string
        projectId:
          type: string
        config:
          type: object
          additionalProperties: true
          description: "Stored config. Secret material is redacted: a connected agent's `connection` carries `hasApiKey` (boolean) instead of the encrypted key."
          properties:
            kind:
              type: string
              nullable: true
            modelKey:
              type: string
            connection:
              type: object
              additionalProperties: true
              properties:
                hasApiKey:
                  type: boolean
                  description: Whether an inline API key is stored (the key itself is never returned).
        latestVersion:
          type: integer
          nullable: true
        publishedVersion:
          type: integer
          nullable: true
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    AgentResponse:
      type: object
      description: OpenAI Responses API-compatible response object.
      properties:
        id:
          type: string
          description: Response ID in the form `resp_{conversationId}`.
        object:
          type: string
          enum:
            - response
        model:
          type: string
          description: Agent key that produced the response.
        output:
          type: array
          description: Ordered output items (reasoning and/or assistant messages).
          items:
            $ref: "#/components/schemas/AgentResponseOutputItem"
        status:
          type: string
          enum:
            - completed
            - failed
        usage:
          $ref: "#/components/schemas/AgentResponseUsage"
        created_at:
          type: integer
          description: Unix timestamp (seconds) when the response was created.
        previous_response_id:
          type: string
          nullable: true
          description: The `previous_response_id` supplied on the request, if any.
        version:
          type: integer
          nullable: true
          description: Agent version used for this response, or null if not versioned.
    AgentResponseOutputItem:
      description: "An output item: an assistant message or a reasoning item."
      oneOf:
        - $ref: "#/components/schemas/AgentResponseOutputMessage"
        - $ref: "#/components/schemas/AgentResponseReasoningItem"
    AgentResponseOutputMessage:
      type: object
      description: An assistant message output item.
      properties:
        id:
          type: string
        type:
          type: string
          enum:
            - message
        role:
          type: string
          enum:
            - assistant
        content:
          type: array
          items:
            $ref: "#/components/schemas/AgentResponseOutputText"
    AgentResponseOutputText:
      type: object
      description: An output text content item.
      properties:
        type:
          type: string
          enum:
            - output_text
        text:
          type: string
          description: The generated text.
    AgentResponseReasoningItem:
      type: object
      description: A reasoning ("thinking") output item.
      properties:
        id:
          type: string
        type:
          type: string
          enum:
            - reasoning
        summary:
          type: array
          items:
            type: object
            properties:
              type:
                type: string
                enum:
                  - summary_text
              text:
                type: string
    AgentResponseUsage:
      type: object
      description: Token usage for the response.
      properties:
        input_tokens:
          type: integer
        output_tokens:
          type: integer
        total_tokens:
          type: integer
    AgentResponsesRequest:
      type: object
      description: OpenAI Responses API-compatible request to invoke an agent.
      properties:
        model:
          type: string
          description: Agent key identifying the agent to run.
        input:
          description: "User message: a plain string, or an array of message items."
          oneOf:
            - type: string
            - type: array
              items:
                $ref: "#/components/schemas/AgentInputMessage"
        previous_response_id:
          type: string
          nullable: true
          description: ID (`resp_{conversationId}`) from a previous response, to continue a multi-turn conversation.
        version:
          type: integer
          minimum: 1
          nullable: true
          description: Specific published version to run (positive integer).
        runtime_context:
          $ref: "#/components/schemas/AgentRuntimeContext"
      required:
        - model
        - input
    AgentRuntimeContext:
      type: object
      description: Caller-supplied runtime context. Headers offered to downstream tools/MCP/connected agents (subject to per-target passthrough policy), plus optional per-target overrides and free-form metadata. Server-stamped fields (userId, tokenId, source) are not client-writable.
      properties:
        headers:
          type: object
          additionalProperties:
            type: string
          description: Headers offered to every outbound target.
        connections:
          type: object
          description: Per-target header overrides, keyed by a bare record key or a kind-prefixed key (`tool:<key>`, `mcp:<key>`, `agent:<key>`). Target-scoped headers win over the global `headers` map.
          additionalProperties:
            type: object
            properties:
              headers:
                type: object
                additionalProperties:
                  type: string
        metadata:
          type: object
          additionalProperties: true
          description: Free-form caller metadata surfaced to logs/traces.
    AgentSummary:
      type: object
      description: Public representation of an agent.
      properties:
        key:
          type: string
          description: Unique agent key.
        name:
          type: string
          description: Human-readable agent name.
        description:
          type: string
          nullable: true
          description: Optional agent description.
        config:
          $ref: "#/components/schemas/AgentConfig"
        status:
          type: string
          enum:
            - active
            - inactive
            - draft
          description: Agent lifecycle status.
        createdAt:
          type: string
          format: date-time
          description: When the agent was created.
    AgentUpdateInput:
      type: object
      additionalProperties: true
      description: Partial update of an agent definition. Only supplied fields are changed.
      properties:
        name:
          type: string
          description: Updated name.
        description:
          type: string
          description: Updated description.
        status:
          type: string
          enum:
            - active
            - inactive
            - draft
          description: Updated status.
        config:
          $ref: "#/components/schemas/AgentConfigInput"
        metadata:
          type: object
          additionalProperties: true
          description: Arbitrary metadata. An `a2a` sub-object updates A2A exposure; the endpoint slug is server-owned and preserved.
    AgentVersionRecord:
      type: object
      additionalProperties: true
      description: A published, immutable agent version snapshot.
      properties:
        version:
          type: integer
          description: Monotonic version number assigned to this publish.
          example: 3
        agentKey:
          type: string
        changelog:
          type: string
          nullable: true
        snapshot:
          type: object
          additionalProperties: true
          description: Frozen snapshot of the agent at publish time.
          properties:
            name:
              type: string
            description:
              type: string
            status:
              type: string
        publishedBy:
          type: string
          description: User id that published the version.
        createdAt:
          type: string
          format: date-time
    AnalyticsDailyPoint:
      type: object
      description: One day of the overview series.
      properties:
        date:
          type: string
        sessionsCount:
          type: number
        totalTokens:
          type: number
    AnalyticsEntityEntry:
      type: object
      description: Per-entity attribution row. `user_id` is present when `group_by=user`; `api_token_id` is present when `group_by=token`.
      properties:
        user_id:
          type: string
        api_token_id:
          type: string
        name:
          type: string
          nullable: true
        label:
          type: string
          nullable: true
        requests:
          type: number
        errors:
          type: number
        input_tokens:
          type: number
        output_tokens:
          type: number
        total_tokens:
          type: number
        cost:
          type: number
    AnalyticsModelEntry:
      type: object
      description: Per-model usage aggregate.
      properties:
        model_key:
          type: string
        model_name:
          type: string
          nullable: true
        category:
          type: string
          nullable: true
        provider_key:
          type: string
          nullable: true
        calls:
          type: number
        input_tokens:
          type: number
        output_tokens:
          type: number
        total_tokens:
          type: number
        cost:
          type: number
    AnalyticsOverview:
      type: object
      description: Dashboard rollup for the token's project.
      properties:
        object:
          type: string
          enum:
            - analytics.overview
        stats:
          $ref: "#/components/schemas/AnalyticsOverviewStats"
        recent_sessions:
          type: array
          items:
            $ref: "#/components/schemas/AnalyticsRecentSession"
        daily:
          type: array
          items:
            $ref: "#/components/schemas/AnalyticsDailyPoint"
    AnalyticsOverviewStats:
      type: object
      description: Dashboard aggregate counters. Inner keys are camelCase, mirroring the dashboard payload.
      properties:
        models:
          type: object
          properties:
            total:
              type: number
            llm:
              type: number
            embedding:
              type: number
        vectors:
          type: object
          properties:
            providers:
              type: number
            indexes:
              type: number
        tracing:
          type: object
          properties:
            totalSessions:
              type: number
            totalTokens:
              type: number
            activeSessions:
              type: number
        apiCalls:
          type: object
          properties:
            total:
              type: number
            trend:
              type: number
              description: Percentage change.
    AnalyticsRecentSession:
      type: object
      description: Recent tracing session summary (camelCase, passed through from the tracing service).
      properties:
        sessionId:
          type: string
        agentName:
          type: string
        status:
          type: string
        startedAt:
          type: string
          format: date-time
        durationMs:
          type: number
        totalEvents:
          type: number
        totalTokens:
          type: number
    AnalyticsServiceEntry:
      type: object
      description: Per-service usage aggregate.
      properties:
        service:
          type: string
        requests:
          type: number
        errors:
          type: number
        input_tokens:
          type: number
        output_tokens:
          type: number
        total_tokens:
          type: number
        cost:
          type: number
    AnalyticsTimeseriesPoint:
      type: object
      description: One time-series bucket at the requested interval.
      properties:
        period:
          type: string
        calls:
          type: number
        total_tokens:
          type: number
        cost:
          type: number
    AnalyticsUsageEntity:
      type: object
      description: "Usage response when `group_by=user` or `group_by=token`: per-entity attribution from the usage rollup."
      properties:
        object:
          type: string
          enum:
            - analytics.usage
        group_by:
          type: string
          enum:
            - user
            - token
        from:
          type: string
          nullable: true
          description: Rollup day (YYYY-MM-DD) or null.
        to:
          type: string
          nullable: true
          description: Rollup day (YYYY-MM-DD) or null.
        currency:
          type: string
        totals:
          $ref: "#/components/schemas/AnalyticsUsageEntityTotals"
        breakdown:
          type: array
          items:
            $ref: "#/components/schemas/AnalyticsEntityEntry"
    AnalyticsUsageEntityTotals:
      type: object
      description: Aggregate totals for the per-entity (`user`/`token`) and `service` envelopes.
      properties:
        requests:
          type: number
        errors:
          type: number
        input_tokens:
          type: number
        output_tokens:
          type: number
        total_tokens:
          type: number
        cost:
          type: number
    AnalyticsUsageModel:
      type: object
      description: "Usage response when `group_by=model`: per-model aggregates plus an interval time-series."
      properties:
        object:
          type: string
          enum:
            - analytics.usage
        group_by:
          type: string
          enum:
            - model
        interval:
          type: string
          enum:
            - hour
            - day
            - month
        from:
          type: string
          format: date-time
          nullable: true
        to:
          type: string
          format: date-time
          nullable: true
        currency:
          type: string
        totals:
          $ref: "#/components/schemas/AnalyticsUsageModelTotals"
        by_model:
          type: array
          items:
            $ref: "#/components/schemas/AnalyticsModelEntry"
        timeseries:
          type: array
          items:
            $ref: "#/components/schemas/AnalyticsTimeseriesPoint"
    AnalyticsUsageModelTotals:
      type: object
      description: Aggregate totals for the `group_by=model` envelope.
      properties:
        cost:
          type: number
        calls:
          type: number
        input_tokens:
          type: number
        output_tokens:
          type: number
        total_tokens:
          type: number
    AnalyticsUsageService:
      type: object
      description: "Usage response when `group_by=service`: per-service breakdown across all services."
      properties:
        object:
          type: string
          enum:
            - analytics.usage
        group_by:
          type: string
          enum:
            - service
        from:
          type: string
          nullable: true
          description: Rollup day (YYYY-MM-DD) or null.
        to:
          type: string
          nullable: true
          description: Rollup day (YYYY-MM-DD) or null.
        currency:
          type: string
        totals:
          $ref: "#/components/schemas/AnalyticsUsageEntityTotals"
        breakdown:
          type: array
          items:
            $ref: "#/components/schemas/AnalyticsServiceEntry"
    AudioBase64Input:
      type: object
      description: Audio supplied inline as base64-encoded bytes.
      required:
        - data
      properties:
        data:
          type: string
          description: Base64-encoded audio bytes.
        fileName:
          type: string
          description: Original file name of the audio.
        contentType:
          type: string
          description: MIME type of the audio (e.g. audio/mpeg).
    AudioSpeechRequest:
      type: object
      required:
        - model
        - input
      properties:
        model:
          type: string
          description: TTS model key.
        input:
          type: string
          description: Text to synthesize.
        voice:
          type: string
          description: Voice name. If omitted, the provider falls back to its default voice.
        response_format:
          type: string
          enum:
            - mp3
            - opus
            - aac
            - flac
            - wav
            - pcm
          description: Output audio format. Invalid values are ignored and the provider default is used.
        speed:
          type: number
          description: Playback speed multiplier.
        instructions:
          type: string
          description: Free-form delivery/style instructions.
    AudioTranscriptionJsonRequest:
      type: object
      required:
        - model
        - audio
      properties:
        model:
          type: string
          description: STT model key.
        audio:
          $ref: "#/components/schemas/AudioBase64Input"
        language:
          type: string
          description: Source language hint (e.g. en).
        prompt:
          type: string
          description: Optional text to guide the model.
        response_format:
          type: string
          description: Transcript format (e.g. json, text, verbose_json).
        temperature:
          type: number
          description: Sampling temperature.
        timestamp_granularities:
          type: array
          description: One or more of word, segment.
          items:
            type: string
            enum:
              - word
              - segment
    AudioTranscriptionMultipartRequest:
      type: object
      required:
        - model
        - file
      properties:
        model:
          type: string
          description: STT model key.
        file:
          type: string
          format: binary
          description: Audio file to transcribe.
        language:
          type: string
          description: Source language hint (e.g. en).
        prompt:
          type: string
          description: Optional text to guide the model.
        response_format:
          type: string
          description: Transcript format (e.g. json, text, verbose_json).
        temperature:
          type: number
          description: Sampling temperature.
        timestamp_granularities[]:
          type: array
          description: One or more of word, segment.
          items:
            type: string
            enum:
              - word
              - segment
    AudioTranscriptionResponse:
      type: object
      description: Transcription result. The exact shape depends on response_format; verbose_json adds segment/word detail.
      properties:
        text:
          type: string
          description: The transcribed text.
        request_id:
          type: string
          description: Request correlation ID.
    AudioTranslationJsonRequest:
      type: object
      required:
        - model
        - audio
      properties:
        model:
          type: string
          description: STT model key.
        audio:
          $ref: "#/components/schemas/AudioBase64Input"
        prompt:
          type: string
          description: Optional text to guide the model.
        response_format:
          type: string
          description: Transcript format (e.g. json, text, verbose_json).
        temperature:
          type: number
          description: Sampling temperature.
    AudioTranslationMultipartRequest:
      type: object
      required:
        - model
        - file
      properties:
        model:
          type: string
          description: STT model key.
        file:
          type: string
          format: binary
          description: Audio file to translate.
        prompt:
          type: string
          description: Optional text to guide the model.
        response_format:
          type: string
          description: Transcript format (e.g. json, text, verbose_json).
        temperature:
          type: number
          description: Sampling temperature.
    AudioTranslationResponse:
      type: object
      description: Translation result (English). The exact shape depends on response_format.
      properties:
        text:
          type: string
          description: The translated English text.
        request_id:
          type: string
          description: Request correlation ID.
    AuditLog:
      type: object
      description: A sanitized audit log entry (`_id` stringified as `id`).
      properties:
        id:
          type: string
        tenantId:
          type: string
        projectId:
          type: string
        requestId:
          type: string
        actorType:
          type: string
          enum:
            - user
            - api_token
            - system
        actorUserId:
          type: string
        actorEmail:
          type: string
        actorRole:
          type: string
        apiTokenId:
          type: string
        service:
          type: string
        action:
          type: string
        event:
          type: string
        method:
          type: string
        path:
          type: string
        statusCode:
          type: number
        outcome:
          type: string
          enum:
            - success
            - failure
            - denied
        ipAddress:
          type: string
        userAgent:
          type: string
        resourceType:
          type: string
        resourceId:
          type: string
        metadata:
          type: object
          additionalProperties: true
        createdAt:
          type: string
          format: date-time
    AuditLogList:
      type: object
      description: A list envelope of sanitized audit log entries.
      properties:
        object:
          type: string
          enum:
            - list
        data:
          type: array
          items:
            $ref: "#/components/schemas/AuditLog"
    AutomationView:
      type: object
      description: Live view of a platform automation (background scheduler or maintenance job).
      required:
        - key
        - name
        - description
        - domain
        - cadenceLabel
        - distributed
        - metrics
        - state
        - supportsPause
        - supportsTrigger
        - lastStartedAt
        - lastCompletedAt
        - lastDurationMs
        - lastError
      properties:
        key:
          type: string
          description: Stable automation key.
          enum:
            - alert-evaluation
            - browser-session-reaper
            - browser-session-reconciliation
            - inference-monitoring-poll
        name:
          type: string
          description: Display name.
        description:
          type: string
          description: What the automation does.
        domain:
          type: string
          description: Functional area.
          enum:
            - alerts
            - browser
            - monitoring
        cadenceLabel:
          type: string
          description: Human cadence, e.g. 'Every 30s' or 'Manual maintenance'.
        distributed:
          type: boolean
          description: Whether runs are guarded by a distributed lock across instances.
        metrics:
          type: object
          description: Per-automation metrics; keys vary by domain (e.g. firedCount/processedTenants for alert-evaluation, dueServers for inference-monitoring-poll, liveSessions for browser-session-reaper).
          additionalProperties: true
        state:
          type: string
          description: Derived live state.
          enum:
            - active
            - degraded
            - idle
            - paused
            - running
        supportsPause:
          type: boolean
          description: Whether pause/resume are available.
        supportsTrigger:
          type: boolean
          description: Whether an immediate run can be triggered.
        lastStartedAt:
          type: string
          format: date-time
          nullable: true
          description: ISO timestamp of the last run start.
        lastCompletedAt:
          type: string
          format: date-time
          nullable: true
          description: ISO timestamp of the last run completion.
        lastDurationMs:
          type: integer
          nullable: true
          description: Duration of the last run, in milliseconds.
        lastError:
          type: string
          nullable: true
          description: Error message from the last run, if any.
    BatchCreateRequest:
      type: object
      description: Batch creation payload. Provide `requests` inline or `input_file`, but not both.
      properties:
        endpoint:
          type: string
          description: Target endpoint every line runs against.
          enum:
            - /v1/chat/completions
            - /v1/embeddings
        requests:
          type: array
          description: Inline request lines. Required unless `input_file` is given.
          items:
            $ref: "#/components/schemas/BatchInlineRequest"
        input_file:
          nullable: true
          description: A JSONL source stored in a bucket. Mutually exclusive with `requests`.
          allOf:
            - $ref: "#/components/schemas/BatchFileRef"
        output_bucket_key:
          type: string
          description: When set, the result JSONL is written to this bucket on completion (`object_key` filled in by the finalizer).
        completion_window:
          type: string
          description: Informational (OpenAI compat); defaults to `24h`.
        metadata:
          type: object
          additionalProperties: true
          description: Arbitrary key/value metadata echoed back on the batch.
      required:
        - endpoint
    BatchFileRef:
      type: object
      description: A reference to a JSONL object stored in a Document Store bucket.
      properties:
        bucket_key:
          type: string
          description: The bucket key.
        object_key:
          type: string
          nullable: true
          description: The object key within the bucket. May be null on an output file until the finalizer fills it in.
    BatchInlineRequest:
      type: object
      description: A single inline request line. If no `body` key is present, the object itself is treated as the body.
      properties:
        custom_id:
          type: string
          description: Optional caller-supplied line identifier echoed back on the item and result.
        body:
          type: object
          additionalProperties: true
          description: "The request payload. Must include `model`. For `/v1/chat/completions`, `messages` (array) is required; for `/v1/embeddings`, `input` is required. `stream: true` is rejected."
      required:
        - body
    BatchItem:
      type: object
      description: Per-line execution status within a batch.
      properties:
        id:
          type: string
          description: The item id.
        object:
          type: string
          description: Always `batch.item`.
          example: batch.item
        index:
          type: integer
          description: Zero-based position of the line in the batch.
        custom_id:
          type: string
          nullable: true
          description: The caller-supplied line identifier, if any.
        status:
          type: string
          description: Item execution status.
          enum:
            - pending
            - running
            - succeeded
            - failed
            - cancelled
        response_status_code:
          type: integer
          nullable: true
          description: HTTP status code of the underlying request.
        response_body:
          type: object
          additionalProperties: true
          nullable: true
          description: The model response body when succeeded, otherwise null.
        error_message:
          type: string
          nullable: true
          description: Error message when the item failed.
        usage:
          nullable: true
          description: Token usage, or null until the item runs.
          allOf:
            - $ref: "#/components/schemas/BatchItemUsage"
        started_at:
          type: integer
          nullable: true
          description: Item start time in Unix seconds.
        ended_at:
          type: integer
          nullable: true
          description: Item end time in Unix seconds.
    BatchItemList:
      type: object
      description: A list envelope of batch item objects.
      properties:
        object:
          type: string
          description: Always `list`.
          example: list
        data:
          type: array
          items:
            $ref: "#/components/schemas/BatchItem"
    BatchItemUsage:
      type: object
      description: Token usage for a single item. Null until the item runs.
      properties:
        input_tokens:
          type: integer
        output_tokens:
          type: integer
        total_tokens:
          type: integer
    BatchList:
      type: object
      description: A list envelope of batch objects.
      properties:
        object:
          type: string
          description: Always `list`.
          example: list
        data:
          type: array
          items:
            $ref: "#/components/schemas/BatchObject"
    BatchObject:
      type: object
      description: An asynchronous bulk-inference batch job.
      properties:
        id:
          type: string
          description: The batch id.
        object:
          type: string
          description: Always `batch`.
          example: batch
        endpoint:
          type: string
          description: Target endpoint the lines run against.
          example: /v1/chat/completions
        status:
          type: string
          description: Batch lifecycle status.
          enum:
            - validating
            - in_progress
            - completed
            - failed
            - cancelling
            - cancelled
        completion_window:
          type: string
          nullable: true
          description: Informational completion window (OpenAI compat), e.g. `24h`.
        input_file:
          nullable: true
          description: The JSONL input file reference, or null when the batch was created with inline `requests`.
          allOf:
            - $ref: "#/components/schemas/BatchFileRef"
        output_file:
          nullable: true
          description: The JSONL output file reference when `output_bucket_key` was set and the batch finalized, otherwise null.
          allOf:
            - $ref: "#/components/schemas/BatchFileRef"
        error_message:
          type: string
          nullable: true
          description: Batch-level error message, if any.
        request_counts:
          $ref: "#/components/schemas/BatchRequestCounts"
        usage:
          $ref: "#/components/schemas/BatchUsage"
        metadata:
          type: object
          additionalProperties: true
          description: Arbitrary metadata echoed back on the batch.
        created_at:
          type: integer
          nullable: true
          description: Creation time in Unix seconds.
        started_at:
          type: integer
          nullable: true
          description: Start time in Unix seconds.
        completed_at:
          type: integer
          nullable: true
          description: Completion time in Unix seconds.
        cancelled_at:
          type: integer
          nullable: true
          description: Cancellation time in Unix seconds.
    BatchRequestCounts:
      type: object
      description: Per-status item counts for the batch.
      properties:
        total:
          type: integer
          description: Total number of request lines.
        completed:
          type: integer
          description: Number of items that succeeded.
        failed:
          type: integer
          description: Number of items that failed.
        cancelled:
          type: integer
          description: Number of items that were cancelled.
    BatchUsage:
      type: object
      description: Aggregate token usage across the batch.
      properties:
        input_tokens:
          type: integer
        output_tokens:
          type: integer
        total_tokens:
          type: integer
    BrowserAccessRules:
      type: object
      description: Host allow/block rules applied to navigation.
      properties:
        allowList:
          type: array
          description: Host patterns the browser is allowed to navigate to.
          items:
            type: string
        blockList:
          type: array
          description: Host patterns to block. Evaluated after allowList.
          items:
            type: string
    BrowserAction:
      description: A single browser action. The `type` field discriminates the variant.
      oneOf:
        - type: object
          required:
            - type
            - url
          properties:
            type:
              type: string
              enum:
                - goto
            url:
              type: string
              format: uri
              description: Fully-qualified URL including scheme.
            waitUntil:
              type: string
              enum:
                - load
                - domcontentloaded
                - networkidle
            timeout:
              type: integer
        - type: object
          required:
            - type
          description: Click an element. Either selector or ref is required.
          properties:
            type:
              type: string
              enum:
                - click
            selector:
              type: string
            ref:
              type: string
            button:
              type: string
              enum:
                - left
                - right
                - middle
            timeout:
              type: integer
        - type: object
          required:
            - type
          description: Hover an element. Either selector or ref is required.
          properties:
            type:
              type: string
              enum:
                - hover
            selector:
              type: string
            ref:
              type: string
            timeout:
              type: integer
        - type: object
          required:
            - type
            - text
          description: Type text into a field. Either selector or ref is required.
          properties:
            type:
              type: string
              enum:
                - type
            selector:
              type: string
            ref:
              type: string
            text:
              type: string
              maxLength: 10000
            delay:
              type: integer
            clear:
              type: boolean
        - type: object
          required:
            - type
            - key
          description: Press a keyboard key. Either selector or ref is required.
          properties:
            type:
              type: string
              enum:
                - press
            selector:
              type: string
            ref:
              type: string
            key:
              type: string
        - type: object
          required:
            - type
          description: Wait for a fixed duration or a selector state. Either ms or selector is required.
          properties:
            type:
              type: string
              enum:
                - wait
            selector:
              type: string
            ms:
              type: integer
            state:
              type: string
              enum:
                - attached
                - detached
                - visible
                - hidden
        - type: object
          required:
            - type
          description: Scroll the page or an element. Provide selector/ref or x/y coordinates.
          properties:
            type:
              type: string
              enum:
                - scroll
            selector:
              type: string
            ref:
              type: string
            x:
              type: integer
            y:
              type: integer
    BrowserActionResult:
      type: object
      description: Result of running a browser action.
      properties:
        ok:
          type: boolean
        url:
          type: string
        pageTitle:
          type: string
        ariaSnapshot:
          type: string
          description: Aria reference snapshot of the page after the action (YAML).
        artifact:
          $ref: "#/components/schemas/BrowserArtifactRef"
        errorMessage:
          type: string
    BrowserArtifactRef:
      type: object
      description: Reference to a persisted artifact (screenshot / PDF) in a Files bucket.
      properties:
        bucketKey:
          type: string
        fileId:
          type: string
        objectKey:
          type: string
        url:
          type: string
          description: Relative download URL for the artifact object.
        contentType:
          type: string
    BrowserArtifactResult:
      type: object
      description: Result of persisting a screenshot or PDF.
      properties:
        artifact:
          $ref: "#/components/schemas/BrowserArtifactRef"
        eventId:
          type: string
          description: Id of the session event recorded for this capture.
    BrowserCloseResult:
      type: object
      properties:
        closed:
          type: boolean
    BrowserCreateRequest:
      type: object
      required:
        - name
      properties:
        key:
          type: string
          description: Optional lowercase kebab-case unique key (auto-generated when omitted).
        name:
          type: string
          minLength: 2
          maxLength: 120
        description:
          type: string
          maxLength: 1000
        status:
          type: string
          enum:
            - active
            - disabled
        artifactBucketKey:
          type: string
          maxLength: 120
        defaultSessionConfig:
          $ref: "#/components/schemas/BrowserSessionConfig"
        defaultModelKey:
          type: string
          maxLength: 120
        defaultRunOptions:
          $ref: "#/components/schemas/BrowserRunOptions"
        metadata:
          type: object
          additionalProperties: true
    BrowserExtractRequest:
      type: object
      description: Extract text/html/attribute from the page. Either selector or ref is required; attribute is required when mode is `attr`.
      properties:
        selector:
          type: string
        ref:
          type: string
        mode:
          type: string
          enum:
            - text
            - html
            - attr
        attribute:
          type: string
        multiple:
          type: boolean
          description: When true, extract from all matching elements.
    BrowserExtractResult:
      type: object
      description: Result of an extract operation.
      properties:
        ok:
          type: boolean
        values:
          type: array
          items:
            type: string
        errorMessage:
          type: string
    BrowserJsonRpcRequest:
      type: object
      required:
        - method
      description: A JSON-RPC 2.0 request for the browser MCP server.
      properties:
        jsonrpc:
          type: string
          enum:
            - "2.0"
        id:
          description: Request id (string, number or null).
          oneOf:
            - type: string
            - type: number
          nullable: true
        method:
          type: string
          description: "One of: initialize, notifications/initialized, ping, tools/list, tools/call."
        params:
          type: object
          additionalProperties: true
          description: "Method parameters. For tools/call: { name, arguments }."
    BrowserJsonRpcResponse:
      type: object
      description: A JSON-RPC 2.0 response from the browser MCP server.
      properties:
        jsonrpc:
          type: string
          enum:
            - "2.0"
        id:
          oneOf:
            - type: string
            - type: number
          nullable: true
        result:
          type: object
          additionalProperties: true
          description: "Present on success. For tools/list this is { tools: [...] }; for tools/call this is { content: [{ type, text }], isError }."
        error:
          type: object
          description: Present on JSON-RPC error.
          properties:
            code:
              type: integer
            message:
              type: string
    BrowserMcpTool:
      type: object
      description: A Browser Use-compatible MCP tool descriptor (browser_navigate, browser_click, …).
      properties:
        name:
          type: string
        description:
          type: string
        inputSchema:
          type: object
          additionalProperties: true
    BrowserPdfRequest:
      type: object
      properties:
        format:
          type: string
          enum:
            - A4
            - Letter
            - Legal
            - A3
            - A5
        landscape:
          type: boolean
        printBackground:
          type: boolean
    BrowserProfile:
      type: object
      description: A reusable browser profile (parent container) holding shared session defaults, artifact bucket and default model/runtime metadata.
      properties:
        id:
          type: string
        tenantId:
          type: string
        projectId:
          type: string
          nullable: true
        key:
          type: string
          description: URL-friendly unique identifier scoped to the tenant/project.
        name:
          type: string
        description:
          type: string
        status:
          type: string
          enum:
            - active
            - disabled
        artifactBucketKey:
          type: string
          description: Default Files bucket where screenshots / PDFs are persisted.
        defaultSessionConfig:
          $ref: "#/components/schemas/BrowserSessionConfig"
        defaultModelKey:
          type: string
        defaultRunOptions:
          $ref: "#/components/schemas/BrowserRunOptions"
        metadata:
          type: object
          additionalProperties: true
        createdBy:
          type: string
        updatedBy:
          type: string
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    BrowserRunOptions:
      type: object
      description: Default agent runtime knobs applied when running agents under this browser.
      properties:
        maxSteps:
          type: integer
        temperature:
          type: number
        runtimeProfile:
          type: string
    BrowserScreenshotRequest:
      type: object
      properties:
        fullPage:
          type: boolean
        selector:
          type: string
        ref:
          type: string
        type:
          type: string
          enum:
            - png
            - jpeg
        quality:
          type: integer
          minimum: 1
          maximum: 100
          description: JPEG quality (only used when type is jpeg).
    BrowserSession:
      type: object
      description: A live browser automation session belonging to a browser profile.
      properties:
        id:
          type: string
        tenantId:
          type: string
        projectId:
          type: string
          nullable: true
        browserId:
          type: string
          description: Parent browser profile that owns this session.
        sessionKey:
          type: string
          description: Stable session key exposed to clients.
        name:
          type: string
        agentId:
          type: string
        agentKey:
          type: string
        status:
          type: string
          enum:
            - pending
            - running
            - idle
            - closed
            - errored
            - expired
        config:
          $ref: "#/components/schemas/BrowserSessionConfig"
        currentUrl:
          type: string
        pageTitle:
          type: string
        lastActivityAt:
          type: string
          format: date-time
        lastScreenshot:
          type: object
          description: Reference to the last persisted screenshot artifact.
          properties:
            bucketKey:
              type: string
            fileId:
              type: string
            objectKey:
              type: string
            capturedAt:
              type: string
              format: date-time
        artifactBucketKey:
          type: string
        startedAt:
          type: string
          format: date-time
        endedAt:
          type: string
          format: date-time
        errorMessage:
          type: string
        eventCount:
          type: integer
        metadata:
          type: object
          additionalProperties: true
        createdBy:
          type: string
        updatedBy:
          type: string
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    BrowserSessionConfig:
      type: object
      description: Browser session configuration applied to a spawned session.
      properties:
        headless:
          type: boolean
        viewport:
          type: object
          properties:
            width:
              type: integer
            height:
              type: integer
        userAgent:
          type: string
        locale:
          type: string
        idleTimeoutMs:
          type: integer
          description: Auto-close after this many ms of inactivity.
        maxLifetimeMs:
          type: integer
          description: Hard upper bound on session lifetime (ms).
        actionTimeoutMs:
          type: integer
          description: Default per-action timeout (click/hover/type/snapshot).
        navigationTimeoutMs:
          type: integer
          description: Default navigation timeout (goto).
        access:
          $ref: "#/components/schemas/BrowserAccessRules"
    BrowserSessionCreateRequest:
      type: object
      required:
        - browserId
      properties:
        browserId:
          type: string
          minLength: 1
          maxLength: 128
          description: Parent browser profile id.
        name:
          type: string
          maxLength: 120
        agentKey:
          type: string
          maxLength: 120
        agentId:
          type: string
          maxLength: 128
        artifactBucketKey:
          type: string
          maxLength: 120
        config:
          $ref: "#/components/schemas/BrowserSessionConfig"
        metadata:
          type: object
          additionalProperties: true
    BrowserSessionEvent:
      type: object
      description: A single recorded event in a browser session timeline.
      properties:
        id:
          type: string
        tenantId:
          type: string
        projectId:
          type: string
          nullable: true
        sessionId:
          type: string
        sequence:
          type: integer
          description: Sequence index for ordering within a session.
        type:
          type: string
          enum:
            - create
            - goto
            - click
            - hover
            - type
            - press
            - wait
            - scroll
            - extract
            - snapshot
            - screenshot
            - pdf
            - tool_call
            - agent_event
            - close
            - error
        status:
          type: string
          enum:
            - success
            - error
        url:
          type: string
        selector:
          type: string
        ref:
          type: string
        durationMs:
          type: integer
        artifact:
          type: object
          properties:
            bucketKey:
              type: string
            fileId:
              type: string
            objectKey:
              type: string
            contentType:
              type: string
        data:
          type: object
          additionalProperties: true
          description: Compact, sanitized payload (not raw HTML / large blobs).
        errorMessage:
          type: string
        createdAt:
          type: string
          format: date-time
    BrowserSnapshotResult:
      type: object
      description: Aria snapshot of the current page.
      properties:
        ariaSnapshot:
          type: string
          description: Aria-snapshot of the page (YAML).
        url:
          type: string
    BrowserUpdateRequest:
      type: object
      description: Partial update of a browser profile. All fields optional.
      properties:
        key:
          type: string
        name:
          type: string
          minLength: 2
          maxLength: 120
        description:
          type: string
          maxLength: 1000
        status:
          type: string
          enum:
            - active
            - disabled
        artifactBucketKey:
          type: string
          maxLength: 120
        defaultSessionConfig:
          $ref: "#/components/schemas/BrowserSessionConfig"
        defaultModelKey:
          type: string
          maxLength: 120
        defaultRunOptions:
          $ref: "#/components/schemas/BrowserRunOptions"
        metadata:
          type: object
          additionalProperties: true
    ChatChoice:
      type: object
      properties:
        index:
          type: integer
          description: Index of the choice in the list.
        message:
          $ref: "#/components/schemas/ChatMessage"
        finish_reason:
          type: string
          enum:
            - stop
            - length
            - tool_calls
            - content_filter
          description: Reason the model stopped generating tokens.
    ChatCompletionRequest:
      type: object
      required:
        - model
        - messages
      properties:
        model:
          type: string
          description: Model key configured in the dashboard (e.g., gpt-4, gpt-3.5-turbo).
          example: gpt-4
        messages:
          type: array
          description: Ordered list of messages that make up the conversation.
          items:
            $ref: "#/components/schemas/ChatMessage"
        temperature:
          type: number
          minimum: 0
          maximum: 2
          default: 1
          description: Sampling temperature between 0 and 2.
        top_p:
          type: number
          minimum: 0
          maximum: 1
          default: 1
          description: Nucleus sampling probability mass.
        max_tokens:
          type: integer
          minimum: 1
          description: Maximum number of tokens to generate in the response.
        max_completion_tokens:
          type: integer
          minimum: 1
          description: Alternative to `max_tokens` for the maximum number of completion tokens; takes precedence when both are supplied.
        stream:
          type: boolean
          default: false
          description: When true, partial deltas are returned as a `text/event-stream` of SSE chunks.
        stop:
          description: Up to a few sequences where generation stops.
          oneOf:
            - type: string
            - type: array
              items:
                type: string
        presence_penalty:
          type: number
          minimum: -2
          maximum: 2
          default: 0
          description: Penalizes new tokens based on whether they already appear in the text.
        frequency_penalty:
          type: number
          minimum: -2
          maximum: 2
          default: 0
          description: Penalizes new tokens based on their existing frequency in the text.
        user:
          type: string
          description: Opaque end-user identifier for abuse monitoring.
        request_id:
          type: string
          description: Optional client-provided correlation identifier echoed back on the response.
        tools:
          type: array
          description: List of tools (functions) the model may call.
          items:
            $ref: "#/components/schemas/ChatTool"
        tool_choice:
          description: Controls which (if any) tool the model calls.
          oneOf:
            - type: string
              enum:
                - none
                - auto
            - type: object
    ChatCompletionResponse:
      type: object
      properties:
        id:
          type: string
          description: Unique identifier for the chat completion.
        object:
          type: string
          example: chat.completion
          description: The object type, always `chat.completion`.
        created:
          type: integer
          description: Unix timestamp (seconds) of when the completion was created.
        model:
          type: string
          description: The model key used for the completion.
        choices:
          type: array
          description: List of completion choices.
          items:
            $ref: "#/components/schemas/ChatChoice"
        usage:
          $ref: "#/components/schemas/ChatUsage"
        request_id:
          type: string
          description: Correlation identifier for the request.
    ChatMessage:
      type: object
      required:
        - role
      properties:
        role:
          type: string
          enum:
            - system
            - user
            - assistant
            - tool
          description: The role of the message author.
        content:
          type: string
          nullable: true
          description: The text content of the message. May be null for assistant messages that only contain tool calls.
        name:
          type: string
          description: Optional name of the author of this message.
        tool_calls:
          type: array
          description: Tool calls generated by the model, present on assistant messages.
          items:
            $ref: "#/components/schemas/ChatToolCall"
        tool_call_id:
          type: string
          description: For `tool` role messages, the id of the tool call this message responds to.
    ChatTool:
      type: object
      required:
        - type
        - function
      properties:
        type:
          type: string
          enum:
            - function
          description: The type of the tool; currently always `function`.
        function:
          type: object
          required:
            - name
          properties:
            name:
              type: string
              description: The name of the function to be called.
            description:
              type: string
              description: A description of what the function does, used by the model to decide when to call it.
            parameters:
              type: object
              description: The parameters the function accepts, described as a JSON Schema object.
    ChatToolCall:
      type: object
      required:
        - id
        - type
        - function
      properties:
        id:
          type: string
          description: The id of the tool call.
        type:
          type: string
          enum:
            - function
          description: The type of the tool call; currently always `function`.
        function:
          type: object
          properties:
            name:
              type: string
              description: The name of the function to call.
            arguments:
              type: string
              description: The function arguments as a JSON-encoded string.
    ChatUsage:
      type: object
      properties:
        prompt_tokens:
          type: integer
          description: Number of tokens in the prompt.
        completion_tokens:
          type: integer
          description: Number of tokens in the generated completion.
        total_tokens:
          type: integer
          description: Total number of tokens used (prompt + completion).
        cached_tokens:
          type: integer
          description: Number of prompt tokens served from cache, when supported.
    ConfigAuditLog:
      type: object
      description: An audit trail entry for a config item.
      properties:
        _id:
          type: string
        configKey:
          type: string
          description: Key of the audited config item.
        action:
          type: string
          enum:
            - create
            - read
            - update
            - delete
          description: Action that was performed.
        version:
          type: integer
          description: Item version at the time of the action.
        performedBy:
          type: string
          description: Identifier of the actor.
        createdAt:
          type: string
          format: date-time
    ConfigGroup:
      type: object
      description: A container that organizes related config items.
      properties:
        _id:
          type: string
          description: Unique identifier.
        key:
          type: string
          description: Unique key of the group.
        name:
          type: string
          description: Human-readable name.
        description:
          type: string
          nullable: true
          description: Description.
        tags:
          type: array
          items:
            type: string
          description: Categorization tags.
        metadata:
          type: object
          additionalProperties: true
          description: Custom metadata.
        createdBy:
          type: string
          description: Identifier of the creator.
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    ConfigGroupCreateRequest:
      type: object
      required:
        - name
      properties:
        name:
          type: string
          description: Human-readable name.
        key:
          type: string
          description: Unique key (auto-generated from name if omitted).
        description:
          type: string
          description: Description.
        tags:
          type: array
          items:
            type: string
          description: Categorization tags.
        metadata:
          type: object
          additionalProperties: true
          description: Custom metadata.
    ConfigGroupUpdateRequest:
      type: object
      properties:
        name:
          type: string
          description: Human-readable name.
        description:
          type: string
          description: Description.
        tags:
          type: array
          items:
            type: string
          description: Categorization tags.
        metadata:
          type: object
          additionalProperties: true
          description: Custom metadata.
    ConfigGroupWithItems:
      allOf:
        - $ref: "#/components/schemas/ConfigGroup"
        - type: object
          properties:
            items:
              type: array
              description: Config items belonging to the group. Secret values are masked.
              items:
                $ref: "#/components/schemas/ConfigItem"
    ConfigItem:
      type: object
      description: A configuration value belonging to a group. Secret values are masked in list/get responses.
      properties:
        _id:
          type: string
          description: Unique identifier.
        key:
          type: string
          description: Unique key of the item.
        groupId:
          type: string
          description: Identifier of the parent group.
        name:
          type: string
          description: Human-readable name.
        description:
          type: string
          nullable: true
          description: Description.
        value:
          type: string
          description: Configuration value. Masked when the item is a secret.
        valueType:
          type: string
          enum:
            - string
            - number
            - boolean
            - json
          description: Type of the stored value.
        isSecret:
          type: boolean
          description: Whether the value is encrypted at rest.
        tags:
          type: array
          items:
            type: string
          description: Categorization tags.
        metadata:
          type: object
          additionalProperties: true
          description: Custom metadata.
        version:
          type: integer
          description: Monotonic version incremented on each update.
        createdBy:
          type: string
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    ConfigItemCreateRequest:
      type: object
      required:
        - name
        - value
      properties:
        name:
          type: string
          description: Human-readable name.
        key:
          type: string
          description: Unique key (auto-generated from name if omitted).
        description:
          type: string
          description: Description.
        value:
          type: string
          description: Configuration value.
        valueType:
          type: string
          enum:
            - string
            - number
            - boolean
            - json
          default: string
          description: Type of the stored value.
        isSecret:
          type: boolean
          default: false
          description: Encrypt the value at rest.
        tags:
          type: array
          items:
            type: string
          description: Categorization tags.
        metadata:
          type: object
          additionalProperties: true
          description: Custom metadata.
    ConfigItemUpdateRequest:
      type: object
      description: All fields are optional.
      properties:
        name:
          type: string
          description: Human-readable name.
        description:
          type: string
          description: Description.
        value:
          type: string
          description: Configuration value. Re-encrypted automatically for secrets.
        valueType:
          type: string
          enum:
            - string
            - number
            - boolean
            - json
          description: Type of the stored value.
        isSecret:
          type: boolean
          description: Whether the value is encrypted at rest.
        tags:
          type: array
          items:
            type: string
          description: Categorization tags.
        metadata:
          type: object
          additionalProperties: true
          description: Custom metadata.
    ConfigResolveRequest:
      type: object
      required:
        - keys
      properties:
        keys:
          type: array
          description: Config item keys to resolve. Maximum 50 per request.
          items:
            type: string
          minItems: 1
          maxItems: 50
    ConfigResolvedValue:
      type: object
      description: A decrypted config value.
      properties:
        value:
          type: string
          description: Decrypted value.
        valueType:
          type: string
          enum:
            - string
            - number
            - boolean
            - json
          description: Type of the stored value.
        version:
          type: integer
          description: Current version of the item.
    Crawler:
      type: object
      description: A saved crawler profile.
      properties:
        id:
          type: string
        key:
          type: string
        name:
          type: string
        description:
          type: string
        status:
          type: string
          enum:
            - active
            - disabled
        engine:
          type: string
          enum:
            - axios
            - playwright
            - auto
        maxDepth:
          type: integer
        maxPages:
          type: integer
        autoCrawl:
          type: boolean
        seeds:
          type: array
          items:
            type: string
            format: uri
        scope:
          $ref: "#/components/schemas/CrawlerScope"
        http:
          $ref: "#/components/schemas/CrawlerHttpOptions"
        downloadableMimes:
          type: array
          items:
            type: string
        markdownOptions:
          $ref: "#/components/schemas/CrawlerMarkdownOptions"
        rag:
          nullable: true
          allOf:
            - $ref: "#/components/schemas/CrawlerRag"
        webhook:
          nullable: true
          allOf:
            - $ref: "#/components/schemas/CrawlerWebhook"
        schedule:
          nullable: true
          allOf:
            - $ref: "#/components/schemas/CrawlerSchedule"
        metadata:
          type: object
          additionalProperties: true
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    CrawlerAdhocRunInput:
      type: object
      description: Fields for a one-off crawl without saving a crawler.
      required:
        - seeds
      properties:
        seeds:
          type: array
          minItems: 1
          maxItems: 50
          items:
            type: string
            format: uri
          description: 1-50 seed URLs.
        engine:
          type: string
          enum:
            - axios
            - playwright
            - auto
          default: auto
        maxDepth:
          type: integer
          minimum: 0
          maximum: 3
          default: 0
        maxPages:
          type: integer
          minimum: 0
          maximum: 5000
          default: 20
        autoCrawl:
          type: boolean
          default: false
        scope:
          $ref: "#/components/schemas/CrawlerScope"
        http:
          $ref: "#/components/schemas/CrawlerHttpOptions"
        downloadableMimes:
          type: array
          items:
            type: string
        markdownOptions:
          $ref: "#/components/schemas/CrawlerMarkdownOptions"
        rag:
          $ref: "#/components/schemas/CrawlerRag"
        webhook:
          $ref: "#/components/schemas/CrawlerWebhook"
        callbackUrl:
          type: string
          format: uri
          description: Per-run webhook receiver.
        mode:
          type: string
          enum:
            - sync
            - async
          description: Run mode. Omit to use the API default (async).
        metadata:
          type: object
          additionalProperties: true
    CrawlerCookie:
      type: object
      description: A cookie sent with crawl requests.
      required:
        - name
        - value
      properties:
        name:
          type: string
          minLength: 1
        value:
          type: string
        domain:
          type: string
        path:
          type: string
        secure:
          type: boolean
        httpOnly:
          type: boolean
        sameSite:
          type: string
          enum:
            - Strict
            - Lax
            - None
        expires:
          type: number
    CrawlerCrawlInput:
      type: object
      description: Explicit set of URLs to crawl using a saved crawler's config.
      required:
        - urls
      properties:
        urls:
          type: array
          minItems: 1
          maxItems: 500
          items:
            type: string
            format: uri
          description: URLs to crawl.
        callbackUrl:
          type: string
          format: uri
          description: Per-run webhook receiver.
        mode:
          type: string
          enum:
            - sync
            - async
          description: Run mode. Omit to use the API default (async).
        metadata:
          type: object
          additionalProperties: true
          description: Stored on the job.
    CrawlerCreateInput:
      type: object
      description: Fields for creating a crawler profile.
      required:
        - name
      properties:
        key:
          type: string
          minLength: 1
          maxLength: 120
          pattern: ^[a-z0-9][a-z0-9_-]*$
          description: URL-friendly id, unique per tenant/project. Derived from name if omitted.
        name:
          type: string
          minLength: 1
          maxLength: 200
          description: Display name.
        description:
          type: string
          maxLength: 2000
        seeds:
          type: array
          maxItems: 500
          items:
            type: string
            format: uri
          description: Initial URL list. URLs can also be managed via /urls.
        engine:
          type: string
          enum:
            - axios
            - playwright
            - auto
          default: auto
          description: Fetch engine; playwright renders JS.
        maxDepth:
          type: integer
          minimum: 0
          maximum: 3
          default: 0
          description: Link-follow depth. 0 = only the given URLs.
        maxPages:
          type: integer
          minimum: 0
          maximum: 5000
          default: 50
          description: Page cap. 0 = unlimited.
        autoCrawl:
          type: boolean
          default: false
          description: Follow discovered links within scope.
        scope:
          $ref: "#/components/schemas/CrawlerScope"
        http:
          $ref: "#/components/schemas/CrawlerHttpOptions"
        downloadableMimes:
          type: array
          items:
            type: string
          description: MIME types treated as downloadable files.
        markdownOptions:
          $ref: "#/components/schemas/CrawlerMarkdownOptions"
        rag:
          $ref: "#/components/schemas/CrawlerRag"
        webhook:
          $ref: "#/components/schemas/CrawlerWebhook"
        schedule:
          $ref: "#/components/schemas/CrawlerSchedule"
        metadata:
          type: object
          additionalProperties: true
          description: Arbitrary key/value bag.
    CrawlerHttpOptions:
      type: object
      description: HTTP fetch options applied to each request.
      properties:
        userAgent:
          type: string
        acceptLanguage:
          type: string
        timeoutMs:
          type: integer
          minimum: 1000
          maximum: 120000
        maxConcurrency:
          type: integer
          minimum: 1
          maximum: 16
        retries:
          type: integer
          minimum: 1
          maximum: 5
        headers:
          type: object
          additionalProperties:
            type: string
          description: Extra request headers.
        cookies:
          type: array
          items:
            $ref: "#/components/schemas/CrawlerCookie"
        basicAuth:
          type: object
          required:
            - username
            - password
          properties:
            username:
              type: string
            password:
              type: string
        bearerToken:
          type: string
        allowPrivateNetwork:
          type: boolean
        allowInsecureTls:
          type: boolean
          description: Skip TLS certificate verification - opt-in escape hatch for sites with a misconfigured cert chain.
    CrawlerJob:
      type: object
      description: A crawl job enqueued from a crawler run or an ad-hoc run.
      properties:
        id:
          type: string
        crawlerKey:
          type: string
          nullable: true
          description: Parent crawler key; null for ad-hoc jobs.
        trigger:
          type: string
          enum:
            - manual
            - api
            - adhoc
            - schedule
          description: How the job was started.
        status:
          type: string
          enum:
            - queued
            - running
            - succeeded
            - partial
            - failed
            - canceled
        pagesDiscovered:
          type: integer
        pagesProcessed:
          type: integer
        filesProcessed:
          type: integer
        errorsCount:
          type: integer
        limitReached:
          type: boolean
        planSnapshot:
          type: object
          additionalProperties: true
          description: Frozen crawl config used for this job.
        errorMessage:
          type: string
          nullable: true
        startedAt:
          type: string
          format: date-time
          nullable: true
        endedAt:
          type: string
          format: date-time
          nullable: true
        durationMs:
          type: integer
          nullable: true
    CrawlerMarkdownOptions:
      type: object
      description: Options forwarded to the Markdown extractor.
      properties:
        ocr:
          type: object
          required:
            - enabled
          properties:
            enabled:
              type: boolean
            languages:
              type: array
              items:
                type: string
        outputFormat:
          type: string
          enum:
            - markdown
            - text
        cleanup:
          type: boolean
        stripDataImages:
          type: boolean
        mainContentOnly:
          type: boolean
        contentSelector:
          type: string
          maxLength: 200
        removeSelectors:
          type: array
          maxItems: 50
          items:
            type: string
            maxLength: 200
        maxBodyChars:
          type: integer
          minimum: 0
          maximum: 5000000
    CrawlerRag:
      type: object
      description: Knowledge Engine binding - ingest crawled pages into a module.
      required:
        - ragModuleKey
        - enabled
      properties:
        ragModuleKey:
          type: string
          minLength: 1
        enabled:
          type: boolean
    CrawlerResult:
      type: object
      description: A single fetched page or file stored for a crawl job.
      properties:
        id:
          type: string
        jobId:
          type: string
        url:
          type: string
          format: uri
        parentUrl:
          type: string
          format: uri
          nullable: true
        depth:
          type: integer
        type:
          type: string
          enum:
            - html
            - file
            - error
        httpStatus:
          type: integer
          nullable: true
        contentType:
          type: string
          nullable: true
        title:
          type: string
          nullable: true
        bodyMarkdown:
          type: string
          nullable: true
          description: Extracted Markdown; present for html results.
        bytes:
          type: integer
          nullable: true
        ragDocumentId:
          type: string
          nullable: true
        ragStatus:
          type: string
          nullable: true
          enum:
            - pending
            - indexed
            - skipped
            - failed
          description: Knowledge Engine ingestion status; present only when the crawler has a binding.
        errorMessage:
          type: string
          nullable: true
          description: Present for error results.
        fetchedAt:
          type: string
          format: date-time
    CrawlerRunAccepted:
      type: object
      description: "Async run acknowledgement: the job was enqueued."
      required:
        - jobId
        - status
      properties:
        jobId:
          type: string
        status:
          type: string
          example: queued
    CrawlerRunOptions:
      type: object
      description: Options for running a saved crawler. All fields optional; defaults to the crawler's saved config and async mode.
      properties:
        urls:
          type: array
          maxItems: 500
          items:
            type: string
            format: uri
          description: URLs to crawl. Overrides the saved container targets for this run.
        seeds:
          type: array
          maxItems: 500
          items:
            type: string
            format: uri
          description: Legacy alias for urls.
        callbackUrl:
          type: string
          format: uri
          description: Per-run webhook receiver.
        mode:
          type: string
          enum:
            - sync
            - async
          description: Run mode. Omit to use the API default (async).
        metadata:
          type: object
          additionalProperties: true
          description: Stored on the job.
    CrawlerRunSyncResult:
      type: object
      description: "Sync run result: the finished job state with its results inlined (up to 100 results)."
      required:
        - jobId
        - status
        - results
      properties:
        jobId:
          type: string
        status:
          type: string
        pagesProcessed:
          type: integer
          nullable: true
        filesProcessed:
          type: integer
          nullable: true
        errorsCount:
          type: integer
          nullable: true
        results:
          type: array
          items:
            $ref: "#/components/schemas/CrawlerResult"
    CrawlerSchedule:
      type: object
      description: Recurring schedule for the crawler. Interval mode needs intervalSeconds; cron mode needs cron.
      required:
        - mode
        - enabled
      properties:
        mode:
          type: string
          enum:
            - interval
            - cron
        enabled:
          type: boolean
        intervalSeconds:
          type: integer
          minimum: 60
          maximum: 86400
        cron:
          type: string
          minLength: 1
          maxLength: 120
        startAt:
          type: string
          format: date-time
        endAt:
          type: string
          format: date-time
    CrawlerScope:
      type: object
      description: Scope filters constraining which discovered links are followed.
      properties:
        sameDomainOnly:
          type: boolean
          default: true
          description: Restrict crawling to the seed's domain.
        includeSubdomains:
          type: boolean
          default: false
          description: Allow subdomains of the seed's domain.
        allowList:
          type: array
          items:
            type: string
          description: Host globs to allow.
        blockList:
          type: array
          items:
            type: string
          description: Host globs to block.
    CrawlerUpdateInput:
      type: object
      description: Partial update of a crawler. Set rag, webhook, or schedule to null to clear them.
      properties:
        name:
          type: string
          minLength: 1
          maxLength: 200
        description:
          type: string
          maxLength: 2000
        status:
          type: string
          enum:
            - active
            - disabled
        seeds:
          type: array
          maxItems: 500
          items:
            type: string
            format: uri
        engine:
          type: string
          enum:
            - axios
            - playwright
            - auto
        maxDepth:
          type: integer
          minimum: 0
          maximum: 3
        maxPages:
          type: integer
          minimum: 0
          maximum: 5000
        autoCrawl:
          type: boolean
        scope:
          $ref: "#/components/schemas/CrawlerScope"
        http:
          $ref: "#/components/schemas/CrawlerHttpOptions"
        downloadableMimes:
          type: array
          items:
            type: string
        markdownOptions:
          $ref: "#/components/schemas/CrawlerMarkdownOptions"
        rag:
          nullable: true
          description: Knowledge Engine binding, or null to clear.
          allOf:
            - $ref: "#/components/schemas/CrawlerRag"
        webhook:
          nullable: true
          description: Webhook receiver, or null to clear.
          allOf:
            - $ref: "#/components/schemas/CrawlerWebhook"
        schedule:
          nullable: true
          description: Schedule, or null to clear.
          allOf:
            - $ref: "#/components/schemas/CrawlerSchedule"
        metadata:
          type: object
          additionalProperties: true
    CrawlerUrlsBody:
      type: object
      description: URL list to add to or remove from a crawler.
      required:
        - urls
      properties:
        urls:
          type: array
          minItems: 1
          maxItems: 500
          items:
            type: string
            format: uri
          description: 1-500 URLs to add or remove.
    CrawlerWebhook:
      type: object
      description: Webhook receiver for crawl lifecycle events.
      required:
        - url
        - events
      properties:
        url:
          type: string
          format: uri
        secret:
          type: string
        events:
          type: array
          minItems: 1
          items:
            type: string
            enum:
              - page
              - completed
              - failed
    EmbedEmbedding:
      type: object
      properties:
        object:
          type: string
          example: embedding
          description: The object type, always `embedding`.
        index:
          type: integer
          description: Index of this embedding in the input list.
        embedding:
          type: array
          description: The embedding vector.
          items:
            type: number
    EmbedEmbeddingRequest:
      type: object
      required:
        - model
        - input
      properties:
        model:
          type: string
          description: Embedding model key configured in the dashboard.
          example: text-embedding-3-small
        input:
          description: Text to embed. A single string or an array of strings for batch embedding.
          oneOf:
            - type: string
            - type: array
              items:
                type: string
        encoding_format:
          type: string
          enum:
            - float
            - base64
          default: float
          description: The format in which the embeddings are returned.
        user:
          type: string
          description: Opaque end-user identifier for abuse monitoring.
        request_id:
          type: string
          description: Optional client-provided correlation identifier echoed back on the response.
    EmbedEmbeddingResponse:
      type: object
      properties:
        object:
          type: string
          example: list
          description: The object type, always `list`.
        data:
          type: array
          description: List of embedding objects, one per input, indexed by position.
          items:
            $ref: "#/components/schemas/EmbedEmbedding"
        model:
          type: string
          description: The embedding model key used.
        usage:
          $ref: "#/components/schemas/EmbedUsage"
        request_id:
          type: string
          description: Correlation identifier for the request.
    EmbedUsage:
      type: object
      properties:
        prompt_tokens:
          type: integer
          description: Number of tokens in the input.
        total_tokens:
          type: integer
          description: Total number of tokens used.
    Error:
      type: object
      properties:
        error:
          description: Error detail — a human-readable string, or an object with a message and type.
          oneOf:
            - type: string
            - type: object
              properties:
                message:
                  type: string
                type:
                  type: string
                code:
                  type: string
                  nullable: true
    EvalItemScore:
      type: object
      description: One scorer's result for a single item.
      properties:
        scorer_type:
          type: string
          description: The scorer that produced this score.
          enum:
            - assertion
            - llm-judge
        score:
          type: number
          description: Score in the range 0-1.
        passed:
          type: boolean
          description: Whether this scorer's threshold was met.
        weight:
          type: number
          description: Weight applied to this scorer.
          nullable: true
        error:
          type: string
          description: Error message if this scorer failed to run.
          nullable: true
    EvalRun:
      type: object
      description: A full evaluation run, including its per-item scores.
      allOf:
        - $ref: "#/components/schemas/EvalRunSummary"
        - type: object
          properties:
            items:
              type: array
              items:
                $ref: "#/components/schemas/EvalRunItem"
    EvalRunAggregate:
      type: object
      description: Aggregate result across all items of a run.
      nullable: true
      properties:
        total:
          type: integer
          description: Total items in the run.
        completed:
          type: integer
          description: Items that produced a result.
        failed:
          type: integer
          description: Items that errored (target/judge failure).
        passed:
          type: integer
          description: Items where every scorer passed.
        pass_rate:
          type: number
          description: passed / total.
        avg_score:
          type: number
          description: Mean per-item score.
        avg_latency_ms:
          type: number
          description: Mean per-item target latency in milliseconds.
    EvalRunItem:
      type: object
      description: The scored result for one dataset item.
      properties:
        item_id:
          type: string
          description: Identifier of the dataset item.
        passed:
          type: boolean
          description: True when every scorer passed.
        score:
          type: number
          description: Weighted mean of the item's scorer scores.
        latency_ms:
          type: number
          description: Target latency for this item in milliseconds.
          nullable: true
        output_text:
          type: string
          description: Text output produced by the target for this item.
          nullable: true
        error:
          type: string
          description: Error recorded for this item, if the target/judge failed.
          nullable: true
        scores:
          type: array
          items:
            $ref: "#/components/schemas/EvalItemScore"
    EvalRunSummary:
      type: object
      description: An evaluation run without its per-item breakdown.
      properties:
        id:
          type: string
          description: Run identifier.
        suite_key:
          type: string
          description: Key of the suite that was run.
        target_key:
          type: string
          description: Key of the target under test.
        dataset_key:
          type: string
          description: Key of the dataset used.
        status:
          type: string
          description: Run lifecycle status.
          enum:
            - pending
            - running
            - completed
            - failed
        aggregate:
          $ref: "#/components/schemas/EvalRunAggregate"
        error:
          type: string
          description: Run-level error message, if the run failed.
          nullable: true
        started_at:
          type: string
          format: date-time
          description: When execution started.
          nullable: true
        finished_at:
          type: string
          format: date-time
          description: When execution finished.
          nullable: true
        created_at:
          type: string
          format: date-time
          description: When the run record was created.
          nullable: true
    EvalScorer:
      type: object
      description: A scorer bound to a suite. `assertion` runs deterministic checks against the item's `expected`; `llm-judge` grades the output against a rubric (0-1).
      properties:
        type:
          type: string
          description: Scorer kind.
          enum:
            - assertion
            - llm-judge
        weight:
          type: number
          description: Relative weight of this scorer in the item's weighted-mean score.
          nullable: true
        rubric:
          type: string
          description: Grading rubric used by the llm-judge scorer.
          nullable: true
        threshold:
          type: number
          description: Minimum score for this scorer to be considered passed.
          nullable: true
    EvalSuite:
      type: object
      description: "An evaluation suite: a target + dataset + scorers configuration."
      properties:
        key:
          type: string
          description: Stable suite key.
        name:
          type: string
          description: Display name.
        description:
          type: string
          description: Optional suite description.
          nullable: true
        target_key:
          type: string
          description: Key of the target (model/agent/external) under test.
        dataset_key:
          type: string
          description: Key of the dataset of test cases.
        judge_model_key:
          type: string
          description: Model used for llm-judge scoring, when a judge scorer is present.
          nullable: true
        scorers:
          type: array
          items:
            $ref: "#/components/schemas/EvalScorer"
        created_at:
          type: string
          format: date-time
          description: When the suite was created.
          nullable: true
    FileBucket:
      type: object
      description: A file storage bucket.
      properties:
        _id:
          type: string
        key:
          type: string
        name:
          type: string
        description:
          type: string
        provider:
          type: string
        status:
          type: string
        metadata:
          type: object
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    FileCreateProviderRequest:
      type: object
      description: Payload to create a file storage provider.
      required:
        - key
        - driver
        - label
        - credentials
      properties:
        key:
          type: string
          description: Unique provider key.
          example: s3-prod
        driver:
          type: string
          description: Driver identifier.
          example: s3
        label:
          type: string
          description: Human-readable label.
          example: Production Storage
        description:
          type: string
        credentials:
          type: object
          description: Driver-specific credentials.
        settings:
          type: object
          description: Driver-specific settings.
        capabilitiesOverride:
          type: array
          description: Optional override of provider capability flags.
          items:
            type: string
        metadata:
          type: object
        status:
          type: string
          enum:
            - active
            - inactive
          default: active
    FileObject:
      type: object
      description: A file object stored in a bucket.
      properties:
        _id:
          type: string
        key:
          type: string
          example: report-pdf
        bucketKey:
          type: string
        fileName:
          type: string
          example: report.pdf
        originalName:
          type: string
          example: report.pdf
        contentType:
          type: string
          example: application/pdf
        size:
          type: integer
          example: 12345
        sizeBytes:
          type: integer
          example: 12345
        metadata:
          type: object
        markdownContent:
          type: string
          nullable: true
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    FileProvider:
      type: object
      description: A configured file storage provider.
      properties:
        _id:
          type: string
        key:
          type: string
          example: s3-prod
        driver:
          type: string
          example: s3
        label:
          type: string
          example: Production Storage
        description:
          type: string
        status:
          type: string
          enum:
            - active
            - inactive
            - error
          example: active
        credentials:
          type: object
          description: Provider-specific credentials (returned redacted/encrypted).
        settings:
          type: object
        metadata:
          type: object
        capabilities:
          type: object
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    FileUploadRequest:
      type: object
      description: Multipart form payload to upload a file.
      required:
        - file
      properties:
        file:
          type: string
          format: binary
          description: The binary file content to upload.
        fileName:
          type: string
          description: Name to store the file under.
          example: report.pdf
        contentType:
          type: string
          description: MIME type of the file.
          example: application/pdf
        convertToMarkdown:
          type: boolean
          default: false
          description: Convert supported documents to Markdown for the Knowledge Engine pipeline.
        keyHint:
          type: string
          description: Optional custom key hint for the stored object.
        metadata:
          type: object
          description: Arbitrary metadata to attach to the file.
    GuardCreateInput:
      type: object
      required:
        - name
        - type
      description: Create a guardrail definition.
      properties:
        name:
          type: string
          description: Guardrail name.
        type:
          type: string
          enum:
            - preset
            - custom
          description: Guardrail type.
        action:
          type: string
          enum:
            - block
            - warn
            - flag
          description: Action on violation. Defaults to `block`.
        customPrompt:
          type: string
          description: LLM rule text. Required for `custom` guardrails.
        description:
          type: string
        enabled:
          type: boolean
          description: Whether the guardrail is active. Defaults to true.
        failMode:
          type: string
          enum:
            - open
            - closed
          description: Behaviour when the check errors.
        modelKey:
          type: string
          description: Model used to evaluate the rule. Required for `custom` guardrails and for LLM-backed policy checks.
        policy:
          type: object
          additionalProperties: true
          description: Preset policy config (moderation, promptShield, wordFilter, etc.).
    GuardEvaluateRequest:
      type: object
      required:
        - guardrail_key
        - text
      properties:
        guardrail_key:
          type: string
          description: Key of the guardrail to evaluate.
          example: pii-checker
        text:
          type: string
          description: Content to evaluate.
          example: My email is john@example.com and my phone is 555-0100
    GuardEvaluateResponse:
      type: object
      properties:
        passed:
          type: boolean
          description: "`true` if no findings triggered, `false` otherwise."
        guardrail_key:
          type: string
          description: Key of the evaluated guardrail.
        guardrail_name:
          type: string
          description: Display name of the guardrail.
        action:
          type: string
          description: Configured action.
          enum:
            - block
            - flag
            - redact
        findings:
          type: array
          description: Array of detected issues.
          items:
            $ref: "#/components/schemas/GuardFinding"
        message:
          type: string
          nullable: true
          description: Optional message for blocked/flagged content; `null` when the content passed.
        disabled:
          type: boolean
          description: Whether the guardrail is disabled (evaluation skipped).
        redacted_text:
          type: string
          nullable: true
          description: Redacted text when the action redacts; `null` otherwise.
    GuardFinding:
      type: object
      description: A single issue detected by the guardrail.
      properties:
        category:
          type: string
          description: Category of the detected issue.
          example: email
        message:
          type: string
          description: Human-readable description of the finding.
          example: Email address detected
        block:
          type: boolean
          description: Whether this finding blocks the content.
    GuardRecord:
      type: object
      additionalProperties: true
      description: A stored guardrail definition.
      properties:
        id:
          type: string
        key:
          type: string
          example: no-pii
        name:
          type: string
        description:
          type: string
        type:
          type: string
          enum:
            - preset
            - custom
        action:
          type: string
          enum:
            - block
            - warn
            - flag
        enabled:
          type: boolean
        failMode:
          type: string
          enum:
            - open
            - closed
        modelKey:
          type: string
        policy:
          type: object
          additionalProperties: true
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    GuardUpdateInput:
      type: object
      description: Partial update of a guardrail definition.
      properties:
        name:
          type: string
        action:
          type: string
          enum:
            - block
            - warn
            - flag
        customPrompt:
          type: string
        description:
          type: string
        enabled:
          type: boolean
        failMode:
          type: string
          enum:
            - open
            - closed
        modelKey:
          type: string
        policy:
          type: object
          additionalProperties: true
    McpAegisInput:
      type: object
      description: Aegis enforcement configuration.
      properties:
        shieldId:
          type: string
          description: Aegis shield id to apply.
        mode:
          type: string
          enum:
            - off
            - monitor
            - enforce
          description: Aegis enforcement mode. Defaults to `off`.
    McpConsoleExecuteRequest:
      type: object
      required:
        - tool
      properties:
        tool:
          type: string
          description: Name of the built-in tool to execute.
        arguments:
          type: object
          additionalProperties: true
          description: "Tool arguments (default: empty object)."
    McpConsoleExecuteResponse:
      type: object
      properties:
        result:
          description: The tool's raw result (any JSON value).
        metadata:
          type: object
          properties:
            tool:
              type: string
              description: Executed tool name.
            server:
              type: string
              description: Server key.
              example: console
            latencyMs:
              type: integer
              description: Execution latency in milliseconds.
    McpConsoleListResponse:
      type: object
      properties:
        server:
          type: object
          description: Built-in console MCP server descriptor.
          properties:
            key:
              type: string
              example: console
            name:
              type: string
              example: cognipeer-console
            version:
              type: string
              example: 1.0.0
            builtin:
              type: boolean
              example: true
        tools:
          type: array
          items:
            $ref: "#/components/schemas/McpToolDescriptor"
    McpCreateInput:
      type: object
      required:
        - name
        - upstreamAuth
      description: Create an MCP server definition. `openApiSpec`/`remoteConfig`/`stdioConfig` are required per the chosen `sourceType`.
      properties:
        name:
          type: string
          description: MCP server name.
          example: Tavily Search
        description:
          type: string
        sourceType:
          type: string
          enum:
            - openapi
            - remote
            - stdio
          description: Where the server's tools come from. Defaults to `openapi`.
        openApiSpec:
          type: string
          description: OpenAPI/Postman spec text. Required when `sourceType` is `openapi`.
        specFormat:
          type: string
          enum:
            - auto
            - openapi
            - postman
          description: Hint for parsing `openApiSpec`.
        upstreamBaseUrl:
          type: string
        upstreamAuth:
          $ref: "#/components/schemas/McpUpstreamAuthInput"
        remoteConfig:
          $ref: "#/components/schemas/McpRemoteConfigInput"
        stdioConfig:
          $ref: "#/components/schemas/McpStdioConfigInput"
        exposure:
          $ref: "#/components/schemas/McpExposureInput"
        aegis:
          $ref: "#/components/schemas/McpAegisInput"
    McpExecuteRequest:
      type: object
      required:
        - tool
      properties:
        tool:
          type: string
          description: Name of the tool to execute.
          example: search
        arguments:
          type: object
          additionalProperties: true
          description: "Tool arguments (default: empty object)."
          example:
            query: latest AI news
        runtime_context:
          type: object
          additionalProperties: true
          nullable: true
          description: Optional caller-supplied runtime context. Header values it carries are forwarded upstream only when allowed by the server's runtime-header policy.
    McpExecuteResponse:
      type: object
      properties:
        result:
          description: The tool's raw result (any JSON value).
        metadata:
          type: object
          properties:
            tool:
              type: string
              description: Executed tool name.
              example: search
            server:
              type: string
              description: MCP server key.
              example: tavily-search
            latencyMs:
              type: integer
              description: Execution latency in milliseconds.
              example: 1523
    McpExposureInput:
      type: object
      description: Exposed access surface for the gateway.
      properties:
        protocols:
          type: array
          items:
            type: string
            enum:
              - streamable-http
              - sse
          description: Enabled transport protocols. Defaults to both.
        accessMode:
          type: string
          enum:
            - token
            - public
          description: How callers authenticate against the exposed endpoint. Defaults to `token`.
    McpHubCatalogEntry:
      type: object
      description: MCP-Registry-style catalog entry for one hub member server (whitelist-serialized — no upstream auth/env/vault material).
      properties:
        name:
          type: string
          description: Server key — the stable identifier used in connection URLs.
        title:
          type: string
        description:
          type: string
        version:
          type: string
        tools:
          type: array
          items:
            type: object
            properties:
              name:
                type: string
              description:
                type: string
              inputSchema:
                type: object
                additionalProperties: true
            required:
              - name
        remotes:
          type: array
          items:
            $ref: "#/components/schemas/McpHubRemoteEndpoint"
        _meta:
          type: object
          additionalProperties: true
      required:
        - name
        - title
        - version
        - tools
        - remotes
    McpHubCatalogMetadata:
      type: object
      properties:
        count:
          type: integer
          description: Number of entries in this page.
        nextCursor:
          type: string
          description: Cursor for the next page (absent on the last page).
      required:
        - count
    McpHubCatalogPage:
      type: object
      description: A page of a hub's server catalog (MCP-Registry envelope).
      properties:
        servers:
          type: array
          items:
            $ref: "#/components/schemas/McpHubCatalogEntry"
        metadata:
          $ref: "#/components/schemas/McpHubCatalogMetadata"
      required:
        - servers
        - metadata
    McpHubDetail:
      type: object
      description: Hub summary plus the first page of its server catalog.
      properties:
        hub:
          $ref: "#/components/schemas/McpHubSummary"
        servers:
          type: array
          items:
            $ref: "#/components/schemas/McpHubCatalogEntry"
        metadata:
          $ref: "#/components/schemas/McpHubCatalogMetadata"
      required:
        - hub
        - servers
        - metadata
    McpHubList:
      type: object
      properties:
        hubs:
          type: array
          items:
            $ref: "#/components/schemas/McpHubSummary"
      required:
        - hubs
    McpHubRemoteEndpoint:
      type: object
      description: A remote transport endpoint for a hub member server.
      properties:
        type:
          type: string
          enum:
            - streamable-http
            - sse
        url:
          type: string
        authentication:
          type: object
          description: "Authentication descriptor. `{ type: 'none' }` or `{ type: 'bearer', description }`."
          properties:
            type:
              type: string
              enum:
                - none
                - bearer
            description:
              type: string
          required:
            - type
      required:
        - type
        - url
        - authentication
    McpHubSummary:
      type: object
      description: Summary of a curated MCP hub (server catalog).
      properties:
        key:
          type: string
        name:
          type: string
        description:
          type: string
        accessMode:
          type: string
          enum:
            - token
            - public
          description: Exposure mode of the hub.
        serverCount:
          type: integer
          description: Number of member servers.
        updatedAt:
          type: string
          format: date-time
      required:
        - key
        - name
        - accessMode
        - serverCount
    McpJsonRpcError:
      type: object
      description: JSON-RPC 2.0 error object.
      properties:
        code:
          type: integer
          description: JSON-RPC error code (e.g. -32700 parse error, -32600 invalid request, -32601 method not found, -32602 invalid params, -32001 server not found, -32002 server disabled, -32003 protocol disabled, -32603 internal error).
        message:
          type: string
          description: Error message.
    McpJsonRpcRequest:
      type: object
      description: JSON-RPC 2.0 request envelope for an MCP method.
      required:
        - jsonrpc
        - method
      properties:
        jsonrpc:
          type: string
          enum:
            - "2.0"
          description: JSON-RPC protocol version.
        id:
          description: Request identifier (string or number); omit or null for notifications.
          example: 1
        method:
          type: string
          description: MCP method to invoke.
          enum:
            - initialize
            - notifications/initialized
            - ping
            - tools/list
            - tools/call
          example: tools/call
        params:
          type: object
          additionalProperties: true
          description: Method parameters. For `tools/call`, `name` is the tool name, `arguments` its arguments, and request-scoped extras may ride in `_meta`.
          example:
            name: search
            arguments:
              query: AI news
    McpJsonRpcResponse:
      type: object
      description: JSON-RPC 2.0 response envelope. Contains either `result` or `error`.
      properties:
        jsonrpc:
          type: string
          enum:
            - "2.0"
          description: JSON-RPC protocol version.
        id:
          description: Identifier echoed from the request (string, number, or null).
          example: 1
        result:
          type: object
          additionalProperties: true
          nullable: true
          description: 'Method result on success. For `tools/call` this is `{ content: [{ type: "text", text }], isError }`.'
        error:
          $ref: "#/components/schemas/McpJsonRpcError"
    McpListToolsResponse:
      type: object
      properties:
        server:
          $ref: "#/components/schemas/McpServer"
        tools:
          type: array
          items:
            $ref: "#/components/schemas/McpToolDescriptor"
    McpRemoteConfigInput:
      type: object
      required:
        - url
      description: "Remote MCP source configuration (for `sourceType: remote`)."
      properties:
        url:
          type: string
          description: Remote MCP server URL.
        transport:
          type: string
          enum:
            - streamable-http
            - sse
          description: Transport. Defaults to `streamable-http`.
    McpServer:
      type: object
      description: Serialized MCP server metadata. Secret upstream credentials are masked.
      additionalProperties: true
      properties:
        id:
          type: string
          description: Server identifier.
        key:
          type: string
          description: MCP server key.
          example: tavily-search
        name:
          type: string
          description: Server name.
          example: Tavily Search
        status:
          type: string
          enum:
            - active
            - disabled
          description: Server status.
        totalRequests:
          type: integer
          description: Total requests served.
          example: 42
        sourceType:
          type: string
          description: Underlying source type of the server (e.g. openapi, remote, stdio).
        exposure:
          type: object
          additionalProperties: true
          description: Enabled access surface for the server.
          properties:
            protocols:
              type: array
              description: Enabled transport protocols.
              items:
                type: string
                enum:
                  - streamable-http
                  - sse
        disabledTools:
          type: array
          description: Names of tools disabled on this server.
          items:
            type: string
        createdAt:
          type: string
          format: date-time
          description: Creation timestamp.
    McpStdioConfigInput:
      type: object
      required:
        - packageName
      description: "Stdio (npx/uvx) MCP source configuration (for `sourceType: stdio`)."
      properties:
        runtime:
          type: string
          enum:
            - npx
            - uvx
          description: Package runner. Defaults to `npx`.
        packageName:
          type: string
          description: Package to run.
        args:
          type: array
          items:
            type: string
          description: Extra CLI arguments.
        env:
          type: object
          additionalProperties:
            type: string
          description: Environment variables passed to the process.
        executionMode:
          type: string
          enum:
            - subprocess
            - sandbox
          description: Execution mode. `sandbox` requires an Enterprise license.
        sandbox:
          type: object
          description: Sandbox settings (only used when `executionMode` is `sandbox`).
          properties:
            templateKey:
              type: string
            resources:
              type: object
              properties:
                cpuCores:
                  type: number
                memoryMb:
                  type: number
    McpToolDescriptor:
      type: object
      description: An MCP tool descriptor (name, description and input schema).
      properties:
        name:
          type: string
          description: Tool name.
          example: search
        description:
          type: string
          nullable: true
          description: Tool description.
        inputSchema:
          type: object
          additionalProperties: true
          description: JSON Schema describing the tool's input arguments.
    McpUpdateInput:
      type: object
      additionalProperties: true
      description: Partial update of an MCP server definition.
      properties:
        name:
          type: string
        description:
          type: string
        status:
          type: string
          enum:
            - active
            - disabled
        openApiSpec:
          type: string
        specFormat:
          type: string
          enum:
            - auto
            - openapi
            - postman
        upstreamBaseUrl:
          type: string
        upstreamAuth:
          $ref: "#/components/schemas/McpUpstreamAuthInput"
        remoteConfig:
          $ref: "#/components/schemas/McpRemoteConfigInput"
        stdioConfig:
          $ref: "#/components/schemas/McpStdioConfigInput"
        exposure:
          $ref: "#/components/schemas/McpExposureInput"
        aegis:
          $ref: "#/components/schemas/McpAegisInput"
        runtimeHeaders:
          type: object
          nullable: true
          description: Runtime header passthrough policy. `null` clears it.
          properties:
            allow:
              type: boolean
            allowedNames:
              type: array
              items:
                type: string
        disabledTools:
          type: array
          items:
            type: string
          description: Names of tools to disable on this server.
    McpUpstreamAuthInput:
      type: object
      required:
        - type
      description: Upstream auth configuration. Secret fields are encrypted at rest and masked in responses.
      properties:
        type:
          type: string
          enum:
            - none
            - token
            - header
            - basic
          description: Upstream auth scheme.
        token:
          type: string
          description: Bearer token (for `token`).
        headerName:
          type: string
          description: Custom header name (for `header`).
        headerValue:
          type: string
          description: Custom header value (for `header`).
        username:
          type: string
          description: Username (for `basic`).
        password:
          type: string
          description: Password (for `basic`).
    MemoryBatchRequest:
      type: object
      required:
        - memories
      properties:
        memories:
          type: array
          description: Memory items to add. Maximum 100 per batch; each item must include content.
          items:
            $ref: "#/components/schemas/MemoryCreateRequest"
          minItems: 1
          maxItems: 100
    MemoryCreateRequest:
      type: object
      required:
        - content
      properties:
        content:
          type: string
          description: Memory content.
        scope:
          type: string
          enum:
            - user
            - agent
            - session
            - global
          description: Memory scope.
        scopeId:
          type: string
          description: Identifier the memory is scoped to.
        tags:
          type: array
          items:
            type: string
          description: Categorization tags.
        importance:
          type: number
          description: Importance weight (0-1).
        source:
          type: string
          description: Origin of the memory.
        metadata:
          type: object
          additionalProperties: true
          description: Custom metadata.
    MemoryItem:
      type: object
      description: A stored memory item.
      properties:
        id:
          type: string
          description: Unique identifier.
        storeKey:
          type: string
          description: Key of the owning store.
        content:
          type: string
          description: Memory content.
        scope:
          type: string
          enum:
            - user
            - agent
            - session
            - global
          description: Memory scope.
        scopeId:
          type: string
          nullable: true
          description: Identifier the memory is scoped to.
        tags:
          type: array
          items:
            type: string
          description: Categorization tags.
        importance:
          type: number
          description: Importance weight (0-1).
        source:
          type: string
          description: Origin of the memory.
        status:
          type: string
          enum:
            - active
            - archived
            - expired
          description: Memory status.
        metadata:
          type: object
          additionalProperties: true
          description: Custom metadata.
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    MemoryMatch:
      type: object
      description: A memory returned by a search or recall operation, including its relevance score.
      properties:
        id:
          type: string
          description: Memory identifier.
        content:
          type: string
          description: Memory content.
        score:
          type: number
          description: Similarity score.
        scope:
          type: string
          enum:
            - user
            - agent
            - session
            - global
          description: Memory scope.
        scopeId:
          type: string
          nullable: true
          description: Identifier the memory is scoped to.
        tags:
          type: array
          items:
            type: string
          description: Categorization tags.
        metadata:
          type: object
          additionalProperties: true
          description: Custom metadata.
        importance:
          type: number
          description: Importance weight (0-1).
    MemoryRecallRequest:
      type: object
      required:
        - query
      properties:
        query:
          type: string
          description: Recall query text.
        topK:
          type: integer
          default: 5
          description: Maximum number of memories to recall.
        scope:
          type: string
          enum:
            - user
            - agent
            - session
            - global
          description: Filter by scope.
        scopeId:
          type: string
          description: Filter by scope id.
        maxTokens:
          type: integer
          default: 2000
          description: Maximum tokens for the assembled context string.
    MemoryRecallResult:
      type: object
      description: Result of a recall-for-chat operation.
      properties:
        context:
          type: string
          description: Formatted context string assembled from the recalled memories.
        memories:
          type: array
          items:
            $ref: "#/components/schemas/MemoryMatch"
        storeKey:
          type: string
          description: Key of the recalled store.
    MemorySearchRequest:
      type: object
      required:
        - query
      properties:
        query:
          type: string
          description: Search query text.
        topK:
          type: integer
          default: 10
          description: Maximum number of results.
        minScore:
          type: number
          description: Minimum similarity score.
        scope:
          type: string
          enum:
            - user
            - agent
            - session
            - global
          description: Filter by scope.
        scopeId:
          type: string
          description: Filter by scope id.
        tags:
          type: array
          items:
            type: string
          description: Filter by tags.
    MemorySearchResult:
      type: object
      description: Result of a semantic search.
      properties:
        memories:
          type: array
          items:
            $ref: "#/components/schemas/MemoryMatch"
        query:
          type: string
          description: The query that was executed.
        storeKey:
          type: string
          description: Key of the searched store.
    MemoryStore:
      type: object
      description: A memory store bound to a vector provider and embedding model.
      properties:
        _id:
          type: string
          description: Unique identifier.
        key:
          type: string
          description: Unique key of the store.
        name:
          type: string
          description: Human-readable name.
        description:
          type: string
          nullable: true
          description: Description.
        vectorProviderKey:
          type: string
          description: Key of the vector database provider.
        embeddingModelKey:
          type: string
          description: Key of the embedding model.
        status:
          type: string
          enum:
            - active
            - inactive
            - error
          description: Store status.
        config:
          type: object
          additionalProperties: true
          description: Store-specific configuration.
        createdBy:
          type: string
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    MemoryStoreCreateRequest:
      type: object
      required:
        - name
        - vectorProviderKey
        - embeddingModelKey
      properties:
        name:
          type: string
          description: Human-readable name.
        vectorProviderKey:
          type: string
          description: Key of the vector database provider.
        embeddingModelKey:
          type: string
          description: Key of the embedding model.
        description:
          type: string
          description: Description.
        config:
          type: object
          additionalProperties: true
          description: Store-specific configuration.
    MemoryStoreUpdateRequest:
      type: object
      description: All fields are optional.
      properties:
        name:
          type: string
          description: Human-readable name.
        description:
          type: string
          description: Description.
        status:
          type: string
          enum:
            - active
            - inactive
            - error
          description: Store status.
        config:
          type: object
          additionalProperties: true
          description: Store-specific configuration.
    MemoryUpdateRequest:
      type: object
      description: Only these fields may be updated; at least one must be supplied.
      properties:
        content:
          type: string
          description: Memory content. Regenerates the embedding when changed.
        metadata:
          type: object
          additionalProperties: true
          description: Custom metadata.
        tags:
          type: array
          items:
            type: string
          description: Categorization tags.
        importance:
          type: number
          description: Importance weight (0-1).
        status:
          type: string
          enum:
            - active
            - archived
            - expired
          description: Memory status.
    ModFinding:
      type: object
      properties:
        type:
          type: string
          enum:
            - pii
            - moderation
            - prompt_shield
            - custom
          description: The finding type.
        category:
          type: string
          description: Category identifier within the finding type.
        severity:
          type: string
          enum:
            - low
            - medium
            - high
          description: Severity of the finding.
        message:
          type: string
          description: Human-readable description of the finding.
        action:
          type: string
          description: Guardrail action applied.
        block:
          type: boolean
          description: Whether the finding blocks the content.
        value:
          type: string
          description: Optional matched value (e.g. the detected PII substring).
    ModModerationRequest:
      type: object
      required:
        - input
      properties:
        input:
          description: Text to classify. A single string, an array of strings, or an array of content-part objects with a `text` field. Image inputs are not supported.
          oneOf:
            - type: string
            - type: array
              items:
                oneOf:
                  - type: string
                  - type: object
                    properties:
                      text:
                        type: string
                        description: The text of this content part.
        model:
          type: string
          description: Guardrail key to evaluate against. When omitted, falls back to the first enabled preset guardrail with the moderation policy active.
          example: default-moderation
    ModModerationResponse:
      type: object
      properties:
        id:
          type: string
          description: Unique identifier for the moderation request.
          example: modr_2f1c8e7a-9b3d-4a21-8c0e-7d5f6a1b2c3d
        model:
          type: string
          description: The resolved guardrail key that was evaluated.
          example: default-moderation
        results:
          type: array
          description: One result per input, indexed by input position.
          items:
            $ref: "#/components/schemas/ModModerationResult"
    ModModerationResult:
      type: object
      properties:
        flagged:
          type: boolean
          description: True when any finding was produced (including PII or prompt-shield findings when those policies are enabled).
        categories:
          type: object
          description: Map of every moderation category to a boolean indicating whether it was triggered.
          additionalProperties:
            type: boolean
        category_scores:
          type: object
          description: Map of every moderation category to a score derived from finding severity (low -> 0.3, medium -> 0.6, high -> 0.9); untriggered categories are 0.
          additionalProperties:
            type: number
        findings:
          type: array
          description: "Console extension: the raw guardrail findings, including PII and prompt-shield findings when those policies are enabled."
          items:
            $ref: "#/components/schemas/ModFinding"
    MonitoringInference:
      type: object
      description: Per-server latest metrics plus an aggregate overview for the tenant's inference fleet.
      properties:
        object:
          type: string
          enum:
            - monitoring.inference
        overview:
          $ref: "#/components/schemas/MonitoringOverview"
        servers:
          type: array
          items:
            $ref: "#/components/schemas/MonitoringServer"
        type_breakdown:
          type: array
          items:
            $ref: "#/components/schemas/MonitoringTypeBreakdown"
    MonitoringMetrics:
      type: object
      description: Latest metrics sample for one inference server.
      properties:
        generation_tokens_throughput:
          type: number
        gpu_cache_usage_percent:
          type: number
        num_requests_running:
          type: number
        num_requests_waiting:
          type: number
        prompt_tokens_throughput:
          type: number
        requests_per_second:
          type: number
        running_models:
          type: array
          items:
            type: string
        time_to_first_token_seconds:
          type: number
        timestamp:
          type: string
          format: date-time
    MonitoringOverview:
      type: object
      description: Aggregate inference-fleet counters.
      properties:
        active_servers:
          type: number
        avg_gpu_cache_usage:
          type: number
          nullable: true
        disabled_servers:
          type: number
        errored_servers:
          type: number
        running_models_count:
          type: number
        total_running_requests:
          type: number
        total_servers:
          type: number
        total_waiting_requests:
          type: number
    MonitoringServer:
      type: object
      description: One inference server with its latest metrics (apiKey stripped).
      properties:
        key:
          type: string
        name:
          type: string
        type:
          type: string
        status:
          type: string
        last_error:
          type: string
          nullable: true
        last_polled_at:
          type: string
          format: date-time
          nullable: true
        latest_metrics:
          nullable: true
          allOf:
            - $ref: "#/components/schemas/MonitoringMetrics"
    MonitoringTypeBreakdown:
      type: object
      description: Count of servers per server type.
      properties:
        count:
          type: number
        type:
          type: string
    OcrAddFilesMultipartRequest:
      type: object
      description: Multipart body for adding files. Attach one or more files under files (or file).
      properties:
        files:
          type: array
          description: One or more files to add.
          items:
            type: string
            format: binary
        file:
          type: array
          description: Alternative field name for one or more files.
          items:
            type: string
            format: binary
        mode:
          type: string
          enum:
            - sync
            - async
          description: Processing mode. sync processes inline (200); async queues (202, default).
    OcrAddFilesRequest:
      type: object
      description: JSON body for adding files. Use items (or documents) array.
      properties:
        mode:
          type: string
          enum:
            - sync
            - async
          description: Processing mode. sync processes inline (200); async queues (202, default).
        items:
          type: array
          items:
            $ref: "#/components/schemas/OcrJobItemInput"
        documents:
          type: array
          description: Alias for items.
          items:
            $ref: "#/components/schemas/OcrJobItemInput"
    OcrCreateJobRequest:
      type: object
      required:
        - ocr_model
        - bucket_key
      properties:
        ocr_model:
          type: string
          description: OCR model key. The alias `model` is also accepted.
        bucket_key:
          type: string
          description: Storage bucket key. The alias `bucketKey` is also accepted.
        name:
          type: string
          description: Display name.
        llm_model:
          type: string
          description: LLM model key used for summary/structured outputs.
        outputs:
          type: array
          description: One or more of full_text, summary, structured. Defaults to ["full_text"].
          items:
            type: string
            enum:
              - full_text
              - summary
              - structured
        summary_prompt:
          type: string
          description: Prompt used when summary output is requested.
        structured_schema:
          type: object
          description: Schema used when structured output is requested.
          additionalProperties: true
        language:
          type: string
          description: Language hint.
        features:
          type: array
          description: OCR features to enable.
          items:
            type: string
        pdf_max_pages:
          type: integer
          description: Cap on PDF pages per file.
        callback_url:
          type: string
          description: Per-file webhook URL.
        callback_secret:
          type: string
          description: Secret used to sign callbacks.
        callback_events:
          type: array
          description: Subset of item.succeeded, item.failed.
          items:
            type: string
            enum:
              - item.succeeded
              - item.failed
        metadata:
          type: object
          description: Arbitrary metadata.
          additionalProperties: true
    OcrDocumentInput:
      type: object
      description: Document supplied by URL or as base64 bytes. Provide either url or data.
      properties:
        url:
          type: string
          description: Document URL.
        data:
          type: string
          description: Base64-encoded document bytes.
        fileName:
          type: string
          description: Original file name (with data).
        contentType:
          type: string
          description: MIME type of the document.
    OcrJob:
      type: object
      description: A persistent OCR job container with processing rules, progress counters, and rolling usage/cost totals.
      properties:
        id:
          type: string
        name:
          type: string
          nullable: true
          description: Display name.
        status:
          type: string
          enum:
            - active
            - paused
            - archived
          description: Job lifecycle status.
        bucket_key:
          type: string
        ocr_model:
          type: string
        llm_model:
          type: string
          nullable: true
          description: LLM model key used for summary/structured outputs.
        outputs:
          type: array
          items:
            type: string
            enum:
              - full_text
              - summary
              - structured
        pdf_max_pages:
          type: integer
          nullable: true
          description: Cap on PDF pages per file.
        callback_url:
          type: string
          nullable: true
          description: Per-file webhook URL.
        items_total:
          type: integer
        items_processed:
          type: integer
        items_failed:
          type: integer
        usage:
          $ref: "#/components/schemas/OcrJobUsage"
        cost_total:
          type: number
        cost_ocr:
          type: number
        cost_llm:
          type: number
        cost_currency:
          type: string
        last_item_at:
          type: string
          format: date-time
          nullable: true
        created_at:
          type: string
          format: date-time
    OcrJobItem:
      type: object
      description: A single file within an OCR job, with its own result, usage, and cost.
      properties:
        id:
          type: string
        index:
          type: integer
        file_name:
          type: string
          nullable: true
        status:
          type: string
          description: Item processing status (e.g. queued, succeeded, failed).
        result:
          type: object
          nullable: true
          description: Extraction output for the file.
          properties:
            fullText:
              type: string
            summary:
              type: string
            structured:
              type: object
              additionalProperties: true
          additionalProperties: true
        usage:
          type: object
          nullable: true
          description: Token usage for the item.
          additionalProperties: true
        cost_total:
          type: number
          nullable: true
        cost_currency:
          type: string
          nullable: true
        callback_status:
          type: string
          nullable: true
          description: Delivery status of the per-file callback.
        error_message:
          type: string
          nullable: true
    OcrJobItemInput:
      type: object
      description: A file to add to a job. Provide a source, or the convenience aliases bucket/document.
      properties:
        fileName:
          type: string
          description: Optional file name.
        source:
          type: object
          description: File source. One of inline, url, or bucket.
          properties:
            kind:
              type: string
              enum:
                - inline
                - url
                - bucket
            data:
              type: string
              description: Base64 bytes (kind=inline).
            url:
              type: string
              description: Document URL (kind=url).
            bucketKey:
              type: string
              description: Bucket key (kind=bucket).
            objectKey:
              type: string
              description: Object key within the bucket (kind=bucket).
            fileName:
              type: string
            contentType:
              type: string
        bucket:
          type: object
          description: Convenience bucket reference in place of source.
          properties:
            bucketKey:
              type: string
            objectKey:
              type: string
        document:
          type: object
          description: Convenience document reference (url or base64 data) in place of source.
          properties:
            url:
              type: string
            data:
              type: string
            fileName:
              type: string
            contentType:
              type: string
    OcrJobUsage:
      type: object
      description: Rolling token/page usage totals for the job.
      properties:
        input_tokens:
          type: integer
        output_tokens:
          type: integer
        total_tokens:
          type: integer
        pages:
          type: integer
        ocr_tokens:
          type: integer
        llm_tokens:
          type: integer
    OcrJobUsageDetail:
      type: object
      description: Aggregate token and cost accounting for a job, including progress counters.
      properties:
        items_total:
          type: integer
        items_processed:
          type: integer
        items_failed:
          type: integer
        input_tokens:
          type: integer
        output_tokens:
          type: integer
        total_tokens:
          type: integer
        pages:
          type: integer
        ocr_tokens:
          type: integer
        llm_tokens:
          type: integer
        cost_total:
          type: number
        cost_ocr:
          type: number
        cost_llm:
          type: number
        cost_currency:
          type: string
    OcrMultipartRequest:
      type: object
      required:
        - model
      description: Multipart OCR request. Supply either file or document_url.
      properties:
        model:
          type: string
          description: OCR model key.
        file:
          type: string
          format: binary
          description: Document file to extract.
        document_url:
          type: string
          description: Document URL to extract.
        pages:
          type: string
          description: Comma-separated page numbers (e.g. "1,2,5"). Only positive page numbers are kept.
        language:
          type: string
          description: Language hint for extraction.
        features:
          type: string
          description: Comma-separated OCR features (text, tables, kv_pairs, layout, reading_order, handwriting); unknown values are ignored.
        prompt:
          type: string
          description: Optional extraction guidance prompt.
    OcrRequest:
      type: object
      required:
        - model
        - document
      properties:
        model:
          type: string
          description: OCR model key.
        document:
          $ref: "#/components/schemas/OcrDocumentInput"
        pages:
          type: array
          description: Pages to process. Only positive page numbers are kept.
          items:
            type: integer
        language:
          type: string
          description: Language hint for extraction.
        features:
          type: array
          description: OCR features to enable; unknown values are ignored.
          items:
            type: string
            enum:
              - text
              - tables
              - kv_pairs
              - layout
              - reading_order
              - handwriting
        prompt:
          type: string
          description: Optional extraction guidance prompt.
    OcrResponse:
      type: object
      description: Provider OCR result with request_id merged in. Exact fields depend on the model and requested features.
      properties:
        text:
          type: string
          description: Extracted full text of the document.
        pages:
          type: array
          description: Per-page extraction detail.
          items:
            type: object
            additionalProperties: true
        request_id:
          type: string
          description: Request correlation ID.
      additionalProperties: true
    OcrUpdateJobRequest:
      type: object
      description: Any subset of these fields may be updated.
      properties:
        name:
          type: string
        status:
          type: string
          enum:
            - active
            - paused
            - archived
        ocr_model:
          type: string
        llm_model:
          type: string
        outputs:
          type: array
          description: Normalized; falls back to ["full_text"].
          items:
            type: string
            enum:
              - full_text
              - summary
              - structured
        summary_prompt:
          type: string
        structured_schema:
          type: object
          additionalProperties: true
        language:
          type: string
        pdf_max_pages:
          type: integer
        callback_url:
          type: string
        callback_secret:
          type: string
        callback_events:
          type: array
          items:
            type: string
            enum:
              - item.succeeded
              - item.failed
    PiiDetokenizeRequest:
      type: object
      required:
        - text
        - vault
      properties:
        text:
          type: string
          description: Text containing tokens (e.g. an LLM response).
          example: Blocked the session for [TC_KIMLIK_1]; flagged the IP [IPADDRESS_1].
        vault:
          allOf:
            - $ref: "#/components/schemas/PiiVault"
          description: The vault returned by a prior `/pii/tokenize` call.
    PiiDetokenizeResponse:
      type: object
      properties:
        output_text:
          type: string
          description: Text with vault tokens replaced by their original values.
    PiiFinding:
      type: object
      description: A single detected PII occurrence.
      properties:
        category:
          type: string
          description: Category of the match.
          example: iban
        value:
          type: string
          description: The matched original value.
        start:
          type: integer
          description: Start character offset of the match.
        end:
          type: integer
          description: End character offset of the match.
        severity:
          type: string
          description: Severity of the finding.
          example: high
        replacement:
          type: string
          description: Replacement text applied for the match (for redact/mask/tokenize actions).
    PiiPolicyCreateInput:
      type: object
      required:
        - name
      description: Create a PII policy definition.
      properties:
        name:
          type: string
          example: Support Intake
        defaultAction:
          type: string
          enum:
            - detect
            - redact
            - mask
            - block
            - tokenize
          description: Default action for matched categories. Defaults to `detect`.
        description:
          type: string
        categories:
          type: object
          additionalProperties:
            type: boolean
          description: Enabled detection categories keyed by category name. Defaults to the built-in category set.
        customPatterns:
          type: array
          items:
            type: object
            additionalProperties: true
          description: Custom regex detectors.
        languages:
          type: array
          items:
            type: string
            enum:
              - global
              - en
              - tr
              - de
              - fr
              - es
              - it
              - pt
              - ar
              - ja
              - zh
          description: Languages to detect. A comma-separated string is also accepted.
        enabled:
          type: boolean
          description: Defaults to true.
        metadata:
          type: object
          additionalProperties: true
    PiiPolicyRecord:
      type: object
      additionalProperties: true
      description: A stored PII policy definition.
      properties:
        id:
          type: string
        key:
          type: string
          example: support-intake
        name:
          type: string
        description:
          type: string
        defaultAction:
          type: string
          enum:
            - detect
            - redact
            - mask
            - block
            - tokenize
        categories:
          type: object
          additionalProperties:
            type: boolean
        customPatterns:
          type: array
          items:
            type: object
            additionalProperties: true
        languages:
          type: array
          items:
            type: string
            enum:
              - global
              - en
              - tr
              - de
              - fr
              - es
              - it
              - pt
              - ar
              - ja
              - zh
        enabled:
          type: boolean
        metadata:
          type: object
          additionalProperties: true
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    PiiPolicyRequest:
      type: object
      description: Shared request body for the policy-based PII endpoints (`detect`, `redact`, `mask`, `tokenize`, `scan`). The `action` field is only read by `/pii/scan` as an override; the named endpoints pin their own action and ignore it.
      required:
        - policy_key
        - text
      properties:
        policy_key:
          type: string
          description: Key of the stored policy to apply (managed in the dashboard under Operate → PII). `policyKey` is also accepted.
          example: support-intake
        text:
          type: string
          description: Text to scan.
          example: Wire to IBAN TR33 0006 1005 1978 6457 8413 26 before Friday
        locale:
          type: string
          description: Locale for finding labels/messages. Defaults to `en`.
          enum:
            - global
            - en
            - tr
            - de
            - fr
            - es
            - it
            - pt
            - ar
            - ja
            - zh
          default: en
        action:
          type: string
          description: "Only for `/pii/scan`: override the policy's default action. Ignored by the named endpoints."
          enum:
            - detect
            - redact
            - mask
            - block
            - tokenize
    PiiPolicyUpdateInput:
      type: object
      description: Partial update of a PII policy definition.
      properties:
        name:
          type: string
        description:
          type: string
        defaultAction:
          type: string
          enum:
            - detect
            - redact
            - mask
            - block
            - tokenize
        categories:
          type: object
          additionalProperties:
            type: boolean
        customPatterns:
          type: array
          items:
            type: object
            additionalProperties: true
        languages:
          type: array
          items:
            type: string
            enum:
              - global
              - en
              - tr
              - de
              - fr
              - es
              - it
              - pt
              - ar
              - ja
              - zh
        enabled:
          type: boolean
        metadata:
          type: object
          additionalProperties: true
    PiiScanResponse:
      type: object
      properties:
        policy_key:
          type: string
          description: Key of the applied policy.
        policy_name:
          type: string
          description: Display name of the applied policy.
        action:
          type: string
          description: The action applied.
          enum:
            - detect
            - redact
            - mask
            - block
            - tokenize
        findings:
          type: array
          description: Detected occurrences.
          items:
            $ref: "#/components/schemas/PiiFinding"
        output_text:
          type: string
          description: The transformed text (equals input for `detect`).
        input_length:
          type: integer
          description: Character length of the input.
        has_blocking:
          type: boolean
          description: Whether any finding is blocking.
        languages:
          type: array
          description: Languages used for the scan (from the policy).
          items:
            type: string
          example:
            - global
            - tr
        vault:
          allOf:
            - $ref: "#/components/schemas/PiiVault"
          description: Only present when the effective action is `tokenize`.
    PiiVault:
      type: object
      description: Token → original-value map returned by tokenize. Keys are tokens like `[EMAIL_1]`.
      additionalProperties:
        $ref: "#/components/schemas/PiiVaultEntry"
    PiiVaultEntry:
      type: object
      description: A vault entry mapping a token to its original value and category.
      properties:
        value:
          type: string
          description: The original PII value.
        category:
          type: string
          description: Category of the original value.
    PromptCompare:
      type: object
      description: Side-by-side comparison of two prompt versions.
      properties:
        fromVersion:
          $ref: "#/components/schemas/PromptVersionSummary"
        toVersion:
          $ref: "#/components/schemas/PromptVersionSummary"
        templateDiff:
          type: array
          description: Line-level diff of the two templates.
          items:
            type: object
            properties:
              type:
                type: string
                enum:
                  - added
                  - removed
                  - unchanged
              line:
                type: string
        metadataDiff:
          type: array
          description: Key-level diff of the two versions' metadata.
          items:
            type: object
            properties:
              key:
                type: string
              fromValue: {}
              toValue: {}
              changed:
                type: boolean
        deploymentHistory:
          type: array
          items:
            $ref: "#/components/schemas/PromptDeploymentEvent"
        comments:
          type: array
          items:
            type: object
            properties:
              id:
                type: string
              promptId:
                type: string
              versionId:
                type: string
              version:
                type: integer
              content:
                type: string
              createdBy:
                type: string
              createdByName:
                type: string
              createdAt:
                type: string
                format: date-time
              updatedAt:
                type: string
                format: date-time
    PromptCreateInput:
      type: object
      required:
        - name
        - template
      description: Create a prompt (creates its first version).
      properties:
        name:
          type: string
          description: Prompt name.
          example: Welcome Message
        template:
          type: string
          description: Mustache template body.
          example: Hello {{name}}!
        description:
          type: string
        key:
          type: string
          description: Desired key. Auto-generated from the name when omitted.
        metadata:
          type: object
          additionalProperties: true
        versionComment:
          type: string
          description: Comment for the initial version. `comment` is also accepted.
    PromptDeploymentEvent:
      type: object
      description: A single deployment history event for a prompt.
      properties:
        id:
          type: string
        environment:
          type: string
          enum:
            - dev
            - staging
            - prod
        action:
          type: string
          enum:
            - promote
            - plan
            - activate
            - rollback
        versionId:
          type: string
        version:
          type: integer
        note:
          type: string
        createdBy:
          type: string
        createdAt:
          type: string
          format: date-time
    PromptDeploymentState:
      type: object
      description: Current deployment state of a prompt in one environment.
      properties:
        environment:
          type: string
          enum:
            - dev
            - staging
            - prod
        versionId:
          type: string
        version:
          type: integer
        rolloutStatus:
          type: string
          enum:
            - planned
            - active
        rolloutStrategy:
          type: string
          enum:
            - manual
        rollbackVersionId:
          type: string
        rollbackVersion:
          type: integer
        note:
          type: string
        updatedBy:
          type: string
        updatedAt:
          type: string
          format: date-time
    PromptDeployments:
      type: object
      description: Current deployment state per environment plus the full deployment history.
      properties:
        deployments:
          type: object
          properties:
            dev:
              $ref: "#/components/schemas/PromptDeploymentState"
            staging:
              $ref: "#/components/schemas/PromptDeploymentState"
            prod:
              $ref: "#/components/schemas/PromptDeploymentState"
        history:
          type: array
          items:
            $ref: "#/components/schemas/PromptDeploymentEvent"
    PromptResolvedVersion:
      type: object
      description: Minimal reference to the prompt version resolved for a request.
      properties:
        id:
          type: string
        version:
          type: integer
          example: 3
        name:
          type: string
          example: v3
        description:
          type: string
        isLatest:
          type: boolean
    PromptSetLatestInput:
      type: object
      required:
        - versionId
      description: Re-point the prompt's `latest` pointer to an existing version.
      properties:
        versionId:
          type: string
          description: Id of an existing version to re-point the latest pointer to.
    PromptUpdateInput:
      type: object
      description: Partial update of a prompt. Template changes implicitly create a new version.
      properties:
        name:
          type: string
        template:
          type: string
          description: New template body. Supplying it creates a new version.
        description:
          type: string
        metadata:
          type: object
          additionalProperties: true
        versionComment:
          type: string
          description: Comment for the new version. `comment` is also accepted.
    PromptVersionSummary:
      type: object
      description: A single entry in a prompt's version history.
      properties:
        id:
          type: string
        version:
          type: integer
          example: 3
        name:
          type: string
          example: v3
        description:
          type: string
        comment:
          type: string
        isLatest:
          type: boolean
        createdBy:
          type: string
        createdAt:
          type: string
          format: date-time
    PromptView:
      type: object
      description: A prompt template with its metadata and deployment state.
      properties:
        id:
          type: string
        tenantId:
          type: string
        projectId:
          type: string
        key:
          type: string
          example: welcome-message
        name:
          type: string
          example: Welcome Message
        description:
          type: string
        template:
          type: string
          example: Hello {{name}}!
        metadata:
          type: object
          additionalProperties: true
        currentVersion:
          type: integer
        createdBy:
          type: string
        updatedBy:
          type: string
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
        deployments:
          type: object
          description: Current deployment state keyed by environment.
          properties:
            dev:
              $ref: "#/components/schemas/PromptDeploymentState"
            staging:
              $ref: "#/components/schemas/PromptDeploymentState"
            prod:
              $ref: "#/components/schemas/PromptDeploymentState"
        deploymentHistory:
          type: array
          items:
            $ref: "#/components/schemas/PromptDeploymentEvent"
    RagChunkConfig:
      type: object
      description: Chunking configuration for a Knowledge Engine module.
      properties:
        strategy:
          type: string
          enum:
            - recursive_character
            - token
        chunkSize:
          type: integer
        chunkOverlap:
          type: integer
        separators:
          type: array
          items:
            type: string
        encoding:
          type: string
    RagCreateInput:
      type: object
      required:
        - name
        - embeddingModelKey
        - vectorProviderKey
        - vectorIndexKey
        - chunkConfig
      description: Create a Knowledge Engine (RAG) module.
      properties:
        name:
          type: string
          example: Support Knowledge Base
        embeddingModelKey:
          type: string
          description: Key of the embedding model.
        vectorProviderKey:
          type: string
          description: Key of the vector store provider.
        vectorIndexKey:
          type: string
          description: Key/name of the vector index.
        chunkConfig:
          $ref: "#/components/schemas/RagChunkConfig"
        description:
          type: string
        key:
          type: string
          description: Desired key. Auto-generated when omitted.
        fileBucketKey:
          type: string
        fileProviderKey:
          type: string
        metadata:
          type: object
          additionalProperties: true
        rerankerKey:
          type: string
          description: Optional reranker to apply to query results.
        rerankerOversample:
          type: integer
          description: Candidate multiplier fetched before reranking.
    RagDocument:
      type: object
      description: A document ingested into a Knowledge Engine module.
      properties:
        _id:
          type: string
        tenantId:
          type: string
        projectId:
          type: string
        ragModuleKey:
          type: string
        fileKey:
          type: string
        fileName:
          type: string
          example: faq.txt
        contentType:
          type: string
          example: text/plain
        size:
          type: integer
        status:
          type: string
          enum:
            - pending
            - processing
            - indexed
            - failed
        chunkCount:
          type: integer
          example: 15
        errorMessage:
          type: string
        lastIndexedAt:
          type: string
          format: date-time
        metadata:
          type: object
          additionalProperties: true
        createdBy:
          type: string
        updatedBy:
          type: string
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    RagModule:
      type: object
      description: A Knowledge Engine (RAG) module.
      properties:
        _id:
          type: string
        tenantId:
          type: string
        projectId:
          type: string
        key:
          type: string
          example: support-kb
        name:
          type: string
          example: Support Knowledge Base
        description:
          type: string
        embeddingModelKey:
          type: string
        vectorProviderKey:
          type: string
        vectorIndexKey:
          type: string
        fileBucketKey:
          type: string
        fileProviderKey:
          type: string
        chunkConfig:
          $ref: "#/components/schemas/RagChunkConfig"
        status:
          type: string
          enum:
            - active
            - disabled
        rerankerKey:
          type: string
        rerankerOversample:
          type: integer
        totalDocuments:
          type: integer
        totalChunks:
          type: integer
        metadata:
          type: object
          additionalProperties: true
        createdBy:
          type: string
        updatedBy:
          type: string
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    RagQueryMatch:
      type: object
      description: A single chunk match returned by a Knowledge Engine query.
      properties:
        id:
          type: string
        score:
          type: number
          example: 0.92
        vectorScore:
          type: number
          description: Pre-rerank vector similarity score. Present only when reranking was applied.
        content:
          type: string
        metadata:
          type: object
          additionalProperties: true
        documentId:
          type: string
        fileName:
          type: string
        chunkIndex:
          type: integer
    RagQueryResult:
      type: object
      description: Result of a Knowledge Engine semantic query.
      properties:
        matches:
          type: array
          items:
            $ref: "#/components/schemas/RagQueryMatch"
        query:
          type: string
        ragModuleKey:
          type: string
        latencyMs:
          type: number
    RagUpdateInput:
      type: object
      additionalProperties: true
      description: Partial update of a RAG module definition.
      properties:
        name:
          type: string
        description:
          type: string
        embeddingModelKey:
          type: string
        vectorProviderKey:
          type: string
        vectorIndexKey:
          type: string
        chunkConfig:
          $ref: "#/components/schemas/RagChunkConfig"
        fileBucketKey:
          type: string
        fileProviderKey:
          type: string
        status:
          type: string
          enum:
            - active
            - disabled
        metadata:
          type: object
          additionalProperties: true
        rerankerKey:
          type: string
        rerankerOversample:
          type: integer
    RealtimeModel:
      type: object
      description: A realtime model preset (snake_case client view) — a named session config bundling a response generator (chat model or agent) with STT, TTS, voice, and turn-detection settings.
      properties:
        id:
          type: string
          nullable: true
          description: Realtime model id.
        object:
          type: string
          enum:
            - realtime.model
        key:
          type: string
          description: Stable identifier clients connect with (`?model=<key>`).
        name:
          type: string
        description:
          type: string
          nullable: true
        status:
          type: string
          enum:
            - active
            - disabled
        chat_model_key:
          type: string
          nullable: true
          description: Chat model responses are generated with (null when an agent is set).
        agent_key:
          type: string
          nullable: true
          description: Agent responses are generated with (takes precedence over the chat model).
        instructions:
          type: string
          nullable: true
        temperature:
          type: number
          nullable: true
        max_output_tokens:
          type: integer
          nullable: true
        stt_model_key:
          type: string
          nullable: true
        input_audio_format:
          type: string
          nullable: true
        tts_model_key:
          type: string
          nullable: true
        voice:
          type: string
          nullable: true
        tts_format:
          type: string
          nullable: true
        turn_silence_ms:
          type: integer
          nullable: true
        turn_silence_threshold:
          type: number
          nullable: true
        greeting:
          type: string
          nullable: true
        tool_status_message:
          type: string
          nullable: true
          description: "Agent presets: filler line announced/spoken while the agent calls tools."
        metadata:
          type: object
          additionalProperties: true
        created_at:
          type: string
          nullable: true
        updated_at:
          type: string
          nullable: true
      required:
        - id
        - object
        - key
        - name
        - status
    RealtimeModelCreateRequest:
      type: object
      description: Create payload for a realtime model preset (snake_case). Provide either `chat_model_key` or `agent_key`.
      properties:
        key:
          type: string
          description: Auto-slugged from `name` when omitted.
        name:
          type: string
        description:
          type: string
        chat_model_key:
          type: string
          description: Chat model responses are generated with. Either this or `agent_key` is required.
        agent_key:
          type: string
          description: Agent responses are generated with (takes precedence over `chat_model_key`).
        instructions:
          type: string
        temperature:
          type: number
        max_output_tokens:
          type: integer
        stt_model_key:
          type: string
          description: STT model key — required for voice input / telephony.
        input_audio_format:
          type: string
        tts_model_key:
          type: string
          description: TTS model key — required for spoken responses / telephony.
        voice:
          type: string
        tts_format:
          type: string
          enum:
            - mp3
            - opus
            - aac
            - flac
            - wav
            - pcm
        turn_silence_ms:
          type: integer
          description: "Telephony turn detection: silence that ends a caller turn (ms)."
        turn_silence_threshold:
          type: number
          description: "Telephony turn detection: RMS silence threshold (0..1)."
        greeting:
          type: string
          description: Spoken when a telephony call connects.
        tool_status_message:
          type: string
          description: "Agent presets: filler line announced/spoken while the agent calls tools."
        metadata:
          type: object
          additionalProperties: true
      required:
        - name
    RealtimeModelList:
      type: object
      properties:
        object:
          type: string
          enum:
            - list
        data:
          type: array
          items:
            $ref: "#/components/schemas/RealtimeModel"
      required:
        - object
        - data
    RealtimeModelUpdateRequest:
      type: object
      description: Partial update for a realtime model preset (snake_case). All fields optional; `key` cannot be changed.
      properties:
        name:
          type: string
        description:
          type: string
        chat_model_key:
          type: string
        agent_key:
          type: string
        instructions:
          type: string
        temperature:
          type: number
        max_output_tokens:
          type: integer
        stt_model_key:
          type: string
        input_audio_format:
          type: string
        tts_model_key:
          type: string
        voice:
          type: string
        tts_format:
          type: string
          enum:
            - mp3
            - opus
            - aac
            - flac
            - wav
            - pcm
        turn_silence_ms:
          type: integer
        turn_silence_threshold:
          type: number
        greeting:
          type: string
        tool_status_message:
          type: string
        metadata:
          type: object
          additionalProperties: true
        status:
          type: string
          enum:
            - active
            - disabled
    RedTeamAggregate:
      type: object
      description: Roll-up of attempt verdicts for a completed run.
      properties:
        total:
          type: integer
          description: Total attempts.
        completed:
          type: integer
          description: Completed attempts.
        failed:
          type: integer
          description: Attempts whose target invocation threw.
        vulnerable:
          type: integer
          description: Vulnerable attempts.
        safe:
          type: integer
          description: Safe attempts.
        needsReview:
          type: integer
          description: Attempts needing review.
        attackSuccessRate:
          type: number
          description: "`vulnerable / completed`."
        resilienceScore:
          type: number
          description: "`1 - attackSuccessRate`."
        bySeverity:
          type: object
          description: Vulnerable count by severity.
          properties:
            low:
              type: integer
            medium:
              type: integer
            high:
              type: integer
            critical:
              type: integer
        byCategory:
          type: object
          description: Attempt breakdown keyed by OWASP-LLM category.
          additionalProperties:
            $ref: "#/components/schemas/RedTeamCategoryBreakdown"
        avgLatencyMs:
          type: number
          description: Average target invocation latency in milliseconds.
    RedTeamCampaign:
      type: object
      description: A named, reusable scan configuration.
      properties:
        key:
          type: string
          description: Campaign identifier; used in the scan path.
        name:
          type: string
          description: Campaign name.
        description:
          type: string
          nullable: true
          description: Campaign description.
        target_kind:
          type: string
          description: What the campaign tests.
          enum:
            - agent
            - model
        agent_key:
          type: string
          nullable: true
          description: Target agent reference (set when `target_kind` is `agent`).
        model_key:
          type: string
          nullable: true
          description: Target model reference (set when `target_kind` is `model`).
        probe_keys:
          type: array
          description: Selected probes. Empty means all built-ins run. `custom:`-prefixed keys reference custom probes.
          items:
            type: string
        judge_model_key:
          type: string
          nullable: true
          description: LLM judge for the campaign (also drives adaptive attacker turns).
        created_at:
          type: string
          description: Campaign creation timestamp.
    RedTeamCampaignsResponse:
      type: object
      properties:
        campaigns:
          type: array
          description: Campaigns configured in the token's project.
          items:
            $ref: "#/components/schemas/RedTeamCampaign"
    RedTeamCategoryBreakdown:
      type: object
      description: Per-OWASP-category attempt breakdown.
      properties:
        total:
          type: integer
          description: Attempts in this category.
        vulnerable:
          type: integer
          description: Vulnerable attempts in this category.
        needsReview:
          type: integer
          description: Attempts needing review in this category.
    RedTeamProbe:
      type: object
      description: "A built-in probe: a generator for one vulnerability class."
      properties:
        key:
          type: string
          description: Probe key.
          example: prompt-injection
        name:
          type: string
          description: Probe display name.
        family:
          type: string
          description: Probe family.
          example: prompt-injection
        category:
          type: string
          description: OWASP-LLM category.
          example: LLM01-prompt-injection
        severity:
          type: string
          description: Probe severity.
          enum:
            - low
            - medium
            - high
            - critical
        description:
          type: string
          description: What the probe attempts.
        custom:
          type: boolean
          description: Always `false` on the client surface (built-in probes only).
    RedTeamProbesResponse:
      type: object
      properties:
        probes:
          type: array
          description: Built-in probe catalog.
          items:
            $ref: "#/components/schemas/RedTeamProbe"
    RedTeamRunAttempt:
      type: object
      description: One probe attempt and its verdict.
      properties:
        probe_key:
          type: string
          description: Probe that generated the attempt.
        attempt_id:
          type: string
          description: Attempt identifier.
        family:
          type: string
          description: Probe family.
        category:
          type: string
          description: OWASP-LLM category.
        severity:
          type: string
          description: Attempt severity.
          enum:
            - low
            - medium
            - high
            - critical
        outcome:
          type: string
          description: Effective verdict — a human review override, if present, wins.
          enum:
            - safe
            - vulnerable
            - needs_review
        machine_outcome:
          type: string
          description: The engine's original verdict before any review.
          enum:
            - safe
            - vulnerable
            - needs_review
        decided_by:
          type: string
          description: Which decision rule fired (audit trail).
        confidence:
          type: number
          description: Verdict confidence in [0, 1].
        reviewed:
          type: boolean
          description: True when a human reviewed this attempt on the dashboard.
        latency_ms:
          type: number
          description: Target invocation latency in milliseconds.
        error:
          type: string
          nullable: true
          description: Set when the target invocation itself threw (counts toward `failed`).
    RedTeamRunDetail:
      description: "Full run view: summary plus progress, error, and per-attempt verdicts."
      allOf:
        - $ref: "#/components/schemas/RedTeamRunSummary"
        - type: object
          properties:
            progress:
              nullable: true
              allOf:
                - $ref: "#/components/schemas/RedTeamRunProgress"
            error:
              type: string
              nullable: true
              description: Fatal run error, if any.
            attempts:
              type: array
              description: Per-attempt verdicts.
              items:
                $ref: "#/components/schemas/RedTeamRunAttempt"
    RedTeamRunProgress:
      type: object
      description: Live progress counters for a run.
      properties:
        total:
          type: integer
          description: Total attempts planned.
        completed:
          type: integer
          description: Completed attempts.
        failed:
          type: integer
          description: Failed attempts.
    RedTeamRunResponse:
      type: object
      properties:
        run:
          $ref: "#/components/schemas/RedTeamRunDetail"
    RedTeamRunSummary:
      type: object
      description: Summary view of a run, without per-attempt detail.
      properties:
        id:
          type: string
          description: Run identifier.
        campaign_key:
          type: string
          description: Campaign the run belongs to.
        target_kind:
          type: string
          description: What was tested.
          enum:
            - agent
            - model
        target_ref:
          type: string
          nullable: true
          description: Target reference (agent or model key).
        status:
          type: string
          description: Run status.
          enum:
            - pending
            - running
            - completed
            - failed
            - cancelled
        aggregate:
          nullable: true
          description: Verdict roll-up; `null` until the run completes.
          allOf:
            - $ref: "#/components/schemas/RedTeamAggregate"
        started_at:
          type: string
          nullable: true
          description: When the run started.
        finished_at:
          type: string
          nullable: true
          description: When the run finished.
        created_at:
          type: string
          description: When the run was created.
    RedTeamRunsResponse:
      type: object
      properties:
        runs:
          type: array
          description: Run summaries, newest first.
          items:
            $ref: "#/components/schemas/RedTeamRunSummary"
    RedTeamScanResponse:
      type: object
      properties:
        run:
          $ref: "#/components/schemas/RedTeamRunSummary"
        status:
          type: string
          description: Enqueue status.
          example: pending
    RerankCreateInput:
      type: object
      required:
        - name
        - strategy
        - config
      description: Create a reranker definition.
      properties:
        name:
          type: string
          example: Support Rerank
        strategy:
          type: string
          enum:
            - dedicated-model
            - llm-judge
            - llm-listwise
            - heuristic
          description: Rerank strategy.
        config:
          type: object
          additionalProperties: true
          description: Strategy-specific configuration (e.g. modelKey).
        key:
          type: string
          description: Desired key. Auto-generated when omitted.
        description:
          type: string
        status:
          type: string
          enum:
            - active
            - disabled
          description: Defaults to `active`.
        metadata:
          type: object
          additionalProperties: true
    RerankDocumentInput:
      description: "A document to rerank: either a plain string or an object with `content`/`text` and optional metadata."
      oneOf:
        - type: string
        - type: object
          properties:
            id:
              type: string
              description: Optional document identifier.
            content:
              type: string
              description: Document content (either `content` or `text` must be present).
            text:
              type: string
              description: Alias for `content`.
            score:
              type: number
              description: Optional prior score.
            metadata:
              type: object
              description: Optional arbitrary metadata.
              additionalProperties: true
    RerankGetResponse:
      type: object
      properties:
        reranker:
          $ref: "#/components/schemas/Reranker"
    RerankListResponse:
      type: object
      properties:
        rerankers:
          type: array
          description: Rerankers visible to the token.
          items:
            $ref: "#/components/schemas/Reranker"
    RerankResult:
      type: object
      description: A single reranked document.
      properties:
        index:
          type: integer
          description: Original index of the document in the request.
        relevance_score:
          type: number
          description: Relevance score assigned by the reranker.
        document:
          type: object
          properties:
            text:
              type: string
              description: The document content.
    RerankRunRequest:
      type: object
      required:
        - query
        - documents
      properties:
        query:
          type: string
          description: Query to rerank documents against.
          example: How do I reset my password?
        documents:
          type: array
          description: Documents to rerank. Accepts strings or objects with `content`/`text`.
          items:
            $ref: "#/components/schemas/RerankDocumentInput"
        top_n:
          type: integer
          description: Maximum number of results to return. `topN` is also accepted.
          example: 5
    RerankRunResponse:
      type: object
      description: Cohere-shaped rerank result.
      properties:
        id:
          type: string
          description: Unique identifier for this rerank call.
          example: rerank-abc123
        results:
          type: array
          description: Reranked documents in descending relevance-score order.
          items:
            $ref: "#/components/schemas/RerankResult"
        meta:
          type: object
          properties:
            api_version:
              type: object
              properties:
                version:
                  type: string
                  example: "1"
            reranker:
              type: string
              description: Key of the reranker used.
            strategy:
              type: string
              description: Strategy of the reranker used.
            model:
              type: string
              description: Underlying model key, when applicable.
            latency_ms:
              type: number
              description: Run latency in milliseconds.
    RerankUpdateInput:
      type: object
      description: Partial update of a reranker definition.
      properties:
        name:
          type: string
        description:
          type: string
        strategy:
          type: string
          enum:
            - dedicated-model
            - llm-judge
            - llm-listwise
            - heuristic
        config:
          type: object
          additionalProperties: true
        status:
          type: string
          enum:
            - active
            - disabled
        metadata:
          type: object
          additionalProperties: true
    Reranker:
      type: object
      description: A configured reranker.
      properties:
        key:
          type: string
          description: Reranker key.
          example: support-rerank
        name:
          type: string
          description: Display name.
        description:
          type: string
          description: Optional description.
        strategy:
          type: string
          description: Rerank strategy.
          enum:
            - dedicated-model
            - llm-judge
            - llm-listwise
            - heuristic
            - fusion
        status:
          type: string
          description: Reranker status.
          enum:
            - active
            - disabled
        totalRuns:
          type: integer
          description: Total number of runs recorded.
        avgLatencyMs:
          type: number
          description: Average run latency in milliseconds.
    SandboxCodeRunRequest:
      type: object
      description: Code snippet to run with the appropriate interpreter.
      properties:
        code:
          type: string
          description: Source code to execute.
        language:
          type: string
          description: Interpreter to use.
          enum:
            - python
            - javascript
            - typescript
            - bash
        cwd:
          type: string
          description: Working directory to run the code in.
        env:
          type: object
          description: Additional environment variables for the run.
          additionalProperties:
            type: string
        timeoutSec:
          type: integer
          description: Maximum run time in seconds before the run is killed.
      required:
        - code
    SandboxCreateRequest:
      type: object
      description: Options for creating a sandbox. All fields are optional.
      properties:
        template:
          type: string
          description: Template id or key to base the sandbox on. Defaults to the first available template (the built-in library is auto-seeded on first use).
        env:
          type: object
          description: Environment variables to inject into the sandbox.
          additionalProperties:
            type: string
        name:
          type: string
          description: Human-readable name. Defaults to a generated `sbx-<timestamp>` name.
        runnerId:
          type: string
          nullable: true
          description: Specific runner to schedule the sandbox on. Defaults to automatic placement.
        volumeId:
          type: string
          nullable: true
          description: Id of a volume to attach to the sandbox.
        persist:
          type: boolean
          description: Keep the sandbox around when stopped so it can be started again.
        blockNetwork:
          type: boolean
          description: Block outbound network access (also disables port preview).
        previewEnabled:
          type: boolean
          description: Whether port preview is enabled for the sandbox.
        previewPublic:
          type: boolean
          description: Whether preview allows session-less public share links.
        resources:
          allOf:
            - $ref: "#/components/schemas/SandboxResources"
          description: Resource allocation/limits for the sandbox.
    SandboxDeleteResult:
      type: object
      properties:
        ok:
          type: boolean
          description: True when the sandbox was deleted.
      required:
        - ok
    SandboxDetail:
      type: object
      description: Full sandbox status returned by get-by-id.
      properties:
        id:
          type: string
          description: Sandbox instance id.
        name:
          type: string
          description: Sandbox name.
        status:
          type: string
          description: Current actual state of the sandbox.
        resources:
          allOf:
            - $ref: "#/components/schemas/SandboxResources"
          nullable: true
          description: Resource allocation/limits, or null if not set.
        preview:
          $ref: "#/components/schemas/SandboxPreviewInfo"
      required:
        - id
        - name
        - status
        - preview
    SandboxExecRequest:
      type: object
      description: Shell command to run inside the sandbox.
      properties:
        command:
          type: string
          description: Command to run in the sandbox shell.
        cwd:
          type: string
          description: Working directory to run the command in.
        env:
          type: object
          description: Additional environment variables for the command.
          additionalProperties:
            type: string
        timeoutSec:
          type: integer
          description: Maximum run time in seconds before the command is killed.
      required:
        - command
    SandboxExecResult:
      type: object
      description: Result of running a command or code snippet.
      properties:
        exitCode:
          type: integer
          description: Process exit code.
        stdout:
          type: string
          description: Captured standard output.
        stderr:
          type: string
          description: Captured standard error.
    SandboxFileListResponse:
      type: object
      properties:
        items:
          type: array
          description: Files in the volume.
          items:
            $ref: "#/components/schemas/SandboxVolumeFile"
        nextCursor:
          type: string
          description: Cursor to fetch the next page, absent when there are no more files.
      required:
        - items
    SandboxFileUploadEntry:
      type: object
      description: A single file to upload to the volume.
      properties:
        path:
          type: string
          description: Volume-relative destination path.
        data:
          type: string
          description: File contents as base64 (a bare base64 string or a data-URL).
        contentType:
          type: string
          description: Optional MIME content type to store with the file.
      required:
        - path
        - data
    SandboxFileUploadRequest:
      type: object
      description: Files to upload. Provide either a `files` array or a single `path`+`data` pair.
      properties:
        files:
          type: array
          description: Batch of files to upload.
          items:
            $ref: "#/components/schemas/SandboxFileUploadEntry"
        path:
          type: string
          description: Volume-relative destination path for a single-file upload.
        data:
          type: string
          description: Base64 (or data-URL) contents for a single-file upload.
        contentType:
          type: string
          description: MIME content type for a single-file upload.
    SandboxFileUploadResponse:
      type: object
      properties:
        uploaded:
          type: array
          description: Files that were successfully uploaded.
          items:
            $ref: "#/components/schemas/SandboxUploadedFile"
      required:
        - uploaded
    SandboxForkRequest:
      type: object
      description: Options for forking a sandbox.
      properties:
        name:
          type: string
          description: Name for the forked sandbox. Defaults to a generated `fork-<timestamp>` name.
        persist:
          type: boolean
          description: Keep the forked sandbox around when stopped.
    SandboxLifecycleResult:
      type: object
      description: Minimal sandbox reference returned by lifecycle operations (create/start/stop/fork/restore).
      properties:
        id:
          type: string
          description: Sandbox instance id.
        status:
          type: string
          description: Current actual state of the sandbox (e.g. creating, running, stopped, failed, deleted).
      required:
        - id
        - status
    SandboxListResponse:
      type: object
      properties:
        sandboxes:
          type: array
          description: Sandboxes visible to the token.
          items:
            $ref: "#/components/schemas/SandboxSummary"
      required:
        - sandboxes
    SandboxListeningPort:
      type: object
      description: A TCP port currently LISTENing inside the sandbox.
      properties:
        port:
          type: integer
          description: Port number listening inside the sandbox.
        loopbackOnly:
          type: boolean
          description: True if the service is bound only to loopback and must be rebound to 0.0.0.0 to be previewable.
        label:
          type: string
          nullable: true
          description: Optional label matched from the sandbox's suggested port list.
        url:
          type: string
          description: Authenticated proxy path for reaching the port.
      required:
        - port
        - url
    SandboxListeningPortsResponse:
      type: object
      properties:
        ports:
          type: array
          description: Ports currently listening inside the sandbox (empty when the sandbox is not running).
          items:
            $ref: "#/components/schemas/SandboxListeningPort"
      required:
        - ports
    SandboxPreviewInfo:
      type: object
      description: Preview configuration for a sandbox.
      properties:
        enabled:
          type: boolean
          description: Whether port preview is enabled.
        public:
          type: boolean
          description: Whether preview allows session-less public share links.
        blocked:
          type: boolean
          description: Whether outbound network (and therefore preview reachability) is blocked.
        allPorts:
          type: boolean
          description: Whether any listening port is previewable (not just the suggested list).
        sharingEnabled:
          type: boolean
          description: Whether the platform is configured to mint session-less share links for this (public) sandbox.
        ports:
          type: array
          description: Suggested/labelled previewable ports and their proxy URLs.
          items:
            $ref: "#/components/schemas/SandboxPreviewPort"
      required:
        - enabled
        - public
        - blocked
        - allPorts
        - sharingEnabled
        - ports
    SandboxPreviewPort:
      type: object
      description: A suggested/labelled previewable port and its authenticated proxy URL.
      properties:
        port:
          type: integer
          description: Port number inside the sandbox.
        label:
          type: string
          nullable: true
          description: Optional human-readable label for the port.
        url:
          type: string
          description: Authenticated proxy path for reaching the port through the console origin.
      required:
        - port
        - url
    SandboxPreviewSettings:
      type: object
      description: Current preview settings after an update.
      properties:
        enabled:
          type: boolean
          description: Whether port preview is enabled.
        public:
          type: boolean
          description: Whether preview allows public share links.
      required:
        - enabled
        - public
    SandboxPreviewSettingsUpdate:
      type: object
      description: Preview settings to update. Omitted fields are left unchanged.
      properties:
        enabled:
          type: boolean
          description: Enable or disable port preview.
        public:
          type: boolean
          description: Allow session-less public share links, or keep preview private/login-only.
    SandboxPreviewShareLink:
      type: object
      description: A signed, session-less preview share link.
      properties:
        token:
          type: string
          description: Signed share token.
        port:
          type: integer
          description: Port the link exposes.
        expiresAt:
          type: string
          description: Expiry of the share link (ISO 8601 timestamp).
        url:
          type: string
          description: Public preview path embedding the token.
      required:
        - token
        - port
        - expiresAt
        - url
    SandboxPreviewTokenRequest:
      type: object
      description: Request for a session-less preview share link.
      properties:
        port:
          type: integer
          description: Port inside the sandbox to expose. Must be a positive integer.
        ttlSeconds:
          type: integer
          description: Lifetime of the share link in seconds. Defaults to a platform-configured value.
      required:
        - port
    SandboxResources:
      type: object
      description: Resource allocation/limits for a sandbox container.
      properties:
        cpuCores:
          type: number
          description: Number of CPU cores.
        memoryMb:
          type: integer
          description: Memory limit in megabytes.
        diskMb:
          type: integer
          description: Disk limit in megabytes.
        pids:
          type: integer
          description: Maximum number of process ids.
      additionalProperties: true
    SandboxRestoreRequest:
      type: object
      description: Options for restoring a sandbox from a snapshot.
      properties:
        name:
          type: string
          description: Name for the restored sandbox. Defaults to a generated `sbx-<timestamp>` name.
        persist:
          type: boolean
          description: Keep the restored sandbox around when stopped.
        blockNetwork:
          type: boolean
          description: Block outbound network access for the restored sandbox.
        resources:
          allOf:
            - $ref: "#/components/schemas/SandboxResources"
          description: Resource allocation/limits for the restored sandbox.
    SandboxSnapshotListResponse:
      type: object
      properties:
        snapshots:
          type: array
          description: Snapshots visible to the token.
          items:
            $ref: "#/components/schemas/SandboxSnapshotSummary"
      required:
        - snapshots
    SandboxSnapshotRequest:
      type: object
      description: Options for capturing a snapshot.
      properties:
        name:
          type: string
          description: Snapshot name. Defaults to a generated `snap-<timestamp>` name.
        export:
          type: boolean
          description: Whether to export the snapshot as a portable artifact.
    SandboxSnapshotResult:
      type: object
      description: Minimal snapshot reference returned when a snapshot is captured.
      properties:
        id:
          type: string
          description: Snapshot id.
        status:
          type: string
          description: Snapshot status.
        kind:
          type: string
          description: Snapshot kind (e.g. internal vs exported).
      required:
        - id
        - status
        - kind
    SandboxSnapshotSummary:
      type: object
      description: Snapshot list item.
      properties:
        id:
          type: string
          description: Snapshot id.
        name:
          type: string
          description: Snapshot name.
        status:
          type: string
          description: Snapshot status.
        kind:
          type: string
          description: Snapshot kind.
      required:
        - id
        - name
        - status
        - kind
    SandboxSummary:
      type: object
      description: Sandbox list item.
      properties:
        id:
          type: string
          description: Sandbox instance id.
        name:
          type: string
          description: Sandbox name.
        status:
          type: string
          description: Current actual state of the sandbox.
      required:
        - id
        - name
        - status
    SandboxToolAegisRejection:
      type: object
      description: Aegis enforcement outcome returned when a toolbox operation is held for approval (202) or blocked (403).
      required:
        - error
      properties:
        error:
          type: string
          description: Enforcement code (e.g. 'approval_required' or 'blocked').
        evaluation:
          type: object
          additionalProperties: true
          description: Aegis policy evaluation detail (matched rules, decision, trace).
    SandboxToolBranchesResult:
      type: object
      required:
        - branches
      properties:
        branches:
          type: array
          description: Local branch names.
          items:
            type: string
    SandboxToolCloneResult:
      type: object
      required:
        - ok
        - path
      properties:
        ok:
          type: boolean
          enum:
            - true
          description: Always true on success.
        path:
          type: string
          description: Directory the repository was cloned into.
    SandboxToolCommitResult:
      type: object
      required:
        - hash
      properties:
        hash:
          type: string
          description: Full SHA of the created commit (HEAD).
    SandboxToolExecResult:
      type: object
      required:
        - commandId
      properties:
        commandId:
          type: string
          description: Id of the launched command, used to fetch its logs.
    SandboxToolFileEntry:
      type: object
      description: A single directory entry.
      required:
        - name
        - isDir
        - size
        - modTime
      properties:
        name:
          type: string
          description: Entry name.
        isDir:
          type: boolean
          description: Whether the entry is a directory.
        size:
          type: integer
          description: Size in bytes.
        modTime:
          type: string
          description: UTC modification time (ISO 8601).
    SandboxToolFileInfo:
      type: object
      description: Metadata for a file or directory.
      required:
        - name
        - path
        - size
        - isDir
        - mode
        - permissions
        - modTime
      properties:
        name:
          type: string
          description: Base name.
        path:
          type: string
          description: Absolute path.
        size:
          type: integer
          description: Size in bytes.
        isDir:
          type: boolean
          description: Whether the path is a directory.
        mode:
          type: string
          description: Octal permission bits (e.g. '644').
        permissions:
          type: string
          description: Symbolic permission string (e.g. '-rw-r--r--').
        modTime:
          type: string
          description: UTC modification time (ISO 8601).
    SandboxToolFindMatch:
      type: object
      required:
        - file
        - line
        - content
      properties:
        file:
          type: string
          description: Path of the matching file.
        line:
          type: integer
          description: 1-based line number of the match.
        content:
          type: string
          description: Text of the matching line.
    SandboxToolFindResult:
      type: object
      required:
        - matches
      properties:
        matches:
          type: array
          description: Matching lines (capped at 1000).
          items:
            $ref: "#/components/schemas/SandboxToolFindMatch"
    SandboxToolGitFileChange:
      type: object
      required:
        - path
        - status
      properties:
        path:
          type: string
          description: Changed file path.
        status:
          type: string
          description: Porcelain status code (e.g. 'M', 'A', '??').
    SandboxToolGitLogEntry:
      type: object
      required:
        - hash
        - author
        - email
        - date
        - message
      properties:
        hash:
          type: string
          description: Full commit SHA.
        author:
          type: string
          description: Author name.
        email:
          type: string
          description: Author email.
        date:
          type: string
          description: Author date (ISO 8601).
        message:
          type: string
          description: Commit subject line.
    SandboxToolGitLogResult:
      type: object
      required:
        - commits
      properties:
        commits:
          type: array
          description: Recent commits, newest first.
          items:
            $ref: "#/components/schemas/SandboxToolGitLogEntry"
    SandboxToolGitStatus:
      type: object
      required:
        - branch
        - ahead
        - behind
        - files
      properties:
        branch:
          type: string
          nullable: true
          description: Current branch name, or null when detached/unknown.
        ahead:
          type: integer
          description: Commits ahead of the upstream.
        behind:
          type: integer
          description: Commits behind the upstream.
        files:
          type: array
          description: Changed files.
          items:
            $ref: "#/components/schemas/SandboxToolGitFileChange"
    SandboxToolListResult:
      type: object
      required:
        - files
      properties:
        files:
          type: array
          description: Directory entries, sorted by name.
          items:
            $ref: "#/components/schemas/SandboxToolFileEntry"
    SandboxToolOk:
      type: object
      description: Minimal success acknowledgement.
      required:
        - ok
      properties:
        ok:
          type: boolean
          enum:
            - true
          description: Always true on success.
    SandboxToolReadResult:
      type: object
      required:
        - content
        - encoding
        - size
      properties:
        content:
          type: string
          description: File content, UTF-8 or base64 per 'encoding'.
        encoding:
          type: string
          enum:
            - utf8
            - base64
          description: Encoding of 'content'. Binary files fall back to base64 even when utf8 was requested.
        size:
          type: integer
          description: File size in bytes.
    SandboxToolReplaceEntry:
      type: object
      required:
        - file
        - success
      properties:
        file:
          type: string
          description: Path of the file processed.
        success:
          type: boolean
          description: Whether the replacement succeeded for this file.
        error:
          type: string
          nullable: true
          description: Error message when the replacement failed for this file.
    SandboxToolReplaceResult:
      type: object
      required:
        - results
      properties:
        results:
          type: array
          description: Per-file replacement results.
          items:
            $ref: "#/components/schemas/SandboxToolReplaceEntry"
    SandboxToolSessionCreateResult:
      type: object
      required:
        - sessionId
      properties:
        sessionId:
          type: string
          description: Id of the created session.
    SandboxToolSessionListResult:
      type: object
      required:
        - sessions
      properties:
        sessions:
          type: array
          description: Active session ids.
          items:
            type: string
    SandboxToolSessionLogs:
      type: object
      description: Snapshot of a session command's captured output and state.
      required:
        - stdout
        - stderr
        - exitCode
        - running
      properties:
        stdout:
          type: string
          description: Captured standard output so far.
        stderr:
          type: string
          description: Captured standard error so far.
        exitCode:
          type: integer
          nullable: true
          description: Process exit code, or null while still running.
        running:
          type: boolean
          description: Whether the command is still running.
    SandboxToolWriteResult:
      type: object
      required:
        - bytesWritten
      properties:
        bytesWritten:
          type: integer
          description: Number of bytes written to the file.
    SandboxUploadedFile:
      type: object
      description: Metadata for a file that was uploaded to the volume.
      properties:
        path:
          type: string
          description: Volume-relative path of the stored file.
        name:
          type: string
          description: File name.
        size:
          type: integer
          description: Stored size in bytes.
      required:
        - path
        - name
        - size
    SandboxVolumeFile:
      type: object
      description: A file stored in the sandbox's attached volume.
      properties:
        path:
          type: string
          description: Volume-relative path.
        name:
          type: string
          description: File name.
        size:
          type: integer
          description: Size in bytes.
        contentType:
          type: string
          description: Stored MIME content type.
      required:
        - path
        - name
        - size
    SpendBreakdown:
      type: object
      description: Per-user / per-API-token spend breakdown from the usage_daily rollup (returned when `group_by_entity` is set).
      properties:
        object:
          type: string
          description: Always `spend.breakdown`.
          example: spend.breakdown
        group_by_entity:
          type: string
          enum:
            - user
            - api_key
        from:
          type: string
          nullable: true
          description: First day covered (rollup day), or null.
        to:
          type: string
          nullable: true
          description: Last day covered (rollup day), or null.
        model:
          type: string
          nullable: true
          description: Model key filter, or null.
        currency:
          type: string
          example: USD
        total_requests:
          type: integer
        total_errors:
          type: integer
        total_input_tokens:
          type: integer
        total_output_tokens:
          type: integer
        total_tokens:
          type: integer
        total_cost:
          type: number
        breakdown:
          type: array
          items:
            $ref: "#/components/schemas/SpendBreakdownEntry"
    SpendBreakdownEntry:
      type: object
      description: Per-entity spend breakdown entry. Carries `user_id` when grouped by user, or `api_token_id` when grouped by api_key.
      properties:
        user_id:
          type: string
          description: Present when `group_by_entity=user`. Empty id groups unattributed traffic.
        api_token_id:
          type: string
          description: Present when `group_by_entity=api_key`. Empty id groups unattributed traffic.
        name:
          type: string
          nullable: true
        label:
          type: string
          nullable: true
        requests:
          type: integer
        errors:
          type: integer
        input_tokens:
          type: integer
        output_tokens:
          type: integer
        total_tokens:
          type: integer
        cost:
          type: number
    SpendBudget:
      type: object
      description: A budget policy (quota policy with `limits.budget` set).
      properties:
        id:
          type: string
          nullable: true
          description: The budget policy id.
        object:
          type: string
          description: Always `budget`.
          example: budget
        label:
          type: string
          nullable: true
        description:
          type: string
          nullable: true
        domain:
          type: string
          enum:
            - global
            - llm
            - embedding
            - vector
            - file
            - tracing
            - stt
            - tts
            - ocr
        scope:
          type: string
          enum:
            - tenant
            - user
            - token
            - resource
            - provider
        scope_id:
          type: string
          nullable: true
        project_id:
          type: string
          nullable: true
        daily_limit_usd:
          type: number
          nullable: true
          description: Daily USD cap. `-1` means unlimited; null when unset.
        monthly_limit_usd:
          type: number
          nullable: true
          description: Monthly USD cap. `-1` means unlimited; null when unset.
        alert_thresholds:
          type: array
          nullable: true
          description: Fractions of the limit at which to alert (e.g. 0.8).
          items:
            type: number
        enabled:
          type: boolean
        priority:
          type: number
        created_at:
          type: string
          format: date-time
          nullable: true
        updated_at:
          type: string
          format: date-time
          nullable: true
    SpendBudgetCreateRequest:
      type: object
      description: Budget creation payload. At least one of `daily_limit_usd` or `monthly_limit_usd` is required.
      properties:
        daily_limit_usd:
          type: number
          description: Daily USD cap. Must be >= 0, or -1 for unlimited. Required if `monthly_limit_usd` is absent.
        monthly_limit_usd:
          type: number
          description: Monthly USD cap. Same rules. Required if `daily_limit_usd` is absent.
        domain:
          type: string
          enum:
            - global
            - llm
            - embedding
            - vector
            - file
            - tracing
            - stt
            - tts
            - ocr
          default: llm
        scope:
          type: string
          enum:
            - tenant
            - user
            - token
            - resource
            - provider
          default: tenant
        scope_id:
          type: string
          description: Identifier the scope binds to (e.g. a token id when `scope=token`).
        alert_thresholds:
          type: array
          description: Fractions of the limit at which to alert. Non-numeric entries are dropped.
          items:
            type: number
        label:
          type: string
          default: Budget
          description: Display name.
        description:
          type: string
        priority:
          type: number
          default: 100
        enabled:
          type: boolean
          default: true
          description: Anything other than false enables it.
    SpendBudgetDeleteResponse:
      type: object
      description: Budget deletion confirmation.
      properties:
        deleted:
          type: boolean
        id:
          type: string
    SpendBudgetList:
      type: object
      description: A list envelope of budget objects.
      properties:
        object:
          type: string
          description: Always `list`.
          example: list
        data:
          type: array
          items:
            $ref: "#/components/schemas/SpendBudget"
    SpendBudgetStatus:
      type: object
      description: Current spend versus configured limits per window.
      properties:
        object:
          type: string
          description: Always `budget.status`.
          example: budget.status
        domain:
          type: string
          enum:
            - global
            - llm
            - embedding
            - vector
            - file
            - tracing
            - stt
            - tts
            - ocr
        configured:
          type: boolean
          description: False when no budget exists for the resolved scope.
        per_day:
          $ref: "#/components/schemas/SpendBudgetStatusWindow"
        per_month:
          $ref: "#/components/schemas/SpendBudgetStatusWindow"
        alert_thresholds:
          type: array
          nullable: true
          items:
            type: number
    SpendBudgetStatusWindow:
      type: object
      description: Usage versus limit for a single window.
      properties:
        limit_usd:
          type: number
          nullable: true
          description: Configured limit, or null when the window has no limit.
        used_usd:
          type: number
          description: Actual spend in the window.
        remaining_usd:
          type: number
          nullable: true
          description: Remaining budget, or null when the window has no limit.
    SpendBudgetUpdateRequest:
      type: object
      description: Budget update payload. Only supplied fields are changed; omitted fields keep their existing value.
      properties:
        daily_limit_usd:
          type: number
          description: Daily USD cap. Must be >= 0, or -1 for unlimited.
        monthly_limit_usd:
          type: number
          description: Monthly USD cap. Must be >= 0, or -1 for unlimited.
        alert_thresholds:
          type: array
          description: Fractions of the limit at which to alert. Non-numeric entries are dropped.
          items:
            type: number
        label:
          type: string
        description:
          type: string
        enabled:
          type: boolean
    SpendByModelEntry:
      type: object
      description: Per-model spend breakdown entry.
      properties:
        model_key:
          type: string
        model_name:
          type: string
          nullable: true
        category:
          type: string
          nullable: true
        provider_key:
          type: string
          nullable: true
        calls:
          type: integer
        input_tokens:
          type: integer
        output_tokens:
          type: integer
        total_tokens:
          type: integer
        cost:
          type: number
        currency:
          type: string
    SpendReport:
      type: object
      description: Spend totals, per-model breakdown, and merged timeseries.
      properties:
        object:
          type: string
          description: Always `spend.report`.
          example: spend.report
        from:
          type: string
          format: date-time
          nullable: true
          description: Window start (ISO), or null.
        to:
          type: string
          format: date-time
          nullable: true
          description: Window end (ISO), or null.
        group_by:
          type: string
          enum:
            - hour
            - day
            - month
          description: Timeseries bucket granularity.
        currency:
          type: string
          description: Currency taken from the highest-cost model entry (falls back to USD).
        total_cost:
          type: number
        total_calls:
          type: integer
        total_input_tokens:
          type: integer
        total_output_tokens:
          type: integer
        total_tokens:
          type: integer
        by_model:
          type: array
          description: Per-model breakdown, sorted by cost descending; zero-call models omitted.
          items:
            $ref: "#/components/schemas/SpendByModelEntry"
        timeseries:
          type: array
          description: Timeseries points, sorted ascending by period.
          items:
            $ref: "#/components/schemas/SpendTimeseriesPoint"
    SpendTimeseriesPoint:
      type: object
      description: A single timeseries bucket, merged across all models for the same period.
      properties:
        period:
          type: string
          description: Bucket label (per `group_by` granularity).
        calls:
          type: integer
        total_tokens:
          type: integer
        cost:
          type: number
    ToolAction:
      type: object
      description: A discrete action exposed by a tool.
      properties:
        key:
          type: string
          description: Action key, unique within the tool.
          example: get-current-weather
        name:
          type: string
          description: Human-readable action name.
          example: Get Current Weather
        description:
          type: string
          nullable: true
          description: Action description.
        inputSchema:
          type: object
          additionalProperties: true
          description: JSON Schema describing the action's input arguments.
    ToolAuthConfigInput:
      type: object
      additionalProperties: true
      description: Upstream auth configuration. Credentials are stored server-side and never returned.
      properties:
        type:
          type: string
          description: Auth scheme (e.g. none, bearer, apiKey, basic).
    ToolCreateInput:
      type: object
      required:
        - name
        - type
      description: Create a tool definition.
      properties:
        name:
          type: string
          description: Tool name.
          example: GitHub API
        type:
          type: string
          enum:
            - openapi
            - mcp
          description: Tool source type.
        description:
          type: string
        openApiSpec:
          type: string
          description: OpenAPI/Swagger/Postman spec text (for `openapi` tools).
        specFormat:
          type: string
          enum:
            - auto
            - openapi
            - postman
          description: Hint for parsing `openApiSpec`. Defaults to `auto`.
        upstreamBaseUrl:
          type: string
          description: Override base URL for upstream calls.
        upstreamAuth:
          $ref: "#/components/schemas/ToolAuthConfigInput"
        mcpEndpoint:
          type: string
          description: MCP server endpoint URL (for `mcp` tools).
        mcpTransport:
          type: string
          enum:
            - sse
            - streamable-http
          description: MCP transport (for `mcp` tools).
    ToolDetailResponse:
      type: object
      properties:
        tool:
          $ref: "#/components/schemas/ToolSummary"
    ToolExecuteRequest:
      type: object
      description: Arguments for the tool action. Supply them under `arguments` or the alias `args`; when both are omitted an empty object is used.
      properties:
        arguments:
          type: object
          additionalProperties: true
          description: Action arguments.
          example:
            location: Istanbul
        args:
          type: object
          additionalProperties: true
          description: Alias for `arguments`.
    ToolExecuteResponse:
      type: object
      properties:
        toolKey:
          type: string
          description: Executed tool key.
          example: weather-api
        actionKey:
          type: string
          description: Executed action key.
          example: get-current-weather
        result:
          description: The action's raw result (any JSON value).
        latencyMs:
          type: integer
          description: Execution latency in milliseconds.
          example: 234
    ToolListResponse:
      type: object
      properties:
        tools:
          type: array
          items:
            $ref: "#/components/schemas/ToolSummary"
    ToolSerialized:
      type: object
      additionalProperties: true
      description: A serialized tool definition. Upstream auth secrets are omitted.
      properties:
        id:
          type: string
        tenantId:
          type: string
        projectId:
          type: string
        key:
          type: string
          example: github-api
        name:
          type: string
        description:
          type: string
        type:
          type: string
          enum:
            - openapi
            - mcp
        status:
          type: string
          enum:
            - active
            - disabled
        actions:
          type: array
          description: Discovered actions.
          items:
            $ref: "#/components/schemas/ToolAction"
        upstreamBaseUrl:
          type: string
        mcpEndpoint:
          type: string
        mcpTransport:
          type: string
          enum:
            - sse
            - streamable-http
        metadata:
          type: object
          additionalProperties: true
        createdBy:
          type: string
        updatedBy:
          type: string
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    ToolSummary:
      type: object
      description: A tool from the unified tool system with its actions.
      properties:
        key:
          type: string
          description: Unique tool key.
          example: weather-api
        name:
          type: string
          description: Human-readable tool name.
          example: Weather API
        description:
          type: string
          nullable: true
          description: Tool description.
        type:
          type: string
          enum:
            - openapi
            - mcp
          description: Tool source type.
        status:
          type: string
          enum:
            - active
            - disabled
          description: Tool lifecycle status.
        actions:
          type: array
          description: Actions exposed by the tool.
          items:
            $ref: "#/components/schemas/ToolAction"
        createdAt:
          type: string
          format: date-time
          description: Creation timestamp.
    ToolUpdateInput:
      type: object
      additionalProperties: true
      description: Partial update of a tool definition.
      properties:
        name:
          type: string
        description:
          type: string
        status:
          type: string
          enum:
            - active
            - disabled
        openApiSpec:
          type: string
        specFormat:
          type: string
          enum:
            - auto
            - openapi
            - postman
        upstreamBaseUrl:
          type: string
        upstreamAuth:
          $ref: "#/components/schemas/ToolAuthConfigInput"
        mcpEndpoint:
          type: string
        mcpTransport:
          type: string
          enum:
            - sse
            - streamable-http
        metadata:
          type: object
          additionalProperties: true
    TraceAgent:
      type: object
      description: Metadata about the agent that produced the session.
      properties:
        name:
          type: string
          description: Agent name.
          nullable: true
        version:
          type: string
          description: Agent version.
          nullable: true
        model:
          type: string
          description: Primary model the agent used.
          nullable: true
      additionalProperties: true
    TraceEvent:
      type: object
      description: "A single tracing event (span) within a session. Common types: llm_call, tool_call, retrieval, custom."
      properties:
        id:
          type: string
          description: Client-assigned event id.
          nullable: true
        type:
          type: string
          description: Event type.
          nullable: true
          example: llm_call
        label:
          type: string
          description: Human-readable label.
          nullable: true
        sequence:
          type: integer
          description: Ordering index within the session.
          nullable: true
        timestamp:
          type: string
          format: date-time
          description: When the event occurred.
          nullable: true
        status:
          type: string
          description: Event status; `error` marks a failure.
          nullable: true
        error:
          type: string
          description: Error message when the event failed.
          nullable: true
        model:
          type: string
          description: Model used by the event.
          nullable: true
        modelName:
          type: string
          description: Alternate model name field.
          nullable: true
        modelNames:
          type: array
          description: All models involved in the event.
          items:
            type: string
        traceId:
          type: string
          description: W3C trace identifier (32 hex chars).
          nullable: true
        spanId:
          type: string
          description: Span identifier for this event.
          nullable: true
        parentSpanId:
          type: string
          description: Parent span identifier (for hierarchy).
          nullable: true
        toolName:
          type: string
          description: Tool/function invoked by the event.
          nullable: true
        toolExecutionId:
          type: string
          description: Identifier of the tool execution.
          nullable: true
        inputTokens:
          type: integer
          nullable: true
        outputTokens:
          type: integer
          nullable: true
        cachedInputTokens:
          type: integer
          nullable: true
        totalTokens:
          type: integer
          nullable: true
        reasoningTokens:
          type: integer
          nullable: true
          description: Reasoning/thinking tokens spent by this event's model call. A subset of outputTokens — never billed, or summed into totalTokens, on top of it.
        finishReason:
          type: string
          nullable: true
          description: "Raw provider finish reason for this event's model call, e.g. stop, length, tool_calls."
        durationMs:
          type: integer
          description: Event duration in milliseconds.
          nullable: true
        bytesIn:
          type: integer
          nullable: true
        bytesOut:
          type: integer
          nullable: true
        requestBytes:
          type: integer
          nullable: true
        responseBytes:
          type: integer
          nullable: true
        actor:
          type: object
          description: Who/what produced the event (name/role/scope).
          properties:
            name:
              type: string
              nullable: true
            role:
              type: string
              nullable: true
            scope:
              type: string
              nullable: true
          additionalProperties: true
        sections:
          type: array
          description: Structured payload sections (e.g. input/output content).
          items:
            type: object
            additionalProperties: true
        toolDetails:
          type: object
          description: Details about the invoked tool.
          additionalProperties: true
        metadata:
          type: object
          description: Free-form metadata; may carry modelName and usage.
          additionalProperties: true
        usage:
          type: object
          description: Token usage; supports camelCase and snake_case token fields.
          additionalProperties: true
      additionalProperties: true
    TraceOtlpRequest:
      type: object
      description: OpenTelemetry OTLP/HTTP JSON ExportTraceServiceRequest.
      required:
        - resourceSpans
      properties:
        resourceSpans:
          type: array
          description: One entry per instrumented resource. Must be a non-empty array containing at least one span.
          items:
            type: object
            properties:
              resource:
                type: object
                properties:
                  attributes:
                    type: array
                    items:
                      type: object
                      properties:
                        key:
                          type: string
                        value:
                          type: object
                          additionalProperties: true
              scopeSpans:
                type: array
                items:
                  type: object
                  properties:
                    scope:
                      type: object
                      properties:
                        name:
                          type: string
                        version:
                          type: string
                    spans:
                      type: array
                      items:
                        type: object
                        required:
                          - traceId
                          - spanId
                        properties:
                          traceId:
                            type: string
                            description: W3C trace identifier.
                          spanId:
                            type: string
                            description: Span identifier.
                          parentSpanId:
                            type: string
                          name:
                            type: string
                          startTimeUnixNano:
                            type: string
                          endTimeUnixNano:
                            type: string
                          attributes:
                            type: array
                            items:
                              type: object
                              additionalProperties: true
    TraceSessionRequest:
      type: object
      description: A complete agent tracing session with its events (custom batch ingestion).
      required:
        - sessionId
      properties:
        sessionId:
          type: string
          description: Unique session identifier (upsert key).
        threadId:
          type: string
          description: Optional thread identifier grouping multiple sessions into one logical workflow.
          nullable: true
        traceId:
          type: string
          description: W3C trace identifier (32 hex chars).
          nullable: true
        rootSpanId:
          type: string
          description: Root span identifier for the session.
          nullable: true
        agent:
          $ref: "#/components/schemas/TraceAgent"
        config:
          type: object
          description: Arbitrary session configuration.
          additionalProperties: true
        status:
          type: string
          description: Session status (e.g. completed).
          nullable: true
        startedAt:
          type: string
          format: date-time
          description: When the session started; defaults to now if omitted.
          nullable: true
        endedAt:
          type: string
          format: date-time
          description: When the session ended.
          nullable: true
        durationMs:
          type: integer
          description: Session duration in milliseconds; derived from startedAt/endedAt if omitted.
          nullable: true
        summary:
          $ref: "#/components/schemas/TraceSummary"
        errors:
          type: array
          description: Session-level errors.
          items:
            type: object
            additionalProperties: true
        events:
          type: array
          description: All events belonging to the session.
          items:
            $ref: "#/components/schemas/TraceEvent"
    TraceStreamEndRequest:
      type: object
      description: Final status and summary supplied when a streaming session is finalized.
      properties:
        status:
          type: string
          description: Final session status; defaults to success when omitted.
          nullable: true
        endedAt:
          type: string
          format: date-time
          description: When the session ended; defaults to now if omitted.
          nullable: true
        durationMs:
          type: integer
          description: Session duration in milliseconds; computed from the session's startedAt if omitted.
          nullable: true
        summary:
          $ref: "#/components/schemas/TraceSummary"
        errors:
          type: array
          description: Additional session-level errors to merge in.
          items:
            type: object
            additionalProperties: true
    TraceStreamStartRequest:
      type: object
      description: Optional session metadata recorded when a streaming session is opened. sessionId is taken from the path, not the body.
      properties:
        threadId:
          type: string
          description: Optional thread identifier grouping multiple sessions.
          nullable: true
        traceId:
          type: string
          description: W3C trace identifier (32 hex chars).
          nullable: true
        rootSpanId:
          type: string
          description: Root span identifier for the session.
          nullable: true
        agent:
          $ref: "#/components/schemas/TraceAgent"
        config:
          type: object
          description: Arbitrary session configuration.
          additionalProperties: true
        startedAt:
          type: string
          format: date-time
          description: When the session started; defaults to now if omitted.
          nullable: true
    TraceSummary:
      type: object
      description: Roll-up totals for a session.
      properties:
        totalInputTokens:
          type: integer
          nullable: true
        totalOutputTokens:
          type: integer
          nullable: true
        totalCachedInputTokens:
          type: integer
          nullable: true
        totalReasoningTokens:
          type: integer
          nullable: true
          description: Sum of reasoningTokens across the session's events. A subset of totalOutputTokens — never billed, or summed into a token total, on top of it.
        truncatedEvents:
          type: integer
          nullable: true
          description: "Count of events whose finishReason indicates a token/length cutoff (e.g. length, max_tokens) rather than a normal stop."
        totalBytesIn:
          type: integer
          nullable: true
        totalBytesOut:
          type: integer
          nullable: true
        totalDurationMs:
          type: integer
          nullable: true
        eventCounts:
          type: object
          description: Per-event-type occurrence counts.
          additionalProperties:
            type: integer
      additionalProperties: true
    TracingThread:
      type: object
      description: "A tracing thread: sessions grouped by threadId, with aggregate counters."
      properties:
        threadId:
          type: string
        sessionsCount:
          type: number
        agents:
          type: array
          items:
            type: string
        statuses:
          type: array
          items:
            type: string
        latestStatus:
          type: string
        startedAt:
          type: string
          format: date-time
          nullable: true
        endedAt:
          type: string
          format: date-time
          nullable: true
        totalEvents:
          type: number
        totalInputTokens:
          type: number
        totalOutputTokens:
          type: number
        totalDurationMs:
          type: number
        modelsUsed:
          type: array
          items:
            type: string
    TracingThreadDetail:
      type: object
      description: A tracing thread with aggregated stats and its constituent sessions.
      properties:
        threadId:
          type: string
        status:
          type: string
        agents:
          type: array
          items:
            type: string
        sessionsCount:
          type: number
        startedAt:
          type: string
          format: date-time
          nullable: true
        endedAt:
          type: string
          format: date-time
          nullable: true
        totalDurationMs:
          type: number
        totalEvents:
          type: number
        totalInputTokens:
          type: number
        totalOutputTokens:
          type: number
        totalCachedInputTokens:
          type: number
        modelsUsed:
          type: array
          items:
            type: string
        toolsUsed:
          type: array
          items:
            type: string
        sessions:
          type: array
          items:
            $ref: "#/components/schemas/TracingThreadSession"
    TracingThreadList:
      type: object
      description: Paginated list of tracing threads.
      properties:
        threads:
          type: array
          items:
            $ref: "#/components/schemas/TracingThread"
        total:
          type: number
    TracingThreadSession:
      type: object
      description: A session belonging to a thread.
      properties:
        sessionId:
          type: string
        agentName:
          type: string
        agentVersion:
          type: string
        status:
          type: string
        startedAt:
          type: string
          format: date-time
          nullable: true
        endedAt:
          type: string
          format: date-time
          nullable: true
        durationMs:
          type: number
        totalEvents:
          type: number
        totalTokens:
          type: number
        totalInputTokens:
          type: number
        totalOutputTokens:
          type: number
        modelsUsed:
          type: array
          items:
            type: string
        toolsUsed:
          type: array
          items:
            type: string
    VectorCreateIndexRequest:
      type: object
      description: Payload to create a vector index.
      required:
        - name
        - dimension
      properties:
        name:
          type: string
          example: Product Embeddings
        dimension:
          type: integer
          minimum: 1
          description: Vector dimensionality (must be a positive number).
          example: 1536
        metric:
          type: string
          enum:
            - cosine
            - euclidean
            - dotproduct
          default: cosine
        metadata:
          type: object
    VectorCreateProviderRequest:
      type: object
      description: Payload to create a vector provider.
      required:
        - key
        - driver
        - label
        - credentials
      properties:
        key:
          type: string
          description: Unique provider key.
          example: pinecone-prod
        driver:
          type: string
          description: Driver identifier.
          example: pinecone
        label:
          type: string
          description: Human-readable label.
          example: Production Vectors
        description:
          type: string
        credentials:
          type: object
          description: Driver-specific credentials.
        settings:
          type: object
          description: Driver-specific settings.
        capabilitiesOverride:
          type: array
          description: Optional override of provider capability flags.
          items:
            type: string
        metadata:
          type: object
        status:
          type: string
          enum:
            - active
            - inactive
          default: active
    VectorDeleteVectorsRequest:
      type: object
      description: Payload to delete vectors by ID.
      required:
        - ids
      properties:
        ids:
          type: array
          description: Vector identifiers to delete.
          minItems: 1
          items:
            type: string
          example:
            - vec-1
            - vec-2
    VectorDriverDescriptor:
      type: object
      description: Descriptor for an available provider driver.
      properties:
        id:
          type: string
          example: pinecone
        version:
          type: string
        domains:
          type: array
          items:
            type: string
        display:
          type: object
          properties:
            label:
              type: string
            description:
              type: string
            icon:
              type: string
        capabilities:
          type: object
    VectorIndex:
      type: object
      description: A vector index within a provider.
      properties:
        _id:
          type: string
        key:
          type: string
          example: products
        indexId:
          type: string
          description: Alias of `key`.
          example: products
        name:
          type: string
          example: Product Embeddings
        dimension:
          type: integer
          example: 1536
        metric:
          type: string
          enum:
            - cosine
            - euclidean
            - dotproduct
          example: cosine
        providerKey:
          type: string
        metadata:
          type: object
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    VectorMatch:
      type: object
      description: A single vector match returned from a query.
      properties:
        id:
          type: string
          example: vec-1
        score:
          type: number
          example: 0.95
        values:
          type: array
          items:
            type: number
        metadata:
          type: object
    VectorProvider:
      type: object
      description: A configured vector database provider.
      properties:
        _id:
          type: string
        key:
          type: string
          example: pinecone-prod
        driver:
          type: string
          example: pinecone
        label:
          type: string
          example: Production Vectors
        description:
          type: string
        status:
          type: string
          enum:
            - active
            - inactive
            - error
          example: active
        credentials:
          type: object
          description: Provider-specific credentials (returned redacted/encrypted).
        settings:
          type: object
        metadata:
          type: object
        capabilities:
          type: object
        createdAt:
          type: string
          format: date-time
        updatedAt:
          type: string
          format: date-time
    VectorProviderFormField:
      type: object
      description: A single form field definition for provider configuration.
      properties:
        name:
          type: string
        label:
          type: string
        type:
          type: string
          enum:
            - text
            - password
            - textarea
            - number
            - select
            - switch
        required:
          type: boolean
        placeholder:
          type: string
        description:
          type: string
        options:
          type: array
          items:
            type: object
            properties:
              label:
                type: string
              value:
                type: string
              description:
                type: string
        defaultValue: {}
        scope:
          type: string
          enum:
            - credentials
            - settings
            - metadata
    VectorProviderFormSchema:
      type: object
      description: Credential/settings form schema for rendering a driver configuration UI.
      properties:
        sections:
          type: array
          items:
            type: object
            properties:
              title:
                type: string
              description:
                type: string
              fields:
                type: array
                items:
                  $ref: "#/components/schemas/VectorProviderFormField"
    VectorQueryRequest:
      type: object
      description: Payload to query similar vectors.
      required:
        - query
      properties:
        query:
          type: object
          required:
            - vector
          properties:
            vector:
              type: array
              description: Query embedding.
              items:
                type: number
            topK:
              type: integer
              minimum: 1
              default: 5
              description: Number of matches to return.
            filter:
              type: object
              description: Provider-specific filter criteria.
    VectorQueryResponse:
      type: object
      description: Result of a vector similarity query.
      properties:
        result:
          type: object
          properties:
            matches:
              type: array
              items:
                $ref: "#/components/schemas/VectorMatch"
    VectorUpdateIndexRequest:
      type: object
      description: Payload to update a vector index. Provide at least one field.
      properties:
        name:
          type: string
        metadata:
          type: object
    VectorUpsertItem:
      type: object
      description: A single vector to insert or update.
      required:
        - id
        - values
      properties:
        id:
          type: string
          example: vec-1
        values:
          type: array
          description: Embedding values.
          items:
            type: number
        metadata:
          type: object
    VectorUpsertRequest:
      type: object
      description: Payload to upsert vectors into an index.
      required:
        - vectors
      properties:
        vectors:
          type: array
          minItems: 1
          items:
            $ref: "#/components/schemas/VectorUpsertItem"
    WebSearchProvider:
      type: object
      description: A web search instance visible to the token.
      properties:
        key:
          type: string
          description: Instance key.
          example: brave-main
        driver:
          type: string
          description: Search engine driver.
          example: brave-search
        label:
          type: string
          description: Human-readable instance label.
          example: Brave Web
        status:
          type: string
          description: Instance status.
          example: active
        aiAnswer:
          type: boolean
          description: Whether AI answers are enabled on the instance.
    WebSearchProvidersResponse:
      type: object
      properties:
        providers:
          type: array
          description: Web search instances visible to the token.
          items:
            $ref: "#/components/schemas/WebSearchProvider"
    WebSearchRequest:
      type: object
      required:
        - query
      properties:
        query:
          type: string
          description: Search query.
          example: fastify v5 changes
        provider:
          type: string
          description: Instance key (generic `/websearch/search` endpoint only). Optional when the project has exactly one active instance; with multiple instances the request must name one. Ignored on the named-instance endpoint.
        count:
          type: number
          description: Maximum number of results. Default 10, max 50.
          example: 5
        offset:
          type: number
          description: Paging hint where the engine supports it.
          example: 0
        language:
          type: string
          description: ISO language override.
          example: en
        country:
          type: string
          description: Country/market override (e.g. `US`, `en-US`).
          example: US
        safe_search:
          type: string
          description: Safe-search override.
          enum:
            - off
            - moderate
            - strict
        include_answer:
          type: boolean
          description: Interpret results with the instance's AI model. Fails when AI answers are disabled on the instance.
    WebSearchResponse:
      type: object
      properties:
        id:
          type: string
          description: Ephemeral search identifier.
          example: websearch-mr87slmv
        provider:
          type: string
          description: Instance key that served the search.
        driver:
          type: string
          description: Search engine driver used.
        query:
          type: string
          description: The query that was run.
        answer:
          type: string
          nullable: true
          description: "Present when the AI interpretation ran (`include_answer: true`) or the engine returned a native answer (Tavily, Serper answer box)."
        answer_model:
          type: string
          nullable: true
          description: Set only for AI-interpreted answers; the model that produced `answer`.
        results:
          type: array
          description: Normalized results.
          items:
            $ref: "#/components/schemas/WebSearchResultItem"
        latency_ms:
          type: number
          description: Search latency in milliseconds.
    WebSearchResultItem:
      type: object
      description: A single normalized search result.
      properties:
        title:
          type: string
          description: Result title.
        url:
          type: string
          description: Result URL.
        snippet:
          type: string
          description: Result snippet.
        position:
          type: integer
          description: 1-based rank of the result.
        published_at:
          type: string
          nullable: true
          description: Publication date when known.
        source:
          type: string
          nullable: true
          description: Origin engine for metasearch instances (e.g. SearxNG).
        score:
          type: number
          nullable: true
          description: Relevance score when provided by the engine.
  responses:
    BadRequest:
      description: Bad request — missing or invalid parameters.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error: model is required
    Unauthorized:
      description: Unauthorized — missing or invalid API token.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error: Invalid API token
    Forbidden:
      description: Forbidden — the feature is not enabled for this token, project, or license tier.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error: This feature is not available in your license
    NotFound:
      description: The requested resource was not found.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error: Not found
    Conflict:
      description: Conflict — the resource already exists or is in a conflicting state.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error: A resource with this key already exists
    TooManyRequests:
      description: Rate limit or quota exceeded.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error: Rate limit exceeded
    InternalError:
      description: Internal server error.
      content:
        application/json:
          schema:
            $ref: "#/components/schemas/Error"
          example:
            error:
              message: Internal server error
              type: server_error
