> ## 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.

# List Sessions

> Returns the caller's Sessions, most recently updated first unless `order`
is provided. Items omit the `resources` bindings. Use
`GET /v1/sessions/{id}` for them.

`agent_id` restricts the listing to one Agent, `agent_version` to one of
its pinned versions, and `statuses` to the given lifecycle states.
The `created_at_*` and `updated_at_*` parameters bound the listing by
creation or last-update time; the `gt` / `lt` suffixes are exclusive,
`gte` / `lte` inclusive.
Archived Sessions are excluded unless `include_archived` is true.



## OpenAPI

````yaml /hosted-agents/openapi.yaml get /v1/sessions
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:
    get:
      tags:
        - Sessions
      summary: List Sessions
      description: >-
        Returns the caller's Sessions, most recently updated first unless
        `order`

        is provided. Items omit the `resources` bindings. Use

        `GET /v1/sessions/{id}` for them.


        `agent_id` restricts the listing to one Agent, `agent_version` to one of

        its pinned versions, and `statuses` to the given lifecycle states.

        The `created_at_*` and `updated_at_*` parameters bound the listing by

        creation or last-update time; the `gt` / `lt` suffixes are exclusive,

        `gte` / `lte` inclusive.

        Archived Sessions are excluded unless `include_archived` is true.
      operationId: listSessions
      parameters:
        - $ref: '#/components/parameters/APIVersionHeader'
        - name: order
          in: query
          required: false
          description: Listing order. Defaults to `updated_at_desc`.
          schema:
            $ref: '#/components/schemas/SessionOrder'
          explode: false
          example: updated_at_desc
        - name: agent_id
          in: query
          required: false
          description: Restrict the listing to Sessions running this Agent.
          schema:
            type: string
          explode: false
        - name: agent_version
          in: query
          required: false
          description: >-
            Restrict the listing to Sessions pinned to this Agent version
            (per-resource numeric string, such as `"2"`). Typically combined
            with `agent_id`.
          schema:
            type: string
          explode: false
        - name: statuses
          in: query
          required: false
          description: >-
            Restrict the listing to these lifecycle statuses. Omitted means
            every status.
          schema:
            type: array
            items:
              $ref: '#/components/schemas/SessionState'
          explode: false
        - name: include_archived
          in: query
          required: false
          description: Include archived Sessions. Omitted means they are excluded.
          schema:
            type: boolean
          explode: false
        - name: created_at_gt
          in: query
          required: false
          description: Return Sessions created after this timestamp (exclusive).
          schema:
            type: string
            format: date-time
          explode: false
        - name: created_at_gte
          in: query
          required: false
          description: Return Sessions created at or after this timestamp (inclusive).
          schema:
            type: string
            format: date-time
          explode: false
        - name: created_at_lt
          in: query
          required: false
          description: Return Sessions created before this timestamp (exclusive).
          schema:
            type: string
            format: date-time
          explode: false
        - name: created_at_lte
          in: query
          required: false
          description: Return Sessions created at or before this timestamp (inclusive).
          schema:
            type: string
            format: date-time
          explode: false
        - name: updated_at_gt
          in: query
          required: false
          description: Return Sessions last updated after this timestamp (exclusive).
          schema:
            type: string
            format: date-time
          explode: false
        - name: updated_at_gte
          in: query
          required: false
          description: Return Sessions last updated at or after this timestamp (inclusive).
          schema:
            type: string
            format: date-time
          explode: false
        - name: updated_at_lt
          in: query
          required: false
          description: Return Sessions last updated before this timestamp (exclusive).
          schema:
            type: string
            format: date-time
          explode: false
        - name: updated_at_lte
          in: query
          required: false
          description: >-
            Return Sessions last updated at or before this timestamp
            (inclusive).
          schema:
            type: string
            format: date-time
          explode: false
        - $ref: '#/components/parameters/PaginationQuery.page_size'
        - $ref: '#/components/parameters/PaginationQuery.page_token'
      responses:
        '200':
          description: >-
            Sessions are returned in the requested order. Each item omits
            `resources`.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/SessionList'
              example:
                items: []
                next_page_token: next-page-token
        '400':
          $ref: '#/components/responses/BadRequestErrorResponse'
        '401':
          $ref: '#/components/responses/UnauthorizedErrorResponse'
        '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
    PaginationQuery.page_size:
      name: page_size
      in: query
      required: false
      description: How many items to return (1–1000; default 50).
      schema:
        type: integer
        format: int32
        minimum: 1
        maximum: 1000
        default: 50
      explode: false
      example: 20
    PaginationQuery.page_token:
      name: page_token
      in: query
      required: false
      description: >-
        Pass the `next_page_token` from a previous response to fetch the next
        page.
      schema:
        type: string
      explode: false
      example: ''
  schemas:
    SessionOrder:
      type: string
      enum:
        - created_at
        - created_at_desc
        - updated_at
        - updated_at_desc
      description: >-
        Order used when listing Sessions: `updated_at_desc` (default),
        `updated_at`, `created_at_desc`, or `created_at`.
    SessionState:
      type: string
      enum:
        - idle
        - running
        - stopping
        - terminated
      description: |-
        Current lifecycle state of a Session or Thread.

        - `idle`: not executing. Accepts new input.
        - `running`: executing a turn.
        - `terminated`: final state after archiving.
    SessionList:
      type: object
      required:
        - items
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/Session'
          description: Sessions in the current page.
          examples:
            - []
        next_page_token:
          type: string
          description: >-
            Pagination token for the next page. Absent when the listing is
            exhausted.
          examples:
            - next-page-token
      description: One page of Sessions. Items omit the `resources` bindings.
    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.
    Session:
      type: object
      required:
        - id
        - agent_id
        - environment_id
        - status
        - created_at
        - updated_at
      properties:
        id:
          type: string
          description: Session ID.
          examples:
            - sesn_01h455vb4pex5vsknk084sn02q
        agent_id:
          type: string
          description: Agent this session is running.
          examples:
            - agent_01h455vb4pex5vsknk084sn02q
        environment_id:
          type: string
          description: Environment hosting this session.
          examples:
            - env_01h455vb4pex5vsknk084sn02q
        status:
          $ref: '#/components/schemas/SessionState'
          description: Current lifecycle status.
          examples:
            - idle
        interrupted:
          type: boolean
          description: >-
            Whether a committed stop pauses execution. A new message or explicit
            continue can resume it.
          examples:
            - false
        control_epoch:
          $ref: '#/components/schemas/ControlEpoch'
          description: Current Session control generation.
          examples:
            - '1'
        continue_pending:
          type: boolean
          description: A continue was accepted but execution has not started yet.
          examples:
            - false
        title:
          type: string
          description: Human-readable title.
          examples:
            - Example Session
        metadata:
          $ref: '#/components/schemas/StringMetadata'
          description: Caller-defined metadata with up to 16 entries.
          examples:
            - {}
        agent_overrides:
          $ref: '#/components/schemas/SessionAgentOverrides'
          description: >-
            Session-local agent configuration overrides. Absent when none are
            stored.
          examples:
            - {}
        created_at:
          type: string
          format: date-time
          description: Creation timestamp.
          examples:
            - '2026-01-01T00:00:00Z'
        updated_at:
          type: string
          format: date-time
          description: Last-update timestamp.
          examples:
            - '2026-01-01T00:00:00Z'
        archived_at:
          type: string
          format: date-time
          description: Archive timestamp. Absent while active.
          examples:
            - '2026-01-03T00:00:00Z'
        resources:
          type: array
          items:
            $ref: '#/components/schemas/SessionResource'
          description: >-
            Resources bound to this session. Omitted from `GET /v1/sessions`
            list items.
          examples:
            - []
        agent:
          $ref: '#/components/schemas/SessionAgent'
          description: Agent version snapshot used by the coordinator thread.
          examples:
            - id: agent_01h455vb4pex5vsknk084sn02q
              version: '1'
              name: Example Agent
        resolved_skills:
          type: array
          items:
            $ref: '#/components/schemas/SkillVersion'
          description: >-
            Effective Skills after applying Session overrides and merging roster
            and

            shared workspace Skills. Present only when Get Session explicitly
            uses

            `include=resolved_skills`. An explicitly requested empty set is
            `[]`.

            Otherwise this field is omitted, including from Session list items.

            Entries are sorted by `name`.
          examples:
            - []
        usage:
          $ref: '#/components/schemas/TokenUsage'
          description: >-
            Cumulative token usage of this Session across all Threads. Grows in
            real time as model calls complete. Also returned in list items,
            filled with one batch aggregate query per page.
          examples:
            - input_tokens: 100
              cached_input_tokens: 20
              output_tokens: 50
              reasoning_output_tokens: 10
              total_tokens: 150
      description: A Session running an immutable Agent version.
    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
    ControlEpoch:
      type: string
      maxLength: 19
      pattern: ^(0|[1-9][0-9]{0,18})$
      description: >-
        Non-negative control generation as a decimal string, from `0` through
        `9223372036854775807`.
    StringMetadata:
      type: object
      description: >-
        String metadata supplied by the caller: up to 16 entries, keys up to 64
        and values up to 512 characters.
      maxProperties: 16
      propertyNames:
        type: string
        maxLength: 64
      additionalProperties:
        type: string
        maxLength: 512
    SessionAgentOverrides:
      type: object
      properties:
        mcp_servers:
          type: array
          items:
            $ref: '#/components/schemas/McpServer'
          maxItems: 20
          description: Replacement MCP server connections for this session.
        skills:
          type: array
          items:
            $ref: '#/components/schemas/SkillRef'
          maxItems: 64
          description: >-
            Replacement skill references for this session. Empty versions are
            frozen

            to the then-current latest at write time; "latest" is stored as-is
            and

            re-resolved on every wake.
        plugins:
          type: array
          items:
            $ref: '#/components/schemas/PluginRef'
          maxItems: 64
          description: >-
            Replacement plugin references for this session. Each entry follows
            its

            Plugin's marketplace version rule (see `PluginRef.version`):
            `official`

            entries must omit `version`, `project` entries may pin a published
            one.
        tools:
          type: array
          items:
            $ref: '#/components/schemas/Tool'
          maxItems: 128
          description: >-
            Replacement tools for this session. If no `agent_toolset` is
            included, keeps the bound Agent's (or current effective)
            `agent_toolset`, or prepends `agent_toolset_20261101` if none
            exists. On update, an empty array clears the override and inherits
            the bound Agent. At most one sandbox toolset is allowed. Custom
            tools follow the same validation rules as Agent tools.
        model:
          $ref: '#/components/schemas/ModelRef'
          description: >-
            Replacement model for this session. The provider must match the

            session's model provider (the gateway injects endpoint/key per
            provider).
        system:
          type: string
          description: Replacement system prompt for this session (empty string clears it).
        roster:
          type: array
          items:
            $ref: '#/components/schemas/AgentReference'
          maxItems: 20
          description: >-
            Replacement multiagent roster for this session; entries are resolved

            and frozen to exact versions at write time. Create-session only:

            Session updates reject this field with 400
            `invalid_parameter_error`.
      description: >-
        Session-local agent configuration overrides (full-replacement, never

        merged). Each collection field is tri-state:


        - absent: inherit the frozen agent version's value (create) or leave the

        override unchanged (update).

        - explicit empty array: clear the collection for this session (create)
        or

        clear the override and fall back to the frozen value (update).

        - non-empty array: replace the collection wholesale.


        Exception: `tools` without an `agent_toolset` keeps the bound or current
        `agent_toolset` (or prepends `agent_toolset_20261101` if none exists);
        on update, `tools: []` clears the override.
    SessionResource:
      type: object
      oneOf:
        - $ref: '#/components/schemas/SessionResourceFile'
        - $ref: '#/components/schemas/SessionResourceVault'
        - $ref: '#/components/schemas/SessionResourceMemoryStore'
        - $ref: '#/components/schemas/SessionResourceGitHubRepository'
      discriminator:
        propertyName: type
        mapping:
          file: '#/components/schemas/SessionResourceFile'
          vault: '#/components/schemas/SessionResourceVault'
          memory_store: '#/components/schemas/SessionResourceMemoryStore'
          github_repository: '#/components/schemas/SessionResourceGitHubRepository'
      description: >-
        A resource binding used in Session or Trigger configuration and returned
        for a Session.
    SessionAgent:
      type: object
      required:
        - id
        - version
        - name
      properties:
        id:
          type: string
          description: Agent ID.
        version:
          type: string
          description: Exact immutable agent version.
        name:
          type: string
          description: Human-readable agent name.
        description:
          type: string
          description: Optional agent description.
        model:
          $ref: '#/components/schemas/ModelRef'
          description: Selected model.
        system:
          type: string
          description: System prompt.
        tools:
          type: array
          items:
            $ref: '#/components/schemas/Tool'
          description: Tools available to the thread.
        mcp_servers:
          type: array
          items:
            $ref: '#/components/schemas/McpServer'
          description: MCP servers available to the thread.
        skills:
          type: array
          items:
            $ref: '#/components/schemas/SkillRef'
          description: Exact skill versions available to the thread.
        multiagent:
          $ref: '#/components/schemas/SessionMultiagent'
          description: Full agent definitions the coordinator may create as child threads.
      description: Agent version snapshot used by a Session.
    SkillVersion:
      type: object
      required:
        - skill_id
        - version
        - name
        - description
        - created_at
      properties:
        skill_id:
          type: string
          description: Owning skill ID.
          examples:
            - 0198f2c4-7b3a-7f2e-9c1d-4e5f6a7b8c9d
        version:
          type: string
          description: >-
            Immutable Hosted Agents version identifier (`"1"`, `"2"`, …) within
            this Skill.
          examples:
            - '1'
        name:
          type: string
          description: Skill name declared by this version's SKILL.md.
          examples:
            - data-analysis
        description:
          type: string
          description: Skill description declared by this version's SKILL.md.
          examples:
            - Analyze tabular data and produce summaries.
        created_at:
          type: string
          format: date-time
          description: Time when this version was created.
          examples:
            - '2026-08-01T10:00:00Z'
      description: An immutable package version of a Skill.
    TokenUsage:
      type: object
      required:
        - input_tokens
        - cached_input_tokens
        - output_tokens
        - reasoning_output_tokens
        - total_tokens
      properties:
        input_tokens:
          type: integer
          format: int64
          description: Input tokens, including cached and cache-creation tokens.
        cached_input_tokens:
          type: integer
          format: int64
          description: >-
            Subset of `input_tokens` served from the provider's cache (cache
            read). Cache-creation tokens are counted in `input_tokens` but not
            reported separately.
        output_tokens:
          type: integer
          format: int64
          description: Output tokens, including reasoning tokens.
        reasoning_output_tokens:
          type: integer
          format: int64
          description: Reasoning tokens included in `output_tokens`.
        total_tokens:
          type: integer
          format: int64
          description: Total tokens reported by the model provider.
      description: >-
        Cumulative token usage of a Session or Thread since creation. Only
        successful model calls are counted; values grow in real time as model
        calls complete.
    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.
    McpServer:
      type: object
      required:
        - type
        - name
        - url
      properties:
        type:
          $ref: '#/components/schemas/McpServerType'
          description: Server type. Currently only "url" is supported.
        name:
          type: string
          minLength: 1
          description: Unique name used to reference this server from tool declarations.
        url:
          type: string
          minLength: 1
          description: MCP server endpoint URL.
        headers:
          $ref: '#/components/schemas/McpServerHeaders'
          description: >-
            Non-sensitive HTTP headers sent on every connection to this server,
            such as User-Agent or tenant routing headers.

            Accepted in requests and omitted from responses.

            Because responses omit them, updates merge headers by server
            identity instead of replacing the stored list outright: a server
            whose `headers` is absent or empty inherits the stored headers of an
            unchanged server (same name, type, and url), a non-empty `headers`
            replaces them entirely, and an empty-string value deletes that key
            (send any key with an empty-string value to clear every header of a
            server). A renamed or re-pointed server counts as new and inherits
            nothing.

            Secret tokens must not be declared here: they are supplied through
            Vault credentials instead.
      description: MCP server connection declared on an agent.
    SkillRef:
      type: object
      required:
        - skill_id
      properties:
        skill_id:
          type: string
          minLength: 1
          description: |-
            Skill identifier. Builtin and custom skills share one ID namespace.
            The two kinds are distinguished by ID prefix.
        version:
          type: string
          description: >-
            Skill version (`"1"`, `"2"`, …). If omitted, the latest version at
            write

            time is pinned. An exact version remains pinned. The literal
            `"latest"`

            is preserved and re-resolved on every read or wake.
      description: Reference to one skill version attached to an agent.
    PluginRef:
      type: object
      required:
        - plugin_id
      properties:
        plugin_id:
          type: string
          minLength: 1
          description: Plugin ID to attach.
        version:
          type: string
          description: >-
            Plugin version. Versions follow the Plugin's marketplace: an
            `official`

            Plugin is versioned by the platform, so `version` must be omitted
            and an

            explicit value is rejected with 400; a `project` Plugin may pin one
            of

            its published versions, omit it (pinned to the latest published
            version

            at write time), or carry the literal `"latest"`, which is stored
            as-is

            and re-resolved to the adopted version on every wake.
      description: Reference to a listed plugin attached to an agent.
    Tool:
      type: object
      oneOf:
        - $ref: '#/components/schemas/AgentToolset'
        - $ref: '#/components/schemas/CustomTool'
        - $ref: '#/components/schemas/McpToolset'
      discriminator:
        propertyName: type
        mapping:
          agent_toolset: '#/components/schemas/AgentToolset'
          custom: '#/components/schemas/CustomTool'
          mcp_toolset: '#/components/schemas/McpToolset'
      description: >-
        A tool declaration on an agent: a built-in toolset, custom tool, or MCP
        toolset.
    ModelRef:
      anyOf:
        - type: string
        - $ref: '#/components/schemas/ModelConfig'
      description: 'Model selection: a bare model ID string or a structured configuration.'
    AgentReference:
      type: object
      required:
        - id
        - version
      properties:
        id:
          type: string
          description: Agent ID.
        version:
          type: string
          description: Exact immutable agent version.
      description: An immutable Agent version available to a coordinator.
    SessionResourceFile:
      type: object
      required:
        - type
        - file_id
      properties:
        type:
          type: string
          enum:
            - file
        id:
          type: string
          description: Session resource ID assigned at binding.
        file_id:
          type: string
          description: Identifier of the uploaded file.
        mime_type:
          type: string
          description: MIME type of the uploaded file.
        title:
          type: string
          description: Display title of the uploaded file.
        path:
          type: string
          description: >-
            Path where the file is linked inside the Session workspace, under
            `upload/`.
      description: An uploaded file available to a Session.
      title: File
    SessionResourceVault:
      type: object
      required:
        - type
        - vault_id
      properties:
        type:
          type: string
          enum:
            - vault
        id:
          type: string
          description: Session resource ID assigned at binding.
        vault_id:
          type: string
          minLength: 1
          maxLength: 128
          description: Vault to bind.
      description: A Vault whose credentials are available to a Session.
      title: Vault
    SessionResourceMemoryStore:
      type: object
      required:
        - type
        - memory_store_id
        - access
      properties:
        type:
          type: string
          enum:
            - memory_store
        id:
          type: string
          description: Session resource ID assigned at binding.
        memory_store_id:
          type: string
          minLength: 1
          description: Memory Store to bind.
        access:
          $ref: '#/components/schemas/MemoryAccess'
          description: Access mode for this session's mount.
        instructions:
          type: string
          maxLength: 4096
          description: Additional guidance shown to the model for this binding.
      description: A Memory Store available to a Session from creation.
      title: Memory Store
    SessionResourceGitHubRepository:
      type: object
      required:
        - type
        - url
      properties:
        type:
          type: string
          enum:
            - github_repository
        id:
          type: string
          description: Session resource ID assigned at binding. Absent in creation input.
        url:
          type: string
          description: >-
            Repository URL in the form `https://github.com/<owner>/<repo>`. SSH,
            userinfo, `.git`, query, and fragment forms are rejected. The
            normalized URL must be unique within the owning Session or Trigger.
        authorization_token:
          type: string
          description: >-
            Authorization token for repository authentication. This secret is
            accepted in requests and omitted from responses. Public repositories
            can omit it.
        mount_path:
          type: string
          description: >-
            Normalized final clone directory under `/workspace`. Defaults to
            `/workspace/<repo-name>` in creation input. Paths cannot be equal or
            nested.
        checkout:
          $ref: '#/components/schemas/RepositoryCheckout'
          description: >-
            Requested branch or commit. Absent when the remote default branch
            was requested. The first resolved commit is retained for fresh
            sandbox rebuilds.
        created_at:
          type: string
          format: date-time
          description: Time when the binding was created. Absent in creation input.
        updated_at:
          type: string
          format: date-time
          description: >-
            Time when the public binding metadata was last updated. Absent in
            creation input.
      description: >-
        A GitHub repository binding used in Session or Trigger configuration.
        Session provisioning state is reported through `session.error`, not
        resource status fields.
      title: GitHub repository
    SessionMultiagent:
      type: object
      required:
        - agents
      properties:
        agents:
          type: array
          items:
            $ref: '#/components/schemas/SessionThreadAgent'
          description: Full snapshots of the agent versions available to the coordinator.
      description: Agents available for the coordinator Thread to create as child Threads.
    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.
    McpServerType:
      type: string
      enum:
        - url
      description: Type of an MCP server connection.
    McpServerHeaders:
      type: object
      description: >-
        HTTP headers declared on an MCP server connection: up to 16 entries,
        keys up to 128 and values up to 2048 characters. Keys must be RFC 7230
        header names and must not repeat in a different letter case; values must
        not contain CR/LF.
      maxProperties: 16
      propertyNames:
        type: string
        maxLength: 128
      additionalProperties:
        type: string
        maxLength: 2048
    AgentToolset:
      type: object
      required:
        - type
        - name
      properties:
        type:
          type: string
          enum:
            - agent_toolset
        name:
          $ref: '#/components/schemas/AgentToolsetName'
          description: >-
            Name of the built-in toolset to load.


            `agent_toolset_20260901` includes the built-in tools:

            [read_file, write_file, edit_file, shell, ipython, todo_read,
            todo_write,

            web_open_url, web_search, search_image_by_text,
            search_image_by_image,

            save_artifact].


            `agent_toolset_20261101` includes [read, write, edit, bash, glob,
            grep,

            web_search, web_fetch, save_artifact].


            `default_toolset_20260901` is accepted as a deprecated alias of

            `agent_toolset_20260901`.
        default_config:
          $ref: '#/components/schemas/ToolsetDefaultConfig'
          description: Defaults for every tool in the toolset.
        configs:
          type: array
          items:
            $ref: '#/components/schemas/ToolConfig'
          description: Settings that override the defaults for individual tools.
      description: >-
        Declaration of a built-in toolset for an Agent. If the same `name`
        appears

        more than once, only the first declaration is used, including its

        `default_config` and `configs`; later declarations are not merged.
      title: Agent toolset
    CustomTool:
      type: object
      required:
        - type
        - name
        - description
        - input_schema
      properties:
        type:
          type: string
          enum:
            - custom
        name:
          type: string
          minLength: 1
          maxLength: 128
          pattern: ^[A-Za-z0-9_-]+$
          description: >-
            Unique tool name containing letters, digits, underscores, or
            hyphens.
        description:
          type: string
          minLength: 1
          maxLength: 4096
          description: Tool description used by the model to decide when to call it.
        input_schema:
          $ref: '#/components/schemas/CustomToolInputSchema'
          description: JSON Schema describing the tool's input parameters.
      description: A client-side tool executed by the API caller.
      title: Custom tool
    McpToolset:
      type: object
      required:
        - type
        - mcp_server_name
      properties:
        type:
          type: string
          enum:
            - mcp_toolset
        mcp_server_name:
          type: string
          minLength: 1
          description: Name of the MCP server declared on the same agent.
        default_config:
          $ref: '#/components/schemas/ToolsetDefaultConfig'
          description: Default configuration for tools served by this MCP server.
        configs:
          type: array
          items:
            $ref: '#/components/schemas/ToolConfig'
          description: Per-tool overrides.
      description: Toolset that exposes tools from an MCP server connection.
      title: MCP toolset
    ModelConfig:
      type: object
      required:
        - id
      properties:
        id:
          type: string
          minLength: 1
          description: ID of the model to use.
        reasoning_effort:
          $ref: '#/components/schemas/ReasoningEffort'
          description: Hint for the amount of reasoning effort.
        provider:
          type: string
          description: ID of the provider. An empty value uses the default provider.
      description: Model selection with optional provider and generation hints.
    MemoryAccess:
      type: string
      enum:
        - read_only
        - read_write
      description: |-
        Permissions granted to this Session for a Memory Store.

        - `read_only`: the Session can read the store.
        - `read_write`: the Session can also write to the store. Every write is
        recorded as a Memory Version.
    RepositoryCheckout:
      type: object
      oneOf:
        - $ref: '#/components/schemas/RepositoryBranchCheckout'
        - $ref: '#/components/schemas/RepositoryCommitCheckout'
      discriminator:
        propertyName: type
        mapping:
          branch: '#/components/schemas/RepositoryBranchCheckout'
          commit: '#/components/schemas/RepositoryCommitCheckout'
      description: >-
        Branch or commit checkout for a GitHub repository. Omit it to use the
        remote default branch.
    SessionThreadAgent:
      type: object
      required:
        - id
        - version
        - name
      properties:
        id:
          type: string
          description: Agent ID.
        version:
          type: string
          description: Exact immutable agent version.
        name:
          type: string
          description: Human-readable agent name.
        description:
          type: string
          description: Optional agent description.
        model:
          $ref: '#/components/schemas/ModelRef'
          description: Selected model.
        system:
          type: string
          description: System prompt.
        tools:
          type: array
          items:
            $ref: '#/components/schemas/Tool'
          description: Tools available to the thread.
        mcp_servers:
          type: array
          items:
            $ref: '#/components/schemas/McpServer'
          description: MCP servers available to the thread.
        skills:
          type: array
          items:
            $ref: '#/components/schemas/SkillRef'
          description: Exact skill versions available to the thread.
      description: The immutable Agent version used by a Session thread.
    AgentToolsetName:
      type: string
      enum:
        - agent_toolset_20260901
        - agent_toolset_20261101
        - default_toolset_20260901
      description: >-
        Built-in toolset names. `agent_toolset_20260901` provides `read_file`,

        `write_file`, `edit_file`, `shell`, `ipython`, `todo_read`,
        `todo_write`,

        `web_search`, `web_open_url`, `search_image_by_text`,
        `search_image_by_image`,

        and `save_artifact`. `agent_toolset_20261101` provides `read`, `write`,

        `edit`, `bash`, `glob`, `grep`, `web_search`, `web_fetch`, and
        `save_artifact`.

        `configs[].name` takes the names from the selected toolset. Self-hosted

        environments support both `agent_toolset_20260901` and

        `agent_toolset_20261101`. `default_toolset_20260901` is a deprecated
        alias of

        `agent_toolset_20260901`.
    ToolsetDefaultConfig:
      type: object
      properties:
        enabled:
          type: boolean
          description: Whether tools in the toolset start enabled.
        permission_policy:
          $ref: '#/components/schemas/PermissionPolicy'
          description: Default permission policy for the tools.
        load_mode:
          $ref: '#/components/schemas/ToolLoadMode'
          description: >-
            Default schema loading mode for the tools. When unset, MCP toolsets
            use

            `on_demand`. In `agent_toolset_20260901`, `search_image_by_text` and

            `search_image_by_image` use `on_demand` and the other tools use
            `eager`.
      description: Defaults applied to every tool in a toolset.
    ToolConfig:
      type: object
      required:
        - name
      properties:
        name:
          type: string
          minLength: 1
          description: Name of the tool to configure.
        enabled:
          type: boolean
          description: Whether this tool is enabled.
        permission_policy:
          $ref: '#/components/schemas/PermissionPolicy'
          description: Permission policy for this tool.
        result_hint:
          type: string
          maxLength: 4096
          description: >-
            Optional instruction appended as a text block to the model-facing
            result

            content after a successful tool call. Appears in `agent.tool_result`

            `data.tool_result.content` (and is visible when clients fall back
            from an

            empty `structured_content`), without modifying tool-provided

            `structured_content` or failed results.
        load_mode:
          $ref: '#/components/schemas/ToolLoadMode'
          description: Tool schema loading mode override.
      description: Per-tool settings that override the toolset defaults.
    CustomToolInputSchema:
      type: object
      required:
        - type
      properties:
        type:
          type: string
          enum:
            - object
          description: Custom tool inputs are JSON objects.
        properties:
          type: object
          unevaluatedProperties: {}
          description: Property schemas keyed by input field name.
        required:
          type: array
          items:
            type: string
          description: Input field names that the model must provide.
      description: JSON Schema for the input of a custom client-side tool.
    ReasoningEffort:
      type: string
      enum:
        - low
        - medium
        - high
        - max
      description: Reasoning effort hint. The selected model may ignore it.
    RepositoryBranchCheckout:
      type: object
      required:
        - type
        - name
      properties:
        type:
          type: string
          enum:
            - branch
        name:
          type: string
          minLength: 1
          description: Branch to fetch and check out.
      description: A branch baseline requested for a GitHub repository.
      title: Branch checkout
    RepositoryCommitCheckout:
      type: object
      required:
        - type
        - sha
      properties:
        type:
          type: string
          enum:
            - commit
        sha:
          type: string
          pattern: ^[0-9A-Fa-f]{40}$
          description: Full 40-character Git commit SHA.
      description: An immutable commit baseline requested for a GitHub repository.
      title: Commit checkout
    PermissionPolicy:
      type: string
      enum:
        - always_allow
        - always_ask
      description: >-
        Permission policy applied to a tool or toolset.

        `always_allow` runs the tool when the model calls it.

        `always_ask` pauses the Thread and waits for client confirmation before
        running the tool.

        Disable a tool with `enabled: false`. Disabled tools are not exposed to
        the model.
    ToolLoadMode:
      type: string
      enum:
        - eager
        - on_demand
      description: >-
        Controls when a tool schema is loaded: `eager` loads it with the Agent

        configuration. `on_demand` loads it when the tool is first needed,
        falling

        back to eager loading where on-demand is unsupported.
  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
    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
  securitySchemes:
    BearerAuth:
      type: http
      scheme: Bearer
      description: Bearer token for API authentication.

````