---
title: "系统能力 API：桌面、媒体、系统指标、蓝牙与 HID · Metrix.Bar"
description: "Metrix.Bar 桌面与硬件能力完整参考：<script apis> 39 项能力总表、$metrix.system 命令、通知、剪贴板、硬件指标、电池、媒体、收件箱、音频、图片与 HTML 渲染、OCR/条码/人脸、BLE 与 HID。"
canonical: "https://metrix.bar/zh/docs/system-apis"
language: "zh-Hans"
updated: "2026-11-30T21:58:48+08:00"
---

# 系统能力 API

> 完整 <script apis> 总表、$metrix.system 命令、桌面通知、剪贴板、系统指标、电池、系统媒体、收件箱、音频、图片/HTML/截图/识别、蓝牙与 HID。

## `<script apis="…">` 能力总表

Worker 默认运行在沙箱中，按需在 `<script apis="…">` 中以空格分隔声明区分大小写的能力名。`all` 开启所有受支持的可选 API，但需要独立 `<permissions>` 标签的能力（`<bluetooth>`、`<hid>`、`<process-control>`、`<storage-control>`、`<keyboard-lock>`、`<selection-text>`、`<calendar>`、`<clipboard-watch>`、`<system-media>`、`<system-media-control>`、`<inbox>`、`<http-ingress>`）仍须显式声明。

