---
title: "System APIs: Desktop, Media, Metrics, BLE & HID · Metrix.Bar"
description: "Complete reference for Metrix.Bar desktop and hardware APIs: <script apis>, $metrix.system commands, notifications, clipboard, system metrics, battery, system media, inbox, audio, images, HTML rendering, OCR/barcode/face, BLE, and HID."
canonical: "https://metrix.bar/docs/system-apis"
language: "en"
updated: "2026-11-30T21:58:48+08:00"
---

# System APIs

> Optional <script apis> table, $metrix.system commands, notifications, clipboard, system metrics, battery, media, inbox, audio, images/HTML/screenshots/recognition, BLE, and HID.

## `<script apis="…">` capability table

Workers run sandboxed by default. Request optional capabilities with space-separated case-sensitive names on `<script apis="…">`; `all` enables all supported optional APIs, **except** explicit `<permissions>` declarations (`<bluetooth>`, `<hid>`, `<process-control>`, `<storage-control>`, `<keyboard-lock>`, `<selection-text>`, `<calendar>`, `<clipboard-watch>`, `<system-media>`, `<system-media-control>`, `<inbox>`, `<http-ingress>`) are always required separately.

| API name          | Capability                          | Core entry points                                                                                                                                                  |
| ----------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `app`             | App lifecycle & paths               | `$metrix.quit()`, `$metrix.system("app.*")`                                                                                                                        |
| `audio`           | Audio playback & PCM voices         | `$metrix.audio.load()`, `createSound()`, `now()`                                                                                                                   |
| `auth`            | Browser OAuth & secret mutations    | `$metrix.auth.authorize()`, `setSecret()`, `deleteSecret()` ([Runtime APIs](/docs/runtime-apis.md#browser-authorization-and-secret-storage))                              |
| `background`      | Extended background promises        | `$metrix.waitUntil()` ([Runtime APIs](/docs/runtime-apis.md#background-tasks-metrixwaituntil))                                                                            |
| `badge`           | App icon badge counter              | `navigator.setAppBadge()`, `clearAppBadge()`                                                                                                                       |
| `barcode`         | Barcode decoding                    | `$metrix.barcode.detect()`                                                                                                                                         |
| `battery`         | Host & peripheral batteries, power  | `navigator.getBattery()`, `$metrix.system("power.*")`                                                                                                              |
| `bluetooth`       | Bluetooth Low Energy GATT client    | `$metrix.system("bluetooth.*")` (also requires `<bluetooth>`)                                                                                                      |
| `caches`          | Persistent response cache           | `caches.default`, `caches.open()` ([Runtime APIs](/docs/runtime-apis.md#caches--localstorage))                                                                            |
| `calendar`        | Read-only `.ics` / macOS calendar   | `$metrix.system("calendar.*")` (macOS system calendar needs `<calendar />`)                                                                                        |
| `clipboard`       | Typed clipboard read/write/paste    | `navigator.clipboard.read/write/paste()`, `clipboard.formats/clear`                                                                                                |
| `clipboard-watch` | Clipboard change notifications      | `$metrix.system("clipboard.watch/stopWatching")` (needs `<clipboard-watch />`)                                                                                     |
| `crypto`          | Randomness, SHA digests & HMAC      | `crypto.getRandomValues`, `randomUUID`, `crypto.subtle` ([Runtime APIs](/docs/runtime-apis.md#intl-temporal--web-crypto))                                                 |
| `deadline`        | One-shot wake-up deadlines          | `$metrix.system("deadline.set/cancel")`                                                                                                                            |
| `desktop-capture` | Interactive screen region capture   | `$metrix.system("desktop.captureRegion")`                                                                                                                          |
| `dialog`          | File/message dialogs & safe write   | `$metrix.showOpenDialog/SaveDialog/MessageBox`, `readTextFile`, `fileInfo`, `writeFile` ([Runtime APIs](/docs/runtime-apis.md#versioned-text-and-safe-saving-apisdialog)) |
| `dns`             | DNS resolution                      | `$metrix.dns.lookup/resolve/reverse()` (needs `<dns>`; [Runtime APIs](/docs/runtime-apis.md#dns-queries))                                                                 |
| `face`            | Face detection on macOS             | `$metrix.face.detect()`                                                                                                                                            |
| `hid`             | USB / Bluetooth HID reports         | `$metrix.hid` (needs `<hid>`)                                                                                                                                      |
| `html`            | Headless HTML-to-PNG (macOS)        | `$metrix.html.render()`                                                                                                                                            |
| `image`           | Persistent image import             | `$metrix.image.load()`                                                                                                                                             |
| `indexedDB`       | Structured persistent storage       | `indexedDB`, `IDB*` ([Runtime APIs](/docs/runtime-apis.md#persistent-indexeddb-storage))                                                                                  |
| `intl`            | Internationalization (`en`/`zh`)    | `Intl.*` ([Runtime APIs](/docs/runtime-apis.md#intl-temporal--web-crypto))                                                                                                |
| `keyboard-lock`   | Temporary keyboard input lock       | `$metrix.system("input.lockKeyboard/unlockKeyboard/keyboardLockPermission")` (needs `<keyboard-lock />`)                                                           |
| `localStorage`    | Persistent key-value storage        | `localStorage` ([Runtime APIs](/docs/runtime-apis.md#caches--localstorage))                                                                                               |
| `match-media`     | Appearance & accessibility queries  | `matchMedia()`, `$metrix.system("theme.*")`                                                                                                                        |
| `metrics`         | Host metrics & TCP listeners        | `$metrix.system("metrics.*")`, `network.listeners`                                                                                                                 |
| `notification`    | Rich desktop notifications          | `new Notification(title, options?)`                                                                                                                                |
| `ocr`             | Text recognition on macOS           | `$metrix.ocr.recognize()`                                                                                                                                          |
| `process-control` | Activate / terminate / kill process | `$metrix.system("process.*")` (needs `<process-control />`)                                                                                                        |
| `screen`          | Display geometry & cursor           | `screen` snapshot, `$metrix.system("screen.*")`                                                                                                                    |
| `screenshot`      | Export current panel as PNG         | `$metrix.panel.screenshot()`                                                                                                                                       |
| `shell`           | Open URLs/paths, launch apps, icons | `$metrix.openURL/openPath/showItemInFolder/beep`, `$metrix.system("shell.*")`                                                                                      |
| `shortcut`        | Global keyboard shortcuts           | `$metrix.registerShortcut()`, `unregisterShortcut()` → `event("shortcut")`                                                                                         |
| `sockets`         | TCP, TLS & UDP client sockets       | `cloudflare:sockets`, `node:net/tls/dgram` ([Runtime APIs](/docs/runtime-apis.md#tcp-tls--udp-sockets))                                                                   |
| `sqlite`          | Persistent SQLite databases         | `$metrix.sqlite` ([Runtime APIs](/docs/runtime-apis.md#persistent-sqlite-databases))                                                                                      |
| `storage-control` | Eject external volumes              | `$metrix.system("storage.eject")` (needs `<storage-control />`)                                                                                                    |
| `temporal`        | Date/time arithmetic (+ `intl`)     | `Temporal.*` ([Runtime APIs](/docs/runtime-apis.md#intl-temporal--web-crypto))                                                                                            |
| `watch`           | File/directory watching             | `$metrix.system("watch.start/stop")` → `event("system", { type: "watch" })`                                                                                        |
| `websocket`       | Realtime WebSocket client           | `new WebSocket()` ([Runtime APIs](/docs/runtime-apis.md#realtime-websocket-connections))                                                                                  |

---

## Desktop system commands (`$metrix.system`)

`$metrix.system(command, args?)` returns a Promise (`args` defaults to `{}`). Unknown commands, invalid fields, or missing opt-ins reject. Worker closure automatically releases tokens and watchers.

| Command                                                                          | Arguments                                                                                                                                                   | Opt-in / permission                       |
| -------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |
| `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 }`)                                                                                                                                   | None                                      |
| `network.listeners`                                                              | — (≤ 4096 TCP listeners: `{ address, port, protocol, pid?, createTime? }`)                                                                                  | `metrics`                                 |
| `clipboard.formats`, `clipboard.clear`                                           | —                                                                                                                                                           | `clipboard`                               |
| `clipboard.watch`, `clipboard.stopWatching`                                      | —                                                                                                                                                           | `clipboard-watch` + `<clipboard-watch />` |
| `deadline.set` / `deadline.cancel`                                               | `{ at }` (Unix ms ≤ 1 year ahead) / `{ id }`                                                                                                                | `deadline`                                |
| `calendar.events` / `watch` / `watchFile` / `stopWatching`                       | `{ start, end, path? }` / — / `{ path }` / `{ token }`                                                                                                      | `calendar` (+ `<calendar />` on macOS)    |
| `desktop.captureRegion`                                                          | — (call inside a `Button` `onClick`)                                                                                                                        | `desktop-capture`                         |
| `selection.text`, `selection.permission`                                         | —                                                                                                                                                           | `<selection-text />` + Privacy toggle     |
| `metrics.*`                                                                      | Per-command options (see below)                                                                                                                             | `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.*`                                                                    | See [Bluetooth Low Energy](#bluetooth-low-energy)                                                                                                           | `bluetooth` + `<bluetooth>`               |

- **Shell & app launchers (`apis="shell"`)**: `shell.installedApps` lists up to 4096 apps as `{ name, id, path, token }`. Tokens expire on re-enumeration or Worker restart—persist `id` (or `path`) and re-enumerate on startup to resolve fresh tokens without file-drop grants. `appIcon`/`fileIcon` take integer `size` `1..256` and return PNG data URLs (≤ 1 MiB). `$metrix.openURL(url)` allows `http`, `https`, `mailto`; `$metrix.openPath`, `$metrix.showItemInFolder`, `shell.fileIcon`, and `watch.start` reuse `<file>`, user drops/pickers, and [retained grants](/docs/runtime-apis.md#retained-file-grants) (opening/revealing/fetching an icon for a folder itself needs an exact folder grant). `shell.trash` always rejects (`caniuse` returns `false`).
- **Media queries (`apis="match-media"`)**: `matchMedia(query)` supports `(prefers-color-scheme: dark|light)`, `(prefers-reduced-motion: reduce|no-preference)`, `(prefers-reduced-transparency: reduce|no-preference)`, `(prefers-contrast: more|no-preference)` with live `"change"` events.
- **Badge & shortcuts**: `apis="badge"` provides `navigator.setAppBadge(count?)` (`0`/omitted clears) and `clearAppBadge()`. `apis="shortcut"` provides `$metrix.registerShortcut(accelerator)` / `unregisterShortcut(accelerator)` firing `event("shortcut", { accelerator })`.
- **File watching (`apis="watch"`)**: Fires `event("system", { type: "watch", token, path, oldPath, kind: "create"|"write"|"remove"|"rename", isDir })`.

---

## Desktop notifications

Declare `apis="notification"` and call `new Notification(title, options?)` (empty titles do not deliver; staging throws):

| Option     | Type                                  | Behavior                                                                                                                                                         |
| ---------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `body`     | `string`                              | Body text (≤ 16,384 B).                                                                                                                                          |
| `tag`      | `string`                              | Replaces an earlier notification with the same tag in this Worker only; empty tags are independent.                                                              |
| `subtitle` | `string`                              | Separate subtitle on macOS (above body on Windows/Linux/macOS communication notifications). Probe `notification.subtitle`.                                       |
| `silent`   | `boolean`                             | `true` suppresses sound. Probe `notification.silent`.                                                                                                            |
| `group`    | `string`                              | Groups in macOS Notification Center within this Worker. Probe `notification.group`.                                                                              |
| `image`    | `BufferSource`                        | PNG/JPEG attachment (≤ 512 KiB, ≤ 2048 px/side). Probe `notification.image`.                                                                                     |
| `sender`   | `{ id, name?, avatar: BufferSource }` | Incoming direct-message sender on macOS 12+ signed for Communication Notifications (falls back to ordinary notification otherwise). Probe `notification.sender`. |

- Instances are `EventTarget`s with `title`, `body`, `tag`, `onclick`, `addEventListener("click", fn)`, and idempotent `close()`. Clicks also fire `event("system", { type: "notification.click", tag, id })`. Call `$metrix.invalidate()` if async click handlers update UI.
- **Limits & platforms**: **64** retained notifications and **64** unfinished native Show calls per Worker; string metadata ≤ 4096 B. Close explicitly when done (no OS auto-dismiss callback). macOS requires a packaged app + permission; Linux requires D-Bus default-action support for clicks; Windows uses tray balloons. Unavailable in Playground.

---

## Clipboard, languages & watch

- **`apis="clipboard"`**: `navigator.clipboard.read()` → `ClipboardItem[]`, `write(items)`, and `paste()` (call once synchronously in a native button click or focused `CmdOrCtrl+V` handler—pasting native file URLs grants read access to those exact regular files for the Worker's lifetime; probe `navigator.clipboard.paste`). Supported MIME types: `text/plain`, `text/html`, `image/png`, `text/markdown`, `text/uri-list`, `application/x-mygo-file-list`. Limits: **64** items, **8 MiB** total, PNG ≤ 16M px.
- **`apis="clipboard-watch"` + `<clipboard-watch />` + Privacy toggle**: `clipboard.watch` emits `event("system", { type: "clipboard.change" })` without contents (declare `clipboard` to read).
- **Languages**: Frozen `navigator.languages` / `navigator.language` snapshot captured at Worker creation (normalized BCP 47, default `en-US`; no `languagechange`).

---

## System metrics snapshots

Declare `apis="metrics"` (included in `all`). All `metrics.*` commands share **1** in-flight query per Worker, a **5 s** timeout, and a **2 MiB** response cap. Compute rates in script from consecutive monotonic samples and discard negative deltas on counter resets. Unavailable for real host data in Playground (replayable via read-only `system` fixtures).

### Lightweight snapshot (`metrics.snapshot`)

`await $metrix.system("metrics.snapshot")` returns `{ timestamp, cpu, memory, disk, network, supported }` (unsupported/failed groups are `null` with `supported.<group>: false`):

- `cpu`: `{ userSeconds, systemSeconds, idleSeconds, totalSeconds }` (cumulative seconds across logical CPUs; guest/Windows IRQ overlap excluded).
- `memory`: `{ totalBytes, availableBytes, usedBytes }`.
- `disk`: `{ path, totalBytes, freeBytes, usedBytes }` for system volume (`/` or system drive root; grants no file access).
- `network`: `{ receivedBytes, sentBytes }` across all interfaces including loopback/virtual.

### On-demand & hardware queries

| Command                                                                | Arguments                                                                       | Result                                                                                                                                                   |
| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `metrics.cpu.info` / `counts` / `times`                                | — / `{ logical?: true }` / `{ perCPU?: false }`                                 | CPU metadata, logical/physical count, cumulative per-state seconds                                                                                       |
| `metrics.memory.virtual` / `details` / `swap` / `swapDevices`          | —                                                                               | OS virtual memory, detailed breakdown (`active`/`inactive`/`wired`/`compressed`/`app`/`cachedFilesBytes`), swap totals & devices                         |
| `metrics.disk.partitions` / `usage` / `volumes` / `io`                 | `{ all?: false }` / `{ path }` / — / `{ names?: [] }`                           | Mounted partitions, filesystem space (query by `mountpoint`), volume list (`id`, `path`, `name`, `device`, `external`, `ejectable`), device I/O counters |
| `metrics.net.io` / `interfaces` / `protocols` / `filter` / `conntrack` | `{ perInterface?: true }` / — / `{ protocols?: [] }` / — / `{ perCPU?: false }` | Per-interface/aggregate I/O, addresses, Linux protocol/conntrack stats                                                                                   |
| `metrics.host.info` / `uptime` / `bootTime`                            | —                                                                               | Host OS/kernel info, uptime seconds, boot Unix timestamp                                                                                                 |
| `metrics.load.avg` / `misc`                                            | —                                                                               | `{ load1, load5, load15 }` (not on Windows); process/context-switch counts                                                                               |
| `metrics.sensors.temperatures` / `fans`                                | —                                                                               | °C sensor list (not on 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 list, single-process stats, full process snapshot (`partial` after 4 s cap), per-process cumulative network bytes, verified process path/appName     |

### Process & storage controls

Require **both** `<permissions>` and `<script apis>` (never granted by `apis="all"` alone); unavailable in staging/fixtures/Playground. Always confirm irreversible actions with the user:

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

- `process.activate`, `process.terminate`, `process.kill` accept `{ pid, createTime }` (rechecks process identity so reused PIDs and protected processes are rejected).
- `storage.eject` accepts `{ path, uuid }` from `metrics.disk.volumes` (verifies external & ejectable, rejects system volumes and symlinks).
- **Keyboard lock (`apis="keyboard-lock"` + `<keyboard-lock />`)** — Call `input.lockKeyboard({ reason, timeoutMs? })` synchronously in a native button, tray menu, or global shortcut callback. Each activation can make one request. The command returns `{ token, escapeShortcut, expiresAt }`. The timeout defaults to 10 minutes and accepts 5 seconds to 30 minutes. The host allows one lock at a time and keeps keystrokes private.
- **Unlock** — Call `input.unlockKeyboard({ token })` from the Worker that acquired the lock, press `Cmd+Shift+Esc` on macOS or `Ctrl+Shift+Esc` on Windows/Linux, or select Unlock Keyboard in Settings. The host also unlocks when the timeout expires, the system sleeps or locks, or the Worker closes. When the owning Worker is still active, it receives `event("system", { type: "input.keyboardUnlocked", token, reason })` after the lock is released.
- **Platform support** — Keyboard locking is available on macOS with Accessibility permission, Windows, and Linux X11. Query readiness with the read-only `input.keyboardLockPermission` command.

---

## Battery, peripherals & keep awake

Declare `apis="battery"` (included in `all`):

- **`await navigator.getBattery()`**: Returns `{ level (0..1), charging, chargingTime, dischargingTime }` (seconds or `Infinity`; a full connected battery reports `charging: false, chargingTime: 0`). Rejects with `NotFoundError` (no battery), `NotSupportedError`, or `NotReadableError`. 1 pending read, 5 s budget.
- **`power.batteryInfo`**: `{ timestamp, present, externalPower, condition, cycleCount, fullCapacityMWh, designCapacityMWh, healthPercent, voltageV, chargeRateMW }` (`null` for unknown fields).
- **`power.devices` (peripheral batteries)**: Probe `power.devices`. Combines BLE, HID, and USB accessory battery sources across macOS, Windows, and Linux (≤ 64 devices, 15 s budget, 1 pending read). Each entry has `{ id, name, transport: "bluetooth"|"usb"|"unknown", vendorId, productId, batteryLevel (0..1 | null), charging?, parts?: [{ id, kind: "left"|"right"|"case"|"other", name?, batteryLevel, charging? }] }`. Opaque IDs cannot be passed to `bluetooth.connect` or `hid.open`.
- **Keep awake & power events**: `power.idleTime` (ms), `power.keepAwake({ reason, display? })`, `power.keepRunning({ reason })` (prevents App Nap without blocking display sleep), `power.release({ token })` (max 8 active assertions per Worker, auto-released on close, inspectable in Settings). Power state changes emit `event("system", { type: "power.suspend" | "power.resume" | "power.lock" | "power.unlock" })`. After sleep wake, due active dashboards run a single coalesced refresh.

---

## Subscription and system media

- **Subscription**: `$metrix.subscription()` returns `"free" | "plus"`; changes fire `event("subscription", plan)` (probe `subscription`).
- **Read playback (`<system-media />`)**: Requires per-instance Privacy toggle; probe `systemMedia.watch`. Call `$metrix.systemMedia.watch()` to receive an initial `event("systemMedia", snapshot)` and subsequent updates (`stopWatching()` unsubscribes; grant changes fire `event("systemMediaPermission", granted)`). Snapshot fields: `status` (`playing|paused|stopped|idle|unavailable`), `session`, `actions`, `title`, `artist`, `album`, `source`, `app: { id, name }`, `positionMs`, `durationMs`, `sampledAt` (estimate live progress while playing as `positionMs + (Date.now() - sampledAt)`), `shuffle`, `repeat` (`off|one|all`), and square center-cropped `artwork` data URL. Supported on Windows 10 1809+ and macOS; unavailable on Linux.
- **Control playback (`<system-media-control />`)**: Separate Privacy toggle; probe `systemMedia.control` (changes fire `event("systemMediaControlPermission", granted)`). Call `await $metrix.systemMedia.control(session, action, arg?)` only for actions present in `snapshot.actions`: `"play"`, `"pause"`, `"next"`, `"previous"`, `"seek"` (`positionMs`), `"shuffle"` (`boolean`), `"repeat"` (`"off"|"one"|"all"`). One call in flight at a time—debounce slider seeks.

---

## Inbox

With Plus, declare `<permissions><inbox access="read" /></permissions>` (or `access="manage"` to allow deleting messages) and let the user bind one or more inboxes in dashboard settings. Probe `inbox.boxes`, `inbox.list`, `inbox.read`, `inbox.message`, `inbox.watch`, and `inbox.remove`:

- `$metrix.inbox.boxes()` → `[{ id, name, address, paused, message_count, last_received_at }]` (bound inboxes only; Unix seconds or `null`).
- `$metrix.inbox.list(inboxId, { limit?, before? })` → newest-first `[{ seq, inbox_id, source, received_at, size, subject, sender }]` (`limit` `1..100`, default `100`; exclusive `before` seq).
- `$metrix.inbox.read(inboxId, seq)` → raw `Uint8Array` (≤ 25 MiB).
- `$metrix.inbox.message(inboxId, seq)` → decoded email `{ subject, from, to, cc, date?, text (≤ 256 KiB), attachments: [{ name?, type, size }], truncated }`.
- `$metrix.inbox.remove(inboxId, seq)` → permanently deletes a message (`access="manage"`).
- `event("inboxchange", { inboxIds })` notifies when authorized inboxes update.

---

## Image import, HTML rendering & screenshots

### Image import

Declare `apis="image"` (included in `all`; probe `image.load` or `image`) and call `await $metrix.image.load(source)` where `source` is a permitted HTTP(S) URL, an existing `metrix-image://` reference owned by this instance, or an `ArrayBuffer`/`ArrayBufferView`. Decodes PNG, JPEG, first GIF frame, WebP, and BMP (including 1-bit) into PNG, returning `{ src: "metrix-image://…", width, height, format: "png" }`.

- **Limits**: Input & output ≤ **8 MiB**, ≤ **4096 px/side**, ≤ **16,777,216 px**; **1** in-flight load per Worker, **60 s** timeout; shares the **8 images/instance, 128 global, 64 MiB** cache with HTML rendering (retained once referenced by a committed UI tree).
- **Error codes**: `invalid-options`, `unsupported`, `permission-denied`, `asset-failed`, `image-failed`, `not-found`, `budget-exceeded`, `cancelled`, `timeout`.

### HTML rendering

Declare `apis="html"` (included in `all`) and probe `await $metrix.caniuse("html.render")` (macOS live app with system renderer and image cache only; `false` on Windows, Linux, CLI, staging, fixtures, and Playground). Call `await $metrix.html.render(options)` inside async hooks (never `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,
});
// Keep image.src ("metrix-image://...") in state for Image/Avatar nodes.
```

- **Options & limits**: `html` ≤ 1 MiB; optional `readyScript` ≤ 64 KiB; `viewport.width`/`height` integers `1..2048`, `scale` `0.5..4` (default `1`), output ≤ 4096 px/side, ≤ 16M px, ≤ 8 MiB PNG; optional `assets` ≤ 128 unique absolute paths (`≠ "/"`), each `{ path, contentType, body | url, sha256? }` ≤ 16 MiB (32 MiB total; URL assets fetched by Worker with `<network>` permissions—the WebView has no direct network); `timeoutMs` `1..12000` (default `12000`). **1** render per Worker, **2** globally. Returns `{ src, width, height, format: "png", warnings }`, sharing the 8/instance, 128 global, 64 MiB `metrix-image://` cache.
- **Error codes**: `invalid-options`, `unsupported`, `permission-denied`, `webview-failed`, `asset-failed`, `ready-failed`, `timeout`, `budget-exceeded`, `cancelled`.

### Panel screenshots

Declare `apis="screenshot"` (included in `all`) and call `await $metrix.panel.screenshot(options?)` to capture the current Worker's latest committed `view.panel` (even while closed):

- **Options**: `{ theme?: "system"|"light"|"dark", width?: 1..2048, height?: 1..2048, scale?: 0.5..4, output?: "blob"|"file" }`. Default returns an `image/png` `Blob`; `output: "file"` returns a temporary absolute path with exact read-only access (cleaned on Worker close; ≤ 16 files / 64 MiB per Worker; save permanently with `apis="dialog"` + `writeFile`).
- **Limits**: ≤ 16M px, ≤ 8 MiB PNG, 32 MiB decoded bitmap budget, **1** pending per Worker, **2** globally, **15 s** timeout. Unavailable in staging, fixtures, and Playground.

---

## Image recognition (barcode, OCR, face)

Declare `apis="barcode ocr face"` (individually or via `all`) and pass an `ArrayBuffer` or `TypedArray` (≤ **8 MiB**, PNG/JPEG/GIF first frame/WebP, ≤ **4096 px/side**, ≤ **4,000,000 px**; normalized 0..1 top-left coordinates without EXIF rotation):

```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`; deterministic barcode works in fixtures/Playground).
- `ocr.recognize(bytes, { languages? })` → `{ text, lines: [{ text, confidence, bounds: { x, y, width, height } }] }` (macOS Vision Accurate only).
- `face.detect(bytes)` → `{ faces: [{ confidence, bounds: { x, y, width, height } }] }` (macOS Vision rectangles only, no identity recognition).
- **Concurrency**: **1** pending job per Worker across all three, **2** execution slots process-wide.

---

## Audio players & PCM voices

Declare `apis="audio"` (included in `all`):

- **Compressed files/URLs (`$metrix.audio.load({ url | path, stream?: true })`)**: WAV, MP3, Ogg Vorbis (`8000..192000` Hz, 1–2 ch, ≤ 30 min). Methods: `play()`, `pause()`, `stop()`, `seek(s)`, `configure({ volume (0..1), pan (-1..1), playbackRate (0.1..16), loop, loopStart, loopEnd })`, `status()`, `close()`. Limits: **8** players, **8 MiB** per compressed source / **16 MiB** total, **4 MiB** per `stream: false` effect / **16 MiB** pool.
- **PCM Sounds & Voices**: `$metrix.audio.now()` (monotonic seconds), `await $metrix.audio.createSound({ samples: Float32Array, sampleRate, channels })` → `sound.play({ when?, volume?, pan?, playbackRate?, loop?, attackMs? (0..2000) })` → `AudioVoice` (`configure`, `status`, `release({ when?, durationMs? (default 80, 0..2000) })`, `stop`, `close`). 5 ms scheduling ticker (`when` ≤ 5 s ahead). Limits: **64** Sounds (4 MiB each), **32** independent Voices, **32 MiB** shared PCM, **16 MiB** pending PCM copies, **256** queued commands. Call `sound.close()` on `lifecycle/stop`. Staging rejects `play()`.

---

## Desktop capture, calendars, selected text & deadlines

- **Desktop region capture (`apis="desktop-capture"`)**: Call and await `$metrix.system("desktop.captureRegion")` directly inside a panel `Button`'s `onClick` (1 pick/click). Returns a PNG `ArrayBuffer` (≤ 8 MiB, ≤ 16M px) or `null` if canceled. Requires Screen Recording on macOS; Linux uses Spectacle, GNOME Screenshot, XFCE Screenshooter, or Wayland `slurp`/`grim`. Probe `desktop.captureRegion`.
- **Read-only calendars (`apis="calendar"`)**: `calendar.events({ start, end, path? })` queries up to 31 days (Unix ms) returning ≤ 512 sorted events from an authorized `.ics` `path` (all platforms) or a macOS system calendar selected under Privacy when `<calendar />` is declared and `path` is omitted. `calendar.watchFile({ path })` / `calendar.watch()` emit `event("system", { type: "calendar.change", token })`; release with `calendar.stopWatching({ token })`.
- **Selected text (`<permissions><selection-text /></permissions>` + Privacy toggle)**: Non-destructive read of selected text in the frontmost app (`selection.text` → `{ text (≤ 64 KiB), truncated, app?, bounds? }`; `selection.permission` → `{ granted, status, supported }`). Uses macOS Accessibility, Windows UI Automation, and Linux X11 `PRIMARY` (unavailable on Linux Wayland).
- **One-shot deadlines (`apis="deadline"`)**: `deadline.set({ at })` schedules one wake-up per instance (Unix ms ≤ 1 year ahead), firing `event("deadline", { id, at })` even after sleep/restart; cancel with `deadline.cancel({ id })`. Deduplicate by `id`.

---

## Bluetooth Low Energy

Declare `apis="bluetooth"` (or `all`) and `<permissions><bluetooth service="180f" write?="true" /></permissions>` (max 16 exact GATT UUIDs; `all` never grants undeclared services). Probe `bluetooth.capabilities` (`{ supported, transport: "ble" }`) without touching hardware.

| Command                                  | Arguments                                                      | Result                                                                                                                                |
| ---------------------------------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `bluetooth.capabilities`                 | —                                                              | `{ supported, transport: "ble" }`                                                                                                     |
| `bluetooth.scan`                         | `{ services (1..16), durationMs? (100..10000, default 2000) }` | `{ id, name, rssi, services }[]` (≤ 128; replaces previous tokens)                                                                    |
| `bluetooth.connect` / `disconnect`       | `{ device }` / `{ connection }`                                | Opaque connection token / `null`                                                                                                      |
| `bluetooth.services` / `characteristics` | `{ connection }` / `{ connection, service }`                   | Authorized UUIDs / `{ uuid, read, write, notify }[]`                                                                                  |
| `bluetooth.read` / `write`               | `{ connection, service, characteristic, data? }`               | `number[]` / `null` (`write` needs `write="true"`, nonempty `data` ≤ 512 B)                                                           |
| `bluetooth.subscribe` / `unsubscribe`    | `{ connection, service, characteristic }` / `{ token }`        | Subscription token / `null` → `event("system", { type: "bluetooth.notification", token, connection, service, characteristic, data })` |

- **Limits & platforms**: **4** connections, **16** subscriptions, **1** pending command, **12 s** budget, **512 B** values. On macOS (CoreBluetooth, requires Bluetooth permission), read a characteristic before subscribing (reading an actively subscribed characteristic rejects as busy until unsubscribed). Windows uses WinRT BLE; Linux requires BlueZ + system D-Bus. Unavailable in fixtures and Playground.

---

## HID devices

Declare `apis="hid"` (or `all`) and `<permissions><hid vendor-id="0x1234" product-id="0xabcd" usage-page? usage? write? /></permissions>`. On Windows, optional `usage-page`/`usage` narrow the collection; macOS/Linux open whole endpoints (collection-scoped grants match nothing there).

```js
await $metrix.hid.watch(); // Start watching before initial enumerate
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` is required (`false` requires `reportId: 0`; `true` uses `1..255`). `data` is a `Uint8Array` excluding the report ID; writes require `write="true"`.
- `watch()` polls at 1 s intervals and dispatches `event("hid", { type: "connected" | "disconnected", device })` (queue size 32) until `stopWatching()` or Worker close.
- **Limits**: **4** handles, **64** tokens, **4** pending ops (1 per session), **4096 B** payload per report; host-wide 32 handles / 64 native ops. Open sessions in `lifecycle/start` or user actions; unavailable in staging, fixtures, and Playground.
