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

# Streaming World 控制

> 通过控制 WebSocket 引导故事、更新状态、添加参考素材并停止会话。

创建会话后，应用通过控制 WebSocket 改变接下来发生的内容。视频仍通过 HLS 播放 URL 传输，WebSocket 则用于传递指令和响应。

## 交互概览

你可以通过四种方式与正在运行的故事交互：

| 控制事件 | 适用场景 | 响应 |
| - | - | - |
| `instruction.create` | 需要决定接下来发生什么。 | 指令依次进入已接收、已调度、已开始以及已完成或失败状态。 |
| `state.update` / `state.get` | 产品需要更改或读取生命值、分数、位置、物品栏或其他结构化数值。 | 通过 `state.updated` 或 `state.snapshot` 返回完整状态。 |
| `assets.add` | 新角色、对象、地点、图像或声音需要参与故事。 | `assets.added` 确认后续指令可以使用该参考素材。 |
| `session.stop` | 用户离开，或故事应该进入结局。 | 先发送 `session.ending`，再发送 `session.ended`。 |

常见交互流程如下：

```mermaid theme={null}
flowchart LR
  A[建立连接] --> B[1. 发送指令]
  B --> C[2. 更新或读取状态]
  C --> D[3. 按需添加参考素材]
  D --> B
  B --> E[4. 停止会话]
  E --> F[会话结束]
```

客户端不必使用所有控制事件。大多数体验可以先使用 `instruction.create`；当产品需要展示数值或执行规则时再加入状态；只有出现新角色或对象时才添加参考素材。

## 建立一次连接并开始播放

先创建会话，再使用返回的控制 URL 和会话专属密钥建立连接：

```javascript theme={null}
const ws = new WebSocket(session.control.url, [
  "streaming-world.v1",
  session.control.client_secret
]);

let lastEventId = 0;

ws.onmessage = ({ data }) => {
  const event = JSON.parse(data);
  if (Number.isInteger(event.id)) lastEventId = event.id;

  if (event.type === "session.ready") {
    player.load(event.playback.url);
    player.play();
  }
};
```

`session.ready` 表示开场媒体已经可以播放。其中的 `playback.url` 是 HLS 地址，请将它交给支持 HLS 的播放器，不要自行拼接 URL。

第二个 WebSocket 子协议值是会话密钥。不要通过此通道发送通用 API 密钥。

## 发送下一条指令

`instruction.create` 是主要交互事件。用户选择动作、提出需要纳入故事的问题，或希望改变下一场景的发展方向时，请使用该事件。

### 请求

使用一段连贯的文字描述接下来应该发生的内容，并包含重要动作、角色、基调和视觉结果。无需将其拆分成镜头或对话轮次。

```json theme={null}
{
  "type": "instruction.create",
  "client_request_id": "choice_001",
  "text": "The detective opens the hidden drawer, finds a torn photograph, and asks the witness who is missing from it. Keep the camera close to the photograph before returning to their faces.",
  "duration_seconds": 10
}
```