| API 名称          | 能力                          | 核心入口                                                                                                                                               |
| ----------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `app`             | 应用生命周期与标准路径        | `$metrix.quit()`、`$metrix.system("app.*")`                                                                                                            |
| `audio`           | 音频播放与 PCM 合成           | `$metrix.audio.load()`、`createSound()`、`now()`                                                                                                       |
| `auth`            | 浏览器 OAuth 与密钥写入       | `$metrix.auth.authorize()`、`setSecret()`、`deleteSecret()`（[运行时 API](/zh/docs/runtime-apis.md#浏览器授权与-secret-存储)）                                   |
| `background`      | 后台长时任务                  | `$metrix.waitUntil()`（[运行时 API](/zh/docs/runtime-apis.md#后台任务metrixwaituntil)）                                                                          |
| `badge`           | 应用图标角标                  | `navigator.setAppBadge()`、`clearAppBadge()`                                                                                                           |
| `barcode`         | 条码 / 二维码识别             | `$metrix.barcode.detect()`                                                                                                                             |
| `battery`         | 主机与外设电池、电源管理      | `navigator.getBattery()`、`$metrix.system("power.*")`                                                                                                  |
| `bluetooth`       | 蓝牙低功耗（BLE）GATT 客户端  | `$metrix.system("bluetooth.*")`（另需 `<bluetooth>`）                                                                                                  |
| `caches`          | 持久化响应缓存                | `caches.default`、`caches.open()`（[运行时 API](/zh/docs/runtime-apis.md#持久化缓存与-localstorage)）                                                            |
| `calendar`        | 只读 `.ics` / macOS 系统日历  | `$metrix.system("calendar.*")`（macOS 系统日历另需 `<calendar />`）                                                                                    |
| `clipboard`       | 多类型剪贴板读写与粘贴        | `navigator.clipboard.read/write/paste()`、`clipboard.formats/clear`                                                                                    |
| `clipboard-watch` | 剪贴板变更通知                | `$metrix.system("clipboard.watch/stopWatching")`（另需 `<clipboard-watch />`）                                                                         |
| `crypto`          | 随机数、SHA 摘要与 HMAC       | `crypto.getRandomValues`、`randomUUID`、`crypto.subtle`（[运行时 API](/zh/docs/runtime-apis.md#intltemporal-与-web-crypto)）                                     |
| `deadline`        | 一次性唤醒截止时间            | `$metrix.system("deadline.set/cancel")`                                                                                                                |
| `desktop-capture` | 交互式桌面区域截屏            | `$metrix.system("desktop.captureRegion")`                                                                                                              |
| `dialog`          | 文件/消息对话框与安全保存     | `$metrix.showOpenDialog/SaveDialog/MessageBox`、`readTextFile`、`fileInfo`、`writeFile`（[运行时 API](/zh/docs/runtime-apis.md#版本化文本与安全保存apisdialog)） |
| `dns`             | DNS 解析                      | `$metrix.dns.lookup/resolve/reverse()`（另需 `<dns>`；[运行时 API](/zh/docs/runtime-apis.md#dns-查询)）                                                          |
| `face`            | macOS 人脸框检测              | `$metrix.face.detect()`                                                                                                                                |
| `hid`             | USB / 蓝牙 HID 报告           | `$metrix.hid`（另需 `<hid>`）                                                                                                                          |
| `html`            | 无头 HTML 转 PNG（macOS）     | `$metrix.html.render()`                                                                                                                                |
| `image`           | 持久化图片导入                | `$metrix.image.load()`                                                                                                                                 |
| `indexedDB`       | 结构化持久存储                | `indexedDB`、`IDB*`（[运行时 API](/zh/docs/runtime-apis.md#indexeddb-持久存储)）                                                                                 |
| `intl`            | 国际化（`en`/`zh`）           | `Intl.*`（[运行时 API](/zh/docs/runtime-apis.md#intltemporal-与-web-crypto)）                                                                                    |
| `keyboard-lock`   | 临时锁定键盘输入              | `$metrix.system("input.lockKeyboard/unlockKeyboard/keyboardLockPermission")`（另需 `<keyboard-lock />`）                                               |
| `localStorage`    | 持久化键值存储                | `localStorage`（[运行时 API](/zh/docs/runtime-apis.md#持久化缓存与-localstorage)）                                                                               |
| `match-media`     | 外观与无障碍媒体查询          | `matchMedia()`、`$metrix.system("theme.*")`                                                                                                            |
| `metrics`         | 系统指标与本机 TCP 监听       | `$metrix.system("metrics.*")`、`network.listeners`                                                                                                     |
| `notification`    | 富桌面通知                    | `new Notification(title, options?)`                                                                                                                    |
| `ocr`             | macOS 文字识别                | `$metrix.ocr.recognize()`                                                                                                                              |
| `process-control` | 激活 / 终止 / 强杀进程        | `$metrix.system("process.*")`（另需 `<process-control />`）                                                                                            |
| `screen`          | 显示器几何信息与指针坐标      | `screen` 快照、`$metrix.system("screen.*")`                                                                                                            |
| `screenshot`      | 导出当前面板 PNG 截图         | `$metrix.panel.screenshot()`                                                                                                                           |
| `shell`           | 打开链接/路径、启动应用与图标 | `$metrix.openURL/openPath/showItemInFolder/beep`、`$metrix.system("shell.*")`                                                                          |
| `shortcut`        | 全局快捷键                    | `$metrix.registerShortcut()`、`unregisterShortcut()` → `event("shortcut")`                                                                             |
| `sockets`         | TCP / TLS / UDP 客户端套接字  | `cloudflare:sockets`、`node:net/tls/dgram`（[运行时 API](/zh/docs/runtime-apis.md#tcptls-与-udp-套接字)）                                                        |
| `sqlite`          | 持久 SQLite 数据库            | `$metrix.sqlite`（[运行时 API](/zh/docs/runtime-apis.md#sqlite-持久数据库)）                                                                                     |
| `storage-control` | 弹出外置卷                    | `$metrix.system("storage.eject")`（另需 `<storage-control />`）                                                                                        |
| `temporal`        | 日期时间计算（含 `intl`）     | `Temporal.*`（[运行时 API](/zh/docs/runtime-apis.md#intltemporal-与-web-crypto)）                                                                                |
| `watch`           | 文件/目录变更监听             | `$metrix.system("watch.start/stop")` → `event("system", { type: "watch" })`                                                                            |
| `websocket`       | 实时 WebSocket 客户端         | `new WebSocket()`（[运行时 API](/zh/docs/runtime-apis.md#实时-websocket-连接)）                                                                                  |

---

## 桌面系统命令（`$metrix.system`）

`$metrix.system(command, args?)` 返回 Promise（`args` 默认 `{}`）。未知命令、非法参数或缺少权限会拒绝；Worker 关闭自动释放句柄与监听。

| 命令                                                                             | 参数                                                                                                                                                         | 所需声明 / 权限                                 |
| -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------- |
| `screen.displays`、`screen.primary`、`screen.cursor`                             | —                                                                                                                                                            | `screen`                                        |
| `screen.nearest` / `screen.matching`                                             | `{ x, y }` / `{ x, y, width, height }`                                                                                                                       | `screen`                                        |
| `theme.source`、`theme.preferences`、`theme.isDark`                              | —                                                                                                                                                            | `match-media`                                   |
| `network.status`                                                                 | —（`{ online, metered }`）                                                                                                                                   | 无                                              |
| `network.listeners`                                                              | —（≤ 4096 条本机 TCP 监听：`{ address, port, protocol, pid?, createTime? }`）                                                                                | `metrics`                                       |
| `clipboard.formats`、`clipboard.clear`                                           | —                                                                                                                                                            | `clipboard`                                     |
| `clipboard.watch`、`clipboard.stopWatching`                                      | —                                                                                                                                                            | `clipboard-watch` + `<clipboard-watch />`       |
| `deadline.set` / `deadline.cancel`                                               | `{ at }`（未来 1 年内 Unix ms）/ `{ id }`                                                                                                                    | `deadline`                                      |
| `calendar.events` / `watch` / `watchFile` / `stopWatching`                       | `{ start, end, path? }` / — / `{ path }` / `{ token }`                                                                                                       | `calendar`（macOS 系统日历另需 `<calendar />`） |
| `desktop.captureRegion`                                                          | —（须在 `Button` 的 `onClick` 内调用）                                                                                                                       | `desktop-capture`                               |
| `selection.text`、`selection.permission`                                         | —                                                                                                                                                            | `<selection-text />` + 隐私开关                 |
| `metrics.*`                                                                      | 见下方系统指标表                                                                                                                                             | `metrics`                                       |
| `process.activate`、`process.terminate`、`process.kill`                          | `{ pid, createTime }`                                                                                                                                        | `process-control` + `<process-control />`       |
| `storage.eject`                                                                  | `{ path, uuid }`                                                                                                                                             | `storage-control` + `<storage-control />`       |
| `input.lockKeyboard` / `unlockKeyboard` / `keyboardLockPermission`               | `{ reason, timeoutMs? }` / `{ token }` / —                                                                                                                   | `keyboard-lock` + `<keyboard-lock />`           |
| `power.devices`、`power.batteryInfo`、`power.idleTime`                           | —                                                                                                                                                            | `battery`                                       |
| `power.keepAwake` / `power.keepRunning` / `power.release`                        | `{ reason, display? }` / `{ reason }` / `{ token }`                                                                                                          | `battery`                                       |
| `shell.installedApps` / `launchApp` / `appIcon` / `fileIcon`                     | — / `{ token }` / `{ token, size }` / `{ path, size }`                                                                                                       | `shell`                                         |
| `app.locale`、`languages`、`region`、`info`、`focus`、`hide`、`show`、`relaunch` | —                                                                                                                                                            | `app`                                           |
| `app.path`                                                                       | `{ name }`（`home`、`appData`、`userData`、`cache`、`logs`、`resources`、`temp`、`exe`、`desktop`、`documents`、`downloads`、`music`、`pictures`、`videos`） | `app`                                           |
| `watch.start` / `watch.stop`                                                     | `{ path, recursive? }` / `{ token }`                                                                                                                         | `watch`                                         |
| `bluetooth.*`                                                                    | 见[蓝牙低功耗](#蓝牙低功耗ble)                                                                                                                               | `bluetooth` + `<bluetooth>`                     |

- **应用启动与路径（`apis="shell"`）**：`shell.installedApps` 返回最多 4096 个应用 `{ name, id, path, token }`。token 在重新枚举或 Worker 重启后失效——请持久化稳定 `id`（或 `path`）并在启动时重新枚举解析新 token，无需文件拖放授权。`appIcon`/`fileIcon` 接受整数 `size` `1..256`，返回 PNG data URL（≤ 1 MiB）。`$metrix.openURL` 仅限 `http`/`https`/`mailto`；`$metrix.openPath`、`$metrix.showItemInFolder`、`shell.fileIcon` 与 `watch.start` 复用 `<file>`、用户拖入/选择与[保留授权](/zh/docs/runtime-apis.md#跨重启保留文件授权)（打开/定位/取图标针对目录本身须持有精确目录授权）。`shell.trash` 始终拒绝（`caniuse` 返回 `false`）。
- **外观媒体查询（`apis="match-media"`）**：`matchMedia(query)` 支持 `(prefers-color-scheme: dark|light)`、`(prefers-reduced-motion: reduce|no-preference)`、`(prefers-reduced-transparency: reduce|no-preference)`、`(prefers-contrast: more|no-preference)` 及实时 `"change"` 事件。
- **角标与全局快捷键**：`apis="badge"` 提供 `navigator.setAppBadge(count?)`（`0` 或省略清除）与 `clearAppBadge()`；`apis="shortcut"` 提供 `$metrix.registerShortcut(accelerator)` / `unregisterShortcut(accelerator)`，触发 `event("shortcut", { accelerator })`。
- **文件监听（`apis="watch"`）**：派发 `event("system", { type: "watch", token, path, oldPath, kind: "create"|"write"|"remove"|"rename", isDir })`。

---

## 桌面通知

声明 `apis="notification"` 并调用 `new Notification(title, options?)`（空标题不投递；预检阶段抛错）：

| 选项       | 类型                                  | 行为                                                                                                 |
| ---------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `body`     | `string`                              | 正文（≤ 16,384 B）。                                                                                 |
| `tag`      | `string`                              | 仅替换当前 Worker 同 tag 的旧通知；空 tag 各自独立。                                                 |
| `subtitle` | `string`                              | macOS 独立副标题（Windows/Linux/macOS 通讯通知显示于正文上方）。探测 `notification.subtitle`。       |
| `silent`   | `boolean`                             | `true` 请求静音。探测 `notification.silent`。                                                        |
| `group`    | `string`                              | 在 macOS 通知中心按组聚合（限当前 Worker）。探测 `notification.group`。                              |
| `image`    | `BufferSource`                        | PNG/JPEG 附图（≤ 512 KiB、单边 ≤ 2048 px）。探测 `notification.image`。                              |
| `sender`   | `{ id, name?, avatar: BufferSource }` | macOS 12+ 签有通讯通知权限时的直连消息发送者（不支持时降级为普通通知）。探测 `notification.sender`。 |

- 实例为 `EventTarget`，提供 `title`、`body`、`tag`、`onclick`、`addEventListener("click", fn)` 与幂等 `close()`；点击同时发送 `event("system", { type: "notification.click", tag, id })`。异步回调改 UI 后请调用 `$metrix.invalidate()`。
- **限额与平台**：每 Worker 最多 **64** 条保留通知与 **64** 个未返回原生 Show 调用；各字符串字段 ≤ 4096 B。不再需要时请显式 `close()`（系统无自动消失回调）。macOS 需打包 App 与通知权限；Linux 依赖 D-Bus 默认动作；Windows 使用托盘气泡。演练场不可用。

---

## 剪贴板、语言与监听

- **`apis="clipboard"`**：`navigator.clipboard.read()` → `ClipboardItem[]`、`write(items)` 与 `paste()`（须在原生按钮点击或聚焦 `CmdOrCtrl+V` 回调中同步调用一次；粘贴原生文件 URL 会授予当前 Worker 读取这些常规文件的权限；探测 `navigator.clipboard.paste`）。仅支持六种 MIME：`text/plain`、`text/html`、`image/png`、`text/markdown`、`text/uri-list`、`application/x-mygo-file-list`。限额：**64** 项、合计 **8 MiB**、PNG ≤ 16M px。
- **`apis="clipboard-watch"` + `<clipboard-watch />` + 隐私开关**：`clipboard.watch` 发送不含内容的 `event("system", { type: "clipboard.change" })`（读取内容另需 `clipboard`）。
- **语言**：Worker 创建时捕获的冻结 `navigator.languages` / `navigator.language` 快照（规范 BCP 47，默认 `en-US`，无 `languagechange`）。

---

## 系统指标快照

声明 `apis="metrics"`（包含在 `all` 中）。所有 `metrics.*` 命令每 Worker 共享 **1** 个在途查询槽、**5 秒**超时与 **2 MiB** 响应上限。请基于连续单调样本在脚本中计算速率，遇计数器重置丢弃负差值。演练场不可访问真实宿主机指标（可通过只读 `system` fixture 回放）。

### 轻量快照（`metrics.snapshot`）

`await $metrix.system("metrics.snapshot")` 返回 `{ timestamp, cpu, memory, disk, network, supported }`（不支持或失败的分组为 `null` 且对应 `supported.<group>: false`）：

- `cpu`：`{ userSeconds, systemSeconds, idleSeconds, totalSeconds }`（逻辑核累计秒数，不重复计入 guest/Windows IRQ）。
- `memory`：`{ totalBytes, availableBytes, usedBytes }`。
- `disk`：系统卷（`/` 或系统盘根）`{ path, totalBytes, freeBytes, usedBytes }`（不授予文件访问权）。
- `network`：所有网卡（含回环与虚拟网卡）累计 `{ receivedBytes, sentBytes }`。

### 按需与详细硬件查询

| 命令                                                                   | 参数                                                                            | 返回值                                                                                                                                            |
| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `metrics.cpu.info` / `counts` / `times`                                | — / `{ logical?: true }` / `{ perCPU?: false }`                                 | CPU 信息、逻辑/物理核数、各状态累计秒数                                                                                                           |
| `metrics.memory.virtual` / `details` / `swap` / `swapDevices`          | —                                                                               | 虚拟内存、细分内存（`active`/`inactive`/`wired`/`compressed`/`app`/`cachedFilesBytes`）、交换空间与设备                                           |
| `metrics.disk.partitions` / `usage` / `volumes` / `io`                 | `{ all?: false }` / `{ path }` / — / `{ names?: [] }`                           | 挂载分区、文件系统用量（按 `mountpoint` 查）、卷列表（`id`/`path`/`name`/`device`/`external`/`ejectable`）、磁盘 I/O                              |
| `metrics.net.io` / `interfaces` / `protocols` / `filter` / `conntrack` | `{ perInterface?: true }` / — / `{ protocols?: [] }` / — / `{ perCPU?: false }` | 分网卡/汇总流量、接口地址、Linux 协议/连接跟踪计数                                                                                                |
| `metrics.host.info` / `uptime` / `bootTime`                            | —                                                                               | 主机系统/内核信息、运行时长秒数、开机时间戳                                                                                                       |
| `metrics.load.avg` / `misc`                                            | —                                                                               | `{ load1, load5, load15 }`（Windows 不可用）；进程与上下文切换计数                                                                                |
| `metrics.sensors.temperatures` / `fans`                                | —                                                                               | 温度传感器 °C（Windows 不可用）；`{ devices: [{ id, name, rpm, minRPM, maxRPM }] }`                                                               |
| `metrics.thermal.state`                                                | —                                                                               | `{ timestamp, state: "nominal"\|"fair"\|"serious"\|"critical"\|"unknown" }`                                                                       |
| `metrics.gpu.snapshot`                                                 | —                                                                               | `{ timestamp, devices: [{ id, name, vendor, utilizationPercent, coreClockHz, memoryClockHz, memoryTotalBytes, memoryUsedBytes, temperatureC }] }` |
| `metrics.process.pids` / `stats` / `snapshot` / `network` / `info`     | — / `{ pid }` / — / — / `{ pid, createTime }`                                   | PID 列表、单进程统计、全量进程快照（4 秒截止并置 `partial`）、进程累计网络流量、核验身份的进程路径与应用名                                        |

### 进程与存储控制

须**同时**声明 `<permissions>` 与 `<script apis>`（`apis="all"` 不会单独授予）；预检、fixture 与演练场不可用。不可逆操作前务必先向用户确认：

```bar
<permissions><process-control /><storage-control /></permissions>
<script apis="metrics process-control storage-control">/* ... */</script>
```

- `process.activate`、`process.terminate`、`process.kill` 接收 `{ pid, createTime }`（执行前重校验身份，拒绝受保护进程与复用 PID）。
- `storage.eject` 接收来自 `metrics.disk.volumes` 的 `{ path, uuid }`（校验外置可弹出，拒绝系统卷与符号链接）。
- **键盘输入锁定（`apis="keyboard-lock"` + `<keyboard-lock />`）** — 在原生按钮、托盘菜单或全局快捷键回调中同步调用 `input.lockKeyboard({ reason, timeoutMs? })`，每次触发可请求一次。命令返回 `{ token, escapeShortcut, expiresAt }`。超时默认 10 分钟，可设置为 5 秒至 30 分钟。宿主同时只允许一把锁，按键内容对 Worker 保密。
- **解锁** — 由持有键盘锁的 Worker 调用 `input.unlockKeyboard({ token })`，在 macOS 按 `⌘⇧Esc`、在 Windows 或 Linux 按 `Ctrl+Shift+Esc`，或在设置中选择「解锁键盘」。到期、系统休眠、锁屏或 Worker 关闭时，宿主也会释放键盘锁。解锁后，若持有键盘锁的 Worker 仍活跃，它会收到 `event("system", { type: "input.keyboardUnlocked", token, reason })`。
- **平台支持** — 键盘锁定支持已授予辅助功能权限的 macOS、Windows 和 Linux X11。使用只读命令 `input.keyboardLockPermission` 查询当前权限状态。

---

## 电池、外设电量与防休眠

声明 `apis="battery"`（包含在 `all` 中）：

- **`await navigator.getBattery()`**：返回 `{ level (0..1), charging, chargingTime, dischargingTime }`（秒或 `Infinity`；插电充满时 `charging: false, chargingTime: 0`）。无电池抛 `NotFoundError`，不支持抛 `NotSupportedError`，读取失败抛 `NotReadableError`。并发 1 次、5 秒超时。
- **`power.batteryInfo`**：`{ timestamp, present, externalPower, condition, cycleCount, fullCapacityMWh, designCapacityMWh, healthPercent, voltageV, chargeRateMW }`（未知字段为 `null`）。
- **`power.devices`（外设电量）**：探测 `power.devices`。合并 macOS/Windows/Linux 的 BLE、HID 与 USB 外设电量源（≤ 64 设备、15 秒超时、并发 1 次）。条目含 `{ id, name, transport: "bluetooth"|"usb"|"unknown", vendorId, productId, batteryLevel (0..1 | null), charging?, parts?: [{ id, kind: "left"|"right"|"case"|"other", name?, batteryLevel, charging? }] }`。不透明 `id` 不可传入 `bluetooth.connect` 或 `hid.open`。
- **防休眠与电源事件**：`power.idleTime`（毫秒）、`power.keepAwake({ reason, display? })`、`power.keepRunning({ reason })`（阻止如 macOS App Nap 的进程限流且不阻止熄屏）、`power.release({ token })`（每 Worker 最多 8 个活跃断言，关闭自动释放，可在设置查看释放）。电源事件为 `event("system", { type: "power.suspend" | "power.resume" | "power.lock" | "power.unlock" })`。系统唤醒后到期活跃看板合并刷新一次。

---

## 订阅状态与系统媒体

- **订阅状态**：`$metrix.subscription()` 返回 `"free" | "plus"`；变更派发 `event("subscription", plan)`（探测 `subscription`）。
- **读取播放（`<system-media />`）**：需单实例隐私授权；探测 `systemMedia.watch`。调用 `$metrix.systemMedia.watch()` 接收初始与后续 `event("systemMedia", snapshot)`（`stopWatching()` 退订；权限变更派发 `event("systemMediaPermission", granted)`）。快照含 `status`（`playing|paused|stopped|idle|unavailable`）、`session`、`actions`、`title`、`artist`、`album`、`source`、`app: { id, name }`、`positionMs`、`durationMs`、`sampledAt`（播放中按 `positionMs + (Date.now() - sampledAt)` 估算当前进度）、`shuffle`、`repeat`（`off|one|all`）与居中裁切的方形 `artwork` data URL。支持 Windows 10 1809+ 与 macOS；Linux 不提供。
- **控制播放（`<system-media-control />`）**：独立隐私授权；探测 `systemMedia.control`（变更派发 `event("systemMediaControlPermission", granted)`）。仅调用 `snapshot.actions` 中列出的动作：`await $metrix.systemMedia.control(session, action, arg?)`（`"play"`、`"pause"`、`"next"`、`"previous"`、`"seek"` 传 `positionMs`、`"shuffle"` 传布尔、`"repeat"` 传 `"off"|"one"|"all"`）。同时仅一个控制调用在途，进度条拖拽请防抖。

---

## 收件箱

开通 Plus 后，声明 `<permissions><inbox access="read" /></permissions>`（或 `access="manage"` 允许删除消息），并在看板设置中绑定一个或多个收件箱。探测 `inbox.boxes`、`inbox.list`、`inbox.read`、`inbox.message`、`inbox.watch` 与 `inbox.remove`：

- `$metrix.inbox.boxes()` → `[{ id, name, address, paused, message_count, last_received_at }]`（仅已绑定收件箱；Unix 秒或 `null`）。
- `$metrix.inbox.list(inboxId, { limit?, before? })` → 按最新在前返回 `[{ seq, inbox_id, source, received_at, size, subject, sender }]`（`limit` `1..100`，默认 `100`；`before` 为不含边界的序号）。
- `$metrix.inbox.read(inboxId, seq)` → 原始字节 `Uint8Array`（≤ 25 MiB）。
- `$metrix.inbox.message(inboxId, seq)` → 解析后的可读邮件 `{ subject, from, to, cc, date?, text (≤ 256 KiB), attachments: [{ name?, type, size }], truncated }`。
- `$metrix.inbox.remove(inboxId, seq)` → 永久删除单条消息（需 `access="manage"`）。
- `event("inboxchange", { inboxIds })` 通知已授权收件箱变更。

---

## 图片导入、HTML 渲染与面板截图

### 图片导入

声明 `apis="image"`（包含在 `all` 中；探测 `image.load` 或 `image`），调用 `await $metrix.image.load(source)`（接受已授权 HTTP(S) URL、本实例 `metrix-image://` 引用或 `ArrayBuffer`/`ArrayBufferView`）。将 PNG、JPEG、GIF 首帧、WebP 与 BMP（含 1-bit）规范化为 PNG，返回 `{ src: "metrix-image://…", width, height, format: "png" }`。

- **限额**：输入与输出均 ≤ **8 MiB**、单边 ≤ **4096 px**、总像素 ≤ **16,777,216**；每 Worker 同时 **1** 个加载、超时 **60 秒**；与 HTML 渲染共享 **单实例 8 张 / 全局 128 张 / 64 MiB** 缓存（被成功渲染树引用后持久保留）。
- **错误码**：`invalid-options`、`unsupported`、`permission-denied`、`asset-failed`、`image-failed`、`not-found`、`budget-exceeded`、`cancelled`、`timeout`。

### HTML 渲染

声明 `apis="html"`（包含在 `all` 中），先探测 `await $metrix.caniuse("html.render")`（仅在具备系统渲染器与图片缓存的正式 macOS App 可用；Windows、Linux、CLI、预检、fixture 与演练场均为 `false`）。仅在异步钩子中调用 `await $metrix.html.render(options)`（不可在 `render()` 中调用）：

```js
const image = await $metrix.html.render({
  html: '<html><head><link rel="stylesheet" href="/theme.css"></head><body>Hello</body></html>',
  assets: [{ path: "/theme.css", contentType: "text/css", body: "body { margin: 0 }" }],
  viewport: { width: 800, height: 480, scale: 1 },
  readyScript: "await document.fonts.ready;",
  timeoutMs: 12000,
});
// 将 image.src ("metrix-image://...") 存入状态供 Image/Avatar 节点引用。
```

- **参数与限额**：`html` ≤ 1 MiB；可选 `readyScript` ≤ 64 KiB；`viewport.width`/`height` 为 `1..2048` 整数，`scale` `0.5..4`（默认 `1`），输出单边 ≤ 4096 px、总像素 ≤ 16M、PNG ≤ 8 MiB；可选 `assets` 最多 128 个唯一绝对路径（`≠ "/"`），每项 `{ path, contentType, body | url, sha256? }` ≤ 16 MiB（合计 ≤ 32 MiB；URL 资产由 Worker 依 `<network>` 权限下载，WebView 本身无直连网络）；`timeoutMs` `1..12000`（默认 `12000`）。每 Worker **1** 并发，全局 **2** 并发。返回 `{ src, width, height, format: "png", warnings }`，共享 8 张/实例、128 张全局、64 MiB 的 `metrix-image://` 缓存。
- **错误码**：`invalid-options`、`unsupported`、`permission-denied`、`webview-failed`、`asset-failed`、`ready-failed`、`timeout`、`budget-exceeded`、`cancelled`。

### 面板截图

声明 `apis="screenshot"`（包含在 `all` 中），调用 `await $metrix.panel.screenshot(options?)` 截取当前 Worker 最近一次成功提交的 `view.panel`（面板未打开时也可截取）：

- **参数**：`{ theme?: "system"|"light"|"dark", width?: 1..2048, height?: 1..2048, scale?: 0.5..4, output?: "blob"|"file" }`。默认返回 `image/png` `Blob`；`output: "file"` 返回仅本 Worker 只读的临时绝对路径（Worker 关闭时清理，每 Worker 上限 16 文件 / 64 MiB；永久保存请用 `apis="dialog"` + `writeFile`）。
- **限额**：≤ 16M px、≤ 8 MiB PNG、源位图解码预算 32 MiB、每 Worker **1** 并发、全局 **2** 并发、**15 秒**超时。预检、fixture 与演练场不可用。

---

## 图片识别（条码、OCR、人脸）

声明 `apis="barcode ocr face"`（可单选或用 `all`），传入 `ArrayBuffer` 或 `TypedArray`（≤ **8 MiB**，支持 PNG/JPEG/GIF 首帧/WebP，单边 ≤ **4096 px**，总像素 ≤ **4,000,000 px**；坐标按编码像素左上角归一化到 `0..1`，不做 EXIF 旋转）：

```js
if (await $metrix.caniuse("barcode", { formats: ["qr_code"] })) {
  const { barcodes } = await $metrix.barcode.detect(bytes, { formats: ["qr_code"] });
}
if (await $metrix.caniuse("ocr", { languages: ["en-US"] })) {
  const { text, lines } = await $metrix.ocr.recognize(bytes, { languages: ["en-US"] });
}
if (await $metrix.caniuse("face")) {
  const { faces } = await $metrix.face.detect(bytes);
}
```

- `barcode.detect(bytes, { formats? })` → `{ barcodes: [{ payload, format, points: [{ x, y }] }] }`（`qr_code`、`code_128`、`ean_13`；确定性条码解码在 fixture/演练场可用）。
- `ocr.recognize(bytes, { languages? })` → `{ text, lines: [{ text, confidence, bounds: { x, y, width, height } }] }`（仅 macOS Vision Accurate）。
- `face.detect(bytes)` → `{ faces: [{ confidence, bounds: { x, y, width, height } }] }`（仅 macOS Vision 人脸框，不做身份识别）。
- **并发**：三者共享每 Worker **1** 个在途任务，进程全局 **2** 个执行槽。

---

## 音频播放与 PCM 合成

声明 `apis="audio"`（包含在 `all` 中）：

- **压缩文件/URL（`$metrix.audio.load({ url | path, stream?: true })`）**：支持 WAV、MP3、Ogg Vorbis（`8000..192000` Hz、1–2 声道、≤ 30 分钟）。方法：`play()`、`pause()`、`stop()`、`seek(s)`、`configure({ volume (0..1), pan (-1..1), playbackRate (0.1..16), loop, loopStart, loopEnd })`、`status()`、`close()`。限额：**8** 播放器、单源压缩 **8 MiB** / 总计 **16 MiB**、`stream: false` 单音效解码 **4 MiB** / 池 **16 MiB**。
- **PCM Sound 与独立 Voice**：`$metrix.audio.now()`（单调秒）、`await $metrix.audio.createSound({ samples: Float32Array, sampleRate, channels })` → `sound.play({ when?, volume?, pan?, playbackRate?, loop?, attackMs? (0..2000) })` → `AudioVoice`（`configure`、`status`、`release({ when?, durationMs? (默认 80，0..2000) })`、`stop`、`close`）。5 ms 调度步进（`when` 最多提前 5 秒）。限额：**64** Sound（单个 ≤ 4 MiB）、**32** 独立 Voice、**32 MiB** 共享 PCM、**16 MiB** 待复制缓冲、**256** 命令队列。请在 `lifecycle/stop` 中 `sound.close()`。预检禁止 `play()`。

---

## 区域截屏、日历、选区文本与定时截止

- **桌面区域截屏（`apis="desktop-capture"`）**：须在面板 `Button` 的 `onClick` 内直接调用并等待 `$metrix.system("desktop.captureRegion")`（每次点击一次选取）。返回 PNG `ArrayBuffer`（≤ 8 MiB、≤ 16M px）或用户取消时返回 `null`。macOS 需屏幕录制权限；Linux 使用 Spectacle、GNOME Screenshot、XFCE Screenshooter 或 Wayland `slurp`/`grim`。探测 `desktop.captureRegion`。
- **只读日历（`apis="calendar"`）**：`calendar.events({ start, end, path? })` 查询最长 31 天（Unix ms）内的最多 512 条有序事件；全平台可传已授权 `.ics` 路径，macOS 声明 `<calendar />` 并在隐私中绑定系统日历后可省略 `path`。`calendar.watchFile({ path })` / `calendar.watch()` 触发 `event("system", { type: "calendar.change", token })`，用 `calendar.stopWatching({ token })` 退订。
- **选区文本（`<permissions><selection-text /></permissions>` + 隐私开关）**：非破坏性读取前台应用当前选中文本（`selection.text` → `{ text (≤ 64 KiB), truncated, app?, bounds? }`；`selection.permission` → `{ granted, status, supported }`），不模拟按键也不碰剪贴板。支持 macOS 辅助功能、Windows UI Automation 与 Linux X11 `PRIMARY`（Linux Wayland 不可用）。
- **一次性截止时间（`apis="deadline"`）**：`deadline.set({ at })` 为当前实例预约一次未来 1 年内的唤醒（Unix ms），到期或休眠重启后触发 `event("deadline", { id, at })`，用 `deadline.cancel({ id })` 取消；按 `id` 去重。

---

## 蓝牙低功耗（BLE）

声明 `apis="bluetooth"`（或 `all`）与 `<permissions><bluetooth service="180f" write?="true" /></permissions>`（最多 16 个精确 GATT UUID；`all` 绝不授予未声明服务）。可调用 `bluetooth.capabilities`（`{ supported, transport: "ble" }`）探测后端而不触碰硬件。

| 命令                                     | 参数                                                        | 返回值                                                                                                                        |
| ---------------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `bluetooth.capabilities`                 | —                                                           | `{ supported, transport: "ble" }`                                                                                             |
| `bluetooth.scan`                         | `{ services (1..16), durationMs? (100..10000，默认 2000) }` | `{ id, name, rssi, services }[]`（≤ 128；覆盖上次发现 token）                                                                 |
| `bluetooth.connect` / `disconnect`       | `{ device }` / `{ connection }`                             | 不透明连接 token / `null`                                                                                                     |
| `bluetooth.services` / `characteristics` | `{ connection }` / `{ connection, service }`                | 已授权 UUID / `{ uuid, read, write, notify }[]`                                                                               |
| `bluetooth.read` / `write`               | `{ connection, service, characteristic, data? }`            | `number[]` / `null`（写入需 `write="true"`，非空 `data` ≤ 512 B）                                                             |
| `bluetooth.subscribe` / `unsubscribe`    | `{ connection, service, characteristic }` / `{ token }`     | 订阅 token / `null` → `event("system", { type: "bluetooth.notification", token, connection, service, characteristic, data })` |

- **限额与平台**：每 Worker **4** 连接、**16** 订阅、**1** 并发命令、**12 秒**超时、读写/通知上限 **512 B**。macOS（CoreBluetooth，需蓝牙权限）上请先读再订阅——对活跃订阅的特征执行读操作会报 busy，须先退订。Windows 使用 WinRT BLE；Linux 需 BlueZ 与系统 D-Bus。fixture 与演练场不可用。

---

## HID 设备

声明 `apis="hid"`（或 `all`）与 `<permissions><hid vendor-id="0x1234" product-id="0xabcd" usage-page? usage? write? /></permissions>`。Windows 可用 `usage-page`/`usage` 限定集合；macOS/Linux 打开整个端点（限定集合的授权不会匹配设备）。

```js
await $metrix.hid.watch(); // 枚举前先启动监听
const devices = await $metrix.hid.enumerate();
const session = await $metrix.hid.open(devices[0].token, { numberedReports: true });
const report = await session.readInputReport({ timeout: 5000 }); // 1..30000 ms
await session.writeOutputReport({ reportId: report.reportId, data: new Uint8Array([1, 2]) });
const feat = await session.getFeatureReport({ reportId: 1, length: 16 }); // 0..4096 B
await session.setFeatureReport({ reportId: 1, data: feat.data });
await session.close();
```

- `numberedReports` 为必填布尔（`false` 须用 `reportId: 0`；`true` 用 `1..255`）。`data` 为不含报告 ID 的 `Uint8Array`；写入须 `write="true"`。
- `watch()` 以 1 秒轮询派发 `event("hid", { type: "connected" | "disconnected", device })`（队列 32 条），直至 `stopWatching()` 或 Worker 关闭。
- **限额**：每 Worker **4** 句柄、**64** token、**4** 并发操作（单会话 1 个）、单报告 **4096 B**；进程全局 32 句柄 / 64 原生操作。请在 `lifecycle/start` 或用户交互中打开会话；预检、fixture 与演练场不可用。
