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

# RPA 工作流

> 将录制的浏览器操作发布为 MCP 工具，供 AI Agent 远程调用

# RPA 工作流

Zeus Desktop 支持将录制并参数化的浏览器操作工作流 **发布为标准的 MCP（JSON-RPC 2.0）工具**，让 AI Agent 能够像调用普通函数一样驱动浏览器执行业务操作。

## 概述

### 整体架构

```mermaid theme={null}
flowchart LR
    subgraph Cloud["云端 / AI Backend"]
        Agent["AI Agent"]
        WS["WebSocket Server"]
    end

    subgraph Desktop["终端 / Zeus Desktop"]
        WSC["WebSocket Client"]
        MCP["MCP Server\n(JSON-RPC 2.0)"]
        RE["CDP Replay Engine"]
        BR["Browser Reader"]
        HITL["HITL Manager"]
        Browser["Chrome Browser\n(Silent Mode)"]
    end

    Agent -->|"调用工具"| WS
    WS <-->|"WebSocket\n(终端主动连接)"| WSC
    WSC --> MCP
    MCP -->|"workflow_*"| RE
    MCP -->|"browser_read"| BR
    MCP -->|"hitl_prompt"| HITL
    RE --> Browser
    BR --> Browser
```

### 设计原则

| 原则          | 说明                           |
| ----------- | ---------------------------- |
| **终端不开放端口** | 所有通信通过终端主动建立的 WebSocket 连接完成 |
| **标准协议**    | 严格遵循 JSON-RPC 2.0 / MCP 协议规范 |
| **动态注册**    | 工作流发布后自动注册为可调用工具，无需重启        |
| **静默执行**    | 浏览器可在后台静默运行，不干扰用户            |
| **严格流程**    | 工作流按步骤顺序执行，不允许探索性操作          |

## 发布工作流为工具

### 发布流程

