diff --git a/apps/site/docs/en/index.mdx b/apps/site/docs/en/index.mdx
index 229923e1b3..06748fe6e4 100644
--- a/apps/site/docs/en/index.mdx
+++ b/apps/site/docs/en/index.mdx
@@ -57,6 +57,8 @@ Visual localization does not depend on the UI rendering stack, so the same API w
+Beyond built-in platforms, you can use [`@midscene/connect`](./midscene-connect) to connect any UI over HTTP—including car screens, embedded panels, and physical devices driven by robotic arms or HID modules. See [midscene-test-everything](https://github.com/web-infra-dev/midscene-test-everything) for real-world hardware integrations.
+
### Model options and cost {#model-options}
diff --git a/apps/site/docs/en/integrate-with-any-interface.mdx b/apps/site/docs/en/integrate-with-any-interface.mdx
index 36a4088a16..603da01b45 100644
--- a/apps/site/docs/en/integrate-with-any-interface.mdx
+++ b/apps/site/docs/en/integrate-with-any-interface.mdx
@@ -2,6 +2,12 @@ import SetupEnv from './common/setup-env.mdx';
# Integrate with any interface
+:::info Prefer Midscene Connect for connecting custom devices
+For new device integrations, use [Midscene Connect](./midscene-connect) (`@midscene/connect`). You can describe a device in one `.mjs` file, serve it over HTTP, and drive it from the Agent SDK, CLI, or Playground without implementing `AbstractInterface`.
+
+Implementing `AbstractInterface` directly is no longer the recommended path for connecting custom devices. This page remains available for maintaining existing `AbstractInterface` implementations and referencing low-level APIs such as `defineAction`.
+:::
+
You can use Midscene Agent to control any interface—such as IoT devices, in-house apps, and in-vehicle displays—by implementing a UI operation class that conforms to `AbstractInterface`.
After implementing the UI operation class, you get the full capabilities of Midscene Agent:
diff --git a/apps/site/docs/en/midscene-connect.mdx b/apps/site/docs/en/midscene-connect.mdx
new file mode 100644
index 0000000000..52bf64c980
--- /dev/null
+++ b/apps/site/docs/en/midscene-connect.mdx
@@ -0,0 +1,179 @@
+import SetupEnv from './common/setup-env.mdx';
+
+# Connect any UI
+
+Use [`@midscene/connect`](https://github.com/web-infra-dev/midscene/tree/main/packages/connect) to connect any screen or custom hardware to Midscene—such as robotic arms, capture cards with HID modules, in-vehicle displays, IoT devices, or remote machines.
+
+Describe the device in one `.mjs` file, serve it over HTTP, and drive it with the Agent SDK, the CLI, or the Playground without writing an `AbstractInterface` class.
+
+## Real-world examples
+
+See the [midscene-test-everything](https://github.com/web-infra-dev/midscene-test-everything) repository for real-world hardware and platform integrations built on `@midscene/connect`:
+
+- **Robot arm × physical touchscreen** (`mg400-service`, `arm-kit`, `robotics-vision`): camera capture, ArUco screen calibration, coordinate mapping, and a DOBOT MG400 reference setup for car screens and industrial panels.
+- **Bluetooth HID × physical iPhone** (`ios-airlink`): driving physical iPhones from macOS over Bluetooth HID with USB, AirPlay, or camera screen capture, without jailbreaking or enabling Developer Mode.
+
+## Set up API keys for model
+
+
+
+## 1. Define a device
+
+One `.mjs` file describes one kind of device, and `options` selects a concrete instance. Keys in `actions` that match a built-in input primitive are plain functions; any other key is a custom action.
+
+```js
+// car-screen.mjs
+export default {
+ name: 'Car Screen',
+ description: 'In-car touchscreen driven by a robot arm', // added to aiAct context
+ pointerType: 'touch', // required with `swipe`: 'touch' | 'mouse'
+ options: {
+ type: 'object',
+ properties: { armId: { type: 'string' } },
+ required: ['armId'],
+ },
+ async connect({ armId }) {
+ const arm = await openArm(armId);
+ return {
+ screenshot: () => camera.jpeg(), // PNG/JPEG Buffer, data URL, or base64
+ actions: {
+ tap: (p) => arm.tap(p.x, p.y),
+ swipe: (from, to, opts) => arm.swipe(from, to, opts?.duration),
+ homeButton: () => arm.pressHome(),
+ wakeVoiceAssistant: {
+ description: 'Wake up the voice assistant with a phrase',
+ params: {
+ type: 'object',
+ properties: {
+ phrase: { type: 'string' },
+ button: { 'x-midscene-locate': true, description: 'The mic button' },
+ },
+ required: ['phrase'],
+ },
+ call: ({ phrase, button }) => arm.tapAndSay(button.center, phrase),
+ },
+ },
+ destroy: () => arm.close(),
+ };
+ },
+};
+```
+
+`import { defineDevice } from '@midscene/connect'` adds editor type hints, but a plain default export works without it.
+
+`size()` is optional in the object returned by `connect()`. When omitted, screen dimensions are read from the current screenshot.
+
+### Built-in primitives
+
+The function signatures match `@midscene/core`'s `InputPrimitives`. Coordinates are in screenshot pixels.
+
+| Group | Primitives | Rule |
+| --- | --- | --- |
+| Pointer | `tap`, `doubleClick`, `rightClick`, `middleClick`, `hover`, `longPress`, `dragAndDrop` | Every other pointer primitive requires `tap` |
+| Swipe | `swipe`, `pinch` | `swipe` requires `pointerType` (a `mouse` swipe also requires `tap`); `pinch` requires `swipe` with `pointerType: 'touch'` |
+| Keyboard | `typeText`, `keyboardPress`, `clearInput`, `cursorMove` | `typeText`, `keyboardPress`, and `clearInput` must be provided together |
+| Scroll | `scroll` | |
+| System | `backButton`, `homeButton`, `recentAppsButton` | |
+
+### Parameter schemas
+
+Custom action `params` and device `options` use a JSON Schema subset:
+
+- `string` (`enum`, `minLength`, `maxLength`)
+- `number` / `integer` (`minimum`, `maximum`)
+- `boolean`
+- `array` (`items`, `minItems`, `maxItems`)
+- `object` (`properties`, `required`)
+- `description`
+
+A top-level property marked `{ "x-midscene-locate": true }` is an element located by the AI model. Your `call` function receives `{ description, center, rect }`.
+
+`serve` rejects any keyword outside this subset at startup. Request bodies are validated strictly, so unknown keys fail.
+
+## 2. Serve the device
+
+Start the device service first. It keeps the device connected and exposes an HTTP API with Swagger UI at `/api/docs/`:
+
+```bash
+npx @midscene/connect serve ./car-screen.mjs --arm-id mg400-1
+# ✔ Car Screen is ready
+# Connect URL: http://127.0.0.1:5820
+# API docs: http://127.0.0.1:5820/api/docs/
+```
+
+- Each `serve` process holds one device instance. Pass `--port` to serve additional devices.
+- When `--host` is not a loopback address, the server requires bearer token authentication. Pass `--token
`, or use the token generated and printed at startup.
+
+## 3. Drive the device
+
+### Agent SDK
+
+Create an Agent connected to the served device with `agentOverConnectProtocol`:
+
+```ts
+import { agentOverConnectProtocol } from '@midscene/connect';
+
+const agent = await agentOverConnectProtocol({
+ url: 'http://127.0.0.1:5820',
+ // token: '...', // or set MIDSCENE_CONNECT_TOKEN
+ // agentOptions: { ... }, // standard Agent options
+});
+
+await agent.aiAct('Open the music app and search for "Jay Chou"');
+await agent.aiAssert('Search results are visible');
+```
+
+- `url` defaults to `MIDSCENE_CONNECT_URL`, then `http://127.0.0.1:5820`.
+- `token` defaults to `MIDSCENE_CONNECT_TOKEN`.
+- If the device defines `description` and `agentOptions` does not set an `aiAct` context, `description` is automatically added to `aiContexts.aiAct`.
+
+### CLI and Playground
+
+The CLI builds its subcommands dynamically from the served device's action space:
+
+```bash
+export MIDSCENE_CONNECT_URL=http://127.0.0.1:5820 # or pass --url / --token
+npx @midscene/connect act --prompt "Open the music app"
+npx @midscene/connect tap --locate "the search box"
+npx @midscene/connect wakevoiceassistant --phrase "hello"
+npx @midscene/connect playground
+```
+
+`playground` supports `--url`, `--token`, `--port` (default `5800`), and `--no-open`.
+
+## Embed in an existing server
+
+To mount the Connect protocol inside an existing Node HTTP server:
+
+```js
+import http from 'node:http';
+import { createConnectHandler } from '@midscene/connect/server';
+
+const handler = createConnectHandler(
+ { name: 'Phone', screenshot, actions },
+ {
+ basePath: '/devices/phone-1/api',
+ token,
+ },
+);
+
+http.createServer((req, res) => handler.handle(req, res) || next(req, res));
+// Clients connect with url: http://host:port/devices/phone-1
+```
+
+## HTTP API
+
+| Method | Path | Description |
+| --- | --- | --- |
+| `GET` | `/api/info` | Protocol version, name, description, `pointerType`, primitives, and custom actions |
+| `GET` | `/api/screenshot` | Returns `{ image: dataURL, width, height }` |
+| `GET` | `/api/size` | Returns `{ width, height }` |
+| `POST` | `/api/primitives/{name}` | Runs a built-in primitive |
+| `POST` | `/api/actions/{name}` | Runs a custom action and returns `{ ok, result? }` |
+| `GET` | `/api/openapi.json`, `/api/docs/` | OpenAPI specification and Swagger UI |
+
+The server executes actions one at a time. Errors return `{ error, code }`.
+
+## Low-level `AbstractInterface` integration
+
+If you maintain an existing custom interface class or need the low-level `AbstractInterface` and `defineAction` reference, see [Integrate with any interface](./integrate-with-any-interface).
diff --git a/apps/site/docs/en/skills.mdx b/apps/site/docs/en/skills.mdx
index 9563b14797..ecb79d81d3 100644
--- a/apps/site/docs/en/skills.mdx
+++ b/apps/site/docs/en/skills.mdx
@@ -1,4 +1,4 @@
-# Control any platform with Skills
+# Control with Skills
[Agent Skills](https://github.com/anthropics/skills) are a format for extending AI coding agents with specialized capabilities. Midscene provides Agent Skills that let AI coding tools (like Claude Code, Cline, etc.) drive UI automation through CLI commands.
diff --git a/apps/site/docs/zh/index.mdx b/apps/site/docs/zh/index.mdx
index 3a36f7019c..595723f0c5 100644
--- a/apps/site/docs/zh/index.mdx
+++ b/apps/site/docs/zh/index.mdx
@@ -57,6 +57,8 @@ E2E 测试的初衷是从用户视角验证完整流程,所以 Midscene 按用
+除了内置平台,还可以通过 [`@midscene/connect`](./midscene-connect) 以 HTTP 协议接入任意界面,例如车机屏、嵌入式面板,以及通过机械臂或 HID 模块驱动的物理设备。真实硬件接入案例见 [midscene-test-everything](https://github.com/web-infra-dev/midscene-test-everything)。
+
### 模型选择与成本 {#model-options}
diff --git a/apps/site/docs/zh/integrate-with-any-interface.mdx b/apps/site/docs/zh/integrate-with-any-interface.mdx
index ba5d03a0b0..e9e3751de8 100644
--- a/apps/site/docs/zh/integrate-with-any-interface.mdx
+++ b/apps/site/docs/zh/integrate-with-any-interface.mdx
@@ -2,6 +2,12 @@ import SetupEnv from './common/setup-env.mdx';
# 与任意界面集成
+:::info 接入自定义设备请优先使用 Midscene Connect
+新接入自定义设备推荐使用 [Midscene Connect](./midscene-connect)(`@midscene/connect`):在一个 `.mjs` 文件中描述设备并通过 HTTP 启动服务,即可直接使用 Agent SDK、CLI 或 Playground 驱动,无需编写 `AbstractInterface` 类。
+
+直接实现 `AbstractInterface` 的方式已不再作为接入自定义设备的首选推荐。本页继续保留,供维护已有 `AbstractInterface` 实现以及查阅 `defineAction` 等底层 API 参考。
+:::
+
你可以使用 Midscene 的 Agent 来控制任意界面,比如 IoT 设备、内部应用、车载显示器等,只需要实现一个符合 `AbstractInterface` 定义的 UI 操作类。
在实现了 UI 操作类之后,你可以获得 Midscene Agent 的全部特性:
diff --git a/apps/site/docs/zh/midscene-connect.mdx b/apps/site/docs/zh/midscene-connect.mdx
new file mode 100644
index 0000000000..bf73ebc409
--- /dev/null
+++ b/apps/site/docs/zh/midscene-connect.mdx
@@ -0,0 +1,179 @@
+import SetupEnv from './common/setup-env.mdx';
+
+# 接入任意界面
+
+使用 [`@midscene/connect`](https://github.com/web-infra-dev/midscene/tree/main/packages/connect) 可以把任意屏幕或自定义硬件接入 Midscene,例如机械臂、采集卡加 HID 模块、车载显示器、IoT 设备或远程机器。
+
+只需在一个 `.mjs` 文件中描述设备并通过 HTTP 启动服务,就能直接使用 Agent SDK、CLI 或 Playground 操作设备,无需实现 `AbstractInterface` 类。
+
+## 真实案例
+
+[midscene-test-everything](https://github.com/web-infra-dev/midscene-test-everything) 仓库收录了多个基于 `@midscene/connect` 实现的真实硬件与平台接入案例:
+
+- **机械臂 × 物理触屏**(`mg400-service`、`arm-kit`、`robotics-vision`):面向车机屏幕与工业面板的相机采集、ArUco 屏幕标定、坐标映射,以及基于 DOBOT MG400 的端到端参考实现。
+- **蓝牙 HID × iPhone 真机**(`ios-airlink`):在 macOS 上通过蓝牙 HID 驱动物理 iPhone,配合 USB、AirPlay 或摄像头采集画面,无需越狱或开启开发者模式。
+
+## 配置 AI 模型服务
+
+
+
+## 1. 定义设备
+
+一个 `.mjs` 文件描述一类设备,`options` 用于选择具体实例。`actions` 中的键如果与内置输入操作同名,直接写函数即可;其他键则为自定义动作。
+
+```js
+// car-screen.mjs
+export default {
+ name: 'Car Screen',
+ description: 'In-car touchscreen driven by a robot arm', // 会加入 aiAct 上下文
+ pointerType: 'touch', // 提供 swipe 时必填:'touch' | 'mouse'
+ options: {
+ type: 'object',
+ properties: { armId: { type: 'string' } },
+ required: ['armId'],
+ },
+ async connect({ armId }) {
+ const arm = await openArm(armId);
+ return {
+ screenshot: () => camera.jpeg(), // PNG/JPEG Buffer、data URL 或 base64
+ actions: {
+ tap: (p) => arm.tap(p.x, p.y),
+ swipe: (from, to, opts) => arm.swipe(from, to, opts?.duration),
+ homeButton: () => arm.pressHome(),
+ wakeVoiceAssistant: {
+ description: 'Wake up the voice assistant with a phrase',
+ params: {
+ type: 'object',
+ properties: {
+ phrase: { type: 'string' },
+ button: { 'x-midscene-locate': true, description: 'The mic button' },
+ },
+ required: ['phrase'],
+ },
+ call: ({ phrase, button }) => arm.tapAndSay(button.center, phrase),
+ },
+ },
+ destroy: () => arm.close(),
+ };
+ },
+};
+```
+
+`import { defineDevice } from '@midscene/connect'` 可以提供编辑器类型提示,但不是必需的,直接默认导出普通对象即可。
+
+`connect()` 返回的对象中 `size()` 是可选的;省略时会默认读取当前截图的宽高。
+
+### 内置操作
+
+函数签名与 `@midscene/core` 的 `InputPrimitives` 一致,坐标单位为截图像素。
+
+| 分组 | 操作 | 约束 |
+| --- | --- | --- |
+| 指针 | `tap`、`doubleClick`、`rightClick`、`middleClick`、`hover`、`longPress`、`dragAndDrop` | 其他指针操作都需要同时提供 `tap` |
+| 滑动 | `swipe`、`pinch` | `swipe` 需要设置 `pointerType`(`mouse` 方式的 `swipe` 也需要 `tap`);`pinch` 需要 `pointerType: 'touch'` 的 `swipe` |
+| 键盘 | `typeText`、`keyboardPress`、`clearInput`、`cursorMove` | `typeText`、`keyboardPress`、`clearInput` 必须一起提供 |
+| 滚动 | `scroll` | |
+| 系统 | `backButton`、`homeButton`、`recentAppsButton` | |
+
+### 参数 Schema
+
+自定义动作的 `params` 和设备的 `options` 使用一个精简的 JSON Schema 子集:
+
+- `string`(`enum`、`minLength`、`maxLength`)
+- `number` / `integer`(`minimum`、`maximum`)
+- `boolean`
+- `array`(`items`、`minItems`、`maxItems`)
+- `object`(`properties`、`required`)
+- `description`
+
+顶层属性标记 `{ "x-midscene-locate": true }` 表示这是一个由 AI 模型定位的元素,`call` 收到的是 `{ description, center, rect }`。
+
+`serve` 启动时会拒绝子集之外的关键字;请求体也会严格校验,出现未知字段即报错。
+
+## 2. 启动服务
+
+先启动设备服务。它会保持设备连接,并提供 HTTP 接口,接口文档(Swagger UI)位于 `/api/docs/`:
+
+```bash
+npx @midscene/connect serve ./car-screen.mjs --arm-id mg400-1
+# ✔ Car Screen is ready
+# Connect URL: http://127.0.0.1:5820
+# API docs: http://127.0.0.1:5820/api/docs/
+```
+
+- 每个 `serve` 进程持有一台设备实例,要接入多台设备时通过 `--port` 启动多个服务。
+- 当 `--host` 不是本机回环地址时,服务端要求携带 bearer token:可以通过 `--token
` 指定,否则会在启动时自动生成并打印。
+
+## 3. 操作设备
+
+### Agent SDK
+
+使用 `agentOverConnectProtocol` 创建连接到该设备服务的 Agent:
+
+```ts
+import { agentOverConnectProtocol } from '@midscene/connect';
+
+const agent = await agentOverConnectProtocol({
+ url: 'http://127.0.0.1:5820',
+ // token: '...', // 或设置环境变量 MIDSCENE_CONNECT_TOKEN
+ // agentOptions: { ... }, // 通用 Agent 配置
+});
+
+await agent.aiAct('打开音乐 App,搜索“周杰伦”');
+await agent.aiAssert('搜索结果已显示');
+```
+
+- `url` 默认读取 `MIDSCENE_CONNECT_URL`,未设置时回退到 `http://127.0.0.1:5820`。
+- `token` 默认读取 `MIDSCENE_CONNECT_TOKEN`。
+- 如果设备定义了 `description` 且 `agentOptions` 未配置 `aiAct` 上下文,`description` 会自动加入 `aiContexts.aiAct`。
+
+### CLI 与 Playground
+
+CLI 的子命令会根据所连设备的动作空间动态生成:
+
+```bash
+export MIDSCENE_CONNECT_URL=http://127.0.0.1:5820 # 也可以传 --url / --token
+npx @midscene/connect act --prompt "打开音乐 App"
+npx @midscene/connect tap --locate "搜索框"
+npx @midscene/connect wakevoiceassistant --phrase "你好"
+npx @midscene/connect playground
+```
+
+`playground` 支持 `--url`、`--token`、`--port`(默认 `5800`)和 `--no-open` 参数。
+
+## 嵌入已有服务
+
+在已有的 Node HTTP 服务里挂载 Connect 协议:
+
+```js
+import http from 'node:http';
+import { createConnectHandler } from '@midscene/connect/server';
+
+const handler = createConnectHandler(
+ { name: 'Phone', screenshot, actions },
+ {
+ basePath: '/devices/phone-1/api',
+ token,
+ },
+);
+
+http.createServer((req, res) => handler.handle(req, res) || next(req, res));
+// 客户端使用 url: http://host:port/devices/phone-1
+```
+
+## HTTP API
+
+| 方法 | 路径 | 说明 |
+| --- | --- | --- |
+| `GET` | `/api/info` | 协议版本、名称、描述、`pointerType`、内置操作和自定义动作 |
+| `GET` | `/api/screenshot` | 返回 `{ image: dataURL, width, height }` |
+| `GET` | `/api/size` | 返回 `{ width, height }` |
+| `POST` | `/api/primitives/{name}` | 执行内置操作 |
+| `POST` | `/api/actions/{name}` | 执行自定义动作,返回 `{ ok, result? }` |
+| `GET` | `/api/openapi.json`、`/api/docs/` | OpenAPI 规范和 Swagger UI |
+
+服务端一次只执行一个动作,出错时返回 `{ error, code }`。
+
+## 底层 `AbstractInterface` 集成
+
+如果你需要维护已有的自定义界面类,或查阅 `AbstractInterface` 与 `defineAction` 等底层 API,请参考[与任意界面集成](./integrate-with-any-interface)。
diff --git a/apps/site/docs/zh/skills.mdx b/apps/site/docs/zh/skills.mdx
index 07bccfa830..92ee9cf381 100644
--- a/apps/site/docs/zh/skills.mdx
+++ b/apps/site/docs/zh/skills.mdx
@@ -1,4 +1,4 @@
-# 使用 Skills 控制任意平台
+# 使用 Skills 控制
[Agent Skills](https://github.com/anthropics/skills) 是一种扩展 AI 编程助手能力的格式。Midscene 提供了 Agent Skills,让 AI 编程工具(如 Claude Code、Cline 等)可以通过 CLI 命令驱动 UI 自动化。
diff --git a/apps/site/rspress.config.ts b/apps/site/rspress.config.ts
index 5326d8f492..daaf445dd4 100644
--- a/apps/site/rspress.config.ts
+++ b/apps/site/rspress.config.ts
@@ -196,7 +196,7 @@ export default defineConfig(async () => {
link: '/get-started',
},
{
- text: 'Control any platform with Skills',
+ text: 'Control with Skills',
link: '/skills',
},
{
@@ -375,6 +375,10 @@ export default defineConfig(async () => {
text: 'Provide application knowledge to a GUI Agent',
link: '/provide-application-knowledge-to-gui-agent',
},
+ {
+ text: 'Connect any UI',
+ link: '/midscene-connect',
+ },
{
text: 'Process report files',
link: '/consume-report-file',
@@ -383,10 +387,6 @@ export default defineConfig(async () => {
text: 'Write BDD scripts with Gherkin',
link: '/advanced/bdd-style-scripts-with-gherkin',
},
- {
- text: 'Integrate with any interface',
- link: '/integrate-with-any-interface',
- },
{
text: 'Cache AI plans & DOM locators',
link: '/caching',
@@ -471,7 +471,7 @@ export default defineConfig(async () => {
link: '/zh/get-started',
},
{
- text: '使用 Skills 控制任意平台',
+ text: '使用 Skills 控制',
link: '/zh/skills',
},
{
@@ -650,6 +650,10 @@ export default defineConfig(async () => {
text: '为 GUI Agent 补充应用知识',
link: '/zh/provide-application-knowledge-to-gui-agent',
},
+ {
+ text: '接入任意界面',
+ link: '/zh/midscene-connect',
+ },
{
text: '处理报告文件',
link: '/zh/consume-report-file',
@@ -658,10 +662,6 @@ export default defineConfig(async () => {
text: '使用 Gherkin 编写 BDD 脚本',
link: '/zh/advanced/bdd-style-scripts-with-gherkin',
},
- {
- text: '与任意界面集成',
- link: '/zh/integrate-with-any-interface',
- },
{
text: '缓存 AI 规划与 DOM 定位',
link: '/zh/caching',
diff --git a/apps/site/theme/components/PlatformHub.tsx b/apps/site/theme/components/PlatformHub.tsx
index 89b97708b5..e6e6ba8712 100644
--- a/apps/site/theme/components/PlatformHub.tsx
+++ b/apps/site/theme/components/PlatformHub.tsx
@@ -55,8 +55,8 @@ export function PlatformHub() {
},
{
name: t('platformCustom'),
- packageName: '@midscene/core',
- href: '/integrate-with-any-interface',
+ packageName: '@midscene/connect',
+ href: '/midscene-connect',
icon: Blocks,
},
];
diff --git a/apps/site/theme/i18n/enUS.ts b/apps/site/theme/i18n/enUS.ts
index 8d86ffd48f..c9e0dec477 100644
--- a/apps/site/theme/i18n/enUS.ts
+++ b/apps/site/theme/i18n/enUS.ts
@@ -96,7 +96,7 @@ export const EN_US = {
visionStepVerify: 'Verify',
visionStepVerifyDesc: 'Assert on what users actually see',
visionShowcaseLink: 'See real-world examples',
- platformCustom: 'Custom interfaces',
+ platformCustom: 'Connect any UI',
platformCustomDoc: 'Extension guide',
platformBridgeDoc: 'Bridge Mode',
diff --git a/apps/site/theme/i18n/zhCN.ts b/apps/site/theme/i18n/zhCN.ts
index 5c9297e5f8..13157a17d2 100644
--- a/apps/site/theme/i18n/zhCN.ts
+++ b/apps/site/theme/i18n/zhCN.ts
@@ -94,7 +94,7 @@ export const ZH_CN: Record = {
visionStepVerify: '检查结果',
visionStepVerifyDesc: '断言用户实际看到的内容',
visionShowcaseLink: '查看实际案例',
- platformCustom: '自定义界面',
+ platformCustom: '接入任意界面',
platformCustomDoc: '扩展指南',
platformBridgeDoc: 'Bridge 模式',
diff --git a/packages/connect/README.md b/packages/connect/README.md
new file mode 100644
index 0000000000..9465d6b536
--- /dev/null
+++ b/packages/connect/README.md
@@ -0,0 +1,5 @@
+# @midscene/connect
+
+Connect any screen or custom device to Midscene by defining it in a single `.mjs` file, serving it over HTTP, and driving it with the Agent SDK, CLI, or Playground.
+
+See .
diff --git a/packages/connect/bin/midscene-connect b/packages/connect/bin/midscene-connect
new file mode 100755
index 0000000000..73757996ee
--- /dev/null
+++ b/packages/connect/bin/midscene-connect
@@ -0,0 +1,2 @@
+#!/usr/bin/env node
+import('../dist/es/cli.mjs');
diff --git a/packages/connect/package.json b/packages/connect/package.json
new file mode 100644
index 0000000000..8b51f0ce5b
--- /dev/null
+++ b/packages/connect/package.json
@@ -0,0 +1,50 @@
+{
+ "name": "@midscene/connect",
+ "version": "1.18.2",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/web-infra-dev/midscene.git",
+ "directory": "packages/connect"
+ },
+ "description": "Connect any screen to Midscene: define a device in one file, serve it over HTTP, drive it with Agent, CLI and Playground",
+ "main": "./dist/lib/index.js",
+ "module": "./dist/es/index.mjs",
+ "types": "./dist/types/index.d.ts",
+ "bin": {
+ "midscene-connect": "./bin/midscene-connect"
+ },
+ "files": ["bin", "dist", "README.md"],
+ "exports": {
+ ".": {
+ "types": "./dist/types/index.d.ts",
+ "import": "./dist/es/index.mjs",
+ "require": "./dist/lib/index.js"
+ },
+ "./server": {
+ "types": "./dist/types/server.d.ts",
+ "import": "./dist/es/server.mjs",
+ "require": "./dist/lib/server.js"
+ },
+ "./package.json": "./package.json"
+ },
+ "scripts": {
+ "dev": "npm run build:watch",
+ "build": "rslib build",
+ "build:watch": "rslib build --watch --no-clean",
+ "test": "rstest"
+ },
+ "dependencies": {
+ "@midscene/core": "workspace:*",
+ "@midscene/playground": "workspace:*",
+ "@midscene/shared": "workspace:*",
+ "swagger-ui-dist": "^5.32.0",
+ "zod": "^3.25.1"
+ },
+ "devDependencies": {
+ "@rslib/core": "~0.19.6",
+ "@rstest/core": "0.12.0",
+ "@types/node": "^18.0.0",
+ "typescript": "^5.8.3"
+ },
+ "license": "MIT"
+}
diff --git a/packages/connect/rslib.config.ts b/packages/connect/rslib.config.ts
new file mode 100644
index 0000000000..c985ed8f64
--- /dev/null
+++ b/packages/connect/rslib.config.ts
@@ -0,0 +1,31 @@
+import { defineConfig } from '@rslib/core';
+import { createTypeCheckPlugin } from '../../scripts/rsbuild-utils.ts';
+import { version } from './package.json';
+
+export default defineConfig({
+ lib: [
+ {
+ output: { distPath: { root: 'dist/lib' } },
+ format: 'cjs',
+ syntax: 'es2020',
+ },
+ {
+ output: { distPath: { root: 'dist/es' } },
+ dts: { bundle: true, distPath: 'dist/types' },
+ format: 'esm',
+ syntax: 'es2020',
+ },
+ ],
+ source: {
+ tsconfigPath: 'tsconfig.build.json',
+ entry: {
+ index: './src/index.ts',
+ server: './src/server.ts',
+ cli: './src/cli.ts',
+ },
+ define: {
+ __VERSION__: JSON.stringify(version),
+ },
+ },
+ plugins: [createTypeCheckPlugin()],
+});
diff --git a/packages/connect/rstest.config.ts b/packages/connect/rstest.config.ts
new file mode 100644
index 0000000000..e396441483
--- /dev/null
+++ b/packages/connect/rstest.config.ts
@@ -0,0 +1,19 @@
+import path from 'node:path';
+import { defineConfig } from '@rstest/core';
+import { defineVersion, photonExternal } from '../../scripts/rstest-shared';
+import { version } from './package.json';
+
+export default defineConfig({
+ name: '@midscene/connect',
+ resolve: {
+ alias: { '@': path.resolve(__dirname, 'src') },
+ },
+ include: ['tests/unit/**/*.test.ts'],
+ testTimeout: 30 * 1000,
+ source: {
+ define: defineVersion(version),
+ },
+ output: {
+ externals: photonExternal,
+ },
+});
diff --git a/packages/connect/src/cli-utils.ts b/packages/connect/src/cli-utils.ts
new file mode 100644
index 0000000000..bb48115536
--- /dev/null
+++ b/packages/connect/src/cli-utils.ts
@@ -0,0 +1,75 @@
+import { resolve } from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { CLIError } from '@midscene/shared/cli';
+import type { DeviceDefinition } from './device';
+import { coerceCliValue } from './schema';
+
+/** Minimal `--key value` / `--key=value` / `--flag` parser. */
+export function parseFlags(args: string[]) {
+ const positionals: string[] = [];
+ const flags: Record = {};
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ if (!arg.startsWith('--')) {
+ positionals.push(arg);
+ continue;
+ }
+ const eq = arg.indexOf('=');
+ if (eq > 0) flags[arg.slice(2, eq)] = arg.slice(eq + 1);
+ else if (i + 1 < args.length && !args[i + 1].startsWith('--'))
+ flags[arg.slice(2)] = args[++i];
+ else flags[arg.slice(2)] = true;
+ }
+ return { positionals, flags };
+}
+
+const camel = (key: string) =>
+ key.replace(/-([a-z0-9])/g, (_, c: string) => c.toUpperCase());
+export const str = (value: string | true | undefined, name: string) => {
+ if (value === true) throw new CLIError(`--${name} needs a value`);
+ return value;
+};
+
+export async function loadDefinition(
+ file: string,
+): Promise> {
+ const href = pathToFileURL(resolve(file)).href;
+ const mod = await import(/* webpackIgnore: true */ href);
+ const definition = mod.default ?? mod.device;
+ if (!definition || typeof definition.connect !== 'function')
+ throw new CLIError(
+ `${file} must default-export a device definition with connect(options)`,
+ );
+ return definition;
+}
+
+/** Turn leftover CLI flags into instance options using the definition's schema. */
+export function parseDeviceOptions(
+ definition: DeviceDefinition,
+ flags: Record,
+) {
+ const properties = definition.options?.properties ?? {};
+ const options: Record = {};
+ for (const [flag, raw] of Object.entries(flags)) {
+ const key = camel(flag);
+ const schema = properties[key];
+ if (!schema) {
+ const known = Object.keys(properties);
+ throw new CLIError(
+ `Unknown option --${flag} for "${definition.name}".${known.length ? ` Available: ${known.map((k) => `--${k.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`).join(', ')}` : ' This device takes no options.'}`,
+ );
+ }
+ options[key] =
+ raw === true
+ ? 'type' in schema && schema.type === 'boolean'
+ ? true
+ : raw
+ : coerceCliValue(schema, raw);
+ if (
+ options[key] === true &&
+ !('type' in schema && schema.type === 'boolean')
+ )
+ throw new CLIError(`--${flag} needs a value`);
+ }
+ return options;
+}
diff --git a/packages/connect/src/cli.ts b/packages/connect/src/cli.ts
new file mode 100644
index 0000000000..8cf0d0b448
--- /dev/null
+++ b/packages/connect/src/cli.ts
@@ -0,0 +1,118 @@
+import { createReportCliCommands } from '@midscene/core';
+import { CLIError, reportCLIError, runToolsCLI } from '@midscene/shared/cli';
+import {
+ loadDefinition,
+ parseDeviceOptions,
+ parseFlags,
+ str,
+} from './cli-utils';
+import { ConnectError, RemoteDevice, agentOverConnectProtocol } from './client';
+import { DEFAULT_CONNECT_PORT } from './device';
+import { serveDevice } from './server';
+import { ConnectMidsceneTools } from './tools';
+
+declare const __VERSION__: string;
+const scriptName = 'midscene-connect';
+
+async function serve(args: string[]) {
+ const { positionals, flags } = parseFlags(args);
+ const [file] = positionals;
+ if (!file || flags.help)
+ return console.log(`
+Usage: ${scriptName} serve [--port ${DEFAULT_CONNECT_PORT}] [--host 127.0.0.1] [--token ] [device options]
+
+Connects the device defined in and serves it over HTTP.
+Device options are declared by the definition's \`options\` schema.`);
+ const { port, host, token, ...deviceFlags } = flags;
+ const definition = await loadDefinition(file);
+ const portValue = str(port, 'port');
+ const served = await serveDevice(definition, {
+ port: portValue === undefined ? undefined : Number(portValue),
+ host: str(host, 'host'),
+ token: str(token, 'token'),
+ options: parseDeviceOptions(definition, deviceFlags),
+ });
+ console.log(`✔ ${definition.name} is ready`);
+ console.log(` Connect URL: ${served.url}`);
+ console.log(` API docs: ${served.url}/api/docs/`);
+ if (served.token) console.log(` Token: ${served.token}`);
+ const stop = () => {
+ served.close().finally(() => process.exit(0));
+ };
+ process.once('SIGINT', stop);
+ process.once('SIGTERM', stop);
+}
+
+async function playground(args: string[]) {
+ if (args.includes('--help') || args.includes('-h')) {
+ console.log(`
+Usage: ${scriptName} playground [options]
+
+Open the Playground for a Connect device.
+
+ --url Device URL (env: MIDSCENE_CONNECT_URL, default: http://127.0.0.1:${DEFAULT_CONNECT_PORT})
+ --token Device token (env: MIDSCENE_CONNECT_TOKEN)
+ --port Local Playground web port (default: 5800)
+ --no-open Start without opening a browser`);
+ return;
+ }
+
+ const { flags } = parseFlags(args);
+ const url = str(flags.url, 'url');
+ const token = str(flags.token, 'token');
+ const port = str(flags.port, 'port');
+ const device = await RemoteDevice.connect({ url, token });
+ const { playgroundForAgentFactory } = await import('@midscene/playground');
+ await playgroundForAgentFactory(() =>
+ agentOverConnectProtocol({ url, token }),
+ ).launch({
+ port: port === undefined ? undefined : Number(port),
+ openBrowser: flags['no-open'] === undefined,
+ });
+ console.log(`🎮 Playground for ${device.describe()} (${device.client.url})`);
+}
+
+async function main(argv = process.argv.slice(2)) {
+ const [command, ...rest] = argv;
+ if (command === 'serve') return serve(rest);
+ if (command === 'playground') return playground(rest);
+
+ const showingHelp = !command || command === '--help' || command === '-h';
+ const { flags } = parseFlags(rest);
+ let device: RemoteDevice | undefined;
+ try {
+ device = await RemoteDevice.connect({
+ url: typeof flags.url === 'string' ? flags.url : undefined,
+ token: typeof flags.token === 'string' ? flags.token : undefined,
+ });
+ } catch (error) {
+ if (
+ !showingHelp &&
+ command !== '--version' &&
+ command !== '-v' &&
+ command !== 'version'
+ )
+ throw error;
+ }
+ if (showingHelp) {
+ console.log(`
+Device commands:
+ serve Connect a device and serve it over HTTP (run this first)
+ playground Open the Playground for the served device
+${device ? `\nServed device: ${device.describe()} (${device.client.url})` : '\nNo served device reachable; device actions are listed once one is running.'}`);
+ }
+ await runToolsCLI(new ConnectMidsceneTools(device), scriptName, {
+ argv,
+ stripPrefix: 'connect_',
+ version: __VERSION__,
+ extraCommands: createReportCliCommands(),
+ });
+}
+
+main().catch((error) => {
+ process.exit(
+ reportCLIError(
+ error instanceof ConnectError ? new CLIError(error.message) : error,
+ ),
+ );
+});
diff --git a/packages/connect/src/client.ts b/packages/connect/src/client.ts
new file mode 100644
index 0000000000..dd2f400c58
--- /dev/null
+++ b/packages/connect/src/client.ts
@@ -0,0 +1,253 @@
+import type { DeviceAction, Size } from '@midscene/core';
+import { Agent, type AgentOpt } from '@midscene/core/agent';
+import {
+ type AbstractInterface,
+ type InputPrimitives,
+ defineAction,
+ defineActionsFromInputPrimitives,
+} from '@midscene/core/device';
+import {
+ type ConnectInfo,
+ DEFAULT_CONNECT_PORT,
+ PROTOCOL_VERSION,
+} from './device';
+import { primitiveByName, systemActionConfigs } from './primitives';
+import { paramsToWire, toZod } from './schema';
+
+export interface ConnectTarget {
+ /** Defaults to `MIDSCENE_CONNECT_URL`, then `http://127.0.0.1:5820`. */
+ url?: string;
+ /** Defaults to `MIDSCENE_CONNECT_TOKEN`. */
+ token?: string;
+}
+
+export class ConnectError extends Error {
+ constructor(
+ message: string,
+ readonly status?: number,
+ readonly code?: string,
+ ) {
+ super(message);
+ }
+}
+
+export function resolveConnectTarget(target: ConnectTarget = {}) {
+ const url = (
+ target.url ||
+ process.env.MIDSCENE_CONNECT_URL ||
+ `http://127.0.0.1:${DEFAULT_CONNECT_PORT}`
+ ).replace(/\/+$/, '');
+ const token = target.token || process.env.MIDSCENE_CONNECT_TOKEN || undefined;
+ return { url, token };
+}
+
+/** Thin JSON client for a `midscene-connect serve` endpoint. */
+export class ConnectClient {
+ readonly url: string;
+ private readonly token?: string;
+
+ constructor(target: ConnectTarget = {}) {
+ const resolved = resolveConnectTarget(target);
+ this.url = resolved.url;
+ this.token = resolved.token;
+ }
+
+ async request(
+ method: 'GET' | 'POST',
+ path: string,
+ body?: unknown,
+ ): Promise {
+ const apiUrl = `${this.url}/api${path}`;
+ let res: Response;
+ try {
+ res = await fetch(apiUrl, {
+ method,
+ headers: {
+ ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
+ ...(this.token ? { Authorization: `Bearer ${this.token}` } : {}),
+ },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ } catch (error) {
+ throw new ConnectError(
+ `Cannot reach the device at ${this.url}. Start it with \`midscene-connect serve \` first. (${error instanceof Error ? error.message : String(error)})`,
+ );
+ }
+ const text = await res.text();
+ let data: any;
+ try {
+ data = text ? JSON.parse(text) : {};
+ } catch {
+ throw new ConnectError(
+ `Unexpected non-JSON response from ${apiUrl} (HTTP ${res.status})`,
+ res.status,
+ );
+ }
+ if (!res.ok)
+ throw new ConnectError(
+ data?.error ?? `HTTP ${res.status} from ${apiUrl}`,
+ res.status,
+ data?.code,
+ );
+ return data as T;
+ }
+
+ async info(): Promise {
+ const info = await this.request('GET', '/info');
+ if (info?.protocol !== PROTOCOL_VERSION)
+ throw new ConnectError(
+ `Unsupported protocol at ${this.url}: expected ${PROTOCOL_VERSION}, got ${JSON.stringify(info?.protocol)}`,
+ );
+ return info;
+ }
+}
+
+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
+
+/** A Midscene interface whose screen and input live behind the connect protocol. */
+export class RemoteDevice implements AbstractInterface {
+ readonly interfaceType = 'midscene-connect';
+ readonly inputPrimitives: InputPrimitives;
+ private readonly actions: DeviceAction[];
+
+ constructor(
+ readonly client: ConnectClient,
+ readonly info: ConnectInfo,
+ ) {
+ const has = (name: string) => info.primitives.includes(name);
+ const call = (name: string) => {
+ const spec = primitiveByName.get(name)!;
+ return async (...args: any[]) => {
+ await client.request(
+ 'POST',
+ `/primitives/${name}`,
+ spec.toBody(...args),
+ );
+ };
+ };
+ const optional = (name: string) => (has(name) ? call(name) : undefined);
+ const touchSwipe = has('swipe') && info.pointerType === 'touch';
+
+ this.inputPrimitives = {
+ pointer: has('tap')
+ ? {
+ tap: call('tap'),
+ doubleClick: optional('doubleClick'),
+ rightClick: optional('rightClick'),
+ middleClick: optional('middleClick'),
+ hover: optional('hover'),
+ longPress: optional('longPress'),
+ dragAndDrop: optional('dragAndDrop'),
+ swipe:
+ has('swipe') && info.pointerType === 'mouse'
+ ? call('swipe')
+ : undefined,
+ }
+ : undefined,
+ touch: touchSwipe
+ ? { swipe: call('swipe'), pinch: optional('pinch') }
+ : undefined,
+ keyboard: has('typeText')
+ ? {
+ typeText: call('typeText'),
+ keyboardPress: call('keyboardPress'),
+ clearInput: call('clearInput'),
+ cursorMove: optional('cursorMove'),
+ }
+ : undefined,
+ scroll: has('scroll') ? { scroll: call('scroll') } : undefined,
+ system: {
+ backButton: optional('backButton'),
+ homeButton: optional('homeButton'),
+ recentAppsButton: optional('recentAppsButton'),
+ },
+ };
+
+ const builtIn = defineActionsFromInputPrimitives(this.inputPrimitives, {
+ size: () => this.size(),
+ sleep,
+ systemActions: systemActionConfigs,
+ });
+ const builtInNames = new Set(builtIn.map((a) => a.name));
+ const custom = info.actions.map((action) => {
+ if (builtInNames.has(action.name))
+ throw new ConnectError(
+ `Custom action "${action.name}" conflicts with a built-in action; rename it on the device`,
+ );
+ return defineAction({
+ name: action.name,
+ description: action.description,
+ paramSchema: action.params ? (toZod(action.params) as any) : undefined,
+ call: async (param: unknown) => {
+ const res = await client.request(
+ 'POST',
+ `/actions/${action.name}`,
+ paramsToWire(action.params, param),
+ );
+ return res.result;
+ },
+ } as any) as DeviceAction;
+ });
+ this.actions = [...builtIn, ...custom];
+ }
+
+ static async connect(target: ConnectTarget = {}) {
+ const client = new ConnectClient(target);
+ return new RemoteDevice(client, await client.info());
+ }
+
+ describe() {
+ return this.info.description
+ ? `${this.info.name}: ${this.info.description}`
+ : this.info.name;
+ }
+
+ async screenshotBase64(): Promise {
+ const { image } = await this.client.request<{ image: string }>(
+ 'GET',
+ '/screenshot',
+ );
+ return image;
+ }
+
+ async size(): Promise {
+ const { width, height } = await this.client.request('GET', '/size');
+ return { width, height };
+ }
+
+ actionSpace() {
+ return this.actions;
+ }
+
+ async destroy() {}
+}
+
+export interface AgentOverConnectProtocolOptions extends ConnectTarget {
+ agentOptions?: AgentOpt;
+}
+
+/**
+ * Create an Agent for a device served by `midscene-connect serve`.
+ * The device description is added to the aiAct context unless one is given.
+ */
+export async function agentOverConnectProtocol(
+ options: AgentOverConnectProtocolOptions = {},
+): Promise> {
+ const device = await RemoteDevice.connect(options);
+ const agentOptions = options.agentOptions ?? {};
+ const hasContext =
+ agentOptions.aiContexts?.aiAct !== undefined ||
+ agentOptions.aiActContext !== undefined ||
+ agentOptions.aiActionContext !== undefined;
+ return new Agent(device, {
+ ...agentOptions,
+ ...(device.info.description && !hasContext
+ ? {
+ aiContexts: {
+ ...agentOptions.aiContexts,
+ aiAct: device.info.description,
+ },
+ }
+ : {}),
+ });
+}
diff --git a/packages/connect/src/device.ts b/packages/connect/src/device.ts
new file mode 100644
index 0000000000..cda48d020b
--- /dev/null
+++ b/packages/connect/src/device.ts
@@ -0,0 +1,206 @@
+import { imageInfoOfBase64 } from '@midscene/shared/img';
+import { primitiveByName, primitiveSpecs } from './primitives';
+import {
+ type ObjectParamSchema,
+ type SchemaError,
+ assertParamSchema,
+} from './schema';
+
+export const PROTOCOL_VERSION = 'midscene-connect/1';
+/** Default `serve` port (the Playground uses 5800). */
+export const DEFAULT_CONNECT_PORT = 5820;
+
+export type PointerType = 'touch' | 'mouse';
+export type ScreenSize = { width: number; height: number };
+
+/** A device-specific action beyond the built-in primitives. */
+export interface CustomAction {
+ description: string;
+ /** JSON Schema subset; the root must be `{ type: 'object' }`. */
+ params?: ObjectParamSchema;
+ call(params: TParams): unknown;
+}
+
+/**
+ * What `connect()` returns. Keys of `actions` that match a built-in primitive
+ * name (`tap`, `swipe`, `typeText`, `homeButton`, ...) are functions with core
+ * `InputPrimitives` signatures; any other key is a {@link CustomAction}.
+ */
+export interface DeviceConnection {
+ /** A PNG/JPEG Buffer, a data URL, or raw base64 image data. */
+ screenshot(): Promise | Buffer | string;
+ /** Defaults to the dimensions of the current screenshot. */
+ size?(): Promise | ScreenSize;
+ actions?: Record unknown) | CustomAction>;
+ destroy?(): Promise | void;
+}
+
+export interface DeviceMeta {
+ name: string;
+ description?: string;
+ /** How `swipe` is performed and described to the model. Required with `swipe`. */
+ pointerType?: PointerType;
+}
+
+/** A device instance, used when embedding the protocol in another server. */
+export type ConnectDevice = DeviceMeta & DeviceConnection;
+
+/** One file describes one kind of device; `options` select an instance. */
+export interface DeviceDefinition>
+ extends DeviceMeta {
+ /** JSON Schema subset describing `midscene-connect serve` options. */
+ options?: ObjectParamSchema;
+ connect(options: TOptions): Promise | DeviceConnection;
+}
+
+/** Identity helper for editor type hints; a plain default export works too. */
+export function defineDevice>(
+ definition: DeviceDefinition,
+): DeviceDefinition {
+ return definition;
+}
+
+/** The `/info` response. */
+export interface ConnectInfo {
+ protocol: typeof PROTOCOL_VERSION;
+ name: string;
+ description?: string;
+ pointerType?: PointerType;
+ primitives: string[];
+ actions: { name: string; description: string; params?: ObjectParamSchema }[];
+}
+
+export interface PreparedDevice {
+ info: ConnectInfo;
+ primitives: Map unknown>;
+ actions: Map;
+ screenshot(): Promise<{ image: string; width: number; height: number }>;
+ size(): Promise;
+ destroy(): Promise;
+}
+
+const actionNamePattern = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
+
+function toDataUrl(raw: Buffer | string): string {
+ if (typeof raw === 'string' && raw.startsWith('data:image/')) return raw;
+ const buffer = typeof raw === 'string' ? Buffer.from(raw, 'base64') : raw;
+ if (!Buffer.isBuffer(buffer) || buffer.length < 4)
+ throw new Error(
+ 'screenshot() must return a PNG/JPEG Buffer or base64 string',
+ );
+ const mime =
+ buffer[0] === 0x89 && buffer[1] === 0x50
+ ? 'image/png'
+ : buffer[0] === 0xff && buffer[1] === 0xd8
+ ? 'image/jpeg'
+ : undefined;
+ if (!mime) throw new Error('screenshot() must return a PNG or JPEG image');
+ return `data:${mime};base64,${buffer.toString('base64')}`;
+}
+
+/** Validate a device and normalize it for the server. Throws on misuse. */
+export function prepareDevice(device: ConnectDevice): PreparedDevice {
+ const fail = (message: string): never => {
+ throw new Error(`Invalid device "${device?.name}": ${message}`);
+ };
+ if (!device || typeof device.name !== 'string' || !device.name.trim())
+ fail('name is required');
+ if (typeof device.screenshot !== 'function') fail('screenshot() is required');
+ if (
+ device.pointerType !== undefined &&
+ device.pointerType !== 'touch' &&
+ device.pointerType !== 'mouse'
+ )
+ fail('pointerType must be "touch" or "mouse"');
+
+ const primitives = new Map unknown>();
+ const actions = new Map();
+ for (const [name, value] of Object.entries(device.actions ?? {})) {
+ if (primitiveByName.has(name)) {
+ if (typeof value !== 'function')
+ fail(`actions.${name} is a built-in primitive and must be a function`);
+ primitives.set(name, value as (...args: any[]) => unknown);
+ continue;
+ }
+ if (!actionNamePattern.test(name))
+ fail(`actions.${name}: action names must match ${actionNamePattern}`);
+ if (typeof value === 'function')
+ fail(
+ `actions.${name} is not a built-in primitive (${primitiveSpecs.map((p) => p.name).join(', ')}); custom actions must be { description, params?, call }`,
+ );
+ const custom = value as CustomAction;
+ if (typeof custom?.description !== 'string' || !custom.description.trim())
+ fail(`actions.${name}.description is required`);
+ if (typeof custom.call !== 'function')
+ fail(`actions.${name}.call must be a function`);
+ if (custom.params !== undefined) {
+ try {
+ assertParamSchema(custom.params, 'params');
+ } catch (error) {
+ fail(`actions.${name}.${(error as SchemaError).message}`);
+ }
+ if (custom.params.type !== 'object')
+ fail(`actions.${name}.params must be { type: 'object', ... }`);
+ }
+ actions.set(name, custom);
+ }
+
+ const has = (name: string) => primitives.has(name);
+ const pointer = [
+ 'doubleClick',
+ 'rightClick',
+ 'middleClick',
+ 'hover',
+ 'longPress',
+ 'dragAndDrop',
+ ];
+ if (!has('tap') && pointer.some(has))
+ fail(`${pointer.filter(has).join(', ')} require tap`);
+ if (has('swipe') && !device.pointerType)
+ fail('pointerType ("touch" or "mouse") is required when swipe is provided');
+ if (has('swipe') && device.pointerType === 'mouse' && !has('tap'))
+ fail('a mouse swipe requires tap');
+ if (has('pinch') && !(has('swipe') && device.pointerType === 'touch'))
+ fail('pinch requires swipe with pointerType "touch"');
+ const keyboard = ['typeText', 'keyboardPress', 'clearInput'];
+ if ([...keyboard, 'cursorMove'].some(has) && !keyboard.every(has))
+ fail('typeText, keyboardPress and clearInput must be provided together');
+
+ const screenshot = async () => {
+ const image = toDataUrl(await device.screenshot());
+ const { width, height } = await imageInfoOfBase64(image);
+ return { image, width, height };
+ };
+ const size = async (): Promise => {
+ if (device.size) {
+ const { width, height } = await device.size();
+ if (!(width > 0 && height > 0))
+ throw new Error('size() returned an invalid size');
+ return { width, height };
+ }
+ const { width, height } = await screenshot();
+ return { width, height };
+ };
+
+ return {
+ info: {
+ protocol: PROTOCOL_VERSION,
+ name: device.name,
+ ...(device.description ? { description: device.description } : {}),
+ ...(device.pointerType ? { pointerType: device.pointerType } : {}),
+ primitives: primitiveSpecs.map((p) => p.name).filter(has),
+ actions: [...actions].map(([name, action]) => ({
+ name,
+ description: action.description,
+ ...(action.params ? { params: action.params } : {}),
+ })),
+ },
+ primitives,
+ actions,
+ screenshot,
+ size,
+ destroy: async () => {
+ await device.destroy?.();
+ },
+ };
+}
diff --git a/packages/connect/src/index.ts b/packages/connect/src/index.ts
new file mode 100644
index 0000000000..ff4b46361c
--- /dev/null
+++ b/packages/connect/src/index.ts
@@ -0,0 +1,20 @@
+export {
+ ConnectClient,
+ ConnectError,
+ RemoteDevice,
+ agentOverConnectProtocol,
+ resolveConnectTarget,
+} from './client';
+export type { AgentOverConnectProtocolOptions, ConnectTarget } from './client';
+export { DEFAULT_CONNECT_PORT, PROTOCOL_VERSION, defineDevice } from './device';
+export type {
+ ConnectDevice,
+ ConnectInfo,
+ CustomAction,
+ DeviceConnection,
+ DeviceDefinition,
+ PointerType,
+ ScreenSize,
+} from './device';
+export { LOCATE_KEYWORD } from './schema';
+export type { LocatedElement, ObjectParamSchema, ParamSchema } from './schema';
diff --git a/packages/connect/src/openapi.ts b/packages/connect/src/openapi.ts
new file mode 100644
index 0000000000..f9ba8db6f4
--- /dev/null
+++ b/packages/connect/src/openapi.ts
@@ -0,0 +1,156 @@
+import type { ConnectInfo } from './device';
+import { primitiveByName } from './primitives';
+import {
+ type ParamSchema,
+ isLocateSchema,
+ locatedElementSchema,
+} from './schema';
+
+/** JSON Schema subset -> OpenAPI schema (locate markers become element objects). */
+function toOpenAPISchema(schema: ParamSchema): Record {
+ if (isLocateSchema(schema))
+ return {
+ ...toOpenAPISchema(locatedElementSchema),
+ ...(schema.description ? { description: schema.description } : {}),
+ };
+ if (schema.type === 'object')
+ return {
+ type: 'object',
+ ...(schema.description ? { description: schema.description } : {}),
+ properties: Object.fromEntries(
+ Object.entries(schema.properties).map(([k, v]) => [
+ k,
+ toOpenAPISchema(v),
+ ]),
+ ),
+ ...(schema.required?.length ? { required: schema.required } : {}),
+ additionalProperties: false,
+ };
+ if (schema.type === 'array')
+ return { ...schema, items: toOpenAPISchema(schema.items) };
+ return { ...schema };
+}
+
+const errorResponse = {
+ description: 'Error',
+ content: {
+ 'application/json': {
+ schema: {
+ type: 'object',
+ properties: { error: { type: 'string' }, code: { type: 'string' } },
+ required: ['error', 'code'],
+ },
+ },
+ },
+};
+const json = (schema: Record, description = 'OK') => ({
+ description,
+ content: { 'application/json': { schema } },
+});
+
+export function buildOpenAPI(
+ info: ConnectInfo,
+ { basePath, secured }: { basePath: string; secured: boolean },
+) {
+ const paths: Record = {
+ [`${basePath}/info`]: {
+ get: {
+ summary: 'Device description, supported primitives and custom actions',
+ responses: { 200: json({ type: 'object' }), default: errorResponse },
+ },
+ },
+ [`${basePath}/screenshot`]: {
+ get: {
+ summary: 'Capture the current screen',
+ responses: {
+ 200: json({
+ type: 'object',
+ properties: {
+ image: {
+ type: 'string',
+ description: 'data:image/...;base64 URL',
+ },
+ width: { type: 'number' },
+ height: { type: 'number' },
+ },
+ required: ['image', 'width', 'height'],
+ }),
+ default: errorResponse,
+ },
+ },
+ },
+ [`${basePath}/size`]: {
+ get: {
+ summary: 'Screen size in screenshot pixels',
+ responses: {
+ 200: json({
+ type: 'object',
+ properties: {
+ width: { type: 'number' },
+ height: { type: 'number' },
+ },
+ required: ['width', 'height'],
+ }),
+ default: errorResponse,
+ },
+ },
+ },
+ };
+ const ok = json({
+ type: 'object',
+ properties: { ok: { type: 'boolean' }, result: {} },
+ required: ['ok'],
+ });
+ for (const name of info.primitives) {
+ const spec = primitiveByName.get(name)!;
+ paths[`${basePath}/primitives/${name}`] = {
+ post: {
+ tags: ['primitives'],
+ summary: spec.description,
+ requestBody: {
+ required: true,
+ content: {
+ 'application/json': { schema: toOpenAPISchema(spec.body) },
+ },
+ },
+ responses: { 200: ok, default: errorResponse },
+ },
+ };
+ }
+ for (const action of info.actions) {
+ paths[`${basePath}/actions/${action.name}`] = {
+ post: {
+ tags: ['actions'],
+ summary: action.description,
+ requestBody: {
+ required: true,
+ content: {
+ 'application/json': {
+ schema: toOpenAPISchema(
+ action.params ?? { type: 'object', properties: {} },
+ ),
+ },
+ },
+ },
+ responses: { 200: ok, default: errorResponse },
+ },
+ };
+ }
+ return {
+ openapi: '3.1.0',
+ info: {
+ title: `${info.name} · Midscene Connect`,
+ version: info.protocol,
+ ...(info.description ? { description: info.description } : {}),
+ },
+ paths,
+ ...(secured
+ ? {
+ components: {
+ securitySchemes: { bearer: { type: 'http', scheme: 'bearer' } },
+ },
+ security: [{ bearer: [] }],
+ }
+ : {}),
+ };
+}
diff --git a/packages/connect/src/primitives.ts b/packages/connect/src/primitives.ts
new file mode 100644
index 0000000000..becc5d5d6b
--- /dev/null
+++ b/packages/connect/src/primitives.ts
@@ -0,0 +1,251 @@
+/**
+ * The built-in input primitives understood by the connect protocol.
+ * Names and call signatures mirror core's `InputPrimitives`, so the client can
+ * rebuild the standard action space with `defineActionsFromInputPrimitives`.
+ */
+import {
+ type ObjectParamSchema,
+ type ParamSchema,
+ locatedElementSchema,
+ pointSchema,
+ toLocatedElement,
+} from './schema';
+
+export type PrimitiveGroup =
+ | 'pointer'
+ | 'touch'
+ | 'keyboard'
+ | 'scroll'
+ | 'system';
+
+export interface PrimitiveSpec {
+ name: string;
+ group: PrimitiveGroup;
+ description: string;
+ body: ObjectParamSchema;
+ /** Client: core call arguments -> JSON body. */
+ toBody(...args: any[]): Record;
+ /** Server: JSON body -> call arguments for the device implementation. */
+ toArgs(body: Record): unknown[];
+}
+
+const obj = (
+ properties: Record,
+ required: string[] = [],
+): ObjectParamSchema => ({ type: 'object', properties, required });
+const duration: ParamSchema = {
+ type: 'number',
+ minimum: 0,
+ description: 'Duration in milliseconds',
+};
+const pick = (o: Record | undefined, keys: string[]) => {
+ const out: Record = {};
+ for (const key of keys) if (o?.[key] !== undefined) out[key] = o[key];
+ return out;
+};
+const point = (p: { x: number; y: number }) => ({ x: p.x, y: p.y });
+
+const pointOnly = (
+ name: string,
+ description: string,
+ group: PrimitiveGroup = 'pointer',
+): PrimitiveSpec => ({
+ name,
+ group,
+ description,
+ body: obj({ point: pointSchema }, ['point']),
+ toBody: (p) => ({ point: point(p) }),
+ toArgs: (b) => [b.point],
+});
+
+const noArgs = (name: string, description: string): PrimitiveSpec => ({
+ name,
+ group: 'system',
+ description,
+ body: obj({}),
+ toBody: () => ({}),
+ toArgs: () => [],
+});
+
+export const primitiveSpecs: PrimitiveSpec[] = [
+ {
+ name: 'tap',
+ group: 'pointer',
+ description: 'Tap or click at a point. Required for any pointer input.',
+ body: obj({ point: pointSchema, duration }, ['point']),
+ toBody: (p, opts) => ({ point: point(p), ...pick(opts, ['duration']) }),
+ toArgs: (b) => [b.point, pick(b, ['duration'])],
+ },
+ pointOnly('doubleClick', 'Double-tap or double-click at a point.'),
+ pointOnly('rightClick', 'Right-click at a point.'),
+ pointOnly('middleClick', 'Middle-click at a point.'),
+ pointOnly('hover', 'Move the pointer over a point.'),
+ {
+ name: 'longPress',
+ group: 'pointer',
+ description: 'Press and hold at a point.',
+ body: obj({ point: pointSchema, duration }, ['point']),
+ toBody: (p, opts) => ({ point: point(p), ...pick(opts, ['duration']) }),
+ toArgs: (b) => [b.point, pick(b, ['duration'])],
+ },
+ {
+ name: 'dragAndDrop',
+ group: 'pointer',
+ description: 'Drag from one point and drop at another.',
+ body: obj({ from: pointSchema, to: pointSchema }, ['from', 'to']),
+ toBody: (from, to) => ({ from: point(from), to: point(to) }),
+ toArgs: (b) => [b.from, b.to],
+ },
+ {
+ name: 'swipe',
+ // Mapped to `touch.swipe` or `pointer.swipe` depending on `pointerType`.
+ group: 'touch',
+ description: 'Swipe from one point to another.',
+ body: obj(
+ {
+ from: pointSchema,
+ to: pointSchema,
+ duration,
+ repeat: { type: 'integer', minimum: 1 },
+ },
+ ['from', 'to'],
+ ),
+ toBody: (from, to, opts) => ({
+ from: point(from),
+ to: point(to),
+ ...pick(opts, ['duration', 'repeat']),
+ }),
+ toArgs: (b) => [b.from, b.to, pick(b, ['duration', 'repeat'])],
+ },
+ {
+ name: 'pinch',
+ group: 'touch',
+ description:
+ 'Two-finger pinch around a center point. Requires a touch swipe.',
+ body: obj(
+ {
+ center: pointSchema,
+ startDistance: { type: 'number' },
+ endDistance: { type: 'number' },
+ duration,
+ },
+ ['center', 'startDistance', 'endDistance', 'duration'],
+ ),
+ toBody: (center, opts) => ({
+ center: point(center),
+ ...pick(opts, ['startDistance', 'endDistance', 'duration']),
+ }),
+ toArgs: (b) => [
+ b.center,
+ pick(b, ['startDistance', 'endDistance', 'duration']),
+ ],
+ },
+ {
+ name: 'typeText',
+ group: 'keyboard',
+ description:
+ 'Type text into the focused input. typeText, keyboardPress and clearInput must be provided together.',
+ body: obj(
+ {
+ text: { type: 'string' },
+ replace: { type: 'boolean' },
+ focusOnly: { type: 'boolean' },
+ autoDismissKeyboard: { type: 'boolean' },
+ },
+ ['text'],
+ ),
+ toBody: (text, opts) => ({
+ text,
+ ...pick(opts, ['replace', 'focusOnly', 'autoDismissKeyboard']),
+ }),
+ toArgs: (b) => [
+ b.text,
+ pick(b, ['replace', 'focusOnly', 'autoDismissKeyboard']),
+ ],
+ },
+ {
+ name: 'keyboardPress',
+ group: 'keyboard',
+ description: 'Press a key or key combination, e.g. "Enter" or "Control+A".',
+ body: obj({ key: { type: 'string', minLength: 1 } }, ['key']),
+ toBody: (key) => ({ key }),
+ toArgs: (b) => [b.key],
+ },
+ {
+ name: 'clearInput',
+ group: 'keyboard',
+ description: 'Clear the focused input.',
+ body: obj({}),
+ toBody: () => ({}),
+ toArgs: () => [],
+ },
+ {
+ name: 'cursorMove',
+ group: 'keyboard',
+ description: 'Move the text cursor left or right.',
+ body: obj(
+ {
+ direction: { type: 'string', enum: ['left', 'right'] },
+ times: { type: 'integer', minimum: 1 },
+ },
+ ['direction'],
+ ),
+ toBody: (direction, times) => ({
+ direction,
+ ...(times === undefined ? {} : { times }),
+ }),
+ toArgs: (b) => [b.direction, b.times],
+ },
+ {
+ name: 'scroll',
+ group: 'scroll',
+ description: 'Scroll the screen or the located region.',
+ body: obj({
+ direction: { type: 'string', enum: ['up', 'down', 'left', 'right'] },
+ scrollType: {
+ type: 'string',
+ enum: [
+ 'singleAction',
+ 'scrollToBottom',
+ 'scrollToTop',
+ 'scrollToRight',
+ 'scrollToLeft',
+ ],
+ },
+ distance: { type: 'number' },
+ locate: locatedElementSchema,
+ }),
+ toBody: (param) => ({
+ ...pick(param, ['direction', 'scrollType']),
+ ...(typeof param?.distance === 'number'
+ ? { distance: param.distance }
+ : {}),
+ ...(param?.locate ? { locate: toLocatedElement(param.locate) } : {}),
+ }),
+ toArgs: (b) => [b],
+ },
+ noArgs('backButton', 'Trigger the system "back" operation.'),
+ noArgs('homeButton', 'Go to the home screen.'),
+ noArgs('recentAppsButton', 'Open the recent apps view.'),
+];
+
+export const primitiveByName = new Map(primitiveSpecs.map((p) => [p.name, p]));
+
+/** Action names the client registers for system primitives. */
+export const systemActionConfigs = {
+ backButton: {
+ name: 'BackButton',
+ supportedBySystemOne: true,
+ description: 'Trigger the system "back" operation on the device',
+ },
+ homeButton: {
+ name: 'HomeButton',
+ supportedBySystemOne: true,
+ description: 'Go to the home screen of the device',
+ },
+ recentAppsButton: {
+ name: 'RecentAppsButton',
+ supportedBySystemOne: true,
+ description: 'Open the recent apps view of the device',
+ },
+};
diff --git a/packages/connect/src/schema.ts b/packages/connect/src/schema.ts
new file mode 100644
index 0000000000..de136c1e8e
--- /dev/null
+++ b/packages/connect/src/schema.ts
@@ -0,0 +1,337 @@
+/**
+ * A deliberately small JSON Schema subset used for custom action params,
+ * device options and the wire protocol. Anything outside the subset is
+ * rejected up front instead of being half-supported.
+ */
+import { getMidsceneLocationSchema, z } from '@midscene/core';
+
+export const LOCATE_KEYWORD = 'x-midscene-locate';
+
+export type ParamSchema =
+ | {
+ type: 'string';
+ description?: string;
+ enum?: string[];
+ minLength?: number;
+ maxLength?: number;
+ }
+ | {
+ type: 'number' | 'integer';
+ description?: string;
+ minimum?: number;
+ maximum?: number;
+ }
+ | { type: 'boolean'; description?: string }
+ | {
+ type: 'array';
+ description?: string;
+ items: ParamSchema;
+ minItems?: number;
+ maxItems?: number;
+ }
+ | ObjectParamSchema
+ | LocateParamSchema;
+
+export interface ObjectParamSchema {
+ type: 'object';
+ description?: string;
+ properties: Record;
+ required?: string[];
+}
+
+/** An element the AI should locate on screen; resolved on the client side. */
+export interface LocateParamSchema {
+ [LOCATE_KEYWORD]: true;
+ description?: string;
+}
+
+/** The wire form of a located element. */
+export interface LocatedElement {
+ description: string;
+ center: [number, number];
+ rect: { left: number; top: number; width: number; height: number };
+}
+
+export class SchemaError extends Error {}
+
+const allowedKeys: Record = {
+ string: ['type', 'description', 'enum', 'minLength', 'maxLength'],
+ number: ['type', 'description', 'minimum', 'maximum'],
+ integer: ['type', 'description', 'minimum', 'maximum'],
+ boolean: ['type', 'description'],
+ array: ['type', 'description', 'items', 'minItems', 'maxItems'],
+ object: ['type', 'description', 'properties', 'required'],
+ locate: [LOCATE_KEYWORD, 'description'],
+};
+
+export function isLocateSchema(
+ schema: ParamSchema,
+): schema is LocateParamSchema {
+ return (schema as LocateParamSchema)[LOCATE_KEYWORD] === true;
+}
+
+function isPlainObject(value: unknown): value is Record {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+/** Throw unless `schema` is inside the supported subset. */
+export function assertParamSchema(
+ schema: unknown,
+ path = 'schema',
+ { allowLocate = false } = {},
+): asserts schema is ParamSchema {
+ if (!isPlainObject(schema))
+ throw new SchemaError(`${path} must be an object`);
+ const kind =
+ schema[LOCATE_KEYWORD] === true ? 'locate' : (schema.type as string);
+ const keys = allowedKeys[kind];
+ if (!keys)
+ throw new SchemaError(
+ `${path}.type must be one of string, number, integer, boolean, array, object (got ${JSON.stringify(schema.type)})`,
+ );
+ for (const key of Object.keys(schema))
+ if (!keys.includes(key))
+ throw new SchemaError(`${path}.${key} is not supported for "${kind}"`);
+ if (
+ schema.description !== undefined &&
+ typeof schema.description !== 'string'
+ )
+ throw new SchemaError(`${path}.description must be a string`);
+ if (kind === 'locate' && !allowLocate)
+ throw new SchemaError(
+ `${path}: "${LOCATE_KEYWORD}" is only allowed on top-level properties of action params`,
+ );
+ if (kind === 'string' && schema.enum !== undefined) {
+ if (
+ !Array.isArray(schema.enum) ||
+ !schema.enum.length ||
+ schema.enum.some((v) => typeof v !== 'string')
+ )
+ throw new SchemaError(`${path}.enum must be a non-empty string array`);
+ }
+ for (const key of [
+ 'minLength',
+ 'maxLength',
+ 'minimum',
+ 'maximum',
+ 'minItems',
+ 'maxItems',
+ ])
+ if (schema[key] !== undefined && typeof schema[key] !== 'number')
+ throw new SchemaError(`${path}.${key} must be a number`);
+ if (kind === 'array') assertParamSchema(schema.items, `${path}.items`);
+ if (kind === 'object') {
+ if (!isPlainObject(schema.properties))
+ throw new SchemaError(`${path}.properties must be an object`);
+ for (const [name, prop] of Object.entries(schema.properties))
+ assertParamSchema(prop, `${path}.properties.${name}`, {
+ allowLocate: path === 'params',
+ });
+ if (schema.required !== undefined) {
+ if (
+ !Array.isArray(schema.required) ||
+ schema.required.some(
+ (name) =>
+ typeof name !== 'string' ||
+ !(name in (schema.properties as object)),
+ )
+ )
+ throw new SchemaError(
+ `${path}.required must list names declared in properties`,
+ );
+ }
+ }
+}
+
+/** Strictly validate `value`; unknown object keys are rejected. */
+export function validateValue(
+ schema: ParamSchema,
+ value: unknown,
+ path = 'value',
+): void {
+ const fail = (message: string): never => {
+ throw new SchemaError(`${path} ${message}`);
+ };
+ if (isLocateSchema(schema)) {
+ if (!isPlainObject(value)) fail('must be a located element');
+ validateValue(locatedElementSchema, value, path);
+ return;
+ }
+ switch (schema.type) {
+ case 'string':
+ if (typeof value !== 'string') fail('must be a string');
+ if (schema.enum && !schema.enum.includes(value as string))
+ fail(`must be one of ${schema.enum.join(', ')}`);
+ if (
+ schema.minLength !== undefined &&
+ (value as string).length < schema.minLength
+ )
+ fail(`must have at least ${schema.minLength} characters`);
+ if (
+ schema.maxLength !== undefined &&
+ (value as string).length > schema.maxLength
+ )
+ fail(`must have at most ${schema.maxLength} characters`);
+ return;
+ case 'number':
+ case 'integer':
+ if (typeof value !== 'number' || !Number.isFinite(value))
+ fail('must be a finite number');
+ if (schema.type === 'integer' && !Number.isInteger(value))
+ fail('must be an integer');
+ if (schema.minimum !== undefined && (value as number) < schema.minimum)
+ fail(`must be >= ${schema.minimum}`);
+ if (schema.maximum !== undefined && (value as number) > schema.maximum)
+ fail(`must be <= ${schema.maximum}`);
+ return;
+ case 'boolean':
+ if (typeof value !== 'boolean') fail('must be a boolean');
+ return;
+ case 'array': {
+ if (!Array.isArray(value)) fail('must be an array');
+ const list = value as unknown[];
+ if (schema.minItems !== undefined && list.length < schema.minItems)
+ fail(`must have at least ${schema.minItems} items`);
+ if (schema.maxItems !== undefined && list.length > schema.maxItems)
+ fail(`must have at most ${schema.maxItems} items`);
+ list.forEach((item, i) =>
+ validateValue(schema.items, item, `${path}[${i}]`),
+ );
+ return;
+ }
+ case 'object': {
+ if (!isPlainObject(value)) fail('must be an object');
+ const record = value as Record;
+ for (const key of Object.keys(record))
+ if (!(key in schema.properties)) fail(`has unknown property "${key}"`);
+ for (const name of schema.required ?? [])
+ if (record[name] === undefined) fail(`is missing "${name}"`);
+ for (const [name, prop] of Object.entries(schema.properties))
+ if (record[name] !== undefined)
+ validateValue(prop, record[name], `${path}.${name}`);
+ return;
+ }
+ }
+}
+
+const num = { type: 'number' } as const;
+export const pointSchema: ObjectParamSchema = {
+ type: 'object',
+ properties: { x: num, y: num },
+ required: ['x', 'y'],
+};
+export const locatedElementSchema: ObjectParamSchema = {
+ type: 'object',
+ description: 'An element located on the screenshot',
+ properties: {
+ description: { type: 'string' },
+ center: { type: 'array', items: num, minItems: 2, maxItems: 2 },
+ rect: {
+ type: 'object',
+ properties: { left: num, top: num, width: num, height: num },
+ required: ['left', 'top', 'width', 'height'],
+ },
+ },
+ required: ['center', 'rect'],
+};
+
+/** Reduce a core locate result to the plain wire shape. */
+export function toLocatedElement(value: any): LocatedElement {
+ const { left, top, width, height } = value.rect;
+ return {
+ description: value.description ?? '',
+ center: [value.center[0], value.center[1]],
+ rect: { left, top, width, height },
+ };
+}
+
+/** Strip locate results in action params down to their wire shape. */
+export function paramsToWire(
+ schema: ObjectParamSchema | undefined,
+ params: unknown,
+): Record {
+ if (!schema) return {};
+ const record = { ...((params ?? {}) as Record) };
+ for (const [name, prop] of Object.entries(schema.properties))
+ if (isLocateSchema(prop) && record[name] != null)
+ record[name] = toLocatedElement(record[name]);
+ for (const key of Object.keys(record))
+ if (!(key in schema.properties) || record[key] === undefined)
+ delete record[key];
+ return record;
+}
+
+/** Convert the subset into the zod shape consumed by core planning. */
+export function toZod(schema: ParamSchema): z.ZodTypeAny {
+ let type: z.ZodTypeAny;
+ if (isLocateSchema(schema)) {
+ type = getMidsceneLocationSchema();
+ } else {
+ switch (schema.type) {
+ case 'string': {
+ let s = schema.enum
+ ? z.enum(schema.enum as [string, ...string[]])
+ : z.string();
+ if (!schema.enum && schema.minLength !== undefined)
+ s = (s as z.ZodString).min(schema.minLength);
+ if (!schema.enum && schema.maxLength !== undefined)
+ s = (s as z.ZodString).max(schema.maxLength);
+ type = s;
+ break;
+ }
+ case 'number':
+ case 'integer': {
+ let n = z.number();
+ if (schema.type === 'integer') n = n.int();
+ if (schema.minimum !== undefined) n = n.min(schema.minimum);
+ if (schema.maximum !== undefined) n = n.max(schema.maximum);
+ type = n;
+ break;
+ }
+ case 'boolean':
+ type = z.boolean();
+ break;
+ case 'array': {
+ let a = z.array(toZod(schema.items));
+ if (schema.minItems !== undefined) a = a.min(schema.minItems);
+ if (schema.maxItems !== undefined) a = a.max(schema.maxItems);
+ type = a;
+ break;
+ }
+ case 'object': {
+ const required = new Set(schema.required ?? []);
+ type = z.object(
+ Object.fromEntries(
+ Object.entries(schema.properties).map(([name, prop]) => {
+ const field = toZod(prop);
+ return [name, required.has(name) ? field : field.optional()];
+ }),
+ ),
+ );
+ break;
+ }
+ }
+ }
+ return schema.description ? type.describe(schema.description) : type;
+}
+
+/** Coerce a raw CLI string into the type a schema expects. */
+export function coerceCliValue(schema: ParamSchema, raw: string): unknown {
+ if (isLocateSchema(schema)) return raw;
+ switch (schema.type) {
+ case 'number':
+ case 'integer':
+ return raw.trim() === '' ? raw : Number(raw);
+ case 'boolean':
+ return raw === 'true' ? true : raw === 'false' ? false : raw;
+ case 'array':
+ case 'object':
+ try {
+ return JSON.parse(raw);
+ } catch {
+ return raw;
+ }
+ default:
+ return raw;
+ }
+}
diff --git a/packages/connect/src/server.ts b/packages/connect/src/server.ts
new file mode 100644
index 0000000000..f51b3c3824
--- /dev/null
+++ b/packages/connect/src/server.ts
@@ -0,0 +1,383 @@
+import { randomBytes, timingSafeEqual } from 'node:crypto';
+import { readFile } from 'node:fs/promises';
+import {
+ type IncomingMessage,
+ type Server,
+ type ServerResponse,
+ createServer,
+} from 'node:http';
+import { createRequire } from 'node:module';
+import { dirname, join } from 'node:path';
+import { getDebug } from '@midscene/shared/logger';
+import {
+ type ConnectDevice,
+ DEFAULT_CONNECT_PORT,
+ type DeviceDefinition,
+ type PreparedDevice,
+ prepareDevice,
+} from './device';
+import { buildOpenAPI } from './openapi';
+import { primitiveByName } from './primitives';
+import { SchemaError, assertParamSchema, validateValue } from './schema';
+
+export { DEFAULT_CONNECT_PORT } from './device';
+export type {
+ ConnectDevice,
+ ConnectInfo,
+ CustomAction,
+ DeviceConnection,
+ DeviceDefinition,
+} from './device';
+
+const debug = getDebug('connect:server', { console: true });
+const maxBodyBytes = 1024 * 1024;
+
+export interface ConnectHandlerOptions {
+ /** Require `Authorization: Bearer ` on API routes. */
+ token?: string;
+ /** Route prefix, useful when embedding into an existing server. */
+ basePath?: string;
+}
+
+class HttpError extends Error {
+ constructor(
+ readonly status: number,
+ readonly code: string,
+ message: string,
+ ) {
+ super(message);
+ }
+}
+
+function readJson(req: IncomingMessage): Promise {
+ return new Promise((resolve, reject) => {
+ const chunks: Buffer[] = [];
+ let size = 0;
+ req.on('data', (chunk: Buffer) => {
+ size += chunk.length;
+ if (size > maxBodyBytes) {
+ reject(
+ new HttpError(413, 'PAYLOAD_TOO_LARGE', 'Request body is too large'),
+ );
+ req.destroy();
+ } else chunks.push(chunk);
+ });
+ req.on('end', () => {
+ const text = Buffer.concat(chunks).toString('utf8').trim();
+ if (!text) return resolve({});
+ try {
+ resolve(JSON.parse(text));
+ } catch {
+ reject(
+ new HttpError(400, 'INVALID_REQUEST', 'Request body must be JSON'),
+ );
+ }
+ });
+ req.on('error', reject);
+ });
+}
+
+let swaggerDir: string | undefined;
+function swaggerAssetDir() {
+ swaggerDir ??= dirname(
+ createRequire(import.meta.url).resolve('swagger-ui-dist/package.json'),
+ );
+ return swaggerDir;
+}
+const swaggerAssets: Record = {
+ 'swagger-ui.css': 'text/css; charset=utf-8',
+ 'swagger-ui-bundle.js': 'text/javascript; charset=utf-8',
+ 'favicon-32x32.png': 'image/png',
+};
+const docsHtml = (title: string) => `
+${title.replace(/
+
+
+`;
+
+/**
+ * Expose a device over the Midscene Connect protocol.
+ * `handle()` returns `false` for requests outside `basePath` so callers can
+ * mount it next to their own routes.
+ */
+export function createConnectHandler(
+ device: ConnectDevice | PreparedDevice,
+ options: ConnectHandlerOptions = {},
+) {
+ const prepared =
+ 'info' in device &&
+ 'primitives' in device &&
+ device.primitives instanceof Map
+ ? (device as PreparedDevice)
+ : prepareDevice(device as ConnectDevice);
+ const basePath = (options.basePath ?? '/api').replace(/\/+$/, '');
+ const token = options.token
+ ? Buffer.from(`Bearer ${options.token}`)
+ : undefined;
+ const openAPI = JSON.stringify(
+ buildOpenAPI(prepared.info, { basePath, secured: Boolean(token) }),
+ );
+ let queue: Promise = Promise.resolve();
+ const serial = (task: () => Promise): Promise => {
+ const run = queue.then(task);
+ queue = run.catch(() => {});
+ return run;
+ };
+
+ const invoke = async (name: string, call: () => unknown) => {
+ try {
+ return await serial(async () => call());
+ } catch (error) {
+ debug(`action ${name} failed:`, error);
+ throw new HttpError(
+ 500,
+ 'ACTION_FAILED',
+ `${name} failed: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ };
+
+ async function route(req: IncomingMessage, path: string) {
+ const method = req.method ?? 'GET';
+ if (method === 'GET' && path === '/info') return prepared.info;
+ if (method === 'GET' && path === '/screenshot')
+ return prepared.screenshot();
+ if (method === 'GET' && path === '/size') return prepared.size();
+ const match = /^\/(primitives|actions)\/([^/]+)$/.exec(path);
+ if (!match)
+ throw new HttpError(404, 'NOT_FOUND', `No route for ${method} ${path}`);
+ if (method !== 'POST')
+ throw new HttpError(
+ 405,
+ 'METHOD_NOT_ALLOWED',
+ `${path} only accepts POST`,
+ );
+ const [, kind, name] = match;
+ const body = await readJson(req);
+ if (kind === 'primitives') {
+ const spec = primitiveByName.get(name);
+ const fn = prepared.primitives.get(name);
+ if (!spec || !fn)
+ throw new HttpError(
+ 404,
+ 'NOT_FOUND',
+ `Primitive "${name}" is not supported by this device`,
+ );
+ validate(spec.body, body);
+ await invoke(name, () =>
+ fn(...spec.toArgs(body as Record)),
+ );
+ return { ok: true };
+ }
+ const action = prepared.actions.get(name);
+ if (!action)
+ throw new HttpError(404, 'NOT_FOUND', `Action "${name}" is not defined`);
+ validate(action.params ?? { type: 'object', properties: {} }, body);
+ const result = await invoke(name, () => action.call(body));
+ return { ok: true, ...(result === undefined ? {} : { result }) };
+ }
+
+ function validate(
+ schema: Parameters[0],
+ body: unknown,
+ ) {
+ try {
+ validateValue(schema, body, 'body');
+ } catch (error) {
+ if (error instanceof SchemaError)
+ throw new HttpError(400, 'INVALID_REQUEST', error.message);
+ throw error;
+ }
+ }
+
+ function serveDocs(req: IncomingMessage, res: ServerResponse, path: string) {
+ if (path === '/openapi.json') {
+ res.writeHead(200, { 'Content-Type': 'application/json' });
+ return res.end(openAPI);
+ }
+ if (path === '/docs') {
+ res.writeHead(308, { Location: `${basePath}/docs/` });
+ return res.end();
+ }
+ const file = path.slice('/docs/'.length);
+ if (!file) {
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
+ return res.end(docsHtml(prepared.info.name));
+ }
+ if (file === 'init.js') {
+ res.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8' });
+ return res.end(
+ `SwaggerUIBundle({ url: ${JSON.stringify(`${basePath}/openapi.json`)}, dom_id: '#swagger-ui', validatorUrl: null, persistAuthorization: true });`,
+ );
+ }
+ const type = swaggerAssets[file];
+ if (!type) {
+ res.writeHead(404).end();
+ return;
+ }
+ void readFile(join(swaggerAssetDir(), file)).then(
+ (data) => {
+ res.writeHead(200, {
+ 'Content-Type': type,
+ 'Cache-Control': 'max-age=3600',
+ });
+ res.end(data);
+ },
+ () => res.writeHead(500).end('Swagger UI asset unavailable'),
+ );
+ }
+
+ function handle(req: IncomingMessage, res: ServerResponse): boolean {
+ let pathname: string;
+ try {
+ pathname = new URL(req.url ?? '/', 'http://localhost').pathname;
+ } catch {
+ return false;
+ }
+ if (pathname !== basePath && !pathname.startsWith(`${basePath}/`))
+ return false;
+ const path = pathname.slice(basePath.length) || '/';
+ if (
+ req.method === 'GET' &&
+ (path === '/openapi.json' ||
+ path === '/docs' ||
+ path.startsWith('/docs/'))
+ ) {
+ serveDocs(req, res, path);
+ return true;
+ }
+ const send = (status: number, body: unknown) => {
+ if (res.headersSent || res.destroyed) return;
+ res.writeHead(status, {
+ 'Content-Type': 'application/json',
+ 'Cache-Control': 'no-store',
+ });
+ res.end(JSON.stringify(body));
+ };
+ if (token) {
+ const supplied = Buffer.from(req.headers.authorization ?? '');
+ if (
+ supplied.length !== token.length ||
+ !timingSafeEqual(supplied, token)
+ ) {
+ res.setHeader('WWW-Authenticate', 'Bearer');
+ send(401, {
+ error: 'A valid bearer token is required',
+ code: 'UNAUTHORIZED',
+ });
+ return true;
+ }
+ }
+ route(req, path).then(
+ (body) => send(200, body),
+ (error) => {
+ if (error instanceof HttpError)
+ send(error.status, { error: error.message, code: error.code });
+ else {
+ debug('request failed:', error);
+ send(500, {
+ error: error instanceof Error ? error.message : String(error),
+ code: 'INTERNAL_ERROR',
+ });
+ }
+ },
+ );
+ return true;
+ }
+
+ return { handle, info: prepared.info, close: () => prepared.destroy() };
+}
+
+export interface ServeOptions {
+ port?: number;
+ /** Defaults to 127.0.0.1. A token is required for non-loopback hosts. */
+ host?: string;
+ token?: string;
+ /** Instance options passed to `definition.connect()`. */
+ options?: Record;
+}
+
+const loopbackHosts = new Set(['127.0.0.1', 'localhost', '::1']);
+
+/** Validate options, connect the device and start an HTTP server for it. */
+export async function serveDevice(
+ definition: DeviceDefinition,
+ serveOptions: ServeOptions = {},
+): Promise<{
+ server: Server;
+ url: string;
+ token?: string;
+ close(): Promise;
+}> {
+ if (!definition || typeof definition.connect !== 'function')
+ throw new Error('A device definition must provide connect(options)');
+ const instanceOptions = serveOptions.options ?? {};
+ if (definition.options) {
+ assertParamSchema(definition.options, 'options');
+ if (definition.options.type !== 'object')
+ throw new Error("Device options must be { type: 'object', ... }");
+ validateValue(definition.options, instanceOptions, 'options');
+ } else if (Object.keys(instanceOptions).length)
+ throw new Error(
+ `Device "${definition.name}" does not declare options, got: ${Object.keys(instanceOptions).join(', ')}`,
+ );
+
+ const host = serveOptions.host ?? '127.0.0.1';
+ const token =
+ serveOptions.token ??
+ (loopbackHosts.has(host)
+ ? undefined
+ : randomBytes(18).toString('base64url'));
+
+ const connection = await definition.connect(instanceOptions);
+ let prepared: PreparedDevice;
+ try {
+ prepared = prepareDevice({
+ name: definition.name,
+ description: definition.description,
+ pointerType: definition.pointerType,
+ ...connection,
+ });
+ } catch (error) {
+ await connection?.destroy?.();
+ throw error;
+ }
+ const handler = createConnectHandler(prepared, { token });
+ const server = createServer((req, res) => {
+ const path = new URL(req.url ?? '/', 'http://localhost').pathname;
+ if (path === '/') {
+ res.writeHead(302, { Location: '/api/docs/' }).end();
+ return;
+ }
+ if (!handler.handle(req, res)) res.writeHead(404).end();
+ });
+ await new Promise((resolve, reject) => {
+ server.once('error', reject);
+ server.listen(serveOptions.port ?? DEFAULT_CONNECT_PORT, host, () =>
+ resolve(),
+ );
+ });
+ const address = server.address();
+ const port =
+ typeof address === 'object' && address ? address.port : serveOptions.port;
+ const urlHost = host.includes(':') ? `[${host}]` : host;
+ let closing: Promise | undefined;
+ return {
+ server,
+ url: `http://${urlHost}:${port}`,
+ token,
+ close: () => {
+ if (!closing) {
+ closing = (async () => {
+ const closed = new Promise((resolve) =>
+ server.close(() => resolve()),
+ );
+ server.closeAllConnections?.();
+ await closed;
+ await handler.close();
+ })();
+ }
+ return closing;
+ },
+ };
+}
diff --git a/packages/connect/src/tools.ts b/packages/connect/src/tools.ts
new file mode 100644
index 0000000000..da2f9f5c4b
--- /dev/null
+++ b/packages/connect/src/tools.ts
@@ -0,0 +1,133 @@
+import { z } from '@midscene/core';
+import type { Agent } from '@midscene/core/agent';
+import {
+ type AgentBehaviorInitArgs,
+ agentBehaviorInitArgShape,
+ extractAgentBehaviorInitArgs,
+ getAgentInitArgsSignature,
+ shouldRebuildAgentForInitArgs,
+} from '@midscene/shared/agent-tools/agent-behavior-init-args';
+import {
+ BaseMidsceneTools,
+ type InitArgSpec,
+} from '@midscene/shared/agent-tools/base-tools';
+import type { ToolDefinition } from '@midscene/shared/agent-tools/types';
+import { getDebug } from '@midscene/shared/logger';
+import { type RemoteDevice, agentOverConnectProtocol } from './client';
+
+const debug = getDebug('connect:tools');
+
+type ConnectInitArgs = AgentBehaviorInitArgs & { url?: string; token?: string };
+
+/** CLI tools generated from the action space of a served device. */
+export class ConnectMidsceneTools extends BaseMidsceneTools<
+ Agent,
+ ConnectInitArgs
+> {
+ private lastInitArgsSignature?: string;
+
+ constructor(
+ /** Device fetched before tool generation; undefined when unreachable. */
+ private readonly device: RemoteDevice | undefined,
+ ) {
+ super();
+ }
+
+ protected getCliReportSessionName() {
+ return 'midscene-connect';
+ }
+
+ protected readonly initArgSpec: InitArgSpec = {
+ namespace: 'connect',
+ shape: {
+ url: z
+ .string()
+ .optional()
+ .describe(
+ 'Device URL printed by `midscene-connect serve` (env: MIDSCENE_CONNECT_URL)',
+ ),
+ token: z
+ .string()
+ .optional()
+ .describe('Device access token (env: MIDSCENE_CONNECT_TOKEN)'),
+ ...agentBehaviorInitArgShape,
+ },
+ cli: { preferBareKeys: true },
+ adapt: (extracted) => {
+ if (!extracted) return undefined;
+ const args: ConnectInitArgs = {
+ ...(typeof extracted.url === 'string' ? { url: extracted.url } : {}),
+ ...(typeof extracted.token === 'string'
+ ? { token: extracted.token }
+ : {}),
+ ...(extractAgentBehaviorInitArgs(extracted as AgentBehaviorInitArgs) ??
+ {}),
+ };
+ return Object.keys(args).length ? args : undefined;
+ },
+ };
+
+ protected createTemporaryDevice() {
+ return this.device ?? { actionSpace: () => [] };
+ }
+
+ protected async ensureAgent(initArgs?: ConnectInitArgs) {
+ const signature = getAgentInitArgsSignature(initArgs);
+ if (
+ this.agent &&
+ shouldRebuildAgentForInitArgs(this.lastInitArgsSignature, signature)
+ ) {
+ await this.agent
+ .destroy()
+ .catch((error) => debug('destroy failed:', error));
+ this.agent = undefined;
+ }
+ if (this.agent) return this.agent;
+ this.agent = await agentOverConnectProtocol({
+ url: initArgs?.url,
+ token: initArgs?.token,
+ agentOptions: {
+ ...(extractAgentBehaviorInitArgs(initArgs) ?? {}),
+ ...(this.readCliReportAgentOptions() ?? {}),
+ },
+ });
+ this.lastInitArgsSignature = signature;
+ return this.agent;
+ }
+
+ protected preparePlatformTools(): ToolDefinition[] {
+ return [
+ {
+ name: 'connect_connect',
+ description: 'Check the served device and start a new report session',
+ schema: this.getAgentInitArgSchema(),
+ cli: this.getAgentInitArgCliMetadata(),
+ handler: async (args: Record) => {
+ const initArgs = this.extractAgentInitParam(args);
+ this.commitCliReportSession(
+ this.createNewCliReportSession(initArgs?.url ?? 'default'),
+ );
+ if (this.agent) {
+ await this.agent
+ .destroy()
+ .catch((error) => debug('destroy failed:', error));
+ this.agent = undefined;
+ this.lastInitArgsSignature = undefined;
+ }
+ const agent = await this.ensureAgent(initArgs);
+ const screenshot = await agent.interface.screenshotBase64();
+ return {
+ content: [
+ {
+ type: 'text',
+ text: `Connected to ${agent.interface.describe()} at ${agent.interface.client.url}`,
+ },
+ ...this.buildScreenshotContent(screenshot),
+ ],
+ isError: false,
+ };
+ },
+ },
+ ];
+ }
+}
diff --git a/packages/connect/tests/fixtures/mock-device.mjs b/packages/connect/tests/fixtures/mock-device.mjs
new file mode 100644
index 0000000000..ce3299ce8f
--- /dev/null
+++ b/packages/connect/tests/fixtures/mock-device.mjs
@@ -0,0 +1,89 @@
+import { deflateSync } from 'node:zlib';
+
+/** Build a solid-color RGB PNG without extra dependencies. */
+export function solidPng(width, height, [r, g, b] = [32, 128, 224]) {
+ const crcTable = Array.from({ length: 256 }, (_, n) => {
+ let c = n;
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ return c >>> 0;
+ });
+ const crc = (buf) => {
+ let c = 0xffffffff;
+ for (const byte of buf) c = crcTable[(c ^ byte) & 0xff] ^ (c >>> 8);
+ return (c ^ 0xffffffff) >>> 0;
+ };
+ const chunk = (type, data) => {
+ const len = Buffer.alloc(4);
+ len.writeUInt32BE(data.length);
+ const body = Buffer.concat([Buffer.from(type), data]);
+ const sum = Buffer.alloc(4);
+ sum.writeUInt32BE(crc(body));
+ return Buffer.concat([len, body, sum]);
+ };
+ const header = Buffer.alloc(13);
+ header.writeUInt32BE(width, 0);
+ header.writeUInt32BE(height, 4);
+ header[8] = 8;
+ header[9] = 2;
+ const row = Buffer.concat([
+ Buffer.from([0]),
+ Buffer.alloc(width * 3).fill(Buffer.from([r, g, b])),
+ ]);
+ return Buffer.concat([
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ chunk('IHDR', header),
+ chunk('IDAT', deflateSync(Buffer.concat(Array(height).fill(row)))),
+ chunk('IEND', Buffer.alloc(0)),
+ ]);
+}
+
+/** A device that records every call; used by tests and as a docs example. */
+export default {
+ name: 'Mock Screen',
+ description: 'A fake touchscreen used for testing',
+ pointerType: 'touch',
+ options: {
+ type: 'object',
+ properties: {
+ width: { type: 'integer', minimum: 1 },
+ height: { type: 'integer', minimum: 1 },
+ },
+ },
+ connect({ width = 400, height = 300 } = {}) {
+ const calls = [];
+ globalThis.__mockDeviceCalls = calls;
+ const record =
+ (name) =>
+ (...args) => {
+ calls.push([name, ...args]);
+ };
+ return {
+ screenshot: () => solidPng(width, height),
+ actions: {
+ tap: record('tap'),
+ longPress: record('longPress'),
+ swipe: record('swipe'),
+ typeText: record('typeText'),
+ keyboardPress: record('keyboardPress'),
+ clearInput: record('clearInput'),
+ homeButton: record('homeButton'),
+ wakeVoiceAssistant: {
+ description: 'Wake up the voice assistant with a phrase',
+ params: {
+ type: 'object',
+ properties: {
+ phrase: { type: 'string', description: 'What to say' },
+ target: { 'x-midscene-locate': true, description: 'Mic button' },
+ },
+ required: ['phrase'],
+ },
+ call: (params) => {
+ calls.push(['wakeVoiceAssistant', params]);
+ return { heard: params.phrase };
+ },
+ },
+ },
+ destroy: record('destroy'),
+ };
+ },
+};
diff --git a/packages/connect/tests/unit/cli.test.ts b/packages/connect/tests/unit/cli.test.ts
new file mode 100644
index 0000000000..b3cfea186e
--- /dev/null
+++ b/packages/connect/tests/unit/cli.test.ts
@@ -0,0 +1,19 @@
+import { execFileSync } from 'node:child_process';
+import path from 'node:path';
+import { describe, expect, it } from '@rstest/core';
+
+describe('playground help', () => {
+ it.each(['--help', '-h'])('prints help offline with %s', (flag) => {
+ const cli = path.resolve(__dirname, '../../bin/midscene-connect');
+ const output = execFileSync(process.execPath, [cli, 'playground', flag], {
+ encoding: 'utf8',
+ env: { ...process.env, MIDSCENE_CONNECT_URL: 'invalid-url' },
+ timeout: 10_000,
+ });
+
+ expect(output).toContain('Usage: midscene-connect playground [options]');
+ for (const option of ['--url', '--token', '--port', '--no-open']) {
+ expect(output).toContain(option);
+ }
+ });
+});
diff --git a/packages/connect/tests/unit/device.test.ts b/packages/connect/tests/unit/device.test.ts
new file mode 100644
index 0000000000..8703afc89f
--- /dev/null
+++ b/packages/connect/tests/unit/device.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from '@rstest/core';
+import { type ConnectDevice, prepareDevice } from '../../src/device';
+
+const base = { name: 'Test', screenshot: () => Buffer.from('') };
+const fn = () => {};
+const prepare = (device: Partial) =>
+ prepareDevice({ ...base, ...device } as ConnectDevice);
+
+describe('prepareDevice', () => {
+ it('lists primitives and custom actions in /info', () => {
+ const { info } = prepare({
+ pointerType: 'touch',
+ actions: {
+ swipe: fn,
+ tap: fn,
+ reset: { description: 'Reset the arm', call: fn },
+ },
+ });
+ expect(info.primitives).toEqual(['tap', 'swipe']);
+ expect(info.actions).toEqual([
+ { name: 'reset', description: 'Reset the arm' },
+ ]);
+ });
+
+ it('rejects unknown functions and malformed custom actions', () => {
+ expect(() => prepare({ actions: { tapp: fn } })).toThrow(
+ /not a built-in primitive/,
+ );
+ expect(() =>
+ prepare({ actions: { tap: { description: 'x', call: fn } as any } }),
+ ).toThrow(/must be a function/);
+ expect(() => prepare({ actions: { reset: { call: fn } as any } })).toThrow(
+ /description is required/,
+ );
+ expect(() =>
+ prepare({
+ actions: {
+ reset: {
+ description: 'x',
+ call: fn,
+ params: { type: 'string' } as any,
+ },
+ },
+ }),
+ ).toThrow(/params must be/);
+ });
+
+ it('enforces primitive groups', () => {
+ expect(() => prepare({ actions: { typeText: fn } })).toThrow(
+ /provided together/,
+ );
+ expect(() => prepare({ actions: { tap: fn, swipe: fn } })).toThrow(
+ /pointerType/,
+ );
+ expect(() => prepare({ actions: { longPress: fn } })).toThrow(
+ /require tap/,
+ );
+ expect(() =>
+ prepare({
+ pointerType: 'mouse',
+ actions: { tap: fn, swipe: fn, pinch: fn },
+ }),
+ ).toThrow(/pinch requires/);
+ });
+
+ it('rejects screenshots that are not PNG or JPEG', async () => {
+ await expect(prepare({}).screenshot()).rejects.toThrow(/PNG/);
+ });
+});
diff --git a/packages/connect/tests/unit/schema.test.ts b/packages/connect/tests/unit/schema.test.ts
new file mode 100644
index 0000000000..4f90b84464
--- /dev/null
+++ b/packages/connect/tests/unit/schema.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from '@rstest/core';
+import {
+ type ObjectParamSchema,
+ SchemaError,
+ assertParamSchema,
+ paramsToWire,
+ toZod,
+ validateValue,
+} from '../../src/schema';
+
+describe('param schema subset', () => {
+ const params: ObjectParamSchema = {
+ type: 'object',
+ properties: {
+ phrase: { type: 'string', description: 'What to say' },
+ times: { type: 'integer', minimum: 1 },
+ target: { 'x-midscene-locate': true },
+ },
+ required: ['phrase'],
+ };
+
+ it('accepts the supported subset', () => {
+ expect(() => assertParamSchema(params, 'params')).not.toThrow();
+ });
+
+ it('rejects keywords outside the subset', () => {
+ expect(() =>
+ assertParamSchema(
+ { type: 'object', properties: {}, oneOf: [] },
+ 'params',
+ ),
+ ).toThrow(SchemaError);
+ expect(() => assertParamSchema({ type: 'null' }, 'params')).toThrow(
+ /type must be one of/,
+ );
+ expect(() =>
+ assertParamSchema(
+ { type: 'object', properties: {}, required: ['missing'] },
+ 'params',
+ ),
+ ).toThrow(/required/);
+ });
+
+ it('only allows locate markers on top-level action params', () => {
+ expect(() =>
+ assertParamSchema(
+ {
+ type: 'object',
+ properties: {
+ nested: {
+ type: 'object',
+ properties: { el: { 'x-midscene-locate': true } },
+ },
+ },
+ },
+ 'params',
+ ),
+ ).toThrow(/only allowed on top-level/);
+ });
+
+ it('validates values strictly', () => {
+ expect(() => validateValue(params, { phrase: 'hi' })).not.toThrow();
+ expect(() => validateValue(params, {})).toThrow(/missing "phrase"/);
+ expect(() => validateValue(params, { phrase: 'hi', extra: 1 })).toThrow(
+ /unknown property "extra"/,
+ );
+ expect(() => validateValue(params, { phrase: 'hi', times: 1.5 })).toThrow(
+ /integer/,
+ );
+ expect(() =>
+ validateValue(params, { phrase: 'hi', target: { center: [1, 2] } }),
+ ).toThrow(/missing "rect"/);
+ });
+
+ it('converts to zod for core planning', () => {
+ const schema = toZod(params) as any;
+ expect(schema.shape.phrase.description).toBe('What to say');
+ expect(schema.safeParse({ phrase: 'hi' }).success).toBe(true);
+ expect(schema.safeParse({ times: 2 }).success).toBe(false);
+ // locate fields reuse core's locator schema
+ expect(schema.shape.target.unwrap().shape.prompt).toBeDefined();
+ });
+
+ it('strips locate results to the wire shape', () => {
+ expect(
+ paramsToWire(params, {
+ phrase: 'hi',
+ target: {
+ description: 'mic',
+ center: [10, 20],
+ rect: { left: 0, top: 0, width: 20, height: 40, dpr: 2 },
+ xpaths: [],
+ },
+ ignored: true,
+ }),
+ ).toEqual({
+ phrase: 'hi',
+ target: {
+ description: 'mic',
+ center: [10, 20],
+ rect: { left: 0, top: 0, width: 20, height: 40 },
+ },
+ });
+ });
+});
diff --git a/packages/connect/tests/unit/serve.test.ts b/packages/connect/tests/unit/serve.test.ts
new file mode 100644
index 0000000000..367c3398e6
--- /dev/null
+++ b/packages/connect/tests/unit/serve.test.ts
@@ -0,0 +1,170 @@
+import { resolve } from 'node:path';
+import { afterAll, beforeAll, describe, expect, it } from '@rstest/core';
+import {
+ loadDefinition,
+ parseDeviceOptions,
+ parseFlags,
+} from '../../src/cli-utils';
+import {
+ ConnectClient,
+ RemoteDevice,
+ agentOverConnectProtocol,
+} from '../../src/client';
+import { serveDevice } from '../../src/server';
+
+const fixture = resolve(__dirname, '../fixtures/mock-device.mjs');
+const calls = () => (globalThis as any).__mockDeviceCalls as unknown[][];
+
+describe('serve + remote device', () => {
+ let served: Awaited>;
+ let device: RemoteDevice;
+
+ beforeAll(async () => {
+ const definition = await loadDefinition(fixture);
+ served = await serveDevice(definition, {
+ port: 0,
+ options: parseDeviceOptions(
+ definition,
+ parseFlags(['--width', '640', '--height=480']).flags,
+ ),
+ });
+ device = await RemoteDevice.connect({ url: served.url });
+ });
+ afterAll(async () => {
+ await served?.close();
+ });
+
+ it('rebuilds the action space from primitives and custom actions', () => {
+ const names = device.actionSpace().map((a) => a.name);
+ expect(names).toEqual(
+ expect.arrayContaining([
+ 'Tap',
+ 'LongPress',
+ 'Input',
+ 'KeyboardPress',
+ 'Swipe',
+ 'HomeButton',
+ 'wakeVoiceAssistant',
+ ]),
+ );
+ expect(names).not.toContain('DoubleClick');
+ });
+
+ it('reports screen size from the screenshot', async () => {
+ expect(await device.size()).toEqual({ width: 640, height: 480 });
+ expect(await device.screenshotBase64()).toMatch(/^data:image\/png;base64,/);
+ });
+
+ it('forwards built-in actions to device primitives', async () => {
+ const action = (name: string) =>
+ device.actionSpace().find((a) => a.name === name)!;
+ const locate = {
+ description: 'btn',
+ center: [100, 50] as [number, number],
+ rect: { left: 90, top: 40, width: 20, height: 20 },
+ };
+ await action('Tap').call({ locate });
+ await action('HomeButton').call(undefined);
+ await device.inputPrimitives.keyboard!.typeText('hello', {
+ replace: true,
+ target: {},
+ });
+ expect(calls()).toEqual(
+ expect.arrayContaining([
+ ['tap', { x: 100, y: 50 }, {}],
+ ['homeButton'],
+ ['typeText', 'hello', { replace: true }],
+ ]),
+ );
+ });
+
+ it('calls custom actions with wire params and returns results', async () => {
+ const action = device
+ .actionSpace()
+ .find((a) => a.name === 'wakeVoiceAssistant')!;
+ const result = await action.call({
+ phrase: 'hi',
+ target: {
+ description: 'mic',
+ center: [1, 2],
+ rect: { left: 0, top: 0, width: 2, height: 4 },
+ extra: true,
+ },
+ });
+ expect(result).toEqual({ heard: 'hi' });
+ expect(calls().at(-1)).toEqual([
+ 'wakeVoiceAssistant',
+ {
+ phrase: 'hi',
+ target: {
+ description: 'mic',
+ center: [1, 2],
+ rect: { left: 0, top: 0, width: 2, height: 4 },
+ },
+ },
+ ]);
+ });
+
+ it('rejects invalid bodies with 400', async () => {
+ const client = new ConnectClient({ url: served.url });
+ await expect(
+ client.request('POST', '/primitives/tap', { point: { x: 1 } }),
+ ).rejects.toMatchObject({
+ status: 400,
+ code: 'INVALID_REQUEST',
+ });
+ await expect(
+ client.request('POST', '/primitives/pinch', {}),
+ ).rejects.toMatchObject({ status: 404 });
+ });
+
+ it('serves OpenAPI for primitives and custom actions', async () => {
+ const res = await fetch(`${served.url}/api/openapi.json`);
+ const spec = await res.json();
+ expect(Object.keys(spec.paths)).toEqual(
+ expect.arrayContaining([
+ '/api/info',
+ '/api/primitives/tap',
+ '/api/actions/wakeVoiceAssistant',
+ ]),
+ );
+ expect((await fetch(`${served.url}/api/docs/`)).status).toBe(200);
+ });
+
+ it('injects the device description into the agent aiAct context', async () => {
+ const agent = await agentOverConnectProtocol({ url: served.url });
+ expect((agent as any).opts.aiContexts.aiAct).toBe(
+ 'A fake touchscreen used for testing',
+ );
+ await agent.destroy();
+ });
+});
+
+describe('serve options', () => {
+ it('rejects unknown and invalid device options', async () => {
+ const definition = await loadDefinition(fixture);
+ expect(() => parseDeviceOptions(definition, { color: 'red' })).toThrow(
+ /Unknown option --color/,
+ );
+ await expect(
+ serveDevice(definition, { port: 0, options: { width: 0 } }),
+ ).rejects.toThrow(/>= 1/);
+ });
+
+ it('requires a token when exposed beyond loopback', async () => {
+ const definition = await loadDefinition(fixture);
+ const served = await serveDevice(definition, { port: 0, host: '0.0.0.0' });
+ try {
+ expect(served.token).toBeTruthy();
+ const url = served.url.replace('0.0.0.0', '127.0.0.1');
+ await expect(new ConnectClient({ url }).info()).rejects.toMatchObject({
+ status: 401,
+ });
+ expect(
+ (await new ConnectClient({ url, token: served.token }).info()).name,
+ ).toBe('Mock Screen');
+ } finally {
+ await served.close();
+ }
+ });
+});
diff --git a/packages/connect/tsconfig.build.json b/packages/connect/tsconfig.build.json
new file mode 100644
index 0000000000..4c6923a527
--- /dev/null
+++ b/packages/connect/tsconfig.build.json
@@ -0,0 +1,8 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "rootDir": "src",
+ "module": "ES2020"
+ },
+ "include": ["src"]
+}
diff --git a/packages/connect/tsconfig.json b/packages/connect/tsconfig.json
new file mode 100644
index 0000000000..be457285f5
--- /dev/null
+++ b/packages/connect/tsconfig.json
@@ -0,0 +1,17 @@
+{
+ "extends": "../shared/tsconfig.base.json",
+ "compilerOptions": {
+ "rootDir": ".",
+ "declarationDir": "dist/types",
+ "types": ["node"],
+ "paths": {
+ "@/*": ["./src/*"]
+ }
+ },
+ "include": ["src", "tests"],
+ "references": [
+ { "path": "../core" },
+ { "path": "../shared" },
+ { "path": "../playground" }
+ ]
+}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6085b9a4b1..dd91ae6cb5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1042,6 +1042,37 @@ importers:
specifier: ^5.8.3
version: 5.9.3
+ packages/connect:
+ dependencies:
+ '@midscene/core':
+ specifier: workspace:*
+ version: link:../core
+ '@midscene/playground':
+ specifier: workspace:*
+ version: link:../playground
+ '@midscene/shared':
+ specifier: workspace:*
+ version: link:../shared
+ swagger-ui-dist:
+ specifier: ^5.32.0
+ version: 5.36.0
+ zod:
+ specifier: ^3.25.1
+ version: 3.25.76
+ devDependencies:
+ '@rslib/core':
+ specifier: ~0.19.6
+ version: 0.19.6(@microsoft/api-extractor@7.60.1(@types/node@18.19.130))(typescript@5.9.3)
+ '@rstest/core':
+ specifier: 0.12.0
+ version: 0.12.0(core-js@3.51.0)(jsdom@29.0.2(@noble/hashes@1.8.0))
+ '@types/node':
+ specifier: ^18.0.0
+ version: 18.19.130
+ typescript:
+ specifier: ^5.8.3
+ version: 5.9.3
+
packages/core:
dependencies:
'@midscene/shared':
@@ -3995,6 +4026,9 @@ packages:
resolution: {integrity: sha512-acP68tGx/DJEIQgTqj/xStBRaghN7axV+uAjNasDjVXgHgHaLQ1f16/bbXtw6mNLjURhTORD4fdfbOZM7kyWcw==}
engines: {node: '>=20.9.0'}
+ '@scarf/scarf@1.4.0':
+ resolution: {integrity: sha512-xxeapPiUXdZAE3che6f3xogoJPeZgig6omHEy1rIY5WVsB3H2BHNnZH+gHG6x91SCWyQCzWGsuL2Hh3ClO5/qQ==}
+
'@sec-ant/readable-stream@0.4.1':
resolution: {integrity: sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg==}
@@ -9399,6 +9433,9 @@ packages:
engines: {node: '>=14.0.0'}
hasBin: true
+ swagger-ui-dist@5.36.0:
+ resolution: {integrity: sha512-Lt6/Kb0gXmLdiabLhvso4VdJP9V7qJWB0zh0gzeXUV3+CMOTzMmvpJRSXN7EAjfwixwmoi9ezDbLHiexC7lA9A==}
+
swc-plugin-coverage-instrument@0.0.33:
resolution: {integrity: sha512-zM17DgG3jURPNOrEHye0MtrkrsZ9BtCMf3W5osQTHAtlNolfDUtZl7740wdx7XhUSL322qdph//DgHzZe62wHg==}
@@ -12785,6 +12822,8 @@ snapshots:
transitivePeerDependencies:
- '@types/node'
+ '@scarf/scarf@1.4.0': {}
+
'@sec-ant/readable-stream@0.4.1': {}
'@shikijs/core@4.6.0':
@@ -19329,6 +19368,10 @@ snapshots:
picocolors: 1.1.1
sax: 1.6.1
+ swagger-ui-dist@5.36.0:
+ dependencies:
+ '@scarf/scarf': 1.4.0
+
swc-plugin-coverage-instrument@0.0.33: {}
symbol-tree@3.2.4: {}