Skip to main content

Subscribe to session events in real time

Call requirements, permissions, request fields, response fields, and error handling.

Request and permissions

GET https://openapi.qwenwork.ai/v1/session/sessions/{session_id}/events/stream Authentication: Authorization: Bearer <access_token>; use an access token obtained through user OAuth authorization. Required business Scope: session.session.read Authorization methods declared by the contract: Organization authorization (organization), personal authorization (personal) The platform must enable the Scope for the application. The user must have the corresponding business permissions, and the target resource must be within their accessible scope. Whether personal or organization authorization is available to the application depends on the actual console configuration.

Behavior and limitations

Omitting session_type selects a cloud session. Every remote-control request must use session_type=remote and provide a nonempty device_id. Providing device_id for a cloud session, an empty or unknown type, or duplicate target parameters returns 422 VALIDATION_ERROR. Cross-device aggregated lists and automatic fallback to cloud are not provided. Both types use the same authentication chain; the open platform validates the corresponding Scope declared by each endpoint. Cloud sessions: Server-Sent Events over a persistent connection. Event content is identical to GET /sessions/{session_id}/events and shares the same seq_id space; events are pushed as they occur rather than waiting for polling. What this adds beyond polling. Agent text arrives at the granularity at which it is produced—a response is delivered as sequential fragments as they are written, not one finished block. Polling cannot see this layer: events have already been aggregated by the time they are stored. Reading a fragmented message. Aggregate by id, not seq_id. Every fragment of a message has the same id; its seq_ids lists the covered sequence numbers. A frame whose seq_ids covers multiple values is the aggregated form and replaces content accumulated for that id; a single-value frame appends. This also makes reconnecting mid-message safe—the whole message returns rather than half of it being duplicated. Cursor. Your resume position is the end of the first contiguous sequence range you hold, not the largest value you have seen. Within an envelope, advance to the maximum seq_ids value, not seq_id: seq_id is the first sequence number covered, so an aggregated message reports a smaller number than its actual delivery position. Resuming from it redelivers the message tail. Missing sequence numbers are normal, not lost events. Some events exist but are not published by this endpoint, while still consuming sequence numbers—so numbers may skip. Do not treat gaps as missing events or wait for them. What matters is that nothing remains unresolved before your resume position. Resuming. id: is written only at message boundaries, so reconnecting never lands in the middle of a message. If a gap truly cannot be recovered, an error frame with code resync_required tells you which endpoint to use to fill it and where to resume. This is expected after a long disconnection, not a fault. Ending. The stream always ends with a done or error frame, never simply by closing the connection, so clients need not guess whether everything was received. done means orderly closure; session_terminated means the session itself has ended and reconnecting will never yield more data. Any other reason only closes the connection: reconnect with the last received id to continue. error carries a code and resume_from; every error code permits resuming from that position. Authentication uses the same bearer token as other endpoints, sent through Authorization: Bearer <token>. The public OpenAPI gateway reads Bearer Tokens only from the Authorization header. It does not authenticate using query tokens or login cookies. If native EventSource cannot set this header, use a streaming client that supports custom headers. Tokens in URLs are recorded in access logs, proxy logs, and Referer, and URLs are far more likely than headers to be pasted into bug reports. Wherever headers are supported, the header form remains the safer default. Two failure surfaces. Before the response starts, failures use normal HTTP status codes. Once the stream opens, its status is already 200; subsequent failures can only appear as an error frame or a disconnected connection. Clients must handle both. Content safety. content_blocked retracts text already delivered by this stream; discard all content received for that turn_id. Retractions cannot be replayed, so those occurring while disconnected will not be delivered. You must still moderate agent-generated text yourself before forwarding it externally. Remote-control sessions: Shares public gateway authentication with cloud sessions; this endpoint requires the business Scope stated below. No controller device ID or pairing is required. The target remote-control master switch must be enabled. If explicitly disabled, returns 403 FORBIDDEN with detail.reason=ACP_HOST_DISABLED; rejected write requests return detail.acceptance=not_accepted. An explicitly nonexistent session returns 404 NOT_FOUND with detail.reason=SESSION_NOT_FOUND. Commands route only to target connections signed in to the currently authenticated account. Offline targets, unknown targets, and targets belonging to other accounts all return device unavailable. Unknown request body fields are rejected. Use cursor or Last-Event-ID to subscribe to events in the same resource scope; conflicting values are rejected. Omitting the cursor starts at the beginning of available history; a missing history prefix returns an error. Establish the subscription first, then obtain the activation snapshot; after replay, send buffered and live events. Heartbeats keep the connection alive. Slow consumers, history gaps, or event stream changes end the stream. Offline replay is limited to a known contiguous cache window and does not represent the latest execution state. done closes the observation channel without stopping the executing turn. Like cloud SSE, authentication occurs only on connection or reconnection. Established connections have no fixed 30-minute duration or token-expiry timer; immediate disconnection on credential expiry or revocation is not guaranteed. Reconnection requires valid credentials and the same session target. Errors before response headers are sent use JSON; after streaming starts, an SSE error frame is sent if the connection remains writable. Call through the open platform, retaining the existing oauth_app Token, identity resolution, application IP restrictions, and resource ownership checks. Cloud and remote-control parameters retain their actual contract semantics. Short paths such as /sessions in this page are relative to the common prefix /v1/session. Use the full path at the top of this page for actual requests. Supported session types: cloud, remote In the full JSON, x-session-variants preserves the parameters, request bodies, and responses for cloud and remote-control sessions separately. Do not mix fields from the two branches.

Path parameters

ParameterTypeRequiredDescription and constraints
session_idstringYesSession identifier: a UUID for cloud sessions; an opaque identifier on the selected device for remote-control sessions.
Minimum length: 1
Maximum length: 256

Query parameters

ParameterTypeRequiredDescription and constraints
cursorstringNoResume after this seq_id.

🔴 What to pass: the end of the first contiguous sequence range you hold, not the largest sequence number observed. If you hold 1,2,3,7,8, pass 3, not 8. Numbers you never received are normal (some events are not published here but still consume sequence numbers), so gaps are not lost events and will never be filled—but resuming past them skips everything in between.