1. **完成录制**：录制浏览器操作并保存为工作流
2. **参数化**：将需要动态传入的值标记为变量（参见 [流程录制 - 参数化](/zh/desktop/recording#参数化)）
3. **发布工具**：在工作流编辑器中点击 **发布 Tool** 按钮
4. **配置元信息**：
   * **工具名称**（`toolName`）：Agent 调用时使用的标识，如 `query_power_data`
   * **工具描述**（`toolDescription`）：告诉 Agent 这个工具的用途
5. **确认发布**：保存后工具立即可用

### 发布对话框

发布对话框会自动提取工作流中所有参数化操作，生成工具参数列表：

| 字段   | 来源                 | 说明         |
| ---- | ------------------ | ---------- |
| 参数名  | `variableName`     | 变量名作为工具入参名 |
| 描述   | `paramDescription` | 参数用途说明     |
| 默认值  | `defaultValue`     | 可选的默认值     |
| 是否必填 | 无默认值 → 必填          | 无默认值的参数为必填 |

### 生成的工具定义

发布后，系统自动生成符合 MCP 规范的工具定义：

```json theme={null}
{
  "name": "workflow_query_power_data",
  "description": "登录电力系统并查询指定区域的用电数据",
  "inputSchema": {
    "type": "object",
    "properties": {
      "username": {
        "type": "string",
        "description": "登录用户名"
      },
      "password": {
        "type": "string",
        "description": "登录密码"
      },
      "region": {
        "type": "string",
        "description": "查询区域编码",
        "default": "110000"
      },
      "profileId": {
        "type": "string",
        "description": "Browser profile ID (optional override)"
      }
    },
    "required": ["username", "password"]
  }
}
```

## Agent 调用流程

### 工具发现

Agent 通过 MCP 的 `tools/list` 方法获取终端上可用的所有工具：

```json theme={null}
// Agent → Desktop (JSON-RPC Request)
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/list"
}

// Desktop → Agent (JSON-RPC Response)
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "tools": [
      {
        "name": "desktop_exec",
        "description": "Execute shell commands on desktop"
      },
      {
        "name": "browser_read",
        "description": "Extract data from browser pages"
      },
      {
        "name": "hitl_prompt",
        "description": "Request user input during automation"
      },
      {
        "name": "workflow_query_power_data",
        "description": "登录电力系统并查询指定区域的用电数据",
        "inputSchema": { "..." }
      }
    ]
  }
}
```

### 工具调用

Agent 决定调用某个工作流工具时，发送标准的 `tools/call` 请求：

```json theme={null}
// Agent → Desktop
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "workflow_query_power_data",
    "arguments": {
      "username": "operator_001",
      "password": "secure_pass",
      "region": "330100"
    }
  }
}
```

### 执行结果

```json theme={null}
// Desktop → Agent
{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "{\"success\": true, \"totalActions\": 8, \"completedActions\": 8, \"failedActions\": 0}"
      }
    ]
  }
}
```

## 内置工具

除了动态注册的工作流工具，Desktop 还提供以下内置 MCP 工具：

### desktop\_exec

在终端执行 Shell 命令。

```json theme={null}
{
  "name": "desktop_exec",
  "arguments": {
    "command": "ls -la /tmp/reports/"
  }
}
```

### browser\_read

从浏览器页面提取数据，支持多种提取方式：

| Action       | 说明               | 返回值            |
| ------------ | ---------------- | -------------- |
| `text`       | 提取页面或元素的文本内容     | 纯文本字符串         |
| `table`      | 解析 HTML 表格为结构化数据 | 二维数组（表头 + 行数据） |
| `form`       | 提取表单字段当前值        | 字段名-值映射        |
| `html`       | 获取元素或页面的 HTML    | HTML 字符串       |
| `url`        | 获取当前页面 URL       | URL 字符串        |
| `screenshot` | 截取页面截图           | Base64 PNG 图片  |

**调用示例：**

```json theme={null}
{
  "name": "browser_read",
  "arguments": {
    "action": "table",
    "selector": "#data-table",
    "profileId": "profile-001"
  }
}
```

**典型场景：** Agent 先执行 `workflow_query_power_data` 进入数据页面，再用 `browser_read` 提取页面上的表格数据进行分析。

### hitl\_prompt

在自动化流程中请求用户手动输入，适用于验证码、短信码等无法自动获取的场景。

```json theme={null}
{
  "name": "hitl_prompt",
  "arguments": {
    "title": "短信验证码",
    "message": "请输入您手机收到的 6 位验证码",
    "inputType": "text",
    "timeout": 120
  }
}
```

**执行流程：**

1. 系统弹出通知提醒用户
2. 在 Desktop 界面弹出输入对话框
3. 用户输入后，值返回给 Agent
4. 超时未输入则返回超时状态

**交互方式优先级：**

| 优先级 | 方式          | 说明                         |
| --- | ----------- | -------------------------- |
| 1   | Renderer 弹窗 | Desktop 主窗口可见时，在渲染进程中展示对话框 |
| 2   | 原生对话框       | 主窗口不可见时，使用 Electron 原生对话框  |
| 3   | 超时          | 超过设定时间无响应，返回超时状态           |

## 静默浏览器模式

当 Agent 远程调用工作流工具时，浏览器会以 **静默模式** 启动，不会在用户屏幕上显示浏览器窗口：

### 静默模式特性

| 特性        | 说明                             |
| --------- | ------------------------------ |
| **窗口不可见** | 浏览器窗口定位在屏幕外（-2400, -2400）      |
| **固定视口**  | 窗口大小固定为 1280×720               |
| **最小资源**  | 禁用 GPU、扩展、弹窗和通知                |
| **独立配置**  | 使用指定的浏览器 Profile，隔离 Cookie 和状态 |

### 静默模式启动参数

```
--window-position=-2400,-2400
--window-size=1280,720
--disable-gpu
--disable-extensions
--disable-popup-blocking
--disable-notifications
```

## 动态工具注册

### 注册时机

Desktop 在以下时机将工具信息同步到后端：

1. **WebSocket 连接建立时**：发送注册消息，包含所有可用工具列表
2. **工作流发布/取消发布时**：通知后端更新工具列表

### 注册消息

```json theme={null}
{
  "type": "register",
  "deviceId": "device-abc123",
  "capabilities": ["desktop_exec", "browser_control", "workflow_execution"],
  "available_tools": [
    "desktop_exec",
    "browser_read",
    "hitl_prompt",
    "workflow_query_power_data",
    "workflow_generate_report"
  ]
}
```

### 后端工具创建

AI Backend（Python）收到工具列表后，为每个工作流工具动态创建 LangChain `StructuredTool`：

```python theme={null}
# 动态创建 Pydantic schema
DynamicModel = create_model(
    "QueryPowerDataInput",
    username=(str, Field(description="登录用户名")),
    password=(str, Field(description="登录密码")),
    region=(str, Field(default="110000", description="查询区域编码")),
)

# 创建 LangChain Tool
tool = StructuredTool.from_function(
    name="workflow_query_power_data",
    description="登录电力系统并查询指定区域的用电数据",
    args_schema=DynamicModel,
    func=lambda **kwargs: call_desktop_tool("workflow_query_power_data", kwargs),
)
```

## 典型业务场景

### 场景一：电力数据采集

```mermaid theme={null}
sequenceDiagram
    participant Agent as AI Agent
    participant Desktop as Zeus Desktop
    participant Browser as Chrome (Silent)
    participant System as 电力系统

    Agent->>Desktop: tools/call workflow_login_power_system
    Desktop->>Browser: 启动静默浏览器
    Browser->>System: 导航到登录页
    Browser->>System: 输入用户名/密码
    Browser->>System: 提交登录
    Desktop-->>Agent: 登录成功

    Agent->>Desktop: tools/call browser_read (table)
    Desktop->>Browser: 提取数据表格
    Desktop-->>Agent: 返回结构化数据

    Agent->>Agent: 分析数据，生成报告
```

### 场景二：需要验证码的操作

```mermaid theme={null}
sequenceDiagram
    participant Agent as AI Agent
    participant Desktop as Zeus Desktop
    participant User as 终端用户
    participant Browser as Chrome

    Agent->>Desktop: tools/call workflow_submit_report
    Desktop->>Browser: 执行到验证码步骤
    Note over Desktop: 检测到需要人工输入

    Agent->>Desktop: tools/call hitl_prompt
    Desktop->>User: 弹出通知 + 输入对话框
    User->>Desktop: 输入验证码 "123456"
    Desktop-->>Agent: 返回验证码

    Agent->>Desktop: 继续执行 workflow
    Desktop->>Browser: 输入验证码，提交
    Desktop-->>Agent: 操作完成
```

### 场景三：批量数据处理

Agent 可以循环调用工作流工具，处理批量任务：

1. 调用 `workflow_login` 登录系统
2. 循环调用 `workflow_query_data`（传入不同参数）提取多页数据
3. 调用 `browser_read` 获取页面数据
4. 汇总分析，调用 `workflow_generate_report` 生成报告

## 错误处理

### 错误码

| 错误码      | 说明      |
| -------- | ------- |
| `-32001` | 工具执行错误  |
| `-32002` | 工作流执行错误 |
| `-32003` | 工作流未找到  |
| `-32004` | 浏览器未运行  |

### 回放引擎容错

| 机制       | 参数        | 说明              |
| -------- | --------- | --------------- |
| **元素等待** | 最长 10s    | 等待目标元素出现在 DOM 中 |
| **操作重试** | 3 次，间隔 1s | 操作失败自动重试        |
| **超时保护** | 30s/操作    | 单个操作超时后继续下一步    |

### 执行结果

工作流执行完成后返回结构化结果：

```typescript theme={null}
interface WorkflowExecutionResult {
  success: boolean
  totalActions: number
  completedActions: number
  failedActions: number
  results: ActionResult[]
}
```

## 兼容性

### Windows 7 支持

由于部分终端运行 Windows 7 系统，需注意：

* Electron 22.x 是最后支持 Win7 的版本
* 需要使用对应版本的 Chromium 内核
* 部分现代 Web API 可能不可用

### 信创系统支持

信创终端（UOS / 麒麟）兼容方案：

| 平台       | 架构          | 分发格式            |
| -------- | ----------- | --------------- |
| UOS      | x64 / arm64 | `.deb`          |
| 麒麟       | x64 / arm64 | `.rpm` / `.deb` |
| 通用 Linux | x64         | `.zip` (便携版)    |

## 相关文档

* [流程录制](/zh/desktop/recording) - 录制、编辑、参数化工作流
* [Desktop 概览](/zh/desktop/overview) - Desktop 应用总览
* [流程录制方案](/zh/desktop/workflow-recording) - 视频 + 音频 + 事件多层录制技术方案
