> ## Documentation Index
> Fetch the complete documentation index at: https://platform.kimi.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Stream Thread events (SSE)

> Opens a live Server-Sent Events stream for one Thread. Only events
produced by that Thread appear here. Use the Thread's `/events` endpoint
for stored history. Frame format, delta delivery, and resume behavior
match the Session event stream.



## OpenAPI

````yaml /hosted-agents/openapi.yaml get /v1/sessions/{id}/threads/{thread_id}/events/stream
openapi: 3.2.0
info:
  title: Kimi Hosted Agents
  version: 2026-09-01-beta
  description: >-
    ## Overview


    Kimi Hosted Agents provides a REST API for configuring Agents, running
    Sessions, and reading their events and Artifacts.


    Base URL: `https://api.moonshot.ai/v1`. Operation paths in this reference
    include `/v1`; use the server URL `https://api.moonshot.ai` when composing
    those paths.


    ### Resource model


    An **Agent** defines how to run: its model, instructions, tools, and other
    configuration. A **Session** binds a frozen Agent version to a conversation
    and its execution history. Session overrides can replace parts of that
    configuration without changing the Agent.


    Each Session has a coordinator **Thread**, which receives user input and can
    delegate work to independently executing child Threads. The Session event
    stream includes child activity; use `session_thread_id` to identify the
    originating Thread.


    Other resources set up execution or store its results:


    - **Environments** provide cloud sandboxes or self-hosted execution.
    Self-hosted workers claim **WorkItems** and execute sandbox tool calls under
    a lease.

    - **Vaults** hold project-scoped credentials. Secret values are write-only.

    - **Skills** supply reusable instructions; **Plugins** bundle Skills and MCP
    servers.

    - **Memory Stores** hold project-scoped files available to Sessions.
    **Dreams** maintain those memories.

    - **Triggers** start or reuse Sessions on a schedule or manually. Each
    execution is recorded as a **TriggerRun**.

    - **Artifacts** are files a Session delivers for download.

    - **Webhooks** send signed HTTPS notifications when project resources
    change.


    On model-provider operations, `provider binding` means the caller's
    configured access to that provider.


    ## Authentication


    Send the credential in the `Authorization` header using the Bearer scheme.
    Choose the credential for the operation you are calling:


    | Credential | Scope |

    | --- | --- |

    | API key (`sk-...`) | Project API access, subject to the caller's
    permissions. |

    | Environment work key | The bound Environment's work queue. |

    | Session work token | Permitted worker operations on the bound Session. |


    Worker credentials are not interchangeable with API keys or with each other.


    For example, list Agents with an API key:


    ```sh

    curl https://api.moonshot.ai/v1/agents \
      -H "Authorization: Bearer $KIMI_API_KEY" \
      -H "kimi-api-version: 2026-09-01-beta"
    ```


    ## API versioning


    ### Selecting a version


    Send `kimi-api-version: 2026-09-01-beta` to use this contract. Outside
    `/v1/files*`, a missing version header returns 400 `invalid_request_error`;
    an unknown version is rejected on every endpoint.


    File endpoints also accept requests without the version header for
    compatibility. In that mode, upload and delete return 200 instead of
    201/204, file records use `status` and `status_details` instead of
    `extract_status`, and uploads cannot be attached to Sessions. Omitting the
    header does not select the latest version.


    ### Compatibility


    Stable versions remain backward compatible. Breaking changes ship under a
    new dated version. They include removing or renaming endpoints, fields, or
    enum values; changing types, meanings, or defaults; requiring new request
    fields; narrowing accepted input; and removing or redefining error types.

    Clients must tolerate new endpoints, optional request fields, response
    fields and headers, and response enum values, including error types. Message
    wording is not a stable interface.


    ### Beta and retirement policy


    The current version is a beta, so behavior may change without a new version.
    Caller-visible changes appear in the ChangeLog and release notes. Stable
    versions remain available after a successor ships. We announce retirements
    in advance, but there is no fixed notice period. The retirement policy uses
    `Deprecation` and `Sunset` response headers and rejects the version after
    its sunset date. No version is currently being retired.


    ## Request conventions


    ### Resource identifiers


    Resource IDs are opaque strings: store and pass the whole value. Do not
    validate a prefix, parse the structure, or infer resource properties from an
    ID.


    ### Request bodies and updates


    Use `application/json` for JSON request bodies and `multipart/form-data` for
    bundle and file uploads. An undeclared content type returns 400
    `invalid_request_error`.


    Send only fields declared by the operation; unknown JSON fields return 400
    `invalid_parameter_error`. In a `PATCH`, omitted fields remain unchanged.
    Explicit `null` is rejected for non-nullable fields. Use the empty value
    documented for a field to clear it.


    ### Pagination


    List operations accept `page_size` (1–1000, default 50) and `page_token`,
    and return `{items, next_page_token}`. Pass the returned token unchanged to
    read the next page; an absent `next_page_token` marks the end.


    ### Localization


    Send the optional `X-Language` header (BCP 47, such as `en-US` or `zh-CN`)
    to select localized display names and descriptions on Plugin and Skill
    responses. When the header is omitted or unsupported, the API defaults to
    `zh-CN` and falls back to the base text when that locale has no override.
    Runtime behavior and model-facing definitions do not vary by request
    language.


    ## Idempotency


    Operations that declare `Idempotency-Key` accept a key of up to 255 bytes.
    Use a new key for each independent write intent, including each target
    resource. Do not reuse keys across operations or resources in the same
    project.


    A stored response is replayed with its original status and body for 24
    hours. Keep the key, request target, API version, and request body bytes
    unchanged when retrying: JSON whitespace or a new multipart boundary can
    cause a conflict. Reusing the key with a different request target, API
    version, or body, or while the original request is still in progress,
    returns 409 `conflict_error`.


    Validation, authentication, and permission failures and 5xx responses are
    not stored; business rejections can be stored. A missing replay record does
    not prove that a write never happened. After a timeout, a 500 response, or
    key expiry, query the affected resource or Session state to establish the
    outcome before retrying the write. Idempotency reduces duplicate execution
    but does not guarantee exactly-once writes under every failure.


    ## Rate limits and size limits


    Temporary rate limits return 429 `rate_limit_reached_error` with
    `Retry-After` in seconds. Quota or budget exhaustion uses
    `exceeded_current_quota_error` without that header.

    Oversized requests return 400 `invalid_request_error`, rather than 413.
    Uploads also have file and bundle limits; each operation documents
    additional constraints.


    | Request or upload | Limit |

    | --- | --- |

    | JSON request body, except memory writes | 4 MiB |

    | Memory write request body | 28 MiB |

    | `POST /v1/files` | 100 MiB per file |

    | `POST /v1/skills` | 64 MiB per bundle |

    | Plugin bundle uploads | 64 MiB per bundle |


    ## Errors


    ### HTTP errors


    API errors use `{"error": {type, message, request_id, param?}}`. Check both
    the HTTP status and `error.type` when handling an error. Show `message` to
    explain the failure, but do not parse it.


    | Error type | Status | Recovery |

    | --- | --- | --- |

    | `invalid_parameter_error` | 400 | Correct the field identified by `param`.
    |

    | `invalid_request_error` | 400 | Correct the request format, method,
    version, or size. |

    | `failed_precondition_error` | 400, 409, 412 | Check the operation's state
    requirements. A 409 while completing WorkItem stop means keep serving the
    lease; a 412 from a lease operation means abandon the expired lease and poll
    again. |

    | `authentication_error` | 401 | Renew or replace the credential. |

    | `permission_denied_error` | 403 | Check permissions and credential scope.
    |

    | `resource_not_found_error` | 404 | Check the ID and visibility. |

    | `conflict_error` | 409 | Resolve the name, version, or idempotency
    conflict before retrying. |

    | `rate_limit_reached_error` | 429 | Wait for the seconds specified by
    `Retry-After`. |

    | `exceeded_current_quota_error` | 429 | Resolve quota or budget exhaustion
    before retrying. |

    | `server_error` | 500 | Record the request IDs; check a write's outcome
    before retrying. Back off when retrying reads. |


    These are the currently declared types. Handle unknown types and responses
    outside this envelope, including infrastructure failures.

    Field validation errors carry `param`. Paths can include location prefixes
    and array indices, such as `body.mcp_servers[2].name`, or use a bare field
    name. Do not depend on one path shape.

    Errors stored in resources, such as `TriggerRun.error`, use their own domain
    schemas and display-only types; they are not HTTP error responses.


    ### Request IDs


    Responses carry `Msh-Request-Id`. It normally matches the error body's
    `request_id`; a replay can retain the original body ID while the header
    identifies the retry. Include both IDs when reporting a retry problem.


    ### Session execution errors


    A `session.error` event describes an execution problem after Session
    creation. Its `error_type` is separate from HTTP `error.type`; reconnecting
    the event stream does not retry execution.


    | `error_type` | Recovery |

    | --- | --- |

    | `internal_error` | Report the failure with available request IDs. |

    | `model_error` | Follow the message or retry execution later. |

    | `model_unavailable` | Select an available model or create a new Session. |

    | `rate_limited` | Wait before retrying execution. |

    | `engine_overloaded` | Retry execution later. |

    | `quota_exceeded` | Restore model quota or account balance before
    continuing. |

    | `context_length_exceeded` | Reduce input or start a new Session. |

    | `invalid_request` | Correct the model request as described in the message.
    |

    | `timeout` | Check Session state before retrying execution. |

    | `max_steps` | Send new input to continue with another turn. |

    | `mcp_connection_failed` | Check the affected MCP server's connectivity. |

    | `mcp_authentication_failed` | Renew or reconnect the affected MCP
    credential. |


    Handle future values and check Session state before taking a recovery
    action. An MCP failure can leave only that server's tools unavailable while
    the rest of execution continues. When present, `mcp_server_name` identifies
    the affected server.


    ## Streaming (SSE)


    ### Event format


    Session and Thread streams (`GET .../events/stream`) use `event:` for the
    event type, `id:` for the resume cursor, and `data:` for the complete event
    JSON. A `: hb` heartbeat is sent every 30 seconds.

    Streams deliver complete events in order; `agent.delta` incremental previews
    are sent only when `include_deltas=true`.

    Failures before the stream opens return the HTTP error envelope. After
    opening, a reported stream failure uses `event: error` with that envelope
    and closes the stream. Also handle disconnections without an error frame.


    ### Reconnecting


    Reconnect using the last frame's `id` as `cursor` or `Last-Event-ID`. A
    resource event ID is not a resume cursor. An unusable cursor returns
    `invalid_parameter_error` with `param=cursor`.


    ### Recovering an expired cursor


    If the cursor's position has expired, discard partial previews and recover
    in this order:


    1. Open a `cursor=now` stream, wait for its control frame, and buffer
    incoming live events.

    2. Backfill persisted events through `GET .../events`.

    3. Merge the backfill with buffered events, remove overlaps, and continue
    consuming the open stream.


    Opening the stream before backfilling avoids a gap between history and live
    events. Previews absent from persisted history cannot be reconstructed.


    ### Tool results


    `agent.tool_result` carries `data.tool_result` with two required arrays
    (`structured_content` and `content`) and `is_error`:


    - **Client rendering rule:** Render `structured_content` when it is
    non-empty. When `structured_content` is `[]`, fall back to rendering
    `content` (including raw error text when `is_error` is `true`). Events
    stored before `2026-11-29` retain their previously persisted
    `structured_content`.

    - **Content vocabularies:** `artifact` and `file` cards appear only in
    `structured_content`; `video` parts appear only in `content`. On successful
    calls, any agent-configured `result_hint` is appended as a trailing `text`
    block in `content` (leaving tool-provided `structured_content` unchanged,
    and visible when clients fall back to `content`).

    - **When `structured_content` is populated:** Only when a tool supplies a
    separate user-facing display view — `save_artifact` (`artifact` cards);
    `read` and `read_file` on image, video, or converted PDF/Office files
    (`file` references or formatted conversion views); `web_search` with
    results; `web_fetch` and `web_open_url`; and in `agent_toolset_20260901`,
    `edit_file` on success, `ipython` when images are generated,
    `search_image_by_text` and `search_image_by_image` with results, and
    `todo_read` and `todo_write` on success.

    - **When `structured_content` is `[]`:** Plain-text built-in tools (`read`
    and `read_file` on text or empty files, `write` and `write_file`, `edit`,
    `bash` and `shell`, `glob`, `grep`), text-only `ipython`, empty search
    results, self-hosted worker tool calls, MCP tools, and failed calls without
    display blocks.


    Plain-text or failed tool call (`structured_content` is `[]`, render
    `content`):


    ```json

    {
      "id": "sevt_01h455vb4pex5vsknk084sn02r",
      "processed_at": "2026-11-29T00:00:00Z",
      "type": "agent.tool_result",
      "data": {
        "tool_result": {
          "tool_use_id": "call_01",
          "structured_content": [],
          "content": [
            {"type": "text", "text": "1\thello world\n"}
          ],
          "is_error": false
        }
      }
    }

    ```


    Tool with a dedicated display view (`save_artifact`, render
    `structured_content`):


    ```json

    {
      "id": "sevt_01h455vb4pex5vsknk084sn02s",
      "processed_at": "2026-11-29T00:00:01Z",
      "type": "agent.tool_result",
      "data": {
        "tool_result": {
          "tool_use_id": "call_02",
          "structured_content": [
            {
              "type": "artifact",
              "id": "arti_01h455vb4pex5vsknk084sn02q",
              "version": "1",
              "name": "report.md",
              "path": "/mnt/agents/report.md",
              "mime_type": "text/markdown",
              "size_bytes": 1024
            }
          ],
          "content": [
            {"type": "text", "text": "Saved 1 file(s) as artifacts..."}
          ],
          "is_error": false
        }
      }
    }

    ```


    ## ChangeLog


    The ChangeLog groups caller-visible changes by date. Changes affecting
    existing integrations come first, followed by additions and contract-only
    updates. Each entry describes the impact and any action clients need to
    take. See the operation definitions for complete inputs and outputs.


    ### 2026-12-01


    - **Worker protocol version:** Self-hosted work polling accepts the optional
    `worker_version` query parameter. Omission selects version 0. Poll claims
    the oldest compatible pending item and returns 204 when no compatible work
    is available. Incompatible items remain queued.


    ### 2026-11-29


    - **`agent.tool_result` `structured_content` fallback removed (breaking
    change):** `structured_content` now carries only tool-provided user-facing
    rendering parts (such as file or artifact cards, or formatted views) and is
    `[]` when a tool has no separate display view (including plain-text tools
    such as `read`, `read_file`, `write`, `write_file`, `edit`, `bash`, `shell`,
    `glob`, `grep`, MCP tools, and failed calls without display blocks). Clients
    that previously read only `structured_content` must fall back to `content`
    when `structured_content` is empty; previously stored events keep their
    existing `structured_content`. Agent-configured `result_hint` instructions
    continue to be appended as a `text` block to `agent.tool_result` `content`
    on successful calls (without modifying tool-provided `structured_content`).


    ### 2026-11-26


    - **Built-in toolset names:** Built-in sandbox toolsets are renamed from
    `default_toolset_<date>` to `agent_toolset_<date>`: `agent_toolset_20260901`
    and `agent_toolset_20261101`. New Agents created without an `agent_toolset`
    use `agent_toolset_20261101` by default. Requests and existing
    configurations using `default_toolset_20260901` remain supported as a
    deprecated alias of `agent_toolset_20260901`.

    - **Self-hosted `agent_toolset_20261101` support:** Self-hosted Environments
    now support `agent_toolset_20261101` alongside `agent_toolset_20260901` (and
    its deprecated alias `default_toolset_20260901`). Workers execute `read`,
    `write`, `edit`, `bash`, `glob`, and `grep` locally while `web_search` and
    `web_fetch` run on the platform; `save_artifact` remains disabled in
    self-hosted Environments. Upgrade self-hosted workers before selecting
    `agent_toolset_20261101` on self-hosted Sessions.


    ### 2026-11-25


    - **Tool error details in `structured_content`:** When a failed
    `agent.tool_result` has no tool-provided display blocks,
    `structured_content` now carries the tool's original error text from
    `content` instead of the generic `"The tool call failed."` message. Results
    that include display blocks are unchanged, and `is_error` still indicates
    failure. Clients that previously read `content` to show error details can
    render `structured_content` directly.


    ### 2026-11-24


    - **Default toolset and version pinning:** `POST /v1/agents` now prepends
    `agent_toolset_20261101` to `tools` whenever no `agent_toolset` is declared
    (including omitted, empty, or custom/MCP-only `tools`), counting toward the
    128-item limit. Replacing Agent `tools` or setting Session
    `agent_overrides.tools` without an `agent_toolset` keeps the current (or
    bound Agent's) `agent_toolset`, or prepends `agent_toolset_20261101` if none
    exists; on Session update, `tools: []` still clears the override. Each
    `tools` list allows at most one sandbox toolset; mixing
    `agent_toolset_20260901` and `agent_toolset_20261101` returns 400
    `invalid_parameter_error`. Updating an older Agent version that lacks an
    `agent_toolset` without `tools` returns 400 `failed_precondition_error`;
    include `tools` to pin a toolset. Existing Agent versions keep their saved
    toolset. To disable all built-in tools, declare an `agent_toolset` with
    `default_config: {enabled: false}`. Self-hosted Environments still require
    `agent_toolset_20260901` for enabled sandbox tools (fully disabled sandbox
    toolsets are skipped); on Session update, an incompatible roster child
    returns 400 `failed_precondition_error`.

    - **Localized Plugin and Skill text:** Public REST endpoints now honor the
    optional `X-Language` request header (BCP 47, such as `en-US` or `zh-CN`)
    when rendering Plugin and Skill display names and descriptions. Omitting the
    header or sending an unsupported locale continues to default to `zh-CN` and
    falls back to the base text when no override exists; existing callers need
    no changes.


    ### 2026-11-18


    - **Session resolved Skills:** The Get Session contract adds the detail-only
    `include=resolved_skills` option and optional top-level `resolved_skills`.
    Entries use the existing `SkillVersion` model, including its exact numeric
    `version`, canonical `name`, `description`, and `created_at`, sorted by
    `name`. An explicitly requested empty set is `[]`; without the option, the
    field is omitted. Unknown `include` values return 400
    `invalid_parameter_error`.

    - **Skill archives:** The Skill version content contract adds
    `format=markdown|archive`. Omitting `format` or using `markdown` returns raw
    `SKILL.md` as `text/markdown`; `archive` returns the complete package as
    `application/zip`. Unknown `format` values return 400
    `invalid_parameter_error`.


    ### 2026-11-13


    - **Self-hosted toolset compatibility:** Session creation rejects effective
    coordinator or child sandbox toolsets other than `agent_toolset_20260901`
    for self-hosted environments with 400 `invalid_parameter_error` and
    `param=environment_id`. Session override updates reject incompatible
    effective toolsets, including inherited values restored by clearing an
    override, before any write with `param=agent_overrides.tools`. Select a
    supported toolset or a compatible managed Environment before retrying.
    Agents themselves do not bind an Environment.


    ### 2026-11-11


    - **Error response schema:** All error response definitions now reference
    the shared `APIError` schema (`#/components/schemas/APIError`) instead of
    duplicating per-status wrapper schemas. Wire payloads, status codes,
    headers, and request handling are unchanged.


    ### 2026-11-10


    - **New built-in toolset:** Agent tools and Session agent overrides now
    accept `agent_toolset_20261101`, with `read`, `write`, `edit`, `bash`,
    `glob`, `grep`, `web_search`, `web_fetch`, and `save_artifact`. Select it
    explicitly to use the new tools; the default remains
    `agent_toolset_20260901`. Self-hosted environments still only support the
    older toolset.


    ### 2026-11-09


    - **Missing MCP credentials:** When an enabled Plugin MCP server explicitly
    declares OAuth or bearer-token authentication, creating a Session without a
    matching active credential because the bound Vault is archived now returns
    400 `invalid_parameter_error` with `param=resources` instead of
    `failed_precondition_error`. Bind an active Vault containing a matching
    active credential in `resources` before retrying.


    ### 2026-11-05


    - **Idempotency fingerprint:** All operations that accept `Idempotency-Key`
    now check the request target and API version as well as the request body.
    Keep the key, target, version, and body unchanged when retrying. A retry
    against a response stored before this change may return 409 instead of
    replaying it; establish the original outcome before using a new key.

    - **More retry-safe writes:** `PATCH /v1/environments/{id}`, `POST
    /v1/sessions/{id}/events`, `POST /v1/sessions/{id}/resources`, and Vault
    credential creation, including batch creation, now accept `Idempotency-Key`.
    Reusing the same key with the same request target, API version, and body
    replays the first stored response instead of executing the event or write
    again.

    - **Project Webhooks:** create up to 32 Webhooks per project, subscribe to
    resource events, and rotate signing secrets. New Webhooks start disabled;
    save the returned signing secret and configure your receiver before
    enabling. Verify Standard Webhooks signatures before parsing notifications
    and deduplicate by event ID; notifications can be duplicated, out of order,
    or lost.


    ### 2026-11-04


    - **Trigger resources:** Trigger resource arrays reuse `SessionResource`,
    the same union as Session creation and responses. Trigger create and update
    operations accept `github_repository` entries. The shared repository schema
    keeps optional `authorization_token`; actual responses omit it. For an
    existing normalized repository URL, an omitted token preserves the current
    credential and an explicit empty string clears it.


    ### 2026-11-02


    - **Stream contract:** Session and Thread streams now declare the existing
    `control` and `error` frames alongside business events. This lets generated
    clients decode the resume cursor and stream failures. Live frame names,
    payloads, and request handling are unchanged; existing clients need no
    migration.

    - **GitHub repository resources:** Session creation accepts
    `github_repository` bindings with branch, commit, and mount-path settings.
    Repository provisioning is asynchronous; a successful Create Session
    response does not mean clones are ready. Handle the new repository
    `session.error` types. The write-only `authorization_token` input is never
    returned, and repository bindings cannot be added, changed, or removed after
    creation.


    ### 2026-10-28


    - **Union titles:** Discriminated union references no longer repeat variant
    titles next to `$ref`. Each title stays on the referenced schema, improving
    compatibility with OpenAPI tools. Schema validation, wire payloads, and
    request handling are unchanged.

    - **Error responses and examples:** Shared error responses now use reusable
    response components with valid examples. The spec also adds examples and
    descriptions to request bodies, parameters, and schemas. Wire payloads and
    request handling are unchanged.


    ### 2026-10-27


    - **System prompt text:** Agent and Session system prompts are now used
    verbatim. Template-like text such as `{{.Date}}` is no longer rendered or
    rejected for template syntax. Remove template variables from prompts if you
    relied on date substitution; time continues to be provided through dynamic
    messages.


    ### 2026-10-23


    - **Credential host matching:** Creating or updating an environment-variable
    credential now validates the submitted `networking.allowed_hosts`. Accepted
    entries are exact hostnames, single IP addresses, `*.example.com` wildcards,
    and host-only `http` or `https` URLs with an optional trailing `/`; URLs are
    stored as hostnames or IP addresses. This validation also applies when
    access is `unrestricted`. New writes reject `~regex` and CIDR ranges;
    existing stored entries continue to match requests, but must be replaced
    with supported entries when resubmitting the list.


    ### 2026-11-11


    - **File content:** an ID that does not use the `file_` prefix and is not a
    batch object ID now returns the same JSON parsed-text object as
    `file-extract`. A missing file returns 404 `resource_not_found_error`. A
    file with no parsed text returns 400 `failed_precondition_error`.


    ### 2026-10-22


    - **Stop completion:** events no longer carry the event-level `epoch`. To
    tell whether a status comes from a stop, use the new `data.control_epoch` on
    `session.status`, the Session control generation the status change belongs
    to: after a stop, wait for an `idle` or `terminated` status whose
    `data.control_epoch` is at least the stop's `control_epoch`; when the field
    is absent, confirm with Get Session.


    ### 2026-10-21


    - **Token usage:** `Session` and `SessionThread` gain an optional `usage`
    field (`TokenUsage`) with the cumulative `input_tokens`,
    `cached_input_tokens`, `output_tokens`, `reasoning_output_tokens`, and
    `total_tokens` of successful model calls, also returned on list items. The
    new `session.usage` event carries the Session's cumulative usage snapshot
    just before the Session turns idle or terminated. A missing `usage` means
    usage was not reported, not zero.


    ### 2026-10-14


    #### Triggers


    - **`reuse_session` updates:** updating a Trigger that is and stays in
    `reuse_session` now returns 400 `failed_precondition_error` when it changes
    `agent_id`, `agent_version`, `environment_id`, or `resources`. These changes
    were previously accepted but never reached the managed Session, which keeps
    the configuration it was created with. Switch `session_mode` to
    `new_session` first, or create a new Trigger.

    - **Platform-started runs:** runs started by the platform for a managed
    Trigger, such as a Dreams policy's activity check, now record `context.type:
    "system"` instead of a `manual` context attributed to the Trigger's creator.
    Clients that branch on `context.type` must accept `system`.


    #### Session event streams


    - **Delta previews opt-in:** the Session and Thread event streams no longer
    include `agent.delta` events by default. Set the new `include_deltas=true`
    query parameter to keep receiving incremental previews; consumers of
    complete events only no longer receive delta traffic.


    #### Tool replies


    - **Tool confirmations:** invalid confirmation fields use complete
    `body.events[index].data.field` paths in `error.param`. The response
    documentation now states that accepted `user.tool_confirmation` and
    `user.custom_tool_result` requests return 202 with an empty JSON object;
    response behavior is unchanged.


    ### 2026-10-12


    - Session creation now requires a matching Vault credential for enabled
    remote Plugin MCP servers that explicitly declare OAuth or bearer-token
    authentication and have no non-empty static Authorization header. Bind the
    Vault in `resources` before retrying a rejected request. Anonymous probe
    results alone do not require a Vault binding.


    ### 2026-10-10


    #### Self-hosted worker shutdown


    - **Worker shutdown:** an interrupted Session can release its WorkItem after
    cancellation finishes even if input remains queued. Explicit Continue queues
    work again when the lease was released. Use `user.interrupt` to stop Session
    execution, or WorkItem stop to request worker shutdown.

    - **Stop completion:** WorkItem stop without `final_status` enters
    `stopping`; the worker cancels tools, finishes result writes, then submits
    `final_status: completed`. A still-busy Session is cancelled. An idle worker
    can submit `completed` directly to release without cancellation; active
    execution or new input returns 409 `failed_precondition_error`. Session work
    tokens may stop their own WorkItem. REST does not accept `force` or
    `reason`.


    #### Tool confirmation and Custom Tools


    - **Tool replies:** `always_ask` tools emit `agent.tool_use` and wait for
    `user.tool_confirmation`. Tools declared with `type: custom` emit
    `agent.custom_tool_use`; the client executes them and submits
    `user.custom_tool_result`. Both replies reference `data.event_id`, omit
    `session_thread_id`, and use the first valid reply for each call.

    - **Waiting Threads:** `requires_action` and `stop_reason.event_ids`
    identify pending confirmations and Custom Tool results. Each Thread resumes
    when all its pending replies arrive; the Session list aggregates waiting
    Threads. Child status, requests, and replies appear in the Session stream
    with top-level `session_thread_id`.


    ### 2026-10-09


    - MCP tools now load on demand when neither the toolset nor the tool sets
    `load_mode`. The model receives names first and loads schemas as needed. To
    keep the previous loading behavior, set `load_mode: eager` to send schemas
    with every request; models without on-demand support still use eager
    loading.

    - In `agent_toolset_20260901`, `search_image_by_text` and
    `search_image_by_image` adopt the same default. Other built-in tools remain
    `eager`.


    ### 2026-09-24


    - `project` Plugin references accept `version: "latest"`, resolving to the
    adopted version on each wake. Omitting the version still pins the latest
    published version at write time. `official` references must omit the
    version; any explicit value returns 400 `invalid_parameter_error`.


    ### 2026-09-23


    - **Prompt validation:** Session creation and update reject invalid
    `agent_overrides.system` templates with 400 `invalid_parameter_error`.

    - **Execution events:** New `agent.model_started` and `agent.tool_started`
    events mark model requests and tool execution. Streaming calls emit
    `agent.thinking_started` and `agent.message_started` at the first respective
    chunks; non-streaming calls omit them. Measure TTFT from
    `agent.model_started` to the first `agent.delta`.

    - **Configuration notifications:** Concurrent updates emit `session.updated`
    in commit order; the event does not identify when running execution adopts
    the new configuration.


    ### 2026-09-21


    #### Project Plugins


    - **Project Plugins:** `POST /v1/plugins` and `POST
    /v1/plugins/{id}/versions` publish `.zip` bundles up to 64 MiB, returning
    201 with the Plugin, version, and validation report. Both accept
    `Idempotency-Key`. `POST /v1/plugins/validate` checks without publishing; an
    unpublishable bundle returns a 200 report with `ok: false`.

    - **Plugin versions and archive:** `GET /v1/plugins/{id}/versions` lists
    newest semantic versions first; `GET
    /v1/plugins/{id}/versions/{version}/content` downloads `application/zip`.
    `POST /v1/plugins/{id}/archive` returns 204, removes the Plugin from reads,
    and releases its project name. Existing exact version references keep
    working.

    - **Plugin selection:** `GET /v1/plugins` accepts `scope` for `official` or
    `project`; omission returns both, while `org` and `user` return 400
    `invalid_parameter_error`. `Plugin` adds `scope`, `status`, and
    `latest_version`; `version` still identifies the version pinned at
    configuration write time.

    - **Session Plugins:** create and update accept `agent_overrides.plugins`,
    replacing the frozen Agent's set with the same three-state semantics as
    `skills`. `official` entries omit `version`; `project` entries may pin a
    published version.


    #### OAuth routing


    - `MCPOAuthCredential` and `CreateVaultOAuthSession` accept
    `egress_environment_id`. Discovery, dynamic client registration, token
    exchange, and background refresh use that Environment's proxy. An empty
    string clears the binding. Omission leaves a new credential unbound and
    preserves an existing binding on update.


    ### 2026-09-20


    - Plugin and Skill responses add optional `categories` for display;
    uncategorized resources omit it. The declared vocabulary includes `finance`.
    Categories do not change Agent configuration. `GET /v1/plugins` and `GET
    /v1/skills` accept `category` to filter the list.


    ### 2026-09-19


    - Agent and Session `model.reasoning_effort` accept `max`. This remains a
    hint that the selected model may ignore.


    ### 2026-09-17


    #### Session input and configuration


    - **Input capacity:** 50 pending Session inputs cause new input to return
    400 `failed_precondition_error`. Consumption or retraction frees capacity;
    Interrupt and Continue remain available.

    - **Session overrides:** `agent_overrides` adds `tools`, `model`, and
    `system` alongside `mcp_servers` and `skills`. `roster` can be overridden
    only on creation; including it in `PATCH` returns 400
    `invalid_parameter_error`.

    - **Skill versions:** omission freezes the current version at write time;
    `"latest"` resolves on every wake; an exact version is validated and pinned.
    Mixing `"latest"` and an exact version for one `skill_id` returns 400
    `invalid_parameter_error`.

    - **Update events:** `session.updated` is emitted only for actual changes
    and carries only changed fields: the effective Agent snapshot and override
    document, or `title`. Clearing all overrides emits an empty
    `agent_overrides` object. Clients can safely ignore an unrecognized event.


    #### Trigger delivery and pauses


    - **Reused Sessions:** scheduled and manual `reuse_session` runs skip idle
    Sessions last stopped by an execution error (`session_failed`) and full
    queues (`session_queue_full`). Three consecutive such skips for the same
    Session pause the Trigger; other outcomes reset the count. Existing messages
    and Session retries are unaffected.

    - **Trigger pauses:** scheduled runs that automatically pause an active
    Trigger send `trigger.paused` webhooks. Use `data.id` to retrieve the
    Trigger's `paused_reason`. Ordinary skips and manual operations do not emit
    the webhook.


    #### Contract corrections and clarifications


    - **Trigger errors:** `TriggerRun.error` and `PausedReason.error` use
    `TriggerError`, whose display-only `type` is an open string, including
    `fire_failed`, `session_failed`, and `overlap_in_flight`. This corrects the
    schema's use of `ErrorType`; the wire payload is unchanged.

    - **Existing behavior clarified:** interrupt retains pending input; Trigger
    updates revalidate unchanged `initial_events`; Sessions without a multiagent
    roster omit orchestration tools; duplicate built-in toolsets use the first
    declaration without merging. Requests and responses are unchanged.


    ### 2026-09-15


    - **Unknown JSON fields:** undeclared members now return 400
    `invalid_parameter_error` with a path such as `body.unknown_key`; they were
    previously ignored. Remove extra members from requests.

    - **Time filters:** Agent and Session lists accept `created_at_gt`,
    `created_at_gte`, `created_at_lt`, `created_at_lte`, and matching
    `updated_at_*` filters. `gt` and `lt` exclude the boundary; `gte` and `lte`
    include it.

    - **Contract declarations:** OpenAPI moves from 3.1.0 to 3.2.0. Multipart
    file parts on `POST /v1/files` and `POST /v1/skills` use the standard
    file-part declaration with untyped schemas and wildcard encoding. Event
    streams declare per-event `itemSchema` with `event` and `data`. Create
    operations share one `Idempotency-Key` parameter. Wire formats and request
    handling are unchanged.


    ### 2026-09-14


    - Explicit `null` on an optional non-nullable request field now returns 400
    `invalid_parameter_error`, identifying a path such as `body.name` or
    `body.description`. It was previously treated as omission. Omit fields to
    leave them unchanged; use a field's documented empty value to clear it.


    ### 2026-09-13


    - Request validation now enforces declared types, required fields, ranges,
    patterns, enums, and composition rules for query, path, header, and JSON
    inputs. Violations return 400 `invalid_parameter_error`. Validation paths
    include location prefixes and array indices, such as
    `body.mcp_servers[2].name` and `query.page_size`. Some violations were
    previously accepted or reported later with shorter paths and different
    messages. Check requests against the declared constraints; use `error.type`
    and `param` rather than matching message text.

    - An undeclared `Content-Type` now returns 400 `invalid_request_error`, even
    if the body can be parsed. Use `application/json` for JSON operations and
    `multipart/form-data` for uploads.


    ### 2026-09-10


    The durable-interrupt behavior announced on 2026-09-09 is now effective.


    - **Interrupt:** idle Sessions now accept interrupt and return 202 with
    `control_epoch` rather than 400. The Session and active Threads stop
    asynchronously; neither the response nor `user.interrupt` acknowledgement
    confirms completion. Check Get Session. The optional token is
    `data.expected_control_epoch`; stale values return 409 `conflict_error`.
    Repeated interrupt does not advance the epoch while the Session remains
    interrupted.

    - **Continue:** `POST /v1/sessions/{id}/continue` returns `control_epoch`,
    leaves uninterrupted Sessions unchanged, and returns 409 `conflict_error`
    for stopping or terminated Sessions. Acceptance does not mean startup is
    complete; check `continue_pending` at the returned epoch.

    - **Queued input:** new input after stop resumes execution once stopping
    finishes. Retained input alone does not resume the Session; resumption
    preserves queue order.

    - **Archive:** running child Threads can be archived and cancelled,
    including during Session stop. Repeated child archive returns 204 while the
    parent Session is not terminated. Session archive returns 409
    `conflict_error` while stopping and still returns 400 while running.


    ### 2026-09-09


    The durable-interrupt contract was announced on this date. Execution changes
    took effect on 2026-09-10; see that entry for stop completion and recovery
    behavior.


    - **Control state:** Threads add `interrupted` and `control_epoch`; Sessions
    add `stopping`, `interrupted`, `control_epoch`, and `continue_pending`;
    events may include `epoch` and `user.interrupt` acknowledgements.

    - **Lifecycle operations:** the contract adds bodyless `POST
    /v1/sessions/{id}/continue`, interrupt for idle Sessions, and resumption by
    new input after stop. An optional expected epoch rejects stale requests with
    409 `conflict_error`; omission targets the current generation. Child archive
    cancels active execution. Session deletion returns 409 `conflict_error`
    while lifecycle work or active Threads remain.

    - **Trigger input:** `initial_events` and pending events accept queued user
    messages, excluding interrupt commands in this beta. A `reuse_session`
    Trigger resumes a stopped Session.


    ### 2026-09-07


    - **Field errors:** JSON typing and validation failures use
    `invalid_parameter_error` with the field path; union errors identify the
    union itself. Request-level failures use `invalid_request_error` without
    `param`. This corrects previously misclassified or incomplete field errors.
    Missing `user.message.data` and below-minimum
    `activity.min_changed_sessions` are now rejected.

    - **Opaque IDs:** resource IDs no longer declare `pattern` constraints.
    Remove validation based on the old patterns; they did not cover all issued
    IDs.

    - **MCP errors:** `SessionErrorType` adds `mcp_connection_failed` and
    `mcp_authentication_failed` for initial connection or mid-turn failures.
    Authentication failures are reported after one automatic credential refresh
    and retry still fails; other refresh failures are not Session errors.
    `SessionErrorPayload.mcp_server_name` identifies the affected server and is
    absent on other types and older events. Use it instead of parsing the
    message.

    - **Official Environments:** `GET /v1/environments` adds `official_only`,
    defaulting to false.


    ### 2026-09-06


    - `listTriggers` accepts `agent_id` to filter by owning Agent.


    ### 2026-09-05


    - `listMemoryStores` and `listMemories` now return newest first instead of
    ascending creation order. Update clients that rely on the old order.

    - `GET /v1/agents` adds `official_only`, defaulting to false.


    ### 2026-09-04


    - **Contract declarations only:** operations declare the optional
    `kimi-api-version` header; runtime still requires it outside `/v1/files*`
    and selects the compatibility format when omitted on file endpoints. Streams
    declare the existing `Cache-Control: no-cache` and `X-Accel-Buffering: no`
    headers. The shared 429 response declares the existing `Retry-After` header,
    sent only for `rate_limit_reached_error`. Request handling is unchanged.


    ### 2026-09-03


    - **Batch files:** attaching a `batch` file to a Session returns 400
    `failed_precondition_error` instead of 404 `resource_not_found_error`.
    Attachment remains unsupported.

    - **MCP headers:** Agent and Session `McpServer` declarations accept
    write-only `headers` for non-sensitive connection headers. On update,
    omitted or empty headers preserve values for an unchanged server identity
    (name, type, and URL); non-empty headers replace them, and empty-string
    values delete keys. Names differing only in case are rejected.

    - **Environment proxy:** `EnvironmentProxy.route_all` routes all egress
    hosts through the proxy and allows an empty `hosts` list. Platform-internal
    endpoints bypass it. Under `limited`, the host allow list does not apply;
    the proxy determines reachability.
servers:
  - url: https://api.moonshot.ai
    description: Production
    variables: {}
security:
  - BearerAuth: []
tags:
  - name: Agents
    description: Configure Agents and manage their immutable versions.
  - name: Sessions
    description: Start and manage Sessions, Threads, messages, resources, and events.
  - name: Files
    description: Upload, browse, download, and delete user files.
  - name: Artifacts
    description: Browse delivered Artifacts and download specific versions.
  - name: Skills
    description: Upload Skill packages and manage their immutable versions.
  - name: Work Items
    description: >-
      Claim and drive self-hosted Session work through the Environment work
      queue.
  - name: Environments
    description: Configure the Environments used to run Sessions.
  - name: Vaults
    description: Store and manage credentials and OAuth sessions in Vaults.
  - name: Plugins
    description: Browse the Plugins available to your project.
  - name: Memory Stores
    description: Manage Memory Stores, their files and versions, and Dreams policies.
  - name: Webhooks
    description: Subscribe project endpoints to resource-change notifications.
  - name: Triggers
    description: Create, configure, and run Triggers.
paths:
  /v1/sessions/{id}/threads/{thread_id}/events/stream:
    get:
      tags:
        - Sessions
      summary: Stream Thread events (SSE)
      description: |-
        Opens a live Server-Sent Events stream for one Thread. Only events
        produced by that Thread appear here. Use the Thread's `/events` endpoint
        for stored history. Frame format, delta delivery, and resume behavior
        match the Session event stream.
      operationId: streamThreadEvents
      parameters:
        - $ref: '#/components/parameters/APIVersionHeader'
        - name: id
          in: path
          required: true
          description: Session ID.
          schema:
            type: string
          example: sesn_01h455vb4pex5vsknk084sn02q
        - name: thread_id
          in: path
          required: true
          description: Thread ID.
          schema:
            type: string
          example: sthr_01h455vb4pex5vsknk084sn02q
        - name: cursor
          in: query
          required: false
          description: >-
            Resume after a previous `id:` frame. `now` receives future events
            only.
          schema:
            type: string
          explode: false
          example: now
        - name: include_deltas
          in: query
          required: false
          description: >-
            Include the stream-only `agent.delta` incremental events. Omitted or
            `false` delivers complete events only.
          schema:
            type: boolean
          explode: false
        - name: Last-Event-ID
          in: header
          required: false
          description: >-
            Resume after a previous SSE `id:` frame. `cursor` takes precedence
            when both are set.
          schema:
            type: string
          example: '4096'
      responses:
        '200':
          description: The Thread's live Server-Sent Events stream.
          headers:
            Cache-Control:
              required: true
              description: 'Always `no-cache`: the event stream must not be cached.'
              schema:
                type: string
            X-Accel-Buffering:
              required: true
              description: >-
                Always `no`: hints intermediaries to disable response buffering
                so frames flush immediately.
              schema:
                type: string
          content:
            text/event-stream:
              itemSchema:
                type: object
                properties:
                  event:
                    type: string
                  data:
                    type: string
                required:
                  - event
                oneOf:
                  - title: user.message
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/UserMessageEvent'
                      event:
                        const: user.message
                  - title: user.interrupt
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/UserInterruptEvent'
                      event:
                        const: user.interrupt
                  - title: user.tool_confirmation
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/UserToolConfirmationEvent'
                      event:
                        const: user.tool_confirmation
                  - title: user.custom_tool_result
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/UserCustomToolResultEvent'
                      event:
                        const: user.custom_tool_result
                  - title: agent.message
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/AgentMessageEvent'
                      event:
                        const: agent.message
                  - title: agent.thinking
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/AgentThinkingEvent'
                      event:
                        const: agent.thinking
                  - title: agent.tool_use
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/AgentToolUseEvent'
                      event:
                        const: agent.tool_use
                  - title: agent.tool_result
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/AgentToolResultEvent'
                      event:
                        const: agent.tool_result
                  - title: agent.model_started
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/AgentModelStartedEvent'
                      event:
                        const: agent.model_started
                  - title: agent.thinking_started
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/AgentThinkingStartedEvent'
                      event:
                        const: agent.thinking_started
                  - title: agent.message_started
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/AgentMessageStartedEvent'
                      event:
                        const: agent.message_started
                  - title: agent.tool_started
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/AgentToolStartedEvent'
                      event:
                        const: agent.tool_started
                  - title: agent.custom_tool_use
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/AgentCustomToolUseEvent'
                      event:
                        const: agent.custom_tool_use
                  - title: agent.thread_message_received
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/AgentThreadMessageReceivedEvent'
                      event:
                        const: agent.thread_message_received
                  - title: agent.thread_message_sent
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/AgentThreadMessageSentEvent'
                      event:
                        const: agent.thread_message_sent
                  - title: agent.thread_context_compacted
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: >-
                            #/components/schemas/AgentThreadContextCompactedEvent
                      event:
                        const: agent.thread_context_compacted
                  - title: agent.delta
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/AgentDeltaEvent'
                      event:
                        const: agent.delta
                  - title: session.status
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/SessionStatusEvent'
                      event:
                        const: session.status
                  - title: session.error
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/SessionErrorEvent'
                      event:
                        const: session.error
                  - title: session.thread_created
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/SessionThreadCreatedEvent'
                      event:
                        const: session.thread_created
                  - title: session.thread_status
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/SessionThreadStatusEvent'
                      event:
                        const: session.thread_status
                  - title: session.title_updated
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/SessionTitleUpdatedEvent'
                      event:
                        const: session.title_updated
                  - title: session.updated
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/SessionUpdatedEvent'
                      event:
                        const: session.updated
                  - title: session.usage
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/SessionUsageEvent'
                      event:
                        const: session.usage
                  - title: control
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/StreamControl'
                      event:
                        const: control
                  - title: error
                    properties:
                      data:
                        contentMediaType: application/json
                        contentSchema:
                          $ref: '#/components/schemas/APIError'
                      event:
                        const: error
        '400':
          $ref: '#/components/responses/BadRequestErrorResponse'
        '401':
          $ref: '#/components/responses/UnauthorizedErrorResponse'
        '404':
          $ref: '#/components/responses/NotFoundErrorResponse'
        '429':
          $ref: '#/components/responses/TooManyRequestsErrorResponse'
        default:
          $ref: '#/components/responses/APIError'
components:
  parameters:
    APIVersionHeader:
      name: kimi-api-version
      in: header
      required: false
      description: >-
        API version for this request, in `YYYY-MM-DD` form. Send
        `2026-09-01-beta`

        for the version documented here. Required outside `/v1/files*`: a
        missing

        header there is rejected with 400 `invalid_request_error`; on
        `/v1/files*`

        its absence selects the compatibility behavior. An unknown value is

        rejected with 400 `invalid_request_error` on every endpoint.
      schema:
        $ref: '#/components/schemas/APIVersion'
      example: 2026-09-01-beta
  responses:
    BadRequestErrorResponse:
      description: >-
        The request failed validation. Check `message` for details.
        `invalid_parameter_error` identifies a field error,
        `invalid_request_error` a malformed request, and
        `failed_precondition_error` a resource state that prevents the
        operation.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/APIError'
          example:
            error:
              type: invalid_parameter_error
              message: The `name` parameter is invalid.
              request_id: req_01h455vb4pex5vsknk084sn02q
              param: name
    UnauthorizedErrorResponse:
      description: Credentials are missing or invalid. Provide valid credentials and retry.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/APIError'
          example:
            error:
              type: authentication_error
              message: Provide valid credentials before retrying.
              request_id: req_01h455vb4pex5vsknk084sn02q
    NotFoundErrorResponse:
      description: The resource does not exist or is not visible to the caller.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/APIError'
          example:
            error:
              type: resource_not_found_error
              message: The requested resource does not exist.
              request_id: req_01h455vb4pex5vsknk084sn02q
    TooManyRequestsErrorResponse:
      description: The caller has hit a rate limit or exhausted a quota.
      headers:
        Retry-After:
          required: false
          description: >-
            Wait this many seconds before retrying. The header is present only
            when

            `error.type` is `rate_limit_reached_error`; quota errors do not
            include it.
          schema:
            type: integer
            format: int32
          example: 60
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/APIError'
          example:
            error:
              type: rate_limit_reached_error
              message: Too many requests. Retry after 60 seconds.
              request_id: req_01h455vb4pex5vsknk084sn02q
    APIError:
      description: An unexpected error response.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/APIError'
          example:
            error:
              type: server_error
              message: The platform could not complete the request. Retry later.
              request_id: req_01h455vb4pex5vsknk084sn02q
  schemas:
    APIVersion:
      type: string
      enum:
        - 2026-09-01-beta
      description: >-
        API versions served by the platform. New dated versions are added as
        they

        ship; a version is removed after its announced Sunset date.
    APIError:
      type: object
      required:
        - error
      properties:
        error:
          $ref: '#/components/schemas/ErrorObject'
          description: Details about the failure.
          example:
            type: server_error
            message: The platform could not complete the request. Retry later.
            request_id: req_01h455vb4pex5vsknk084sn02q
      description: Standard error response body for API errors.
      example:
        error:
          type: server_error
          message: The platform could not complete the request. Retry later.
          request_id: req_01h455vb4pex5vsknk084sn02q
    ErrorObject:
      type: object
      required:
        - type
        - message
      properties:
        type:
          $ref: '#/components/schemas/ErrorType'
          description: Error category that tells the client how to handle the failure.
          example: invalid_parameter_error
        message:
          type: string
          description: Message describing the failure.
          example: The `name` parameter is invalid.
        param:
          type: string
          description: >-
            Request parameter or body field to correct, when applicable. Always
            present on `invalid_parameter_error`.
          example: name
        request_id:
          type: string
          description: >-
            Request ID to include when reporting an error. Present on every
            error response and normally matches `Msh-Request-Id`.
          example: req_01h455vb4pex5vsknk084sn02q
      description: Error details returned when a request fails.
    ErrorType:
      type: string
      enum:
        - invalid_parameter_error
        - invalid_request_error
        - failed_precondition_error
        - authentication_error
        - permission_denied_error
        - resource_not_found_error
        - conflict_error
        - rate_limit_reached_error
        - exceeded_current_quota_error
        - server_error
      description: >-
        Error types that identify how a client should respond to a failed
        request.

        The request vocabulary is fixed, but response values may be extended in
        future versions.
  securitySchemes:
    BearerAuth:
      type: http
      scheme: Bearer
      description: Bearer token for API authentication.

````