Within one frame: advance to the maximum seq_ids value, not seq_id—seq_id is the first sequence number covered by the frame, so an aggregated message reports a smaller number than it actually delivered. Resuming from it redelivers the message tail.

⚠️ Omitting this is not the same as passing 0: omission means "start now" without replay; 0 means "replay from the start of the session". ?cursor= (a parameter name with an empty value) is equivalent to omission.

Equivalent to the Last-Event-ID header, which takes precedence. Providing both with different values returns 422.
Remote-control sessions: an opaque string cursor bound to the account, device, session, and event stream.
Pass unchanged as a string in HTTP parameters: a decimal sequence number for cloud sessions, an opaque cursor for remote control. The service validates it according to session type.
Maximum length: 8192
include_statusbooleanNoSet to false to receive only session_event frames. This does not suppress content_blocked, which is always delivered.
Supported only for cloud sessions; passing this parameter for remote control returns 422.
Set to false to receive only session_event frames. This does not suppress content_blocked, which is always delivered.
session_typestringNoOmitting session_type selects a cloud session. Every remote-control request must use session_type=remote and provide a nonempty device_id. Providing device_id for a cloud session, an empty or unknown type, or duplicate target parameters returns 422 VALIDATION_ERROR. Cross-device aggregated lists and automatic fallback to cloud are not provided. Both types use the same authentication chain; the open platform validates the corresponding Scope declared by each endpoint.
Default: "cloud"
Allowed values: ["cloud", "remote"]
device_idstringNoRequired only for remote control. An opaque target device identifier from device discovery; it must be URL-encoded. The target connection must be signed in to the currently authenticated account.
Minimum length: 1
Maximum length: 256

Header parameters

ParameterTypeRequiredDescription and constraints
Last-Event-IDstringNoStandard SSE resume header, sent automatically by the browser's native EventSource. Equivalent to ?cursor= and takes precedence over it.

A position, not a count—do not add 1. The rule is the same as for ?cursor=: the end of the first contiguous sequence range you hold, not the largest observed value. The browser sends back the last id: written by this endpoint, and id: is written only at message boundaries—which is why the browser's automatic behavior is correct.
Remote-control sessions: an opaque string cursor bound to the account, device, session, and event stream.
Pass unchanged as a string in HTTP parameters: a decimal sequence number for cloud sessions, an opaque cursor for remote control. The service validates it according to session type.
Maximum length: 8192

Request body

The public contract declares no request body. Do not add identity fields or undeclared business fields.

Successful responses

Preserve the original response structure of each business endpoint; do not add a common code/msg/data wrapper.

HTTP 200

Success Response type: text/event-stream
FieldTypeRequiredDescription and constraints
(entire response)string——

SSE frame definitions

The response is UTF-8 text/event-stream, not a JSON array returned all at once. Array branches in the full contract describe the possible incoming frames. Clients dispatch on event and parse the corresponding data.
eventMeaning
session_eventSession business event
session_statusSession status
content_blockedRetraction signal for delivered content
doneThis observation stream has ended
errorIn-stream error
For the full data Schema of each cloud and remote-control frame, see responses in the corresponding x-session-variants branch in this service's JSON.

Error responses

HTTPDescription and handling
defaultError. Branch on code, not just the HTTP status code—multiple conditions can share the same status code.
Retain the request ID and error fields in the response for troubleshooting. A write operation may already have taken effect after a timeout or disconnection. Do not automatically retry merely because no successful response was received.

Full field contract

