# 连接任务浏览器流

```{raw} html
<div class="mo-api-page-show-toc" aria-hidden="true"></div>
```

通过WebSocket接收画面和事件，并按协议发送有界输入。它是浏览器交接协议，成功升级不是JSON查询结果。

```text
GET https://api.moi.matrixorigin.cn/v5/workspaces/{workspace_id}/agent-runtime-tasks/{task_id}/browser/stream
```

## 调用前准备

先取得同一工作区/任务的未过期短期令牌。浏览器Origin须是同主机或部署明确允许的Origin；当前身份与角色会在接入及连接期间重新检查。

## 请求参数

:::::::{div} mo-api-tabs
::::::{tab-set}
:::::{tab-item} 输入示例

```javascript
const target = new URL(apiBaseUrl);
target.pathname = target.pathname.replace(/\/$/, '') + `/workspaces/${encodeURIComponent(workspaceId)}/agent-runtime-tasks/${encodeURIComponent(taskId)}/browser/stream`;
target.protocol = target.protocol === 'https:' ? 'wss:' : 'ws:';
target.search = '';
target.hash = '';
const socket = new WebSocket(target.toString(), ['moi-browser.v1', token]);
```

其余变量来自原任务及前一步令牌。此片段只展示握手；处理事件、画面和确认须继续按共享协议实现。

:::::
:::::{tab-item} 参数说明

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `workspace_id` | string | 本人任务所属工作区。 |
| `task_id` | string | 原运行任务ID。 |
| `Origin` | HTTP header | 浏览器自动发送；缺少或不允许时拒绝。 |
| `Sec-WebSocket-Protocol` | string列表 | 同时提供moi-browser.v1和一个moi-browser-token-v1.开头的证明。 |

:::::
::::::
:::::::

## 流式响应

:::::::{div} mo-api-tabs mo-api-response-tabs
::::::{tab-set}
:::::{tab-item} 响应示例

```text
HTTP/1.1 101 Switching Protocols
Sec-WebSocket-Protocol: moi-browser.v1

文本消息：{"type":"frame","seq":1,"metadata":{"deviceWidth":1280,"deviceHeight":720}}
下一条消息：原始图像二进制字节
```

:::::
:::::{tab-item} 字段说明

| 字段或响应项 | 类型 | 说明 |
| --- | --- | --- |
| `type` | string | 已知事件包括frame、url、status、released。 |
| `seq` | integer | 服务端帧序号，用于ack。 |
| `metadata` | JSON对象 | 帧元信息；示例包含尺寸，不宣称所有提供方字段已穷举。 |
| 图像消息 | binary | 紧跟frame文本事件，不能当JSON内Base64读取。 |
| 连接复查 | 协议行为 | 当前实现周期重建访问上下文并复查；失败可发1008关闭。 |

:::::
::::::
:::::::

## 错误响应

| HTTP / code | 条件 |
| --- | --- |
| 400 / 2 | 浏览器参数无效。 |
| 401 / 6 | 身份证明无效，或流证明不匹配路径。 |
| 403 / 5 | 当前授权拒绝，或流的Origin/子协议不符合要求。 |
| 404 / 3 | 任务不可访问、非本人任务或缺少所需上下文。 |
| 409 / 15 | 现有浏览器未运行，details.reason=BROWSER_NOT_RUNNING。 |
| 410 / 3 | 原环境已结束或过期，details.reason=BROWSER_SESSION_ENDED。 |
| 503 / 15 | 浏览器运行依赖不可用，或任务状态不能使用。 |
| 500 / 1 | 其他内部失败。 |

101升级后不再返回普通HTTP JSON错误；周期复查失败可关闭连接，恢复见[环境与错误](errors-environments.md)。

产品认证阶段还可能使用字符串code/msg，不能将上表数字错误当作全部认证封套。