| 字段 | 填写内容 |
| - | - |
| `type` | `instruction.create`。 |
| `client_request_id` | 由应用生成的关联 ID。请保留它，以便与响应事件对应。 |
| `text` | 使用自然语言描述的后续故事动作。 |
| `duration_seconds` | 请求的视频时长。省略时使用服务默认值。 |
| `state_ops` | 属于此指令的可选状态变更；请参阅[状态管理](#streaming-world-control-application-state)。 |

### 响应事件

正常生命周期如下：

```json theme={null}
{
  "id": 10,
  "type": "instruction.received",
  "time": "2026-10-28T08:00:30.000Z",
  "instruction_id": "ins_001",
  "client_request_id": "choice_001",
  "text": "The detective opens the hidden drawer, finds a torn photograph, and asks the witness who is missing from it. Keep the camera close to the photograph before returning to their faces.",
  "duration_seconds": 10,
  "estimated_start_seconds": 18.0
}
```

```json theme={null}
{
  "id": 11,
  "type": "instruction.scheduled",
  "time": "2026-10-28T08:00:31.000Z",
  "instruction_id": "ins_001",
  "start_seconds": 18.0,
  "end_seconds": 28.0
}
```

```json theme={null}
{
  "id": 18,
  "type": "instruction.started",
  "time": "2026-10-28T08:00:50.000Z",
  "instruction_id": "ins_001",
  "start_seconds": 18.0
}
```

```json theme={null}
{
  "id": 26,
  "type": "instruction.completed",
  "time": "2026-10-28T08:01:00.000Z",
  "instruction_id": "ins_001",
  "start_seconds": 18.0,
  "end_seconds": 28.0
}
```

将 `instruction.scheduled` 视为当前时间线估算。后续的 scheduled 事件可能会修正其位置。`instruction.started` 和 `instruction.completed` 表示播放时间线上的里程碑，但不能保证每位观众都在同一现实时间渲染了同一帧。

如果指令无法完成准备，或会话正在结束，服务端可能发送：

```json theme={null}
{
  "id": 29,
  "type": "instruction.failed",
  "time": "2026-10-28T08:01:04.000Z",
  "instruction_id": "ins_002",
  "reason": "preparation_failed"
}
```

会话进入结束流程后收到的指令也可能返回 `instruction.cancelled`。真正的新指令应使用新的 `client_request_id`。不要仅仅因为确认事件延迟，就用新 ID 重发相同文本。

## 管理世界状态

状态用于保存产品需要展示或强制执行的结构化值，例如生命值、分数、位置、物品栏、线索数量、天气或任务进度。状态与自然语言指令相互独立，但指令可以携带需要与该场景同时发生的状态变更。

例如，一场战斗可以从以下状态开始：

```json theme={null}
{
  "characters": {
    "detective": {"hp": 100, "location": "warehouse"},
    "attacker": {"hp": 100, "location": "warehouse"}
  },
  "round": 1,
  "clue_count": 0
}
```

### 立即更改数值

当应用已经决定某个值需要立即改变时，使用 `state.update`：

```json theme={null}
{
  "type": "state.update",
  "client_request_id": "state_001",
  "ops": [
    {
      "op": "set",
      "path": ["round"],
      "value": 2,
      "when": {"type": "immediate"}
    },
    {
      "op": "set",
      "path": ["characters", "detective", "hp"],
      "value": 85,
      "when": {"type": "immediate"}
    }
  ]
}
```

响应为包含完整状态的 `state.updated` 事件，而不只是两个发生变化的字段：

```json theme={null}
{
  "id": 32,
  "type": "state.updated",
  "time": "2026-10-28T08:01:10.000Z",
  "state": {
    "characters": {
      "detective": {"hp": 85, "location": "warehouse"},
      "attacker": {"hp": 100, "location": "warehouse"}
    },
    "round": 2,
    "clue_count": 0
  },
  "changes": [
    {"op":"set","path":["round"],"value":2,"client_request_id":"state_001"},
    {"op":"set","path":["characters","detective","hp"],"value":85,"client_request_id":"state_001"}
  ],
  "media_seconds": 18.0
}
```

### 将数值与场景关联

如果某个值应随指令一起生效，请在 `instruction.create` 中使用 `state_ops`：

```json theme={null}
{
  "type": "instruction.create",
  "client_request_id": "fight_002",
  "text": "The detective lands a clean hit and the attacker falls against the wall.",
  "duration_seconds": 8,
  "state_ops": [
    {
      "op": "set",
      "path": ["characters", "attacker", "hp"],
      "value": 40,
      "when": {"type": "instruction_end"}
    }
  ]
}
```

该指令播放结束时应用状态变更。需要在场景开始时生效的事实使用 `instruction_start`；需要在场景结束时生效的变更使用 `instruction_end`。

对于已经接受的指令，`state.update` 也可以显式指定它：

```json theme={null}
{
  "type": "state.update",
  "client_request_id": "state_002",
  "ops": [
    {
      "op": "set",
      "path": ["characters", "detective", "location"],
      "value": "warehouse",
      "when": {
        "type": "instruction_start",
        "instruction_id": "ins_001"
      }
    }
  ]
}
```

支持的操作包括 `set`、`delete`、`append` 和 `remove`。服务会整体接受或拒绝一批操作，不会只应用无效批次中的一部分。

### 读取当前状态

当界面需要最新状态快照时，使用 `state.get`：

```json theme={null}
{"type":"state.get","client_request_id":"state_read_001"}
```

响应只发送给发起请求的连接：

```json theme={null}
{
  "type": "state.snapshot",
  "time": "2026-10-28T08:01:22.000Z",
  "client_request_id": "state_read_001",
  "state": {
    "characters": {
      "detective": {"hp": 85, "location": "warehouse"},
      "attacker": {"hp": 100, "location": "warehouse"}
    },
    "round": 2,
    "clue_count": 0
  },
  "media_seconds": 18.0,
  "last_event_id": 32
}
```

使用 `state.updated` 或 `state.snapshot` 中完整的 `state` 对象替换本地状态。不要推断另一套隐藏的状态结构。

## 在故事需要时添加参考素材

当新角色、对象、地点或声音需要参与故事时，请添加参考素材。先通过公开上传 API 注册文件，再通过控制通道发送其 `file_id`。

```bash theme={null}
curl -X POST https://api.vivix.ai/v1/files/images \\
  -H "Authorization: Bearer $VIVIX_API_KEY" \\
  -F "file=@attacker.jpg"
```

然后将其添加到会话：

```json theme={null}
{
  "type": "assets.add",
  "client_request_id": "asset_001",
  "assets": [
    {
      "name": "attacker",
      "type": "image",
      "file_id": "file_img_attacker",
      "description": "Tall attacker wearing a dark jacket"
    }
  ]
}
```

### 响应事件

成功：

```json theme={null}
{
  "id": 34,
  "type": "assets.added",
  "time": "2026-10-28T08:01:30.000Z",
  "client_request_id": "asset_001",
  "assets": [
    {"asset_id":"asset_attacker","name":"attacker","type":"image"}
  ]
}
```

失败：

```json theme={null}
{
  "id": 35,
  "type": "assets.failed",
  "time": "2026-10-28T08:01:31.000Z",
  "client_request_id": "asset_002",
  "error": {
    "code": "asset_preparation_failed",
    "message": "could not prepare the requested assets"
  }
}
```

发送依赖新参考素材的指令前，请等待 `assets.added`：

```json theme={null}
{
  "type": "instruction.create",
  "client_request_id": "fight_003",
  "text": "The attacker enters from the left and challenges the detective. Use the reference named attacker for the attacker's appearance.",
  "duration_seconds": 8
}
```

添加参考素材不会强制它出现在当前画面中，只会让后续故事指令可以使用该素材。一个会话可以包含多于单个生成片段所需数量的参考素材；服务会为每个片段选择相关的参考素材。

## 停止会话

用户离开或应用必须立即结束体验时，立即停止会话：

```json theme={null}
{"type":"session.stop","immediate":true}
```

用户希望看到结局时，请求生成收尾场景：

```json theme={null}
{
  "type": "session.stop",
  "closing": {
    "text": "The detective secures the evidence, looks toward the rain-covered window, and leaves the warehouse.",
    "duration_seconds": 8
  }
}
```

准备收尾场景时，服务端发送 `session.ending`；会话进入终止状态后发送 `session.ended`。收到 `session.ending` 后，请停止发送新的故事指令。

## 重连与事件顺序

每个历史服务端事件都包含单调递增的 `id`。处理每个事件后，保存最新 ID。连接断开时，使用以下 URL 重新连接：

```text theme={null}
wss://sw.vivix.ai/v1/streaming-world/sessions/sw_example/control?last_event_id=42
```

服务端会发送该游标之后的事件，再恢复实时事件传输。`state.snapshot.last_event_id` 是读取状态时一并返回的游标。

请按 `id` 处理事件。后续的 `instruction.scheduled` 可能会修正之前的时间线估算。如果会话已经结束，请使用 `GET /v1/streaming-world/sessions/{session_id}` 获取最终状态和时间线。

## 处理控制错误

根据公开的 `error.code` 决定客户端的处理方式：

| 错误码 | 客户端操作 |
| - | - |
| `invalid_request` | 修正消息或值，使用新的请求 ID 重试。 |
| `unauthorized` | 刷新会话凭证。 |
| `session_ending` / `session_ended` | 停止发送新指令并显示最终状态。 |
| `capacity_unavailable` | 稍后使用退避策略重试。 |
| `asset_preparation_failed` | 检查已上传文件并重新注册。 |
| `upstream_failed` / `internal_error` | 显示通用重试消息，并保留会话 ID 以便支持团队排查。 |

完整请求字段请参阅[客户端消息](https://docs.vivix.ai/cn/streaming-world/api-references/client-events.md)，所有响应结构请参阅[服务端事件](https://docs.vivix.ai/cn/streaming-world/api-references/server-events.md)。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.