The JSON below contains the complete request, response, and error schemas, nested constraints, and public extension definitions for this endpoint. Copy it for verification. Success examples not declared in the contract are not inferred.
{
  "components": {
    "schemas": {
      "SessionPublicErrorBody": {
        "additionalProperties": false,
        "properties": {
          "code": {
            "description": "Stable machine-readable error code. Branch on it rather than the HTTP status code, because different conditions can share the same status. New codes may be added; treat unrecognized values as unexpected errors in that HTTP status class.",
            "examples": [
              "VALIDATION_ERROR"
            ],
            "type": "string"
          },
          "detail": {
            "description": "Structured context whose shape depends on code—for example, the fields rejected by validation. null when no additional information is available."
          },
          "message": {
            "description": "Human-readable explanation for logs and error displays. The wording is not part of the contract and may change without a version increment.",
            "examples": [
              "Request validation failed"
            ],
            "type": "string"
          },
          "trace_id": {
            "description": "W3C trace id for this request. Include it when reporting problems—it locates the request in platform logs. If the request carried no trace context, this is 32 zero characters.",
            "examples": [
              "00000000000000000000000000000000"
            ],
            "type": "string"
          }
        },
        "required": [
          "code",
          "message",
          "detail",
          "trace_id"
        ],
        "type": "object"
      },
      "SessionRelayError": {
        "additionalProperties": false,
        "properties": {
          "error": {
            "type": "string"
          },
          "error_code": {
            "type": "string"
          },
          "error_description": {
            "type": "string"
          }
        },
        "required": [
          "error",
          "error_description",
          "error_code"
        ],
        "type": "object"
      },
      "SessionPublicStreamContentBlockedFrame": {
        "additionalProperties": false,
        "properties": {
          "reason": {
            "description": "Reason the content was retracted. Open enum.",
            "examples": [
              "content_safety_violation"
            ],
            "type": "string"
          },
          "session_id": {
            "description": "Session to which the retracted content belongs.",
            "type": "string"
          },
          "turn_id": {
            "description": "Turn to retract. Retraction is turn-level: discard all received session_event frames with this turn_id.",
            "type": "string"
          }
        },
        "required": [
          "session_id",
          "reason"
        ],
        "type": "object"
      },
      "SessionPublicStreamDoneFrame": {
        "additionalProperties": false,
        "properties": {
          "final_seq_id": {
            "description": "Largest seq_id delivered on this connection. Equals the last id received, which is the resume position.",
            "format": "int64",
            "type": "integer"
          },
          "reason": {
            "description": "session_terminated: the session has ended—do not reconnect or poll it again. idle_timeout: this idle connection was closed; reconnect if the session is still needed. server_shutdown: the server is undergoing a rolling deployment; reconnect. Open enum—treat unrecognized values as reconnectable.",
            "enum": [
              "session_terminated",
              "idle_timeout",
              "server_shutdown"
            ],
            "type": "string"
          }
        },
        "required": [
          "reason",
          "final_seq_id"
        ],
        "type": "object"
      },
      "SessionPublicStreamErrorFrame": {
        "additionalProperties": false,
        "properties": {
          "code": {
            "description": "resync_required: the connection cannot provide a **contiguous** event range from the requested resume position, so it stops explicitly rather than delivering a stream with gaps. Fetch the missing range using poll_url, then reconnect from resume_from. This is **expected**, not a fault, after a long disconnection or an initial connection with a very old cursor.\n\nOnly one case warrants checking your own code: **the cursor exceeds resume_from**. Sequence numbers are **per session**, so accidentally storing another session's cursor produces exactly this situation.\n\nclient_too_slow: this connection could not keep up and was closed rather than silently skipping events; reconnect from resume_from. internal_error: server failure. Open enum.",
            "enum": [
              "resync_required",
              "client_too_slow",
              "internal_error"
            ],
            "type": "string"
          },
          "message": {
            "description": "Additional human-readable explanation. Do not parse it; branch on code.",
            "type": "string"
          },
          "poll_url": {
            "description": "Paginated endpoint path for filling gaps before reconnecting, for example /v1/session/sessions/{session_id}/events. An absolute path on the same host as the current stream—use it unchanged, not resolved relative to the stream URL. Present when filling gaps is the remedy.",
            "type": "string"
          },
          "resume_from": {
            "description": "Largest seq_id delivered before the error. Resume here—do not add one. 0 means this connection delivered nothing; retain your original cursor in that case.",
            "format": "int64",
            "type": "integer"
          }
        },
        "required": [
          "code",
          "resume_from"
        ],
        "type": "object"
      },
      "SessionPublicEvent": {
        "additionalProperties": false,
        "properties": {
          "created_at": {
            "description": "When the event was recorded. ISO 8601, with microseconds and timezone. Sort by seq_id, not this value—database insertion order may differ from timestamp order.",
            "type": "string"
          },
          "id": {
            "description": "Unique id of this event.",
            "examples": [
              "evt_01J8XQ2ZK4M7"
            ],
            "type": "string"
          },
          "method": {
            "description": "JSON-RPC method when type=method; null for result and error frames. Currently session/update or session/request_permission. This is an open set—tolerate unrecognized values.",
            "examples": [
              "session/update"
            ],
            "type": [
              "string",
              "null"
            ]
          },
          "raw": {
            "type": "object",
            "additionalProperties": {},
            "description": "JSON-RPC 2.0 message, passed through verbatim. Payload locations: raw.params.update for session/update, raw.params for other methods, and raw.result for type=result. See x-event-catalogue in open-events-schema.json for the payload shape of each (type, method, sub_type) combination.\n\n🔴 **Do not read ids from here.** raw contains the runtime's own identifiers—especially `raw.params.sessionId`, which is the agent runtime's session handle, **not the same value** as this API's `session_id` (observed: a UUID such as `9bf6533e-…` in the envelope versus `ses_f8dc…` in raw). Use `session_id` / `turn_id` / `seq_id` on the envelope—every endpoint in this API recognizes only these identifiers."
          },
          "seq_id": {
            "description": "Monotonically increasing sequence number within the session, also used as a pagination cursor. Persist the highest processed value and pass it back as ?cursor= to resume without gaps or duplicates.",
            "examples": [
              42
            ],
            "format": "int64",
            "type": "integer"
          },
          "seq_ids": {
            "description": "Sequence numbers covered by this envelope, in ascending order. This is **how to distinguish deltas from complete messages**, which must be handled differently.\n\nGroup by id first, then within each group:\n\n- len(seq_ids) == 1—streaming **delta**. **Append** its text to the existing content for that id.\n- len(seq_ids) > 1—an **assembled complete message** covering those deltas. **Replace all** existing content for that id; **do not append**.\n\nWhy both exist: each streaming fragment arrives in an envelope with the same id. Once complete, the message is stored as **one** event containing the entire message text. History readers, or callers reconnecting mid-message, receive **the whole message at once**—appending it to existing fragments would duplicate content.\n\nObserved example. Five live envelopes, id=e57bee1f, with seq_ids [26], [27], [28], [29], [30] and text fragments meaning \"I will\", \"make a\", \"water-ink\", \"style\", \"five\"—append. A later envelope with the same id, seq_ids=[26..38], contains the full text meaning \"I will make a water-ink-style Gomoku game. First, build the overall structure.\"—replace.\n\nCursors: **within one envelope**, advance to the **maximum** value here, not seq_id (the **smallest** sequence number covered; resuming from it redelivers the message tail). **Across envelopes**, resume from **the end of the first contiguous sequence range you hold**, not the largest observed value. Missing numbers are **normal** and will never arrive—some events consume sequence numbers but are not published here. Gaps do not mean lost events, but resuming past a gap skips everything after it.",
            "items": {
              "format": "int64",
              "type": "integer"
            },
            "type": "array"
          },
          "session_id": {
            "description": "The session this event belongs to.",
            "examples": [
              "0b9f2c14-6d3a-4f18-9c27-8ae5d1b47f30"
            ],
            "type": "string"
          },
          "sub_type": {
            "description": "Variant discriminator: the sessionUpdate value, or prompt_response on a result frame ending a turn. null when the method needs no further subdivision, such as session/request_permission. See x-event-catalogue in the events schema for all types. Open enum; tolerate unrecognized values.",
            "examples": [
              "agent_message_chunk"
            ],
            "type": [
              "string",
              "null"
            ]
          },
          "turn_id": {
            "description": "The turn this event belongs to. null for events outside a turn—session startup, idle state, and out-of-band publication genuinely belong to no turn.",
            "type": [
              "string",
              "null"
            ]
          },
          "type": {
            "description": "JSON-RPC frame type. Dispatch on (type, method, sub_type); see x-event-catalogue in the events schema.",
            "enum": [
              "method",
              "result",
              "error"
            ],
            "type": "string"
          }
        },
        "required": [
          "id",
          "session_id",
          "seq_id",
          "seq_ids",
          "type",
          "method",
          "sub_type",
          "raw",
          "turn_id",
          "created_at"
        ],
        "type": "object"
      },
      "SessionPublicStreamStatusFrame": {
        "additionalProperties": false,
        "properties": {
          "session_id": {
            "description": "Session described by this snapshot.",
            "type": "string"
          },
          "status": {
            "description": "Session state, with the same field name and value space as GET /sessions/{session_id}. Open enum; tolerate unrecognized values.",
            "examples": [
              "running"
            ],
            "type": "string"
          },
          "status_info": {
            "description": "Free text when the producer provides additional explanation. Absent otherwise; unsuitable for programmatic branching.",
            "type": "string"
          }
        },
        "required": [
          "session_id",
          "status"
        ],
        "type": "object"
      },
      "SessionPublicRemoteContentBlocked": {
        "additionalProperties": false,
        "properties": {
          "reason": {
            "type": "string"
          },
          "session_id": {
            "type": "string"
          }
        },
        "required": [
          "session_id",
          "reason"
        ],
        "type": "object"
      },
      "SessionPublicRemoteStreamDone": {
        "additionalProperties": false,
        "properties": {
          "execution_available": {
            "type": "boolean"
          },
          "reason": {
            "type": "string"
          },
          "session_id": {
            "type": "string"
          }
        },
        "required": [
          "session_id",
          "reason",
          "execution_available"
        ],
        "type": "object"
      },
      "SessionPublicRemoteStreamError": {
        "additionalProperties": false,
        "properties": {
          "code": {
            "type": "string"
          },
          "detail": {
            "$ref": "#/components/schemas/SessionPublicRemoteStreamErrorDetail"
          },
          "message": {
            "type": "string"
          },
          "trace_id": {
            "type": "string"
          }
        },
        "required": [
          "code",
          "message",
          "trace_id",
          "detail"
        ],
        "type": "object"
      },
      "SessionPublicRemoteStreamErrorDetail": {
        "additionalProperties": false,
        "properties": {
          "reason": {
            "type": "string"
          }
        },
        "required": [
          "reason"
        ],
        "type": "object"
      },
      "SessionPublicRemoteEvent": {
        "additionalProperties": false,
        "properties": {
          "created_at": {
            "type": "string"
          },
          "id": {
            "type": "string"
          },
          "method": {
            "type": [
              "string",
              "null"
            ]
          },
          "raw": {
            "type": "object",
            "additionalProperties": {},
            "description": "JSON-RPC after the existing safe outbound projection, not executor logs."
          },
          "seq_id": {
            "description": "The first covered sequence number in the current event stream. Use the opaque cursor to resume.",
            "format": "int64",
            "type": "integer"
          },
          "seq_ids": {
            "description": "Set of covered sequence numbers. Deduplicate single-sequence text fragments by sequence number before appending; multi-sequence aggregated text replaces existing fragments with the same id.",
            "items": {
              "format": "int64",
              "type": "integer"
            },
            "type": "array"
          },
          "session_id": {
            "type": "string"
          },
          "sub_type": {
            "type": [
              "string",
              "null"
            ]
          },
          "turn_id": {
            "type": [
              "string",
              "null"
            ]
          },
          "type": {
            "type": "string"
          }
        },
        "required": [
          "id",
          "session_id",
          "seq_id",
          "seq_ids",
          "type",
          "method",
          "sub_type",
          "raw",
          "turn_id",
          "created_at"
        ],
        "type": "object"
      },
      "SessionPublicRemoteStreamStatus": {
        "additionalProperties": false,
        "properties": {
          "session_id": {
            "type": "string"
          },
          "status": {
            "type": "string"
          }
        },
        "required": [
          "session_id",
          "status"
        ],
        "type": "object"
      }
    },
    "securitySchemes": {
      "OpenPlatformBearer": {
        "description": "Authorization: Bearer <access_token>; JSON Content-Type: application/json; charset=utf-8. The current CN Review temporarily allows access only for routing debugging.",
        "scheme": "bearer",
        "type": "http"
      }
    }
  },
  "openapi": "3.1.0",
  "paths": {
    "/v1/session/sessions/{session_id}/events/stream": {
      "get": {
        "description": "Omitting session_type selects a cloud session. Every remote-control request must use session_type=remote and provide a nonempty device_id. Providing device_id for a cloud session, an empty or unknown type, or duplicate target parameters returns 422 VALIDATION_ERROR. Cross-device aggregated lists and automatic fallback to cloud are not provided. Both types use the same authentication chain; the open platform validates the corresponding Scope declared by each endpoint.\n\nCloud sessions:\nServer-Sent Events over a persistent connection. Event content is identical to `GET /sessions/{session_id}/events` and shares the same `seq_id` space; events are pushed as they occur rather than waiting for polling.\n\n**What this adds beyond polling.** Agent text arrives at the granularity at which it is produced—a response is delivered as sequential fragments as they are written, not one finished block. Polling cannot see this layer: events have already been aggregated by the time they are stored.\n\n**Reading a fragmented message.** Aggregate by `id`, not `seq_id`. Every fragment of a message has the same `id`; its `seq_ids` lists the covered sequence numbers. A frame whose `seq_ids` covers multiple values is the aggregated form and **replaces** content accumulated for that `id`; a single-value frame **appends**. This also makes reconnecting mid-message safe—the whole message returns rather than half of it being duplicated.\n\n**Cursor.** Your resume position is **the end of the first contiguous sequence range you hold**, not the largest value you have seen. Within an envelope, advance to the maximum `seq_ids` value, not `seq_id`: `seq_id` is the **first** sequence number covered, so an aggregated message reports a smaller number than its actual delivery position. Resuming from it redelivers the message tail.\n\n**Missing sequence numbers are normal, not lost events.** Some events exist but are not published by this endpoint, while still consuming sequence numbers—so numbers **may skip**. Do not treat gaps as missing events or wait for them. What matters is that nothing remains unresolved before your resume position.\n\n**Resuming.** `id:` is written only at message boundaries, so reconnecting never lands in the middle of a message. If a gap truly cannot be recovered, an `error` frame with code `resync_required` tells you which endpoint to use to fill it and where to resume. This is expected after a long disconnection, not a fault.\n\n**Ending.** The stream always ends with a `done` or `error` frame, never simply by closing the connection, so clients need not guess whether everything was received. `done` means orderly closure; `session_terminated` means the session itself has ended and reconnecting will never yield more data. Any other reason only closes the connection: reconnect with the last received id to continue. `error` carries a `code` and `resume_from`; every error code permits resuming from that position.\n\n**Authentication** uses the same bearer token as other endpoints, sent through `Authorization: Bearer <token>`.\n\n**The public OpenAPI gateway reads Bearer Tokens only from the `Authorization` header.** It does not authenticate using query tokens or login cookies. If native `EventSource` cannot set this header, use a streaming client that supports custom headers.\n\nTokens in URLs are recorded in access logs, proxy logs, and `Referer`, and URLs are **far more likely** than headers to be pasted into bug reports. Wherever headers are supported, the header form remains the safer default.\n\n**Two failure surfaces.** Before the response starts, failures use normal HTTP status codes. Once the stream opens, its status is already `200`; subsequent failures can only appear as an `error` frame or a disconnected connection. Clients must handle both.\n\n**Content safety.** `content_blocked` retracts text **already delivered** by this stream; discard all content received for that `turn_id`. Retractions cannot be replayed, so those occurring while disconnected will not be delivered. You must still moderate agent-generated text yourself before forwarding it externally.\n\nRemote-control sessions:\nShares public gateway authentication with cloud sessions; this endpoint requires the business Scope stated below. No controller device ID or pairing is required. The target remote-control master switch must be enabled. If explicitly disabled, returns 403 FORBIDDEN with detail.reason=ACP_HOST_DISABLED; rejected write requests return detail.acceptance=not_accepted. An explicitly nonexistent session returns 404 NOT_FOUND with detail.reason=SESSION_NOT_FOUND. Commands route only to target connections signed in to the currently authenticated account. Offline targets, unknown targets, and targets belonging to other accounts all return device unavailable. Unknown request body fields are rejected. Use cursor or Last-Event-ID to subscribe to events in the same resource scope; conflicting values are rejected. Omitting the cursor starts at the beginning of available history; a missing history prefix returns an error. Establish the subscription first, then obtain the activation snapshot; after replay, send buffered and live events. Heartbeats keep the connection alive. Slow consumers, history gaps, or event stream changes end the stream. Offline replay is limited to a known contiguous cache window and does not represent the latest execution state. done closes the observation channel without stopping the executing turn. Like cloud SSE, authentication occurs only on connection or reconnection. Established connections have no fixed 30-minute duration or token-expiry timer; immediate disconnection on credential expiry or revocation is not guaranteed. Reconnection requires valid credentials and the same session target. Errors before response headers are sent use JSON; after streaming starts, an SSE error frame is sent if the connection remains writable.\nCall through the open platform, retaining the existing oauth_app Token, identity resolution, application IP restrictions, and resource ownership checks. Cloud and remote-control parameters retain their actual contract semantics.",
        "operationId": "publishedStream-events",
        "parameters": [
          {
            "description": "Session identifier: a UUID for cloud sessions; an opaque identifier on the selected device for remote-control sessions.",
            "in": "path",
            "name": "session_id",
            "required": true,
            "schema": {
              "maxLength": 256,
              "minLength": 1,
              "type": "string"
            }
          },
          {
            "description": "Resume after this seq_id.\n\n🔴 **What to pass: the end of the first contiguous sequence range you hold**, **not** the largest sequence number observed. If you hold 1,2,3,7,8, pass **3**, not 8. Numbers you never received are normal (some events are not published here but still consume sequence numbers), so **gaps are not lost events and will never be filled**—but resuming past them skips everything in between.\n\n**Within one frame**: advance to the maximum `seq_ids` value, not `seq_id`—`seq_id` is the **first** sequence number covered by the frame, so an aggregated message reports a smaller number than it actually delivered. Resuming from it redelivers the message tail.\n\n⚠️ **Omitting this is not the same as passing 0**: omission means \"start now\" without replay; 0 means \"replay from the start of the session\". `?cursor=` (a parameter name with an empty value) is equivalent to omission.\n\nEquivalent to the `Last-Event-ID` header, which takes precedence. Providing both with different values returns **422**.\nRemote-control sessions: an opaque string cursor bound to the account, device, session, and event stream.\nPass unchanged as a string in HTTP parameters: a decimal sequence number for cloud sessions, an opaque cursor for remote control. The service validates it according to session type.",
            "explode": false,
            "in": "query",
            "name": "cursor",
            "schema": {
              "maxLength": 8192,
              "type": "string"
            }
          },
          {
            "description": "Standard SSE resume header, sent automatically by the browser's native `EventSource`. Equivalent to `?cursor=` and takes precedence over it.\n\nA **position**, not a count—do not add 1. The rule is the same as for `?cursor=`: the end of the first contiguous sequence range you hold, not the largest observed value. The browser sends back the last `id:` written by this endpoint, and `id:` is **written only at message boundaries**—which is why the browser's automatic behavior is correct.\nRemote-control sessions: an opaque string cursor bound to the account, device, session, and event stream.\nPass unchanged as a string in HTTP parameters: a decimal sequence number for cloud sessions, an opaque cursor for remote control. The service validates it according to session type.",
            "in": "header",
            "name": "Last-Event-ID",
            "schema": {
              "maxLength": 8192,
              "type": "string"
            }
          },
          {
            "description": "Set to false to receive only session_event frames. This does not suppress content_blocked, which is always delivered.\nSupported only for cloud sessions; passing this parameter for remote control returns 422.",
            "explode": false,
            "in": "query",
            "name": "include_status",
            "schema": {
              "description": "Set to false to receive only session_event frames. This does not suppress content_blocked, which is always delivered.",
              "type": "boolean"
            }
          },
          {
            "description": "Omitting session_type selects a cloud session. Every remote-control request must use session_type=remote and provide a nonempty device_id. Providing device_id for a cloud session, an empty or unknown type, or duplicate target parameters returns 422 VALIDATION_ERROR. Cross-device aggregated lists and automatic fallback to cloud are not provided. Both types use the same authentication chain; The upstream does not validate OAuth session scope; the open platform validates the corresponding Scope according to the manifest.",
            "in": "query",
            "name": "session_type",
            "schema": {
              "default": "cloud",
              "enum": [
                "cloud",
                "remote"
              ],
              "type": "string"
            }
          },
          {
            "description": "Required only for remote control. An opaque target device identifier from device discovery; it must be URL-encoded. The target connection must be signed in to the currently authenticated account.",
            "in": "query",
            "name": "device_id",
            "schema": {
              "maxLength": 256,
              "minLength": 1,
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "content": {
              "text/event-stream": {
                "schema": {
                  "type": "string"
                }
              }
            },
            "description": "Success",
            "headers": {
              "X-Request-ID": {
                "description": "Request ID generated by the open platform for each HTTP request, for log correlation and troubleshooting. Retries generate new IDs; this is not an idempotency key or distributed Trace ID.",
                "schema": {
                  "pattern": "^[0-9a-f]{32}$",
                  "type": "string"
                }
              },
              "X-Trace-ID": {
                "description": "OpenTelemetry TraceID for the current open-platform request, correlated with X-Request-ID through request logs. A complete trace may be unavailable if the sample was not retained.",
                "schema": {
                  "pattern": "^[0-9a-f]{32}$",
                  "type": "string"
                }
              }
            }
          },
          "default": {
            "content": {
              "application/json": {
                "schema": {
                  "anyOf": [
                    {
                      "$ref": "#/components/schemas/SessionPublicErrorBody"
                    },
                    {
                      "$ref": "#/components/schemas/SessionRelayError"
                    }
                  ]
                }
              }
            },
            "description": "Error. Branch on `code`, not just the HTTP status code—multiple conditions can share the same status code.",
            "headers": {
              "X-Request-ID": {
                "description": "Request ID generated by the open platform for each HTTP request, for log correlation and troubleshooting. Retries generate new IDs; this is not an idempotency key or distributed Trace ID.",
                "schema": {
                  "pattern": "^[0-9a-f]{32}$",
                  "type": "string"
                }
              },
              "X-Trace-ID": {
                "description": "OpenTelemetry TraceID for the current open-platform request, correlated with X-Request-ID through request logs. A complete trace may be unavailable if the sample was not retained.",
                "schema": {
                  "pattern": "^[0-9a-f]{32}$",
                  "type": "string"
                }
              }
            }
          }
        },
        "security": [
          {
            "OpenPlatformBearer": []
          }
        ],
        "summary": "Subscribe to session events in real time",
        "tags": [
          "会话事件"
        ],
        "x-session-variants": {
          "cloud": {
            "summary": "Subscribe to session events in real time",
            "description": "Server-Sent Events over a persistent connection. Event content is identical to `GET /sessions/{session_id}/events` and shares the same `seq_id` space; events are pushed as they occur rather than waiting for polling.\n\n**What this adds beyond polling.** Agent text arrives at the granularity at which it is produced—a response is delivered as sequential fragments as they are written, not one finished block. Polling cannot see this layer: events have already been aggregated by the time they are stored.\n\n**Reading a fragmented message.** Aggregate by `id`, not `seq_id`. Every fragment of a message has the same `id`; its `seq_ids` lists the covered sequence numbers. A frame whose `seq_ids` covers multiple values is the aggregated form and **replaces** content accumulated for that `id`; a single-value frame **appends**. This also makes reconnecting mid-message safe—the whole message returns rather than half of it being duplicated.\n\n**Cursor.** Your resume position is **the end of the first contiguous sequence range you hold**, not the largest value you have seen. Within an envelope, advance to the maximum `seq_ids` value, not `seq_id`: `seq_id` is the **first** sequence number covered, so an aggregated message reports a smaller number than its actual delivery position. Resuming from it redelivers the message tail.\n\n**Missing sequence numbers are normal, not lost events.** Some events exist but are not published by this endpoint, while still consuming sequence numbers—so numbers **may skip**. Do not treat gaps as missing events or wait for them. What matters is that nothing remains unresolved before your resume position.\n\n**Resuming.** `id:` is written only at message boundaries, so reconnecting never lands in the middle of a message. If a gap truly cannot be recovered, an `error` frame with code `resync_required` tells you which endpoint to use to fill it and where to resume. This is expected after a long disconnection, not a fault.\n\n**Ending.** The stream always ends with a `done` or `error` frame, never simply by closing the connection, so clients need not guess whether everything was received. `done` means orderly closure; `session_terminated` means the session itself has ended and reconnecting will never yield more data. Any other reason only closes the connection: reconnect with the last received id to continue. `error` carries a `code` and `resume_from`; every error code permits resuming from that position.\n\n**Authentication** uses the same bearer token as other endpoints, sent through `Authorization: Bearer <token>`.\n\n**The public OpenAPI gateway reads Bearer Tokens only from the `Authorization` header.** It does not authenticate using query tokens or login cookies. If native `EventSource` cannot set this header, use a streaming client that supports custom headers.\n\nTokens in URLs are recorded in access logs, proxy logs, and `Referer`, and URLs are **far more likely** than headers to be pasted into bug reports. Wherever headers are supported, the header form remains the safer default.\n\n**Two failure surfaces.** Before the response starts, failures use normal HTTP status codes. Once the stream opens, its status is already `200`; subsequent failures can only appear as an `error` frame or a disconnected connection. Clients must handle both.\n\n**Content safety.** `content_blocked` retracts text **already delivered** by this stream; discard all content received for that `turn_id`. Retractions cannot be replayed, so those occurring while disconnected will not be delivered. You must still moderate agent-generated text yourself before forwarding it externally.",
            "parameters": [
              {
                "description": "Session ID returned by POST /sessions.",
                "in": "path",
                "name": "session_id",
                "required": true,
                "schema": {
                  "description": "Session ID returned by POST /sessions.",
                  "format": "uuid",
                  "type": "string"
                }
              },
              {
                "description": "Resume after this seq_id.\n\n🔴 **What to pass: the end of the first contiguous sequence range you hold**, **not** the largest sequence number observed. If you hold 1,2,3,7,8, pass **3**, not 8. Numbers you never received are normal (some events are not published here but still consume sequence numbers), so **gaps are not lost events and will never be filled**—but resuming past them skips everything in between.\n\n**Within one frame**: advance to the maximum `seq_ids` value, not `seq_id`—`seq_id` is the **first** sequence number covered by the frame, so an aggregated message reports a smaller number than it actually delivered. Resuming from it redelivers the message tail.\n\n⚠️ **Omitting this is not the same as passing 0**: omission means \"start now\" without replay; 0 means \"replay from the start of the session\". `?cursor=` (a parameter name with an empty value) is equivalent to omission.\n\nEquivalent to the `Last-Event-ID` header, which takes precedence. Providing both with different values returns **422**.",
                "explode": false,
                "in": "query",
                "name": "cursor",
                "schema": {
                  "description": "Resume after this seq_id.\n\n🔴 **What to pass: the end of the first contiguous sequence range you hold**, **not** the largest sequence number observed. If you hold 1,2,3,7,8, pass **3**, not 8. Numbers you never received are normal (some events are not published here but still consume sequence numbers), so **gaps are not lost events and will never be filled**—but resuming past them skips everything in between.\n\n**Within one frame**: advance to the maximum `seq_ids` value, not `seq_id`—`seq_id` is the **first** sequence number covered by the frame, so an aggregated message reports a smaller number than it actually delivered. Resuming from it redelivers the message tail.\n\n⚠️ **Omitting this is not the same as passing 0**: omission means \"start now\" without replay; 0 means \"replay from the start of the session\". `?cursor=` (a parameter name with an empty value) is equivalent to omission.\n\nEquivalent to the `Last-Event-ID` header, which takes precedence. Providing both with different values returns **422**.",
                  "format": "int64",
                  "minimum": 0,
                  "type": "integer"
                }
              },
              {
                "description": "Standard SSE resume header, sent automatically by the browser's native `EventSource`. Equivalent to `?cursor=` and takes precedence over it.\n\nA **position**, not a count—do not add 1. The rule is the same as for `?cursor=`: the end of the first contiguous sequence range you hold, not the largest observed value. The browser sends back the last `id:` written by this endpoint, and `id:` is **written only at message boundaries**—which is why the browser's automatic behavior is correct.",
                "in": "header",
                "name": "Last-Event-ID",
                "schema": {
                  "description": "Standard SSE resume header, sent automatically by the browser's native `EventSource`. Equivalent to `?cursor=` and takes precedence over it.\n\nA **position**, not a count—do not add 1. The rule is the same as for `?cursor=`: the end of the first contiguous sequence range you hold, not the largest observed value. The browser sends back the last `id:` written by this endpoint, and `id:` is **written only at message boundaries**—which is why the browser's automatic behavior is correct.",
                  "format": "int64",
                  "type": "integer"
                }
              },
              {
                "description": "Set to false to receive only session_event frames. This does not suppress content_blocked, which is always delivered.",
                "explode": false,
                "in": "query",
                "name": "include_status",
                "schema": {
                  "default": true,
                  "description": "Set to false to receive only session_event frames. This does not suppress content_blocked, which is always delivered.",
                  "type": "boolean"
                }
              }
            ],
            "requestBody": null,
            "responses": {
              "200": {
                "content": {
                  "text/event-stream": {
                    "schema": {
                      "description": "Each oneOf object in the array represents a possible Server-Sent Events (SSE) message, serialized as UTF-8 text according to the SSE specification.",
                      "items": {
                        "oneOf": [
                          {
                            "properties": {
                              "data": {
                                "$ref": "#/components/schemas/SessionPublicStreamContentBlockedFrame"
                              },
                              "event": {
                                "const": "content_blocked",
                                "description": "Event name.",
                                "type": "string"
                              },
                              "id": {
                                "description": "Event id.",
                                "type": "integer"
                              },
                              "retry": {
                                "description": "Reconnection wait time in milliseconds.",
                                "type": "integer"
                              }
                            },
                            "required": [
                              "data",
                              "event"
                            ],
                            "title": "Event content_blocked",
                            "type": "object"
                          },
                          {
                            "properties": {
                              "data": {
                                "$ref": "#/components/schemas/SessionPublicStreamDoneFrame"
                              },
                              "event": {
                                "const": "done",
                                "description": "Event name.",
                                "type": "string"
                              },
                              "id": {
                                "description": "Event id.",
                                "type": "integer"
                              },
                              "retry": {
                                "description": "Reconnection wait time in milliseconds.",
                                "type": "integer"
                              }
                            },
                            "required": [
                              "data",
                              "event"
                            ],
                            "title": "Event done",
                            "type": "object"
                          },
                          {
                            "properties": {
                              "data": {
                                "$ref": "#/components/schemas/SessionPublicStreamErrorFrame"
                              },
                              "event": {
                                "const": "error",
                                "description": "Event name.",
                                "type": "string"
                              },
                              "id": {
                                "description": "Event id.",
                                "type": "integer"
                              },
                              "retry": {
                                "description": "Reconnection wait time in milliseconds.",
                                "type": "integer"
                              }
                            },
                            "required": [
                              "data",
                              "event"
                            ],
                            "title": "Event error",
                            "type": "object"
                          },
                          {
                            "properties": {
                              "data": {
                                "$ref": "#/components/schemas/SessionPublicEvent"
                              },
                              "event": {
                                "const": "session_event",
                                "description": "Event name.",
                                "type": "string"
                              },
                              "id": {
                                "description": "Event id.",
                                "type": "integer"
                              },
                              "retry": {
                                "description": "Reconnection wait time in milliseconds.",
                                "type": "integer"
                              }
                            },
                            "required": [
                              "data",
                              "event"
                            ],
                            "title": "Event session_event",
                            "type": "object"
                          },
                          {
                            "properties": {
                              "data": {
                                "$ref": "#/components/schemas/SessionPublicStreamStatusFrame"
                              },
                              "event": {
                                "const": "session_status",
                                "description": "Event name.",
                                "type": "string"
                              },
                              "id": {
                                "description": "Event id.",
                                "type": "integer"
                              },
                              "retry": {
                                "description": "Reconnection wait time in milliseconds.",
                                "type": "integer"
                              }
                            },
                            "required": [
                              "data",
                              "event"
                            ],
                            "title": "Event session_status",
                            "type": "object"
                          }
                        ]
                      },
                      "title": "Server Sent Events",
                      "type": "array"
                    }
                  }
                },
                "description": "Success"
              }
            }
          },
          "remote": {
            "summary": "Subscribe to remote-control session events in real time",
            "description": "Shares public gateway authentication with cloud sessions; this endpoint requires the business Scope stated below. No controller device ID or pairing is required. The target remote-control master switch must be enabled. If explicitly disabled, returns 403 FORBIDDEN with detail.reason=ACP_HOST_DISABLED; rejected write requests return detail.acceptance=not_accepted. An explicitly nonexistent session returns 404 NOT_FOUND with detail.reason=SESSION_NOT_FOUND. Commands route only to target connections signed in to the currently authenticated account. Offline targets, unknown targets, and targets belonging to other accounts all return device unavailable. Unknown request body fields are rejected. Use cursor or Last-Event-ID to subscribe to events in the same resource scope; conflicting values are rejected. Omitting the cursor starts at the beginning of available history; a missing history prefix returns an error. Establish the subscription first, then obtain the activation snapshot; after replay, send buffered and live events. Heartbeats keep the connection alive. Slow consumers, history gaps, or event stream changes end the stream. Offline replay is limited to a known contiguous cache window and does not represent the latest execution state. done closes the observation channel without stopping the executing turn. Like cloud SSE, authentication occurs only on connection or reconnection. Established connections have no fixed 30-minute duration or token-expiry timer; immediate disconnection on credential expiry or revocation is not guaranteed. Reconnection requires valid credentials and the same session target. Errors before response headers are sent use JSON; after streaming starts, an SSE error frame is sent if the connection remains writable.",
            "parameters": [
              {
                "description": "Opaque target device identifier, possibly including suffixes such as :dev. The target connection must belong to the currently authenticated account.",
                "explode": false,
                "in": "query",
                "name": "device_id",
                "required": true,
                "schema": {
                  "description": "Opaque target device identifier, possibly including suffixes such as :dev. The target connection must belong to the currently authenticated account.",
                  "maxLength": 256,
                  "type": "string"
                }
              },
              {
                "description": "Session identifier on the target device.",
                "in": "path",
                "name": "session_id",
                "required": true,
                "schema": {
                  "description": "Session identifier on the target device.",
                  "maxLength": 256,
                  "type": "string"
                }
              },
              {
                "explode": false,
                "in": "query",
                "name": "cursor",
                "schema": {
                  "maxLength": 8192,
                  "type": "string"
                }
              },
              {
                "in": "header",
                "name": "Last-Event-ID",
                "schema": {
                  "maxLength": 8192,
                  "type": "string"
                }
              }
            ],
            "requestBody": null,
            "responses": {
              "200": {
                "content": {
                  "text/event-stream": {
                    "schema": {
                      "description": "Each oneOf object in the array represents a possible Server-Sent Events (SSE) message, serialized as UTF-8 text according to the SSE specification.",
                      "items": {
                        "oneOf": [
                          {
                            "properties": {
                              "data": {
                                "$ref": "#/components/schemas/SessionPublicRemoteContentBlocked"
                              },
                              "event": {
                                "const": "content_blocked",
                                "description": "Event name.",
                                "type": "string"
                              },
                              "id": {
                                "description": "Event id.",
                                "type": "integer"
                              },
                              "retry": {
                                "description": "Reconnection wait time in milliseconds.",
                                "type": "integer"
                              }
                            },
                            "required": [
                              "data",
                              "event"
                            ],
                            "title": "Event content_blocked",
                            "type": "object"
                          },
                          {
                            "properties": {
                              "data": {
                                "$ref": "#/components/schemas/SessionPublicRemoteStreamDone"
                              },
                              "event": {
                                "const": "done",
                                "description": "Event name.",
                                "type": "string"
                              },
                              "id": {
                                "description": "Event id.",
                                "type": "integer"
                              },
                              "retry": {
                                "description": "Reconnection wait time in milliseconds.",
                                "type": "integer"
                              }
                            },
                            "required": [
                              "data",
                              "event"
                            ],
                            "title": "Event done",
                            "type": "object"
                          },
                          {
                            "properties": {
                              "data": {
                                "$ref": "#/components/schemas/SessionPublicRemoteStreamError"
                              },
                              "event": {
                                "const": "error",
                                "description": "Event name.",
                                "type": "string"
                              },
                              "id": {
                                "description": "Event id.",
                                "type": "integer"
                              },
                              "retry": {
                                "description": "Reconnection wait time in milliseconds.",
                                "type": "integer"
                              }
                            },
                            "required": [
                              "data",
                              "event"
                            ],
                            "title": "Event error",
                            "type": "object"
                          },
                          {
                            "properties": {
                              "data": {
                                "$ref": "#/components/schemas/SessionPublicRemoteEvent"
                              },
                              "event": {
                                "const": "session_event",
                                "description": "Event name.",
                                "type": "string"
                              },
                              "id": {
                                "description": "Event id.",
                                "type": "integer"
                              },
                              "retry": {
                                "description": "Reconnection wait time in milliseconds.",
                                "type": "integer"
                              }
                            },
                            "required": [
                              "data",
                              "event"
                            ],
                            "title": "Event session_event",
                            "type": "object"
                          },
                          {
                            "properties": {
                              "data": {
                                "$ref": "#/components/schemas/SessionPublicRemoteStreamStatus"
                              },
                              "event": {
                                "const": "session_status",
                                "description": "Event name.",
                                "type": "string"
                              },
                              "id": {
                                "description": "Event id.",
                                "type": "integer"
                              },
                              "retry": {
                                "description": "Reconnection wait time in milliseconds.",
                                "type": "integer"
                              }
                            },
                            "required": [
                              "data",
                              "event"
                            ],
                            "title": "Event session_status",
                            "type": "object"
                          }
                        ]
                      },
                      "title": "Server Sent Events",
                      "type": "array"
                    }
                  }
                },
                "description": "Success"
              }
            }
          }
        },
        "x-supported-session-types": [
          "cloud",
          "remote"
        ]
      }
    }
  },
  "info": {
    "title": "Subscribe to session events in real time",
    "version": "2026-11-24"
  },
  "servers": [
    {
      "url": "https://openapi.qwenwork.ai"
    }
  ]
}
Back to the OpenAPI overview.