Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(optimus): listening mode with a talk key, voice engines shared with WhatsApp
Salman Qureshi416f7ff9e1b0
diff --git a/.github/workflows/plugin-optimus.yml b/.github/workflows/plugin-optimus.ymlindex 66813b92..3c226201 100644--- a/.github/workflows/plugin-optimus.yml+++ b/.github/workflows/plugin-optimus.yml@@ -41,7 +41,7 @@ jobs:key: optimus-${{ matrix.target }}-${{ hashFiles('plugins/optimus/companion/Cargo.toml', 'plugins/optimus/companion/Cargo.lock') }}- name: Linux libraries (screen capture, X11 input)if: runner.os == 'Linux'- run: sudo apt-get update && sudo apt-get install -y pkg-config clang libclang-dev libxcb1-dev libxrandr-dev libdbus-1-dev libpipewire-0.3-dev libwayland-dev libegl-dev libgbm-dev libxdo-dev+ run: sudo apt-get update && sudo apt-get install -y pkg-config clang libclang-dev libxcb1-dev libxrandr-dev libdbus-1-dev libpipewire-0.3-dev libwayland-dev libegl-dev libgbm-dev libxdo-dev libasound2-dev- name: Buildworking-directory: plugins/optimus/companionrun: cargo build --release --locked --target ${{ matrix.target }} || cargo build --release --target ${{ matrix.target }}diff --git a/plugins/optimus/README.md b/plugins/optimus/README.mdindex a63e9aca..1ca3d89f 100644--- a/plugins/optimus/README.md+++ b/plugins/optimus/README.md@@ -1,6 +1,6 @@# Optimus-Mercury uses your computer like a person: it sees the screen, moves the mouse, types, and opens apps, on macOS, Windows and Linux.+Mercury uses your computer like a person: it sees the screen, moves the mouse, types, and opens apps, on macOS, Windows and Linux. Use it by chat, or out loud with a talk key.## Setup@@ -8,11 +8,25 @@ Mercury uses your computer like a person: it sees the screen, moves the mouse, tmercury plugins install optimus```-Setup asks one question: **Let Optimus control this computer?** Nothing works until you say yes (change it later in `/plugins optimus`).+Setup asks:++1. **Let Optimus control this computer?** Nothing works until you say yes.+2. **How do you want to talk to Optimus?** Chat, Listening, or Both (recommended).+3. **Key to start and stop talking** (default `ctrl+alt+m`: Control+Option+M on a Mac).+4. **Who listens and speaks?** OpenAI is used automatically when Mercury has an OpenAI key; otherwise pick Gemini, Grok, ElevenLabs, Azure, Qwen, or your own Mercury model with Deepgram/Cartesia/etc. Keys you added for the WhatsApp plugin work here too.++Change any of it later in `/plugins optimus`.- **macOS:** Optimus builds `Optimus.app` in its data folder and signs it with a certificate made on your Mac (no Apple account involved), then asks for two permissions in System Settings → Privacy & Security: **Accessibility** (mouse and keyboard) and **Screen Recording** (seeing the screen). The permissions survive updates. macOS asks you to confirm Screen Recording again about once a month.- **Windows:** nothing to grant. Windows running as administrator (Task Manager, installers) can't be controlled yet.-- **Linux:** works fully on X11. On Wayland, screenshots go through the desktop's screen-sharing prompt and input reaches only X11 apps for now.+- **Linux:** works fully on X11. On Wayland, screenshots go through the desktop's screen-sharing prompt, and input and the talk key reach only X11 apps for now (use chat, or the `listen` tool).++## Talking to it++- **Chat:** ask Mercury in any chat (TUI, dashboard, WhatsApp, Telegram): "look at my screen", "open Safari and search for…".+- **Listening:** press the talk key (you hear a rising chime), talk, and Mercury answers out loud while it works on your screen. Press the key while it's speaking to interrupt; press it when it's quiet, or say goodbye, to stop (falling chime). Links and details go to your Mercury chat. Approvals are asked out loud.+- With speakers, the mic is muted while Mercury talks so it doesn't hear itself. With headphones, turn on "I use headphones" in `/plugins optimus` → 🎙 Voice to interrupt just by talking.+- macOS asks once for the **Microphone** for Optimus.## What it can do@@ -24,6 +38,7 @@ Setup asks one question: **Let Optimus control this computer?** Nothing works un| `open` | Open an app by name, a URL, or a file || `windows` | List open windows || `permissions` | Check (and request) the OS permissions |+| `listen` | Start a voice conversation from chat ("let's talk") |## Safety@@ -40,4 +55,4 @@ cd plugins/optimus/companion && cargo build --releasenode plugins/optimus/package.mjs companion/target/release/mercury-optimus darwin-arm64 dist```-Linux needs `libxcb1-dev libxrandr-dev libdbus-1-dev libpipewire-0.3-dev libwayland-dev libegl-dev libgbm-dev clang` to build.+Linux needs `libxcb1-dev libxrandr-dev libdbus-1-dev libpipewire-0.3-dev libwayland-dev libegl-dev libgbm-dev libasound2-dev clang` to build.diff --git a/plugins/optimus/companion/.gitignore b/plugins/optimus/companion/.gitignorenew file mode 100644index 00000000..2f7896d1--- /dev/null+++ b/plugins/optimus/companion/.gitignore@@ -0,0 +1 @@+target/diff --git a/plugins/optimus/companion/Cargo.lock b/plugins/optimus/companion/Cargo.locknew file mode 100644index 00000000..323020a7--- /dev/null+++ b/plugins/optimus/companion/Cargo.lock@@ -0,0 +1,3425 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "adler2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"++[[package]]+name = "aho-corasick"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"+dependencies = [+ "memchr",+]++[[package]]+name = "alsa"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed7572b7ba83a31e20d1b48970ee402d2e3e0537dcfe0a3ff4d6eb7508617d43"+dependencies = [+ "alsa-sys",+ "bitflags 2.13.2",+ "cfg-if",+ "libc",+]++[[package]]+name = "alsa-sys"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db8fee663d06c4e303404ef5f40488a53e062f89ba8bfed81f42325aafad1527"+dependencies = [+ "libc",+ "pkg-config",+]++[[package]]+name = "annotate-snippets"+version = "0.11.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "710e8eae58854cdc1790fcb56cca04d712a17be849eeb81da2a724bf4bae2bc4"+dependencies = [+ "anstyle",+ "unicode-width",+]++[[package]]+name = "anstyle"+version = "1.0.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"++[[package]]+name = "async-broadcast"+version = "0.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"+dependencies = [+ "event-listener",+ "event-listener-strategy",+ "futures-core",+ "pin-project-lite",+]++[[package]]+name = "async-channel"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"+dependencies = [+ "concurrent-queue",+ "event-listener-strategy",+ "futures-core",+ "pin-project-lite",+]++[[package]]+name = "async-executor"+version = "1.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"+dependencies = [+ "async-task",+ "concurrent-queue",+ "fastrand",+ "futures-lite",+ "pin-project-lite",+ "slab",+]++[[package]]+name = "async-io"+version = "2.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"+dependencies = [+ "autocfg",+ "cfg-if",+ "concurrent-queue",+ "futures-io",+ "futures-lite",+ "parking",+ "polling",+ "rustix 1.1.5",+ "slab",+ "windows-sys 0.61.2",+]++[[package]]+name = "async-lock"+version = "3.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"+dependencies = [+ "event-listener",+ "event-listener-strategy",+ "pin-project-lite",+]++[[package]]+name = "async-process"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"+dependencies = [+ "async-channel",+ "async-io",+ "async-lock",+ "async-signal",+ "async-task",+ "blocking",+ "cfg-if",+ "event-listener",+ "futures-lite",+ "rustix 1.1.5",+]++[[package]]+name = "async-recursion"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]++[[package]]+name = "async-signal"+version = "0.2.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485"+dependencies = [+ "async-io",+ "async-lock",+ "atomic-waker",+ "cfg-if",+ "futures-core",+ "futures-io",+ "rustix 1.1.5",+ "signal-hook-registry",+ "slab",+ "windows-sys 0.61.2",+]++[[package]]+name = "async-task"+version = "4.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"++[[package]]+name = "async-trait"+version = "0.1.92"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]++[[package]]+name = "atomic-waker"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"++[[package]]+name = "autocfg"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"++[[package]]+name = "base64"+version = "0.22.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"++[[package]]+name = "base64"+version = "0.23.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"++[[package]]+name = "bindgen"+version = "0.72.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"+dependencies = [+ "annotate-snippets",+ "bitflags 2.13.2",+ "cexpr",+ "clang-sys",+ "itertools",+ "proc-macro2",+ "quote",+ "regex",+ "rustc-hash",+ "shlex 1.3.0",+ "syn 2.0.119",+]++[[package]]+name = "bitflags"+version = "1.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"++[[package]]+name = "bitflags"+version = "2.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"++[[package]]+name = "block2"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"+dependencies = [+ "objc2",+]++[[package]]+name = "blocking"+version = "1.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa"+dependencies = [+ "async-channel",+ "async-task",+ "futures-io",+ "futures-lite",+ "piper",+]++[[package]]+name = "bumpalo"+version = "3.20.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"++[[package]]+name = "bytemuck"+version = "1.25.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"+dependencies = [+ "bytemuck_derive",+]++[[package]]+name = "bytemuck_derive"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]++[[package]]+name = "byteorder-lite"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"++[[package]]+name = "bytes"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"++[[package]]+name = "cc"+version = "1.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "877bf67ac8e52449eb2f9e98a344ea163beb70dd1f9eebe3cc5357dcfeaee4df"+dependencies = [+ "find-msvc-tools",+ "shlex 2.0.1",+]++[[package]]+name = "cesu8"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"++[[package]]+name = "cexpr"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"+dependencies = [+ "nom 7.1.3",+]++[[package]]+name = "cfg-expr"+version = "0.20.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ba9e9ec16c447027685b1f897b720e18e9a8afd00bd7332c483537e38086c9f"+dependencies = [+ "smallvec",+ "target-lexicon",+]++[[package]]+name = "cfg-if"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"++[[package]]+name = "chacha20"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "rand_core",+]++[[package]]+name = "clang-sys"+version = "1.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a"+dependencies = [+ "glob",+ "libc",+ "libloading",+]++[[package]]+name = "combine"+version = "4.6.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92"+dependencies = [+ "bytes",+ "memchr",+]++[[package]]+name = "concurrent-queue"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "cookie-factory"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9885fa71e26b8ab7855e2ec7cae6e9b380edff76cd052e07c683a0319d51b3a2"++[[package]]+name = "core-foundation"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "core-foundation-sys"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"++[[package]]+name = "core-graphics"+version = "0.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fa95a34622365fa5bbf40b20b75dba8dfa8c94c734aea8ac9a5ca38af14316f1"+dependencies = [+ "bitflags 2.13.2",+ "core-foundation",+ "core-graphics-types",+ "foreign-types",+ "libc",+]++[[package]]+name = "core-graphics"+version = "0.25.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97"+dependencies = [+ "bitflags 2.13.2",+ "core-foundation",+ "core-graphics-types",+ "foreign-types",+ "libc",+]++[[package]]+name = "core-graphics-types"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"+dependencies = [+ "bitflags 2.13.2",+ "core-foundation",+ "libc",+]++[[package]]+name = "coreaudio-rs"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1aae284fbaf7d27aa0e292f7677dfbe26503b0d555026f702940805a630eac17"+dependencies = [+ "bitflags 1.3.2",+ "libc",+ "objc2-audio-toolbox",+ "objc2-core-audio",+ "objc2-core-audio-types",+ "objc2-core-foundation",+]++[[package]]+name = "cpal"+version = "0.16.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cbd307f43cc2a697e2d1f8bc7a1d824b5269e052209e28883e5bc04d095aaa3f"+dependencies = [+ "alsa",+ "coreaudio-rs",+ "dasp_sample",+ "jni",+ "js-sys",+ "libc",+ "mach2",+ "ndk",+ "ndk-context",+ "num-derive",+ "num-traits",+ "objc2-audio-toolbox",+ "objc2-core-audio",+ "objc2-core-audio-types",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+ "windows 0.54.0",+]++[[package]]+name = "cpufeatures"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"+dependencies = [+ "libc",+]++[[package]]+name = "crc32fast"+version = "1.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055"+dependencies = [+ "cfg-if",+]++[[package]]+name = "crossbeam-utils"+version = "0.8.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"++[[package]]+name = "dasp_sample"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f"++[[package]]+name = "dispatch2"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "libc",+ "objc2",+]++[[package]]+name = "displaydoc"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]++[[package]]+name = "dlib"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a"+dependencies = [+ "libloading",+]++[[package]]+name = "downcast-rs"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"++[[package]]+name = "drm"+version = "0.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "80bc8c5c6c2941f70a55c15f8d9f00f9710ebda3ffda98075f996a0e6c92756f"+dependencies = [+ "bitflags 2.13.2",+ "bytemuck",+ "drm-ffi",+ "drm-fourcc",+ "libc",+ "rustix 0.38.44",+]++[[package]]+name = "drm"+version = "0.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7a41816e58f47f49acfd956651055ddcf137c4882c2098c30c448817af21183a"+dependencies = [+ "bitflags 2.13.2",+ "bytemuck",+ "bytemuck_derive",+ "drm-ffi",+ "drm-fourcc",+ "libc",+ "rustix 1.1.5",+]++[[package]]+name = "drm-ffi"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "51a91c9b32ac4e8105dec255e849e0d66e27d7c34d184364fb93e469db08f690"+dependencies = [+ "drm-sys",+ "rustix 1.1.5",+]++[[package]]+name = "drm-fourcc"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0aafbcdb8afc29c1a7ee5fbe53b5d62f4565b35a042a662ca9fecd0b54dae6f4"++[[package]]+name = "drm-sys"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ecc8e1361066d91f5ffccff060a3c3be9c3ecde15be2959c1937595f7a82a9f8"+dependencies = [+ "libc",+ "linux-raw-sys 0.9.4",+]++[[package]]+name = "either"+version = "1.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"++[[package]]+name = "endi"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"++[[package]]+name = "enigo"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "71c6c56e50f7acae2906a0dcbb34529ca647e40421119ad5d12e7f8ba6e50010"+dependencies = [+ "core-foundation",+ "core-graphics 0.25.0",+ "foreign-types-shared",+ "libc",+ "log",+ "nom 8.0.0",+ "objc2",+ "objc2-app-kit",+ "objc2-foundation",+ "windows 0.61.3",+ "x11rb",+ "xkbcommon",+ "xkeysym",+]++[[package]]+name = "enumflags2"+version = "0.7.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"+dependencies = [+ "enumflags2_derive",+ "serde",+]++[[package]]+name = "enumflags2_derive"+version = "0.7.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "equivalent"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"++[[package]]+name = "errno"+version = "0.3.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]++[[package]]+name = "event-listener"+version = "5.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"+dependencies = [+ "parking",+ "pin-project-lite",+]++[[package]]+name = "event-listener-strategy"+version = "0.5.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"+dependencies = [+ "event-listener",+ "pin-project-lite",+]++[[package]]+name = "fastrand"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"++[[package]]+name = "fdeflate"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"+dependencies = [+ "simd-adler32",+]++[[package]]+name = "find-msvc-tools"+version = "0.1.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"++[[package]]+name = "flate2"+version = "1.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"+dependencies = [+ "crc32fast",+ "miniz_oxide 0.9.1",+ "zlib-rs",+]++[[package]]+name = "foreign-types"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"+dependencies = [+ "foreign-types-macros",+ "foreign-types-shared",+]++[[package]]+name = "foreign-types-macros"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]++[[package]]+name = "foreign-types-shared"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"++[[package]]+name = "form_urlencoded"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"+dependencies = [+ "percent-encoding",+]++[[package]]+name = "futures-core"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"++[[package]]+name = "futures-io"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"++[[package]]+name = "futures-lite"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"+dependencies = [+ "fastrand",+ "futures-core",+ "futures-io",+ "parking",+ "pin-project-lite",+]++[[package]]+name = "futures-sink"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"++[[package]]+name = "futures-task"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"++[[package]]+name = "futures-util"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"+dependencies = [+ "futures-core",+ "futures-sink",+ "futures-task",+ "pin-project-lite",+ "slab",+]++[[package]]+name = "gbm"+version = "0.18.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ce852e998d3ca5e4a97014fb31c940dc5ef344ec7d364984525fd11e8a547e6a"+dependencies = [+ "bitflags 2.13.2",+ "drm 0.14.1",+ "drm-fourcc",+ "gbm-sys",+ "libc",+ "wayland-backend",+ "wayland-server",+]++[[package]]+name = "gbm-sys"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c13a5f2acc785d8fb6bf6b7ab6bfb0ef5dad4f4d97e8e70bb8e470722312f76f"+dependencies = [+ "libc",+]++[[package]]+name = "gethostname"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"+dependencies = [+ "rustix 1.1.5",+ "windows-link 0.2.1",+]++[[package]]+name = "getrandom"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"+dependencies = [+ "cfg-if",+ "libc",+ "wasi",+]++[[package]]+name = "getrandom"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"+dependencies = [+ "cfg-if",+ "libc",+ "r-efi",+ "rand_core",+]++[[package]]+name = "gl"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a94edab108827d67608095e269cf862e60d920f144a5026d3dbcfd8b877fb404"+dependencies = [+ "gl_generator",+]++[[package]]+name = "gl_generator"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d"+dependencies = [+ "khronos_api",+ "log",+ "xml-rs",+]++[[package]]+name = "glob"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"++[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"++[[package]]+name = "heck"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"++[[package]]+name = "hermit-abi"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"++[[package]]+name = "hex"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"++[[package]]+name = "http"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"+dependencies = [+ "bytes",+ "itoa",+]++[[package]]+name = "httparse"+version = "1.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"++[[package]]+name = "icu_collections"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd"+dependencies = [+ "displaydoc",+ "potential_utf",+ "utf8_iter",+ "yoke",+ "zerofrom",+ "zerovec",+]++[[package]]+name = "icu_locale_core"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0"+dependencies = [+ "displaydoc",+ "litemap",+ "tinystr",+ "writeable",+ "zerovec",+]++[[package]]+name = "icu_normalizer"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599"+dependencies = [+ "icu_collections",+ "icu_normalizer_data",+ "icu_properties",+ "icu_provider",+ "smallvec",+ "zerovec",+]++[[package]]+name = "icu_normalizer_data"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc"++[[package]]+name = "icu_properties"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f"+dependencies = [+ "displaydoc",+ "icu_collections",+ "icu_locale_core",+ "icu_properties_data",+ "icu_provider",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "icu_properties_data"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf"++[[package]]+name = "icu_provider"+version = "2.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514"+dependencies = [+ "displaydoc",+ "icu_locale_core",+ "writeable",+ "yoke",+ "zerofrom",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "idna"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"+dependencies = [+ "idna_adapter",+ "smallvec",+ "utf8_iter",+]++[[package]]+name = "idna_adapter"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"+dependencies = [+ "icu_normalizer",+ "icu_properties",+]++[[package]]+name = "image"+version = "0.25.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"+dependencies = [+ "bytemuck",+ "byteorder-lite",+ "moxcms",+ "num-traits",+ "png",+ "zune-core",+ "zune-jpeg",+]++[[package]]+name = "indexmap"+version = "2.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"+dependencies = [+ "equivalent",+ "hashbrown",+]++[[package]]+name = "itertools"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"+dependencies = [+ "either",+]++[[package]]+name = "itoa"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"++[[package]]+name = "jni"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97"+dependencies = [+ "cesu8",+ "cfg-if",+ "combine",+ "jni-sys 0.3.1",+ "log",+ "thiserror 1.0.69",+ "walkdir",+ "windows-sys 0.45.0",+]++[[package]]+name = "jni-sys"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"+dependencies = [+ "jni-sys 0.4.1",+]++[[package]]+name = "jni-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"+dependencies = [+ "jni-sys-macros",+]++[[package]]+name = "jni-sys-macros"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"+dependencies = [+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "js-sys"+version = "0.3.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"+dependencies = [+ "cfg-if",+ "futures-util",+ "wasm-bindgen",+]++[[package]]+name = "khronos-egl"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6aae1df220ece3c0ada96b8153459b67eebe9ae9212258bb0134ae60416fdf76"+dependencies = [+ "libc",+ "pkg-config",+]++[[package]]+name = "khronos_api"+version = "3.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc"++[[package]]+name = "libc"+version = "0.2.191"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"++[[package]]+name = "libloading"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"+dependencies = [+ "cfg-if",+ "windows-link 0.2.1",+]++[[package]]+name = "libspa"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "882f7427e7989dcc9d388b7f05c4630390a1d7696f9ffa469cd4a7a48f0b4c40"+dependencies = [+ "bitflags 2.13.2",+ "cc",+ "cookie-factory",+ "libc",+ "libspa-sys",+ "nom 8.0.0",+ "rustix 1.1.5",+ "system-deps",+]++[[package]]+name = "libspa-sys"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b6e17bdaf63ed0d5e4144022624032b41fd9733112e8c74ac26fc9bf1291924"+dependencies = [+ "bindgen",+ "cc",+ "system-deps",+]++[[package]]+name = "libwayshot-xcap"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea8a46e4d016ef464e386e4970f5415fe0939c2d63abe0c2f539c05ef88c5fe5"+dependencies = [+ "drm 0.15.0",+ "gbm",+ "gl",+ "image",+ "khronos-egl",+ "memmap2",+ "rustix 1.1.5",+ "thiserror 2.0.21",+ "tracing",+ "wayland-backend",+ "wayland-client",+ "wayland-protocols",+ "wayland-protocols-wlr",+]++[[package]]+name = "linux-raw-sys"+version = "0.4.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"++[[package]]+name = "linux-raw-sys"+version = "0.9.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12"++[[package]]+name = "linux-raw-sys"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"++[[package]]+name = "litemap"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"++[[package]]+name = "log"+version = "0.4.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"++[[package]]+name = "mach2"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d640282b302c0bb0a2a8e0233ead9035e3bed871f0b7e81fe4a1ec829765db44"+dependencies = [+ "libc",+]++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "memmap2"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157"+dependencies = [+ "libc",+]++[[package]]+name = "memoffset"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"+dependencies = [+ "autocfg",+]++[[package]]+name = "mercury-optimus"+version = "0.2.0"+dependencies = [+ "base64 0.22.1",+ "core-foundation",+ "core-graphics 0.24.0",+ "cpal",+ "enigo",+ "futures-util",+ "http",+ "image",+ "serde_json",+ "tokio",+ "tokio-websockets",+ "ureq",+ "windows-sys 0.61.2",+ "x11rb",+ "xcap",+]++[[package]]+name = "minimal-lexical"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"++[[package]]+name = "miniz_oxide"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[package]]+name = "miniz_oxide"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[package]]+name = "mio"+version = "1.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"+dependencies = [+ "libc",+ "wasi",+ "windows-sys 0.61.2",+]++[[package]]+name = "moxcms"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"+dependencies = [+ "num-traits",+ "pxfm",+]++[[package]]+name = "ndk"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"+dependencies = [+ "bitflags 2.13.2",+ "jni-sys 0.3.1",+ "log",+ "ndk-sys",+ "num_enum",+ "thiserror 1.0.69",+]++[[package]]+name = "ndk-context"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"++[[package]]+name = "ndk-sys"+version = "0.6.0+11769913"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"+dependencies = [+ "jni-sys 0.3.1",+]++[[package]]+name = "nom"+version = "7.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"+dependencies = [+ "memchr",+ "minimal-lexical",+]++[[package]]+name = "nom"+version = "8.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"+dependencies = [+ "memchr",+]++[[package]]+name = "num-derive"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+]++[[package]]+name = "num_enum"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26"+dependencies = [+ "num_enum_derive",+ "rustversion",+]++[[package]]+name = "num_enum_derive"+version = "0.7.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"+dependencies = [+ "proc-macro-crate",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "objc2"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"+dependencies = [+ "objc2-encode",+]++[[package]]+name = "objc2-app-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "libc",+ "objc2",+ "objc2-cloud-kit",+ "objc2-core-data",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-core-image",+ "objc2-core-text",+ "objc2-core-video",+ "objc2-foundation",+ "objc2-quartz-core",+]++[[package]]+name = "objc2-audio-toolbox"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6948501a91121d6399b79abaa33a8aa4ea7857fe019f341b8c23ad6e81b79b08"+dependencies = [+ "bitflags 2.13.2",+ "libc",+ "objc2",+ "objc2-core-audio",+ "objc2-core-audio-types",+ "objc2-core-foundation",+ "objc2-foundation",+]++[[package]]+name = "objc2-av-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "478ae33fcac9df0a18db8302387c666b8ef08a3e2d62b510ca4fc278a384b6c0"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "dispatch2",+ "objc2",+ "objc2-avf-audio",+ "objc2-core-audio-types",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-core-image",+ "objc2-core-video",+ "objc2-foundation",+ "objc2-image-io",+ "objc2-media-toolbox",+ "objc2-quartz-core",+]++[[package]]+name = "objc2-avf-audio"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13a380031deed8e99db00065c45937da434ca987c034e13b87e4441f9e4090be"+dependencies = [+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-cloud-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-core-audio"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2"+dependencies = [+ "dispatch2",+ "objc2",+ "objc2-core-audio-types",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-core-audio-types"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+]++[[package]]+name = "objc2-core-data"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-core-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "dispatch2",+ "libc",+ "objc2",+]++[[package]]+name = "objc2-core-graphics"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "dispatch2",+ "libc",+ "objc2",+ "objc2-core-foundation",+ "objc2-io-surface",+ "objc2-metal",+]++[[package]]+name = "objc2-core-image"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006"+dependencies = [+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-core-media"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "05ec576860167a15dd9fce7fbee7512beb4e31f532159d3482d1f9c6caedf31d"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "dispatch2",+ "objc2",+ "objc2-core-audio",+ "objc2-core-audio-types",+ "objc2-core-foundation",+ "objc2-core-video",+]++[[package]]+name = "objc2-core-text"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+ "objc2-core-foundation",+ "objc2-core-graphics",+]++[[package]]+name = "objc2-core-video"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "objc2",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-io-surface",+ "objc2-metal",+]++[[package]]+name = "objc2-encode"+version = "4.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"++[[package]]+name = "objc2-foundation"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "libc",+ "objc2",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-image-io"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32b0446e98cf4a784cc7a0177715ff317eeaa8463841c616cfc78aa4f953c4ea"+dependencies = [+ "objc2",+ "objc2-core-foundation",+ "objc2-core-graphics",+]++[[package]]+name = "objc2-io-surface"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-media-toolbox"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "edd9fdde720df3da7046bb9097811000c1e7ab5cd579fa89d96b27d56781fb30"+dependencies = [+ "objc2",+ "objc2-core-audio-types",+ "objc2-core-foundation",+ "objc2-core-media",+]++[[package]]+name = "objc2-metal"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-quartz-core"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[package]]+name = "ordered-stream"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"+dependencies = [+ "futures-core",+ "pin-project-lite",+]++[[package]]+name = "parking"+version = "2.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"++[[package]]+name = "percent-encoding"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"++[[package]]+name = "pin-project-lite"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"++[[package]]+name = "piper"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1"+dependencies = [+ "atomic-waker",+ "fastrand",+ "futures-io",+]++[[package]]+name = "pipewire"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bde71084c4e25959d68f1ea54daa75e5ecdb338e5caf0b5510143b79baa32d5c"+dependencies = [+ "bitflags 2.13.2",+ "libc",+ "libspa",+ "libspa-sys",+ "pipewire-sys",+ "rustix 1.1.5",+]++[[package]]+name = "pipewire-sys"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ce653f53e63e5b93853218092ee9a8906a5d082c92f3f1db26316955dd63ce0"+dependencies = [+ "bindgen",+ "libspa-sys",+ "system-deps",+]++[[package]]+name = "pkg-config"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"++[[package]]+name = "png"+version = "0.18.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"+dependencies = [+ "bitflags 2.13.2",+ "crc32fast",+ "fdeflate",+ "flate2",+ "miniz_oxide 0.8.9",+]++[[package]]+name = "polling"+version = "3.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"+dependencies = [+ "cfg-if",+ "concurrent-queue",+ "hermit-abi",+ "pin-project-lite",+ "rustix 1.1.5",+ "windows-sys 0.61.2",+]++[[package]]+name = "potential_utf"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"+dependencies = [+ "zerovec",+]++[[package]]+name = "proc-macro-crate"+version = "3.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"+dependencies = [+ "toml_edit",+]++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "pxfm"+version = "0.1.30"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"++[[package]]+name = "quick-xml"+version = "0.41.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"+dependencies = [+ "memchr",+]++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"++[[package]]+name = "rand"+version = "0.10.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"+dependencies = [+ "chacha20",+ "getrandom 0.4.3",+ "rand_core",+]++[[package]]+name = "rand_core"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"++[[package]]+name = "regex"+version = "1.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "regex-automata"+version = "0.4.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"++[[package]]+name = "ring"+version = "0.17.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"+dependencies = [+ "cc",+ "cfg-if",+ "getrandom 0.2.17",+ "libc",+ "untrusted",+ "windows-sys 0.52.0",+]++[[package]]+name = "rustc-hash"+version = "2.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"++[[package]]+name = "rustix"+version = "0.38.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"+dependencies = [+ "bitflags 2.13.2",+ "errno",+ "libc",+ "linux-raw-sys 0.4.15",+ "windows-sys 0.59.0",+]++[[package]]+name = "rustix"+version = "1.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"+dependencies = [+ "bitflags 2.13.2",+ "errno",+ "libc",+ "linux-raw-sys 0.12.1",+ "windows-sys 0.61.2",+]++[[package]]+name = "rustls"+version = "0.23.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"+dependencies = [+ "log",+ "once_cell",+ "ring",+ "rustls-pki-types",+ "rustls-webpki",+ "subtle",+ "zeroize",+]++[[package]]+name = "rustls-pki-types"+version = "1.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"+dependencies = [+ "zeroize",+]++[[package]]+name = "rustls-webpki"+version = "0.103.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"+dependencies = [+ "ring",+ "rustls-pki-types",+ "untrusted",+]++[[package]]+name = "rustversion"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"++[[package]]+name = "same-file"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"+dependencies = [+ "winapi-util",+]++[[package]]+name = "scoped-tls"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294"++[[package]]+name = "scopeguard"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"++[[package]]+name = "serde"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"+dependencies = [+ "serde_core",+ "serde_derive",+]++[[package]]+name = "serde_core"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.229"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]++[[package]]+name = "serde_json"+version = "1.0.154"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"+dependencies = [+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]++[[package]]+name = "serde_repr"+version = "0.1.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]++[[package]]+name = "serde_spanned"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c"+dependencies = [+ "serde_core",+]++[[package]]+name = "shlex"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "signal-hook-registry"+version = "1.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"+dependencies = [+ "errno",+ "libc",+]++[[package]]+name = "simd-adler32"+version = "0.3.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"++[[package]]+name = "simdutf8"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"++[[package]]+name = "slab"+version = "0.4.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"++[[package]]+name = "smallvec"+version = "1.16.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b"++[[package]]+name = "socket2"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]++[[package]]+name = "stable_deref_trait"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"++[[package]]+name = "subtle"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "syn"+version = "3.0.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "synstructure"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]++[[package]]+name = "system-deps"+version = "7.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7"+dependencies = [+ "cfg-expr",+ "heck",+ "pkg-config",+ "toml",+ "version-compare",+]++[[package]]+name = "target-lexicon"+version = "0.13.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"++[[package]]+name = "tempfile"+version = "3.27.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"+dependencies = [+ "fastrand",+ "getrandom 0.4.3",+ "once_cell",+ "rustix 1.1.5",+ "windows-sys 0.61.2",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl 1.0.69",+]++[[package]]+name = "thiserror"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"+dependencies = [+ "thiserror-impl 2.0.21",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "thiserror-impl"+version = "2.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]++[[package]]+name = "tinystr"+version = "0.8.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a"+dependencies = [+ "displaydoc",+ "zerovec",+]++[[package]]+name = "tokio"+version = "1.54.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"+dependencies = [+ "bytes",+ "libc",+ "mio",+ "pin-project-lite",+ "socket2",+ "tokio-macros",+ "windows-sys 0.61.2",+]++[[package]]+name = "tokio-macros"+version = "2.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]++[[package]]+name = "tokio-rustls"+version = "0.26.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db"+dependencies = [+ "rustls",+ "tokio",+]++[[package]]+name = "tokio-util"+version = "0.7.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b"+dependencies = [+ "bytes",+ "futures-core",+ "futures-sink",+ "libc",+ "pin-project-lite",+ "tokio",+]++[[package]]+name = "tokio-websockets"+version = "0.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d52efb639344a7c6adb8e62c6f3d2c19c001ff1b79a5041ba1c6ed42e19c6aa5"+dependencies = [+ "base64 0.22.1",+ "bytes",+ "futures-core",+ "futures-sink",+ "http",+ "httparse",+ "rand",+ "ring",+ "rustls-pki-types",+ "simdutf8",+ "tokio",+ "tokio-rustls",+ "tokio-util",+ "webpki-roots",+]++[[package]]+name = "toml"+version = "1.1.8+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d"+dependencies = [+ "indexmap",+ "serde_core",+ "serde_spanned",+ "toml_datetime",+ "toml_parser",+ "toml_writer",+ "winnow",+]++[[package]]+name = "toml_datetime"+version = "1.1.2+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053"+dependencies = [+ "serde_core",+]++[[package]]+name = "toml_edit"+version = "0.25.17+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c"+dependencies = [+ "indexmap",+ "toml_datetime",+ "toml_parser",+ "winnow",+]++[[package]]+name = "toml_parser"+version = "1.1.5+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"+dependencies = [+ "winnow",+]++[[package]]+name = "toml_writer"+version = "1.1.3+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770"++[[package]]+name = "tracing"+version = "0.1.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"+dependencies = [+ "pin-project-lite",+ "tracing-attributes",+ "tracing-core",+]++[[package]]+name = "tracing-attributes"+version = "0.1.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "tracing-core"+version = "0.1.36"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"+dependencies = [+ "once_cell",+]++[[package]]+name = "uds_windows"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"+dependencies = [+ "memoffset",+ "tempfile",+ "windows-sys 0.61.2",+]++[[package]]+name = "unicode-ident"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"++[[package]]+name = "unicode-width"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"++[[package]]+name = "untrusted"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"++[[package]]+name = "ureq"+version = "3.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cde93ff05758a36a851a398a772b0b79a82fbe3c186a46f2696baaeaf84c966b"+dependencies = [+ "base64 0.23.1",+ "flate2",+ "log",+ "percent-encoding",+ "rustls",+ "rustls-pki-types",+ "ureq-proto",+ "utf8-zero",+ "webpki-roots",+]++[[package]]+name = "ureq-proto"+version = "0.6.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922"+dependencies = [+ "base64 0.23.1",+ "http",+ "httparse",+ "log",+]++[[package]]+name = "url"+version = "2.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"+dependencies = [+ "form_urlencoded",+ "idna",+ "percent-encoding",+ "serde",+]++[[package]]+name = "utf8-zero"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"++[[package]]+name = "utf8_iter"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"++[[package]]+name = "uuid"+version = "1.28.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606"+dependencies = [+ "js-sys",+ "serde_core",+ "wasm-bindgen",+]++[[package]]+name = "version-compare"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e"++[[package]]+name = "walkdir"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"+dependencies = [+ "same-file",+ "winapi-util",+]++[[package]]+name = "wasi"+version = "0.11.1+wasi-snapshot-preview1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"++[[package]]+name = "wasm-bindgen"+version = "0.2.129"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409"+dependencies = [+ "cfg-if",+ "once_cell",+ "rustversion",+ "wasm-bindgen-macro",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-futures"+version = "0.4.79"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e"+dependencies = [+ "js-sys",+ "tokio",+ "wasm-bindgen",+]++[[package]]+name = "wasm-bindgen-macro"+version = "0.2.129"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535"+dependencies = [+ "quote",+ "wasm-bindgen-macro-support",+]++[[package]]+name = "wasm-bindgen-macro-support"+version = "0.2.129"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7"+dependencies = [+ "bumpalo",+ "proc-macro2",+ "quote",+ "syn 3.0.9",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-shared"+version = "0.2.129"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "wayland-backend"+version = "0.3.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078"+dependencies = [+ "cc",+ "downcast-rs",+ "rustix 1.1.5",+ "scoped-tls",+ "smallvec",+ "wayland-sys",+]++[[package]]+name = "wayland-client"+version = "0.31.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073"+dependencies = [+ "bitflags 2.13.2",+ "rustix 1.1.5",+ "wayland-backend",+ "wayland-scanner",+]++[[package]]+name = "wayland-protocols"+version = "0.32.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6"+dependencies = [+ "bitflags 2.13.2",+ "wayland-backend",+ "wayland-client",+ "wayland-scanner",+]++[[package]]+name = "wayland-protocols-wlr"+version = "0.3.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234"+dependencies = [+ "bitflags 2.13.2",+ "wayland-backend",+ "wayland-client",+ "wayland-protocols",+ "wayland-scanner",+]++[[package]]+name = "wayland-scanner"+version = "0.31.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"+dependencies = [+ "proc-macro2",+ "quick-xml",+ "quote",+]++[[package]]+name = "wayland-server"+version = "0.31.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0dde9c29be0f723a573977de51ee455bf3dfa03652730a74f9dd3b337e374d75"+dependencies = [+ "bitflags 2.13.2",+ "downcast-rs",+ "rustix 1.1.5",+ "wayland-backend",+ "wayland-scanner",+]++[[package]]+name = "wayland-sys"+version = "0.31.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be"+dependencies = [+ "dlib",+ "libc",+ "log",+ "memoffset",+ "pkg-config",+]++[[package]]+name = "web-sys"+version = "0.3.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "webpki-roots"+version = "1.0.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9"+dependencies = [+ "rustls-pki-types",+]++[[package]]+name = "widestring"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471"++[[package]]+name = "winapi-util"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "windows"+version = "0.54.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9252e5725dbed82865af151df558e754e4a3c2c30818359eb17465f1346a1b49"+dependencies = [+ "windows-core 0.54.0",+ "windows-targets 0.52.6",+]++[[package]]+name = "windows"+version = "0.61.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"+dependencies = [+ "windows-collections 0.2.0",+ "windows-core 0.61.2",+ "windows-future 0.2.1",+ "windows-link 0.1.3",+ "windows-numerics 0.2.0",+]++[[package]]+name = "windows"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"+dependencies = [+ "windows-collections 0.3.2",+ "windows-core 0.62.2",+ "windows-future 0.3.2",+ "windows-numerics 0.3.1",+]++[[package]]+name = "windows-collections"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8"+dependencies = [+ "windows-core 0.61.2",+]++[[package]]+name = "windows-collections"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"+dependencies = [+ "windows-core 0.62.2",+]++[[package]]+name = "windows-core"+version = "0.54.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "12661b9c89351d684a50a8a643ce5f608e20243b9fb84687800163429f161d65"+dependencies = [+ "windows-result 0.1.2",+ "windows-targets 0.52.6",+]++[[package]]+name = "windows-core"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link 0.1.3",+ "windows-result 0.3.4",+ "windows-strings 0.4.2",+]++[[package]]+name = "windows-core"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link 0.2.1",+ "windows-result 0.4.1",+ "windows-strings 0.5.1",+]++[[package]]+name = "windows-future"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"+dependencies = [+ "windows-core 0.61.2",+ "windows-link 0.1.3",+ "windows-threading 0.1.0",+]++[[package]]+name = "windows-future"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"+dependencies = [+ "windows-core 0.62.2",+ "windows-link 0.2.1",+ "windows-threading 0.2.1",+]++[[package]]+name = "windows-implement"+version = "0.60.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-interface"+version = "0.59.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "windows-link"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a"++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-numerics"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1"+dependencies = [+ "windows-core 0.61.2",+ "windows-link 0.1.3",+]++[[package]]+name = "windows-numerics"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"+dependencies = [+ "windows-core 0.62.2",+ "windows-link 0.2.1",+]++[[package]]+name = "windows-result"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8"+dependencies = [+ "windows-targets 0.52.6",+]++[[package]]+name = "windows-result"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6"+dependencies = [+ "windows-link 0.1.3",+]++[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link 0.2.1",+]++[[package]]+name = "windows-strings"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57"+dependencies = [+ "windows-link 0.1.3",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link 0.2.1",+]++[[package]]+name = "windows-sys"+version = "0.45.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"+dependencies = [+ "windows-targets 0.42.2",+]++[[package]]+name = "windows-sys"+version = "0.52.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"+dependencies = [+ "windows-targets 0.52.6",+]++[[package]]+name = "windows-sys"+version = "0.59.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"+dependencies = [+ "windows-targets 0.52.6",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link 0.2.1",+]++[[package]]+name = "windows-targets"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"+dependencies = [+ "windows_aarch64_gnullvm 0.42.2",+ "windows_aarch64_msvc 0.42.2",+ "windows_i686_gnu 0.42.2",+ "windows_i686_msvc 0.42.2",+ "windows_x86_64_gnu 0.42.2",+ "windows_x86_64_gnullvm 0.42.2",+ "windows_x86_64_msvc 0.42.2",+]++[[package]]+name = "windows-targets"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"+dependencies = [+ "windows_aarch64_gnullvm 0.52.6",+ "windows_aarch64_msvc 0.52.6",+ "windows_i686_gnu 0.52.6",+ "windows_i686_gnullvm",+ "windows_i686_msvc 0.52.6",+ "windows_x86_64_gnu 0.52.6",+ "windows_x86_64_gnullvm 0.52.6",+ "windows_x86_64_msvc 0.52.6",+]++[[package]]+name = "windows-threading"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6"+dependencies = [+ "windows-link 0.1.3",+]++[[package]]+name = "windows-threading"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"+dependencies = [+ "windows-link 0.2.1",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"++[[package]]+name = "windows_aarch64_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"++[[package]]+name = "windows_aarch64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"++[[package]]+name = "windows_i686_gnu"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"++[[package]]+name = "windows_i686_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"++[[package]]+name = "windows_i686_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"++[[package]]+name = "windows_i686_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"++[[package]]+name = "windows_i686_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"++[[package]]+name = "windows_x86_64_gnu"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"++[[package]]+name = "windows_x86_64_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"++[[package]]+name = "windows_x86_64_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"++[[package]]+name = "windows_x86_64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"++[[package]]+name = "winnow"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"+dependencies = [+ "memchr",+]++[[package]]+name = "writeable"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"++[[package]]+name = "x11rb"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"+dependencies = [+ "gethostname",+ "rustix 1.1.5",+ "x11rb-protocol",+]++[[package]]+name = "x11rb-protocol"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"++[[package]]+name = "xcap"+version = "0.9.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da270fd7c8581d43d731cb690bcc791fc0a7b3bc96e131a4b6552d0379640a9e"+dependencies = [+ "dispatch2",+ "image",+ "libwayshot-xcap",+ "log",+ "objc2",+ "objc2-app-kit",+ "objc2-av-foundation",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-core-media",+ "objc2-core-video",+ "objc2-foundation",+ "percent-encoding",+ "pipewire",+ "rand",+ "scopeguard",+ "serde",+ "thiserror 2.0.21",+ "url",+ "widestring",+ "windows 0.62.2",+ "xcb",+ "zbus",+]++[[package]]+name = "xcb"+version = "1.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6c2ad15e0e922856ee89afe862b8992334bbe7953adad56cd1199358cb30566"+dependencies = [+ "bitflags 2.13.2",+ "libc",+ "quick-xml",+]++[[package]]+name = "xkbcommon"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7a974f48060a14e95705c01f24ad9c3345022f4d97441b8a36beb7ed5c4a02d"+dependencies = [+ "libc",+ "memmap2",+ "xkeysym",+]++[[package]]+name = "xkeysym"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"++[[package]]+name = "xml-rs"+version = "0.8.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"++[[package]]+name = "yoke"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3"+dependencies = [+ "stable_deref_trait",+ "yoke-derive",+ "zerofrom",+]++[[package]]+name = "yoke-derive"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+ "synstructure",+]++[[package]]+name = "zbus"+version = "5.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907"+dependencies = [+ "async-broadcast",+ "async-executor",+ "async-io",+ "async-lock",+ "async-process",+ "async-recursion",+ "async-task",+ "async-trait",+ "blocking",+ "enumflags2",+ "event-listener",+ "futures-core",+ "futures-lite",+ "hex",+ "libc",+ "ordered-stream",+ "rustix 1.1.5",+ "serde",+ "serde_repr",+ "tracing",+ "uds_windows",+ "uuid",+ "windows-sys 0.61.2",+ "winnow",+ "zbus_macros",+ "zbus_names",+ "zvariant",+]++[[package]]+name = "zbus_macros"+version = "5.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40"+dependencies = [+ "proc-macro-crate",+ "proc-macro2",+ "quote",+ "syn 3.0.9",+ "zbus_names",+ "zvariant",+ "zvariant_utils",+]++[[package]]+name = "zbus_names"+version = "4.3.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd"+dependencies = [+ "serde",+ "winnow",+ "zvariant",+]++[[package]]+name = "zcheapstr"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473"+dependencies = [+ "serde",+]++[[package]]+name = "zerofrom"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"+dependencies = [+ "zerofrom-derive",+]++[[package]]+name = "zerofrom-derive"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+ "synstructure",+]++[[package]]+name = "zeroize"+version = "1.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"++[[package]]+name = "zerotrie"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"+dependencies = [+ "displaydoc",+ "yoke",+ "zerofrom",+]++[[package]]+name = "zerovec"+version = "0.11.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40"+dependencies = [+ "yoke",+ "zerofrom",+ "zerovec-derive",+]++[[package]]+name = "zerovec-derive"+version = "0.11.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.9",+]++[[package]]+name = "zlib-rs"+version = "0.6.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"++[[package]]+name = "zmij"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"++[[package]]+name = "zune-core"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"++[[package]]+name = "zune-jpeg"+version = "0.5.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"+dependencies = [+ "zune-core",+]++[[package]]+name = "zvariant"+version = "5.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7"+dependencies = [+ "endi",+ "enumflags2",+ "serde",+ "winnow",+ "zcheapstr",+ "zvariant_derive",+ "zvariant_utils",+]++[[package]]+name = "zvariant_derive"+version = "5.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d"+dependencies = [+ "proc-macro-crate",+ "proc-macro2",+ "quote",+ "syn 3.0.9",+ "zvariant_utils",+]++[[package]]+name = "zvariant_utils"+version = "4.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3"+dependencies = [+ "proc-macro2",+ "quote",+ "serde",+ "syn 3.0.9",+ "winnow",+]diff --git a/plugins/optimus/companion/Cargo.toml b/plugins/optimus/companion/Cargo.tomlindex 44171645..3eaf69e3 100644--- a/plugins/optimus/companion/Cargo.toml+++ b/plugins/optimus/companion/Cargo.toml@@ -1,9 +1,9 @@[package]name = "mercury-optimus"-version = "0.1.0"+version = "0.2.0"edition = "2024"rust-version = "1.94"-description = "Optimus: full computer control for Mercury (screen, mouse, keyboard, apps)"+description = "Optimus: full computer control for Mercury (screen, mouse, keyboard, apps, voice)"license = "MIT"publish = false@@ -13,9 +13,24 @@ enigo = "0.6"image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }base64 = "0.22"serde_json = "1"+# Voice: the same links as the WhatsApp plugin (rustls + ring).+tokio = { version = "1.47", features = ["rt-multi-thread", "macros", "sync", "time", "net"] }+tokio-websockets = { version = "0.13.3", features = ["client", "rustls-webpki-roots", "rand", "ring"] }+http = "1"+futures-util = { version = "0.3", default-features = false, features = ["sink", "std"] }+ureq = "3"+# Microphone and speaker.+cpal = "0.16"++[target.'cfg(target_os = "macos")'.dependencies]+core-graphics = "0.24"+core-foundation = "0.10"++[target.'cfg(target_os = "linux")'.dependencies]+x11rb = "0.13"[target.'cfg(windows)'.dependencies]-windows-sys = { version = "0.61", features = ["Win32_UI_HiDpi", "Win32_Foundation", "Win32_UI_WindowsAndMessaging"] }+windows-sys = { version = "0.61", features = ["Win32_UI_HiDpi", "Win32_Foundation", "Win32_UI_WindowsAndMessaging", "Win32_UI_Input_KeyboardAndMouse"] }[profile.release]opt-level = 3diff --git a/plugins/optimus/companion/src/audio.rs b/plugins/optimus/companion/src/audio.rsnew file mode 100644index 00000000..3f43c4b3--- /dev/null+++ b/plugins/optimus/companion/src/audio.rs@@ -0,0 +1,237 @@+//! Microphone and speaker for listening mode (cpal, every OS).+//!+//! The voice links speak 16 kHz mono PCM16 in 60 ms frames (like a phone+//! call). Here the default input is mixed to mono and resampled to that, and+//! link audio is resampled to the default output's rate and played.+//!+//! Without headphones the mic would hear Mercury's own voice; `Output`+//! records when it last played sound so the session can mute the mic while+//! Mercury talks.++use std::collections::VecDeque;+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};+use cpal::{SampleFormat, SizedSample};+use tokio::sync::mpsc;++use crate::links::{CALL_RATE, resample};++/// 60 ms at 16 kHz.+pub const FRAME: usize = 960;++pub struct Output {+ queue: Mutex<VecDeque<f32>>,+ rate: u32,+ start: Instant,+ /// Milliseconds since `start` when the speaker last played sound.+ last_sound: AtomicU64,+}++impl Output {+ /// Queue link audio (16 kHz mono PCM16).+ pub fn play(&self, pcm: &[i16]) {+ let up = resample(pcm, CALL_RATE, self.rate);+ let mut q = self.queue.lock().unwrap();+ q.extend(up.iter().map(|s| *s as f32 / 32768.0));+ }++ pub fn clear(&self) {+ self.queue.lock().unwrap().clear();+ }++ /// Something is still waiting to be played.+ pub fn busy(&self) -> bool {+ !self.queue.lock().unwrap().is_empty()+ }++ /// Sound played within the last `ms` milliseconds (or still queued).+ pub fn recently_audible(&self, ms: u64) -> bool {+ self.busy() || (self.start.elapsed().as_millis() as u64).saturating_sub(self.last_sound.load(Ordering::Relaxed)) < ms+ }++ /// A short tone: rising for "listening", falling for "stopped".+ pub fn chime(&self, rising: bool) {+ let mut q = self.queue.lock().unwrap();+ let notes: [f32; 2] = if rising { [660.0, 880.0] } else { [880.0, 520.0] };+ for f in notes {+ let n = (self.rate as f32 * 0.09) as usize;+ for i in 0..n {+ let t = i as f32 / self.rate as f32;+ let env = (std::f32::consts::PI * i as f32 / n as f32).sin();+ q.push_back((2.0 * std::f32::consts::PI * f * t).sin() * 0.18 * env);+ }+ }+ }++ fn next(&self) -> f32 {+ let s = self.queue.lock().unwrap().pop_front();+ match s {+ Some(v) => {+ if v.abs() > 0.004 {+ self.last_sound.store(self.start.elapsed().as_millis() as u64, Ordering::Relaxed);+ }+ v+ }+ None => 0.0,+ }+ }+}++pub struct Audio {+ pub mic: mpsc::UnboundedReceiver<Vec<i16>>,+ pub out: Arc<Output>,+ stop: Arc<AtomicBool>,+ pub description: String,+}++impl Drop for Audio {+ fn drop(&mut self) {+ self.stop.store(true, Ordering::Relaxed);+ }+}++impl Audio {+ /// Let queued sound finish (up to `max`), e.g. a goodbye before closing.+ pub async fn drain(&self, max: Duration) {+ let until = Instant::now() + max;+ while self.out.busy() && Instant::now() < until {+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ tokio::time::sleep(Duration::from_millis(150)).await;+ }+}++/// Open the default microphone and speaker. The streams live on their own+/// thread (they aren't Send on every OS) until the returned `Audio` is dropped.+pub fn open() -> Result<Audio, String> {+ let (mic_tx, mic_rx) = mpsc::unbounded_channel::<Vec<i16>>();+ let stop = Arc::new(AtomicBool::new(false));+ let (ready_tx, ready_rx) = std::sync::mpsc::channel::<Result<(Arc<Output>, String), String>>();+ let stop2 = stop.clone();+ std::thread::Builder::new()+ .name("optimus-audio".into())+ .spawn(move || {+ let host = cpal::default_host();+ let started = (|| -> Result<(cpal::Stream, cpal::Stream, Arc<Output>, String), String> {+ let input = host.default_input_device().ok_or("no microphone found")?;+ let output = host.default_output_device().ok_or("no speaker found")?;+ let in_cfg = input.default_input_config().map_err(|e| format!("microphone: {e}"))?;+ let out_cfg = output.default_output_config().map_err(|e| format!("speaker: {e}"))?;+ let out = Arc::new(Output {+ queue: Mutex::new(VecDeque::new()),+ rate: out_cfg.sample_rate().0,+ start: Instant::now(),+ last_sound: AtomicU64::new(0),+ });+ let in_stream = build_input(&input, &in_cfg, mic_tx)?;+ let out_stream = build_output(&output, &out_cfg, out.clone())?;+ in_stream.play().map_err(|e| format!("microphone: {e}"))?;+ out_stream.play().map_err(|e| format!("speaker: {e}"))?;+ let desc = format!(+ "mic: {}, speaker: {}",+ input.name().unwrap_or_else(|_| "default".into()),+ output.name().unwrap_or_else(|_| "default".into())+ );+ Ok((in_stream, out_stream, out, desc))+ })();+ match started {+ Ok((i, o, out, desc)) => {+ let _ = ready_tx.send(Ok((out, desc)));+ while !stop2.load(Ordering::Relaxed) {+ std::thread::sleep(Duration::from_millis(50));+ }+ drop(i);+ drop(o);+ }+ Err(e) => {+ let _ = ready_tx.send(Err(e));+ }+ }+ })+ .map_err(|e| e.to_string())?;+ let (out, description) = ready_rx.recv_timeout(Duration::from_secs(10)).map_err(|_| "the microphone didn't open in time".to_string())??;+ Ok(Audio { mic: mic_rx, out, stop, description })+}++fn build_input(device: &cpal::Device, cfg: &cpal::SupportedStreamConfig, tx: mpsc::UnboundedSender<Vec<i16>>) -> Result<cpal::Stream, String> {+ let config: cpal::StreamConfig = cfg.config();+ match cfg.sample_format() {+ SampleFormat::F32 => input_stream::<f32>(device, &config, tx, |s| s),+ SampleFormat::I16 => input_stream::<i16>(device, &config, tx, |s| s as f32 / 32768.0),+ SampleFormat::U16 => input_stream::<u16>(device, &config, tx, |s| (s as f32 - 32768.0) / 32768.0),+ SampleFormat::I32 => input_stream::<i32>(device, &config, tx, |s| s as f32 / 2147483648.0),+ other => Err(format!("unsupported microphone format {other:?}")),+ }+}++fn input_stream<T: SizedSample + Send + 'static>(+ device: &cpal::Device,+ config: &cpal::StreamConfig,+ tx: mpsc::UnboundedSender<Vec<i16>>,+ to_f32: fn(T) -> f32,+) -> Result<cpal::Stream, String> {+ let channels = config.channels.max(1) as usize;+ let rate = config.sample_rate.0;+ let chunk = (rate / 50) as usize; // 20 ms at the device rate+ let mut pending: Vec<i16> = Vec::with_capacity(chunk * 2);+ let mut frame: Vec<i16> = Vec::with_capacity(FRAME * 2);+ device+ .build_input_stream(+ config,+ move |data: &[T], _| {+ for f in data.chunks(channels) {+ let m = f.iter().map(|s| to_f32(*s)).sum::<f32>() / channels as f32;+ pending.push((m.clamp(-1.0, 1.0) * 32767.0) as i16);+ }+ while pending.len() >= chunk {+ let part: Vec<i16> = pending.drain(..chunk).collect();+ frame.extend(resample(&part, rate, CALL_RATE));+ while frame.len() >= FRAME {+ let f: Vec<i16> = frame.drain(..FRAME).collect();+ let _ = tx.send(f);+ }+ }+ },+ |e| eprintln!("optimus: microphone error: {e}"),+ None,+ )+ .map_err(|e| format!("microphone: {e}"))+}++fn build_output(device: &cpal::Device, cfg: &cpal::SupportedStreamConfig, out: Arc<Output>) -> Result<cpal::Stream, String> {+ let config: cpal::StreamConfig = cfg.config();+ match cfg.sample_format() {+ SampleFormat::F32 => output_stream::<f32>(device, &config, out, |v| v),+ SampleFormat::I16 => output_stream::<i16>(device, &config, out, |v| (v.clamp(-1.0, 1.0) * 32767.0) as i16),+ SampleFormat::U16 => output_stream::<u16>(device, &config, out, |v| ((v.clamp(-1.0, 1.0) * 32767.0) + 32768.0) as u16),+ SampleFormat::I32 => output_stream::<i32>(device, &config, out, |v| (v.clamp(-1.0, 1.0) as f64 * 2147483647.0) as i32),+ other => Err(format!("unsupported speaker format {other:?}")),+ }+}++fn output_stream<T: SizedSample + Send + 'static>(+ device: &cpal::Device,+ config: &cpal::StreamConfig,+ out: Arc<Output>,+ from_f32: fn(f32) -> T,+) -> Result<cpal::Stream, String> {+ let channels = config.channels.max(1) as usize;+ device+ .build_output_stream(+ config,+ move |data: &mut [T], _| {+ for f in data.chunks_mut(channels) {+ let v = from_f32(out.next());+ for s in f.iter_mut() {+ *s = v;+ }+ }+ },+ |e| eprintln!("optimus: speaker error: {e}"),+ None,+ )+ .map_err(|e| format!("speaker: {e}"))+}diff --git a/plugins/optimus/companion/src/core.rs b/plugins/optimus/companion/src/core.rsnew file mode 100644index 00000000..aec02604--- /dev/null+++ b/plugins/optimus/companion/src/core.rs@@ -0,0 +1,227 @@+//! The part of Optimus that touches the computer: screen and input (ops.rs),+//! the talk key (hotkey.rs) and voice sessions (voice.rs).+//!+//! On macOS it runs inside Optimus.app; elsewhere on a thread of the plugin+//! process. Either way it talks to the plugin side (main.rs) with JSON+//! messages, one per line on macOS:+//!+//! plugin → core {"op": {"id": 1, "name": "look", "args": {…}}}+//! {"mercury": <JSON-RPC from Mercury: replies to our requests, mercury/call/* notifications>}+//! {"quit": true}+//! core → plugin {"opResult": {"id": 1, "ok": {…}}} or {"opResult": {"id": 1, "err": "…"}}+//! {"mercury": <JSON-RPC for Mercury>}++use std::collections::HashMap;+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::{Arc, Mutex};+use std::time::Duration;++use serde_json::{Value, json};+use tokio::sync::oneshot;++use crate::ops::Ops;++pub fn log(msg: impl AsRef<str>) {+ eprintln!("optimus: {}", msg.as_ref());+}++pub fn settings() -> Value {+ std::env::var("MERCURY_PLUGIN_SETTINGS").ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or(json!({}))+}++pub fn voice_enabled() -> bool {+ !matches!(settings().get("mode").and_then(Value::as_str), Some("chat"))+}++type Pending = Mutex<HashMap<u64, oneshot::Sender<Result<Value, String>>>>;++/// Requests and notifications to Mercury, through the plugin process.+pub struct Out {+ send: Box<dyn Fn(Value) + Send + Sync>,+ pending: Pending,+ next: AtomicU64,+}++impl Out {+ pub fn notify(&self, method: &str, params: Value) {+ (self.send)(json!({ "mercury": { "jsonrpc": "2.0", "method": method, "params": params } }));+ }++ pub async fn request(&self, method: &str, params: Value, timeout: Duration) -> Result<Value, String> {+ let n = self.next.fetch_add(1, Ordering::Relaxed);+ let (tx, rx) = oneshot::channel();+ self.pending.lock().unwrap().insert(n, tx);+ (self.send)(json!({ "mercury": { "jsonrpc": "2.0", "id": format!("oc-{n}"), "method": method, "params": params } }));+ let r = tokio::time::timeout(timeout, rx).await;+ self.pending.lock().unwrap().remove(&n);+ match r {+ Ok(Ok(v)) => v,+ Ok(Err(_)) => Err("Mercury went away".into()),+ Err(_) => Err(format!("{method} timed out")),+ }+ }++ fn resolve(&self, id: &str, result: Result<Value, String>) {+ let Some(n) = id.strip_prefix("oc-").and_then(|n| n.parse::<u64>().ok()) else { return };+ if let Some(tx) = self.pending.lock().unwrap().remove(&n) {+ let _ = tx.send(result);+ }+ }++ fn op_result(&self, id: u64, r: Result<Value, String>) {+ (self.send)(match r {+ Ok(v) => json!({ "opResult": { "id": id, "ok": v } }),+ Err(e) => json!({ "opResult": { "id": id, "err": e } }),+ });+ }+}++pub struct Shared {+ pub out: Out,+ pub rt: tokio::runtime::Handle,+ pub ops: Mutex<Ops>,+ /// What Mercury is doing right now for a session's question (mercury/call/progress).+ pub call_activity: Mutex<HashMap<String, String>>,+ /// Things the voice should mention (an approval answered elsewhere, …).+ pub call_context: Mutex<HashMap<String, Vec<String>>>,+ /// Approvals Mercury is waiting on, per session: (approval id, what for).+ pub call_approvals: Mutex<HashMap<String, Vec<(String, String)>>>,+ /// The live voice session, if any.+ pub session: Mutex<Option<crate::voice::SessionCtl>>,+ /// How the talk key reads, e.g. "Control+Option+M" (empty when there's none).+ pub hotkey_label: Mutex<String>,+}++/// Run the core until the plugin side goes away.+pub fn run(inbox: std::sync::mpsc::Receiver<Value>, send: impl Fn(Value) + Send + Sync + 'static) {+ let rt = tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build().expect("tokio runtime");+ let shared = Arc::new(Shared {+ out: Out { send: Box::new(send), pending: Mutex::new(HashMap::new()), next: AtomicU64::new(1) },+ rt: rt.handle().clone(),+ ops: Mutex::new(Ops::new()),+ call_activity: Mutex::new(HashMap::new()),+ call_context: Mutex::new(HashMap::new()),+ call_approvals: Mutex::new(HashMap::new()),+ session: Mutex::new(None),+ hotkey_label: Mutex::new(String::new()),+ });++ start_hotkey(&shared);++ for msg in inbox {+ if msg.get("quit").is_some() {+ break;+ }+ if let Some(op) = msg.get("op") {+ let id = op["id"].as_u64().unwrap_or(0);+ let name = op["name"].as_str().unwrap_or("").to_string();+ let args = op["args"].clone();+ let sh = shared.clone();+ if name == "listen" {+ rt.spawn(async move {+ let r = crate::voice::press(sh.clone(), true).await;+ sh.out.op_result(id, r.map(|text| json!({ "text": text })));+ });+ continue;+ }+ rt.spawn_blocking(move || {+ let r = sh.ops.lock().unwrap_or_else(|e| e.into_inner()).run(&name, &args);+ sh.out.op_result(id, r);+ });+ continue;+ }+ if let Some(m) = msg.get("mercury") {+ on_mercury(&shared, m);+ }+ }+ // Stop any live session cleanly before exiting.+ if let Some(s) = shared.session.lock().unwrap().take() {+ s.stop();+ }+ rt.shutdown_timeout(Duration::from_secs(2));+}++fn start_hotkey(shared: &Arc<Shared>) {+ let status = |detail: String| {+ shared.out.notify("mercury/channel/status", json!({ "state": "connected", "account": "this computer", "detail": detail }));+ };+ if !voice_enabled() {+ status("Chat mode: ask Mercury in any chat to use the screen.".into());+ return;+ }+ let spec = settings().get("hotkey").and_then(Value::as_str).filter(|s| !s.trim().is_empty()).unwrap_or("ctrl+alt+m").to_string();+ let hk = match crate::hotkey::parse(&spec) {+ Ok(h) => h,+ Err(e) => {+ log(format!("talk key: {e}"));+ status(format!("Talk key not set: {e}. Fix it in /plugins optimus."));+ return;+ }+ };+ let label = hk.to_string();+ let sh = shared.clone();+ match crate::hotkey::listen(hk, move || {+ let sh2 = sh.clone();+ sh.rt.spawn(async move {+ if let Err(e) = crate::voice::press(sh2.clone(), false).await {+ log(format!("listening: {e}"));+ }+ });+ }) {+ Ok(()) => {+ *shared.hotkey_label.lock().unwrap() = label.clone();+ log(format!("press {label} to talk"));+ status(format!("Press {label} to talk; press it again to stop."));+ }+ Err(e) => {+ log(format!("talk key {label}: {e}"));+ status(format!("Talk key {label} isn't working: {e}"));+ }+ }+}++fn on_mercury(shared: &Arc<Shared>, msg: &Value) {+ // A reply to one of our requests.+ if let Some(id) = msg.get("id").and_then(Value::as_str) {+ if msg.get("method").is_none() {+ let r = match (msg.get("result"), msg.get("error")) {+ (Some(r), _) => Ok(r.clone()),+ (_, Some(e)) => Err(e.get("message").and_then(Value::as_str).unwrap_or("error").to_string()),+ _ => Err("empty reply".into()),+ };+ shared.out.resolve(id, r);+ return;+ }+ }+ let method = msg.get("method").and_then(Value::as_str).unwrap_or("");+ let p = msg.get("params").cloned().unwrap_or(Value::Null);+ let call = p.get("callId").and_then(Value::as_str).unwrap_or("").to_string();+ match method {+ "mercury/call/progress" => {+ if let Some(a) = p.get("activity").and_then(Value::as_str) {+ shared.call_activity.lock().unwrap().insert(call, a.chars().take(80).collect());+ }+ }+ "mercury/call/approval" => {+ if let (Some(id), Some(prompt)) = (p.get("approvalId").and_then(Value::as_str), p.get("prompt").and_then(Value::as_str)) {+ shared.call_approvals.lock().unwrap().entry(call).or_default().push((id.to_string(), prompt.chars().take(600).collect()));+ }+ }+ "mercury/call/approval-resolved" => {+ let Some(id) = p.get("approvalId").and_then(Value::as_str) else { return };+ if let Some(list) = shared.call_approvals.lock().unwrap().get_mut(&call) {+ list.retain(|(a, _)| a != id);+ }+ if p.get("via").and_then(Value::as_str) != Some("voice") {+ let note = format!("RESOLVED:{id}:Nobody answered that approval in time, so it wasn't done. Offer to try again.");+ shared.call_context.lock().unwrap().entry(call).or_default().push(note);+ }+ }+ "mercury/call/context" => {+ if let Some(t) = p.get("text").and_then(Value::as_str) {+ shared.call_context.lock().unwrap().entry(call).or_default().push(t.chars().take(400).collect());+ }+ }+ _ => {}+ }+}diff --git a/plugins/optimus/companion/src/hotkey.rs b/plugins/optimus/companion/src/hotkey.rsnew file mode 100644index 00000000..f195290f--- /dev/null+++ b/plugins/optimus/companion/src/hotkey.rs@@ -0,0 +1,325 @@+//! The talk key: one global hotkey (e.g. "ctrl+alt+m") on every OS.+//!+//! - macOS: an event tap (needs the Accessibility permission Optimus already+//! has). The key press is swallowed so it doesn't also type a letter.+//! - Windows: RegisterHotKey on a thread with its own message loop.+//! - Linux: an X11 key grab (X11 sessions, and XWayland apps on Wayland).++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct Mods {+ pub ctrl: bool,+ pub alt: bool,+ pub shift: bool,+ pub cmd: bool,+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Hotkey {+ pub mods: Mods,+ /// Lowercase key name: a letter or digit, "space", "enter", "tab", "esc", "f1".."f12".+ pub key: String,+}++impl std::fmt::Display for Hotkey {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ let mac = cfg!(target_os = "macos");+ let mut parts: Vec<String> = Vec::new();+ if self.mods.ctrl {+ parts.push("Control".into());+ }+ if self.mods.alt {+ parts.push(if mac { "Option".into() } else { "Alt".into() });+ }+ if self.mods.shift {+ parts.push("Shift".into());+ }+ if self.mods.cmd {+ parts.push(if mac { "Command".into() } else if cfg!(windows) { "Win".into() } else { "Super".into() });+ }+ let k = if self.key.len() == 1 { self.key.to_uppercase() } else { capitalize(&self.key) };+ parts.push(k);+ write!(f, "{}", parts.join("+"))+ }+}++fn capitalize(s: &str) -> String {+ let mut c = s.chars();+ match c.next() {+ Some(first) => first.to_uppercase().collect::<String>() + c.as_str(),+ None => String::new(),+ }+}++pub fn parse(spec: &str) -> Result<Hotkey, String> {+ let mut mods = Mods::default();+ let mut key: Option<String> = None;+ for part in spec.split('+').map(|p| p.trim().to_ascii_lowercase()).filter(|p| !p.is_empty()) {+ match part.as_str() {+ "ctrl" | "control" => mods.ctrl = true,+ "alt" | "option" | "opt" => mods.alt = true,+ "shift" => mods.shift = true,+ "cmd" | "command" | "super" | "win" | "meta" => mods.cmd = true,+ other => {+ if key.is_some() {+ return Err(format!("\"{spec}\" has more than one key; use modifiers plus one key, e.g. ctrl+alt+m"));+ }+ let k = match other {+ "return" => "enter".to_string(),+ "escape" => "esc".to_string(),+ "spacebar" => "space".to_string(),+ o => o.to_string(),+ };+ let valid = (k.len() == 1 && k.chars().all(|c| c.is_ascii_alphanumeric()))+ || ["space", "enter", "tab", "esc"].contains(&k.as_str())+ || k.strip_prefix('f').and_then(|n| n.parse::<u8>().ok()).is_some_and(|n| (1..=12).contains(&n));+ if !valid {+ return Err(format!("unknown key \"{other}\" in \"{spec}\" (use a letter, digit, space, enter, tab, esc or f1–f12)"));+ }+ key = Some(k);+ }+ }+ }+ let key = key.ok_or_else(|| format!("\"{spec}\" has no key, e.g. ctrl+alt+m"))?;+ let is_f = key.starts_with('f') && key.len() > 1;+ if !is_f && !mods.ctrl && !mods.alt && !mods.cmd {+ return Err(format!("\"{spec}\" would fire while typing: add ctrl, alt or cmd (or use an F key)"));+ }+ Ok(Hotkey { mods, key })+}++/// Start listening for the hotkey; `on_press` runs on the listener thread.+/// Returns once the key is registered (or why it couldn't be).+pub fn listen(hk: Hotkey, on_press: impl Fn() + Send + 'static) -> Result<(), String> {+ let (tx, rx) = std::sync::mpsc::channel::<Result<(), String>>();+ std::thread::Builder::new()+ .name("optimus-hotkey".into())+ .spawn(move || platform::run(hk, on_press, tx))+ .map_err(|e| e.to_string())?;+ rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap_or_else(|_| Err("the hotkey listener didn't start".into()))+}++#[cfg(target_os = "macos")]+mod platform {+ use super::Hotkey;+ use core_foundation::runloop::{CFRunLoop, kCFRunLoopCommonModes};+ use core_graphics::event::{CGEventFlags, CGEventTap, CGEventTapLocation, CGEventTapOptions, CGEventTapPlacement, CGEventType, EventField};+ use std::sync::atomic::{AtomicPtr, Ordering};++ unsafe extern "C" {+ fn CGEventTapEnable(tap: *mut std::ffi::c_void, enable: bool);+ }++ static TAP: AtomicPtr<std::ffi::c_void> = AtomicPtr::new(std::ptr::null_mut());++ fn keycode(key: &str) -> Option<i64> {+ let k = match key {+ "a" => 0, "s" => 1, "d" => 2, "f" => 3, "h" => 4, "g" => 5, "z" => 6, "x" => 7, "c" => 8, "v" => 9,+ "b" => 11, "q" => 12, "w" => 13, "e" => 14, "r" => 15, "y" => 16, "t" => 17, "1" => 18, "2" => 19,+ "3" => 20, "4" => 21, "6" => 22, "5" => 23, "9" => 25, "7" => 26, "8" => 28, "0" => 29, "o" => 31,+ "u" => 32, "i" => 34, "p" => 35, "l" => 37, "j" => 38, "k" => 40, "n" => 45, "m" => 46,+ "enter" => 36, "tab" => 48, "space" => 49, "esc" => 53,+ "f1" => 122, "f2" => 120, "f3" => 99, "f4" => 118, "f5" => 96, "f6" => 97, "f7" => 98, "f8" => 100,+ "f9" => 101, "f10" => 109, "f11" => 103, "f12" => 111,+ _ => return None,+ };+ Some(k)+ }++ pub fn run(hk: Hotkey, on_press: impl Fn() + Send + 'static, ready: std::sync::mpsc::Sender<Result<(), String>>) {+ let Some(code) = keycode(&hk.key) else {+ let _ = ready.send(Err(format!("can't use {} as a key on macOS", hk.key)));+ return;+ };+ let want = hk.mods;+ let tap = CGEventTap::new(+ CGEventTapLocation::Session,+ CGEventTapPlacement::HeadInsertEventTap,+ CGEventTapOptions::Default,+ vec![CGEventType::KeyDown],+ move |_proxy, etype, event| {+ if matches!(etype, CGEventType::TapDisabledByTimeout | CGEventType::TapDisabledByUserInput) {+ let t = TAP.load(Ordering::Relaxed);+ if !t.is_null() {+ unsafe { CGEventTapEnable(t, true) };+ }+ return None;+ }+ if event.get_integer_value_field(EventField::KEYBOARD_EVENT_KEYCODE) != code {+ return None;+ }+ let f = event.get_flags();+ let has = |flag: CGEventFlags| f.contains(flag);+ if has(CGEventFlags::CGEventFlagControl) != want.ctrl+ || has(CGEventFlags::CGEventFlagAlternate) != want.alt+ || has(CGEventFlags::CGEventFlagShift) != want.shift+ || has(CGEventFlags::CGEventFlagCommand) != want.cmd+ {+ return None;+ }+ if event.get_integer_value_field(EventField::KEYBOARD_EVENT_AUTOREPEAT) == 0 {+ on_press();+ }+ // Swallow it: the press shouldn't also type into the front app.+ event.set_type(CGEventType::Null);+ None+ },+ );+ match tap {+ Ok(tap) => unsafe {+ TAP.store(tap.mach_port.as_concrete_TypeRef() as *mut std::ffi::c_void, Ordering::Relaxed);+ let Ok(source) = tap.mach_port.create_runloop_source(0) else {+ let _ = ready.send(Err("couldn't attach the hotkey listener".into()));+ return;+ };+ CFRunLoop::get_current().add_source(&source, kCFRunLoopCommonModes);+ tap.enable();+ let _ = ready.send(Ok(()));+ CFRunLoop::run_current();+ },+ Err(()) => {+ let _ = ready.send(Err("macOS refused the hotkey listener: allow Optimus under Privacy & Security → Accessibility".into()));+ }+ }+ }++ use core_foundation::base::TCFType;+}++#[cfg(windows)]+mod platform {+ use super::Hotkey;+ use windows_sys::Win32::UI::Input::KeyboardAndMouse::{MOD_ALT, MOD_CONTROL, MOD_NOREPEAT, MOD_SHIFT, MOD_WIN, RegisterHotKey};+ use windows_sys::Win32::UI::WindowsAndMessaging::{GetMessageW, MSG, WM_HOTKEY};++ fn vk(key: &str) -> Option<u32> {+ Some(match key {+ "space" => 0x20,+ "enter" => 0x0D,+ "tab" => 0x09,+ "esc" => 0x1B,+ k if k.len() == 1 => k.to_ascii_uppercase().chars().next()? as u32,+ k => 0x70 + k.strip_prefix('f')?.parse::<u32>().ok()? - 1,+ })+ }++ pub fn run(hk: Hotkey, on_press: impl Fn() + Send + 'static, ready: std::sync::mpsc::Sender<Result<(), String>>) {+ let Some(code) = vk(&hk.key) else {+ let _ = ready.send(Err(format!("can't use {} as a key", hk.key)));+ return;+ };+ let mut mods = MOD_NOREPEAT;+ if hk.mods.ctrl {+ mods |= MOD_CONTROL;+ }+ if hk.mods.alt {+ mods |= MOD_ALT;+ }+ if hk.mods.shift {+ mods |= MOD_SHIFT;+ }+ if hk.mods.cmd {+ mods |= MOD_WIN;+ }+ if unsafe { RegisterHotKey(std::ptr::null_mut(), 1, mods, code) } == 0 {+ let _ = ready.send(Err(format!("{hk} is already used by another app; pick another key in /plugins optimus")));+ return;+ }+ let _ = ready.send(Ok(()));+ let mut msg: MSG = unsafe { std::mem::zeroed() };+ while unsafe { GetMessageW(&mut msg, std::ptr::null_mut(), 0, 0) } > 0 {+ if msg.message == WM_HOTKEY {+ on_press();+ }+ }+ }+}++#[cfg(target_os = "linux")]+mod platform {+ use super::Hotkey;+ use x11rb::connection::Connection;+ use x11rb::protocol::Event;+ use x11rb::protocol::xproto::{ConnectionExt, GrabMode, ModMask};++ fn keysym(key: &str) -> Option<u32> {+ Some(match key {+ "space" => 0x20,+ "enter" => 0xff0d,+ "tab" => 0xff09,+ "esc" => 0xff1b,+ k if k.len() == 1 => k.chars().next()? as u32,+ k => 0xffbe + k.strip_prefix('f')?.parse::<u32>().ok()? - 1,+ })+ }++ pub fn run(hk: Hotkey, on_press: impl Fn() + Send + 'static, ready: std::sync::mpsc::Sender<Result<(), String>>) {+ let result = (|| -> Result<(x11rb::rust_connection::RustConnection, u8, u16), String> {+ let (conn, screen) = x11rb::connect(None).map_err(|e| format!("no X11 display for the hotkey ({e}); on Wayland use chat, or the listen tool"))?;+ let root = conn.setup().roots[screen].root;+ let sym = keysym(&hk.key).ok_or("unknown key")?;+ let setup = conn.setup();+ let (min, max) = (setup.min_keycode, setup.max_keycode);+ let map = conn.get_keyboard_mapping(min, max - min + 1).map_err(|e| e.to_string())?.reply().map_err(|e| e.to_string())?;+ let per = map.keysyms_per_keycode as usize;+ let code = (0..=(max - min) as usize)+ .find(|i| map.keysyms[i * per..(i + 1) * per].contains(&sym))+ .map(|i| min + i as u8)+ .ok_or("that key isn't on this keyboard")?;+ let mut mods = 0u16;+ if hk.mods.ctrl {+ mods |= u16::from(ModMask::CONTROL);+ }+ if hk.mods.alt {+ mods |= u16::from(ModMask::M1);+ }+ if hk.mods.shift {+ mods |= u16::from(ModMask::SHIFT);+ }+ if hk.mods.cmd {+ mods |= u16::from(ModMask::M4);+ }+ // Also with Caps Lock and Num Lock on.+ for extra in [0u16, u16::from(ModMask::LOCK), u16::from(ModMask::M2), u16::from(ModMask::LOCK) | u16::from(ModMask::M2)] {+ conn.grab_key(true, root, ModMask::from(mods | extra), code, GrabMode::ASYNC, GrabMode::ASYNC)+ .map_err(|e| e.to_string())?+ .check()+ .map_err(|_| format!("{hk} is already used by another app; pick another key in /plugins optimus"))?;+ }+ conn.flush().map_err(|e| e.to_string())?;+ Ok((conn, code, mods))+ })();+ let (conn, code, _) = match result {+ Ok(v) => v,+ Err(e) => {+ let _ = ready.send(Err(e));+ return;+ }+ };+ let _ = ready.send(Ok(()));+ while let Ok(ev) = conn.wait_for_event() {+ if let Event::KeyPress(k) = ev {+ if k.detail == code {+ on_press();+ }+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parses_keys() {+ let h = parse("Ctrl+Option+M").unwrap();+ assert_eq!(h.mods, Mods { ctrl: true, alt: true, shift: false, cmd: false });+ assert_eq!(h.key, "m");+ assert_eq!(parse("f9").unwrap().key, "f9");+ assert_eq!(parse("cmd+shift+space").unwrap().key, "space");+ assert!(parse("m").is_err(), "a bare letter would fire while typing");+ assert!(parse("ctrl+a+b").is_err());+ assert!(parse("ctrl+alt").is_err());+ assert!(parse("ctrl+hyper").is_err());+ }+}diff --git a/plugins/optimus/companion/src/links/gemini.rs b/plugins/optimus/companion/src/links/gemini.rsnew file mode 100644index 00000000..51629876--- /dev/null+++ b/plugins/optimus/companion/src/links/gemini.rs@@ -0,0 +1,158 @@+//! Google Gemini Live: native 16 kHz input, 24 kHz output, its own protocol.+//! Connections last ~10 minutes, so the link resumes the session (handle from+//! sessionResumptionUpdate) on goAway or a drop, and the call carries on.++use std::collections::HashMap;+use std::time::Duration;++use serde_json::{Value, json};+use tokio::sync::mpsc;+use tokio_websockets::Message;+use futures_util::{SinkExt, StreamExt};++use super::{Brain, CALL_RATE, Link, LinkCmd, LinkConfig, LinkEvent, b64, env_key, pcm_from_bytes, resample, setting, unb64, ws};++const URL: &str = "wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent";++fn setup(cfg: &LinkConfig, handle: Option<&str>) -> Value {+ let s = &cfg.settings;+ let decls: Vec<Value> = cfg.tools.as_array().cloned().unwrap_or_default().iter().map(|t| json!({+ "name": t.get("name"), "description": t.get("description"), "parameters": t.get("parameters"),+ })).collect();+ let mut setup = json!({+ "model": format!("models/{}", setting(s, "geminiModel", "gemini-3.8-live")),+ "generationConfig": {+ "responseModalities": ["AUDIO"],+ "speechConfig": { "voiceConfig": { "prebuiltVoiceConfig": { "voiceName": setting(s, "geminiVoice", "Kore") } } },+ },+ "systemInstruction": { "parts": [{ "text": cfg.instructions }] },+ "tools": [{ "functionDeclarations": decls }],+ "inputAudioTranscription": {},+ "outputAudioTranscription": {},+ "realtimeInputConfig": {+ "automaticActivityDetection": { "disabled": false, "silenceDurationMs": 600 },+ "activityHandling": "START_OF_ACTIVITY_INTERRUPTS",+ },+ "contextWindowCompression": { "slidingWindow": {} },+ "sessionResumption": {},+ });+ if let Some(h) = handle { setup["sessionResumption"] = json!({ "handle": h }); }+ json!({ "setup": setup })+}++pub async fn open(cfg: LinkConfig) -> Result<Link, String> {+ let key = env_key("GEMINI_API_KEY").ok_or("no Gemini API key")?;+ let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel::<LinkCmd>();+ let (ev_tx, ev_rx) = mpsc::unbounded_channel::<LinkEvent>();+ // Fail fast on a bad key or model: the first connection is made here.+ let mut sock = connect(&key, &cfg, None).await?;++ tokio::spawn(async move {+ let mut handle: Option<String> = None;+ let mut names: HashMap<String, String> = HashMap::new();+ let (mut user_text, mut model_text) = (String::new(), String::new());+ let mut responding = false;+ 'conn: loop {+ let (mut tx, mut rx) = sock.split();+ loop {+ tokio::select! {+ c = cmd_rx.recv() => {+ let Some(c) = c else { let _ = tx.close().await; return };+ let msg = match c {+ LinkCmd::Audio(frame) => json!({ "realtimeInput": { "audio": { "data": b64(&frame), "mimeType": "audio/pcm;rate=16000" } } }),+ LinkCmd::Instruct(text) => json!({ "clientContent": { "turns": [{ "role": "user", "parts": [{ "text": text }] }], "turnComplete": true } }),+ LinkCmd::Say(text) => json!({ "clientContent": { "turns": [{ "role": "user", "parts": [{ "text": format!("[Say this to the caller, naturally] {text}") }] }], "turnComplete": true } }),+ LinkCmd::ToolResult { id, output } => {+ let name = names.remove(&id).unwrap_or_default();+ json!({ "toolResponse": { "functionResponses": [{ "id": id, "name": name, "response": { "result": output } }] } })+ }+ LinkCmd::Cancel => continue,+ };+ if tx.send(Message::text(msg.to_string())).await.is_err() { break; }+ }+ m = rx.next() => {+ let Some(Ok(m)) = m else { break };+ if m.is_close() {+ let reason = m.as_close().map(|(_, r)| r.to_string()).unwrap_or_default();+ if handle.is_none() {+ let _ = ev_tx.send(LinkEvent::Closed(format!("Gemini closed the session{}", if reason.is_empty() { String::new() } else { format!(": {reason}") })));+ return;+ }+ break;+ }+ let text = if let Some(t) = m.as_text() { t.to_string() } else { String::from_utf8_lossy(&m.as_payload().to_vec()).to_string() };+ let Ok(v) = serde_json::from_str::<Value>(&text) else { continue };+ if let Some(h) = v.pointer("/sessionResumptionUpdate/newHandle").and_then(Value::as_str) {+ if v.pointer("/sessionResumptionUpdate/resumable").and_then(Value::as_bool) != Some(false) { handle = Some(h.to_string()); }+ }+ if v.get("goAway").is_some() { break; } // resume on a fresh connection+ if let Some(calls) = v.pointer("/toolCall/functionCalls").and_then(Value::as_array) {+ for c in calls {+ let id = c.get("id").and_then(Value::as_str).unwrap_or("").to_string();+ let name = c.get("name").and_then(Value::as_str).unwrap_or("").to_string();+ names.insert(id.clone(), name.clone());+ let _ = ev_tx.send(LinkEvent::ToolCall { id, name, args: c.get("args").cloned().unwrap_or(json!({})) });+ }+ }+ let Some(sc) = v.get("serverContent") else { continue };+ if sc.get("interrupted").and_then(Value::as_bool) == Some(true) {+ let _ = ev_tx.send(LinkEvent::SpeechStarted);+ }+ if let Some(t) = sc.pointer("/inputTranscription/text").and_then(Value::as_str) { user_text.push_str(t); }+ if let Some(t) = sc.pointer("/outputTranscription/text").and_then(Value::as_str) { model_text.push_str(t); }+ if let Some(parts) = sc.pointer("/modelTurn/parts").and_then(Value::as_array) {+ for part in parts {+ if let Some(d) = part.pointer("/inlineData/data").and_then(Value::as_str) {+ if !responding {+ responding = true;+ let _ = ev_tx.send(LinkEvent::ResponseStarted);+ if !user_text.trim().is_empty() { let _ = ev_tx.send(LinkEvent::UserText(std::mem::take(&mut user_text).trim().to_string())); }+ }+ let _ = ev_tx.send(LinkEvent::Audio(resample(&pcm_from_bytes(&unb64(d)), 24_000, CALL_RATE)));+ }+ }+ }+ if sc.get("turnComplete").and_then(Value::as_bool) == Some(true) {+ if !user_text.trim().is_empty() { let _ = ev_tx.send(LinkEvent::UserText(std::mem::take(&mut user_text).trim().to_string())); }+ if !model_text.trim().is_empty() { let _ = ev_tx.send(LinkEvent::AssistantText(std::mem::take(&mut model_text).trim().to_string())); }+ responding = false;+ let _ = ev_tx.send(LinkEvent::ResponseDone);+ }+ }+ }+ }+ // Connection ended without the call ending: resume where we left off.+ for attempt in 0..3u64 {+ tokio::time::sleep(Duration::from_millis(300 * (attempt + 1))).await;+ match connect(&key, &cfg, handle.as_deref()).await {+ Ok(s) => { sock = s; continue 'conn; }+ Err(e) => crate::log(format!("gemini resume failed: {e}")),+ }+ }+ let _ = ev_tx.send(LinkEvent::Closed("lost the connection to Gemini".into()));+ return;+ }+ });++ Ok(Link { brain: Brain::Voice, cmd: cmd_tx, events: ev_rx })+}++async fn connect(key: &str, cfg: &LinkConfig, handle: Option<&str>) -> Result<ws::Socket, String> {+ let mut sock = ws::connect(&format!("{URL}?key={key}"), &[]).await.map_err(|e| format!("couldn't reach Gemini: {e}"))?;+ sock.send(Message::text(setup(cfg, handle).to_string())).await.map_err(|e| e.to_string())?;+ // Wait for setupComplete before streaming audio.+ let wait = async {+ while let Some(m) = sock.next().await {+ let m = m.map_err(|e| e.to_string())?;+ if m.is_close() {+ let reason = m.as_close().map(|(_, r)| r.to_string()).unwrap_or_default();+ return Err(format!("Gemini refused the session: {reason}"));+ }+ let text = if let Some(t) = m.as_text() { t.to_string() } else { String::from_utf8_lossy(&m.as_payload().to_vec()).to_string() };+ if text.contains("setupComplete") { return Ok(()); }+ }+ Err("Gemini closed during setup".to_string())+ };+ tokio::time::timeout(Duration::from_secs(15), wait).await.map_err(|_| "Gemini setup timed out".to_string())??;+ Ok(sock)+}diff --git a/plugins/optimus/companion/src/links/mod.rs b/plugins/optimus/companion/src/links/mod.rsnew file mode 100644index 00000000..e2d20771--- /dev/null+++ b/plugins/optimus/companion/src/links/mod.rs@@ -0,0 +1,233 @@+//! Voice links (shared with the WhatsApp plugin): one per kind of voice+//! provider, all speaking the same small language to the session bridge+//! (voice.rs). The bridge owns everything about+//! the call itself (Mercury questions, approvals, progress updates, photos,+//! summaries); a link only moves audio and events.+//!+//! - realtime: speech-to-speech models on OpenAI's Realtime protocol+//! (OpenAI, Azure OpenAI, xAI Grok, ElevenLabs Realtime, Qwen-Omni)+//! - gemini: Google Gemini Live+//! - pipeline: speech-to-text → the user's own Mercury model → text-to-speech+//! (Deepgram / AssemblyAI / ElevenLabs Scribe / Sarvam, then Cartesia /+//! ElevenLabs / MiniMax / Sarvam / Deepgram voices)++pub mod gemini;+pub mod pipeline;+pub mod realtime;+pub mod stt;+pub mod tts;+pub mod ws;++use serde_json::Value;+use tokio::sync::mpsc;++/// Phone-call audio rate: 16 kHz mono PCM16.+pub const CALL_RATE: u32 = 16_000;++#[derive(Debug)]+pub enum LinkEvent {+ /// Audio for the caller, 16 kHz mono PCM16.+ Audio(Vec<i16>),+ /// The caller started talking: stop playing and cancel speech (barge-in).+ SpeechStarted,+ /// A finished utterance from the caller.+ UserText(String),+ /// What the voice said (for the transcript).+ AssistantText(String),+ /// The voice model wants a tool (ask_mercury, answer_approval, end_call).+ ToolCall { id: String, name: String, args: Value },+ ResponseStarted,+ ResponseDone,+ /// The provider closed the session; the reason is already in plain words.+ Closed(String),+}++#[derive(Debug)]+pub enum LinkCmd {+ /// Caller audio, 16 kHz mono PCM16, 60 ms frames.+ Audio(Vec<i16>),+ /// An instruction for a model that reasons (status update, approval question).+ Instruct(String),+ /// Speak exactly this (pipeline voices; realtime models are asked to say it).+ Say(String),+ /// The result of a ToolCall.+ ToolResult { id: String, output: String },+ /// Stop speaking now (barge-in).+ Cancel,+}++/// Does this link's own model reason and call tools, or does Mercury think for every turn?+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Brain {+ /// A speech-to-speech model: it chats and calls ask_mercury when it needs to.+ Voice,+ /// Every caller utterance is a Mercury turn; the link only listens and speaks.+ Mercury,+}++pub struct Link {+ pub brain: Brain,+ pub cmd: mpsc::UnboundedSender<LinkCmd>,+ pub events: mpsc::UnboundedReceiver<LinkEvent>,+}++impl Link {+ pub fn send(&self, c: LinkCmd) {+ let _ = self.cmd.send(c);+ }+}++/// Everything a link needs to start: provider choice and keys come from the+/// plugin settings and environment (keys are passed by Mercury, never typed here).+pub struct LinkConfig {+ pub instructions: String,+ pub tools: Value,+ pub settings: Value,+}++pub fn setting<'a>(settings: &'a Value, key: &str, default: &'a str) -> String {+ settings.get(key).and_then(Value::as_str).filter(|s| !s.trim().is_empty()).unwrap_or(default).trim().to_string()+}++pub fn env_key(name: &str) -> Option<String> {+ std::env::var(name).ok().filter(|k| !k.trim().is_empty())+}++/// Which voice engine the owner picked, and whether its keys are present.+pub fn engine(settings: &Value) -> String {+ setting(settings, "voiceEngine", "openai")+}++/// Human-readable reason calls can't start with the current settings, if any.+pub fn not_ready(settings: &Value) -> Option<String> {+ let plugin = std::env::var("MERCURY_PLUGIN_ID").unwrap_or_else(|_| "optimus".into());+ let need = |name: &str, what: &str| if env_key(name).is_none() { Some(format!("voice with {what} needs its API key: add it in /plugins {plugin} → 🎙 Voice")) } else { None };+ match engine(settings).as_str() {+ "openai" => if env_key("MERCURY_PROVIDER_OPENAI_API_KEY").is_none() { Some(format!("voice needs an OpenAI key (recommended): add it once in the dashboard (Providers) or with `mercury doctor`, or pick another voice in /plugins {plugin} → 🎙 Voice")) } else { None },+ "grok" => if env_key("MERCURY_PROVIDER_GROK_API_KEY").is_none() { Some("voice with Grok needs a Grok provider: add your xAI key in the dashboard (Providers)".into()) } else { None },+ "azure" => need("AZURE_OPENAI_API_KEY", "Azure OpenAI").or_else(|| if setting(settings, "azureEndpoint", "").is_empty() { Some(format!("set the Azure endpoint in /plugins {plugin}")) } else { None }),+ "elevenlabs" => need("ELEVENLABS_API_KEY", "ElevenLabs"),+ "qwen" => need("DASHSCOPE_API_KEY", "Qwen (Alibaba Model Studio)"),+ "gemini" => need("GEMINI_API_KEY", "Gemini"),+ "mercury" => {+ let stt = setting(settings, "sttProvider", "deepgram");+ let tts = setting(settings, "ttsProvider", "cartesia");+ stt::key_name(&stt).and_then(|k| need(k, &stt::label(&stt))).or_else(|| tts::key_name(&tts).and_then(|k| need(k, &tts::label(&tts))))+ }+ other => Some(format!("unknown voice engine \"{other}\"")),+ }+}++pub async fn open(cfg: LinkConfig) -> Result<Link, String> {+ match engine(&cfg.settings).as_str() {+ "gemini" => gemini::open(cfg).await,+ "mercury" => pipeline::open(cfg).await,+ _ => realtime::open(cfg).await,+ }+}++// ── shared helpers ────────────────────────────────────────────────────────++/// Linear resampling of mono i16 PCM.+pub fn resample(input: &[i16], from: u32, to: u32) -> Vec<i16> {+ if input.is_empty() || from == to {+ return input.to_vec();+ }+ let out_len = ((input.len() as u64 * to as u64) / from as u64).max(1) as usize;+ let step = from as f64 / to as f64;+ (0..out_len)+ .map(|i| {+ let pos = i as f64 * step;+ let idx = pos as usize;+ let frac = pos - idx as f64;+ let a = input[idx.min(input.len() - 1)] as f64;+ let b = input[(idx + 1).min(input.len() - 1)] as f64;+ (a + (b - a) * frac).round().clamp(i16::MIN as f64, i16::MAX as f64) as i16+ })+ .collect()+}++pub fn pcm_bytes(samples: &[i16]) -> Vec<u8> {+ let mut bytes = Vec::with_capacity(samples.len() * 2);+ for s in samples {+ bytes.extend_from_slice(&s.to_le_bytes());+ }+ bytes+}++pub fn pcm_from_bytes(bytes: &[u8]) -> Vec<i16> {+ bytes.chunks_exact(2).map(|c| i16::from_le_bytes([c[0], c[1]])).collect()+}++pub fn b64(samples: &[i16]) -> String {+ use base64::Engine as _;+ base64::engine::general_purpose::STANDARD.encode(pcm_bytes(samples))+}++pub fn unb64(data: &str) -> Vec<u8> {+ use base64::Engine as _;+ base64::engine::general_purpose::STANDARD.decode(data).unwrap_or_default()+}++/// Drop a RIFF/WAV header if a provider sends one in front of raw PCM.+pub fn strip_wav(bytes: &[u8]) -> &[u8] {+ if bytes.len() > 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WAVE" {+ let mut i = 12;+ while i + 8 <= bytes.len() {+ let len = u32::from_le_bytes([bytes[i + 4], bytes[i + 5], bytes[i + 6], bytes[i + 7]]) as usize;+ if &bytes[i..i + 4] == b"data" {+ return &bytes[(i + 8).min(bytes.len())..];+ }+ i += 8 + len;+ }+ }+ bytes+}++/// The language of a reply, by script: Devanagari → Hindi, Arabic script → Urdu, else English.+pub fn script_language(text: &str) -> &'static str {+ let (mut deva, mut arabic, mut latin) = (0, 0, 0);+ for c in text.chars() {+ match c as u32 {+ 0x0900..=0x097F => deva += 1,+ 0x0600..=0x06FF | 0x0750..=0x077F | 0xFB50..=0xFDFF | 0xFE70..=0xFEFF => arabic += 1,+ 0x41..=0x5A | 0x61..=0x7A => latin += 1,+ _ => {}+ }+ }+ if deva > latin && deva >= arabic { "hi" } else if arabic > latin { "ur" } else { "en" }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn resample_lengths() {+ assert_eq!(resample(&[0i16; 960], 16_000, 24_000).len(), 1440);+ assert_eq!(resample(&[0i16; 1440], 24_000, 16_000).len(), 960);+ }++ #[test]+ fn pcm_round_trip() {+ let s = vec![0i16, 1, -1, i16::MAX, i16::MIN];+ assert_eq!(pcm_from_bytes(&unb64(&b64(&s))), s);+ }++ #[test]+ fn wav_header_is_stripped() {+ let mut wav = b"RIFF\0\0\0\0WAVEfmt \x10\0\0\0".to_vec();+ wav.extend_from_slice(&[0u8; 16]);+ wav.extend_from_slice(b"data\x04\0\0\0");+ wav.extend_from_slice(&[1, 0, 2, 0]);+ assert_eq!(strip_wav(&wav), &[1, 0, 2, 0]);+ assert_eq!(strip_wav(&[5, 6]), &[5, 6]);+ }++ #[test]+ fn languages_by_script() {+ assert_eq!(script_language("Hello there"), "en");+ assert_eq!(script_language("नमस्ते, आप कैसे हैं"), "hi");+ assert_eq!(script_language("آپ کیسے ہیں"), "ur");+ }+}diff --git a/plugins/optimus/companion/src/links/pipeline.rs b/plugins/optimus/companion/src/links/pipeline.rsnew file mode 100644index 00000000..f3c2b297--- /dev/null+++ b/plugins/optimus/companion/src/links/pipeline.rs@@ -0,0 +1,94 @@+//! "My own model" calls: streaming speech-to-text → the bridge (which asks the+//! owner's Mercury model, any provider) → streaming text-to-speech.+//!+//! This link never reasons: every finished utterance goes up as UserText, and+//! the bridge answers with Say. Speech is queued in order; Cancel (barge-in)+//! stops the current utterance and drops anything queued.++use std::collections::VecDeque;++use tokio::sync::mpsc;++use super::{Brain, Link, LinkCmd, LinkConfig, LinkEvent, stt, tts};++pub async fn open(cfg: LinkConfig) -> Result<Link, String> {+ let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel::<LinkCmd>();+ let (ev_tx, ev_rx) = mpsc::unbounded_channel::<LinkEvent>();+ let (stt_tx, mut stt_rx) = mpsc::unbounded_channel::<stt::SttEvent>();+ let audio_in = stt::start(&cfg.settings, stt_tx).await?;++ // Speech-to-text events → bridge.+ let ev = ev_tx.clone();+ tokio::spawn(async move {+ while let Some(e) = stt_rx.recv().await {+ let out = match e {+ stt::SttEvent::SpeechStarted => LinkEvent::SpeechStarted,+ stt::SttEvent::Final(t) => LinkEvent::UserText(t),+ stt::SttEvent::Closed(r) => LinkEvent::Closed(r),+ };+ if ev.send(out).is_err() { break; }+ }+ });++ let settings = cfg.settings.clone();+ tokio::spawn(async move {+ let mut queue: VecDeque<String> = VecDeque::new();+ let mut speaking: Option<tokio::task::JoinHandle<()>> = None;+ let (done_tx, mut done_rx) = mpsc::unbounded_channel::<()>();+ loop {+ // Start the next utterance when idle.+ if speaking.as_ref().map(|h| h.is_finished()).unwrap_or(true) {+ if let Some(text) = queue.pop_front() {+ let _ = ev_tx.send(LinkEvent::ResponseStarted);+ let _ = ev_tx.send(LinkEvent::AssistantText(text.clone()));+ let (pcm_tx, mut pcm_rx) = mpsc::unbounded_channel::<Vec<i16>>();+ let ev2 = ev_tx.clone();+ let fwd = tokio::spawn(async move {+ while let Some(p) = pcm_rx.recv().await {+ if ev2.send(LinkEvent::Audio(p)).is_err() { break; }+ }+ });+ let s = settings.clone();+ let done = done_tx.clone();+ let ev3 = ev_tx.clone();+ speaking = Some(tokio::spawn(async move {+ if let Err(e) = tts::speak(&s, &text, &pcm_tx).await {+ crate::log(format!("voice: {e}"));+ // A broken voice provider shouldn't leave the caller in silence forever.+ let _ = ev3.send(LinkEvent::Closed(e));+ }+ drop(pcm_tx);+ let _ = fwd.await;+ let _ = done.send(());+ }));+ }+ }+ tokio::select! {+ c = cmd_rx.recv() => {+ let Some(c) = c else { break };+ match c {+ LinkCmd::Audio(frame) => { let _ = audio_in.send(frame); }+ LinkCmd::Say(text) => { if !text.trim().is_empty() { queue.push_back(text); } }+ LinkCmd::ToolResult { output, .. } => { if !output.trim().is_empty() { queue.push_back(output); } }+ // Only reasoning models act on instructions; the bridge sends Say for us.+ LinkCmd::Instruct(_) => {}+ LinkCmd::Cancel => {+ queue.clear();+ if let Some(h) = speaking.take() {+ h.abort();+ let _ = ev_tx.send(LinkEvent::ResponseDone);+ }+ }+ }+ }+ Some(()) = done_rx.recv() => {+ speaking = None;+ if queue.is_empty() { let _ = ev_tx.send(LinkEvent::ResponseDone); }+ }+ }+ }+ if let Some(h) = speaking { h.abort(); }+ });++ Ok(Link { brain: Brain::Mercury, cmd: cmd_tx, events: ev_rx })+}diff --git a/plugins/optimus/companion/src/links/realtime.rs b/plugins/optimus/companion/src/links/realtime.rsnew file mode 100644index 00000000..638d854a--- /dev/null+++ b/plugins/optimus/companion/src/links/realtime.rs@@ -0,0 +1,244 @@+//! Speech-to-speech models on OpenAI's Realtime protocol. One client, small+//! per-provider profiles: OpenAI (default), Azure OpenAI, xAI Grok, Alibaba+//! Qwen-Omni (older event names), ElevenLabs Realtime (session minted via a+//! client secret; experimental until ElevenLabs documents server use).++use serde_json::{Value, json};+use tokio::sync::mpsc;+use tokio_websockets::Message;+use futures_util::{SinkExt, StreamExt};++use super::{Brain, CALL_RATE, Link, LinkCmd, LinkConfig, LinkEvent, b64, env_key, pcm_from_bytes, resample, setting, unb64, ws};++#[derive(Clone, Copy, PartialEq, Eq)]+enum Dialect {+ /// OpenAI GA session shape (OpenAI, Azure, ElevenLabs).+ Ga,+ /// GA events, but voice and turn detection at the top of the session (xAI).+ Grok,+ /// Older Realtime shape and event names, tools nested in "function" (Qwen).+ Beta,+}++struct Profile {+ url: String,+ headers: Vec<(&'static str, String)>,+ model: String,+ dialect: Dialect,+ in_rate: u32,+ out_rate: u32,+ voice: String,+ transcribe: Option<String>,+}++fn base_ws(http_base: &str) -> String {+ let b = http_base.trim_end_matches('/');+ if let Some(r) = b.strip_prefix("https://") { format!("wss://{r}") } else if let Some(r) = b.strip_prefix("http://") { format!("ws://{r}") } else { b.to_string() }+}++async fn profile(s: &Value) -> Result<Profile, String> {+ let engine = super::engine(s);+ Ok(match engine.as_str() {+ "openai" => {+ let key = env_key("MERCURY_PROVIDER_OPENAI_API_KEY").ok_or("no OpenAI provider key")?;+ let base = env_key("MERCURY_PROVIDER_OPENAI_BASE_URL").unwrap_or_else(|| "https://api.openai.com/v1".into());+ let model = setting(s, "voiceModel", "gpt-realtime-2.1");+ Profile {+ url: format!("{}/realtime?model={model}", base_ws(&base)),+ headers: vec![("authorization", format!("Bearer {key}"))],+ model, dialect: Dialect::Ga, in_rate: 24_000, out_rate: 24_000,+ voice: setting(s, "voice", "marin"), transcribe: Some("gpt-4o-mini-transcribe".into()),+ }+ }+ "azure" => {+ let key = env_key("AZURE_OPENAI_API_KEY").ok_or("no Azure OpenAI key")?;+ let endpoint = setting(s, "azureEndpoint", "");+ let host = endpoint.trim_start_matches("https://").trim_start_matches("wss://").trim_end_matches('/').to_string();+ if host.is_empty() { return Err("set the Azure endpoint (e.g. myresource.openai.azure.com)".into()); }+ let model = setting(s, "azureDeployment", "gpt-realtime-2.1");+ Profile {+ url: format!("wss://{host}/openai/v1/realtime?model={model}"),+ headers: vec![("api-key", key)],+ model, dialect: Dialect::Ga, in_rate: 24_000, out_rate: 24_000,+ voice: setting(s, "voice", "marin"), transcribe: Some(setting(s, "azureTranscribeModel", "whisper-1")),+ }+ }+ "grok" => {+ let key = env_key("MERCURY_PROVIDER_GROK_API_KEY").ok_or("no Grok provider key")?;+ let model = setting(s, "grokModel", "grok-voice-latest");+ Profile {+ url: format!("wss://api.x.ai/v1/realtime?model={model}"),+ headers: vec![("authorization", format!("Bearer {key}"))],+ // xAI takes phone-rate audio directly: no resampling either way.+ model, dialect: Dialect::Grok, in_rate: CALL_RATE, out_rate: CALL_RATE,+ voice: setting(s, "grokVoice", "eve"), transcribe: Some("grok-transcribe".into()),+ }+ }+ "qwen" => {+ let key = env_key("DASHSCOPE_API_KEY").ok_or("no Qwen (DashScope) key")?;+ let endpoint = setting(s, "qwenEndpoint", "dashscope-intl.aliyuncs.com");+ let host = endpoint.trim_start_matches("https://").trim_start_matches("wss://").trim_end_matches('/').to_string();+ let model = setting(s, "qwenModel", "qwen3.8-omni-flash-realtime");+ Profile {+ url: format!("wss://{host}/api-ws/v1/realtime?model={model}"),+ headers: vec![("authorization", format!("Bearer {key}"))],+ model, dialect: Dialect::Beta, in_rate: CALL_RATE, out_rate: 24_000,+ voice: setting(s, "qwenVoice", "Tina"), transcribe: Some("qwen3-asr-flash-realtime".into()),+ }+ }+ "elevenlabs" => {+ let key = env_key("ELEVENLABS_API_KEY").ok_or("no ElevenLabs key")?;+ let model = setting(s, "elevenlabsModel", "eleven_realtime_v1_mini");+ let voice = setting(s, "elevenlabsVoice", "brian");+ let secret = eleven_client_secret(&key, &model, &voice).await?;+ Profile {+ url: "wss://api.elevenlabs.io/v1/convai/realtime".into(),+ headers: vec![("authorization", format!("Bearer {secret}"))],+ model, dialect: Dialect::Ga, in_rate: 24_000, out_rate: 24_000, voice, transcribe: None,+ }+ }+ other => return Err(format!("{other} isn't a realtime voice engine")),+ })+}++/// ElevenLabs Realtime is reached with a short-lived client secret minted with the API key.+async fn eleven_client_secret(key: &str, model: &str, voice: &str) -> Result<String, String> {+ let body = json!({+ "session": { "type": "realtime", "model": model, "audio": { "output": { "voice": voice } } },+ "expires_after": { "anchor": "created_at", "seconds": 600 },+ });+ let key = key.to_string();+ tokio::task::spawn_blocking(move || -> Result<String, String> {+ let mut res = ureq::post("https://api.elevenlabs.io/v1/convai/realtime/client_secrets")+ .header("xi-api-key", &key)+ .header("content-type", "application/json")+ .send(body.to_string().as_bytes())+ .map_err(|e| format!("ElevenLabs: {e}"))?;+ let v: Value = serde_json::from_str(&res.body_mut().read_to_string().map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;+ v.get("value").and_then(Value::as_str).map(str::to_string).ok_or_else(|| "ElevenLabs didn't return a session secret".into())+ })+ .await+ .map_err(|e| e.to_string())?+}++fn session(p: &Profile, cfg: &LinkConfig) -> Value {+ let tools: Vec<Value> = cfg.tools.as_array().cloned().unwrap_or_default();+ match p.dialect {+ Dialect::Ga => {+ let mut input = json!({+ "format": { "type": "audio/pcm", "rate": p.in_rate },+ "turn_detection": { "type": "server_vad", "interrupt_response": true, "create_response": true },+ });+ if let Some(t) = &p.transcribe { input["transcription"] = json!({ "model": t }); }+ json!({ "type": "session.update", "session": {+ "type": "realtime", "model": p.model, "instructions": cfg.instructions,+ "audio": { "input": input, "output": { "format": { "type": "audio/pcm", "rate": p.out_rate }, "voice": p.voice } },+ "tools": tools,+ } })+ }+ Dialect::Grok => json!({ "type": "session.update", "session": {+ "instructions": cfg.instructions, "voice": p.voice,+ "turn_detection": { "type": "server_vad" },+ "audio": {+ "input": { "format": { "type": "audio/pcm", "rate": p.in_rate }, "transcription": { "model": p.transcribe } },+ "output": { "format": { "type": "audio/pcm", "rate": p.out_rate } },+ },+ "tools": tools,+ } }),+ Dialect::Beta => json!({ "type": "session.update", "session": {+ "modalities": ["text", "audio"], "voice": p.voice, "instructions": cfg.instructions,+ "input_audio_format": "pcm", "output_audio_format": "pcm",+ "turn_detection": { "type": "server_vad", "silence_duration_ms": 700 },+ "input_audio_transcription": { "model": p.transcribe },+ "tools": tools.iter().map(|t| json!({ "type": "function", "function": {+ "name": t.get("name"), "description": t.get("description"), "parameters": t.get("parameters") } })).collect::<Vec<_>>(),+ } }),+ }+}++/// An instruction the model should respond to now (status update, approval, greeting).+fn instruct(p: &Profile, text: &str) -> Vec<Value> {+ match p.dialect {+ // Qwen has no user text items: steer the next response directly.+ Dialect::Beta => vec![json!({ "type": "response.create", "response": { "instructions": text } })],+ _ => vec![+ json!({ "type": "conversation.item.create", "item": { "type": "message", "role": "user", "content": [{ "type": "input_text", "text": text }] } }),+ json!({ "type": "response.create" }),+ ],+ }+}++pub async fn open(cfg: LinkConfig) -> Result<Link, String> {+ let p = profile(&cfg.settings).await?;+ let sock = ws::connect(&p.url, &p.headers).await.map_err(|e| format!("couldn't reach the voice model: {e}"))?;+ let (mut tx, mut rx) = sock.split();+ let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel::<LinkCmd>();+ let (ev_tx, ev_rx) = mpsc::unbounded_channel::<LinkEvent>();++ tx.send(Message::text(session(&p, &cfg).to_string())).await.map_err(|e| e.to_string())?;++ let (in_rate, dialect) = (p.in_rate, p.dialect);+ let p2 = Profile { url: String::new(), headers: vec![], model: p.model.clone(), dialect: p.dialect, in_rate: p.in_rate, out_rate: p.out_rate, voice: p.voice.clone(), transcribe: None };+ tokio::spawn(async move {+ while let Some(c) = cmd_rx.recv().await {+ let msgs: Vec<Value> = match c {+ LinkCmd::Audio(frame) => vec![json!({ "type": "input_audio_buffer.append", "audio": b64(&resample(&frame, CALL_RATE, in_rate)) })],+ LinkCmd::Instruct(text) => instruct(&p2, &text),+ LinkCmd::Say(text) => instruct(&p2, &format!("[Say this to the caller, in your own natural voice] {text}")),+ LinkCmd::ToolResult { id, output } => vec![+ json!({ "type": "conversation.item.create", "item": { "type": "function_call_output", "call_id": id, "output": output } }),+ json!({ "type": "response.create" }),+ ],+ // Server VAD already interrupts the response; nothing to send.+ LinkCmd::Cancel => vec![],+ };+ for m in msgs {+ if tx.send(Message::text(m.to_string())).await.is_err() { return; }+ }+ }+ let _ = tx.close().await;+ });++ let out_rate = p.out_rate;+ tokio::spawn(async move {+ while let Some(m) = rx.next().await {+ let Ok(m) = m else { break };+ if m.is_close() {+ let reason = m.as_close().map(|(_, r)| r.to_string()).unwrap_or_default();+ let _ = ev_tx.send(LinkEvent::Closed(crate::voice::explain_close(&reason)));+ return;+ }+ let Some(t) = m.as_text() else { continue };+ let Ok(v) = serde_json::from_str::<Value>(t) else { continue };+ let s = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or("").to_string();+ let e = match s("type").as_str() {+ "response.created" => Some(LinkEvent::ResponseStarted),+ "response.done" | "response.cancelled" => Some(LinkEvent::ResponseDone),+ "response.output_audio.delta" | "response.audio.delta" => {+ let pcm = pcm_from_bytes(&unb64(&s("delta")));+ Some(LinkEvent::Audio(resample(&pcm, out_rate, CALL_RATE)))+ }+ "input_audio_buffer.speech_started" => Some(LinkEvent::SpeechStarted),+ "conversation.item.input_audio_transcription.completed" => Some(LinkEvent::UserText(s("transcript").trim().to_string())),+ "response.output_audio_transcript.done" | "response.audio_transcript.done" => Some(LinkEvent::AssistantText(s("transcript").trim().to_string())),+ "response.function_call_arguments.done" => Some(LinkEvent::ToolCall {+ id: s("call_id"),+ name: s("name"),+ args: serde_json::from_str(&s("arguments")).unwrap_or(json!({})),+ }),+ "error" => {+ crate::log(format!("voice model error: {}", v.get("error").map(|e| e.to_string()).unwrap_or_default()));+ None+ }+ _ => None,+ };+ if let Some(e) = e {+ if ev_tx.send(e).is_err() { break; }+ }+ }+ let _ = dialect;+ let _ = ev_tx.send(LinkEvent::Closed("the voice model disconnected".into()));+ });++ Ok(Link { brain: Brain::Voice, cmd: cmd_tx, events: ev_rx })+}diff --git a/plugins/optimus/companion/src/links/stt.rs b/plugins/optimus/companion/src/links/stt.rsnew file mode 100644index 00000000..17b61be9--- /dev/null+++ b/plugins/optimus/companion/src/links/stt.rs@@ -0,0 +1,191 @@+//! Streaming speech-to-text for the pipeline: Deepgram, AssemblyAI,+//! ElevenLabs Scribe, Sarvam. Each turns caller audio (16 kHz PCM16) into+//! "speech started" and "finished utterance" events.++use serde_json::{Value, json};+use tokio::sync::mpsc;+use tokio_websockets::Message;+use futures_util::{SinkExt, StreamExt};++use super::{b64, pcm_bytes, setting, env_key, ws};++pub enum SttEvent {+ SpeechStarted,+ Final(String),+ Closed(String),+}++pub fn key_name(provider: &str) -> Option<&'static str> {+ match provider {+ "deepgram" => Some("DEEPGRAM_API_KEY"),+ "assemblyai" => Some("ASSEMBLYAI_API_KEY"),+ "elevenlabs" => Some("ELEVENLABS_API_KEY"),+ "sarvam" => Some("SARVAM_API_KEY"),+ _ => None,+ }+}++pub fn label(provider: &str) -> String {+ match provider {+ "deepgram" => "Deepgram",+ "assemblyai" => "AssemblyAI",+ "elevenlabs" => "ElevenLabs",+ "sarvam" => "Sarvam",+ other => other,+ }+ .to_string()+}++/// Start listening. Audio goes in on the returned sender; events come out on `events`.+pub async fn start(settings: &Value, events: mpsc::UnboundedSender<SttEvent>) -> Result<mpsc::UnboundedSender<Vec<i16>>, String> {+ let provider = setting(settings, "sttProvider", "deepgram");+ let lang = setting(settings, "sttLanguage", "auto");+ let key = env_key(key_name(&provider).ok_or_else(|| format!("unknown speech-to-text provider {provider}"))?)+ .ok_or_else(|| format!("{} needs its API key", label(&provider)))?;++ let (url, headers): (String, Vec<(&str, String)>) = match provider.as_str() {+ "deepgram" => {+ // Nova-3: "multi" covers en/hi and others; Urdu needs language=ur on its own.+ let language = if lang == "auto" { "multi".to_string() } else { lang.clone() };+ (+ format!("wss://api.deepgram.com/v1/listen?model={}&encoding=linear16&sample_rate=16000&channels=1&language={language}&interim_results=true&endpointing=400&utterance_end_ms=1000&vad_events=true&smart_format=true", setting(settings, "sttModel", "nova-3")),+ vec![("authorization", format!("Token {key}"))],+ )+ }+ "assemblyai" => {+ let detect = if lang == "auto" { "&language_detection=true".to_string() } else { format!("&language_codes={lang}") };+ (+ format!("wss://streaming.assemblyai.com/v3/ws?speech_model={}&sample_rate=16000&encoding=pcm_s16le&min_turn_silence=500{detect}", setting(settings, "sttModel", "universal-3-6-pro")),+ vec![("authorization", key)],+ )+ }+ "elevenlabs" => {+ let language = if lang == "auto" { String::new() } else { format!("&language_code={lang}") };+ (+ format!("wss://api.elevenlabs.io/v1/speech-to-text/realtime?model_id={}&audio_format=pcm_16000&commit_strategy=vad&vad_silence_threshold_secs=0.6{language}", setting(settings, "sttModel", "scribe_v2_realtime")),+ vec![("xi-api-key", key)],+ )+ }+ "sarvam" => {+ let language = match lang.as_str() { "auto" => "unknown".to_string(), l if l.contains('-') => l.to_string(), l => format!("{l}-IN") };+ (+ format!("wss://api.sarvam.ai/speech-to-text/ws?model={}&language-code={language}&sample_rate=16000&input_audio_codec=pcm_s16le&vad_signals=true&high_vad_sensitivity=true&mode=transcribe", setting(settings, "sttModel", "saaras:v4")),+ vec![("api-subscription-key", key)],+ )+ }+ other => return Err(format!("unknown speech-to-text provider {other}")),+ };++ let sock = ws::connect(&url, &headers).await.map_err(|e| format!("couldn't reach {}: {e}", label(&provider)))?;+ let (mut tx, mut rx) = sock.split();+ let (audio_tx, mut audio_rx) = mpsc::unbounded_channel::<Vec<i16>>();++ let p = provider.clone();+ tokio::spawn(async move {+ let mut keepalive = tokio::time::interval(std::time::Duration::from_secs(5));+ loop {+ tokio::select! {+ frame = audio_rx.recv() => {+ let Some(frame) = frame else { break };+ let msg = match p.as_str() {+ "elevenlabs" => Message::text(json!({ "message_type": "input_audio_chunk", "audio_base_64": b64(&frame), "commit": false, "sample_rate": 16000 }).to_string()),+ "sarvam" => Message::text(json!({ "audio": { "data": b64(&frame), "sample_rate": "16000", "encoding": "audio/wav" } }).to_string()),+ _ => Message::binary(pcm_bytes(&frame)),+ };+ if tx.send(msg).await.is_err() { break; }+ }+ _ = keepalive.tick() => {+ if p == "deepgram" && tx.send(Message::text(json!({ "type": "KeepAlive" }).to_string())).await.is_err() { break; }+ }+ }+ }+ let close = match p.as_str() {+ "deepgram" => Some(json!({ "type": "CloseStream" })),+ "assemblyai" => Some(json!({ "type": "Terminate" })),+ _ => None,+ };+ if let Some(c) = close { let _ = tx.send(Message::text(c.to_string())).await; }+ let _ = tx.close().await;+ });++ tokio::spawn(async move {+ // Deepgram sends final segments; an utterance ends at speech_final / UtteranceEnd.+ let mut pending = String::new();+ let mut speaking = false;+ while let Some(msg) = rx.next().await {+ let Ok(msg) = msg else { break };+ if msg.is_close() {+ let reason = msg.as_close().map(|(_, r)| r.to_string()).unwrap_or_default();+ let _ = events.send(SttEvent::Closed(if reason.is_empty() { format!("{} closed the connection", label(&provider)) } else { format!("{}: {reason}", label(&provider)) }));+ return;+ }+ let Some(text) = msg.as_text() else { continue };+ let Ok(v) = serde_json::from_str::<Value>(text) else { continue };+ let s = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or("").to_string();+ match provider.as_str() {+ "deepgram" => match s("type").as_str() {+ "SpeechStarted" => { let _ = events.send(SttEvent::SpeechStarted); }+ "Results" => {+ let t = v.pointer("/channel/alternatives/0/transcript").and_then(Value::as_str).unwrap_or("").trim().to_string();+ if !t.is_empty() && !speaking { speaking = true; let _ = events.send(SttEvent::SpeechStarted); }+ if v.get("is_final").and_then(Value::as_bool) == Some(true) && !t.is_empty() {+ if !pending.is_empty() { pending.push(' '); }+ pending.push_str(&t);+ }+ if v.get("speech_final").and_then(Value::as_bool) == Some(true) && !pending.is_empty() {+ let _ = events.send(SttEvent::Final(std::mem::take(&mut pending)));+ speaking = false;+ }+ }+ "UtteranceEnd" => {+ if !pending.is_empty() { let _ = events.send(SttEvent::Final(std::mem::take(&mut pending))); }+ speaking = false;+ }+ "Error" => crate::log(format!("deepgram: {}", s("description"))),+ _ => {}+ },+ "assemblyai" => match s("type").as_str() {+ "SpeechStarted" => { let _ = events.send(SttEvent::SpeechStarted); }+ "Turn" => {+ let t = s("transcript");+ if !t.trim().is_empty() && !speaking { speaking = true; let _ = events.send(SttEvent::SpeechStarted); }+ if v.get("end_of_turn").and_then(Value::as_bool) == Some(true) {+ let u = if s("utterance").trim().is_empty() { t } else { s("utterance") };+ if !u.trim().is_empty() { let _ = events.send(SttEvent::Final(u.trim().to_string())); }+ speaking = false;+ }+ }+ "Termination" => break,+ _ => {}+ },+ "elevenlabs" => match s("message_type").as_str() {+ "partial_transcript" => {+ if !s("text").trim().is_empty() && !speaking { speaking = true; let _ = events.send(SttEvent::SpeechStarted); }+ }+ "committed_transcript" | "committed_transcript_with_timestamps" => {+ let t = s("text");+ if !t.trim().is_empty() { let _ = events.send(SttEvent::Final(t.trim().to_string())); }+ speaking = false;+ }+ "session_started" => {}+ kind => if v.get("error").is_some() { crate::log(format!("elevenlabs stt {kind}: {}", s("error"))); },+ },+ "sarvam" => match s("type").as_str() {+ "events" => {+ if v.pointer("/data/signal_type").and_then(Value::as_str) == Some("START_SPEECH") { let _ = events.send(SttEvent::SpeechStarted); }+ }+ "data" => {+ let t = v.pointer("/data/transcript").and_then(Value::as_str).unwrap_or("").trim().to_string();+ if !t.is_empty() { let _ = events.send(SttEvent::Final(t)); }+ }+ "error" => crate::log(format!("sarvam stt: {}", v.pointer("/data/error").and_then(Value::as_str).unwrap_or(""))),+ _ => {}+ },+ _ => {}+ }+ }+ let _ = events.send(SttEvent::Closed(format!("{} disconnected", label(&provider))));+ });++ Ok(audio_tx)+}diff --git a/plugins/optimus/companion/src/links/tts.rs b/plugins/optimus/companion/src/links/tts.rsnew file mode 100644index 00000000..d7891e40--- /dev/null+++ b/plugins/optimus/companion/src/links/tts.rs@@ -0,0 +1,198 @@+//! Streaming text-to-speech for the pipeline: Cartesia, ElevenLabs, MiniMax,+//! Sarvam, Deepgram. One connection per utterance, so cancelling (barge-in)+//! is just dropping the task: nothing half-spoken can leak into the next reply.++use serde_json::{Value, json};+use tokio::sync::mpsc;+use tokio_websockets::Message;+use futures_util::{SinkExt, StreamExt};++use super::{env_key, pcm_from_bytes, script_language, setting, strip_wav, unb64, ws};++pub fn key_name(provider: &str) -> Option<&'static str> {+ match provider {+ "cartesia" => Some("CARTESIA_API_KEY"),+ "elevenlabs" => Some("ELEVENLABS_API_KEY"),+ "minimax" => Some("MINIMAX_API_KEY"),+ "sarvam" => Some("SARVAM_API_KEY"),+ "deepgram" => Some("DEEPGRAM_API_KEY"),+ _ => None,+ }+}++pub fn label(provider: &str) -> String {+ match provider {+ "cartesia" => "Cartesia",+ "elevenlabs" => "ElevenLabs",+ "minimax" => "MiniMax",+ "sarvam" => "Sarvam",+ "deepgram" => "Deepgram",+ other => other,+ }+ .to_string()+}++fn default_voice(provider: &str) -> &'static str {+ match provider {+ "cartesia" => "a0e99841-438c-4a64-b679-ae501e7d6091",+ "elevenlabs" => "JBFqnCBsd6RMkjVDRZzb",+ "minimax" => "English_expressive_narrator",+ "sarvam" => "shubh",+ "deepgram" => "aura-2-thalia-en",+ _ => "",+ }+}++/// Speak `text`: 16 kHz PCM16 chunks go to `out` as they arrive. Returns when done.+pub async fn speak(settings: &Value, text: &str, out: &mpsc::UnboundedSender<Vec<i16>>) -> Result<(), String> {+ let provider = setting(settings, "ttsProvider", "cartesia");+ let key = env_key(key_name(&provider).ok_or_else(|| format!("unknown voice provider {provider}"))?)+ .ok_or_else(|| format!("{} needs its API key", label(&provider)))?;+ let voice = setting(settings, "ttsVoice", default_voice(&provider));+ let lang = script_language(text);+ let fail = |e: String| format!("{}: {e}", label(&provider));++ match provider.as_str() {+ "cartesia" => {+ let mut sock = ws::connect("wss://api.cartesia.ai/tts/websocket", &[("x-api-key", key), ("cartesia-version", "2026-08-14".into())]).await.map_err(fail)?;+ let req = json!({+ "model_id": setting(settings, "ttsModel", "sonic-3.6"),+ "transcript": text,+ "voice": { "id": voice },+ "language": lang,+ "context_id": format!("u{}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)),+ "output_format": { "container": "raw", "encoding": "pcm_s16le", "sample_rate": 16000 },+ "continue": false,+ });+ sock.send(Message::text(req.to_string())).await.map_err(|e| fail(e.to_string()))?;+ while let Some(m) = sock.next().await {+ let m = m.map_err(|e| fail(e.to_string()))?;+ let Some(t) = m.as_text() else { continue };+ let v: Value = serde_json::from_str(t).unwrap_or_default();+ match v.get("type").and_then(Value::as_str) {+ Some("chunk") => if let Some(d) = v.get("data").and_then(Value::as_str) { let _ = out.send(pcm_from_bytes(&unb64(d))); },+ Some("done") => break,+ Some("error") => return Err(fail(v.get("message").and_then(Value::as_str).unwrap_or("error").to_string())),+ _ => {}+ }+ }+ let _ = sock.close().await;+ }+ "elevenlabs" => {+ let url = format!(+ "wss://api.elevenlabs.io/v1/text-to-speech/{voice}/stream-input?model_id={}&output_format=pcm_16000&inactivity_timeout=30",+ setting(settings, "ttsModel", "eleven_flash_v2_5")+ );+ let mut sock = ws::connect(&url, &[("xi-api-key", key)]).await.map_err(fail)?;+ for msg in [json!({ "text": " " }), json!({ "text": format!("{text} "), "flush": true }), json!({ "text": "" })] {+ sock.send(Message::text(msg.to_string())).await.map_err(|e| fail(e.to_string()))?;+ }+ while let Some(m) = sock.next().await {+ let m = m.map_err(|e| fail(e.to_string()))?;+ if m.is_close() { break; }+ let Some(t) = m.as_text() else { continue };+ let v: Value = serde_json::from_str(t).unwrap_or_default();+ if let Some(a) = v.get("audio").and_then(Value::as_str) { let _ = out.send(pcm_from_bytes(&unb64(a))); }+ if v.get("isFinal").and_then(Value::as_bool) == Some(true) { break; }+ if let Some(e) = v.get("error").and_then(Value::as_str) { return Err(fail(e.to_string())); }+ }+ }+ "minimax" => {+ let mut sock = ws::connect("wss://api.minimax.io/ws/v1/t2a_v2", &[("authorization", format!("Bearer {key}"))]).await.map_err(fail)?;+ let boost = match lang { "hi" => "Hindi", _ => "auto" };+ let mut started = false;+ while let Some(m) = sock.next().await {+ let m = m.map_err(|e| fail(e.to_string()))?;+ if m.is_close() { break; }+ let Some(t) = m.as_text() else { continue };+ let v: Value = serde_json::from_str(t).unwrap_or_default();+ match v.get("event").and_then(Value::as_str) {+ Some("connected_success") => {+ let start = json!({+ "event": "task_start",+ "model": setting(settings, "ttsModel", "speech-2.8-turbo"),+ "language_boost": boost,+ "voice_setting": { "voice_id": voice, "speed": 1, "vol": 1, "pitch": 0 },+ "audio_setting": { "sample_rate": 16000, "format": "pcm", "channel": 1 },+ });+ sock.send(Message::text(start.to_string())).await.map_err(|e| fail(e.to_string()))?;+ }+ Some("task_started") if !started => {+ started = true;+ sock.send(Message::text(json!({ "event": "task_continue", "text": text }).to_string())).await.map_err(|e| fail(e.to_string()))?;+ sock.send(Message::text(json!({ "event": "task_finish" }).to_string())).await.map_err(|e| fail(e.to_string()))?;+ }+ Some("task_failed") => return Err(fail(v.pointer("/base_resp/status_msg").and_then(Value::as_str).unwrap_or("failed").to_string())),+ Some("task_finished") => break,+ _ => {+ if let Some(h) = v.pointer("/data/audio").and_then(Value::as_str) {+ let _ = out.send(pcm_from_bytes(&hex_decode(h)));+ }+ if v.get("is_final").and_then(Value::as_bool) == Some(true) { break; }+ }+ }+ }+ }+ "sarvam" => {+ let url = format!("wss://api.sarvam.ai/text-to-speech/ws?model={}&send_completion_event=true", setting(settings, "ttsModel", "bulbul:v3"));+ let mut sock = ws::connect(&url, &[("api-subscription-key", key)]).await.map_err(fail)?;+ let language_code = match lang { "hi" => "hi-IN", _ => "en-IN" };+ let msgs = [+ json!({ "type": "config", "data": { "model": setting(settings, "ttsModel", "bulbul:v3"), "language_code": language_code, "speaker": voice, "pace": 1.0, "speech_sample_rate": 16000, "output_audio_codec": "linear16" } }),+ json!({ "type": "text", "data": { "text": text } }),+ json!({ "type": "flush" }),+ ];+ for msg in msgs {+ sock.send(Message::text(msg.to_string())).await.map_err(|e| fail(e.to_string()))?;+ }+ while let Some(m) = sock.next().await {+ let m = m.map_err(|e| fail(e.to_string()))?;+ if m.is_close() { break; }+ let Some(t) = m.as_text() else { continue };+ let v: Value = serde_json::from_str(t).unwrap_or_default();+ match v.get("type").and_then(Value::as_str) {+ Some("audio") => if let Some(a) = v.pointer("/data/audio").and_then(Value::as_str) { let bytes = unb64(a); let _ = out.send(pcm_from_bytes(strip_wav(&bytes))); },+ Some("event") if v.pointer("/data/event_type").and_then(Value::as_str) == Some("final") => break,+ Some("error") => return Err(fail(v.pointer("/data/message").and_then(Value::as_str).unwrap_or("error").to_string())),+ _ => {}+ }+ }+ let _ = sock.close().await;+ }+ "deepgram" => {+ let url = format!("wss://api.deepgram.com/v1/speak?model={voice}&encoding=linear16&sample_rate=16000");+ let mut sock = ws::connect(&url, &[("authorization", format!("Token {key}"))]).await.map_err(fail)?;+ sock.send(Message::text(json!({ "type": "Speak", "text": text }).to_string())).await.map_err(|e| fail(e.to_string()))?;+ sock.send(Message::text(json!({ "type": "Flush" }).to_string())).await.map_err(|e| fail(e.to_string()))?;+ while let Some(m) = sock.next().await {+ let m = m.map_err(|e| fail(e.to_string()))?;+ if m.is_close() { break; }+ if m.is_binary() {+ let _ = out.send(pcm_from_bytes(&m.as_payload().to_vec()));+ continue;+ }+ let Some(t) = m.as_text() else { continue };+ let v: Value = serde_json::from_str(t).unwrap_or_default();+ if v.get("type").and_then(Value::as_str) == Some("Flushed") { break; }+ }+ let _ = sock.send(Message::text(json!({ "type": "Close" }).to_string())).await;+ }+ other => return Err(format!("unknown voice provider {other}")),+ }+ Ok(())+}++fn hex_decode(h: &str) -> Vec<u8> {+ let b = h.as_bytes();+ (0..b.len() / 2)+ .filter_map(|i| u8::from_str_radix(std::str::from_utf8(&b[i * 2..i * 2 + 2]).ok()?, 16).ok())+ .collect()+}++#[cfg(test)]+mod tests {+ #[test]+ fn hex() {+ assert_eq!(super::hex_decode("00ff10"), vec![0, 255, 16]);+ }+}diff --git a/plugins/optimus/companion/src/links/ws.rs b/plugins/optimus/companion/src/links/ws.rsnew file mode 100644index 00000000..459aeb52--- /dev/null+++ b/plugins/optimus/companion/src/links/ws.rs@@ -0,0 +1,18 @@+//! WebSocket connect with custom headers (rustls + ring, like the WhatsApp plugin).++use tokio_websockets::{ClientBuilder, MaybeTlsStream, WebSocketStream};+use tokio::net::TcpStream;++pub type Socket = WebSocketStream<MaybeTlsStream<TcpStream>>;++pub async fn connect(url: &str, headers: &[(&str, String)]) -> Result<Socket, String> {+ let uri: http::Uri = url.parse().map_err(|e| format!("bad URL: {e}"))?;+ let mut b = ClientBuilder::from_uri(uri);+ for (name, value) in headers {+ let n = http::HeaderName::from_bytes(name.as_bytes()).map_err(|e| e.to_string())?;+ let v = http::HeaderValue::from_str(value).map_err(|e| e.to_string())?;+ b = b.add_header(n, v).map_err(|e| e.to_string())?;+ }+ let (ws, _) = b.connect().await.map_err(|e| e.to_string())?;+ Ok(ws)+}diff --git a/plugins/optimus/companion/src/mac.rs b/plugins/optimus/companion/src/mac.rsindex 060469d9..53fc8503 100644--- a/plugins/optimus/companion/src/mac.rs+++ b/plugins/optimus/companion/src/mac.rs@@ -22,7 +22,6 @@ use std::time::{Duration, Instant};use serde_json::{Value, json};-use crate::ops::Ops;pub const BUNDLE_ID: &str = "sh.mercuryagent.optimus";const CERT_NAME: &str = "Mercury Optimus (local)";@@ -77,7 +76,7 @@ pub fn permission_report(request: bool) -> Value {json!({ "ready": ax && screen, "accessibility": ax, "screenRecording": screen, "text": text })}-/// `optimus agent --socket <path>`: serve one connection, then exit.+/// `optimus agent --socket <path>`: run the core for one connection, then exit.pub fn agent_main(socket: &Path) -> ! {let _ = fs::remove_file(socket);let listener = match UnixListener::bind(socket) {@@ -101,68 +100,51 @@ pub fn agent_main(socket: &Path) -> ! {}};let _ = stream.set_nonblocking(false);- let mut ops = Ops::new();- let mut out = stream.try_clone().expect("socket clone");- for line in BufReader::new(stream).lines() {- let Ok(line) = line else { break };- let Ok(req) = serde_json::from_str::<Value>(&line) else { continue };- let op = req["op"].as_str().unwrap_or("");- if op == "quit" {- break;- }- let reply = match op {- "hello" => json!({ "ok": { "version": env!("CARGO_PKG_VERSION") } }),- _ => match ops.run(op, &req["args"]) {- Ok(v) => json!({ "ok": v }),- Err(e) => json!({ "err": e }),- },- };- if writeln!(out, "{reply}").is_err() {- break;+ let _ = fs::remove_file(socket);+ let writer = std::sync::Mutex::new(stream.try_clone().expect("socket clone"));+ let mut reader = BufReader::new(stream);+ // LaunchServices started us with launchd's environment, not Mercury's: the+ // plugin sends its settings and voice keys first, over this private socket.+ let mut first = String::new();+ if reader.read_line(&mut first).is_ok() {+ if let Some(env) = serde_json::from_str::<Value>(&first).ok().and_then(|v| v.get("env").cloned()).and_then(|e| e.as_object().cloned()) {+ for (k, v) in env {+ if let Some(v) = v.as_str() {+ // Single-threaded here: nothing else reads the environment yet.+ unsafe { std::env::set_var(k, v) };+ }+ }}}- let _ = fs::remove_file(socket);+ let (tx, rx) = std::sync::mpsc::channel::<Value>();+ std::thread::spawn(move || {+ for line in reader.lines() {+ let Ok(line) = line else { break };+ if let Ok(v) = serde_json::from_str::<Value>(&line) {+ if tx.send(v).is_err() {+ break;+ }+ }+ }+ // The plugin side closed: dropping tx ends the core.+ });+ crate::core::run(rx, move |v| {+ let mut w = writer.lock().unwrap_or_else(|e| e.into_inner());+ let _ = writeln!(w, "{v}");+ });std::process::exit(0)}// ── In the plugin process ──────────────────────────────────────────────-pub struct Agent {- reader: BufReader<UnixStream>,- writer: UnixStream,-}--impl Agent {- pub fn call(&mut self, op: &str, args: &Value) -> Result<Value, String> {- writeln!(self.writer, "{}", json!({ "op": op, "args": args })).map_err(|e| format!("Optimus.app went away: {e}"))?;- let mut line = String::new();- self.reader.read_line(&mut line).map_err(|e| format!("Optimus.app went away: {e}"))?;- if line.is_empty() {- return Err("Optimus.app went away".into());- }- let v: Value = serde_json::from_str(&line).map_err(|e| format!("bad reply from Optimus.app: {e}"))?;- match (v.get("ok"), v.get("err")) {- (Some(ok), _) => Ok(ok.clone()),- (_, Some(e)) => Err(e.as_str().unwrap_or("failed").to_string()),- _ => Err("bad reply from Optimus.app".into()),- }- }-}--impl Drop for Agent {- fn drop(&mut self) {- let _ = writeln!(self.writer, "{}", json!({ "op": "quit" }));- }-}-fn data_dir() -> PathBuf {std::env::var_os("MERCURY_PLUGIN_DATA_DIR").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| "/tmp".into())).join(".mercury/optimus"))}-/// Build (or refresh) Optimus.app, sign it, launch it and connect.-pub fn start_agent() -> Result<Agent, String> {+/// Build (or refresh) Optimus.app, sign it, launch it and connect to its core.+pub fn start_agent() -> Result<UnixStream, String> {let dir = data_dir();fs::create_dir_all(&dir).map_err(|e| format!("can't create {}: {e}", dir.display()))?;let app = dir.join("Optimus.app");@@ -189,10 +171,14 @@ pub fn start_agent() -> Result<Agent, String> {Err(e) => return Err(format!("Optimus.app didn't start: {e}")),}};- let writer = stream.try_clone().map_err(|e| e.to_string())?;- let mut agent = Agent { reader: BufReader::new(stream), writer };- agent.call("hello", &json!({}))?;- Ok(agent)+ // Mercury's environment for the core: settings, plugin info and the voice keys it was given.+ let env: serde_json::Map<String, Value> = std::env::vars()+ .filter(|(k, _)| k.starts_with("MERCURY_") || k.ends_with("_API_KEY"))+ .map(|(k, v)| (k, Value::String(v)))+ .collect();+ let mut w = stream.try_clone().map_err(|e| e.to_string())?;+ writeln!(w, "{}", json!({ "env": env })).map_err(|e| format!("Optimus.app went away: {e}"))?;+ Ok(stream)}fn ensure_bundle(app: &Path, dir: &Path) -> Result<(), String> {diff --git a/plugins/optimus/companion/src/main.rs b/plugins/optimus/companion/src/main.rsindex aa11d7ef..f095c967 100644--- a/plugins/optimus/companion/src/main.rs+++ b/plugins/optimus/companion/src/main.rs@@ -1,73 +1,159 @@-//! mercury-optimus: full computer control for Mercury.+//! mercury-optimus: full computer control for Mercury, by chat or out loud.//!//! Mercury starts this program and talks to it over stdio, one JSON-RPC 2.0-//! message per line (MCP: initialize, tools/list, tools/call, ping). Tools-//! return text plus a screenshot as an MCP image, which Mercury (plugin API-//! 1.2) hands to the model as an image.+//! message per line: MCP (initialize, tools/list, tools/call, ping) plus the+//! channel extension for a "desktop" channel (plugin API 1.2), which is how+//! listening mode reaches Mercury (mercury/call/*, as WhatsApp calls do).//!-//! On macOS the work happens in Optimus.app (see mac.rs) so the OS-//! permissions belong to Optimus; elsewhere it happens here.+//! The work happens in the core (core.rs): inside Optimus.app on macOS, so+//! the OS permissions belong to Optimus, and on a thread of this process+//! elsewhere. This file only relays: tool calls to the core, the core's+//! requests to Mercury, and Mercury's replies and notifications back.//!-//! Nothing runs until the owner turns on "Let Optimus control this-//! computer" in the plugin's setup. Steps that commit something go through+//! Nothing runs until the owner turns on "Let Optimus control this computer"+//! in the plugin's setup. Steps that commit something go through//! act_consequential, which Mercury asks the owner to approve.//!//! stdout is the protocol channel: logs go to stderr only.+mod audio;+mod core;+mod hotkey;+mod links;#[cfg(target_os = "macos")]mod mac;mod ops;+mod voice;+pub use crate::core::log;++use std::collections::HashMap;use std::io::{BufRead, Write};-use std::sync::{Arc, Mutex};+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::{Arc, Mutex, mpsc};+use std::time::Duration;use serde_json::{Value, json};-/// Where operations run: Optimus.app on macOS, this process elsewhere.-struct Backend {- #[cfg(target_os = "macos")]- agent: Option<mac::Agent>,- #[cfg(not(target_os = "macos"))]- ops: ops::Ops,+type CoreSend = Box<dyn Fn(Value) -> Result<(), String> + Send>;++struct Shell {+ stdout: Mutex<std::io::Stdout>,+ core: Mutex<Option<CoreSend>>,+ waiting: Mutex<HashMap<u64, mpsc::Sender<Result<Value, String>>>>,+ next_op: AtomicU64,}-impl Backend {- fn new() -> Self {- Backend {- #[cfg(target_os = "macos")]- agent: None,- #[cfg(not(target_os = "macos"))]- ops: ops::Ops::new(),+impl Shell {+ fn to_mercury(&self, v: &Value) {+ let mut o = self.stdout.lock().unwrap_or_else(|e| e.into_inner());+ let _ = writeln!(o, "{v}");+ let _ = o.flush();+ }++ /// A message from the core.+ fn from_core(&self, v: Value) {+ if let Some(r) = v.get("opResult") {+ let id = r["id"].as_u64().unwrap_or(0);+ let result = match (r.get("ok"), r.get("err")) {+ (Some(ok), _) => Ok(ok.clone()),+ (_, Some(e)) => Err(e.as_str().unwrap_or("failed").to_string()),+ _ => Err("bad reply from Optimus".into()),+ };+ if let Some(tx) = self.waiting.lock().unwrap().remove(&id) {+ let _ = tx.send(result);+ }+ } else if let Some(m) = v.get("mercury") {+ self.to_mercury(m);}}- fn run(&mut self, op: &str, args: &Value) -> Result<Value, String> {+ fn core_gone(&self) {+ *self.core.lock().unwrap() = None;+ for (_, tx) in self.waiting.lock().unwrap().drain() {+ let _ = tx.send(Err("Optimus restarted; try again".into()));+ }+ }++ /// Start the core if it isn't running (Optimus.app on macOS, a thread elsewhere).+ fn ensure_core(self: &Arc<Self>) -> Result<(), String> {+ let mut core = self.core.lock().unwrap();+ if core.is_some() {+ return Ok(());+ }#[cfg(target_os = "macos")]{- if self.agent.is_none() {- self.agent = Some(mac::start_agent()?);- }- let r = self.agent.as_mut().unwrap().call(op, args);- if r.as_ref().err().is_some_and(|e| e.contains("went away")) {- // Optimus.app quit (e.g. macOS restarted it after a permission change): once more.- self.agent = Some(mac::start_agent()?);- return self.agent.as_mut().unwrap().call(op, args);- }- r+ let stream = mac::start_agent()?;+ let reader = std::io::BufReader::new(stream.try_clone().map_err(|e| e.to_string())?);+ let me = self.clone();+ std::thread::spawn(move || {+ for line in reader.lines() {+ let Ok(line) = line else { break };+ if let Ok(v) = serde_json::from_str::<Value>(&line) {+ me.from_core(v);+ }+ }+ me.core_gone();+ });+ let writer = Mutex::new(stream);+ *core = Some(Box::new(move |v: Value| {+ let mut w = writer.lock().unwrap_or_else(|e| e.into_inner());+ writeln!(w, "{v}").map_err(|e| format!("Optimus.app went away: {e}"))+ }));}#[cfg(not(target_os = "macos"))]{- self.ops.run(op, args)+ let (tx, rx) = mpsc::channel::<Value>();+ let me = self.clone();+ std::thread::Builder::new()+ .name("optimus-core".into())+ .spawn(move || {+ let me2 = me.clone();+ core::run(rx, move |v| me2.from_core(v));+ me.core_gone();+ })+ .map_err(|e| e.to_string())?;+ *core = Some(Box::new(move |v: Value| tx.send(v).map_err(|_| "Optimus stopped".to_string())));}+ Ok(())+ }++ fn send_core(&self, v: Value) -> Result<(), String> {+ match self.core.lock().unwrap().as_ref() {+ Some(send) => send(v),+ None => Err("Optimus isn't running".into()),+ }+ }++ /// Run one operation in the core and wait for its result.+ fn op(self: &Arc<Self>, name: &str, args: &Value, timeout: Duration) -> Result<Value, String> {+ for attempt in 0..2 {+ self.ensure_core()?;+ let id = self.next_op.fetch_add(1, Ordering::Relaxed);+ let (tx, rx) = mpsc::channel();+ self.waiting.lock().unwrap().insert(id, tx);+ if let Err(e) = self.send_core(json!({ "op": { "id": id, "name": name, "args": args } })) {+ self.waiting.lock().unwrap().remove(&id);+ self.core_gone();+ if attempt == 0 {+ continue; // Optimus.app quit (e.g. after a permission change): start it again.+ }+ return Err(e);+ }+ return match rx.recv_timeout(timeout) {+ Ok(r) => r,+ Err(_) => {+ self.waiting.lock().unwrap().remove(&id);+ Err(format!("{name} took too long"))+ }+ };+ }+ Err("Optimus isn't running".into())}}fn allowed() -> bool {- std::env::var("MERCURY_PLUGIN_SETTINGS")- .ok()- .and_then(|s| serde_json::from_str::<Value>(&s).ok())- .and_then(|v| v.get("allowControl").and_then(Value::as_bool))- .unwrap_or(false)+ core::settings().get("allowControl").and_then(Value::as_bool).unwrap_or(false)}const NOT_ALLOWED: &str = "Optimus is off: the owner hasn't allowed it to control this computer yet. \@@ -108,13 +194,14 @@ fn action_schema() -> Value {})}-const TOOL_DESCRIPTIONS: [(&str, &str); 6] = [+const TOOL_DESCRIPTIONS: [(&str, &str); 7] = [("look", "See the screen: a screenshot of the display the mouse is on (or `display` N), with the active window. Use `zoom` [x0,y0,x1,y1] for a closer look at part of the last screenshot (coordinates stay in the full screenshot)."),("act", "Use the mouse and keyboard like a person: click, type, press keys, scroll, drag. Returns a fresh screenshot. Only for ordinary, reversible steps. Anything that submits, sends, posts, pays, buys, deletes, installs or changes settings must go through act_consequential instead. Never type passwords, card numbers or 2FA codes: ask the owner to do that part."),("act_consequential", "Same as act, for the step that commits something: submit a form, send a message or email, post, pay or buy, delete, install, change a setting. The owner approves it first, so say what it will do."),("open", "Open an app by name (\"Safari\", \"Blender\", \"Notepad\"), a URL, or a file/folder path. Faster and more reliable than clicking through menus."),("windows", "List open windows (app and title), front first."),("permissions", "Check what the OS lets Optimus do (macOS: Accessibility and Screen Recording). With request=true, shows the system prompts and opens the right Settings page."),+ ("listen", "Start a voice conversation on this computer right now (as if the owner pressed the talk key): Mercury listens through the microphone and answers out loud. Use when the owner asks to talk instead of type."),];fn tools() -> Value {@@ -139,16 +226,12 @@ fn tools() -> Value {)}-fn call(backend: &Mutex<Backend>, name: &str, args: &Value) -> Value {+fn call_tool(shell: &Arc<Shell>, name: &str, args: &Value) -> Value {if name != "permissions" && !allowed() {return json!({ "content": [{ "type": "text", "text": NOT_ALLOWED }], "isError": true });}- let op = match name {- "act_consequential" => "act",- other => other,- };- let result = backend.lock().unwrap_or_else(|e| e.into_inner()).run(op, args);- match result {+ let op = if name == "act_consequential" { "act" } else { name };+ match shell.op(op, args, Duration::from_secs(150)) {Ok(v) => {let mut content = vec![json!({ "type": "text", "text": v["text"].as_str().unwrap_or("Done.") })];if let (Some(data), Some(mime)) = (v["image"]["data"].as_str(), v["image"]["mimeType"].as_str()) {@@ -160,6 +243,26 @@ fn call(backend: &Mutex<Backend>, name: &str, args: &Value) -> Value {}}+/// `mercury/channel/*` requests: the desktop has no chat of its own.+fn channel_request(method: &str, params: &Value) -> Result<Value, String> {+ match method {+ "mercury/channel/sendFile" => {+ // A file Mercury made during a voice session: show it.+ let path = params["path"].as_str().unwrap_or("");+ let opened = if cfg!(target_os = "macos") {+ std::process::Command::new("open").args(["-R", path]).status()+ } else if cfg!(windows) {+ std::process::Command::new("explorer").arg(format!("/select,{path}")).status()+ } else {+ std::process::Command::new("xdg-open").arg(path).status()+ };+ opened.map(|_| json!({})).map_err(|e| e.to_string())+ }+ "mercury/channel/send" | "mercury/channel/typing" => Ok(json!({})),+ other => Err(format!("Optimus has no {other}")),+ }+}+fn main() {let args: Vec<String> = std::env::args().collect();if args.get(1).map(String::as_str) == Some("agent") {@@ -175,54 +278,68 @@ fn main() {}}- let out = Arc::new(Mutex::new(std::io::stdout()));- let send = {- let out = out.clone();- move |v: Value| {- let mut o = out.lock().unwrap_or_else(|e| e.into_inner());- let _ = writeln!(o, "{v}");- let _ = o.flush();- }- };- let backend = Arc::new(Mutex::new(Backend::new()));-- // With consent already given, get Optimus.app running (and its permission- // prompts showing, if any are missing) before the first request.- if allowed() {- let b = backend.clone();- std::thread::spawn(move || {- let report = b.lock().unwrap_or_else(|e| e.into_inner()).run("permissions", &json!({ "request": true }));- match report {- Ok(r) => eprintln!("optimus: {}", r["text"].as_str().unwrap_or("").replace('\n', " | ")),- Err(e) => eprintln!("optimus: {e}"),- }+ let shell = Arc::new(Shell {+ stdout: Mutex::new(std::io::stdout()),+ core: Mutex::new(None),+ waiting: Mutex::new(HashMap::new()),+ next_op: AtomicU64::new(1),+ });+ let reply = |shell: &Shell, id: &Value, r: Result<Value, String>| {+ shell.to_mercury(&match r {+ Ok(v) => json!({ "jsonrpc": "2.0", "id": id, "result": v }),+ Err(e) => json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32000, "message": e } }),});- }+ };for line in std::io::stdin().lock().lines() {let Ok(line) = line else { break };let Ok(msg) = serde_json::from_str::<Value>(&line) else { continue };- let Some(id) = msg.get("id").cloned() else { continue }; // notifications: nothing to do- let method = msg["method"].as_str().unwrap_or("").to_string();+ let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string();+ let id = msg.get("id").cloned();++ // Replies to the core's requests, and Mercury's notifications for it.+ if method.is_empty() || id.is_none() {+ if method == "notifications/initialized" {+ if allowed() {+ // Start now: the talk key, and macOS permission prompts if any are missing.+ let sh = shell.clone();+ std::thread::spawn(move || match sh.op("permissions", &json!({ "request": true }), Duration::from_secs(60)) {+ Ok(r) => log(r["text"].as_str().unwrap_or("").replace('\n', " | ")),+ Err(e) => log(e),+ });+ } else {+ shell.to_mercury(&json!({ "jsonrpc": "2.0", "method": "mercury/channel/status", "params": {+ "state": "connected", "account": "this computer", "detail": "Off until you allow it in /plugins optimus."+ }}));+ }+ continue;+ }+ let _ = shell.send_core(json!({ "mercury": msg }));+ continue;+ }+ let id = id.unwrap();let params = msg.get("params").cloned().unwrap_or(json!({}));match method.as_str() {- "initialize" => send(json!({ "jsonrpc": "2.0", "id": id, "result": {+ "initialize" => reply(&shell, &id, Ok(json!({"protocolVersion": params["protocolVersion"].as_str().unwrap_or("2025-06-18"),"capabilities": { "tools": {} },"serverInfo": { "name": "mercury-optimus", "version": env!("CARGO_PKG_VERSION") }- }})),- "ping" => send(json!({ "jsonrpc": "2.0", "id": id, "result": {} })),- "tools/list" => send(json!({ "jsonrpc": "2.0", "id": id, "result": { "tools": tools() } })),+ }))),+ "ping" => reply(&shell, &id, Ok(json!({}))),+ "tools/list" => reply(&shell, &id, Ok(json!({ "tools": tools() }))),"tools/call" => {- // Off the reader thread, so pings are answered during long actions.- let (backend, send) = (backend.clone(), send.clone());+ // Off the reader thread, so pings and replies keep flowing during long actions.+ let sh = shell.clone();std::thread::spawn(move || {let name = params["name"].as_str().unwrap_or("");- let result = call(&backend, name, ¶ms["arguments"]);- send(json!({ "jsonrpc": "2.0", "id": id, "result": result }));+ let result = call_tool(&sh, name, ¶ms["arguments"]);+ reply(&sh, &id, Ok(result));});}- _ => send(json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32601, "message": format!("unknown method {method}") } })),+ m if m.starts_with("mercury/channel/") => reply(&shell, &id, channel_request(m, ¶ms)),+ _ => reply(&shell, &id, Err(format!("unknown method {method}"))),}}+ let _ = shell.send_core(json!({ "quit": true }));+ std::thread::sleep(Duration::from_millis(300));}diff --git a/plugins/optimus/companion/src/voice.rs b/plugins/optimus/companion/src/voice.rsnew file mode 100644index 00000000..037fc44c--- /dev/null+++ b/plugins/optimus/companion/src/voice.rs@@ -0,0 +1,502 @@+//! Listening mode: talk to Mercury out loud at the computer.+//!+//! Press the talk key (or ask for it in chat): Optimus opens the mic and+//! speaker and a voice link (OpenAI Realtime by default, or any engine the+//! WhatsApp plugin supports). The voice chats; for anything real (the screen,+//! the web, memory, files, doing things) it asks Mercury, whose turn runs+//! with the Optimus tools in reach, and speaks the answer. Approvals are asked+//! out loud. Press the key again, or say goodbye, to stop.+//!+//! This is the WhatsApp call bridge with the computer's own audio in place of+//! a call: Mercury handles both through the same mercury/call/* messages.++use std::collections::{HashMap, VecDeque};+use std::sync::Arc;+use std::time::{Duration, Instant};++use serde_json::{Value, json};+use tokio::sync::mpsc;++use crate::audio::{self, Audio, FRAME};+use crate::core::{Shared, log, settings, voice_enabled};+use crate::links::{self, Brain, Link, LinkCmd, LinkConfig, LinkEvent};++// Long enough for a turn that waits on the owner's approval.+const ASK_TIMEOUT: Duration = Duration::from_secs(300);++pub enum Ctl {+ /// The talk key: interrupt Mercury if it's speaking, otherwise stop listening.+ Press,+ Stop,+}++pub struct SessionCtl {+ tx: mpsc::UnboundedSender<Ctl>,+}++impl SessionCtl {+ pub fn stop(&self) {+ let _ = self.tx.send(Ctl::Stop);+ }+}++/// The talk key was pressed (or the `listen` tool called).+pub async fn press(sh: Arc<Shared>, from_tool: bool) -> Result<String, String> {+ {+ let live = sh.session.lock().unwrap();+ if let Some(s) = live.as_ref() {+ if from_tool {+ return Ok("Already listening: just talk.".into());+ }+ let _ = s.tx.send(Ctl::Press);+ return Ok(String::new());+ }+ }+ if !voice_enabled() {+ return Err("listening mode is off: choose Listening or Both in /plugins optimus".into());+ }+ let (tx, rx) = mpsc::unbounded_channel::<Ctl>();+ {+ // Claim the slot first, so a double press can't start two sessions.+ let mut live = sh.session.lock().unwrap();+ if live.is_some() {+ return Ok(String::new());+ }+ *live = Some(SessionCtl { tx });+ }+ let call_id = format!("desk-{}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0));+ let problem = links::not_ready(&settings());+ let decision = sh+ .out+ .request(+ "mercury/call/incoming",+ json!({ "callId": call_id, "from": "local", "voiceReady": problem.is_none(), "voiceProblem": problem }),+ Duration::from_secs(8),+ )+ .await+ .unwrap_or_else(|e| json!({ "accept": false, "reason": e }));+ if decision.get("accept").and_then(Value::as_bool) != Some(true) {+ *sh.session.lock().unwrap() = None;+ let why = problem.unwrap_or_else(|| decision.get("reason").and_then(Value::as_str).unwrap_or("Mercury declined").to_string());+ return Err(why);+ }+ let instructions = decision.get("instructions").and_then(Value::as_str).unwrap_or("").to_string();+ let audio = match audio::open() {+ Ok(a) => a,+ Err(e) => {+ *sh.session.lock().unwrap() = None;+ let reason = format!("{e}{}", if cfg!(target_os = "macos") { " (allow Optimus under Privacy & Security → Microphone)" } else { "" });+ sh.out.notify("mercury/call/ended", json!({ "callId": call_id, "direction": "incoming", "outcome": format!("failed: {reason}"), "durationSec": 0, "transcript": [] }));+ return Err(reason);+ }+ };+ log(format!("listening ({})", audio.description));+ let sh2 = sh.clone();+ tokio::spawn(async move {+ run_session(sh2.clone(), audio, rx, call_id, instructions).await;+ *sh2.session.lock().unwrap() = None;+ });+ let key = sh.hotkey_label.lock().unwrap().clone();+ Ok(if key.is_empty() {+ "Listening now: talk to Mercury out loud. Say goodbye to stop.".into()+ } else {+ format!("Listening now: talk to Mercury out loud. Press {key} or say goodbye to stop.")+ })+}++fn instructions_for(instructions: &str) -> String {+ let base = "You are Mercury, the user's AI assistant, talking out loud with them at their own computer. \+ Speak naturally and briefly: one or two sentences at a time, no lists, no markdown, no URLs read aloud. \+ You can't see the screen or act yourself, and you don't know today's news or anything current: for anything on their screen \+ ('what's this?', 'what am I looking at?'), for doing things on the computer (open apps, click, type, fill a form, search), \+ for news, facts that may have changed, or the user's own things (memory, files, calendar), call ask_mercury with a clear, complete request. \+ Mercury can see and use the screen, search the web and use its tools. \+ Before a request that will take a while (web searches, several steps on the screen), say in a few words that you're on it. \+ Then say its answer in your own words. If you get a status update while Mercury is still working, give one short, natural sentence about it. \+ Some actions need the user's approval. When you get an approval request, ask the user plainly whether to go ahead, wait for their answer, \+ then call answer_approval. Never answer an approval yourself: only the user's own words count. \+ Links, lists and details go to the user's Mercury chat automatically; just say you've sent them. \+ When the user says goodbye or is done, say a short goodbye and call end_conversation.";+ if instructions.is_empty() { base.to_string() } else { format!("{base}\n\n{instructions}") }+}++fn tools() -> Value {+ json!([+ {+ "type": "function",+ "name": "ask_mercury",+ "description": "Ask Mercury (it sees and uses the screen, and has memory, tools and files) a question or to do something. Returns the answer to speak back.",+ "parameters": { "type": "object", "properties": { "question": { "type": "string" } }, "required": ["question"] },+ },+ { "type": "function", "name": "end_conversation", "description": "Stop listening, after saying goodbye.", "parameters": { "type": "object", "properties": {} } },+ {+ "type": "function",+ "name": "answer_approval",+ "description": "Report the user's answer to the approval you just asked them about. Only call it after they answered out loud.",+ "parameters": { "type": "object", "properties": { "approved": { "type": "boolean", "description": "true only if the user clearly said yes" } }, "required": ["approved"] },+ },+ ])+}++async fn run_session(sh: Arc<Shared>, audio: Audio, ctl: mpsc::UnboundedReceiver<Ctl>, call_id: String, instructions: String) {+ let started = Instant::now();+ let mut transcript: Vec<Value> = Vec::new();+ audio.out.chime(true);+ let outcome = match bridge(&sh, audio, ctl, &call_id, &instructions, &mut transcript).await {+ Ok(()) => "completed".to_string(),+ Err(e) => {+ log(format!("voice session ended: {e}"));+ format!("failed: {e}")+ }+ };+ sh.call_approvals.lock().unwrap().remove(&call_id);+ sh.call_context.lock().unwrap().remove(&call_id);+ sh.call_activity.lock().unwrap().remove(&call_id);+ sh.out.notify("mercury/call/ended", json!({+ "callId": call_id,+ "direction": "incoming",+ "outcome": outcome,+ "durationSec": started.elapsed().as_secs(),+ "transcript": transcript,+ }));+}++fn spoken_status(n: u32, doing: &str) -> String {+ if n == 1 { format!("This one takes a few seconds, I'm {doing}.") } else { format!("Still {doing}, almost there.") }+}++async fn bridge(+ sh: &Arc<Shared>,+ mut audio: Audio,+ mut ctl: mpsc::UnboundedReceiver<Ctl>,+ call_id: &str,+ instructions: &str,+ transcript: &mut Vec<Value>,+) -> Result<(), String> {+ let cfg = LinkConfig { instructions: instructions_for(instructions), tools: tools(), settings: settings() };+ let mut link = links::open(cfg).await?;+ let brain = link.brain;+ let barge_in = settings().get("bargeIn").and_then(Value::as_bool).unwrap_or(false);++ match brain {+ Brain::Voice => link.send(LinkCmd::Instruct(+ "[Context, not said by the user] The user just pressed their talk key to talk to you at their computer. Say a very short hello (a few words, like 'Hey, I'm listening') and wait for them.".into(),+ )),+ Brain::Mercury => link.send(LinkCmd::Say("I'm listening.".into())),+ }++ let out = audio.out.clone();+ let mut mic = std::mem::replace(&mut audio.mic, mpsc::unbounded_channel().1);+ let pending: Arc<std::sync::Mutex<HashMap<String, (Instant, Instant, u32)>>> = Arc::new(std::sync::Mutex::new(HashMap::new()));+ let mut responding = false;+ let (answer_tx, mut answer_rx) = mpsc::unbounded_channel::<(String, String)>();+ let mut ready_answers: VecDeque<(String, String)> = VecDeque::new();+ let mut awaiting: Option<(String, Instant)> = None;+ let mut user_said: Vec<(Instant, String)> = Vec::new();+ let mut verifying: Option<(String, String, Instant, Instant)> = None;+ let mut status_tick = tokio::time::interval(Duration::from_secs(1));+ status_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);+ let mut ask_seq = 0u32;+ let silence = vec![0i16; FRAME];++ let max_minutes = settings().get("maxSessionMinutes").and_then(Value::as_f64).unwrap_or(30.0).clamp(1.0, 240.0);+ let deadline = tokio::time::sleep(Duration::from_secs_f64(max_minutes * 60.0));+ tokio::pin!(deadline);++ let ask = |q: String, id: String, pending: &Arc<std::sync::Mutex<HashMap<String, (Instant, Instant, u32)>>>| {+ let sh2 = sh.clone();+ let tx2 = answer_tx.clone();+ let call_id2 = call_id.to_string();+ let now = Instant::now();+ pending.lock().unwrap().insert(id.clone(), (now, now, 0));+ sh.call_activity.lock().unwrap().remove(call_id);+ let pending2 = pending.clone();+ tokio::spawn(async move {+ let answer = sh2+ .out+ .request("mercury/call/ask", json!({ "callId": call_id2, "question": q }), ASK_TIMEOUT)+ .await+ .ok()+ .and_then(|v| v.get("answer").and_then(Value::as_str).map(str::to_string))+ .unwrap_or_else(|| "Mercury didn't answer in time. It will send the answer to the chat.".into());+ pending2.lock().unwrap().remove(&id);+ let _ = tx2.send((id, answer));+ });+ };++ let result = loop {+ tokio::select! {+ _ = &mut deadline => break Ok(()),+ c = ctl.recv() => match c {+ None | Some(Ctl::Stop) => break Ok(()),+ Some(Ctl::Press) => {+ if responding || out.recently_audible(300) {+ // Mercury is talking: the key interrupts.+ out.clear();+ link.send(LinkCmd::Cancel);+ responding = false;+ } else {+ break Ok(());+ }+ }+ },+ frame = mic.recv() => {+ let Some(frame) = frame else { break Err("the microphone stopped".to_string()) };+ // With speakers, the mic would hear Mercury: send silence while it talks.+ let muted = !barge_in && out.recently_audible(350);+ link.send(LinkCmd::Audio(if muted { silence.clone() } else { frame }));+ }+ Some(a) = answer_rx.recv() => {+ if a.1.starts_with("(superseded") { continue; }+ ready_answers.push_back(a);+ if !responding { deliver(&link, brain, &mut ready_answers, &mut responding); }+ }+ _ = status_tick.tick() => {+ if let Some((fc, _id, _asked, until)) = verifying.clone() {+ if Instant::now() >= until {+ verifying = None;+ ready_answers.push_back((fc, "Not approved: the user hasn't clearly said yes in their own words. Ask them again.".to_string()));+ }+ }+ if !responding && !ready_answers.is_empty() {+ deliver(&link, brain, &mut ready_answers, &mut responding);+ continue;+ }+ if responding || out.busy() { continue; }+ if awaiting.is_none() {+ let next = sh.call_approvals.lock().unwrap().get_mut(call_id).and_then(|l| if l.is_empty() { None } else { Some(l.remove(0)) });+ if let Some((id, prompt)) = next {+ awaiting = Some((id, Instant::now()));+ match brain {+ Brain::Voice => link.send(LinkCmd::Instruct(format!("[Approval needed, not said by the user] Mercury wants to: {prompt}. Ask the user plainly, in one or two sentences, whether to go ahead. Then wait for their answer and call answer_approval."))),+ Brain::Mercury => link.send(LinkCmd::Say(format!("I need your go-ahead to {prompt}. Should I do it? Say yes or no."))),+ }+ responding = true;+ continue;+ }+ }+ let context = sh.call_context.lock().unwrap().remove(call_id);+ if let Some(mut notes) = context.filter(|n| !n.is_empty()) {+ for n in notes.iter_mut() {+ if let Some(rest) = n.strip_prefix("RESOLVED:") {+ let (id, text) = rest.split_once(':').unwrap_or(("", rest));+ if awaiting.as_ref().map(|(a, _)| a == id).unwrap_or(false) { awaiting = None; }+ *n = text.to_string();+ }+ }+ match brain {+ Brain::Voice => link.send(LinkCmd::Instruct(format!("[Status update, not said by the user] {} Mention it in one short sentence.", notes.join(" ")))),+ Brain::Mercury => link.send(LinkCmd::Say(notes.join(" "))),+ }+ responding = true;+ continue;+ }+ let due = {+ let mut p = pending.lock().unwrap();+ let now = Instant::now();+ p.iter_mut().find_map(|(_, (asked, last, n))| {+ let wait = if *n == 0 { Duration::from_secs(8) } else { Duration::from_secs(14) };+ if *n < 8 && now.duration_since(if *n == 0 { *asked } else { *last }) >= wait {+ *last = now;+ *n += 1;+ Some((*n, now.duration_since(*asked).as_secs()))+ } else { None }+ })+ };+ if let Some((n, secs)) = due {+ let doing = sh.call_activity.lock().unwrap().get(call_id).cloned().unwrap_or_else(|| "working on it".into());+ match brain {+ Brain::Voice => link.send(LinkCmd::Instruct(if n == 1 {+ format!("[Status update, not said by the user] Mercury is still {doing}. Tell the user in one short sentence that it's taking a few seconds.")+ } else {+ format!("[Status update, not said by the user] After {secs} seconds Mercury is still {doing}. Give one short, natural update (don't repeat yourself).")+ })),+ Brain::Mercury => link.send(LinkCmd::Say(spoken_status(n, &doing))),+ }+ responding = true;+ }+ }+ ev = link.events.recv() => {+ let Some(ev) = ev else { break Err("the voice connection ended".to_string()) };+ match ev {+ LinkEvent::Closed(reason) => break Err(reason),+ LinkEvent::ResponseStarted => responding = true,+ LinkEvent::ResponseDone => {+ responding = false;+ if !ready_answers.is_empty() { deliver(&link, brain, &mut ready_answers, &mut responding); }+ }+ LinkEvent::Audio(pcm) => out.play(&pcm),+ LinkEvent::SpeechStarted => {+ if barge_in || !out.recently_audible(350) {+ out.clear();+ link.send(LinkCmd::Cancel);+ }+ }+ LinkEvent::AssistantText(t) => {+ if !t.is_empty() { transcript.push(json!({ "role": "mercury", "text": t })); }+ }+ LinkEvent::UserText(t) => {+ if t.is_empty() { continue; }+ transcript.push(json!({ "role": "owner", "text": t.clone() }));+ user_said.push((Instant::now(), t.clone()));+ if user_said.len() > 20 { user_said.remove(0); }+ if let Some((fc, id, asked_at, _)) = verifying.clone() {+ if let Some(v) = spoken_verdict(&user_said, asked_at) {+ verifying = None;+ awaiting = None;+ let o = finalize_approval(sh, call_id, &id, v).await;+ ready_answers.push_back((fc, o));+ if !responding { deliver(&link, brain, &mut ready_answers, &mut responding); }+ }+ continue;+ }+ if brain == Brain::Mercury {+ if let Some((id, asked_at)) = awaiting.clone() {+ if let Some(v) = spoken_verdict(&user_said, asked_at) {+ awaiting = None;+ finalize_approval(sh, call_id, &id, v).await;+ link.send(LinkCmd::Say(if v { "Okay, going ahead.".into() } else { "Okay, I won't.".into() }));+ continue;+ }+ }+ if is_goodbye(&t) {+ link.send(LinkCmd::Say("Okay, bye for now!".into()));+ tokio::time::sleep(Duration::from_millis(2500)).await;+ break Ok(());+ }+ ask_seq += 1;+ transcript.push(json!({ "role": "ask_mercury", "text": t.clone() }));+ ask(t, format!("turn-{ask_seq}"), &pending);+ }+ }+ LinkEvent::ToolCall { id, name, args } => {+ if name == "end_conversation" || name == "end_call" {+ for _ in 0..50 {+ if !out.busy() { break; }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ break Ok(());+ }+ if name == "answer_approval" {+ let approved = args.get("approved").and_then(Value::as_bool).unwrap_or(false);+ match awaiting.clone() {+ None => ready_answers.push_back((id, "No approval is waiting right now.".to_string())),+ Some((aid, asked_at)) => match (approved, spoken_verdict(&user_said, asked_at)) {+ (false, _) | (true, Some(false)) => {+ awaiting = None;+ let o = finalize_approval(sh, call_id, &aid, false).await;+ ready_answers.push_back((id, o));+ }+ (true, Some(true)) => {+ awaiting = None;+ let o = finalize_approval(sh, call_id, &aid, true).await;+ ready_answers.push_back((id, o));+ }+ (true, None) => verifying = Some((id, aid, asked_at, Instant::now() + Duration::from_secs(3))),+ },+ }+ if !responding { deliver(&link, brain, &mut ready_answers, &mut responding); }+ continue;+ }+ if name == "ask_mercury" {+ let q = args.get("question").and_then(Value::as_str).unwrap_or("").to_string();+ transcript.push(json!({ "role": "ask_mercury", "text": q.clone() }));+ ask(q, id, &pending);+ }+ }+ }+ }+ }+ };++ out.clear();+ out.chime(false);+ audio.drain(Duration::from_secs(1)).await;+ result+}++fn is_goodbye(t: &str) -> bool {+ let t = format!(" {} ", t.to_lowercase().trim_matches(|c: char| !c.is_alphanumeric() && !c.is_whitespace()));+ let short = t.split_whitespace().count() <= 4;+ short && [" bye ", " goodbye ", " bye bye ", " that's all ", " thats all ", " stop listening ", " khuda hafiz ", " allah hafiz ", " alvida ", "अलविदा", "خدا حافظ", "اللہ حافظ"].iter().any(|w| t.contains(w))+}++async fn finalize_approval(sh: &Arc<Shared>, call_id: &str, approval_id: &str, yes: bool) -> String {+ match sh.out.request("mercury/call/approve", json!({ "callId": call_id, "approvalId": approval_id, "approved": yes }), Duration::from_secs(10)).await {+ Ok(v) if v.get("ok").and_then(Value::as_bool) == Some(true) => {+ if yes { "Approved. Mercury is carrying on; tell the user briefly.".into() } else { "Declined. Tell the user it won't be done.".into() }+ }+ Ok(v) => format!("That approval was already settled ({}).", v.get("reason").and_then(Value::as_str).unwrap_or("closed")),+ Err(e) => format!("Couldn't reach Mercury: {e}"),+ }+}++/// Did the user say yes (or no) out loud since the approval question?+/// Only their transcribed speech counts; the model's own reading doesn't.+pub fn spoken_verdict(said: &[(Instant, String)], since: Instant) -> Option<bool> {+ for (at, text) in said.iter().rev() {+ if *at < since { break; }+ let t = format!(" {} ", text.to_lowercase().replace(|c: char| !c.is_alphanumeric() && !c.is_whitespace() && (c as u32) < 128, " "));+ const NO: &[&str] = &[" no ", " nope ", " don't ", " dont ", " do not ", " cancel ", " stop ", " wait ", " nahi ", " nahin ", " mat ", "नहीं", "मत", "نہیں"];+ const YES: &[&str] = &[" yes ", " yeah ", " yep ", " yup ", " sure ", " ok ", " okay ", " go ahead ", " do it ", " approve", " confirm", " please do ", " haan ", " han ", " ha ji ", " ji ", " theek ", " thik ", " kar do ", " karo ", "हाँ", "हां", "ठीक", "कर दो", "ہاں", "جی", "ٹھیک"];+ if NO.iter().any(|w| t.contains(w)) { return Some(false); }+ if YES.iter().any(|w| t.contains(w)) { return Some(true); }+ }+ None+}++fn deliver(link: &Link, brain: Brain, ready: &mut VecDeque<(String, String)>, responding: &mut bool) {+ if let Some((id, answer)) = ready.pop_front() {+ match brain {+ Brain::Voice => link.send(LinkCmd::ToolResult { id, output: answer }),+ Brain::Mercury => {+ let spoken = if answer.starts_with("Approved.") { "Okay, going ahead.".to_string() }+ else if answer.starts_with("Declined.") { "Okay, I won't.".to_string() }+ else if answer.starts_with("Not approved:") { "Sorry, I didn't catch a yes. Should I go ahead?".to_string() }+ else { answer };+ link.send(LinkCmd::Say(spoken));+ }+ }+ *responding = true;+ }+}++/// Turn the voice provider's close reason into something the owner can act on.+pub fn explain_close(reason: &str) -> String {+ let r = reason.to_ascii_lowercase();+ if r.contains("insufficient_quota") || r.contains("credit_balance") || r.contains("billing") {+ "your OpenAI account is out of credit. Add credit at platform.openai.com → Settings → Billing, then try again".into()+ } else if r.contains("invalid_api_key") || r.contains("unauthorized") || r.contains("401") {+ "OpenAI rejected the API key. Check the OpenAI provider in Mercury's dashboard (Providers)".into()+ } else if r.contains("model_not_found") || r.contains("does not exist") || r.contains("access") {+ format!("this OpenAI account can't use the realtime voice model ({reason}). Try another voiceModel setting")+ } else if r.contains("rate_limit") {+ "OpenAI is rate-limiting this account right now. Try again in a minute".into()+ } else if reason.is_empty() {+ "the voice model closed the session".into()+ } else {+ format!("the voice model closed the session ({reason})")+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn only_the_users_own_yes_counts() {+ let asked = Instant::now();+ let after = asked + Duration::from_millis(10);+ assert_eq!(spoken_verdict(&[(after, "Yes, go ahead".into())], asked), Some(true));+ assert_eq!(spoken_verdict(&[(after, "No, don't".into())], asked), Some(false));+ assert_eq!(spoken_verdict(&[(after, "what?".into())], asked), None);+ assert_eq!(spoken_verdict(&[(asked - Duration::from_secs(5), "yes".into())], asked), None);+ }++ #[test]+ fn goodbyes() {+ assert!(is_goodbye("Okay, bye!"));+ assert!(is_goodbye("stop listening"));+ assert!(!is_goodbye("say bye to my brother when he calls tomorrow"));+ }+}diff --git a/plugins/optimus/mercury-plugin.template.json b/plugins/optimus/mercury-plugin.template.jsonindex f9e5caf3..60ff1caa 100644--- a/plugins/optimus/mercury-plugin.template.json+++ b/plugins/optimus/mercury-plugin.template.json@@ -3,7 +3,7 @@"id": "optimus","name": "Optimus","version": "0.1.0",- "description": "Mercury uses your computer like a person: sees the screen, moves the mouse, types, and opens apps on macOS, Windows and Linux. Asks before anything that submits, sends, pays or deletes.",+ "description": "Mercury uses your computer like a person: sees the screen, moves the mouse, types and opens apps, by chat or out loud with a talk key. macOS, Windows and Linux. Asks before anything that submits, sends, pays or deletes.","kind": "out-of-process","author": "Cosmic Stack","homepage": "https://github.com/cosmicstack-labs/mercury-agent/tree/main/plugins/optimus",@@ -59,15 +59,71 @@"description": "Check what the OS lets Optimus do (macOS: Accessibility and Screen Recording). With request=true, shows the system prompts and opens the right Settings page.","readOnly": true,"timeoutMs": 60000+ },+ {+ "name": "listen",+ "description": "Start a voice conversation on this computer right now (as if the owner pressed the talk key): Mercury listens through the microphone and answers out loud. Use when the owner asks to talk instead of type.",+ "readOnly": true,+ "timeoutMs": 30000}- ]+ ],+ "channel": {+ "type": "desktop"+ }},"permissions": {- "network": [],- "secrets": [],- "desktop": true+ "network": [+ "*.aliyuncs.com",+ "*.openai.azure.com",+ "api.cartesia.ai",+ "api.deepgram.com",+ "api.elevenlabs.io",+ "api.minimax.io",+ "api.openai.com",+ "api.sarvam.ai",+ "api.x.ai",+ "generativelanguage.googleapis.com",+ "streaming.assemblyai.com"+ ],+ "secrets": [+ "GEMINI_API_KEY",+ "ELEVENLABS_API_KEY",+ "AZURE_OPENAI_API_KEY",+ "DASHSCOPE_API_KEY",+ "DEEPGRAM_API_KEY",+ "ASSEMBLYAI_API_KEY",+ "SARVAM_API_KEY",+ "CARTESIA_API_KEY",+ "MINIMAX_API_KEY"+ ],+ "desktop": true,+ "providers": {+ "openai": {+ "unlocks": "Talking to Optimus",+ "when": {+ "voiceEngine": "openai",+ "mode": [+ "voice",+ "both"+ ]+ },+ "alternative": "Or pick another voice in /plugins optimus → 🎙 Voice, or use chat mode."+ },+ "grok": {+ "unlocks": "Talking to Optimus with Grok",+ "when": {+ "voiceEngine": "grok",+ "mode": [+ "voice",+ "both"+ ]+ },+ "alternative": "Or pick another voice in /plugins optimus → 🎙 Voice."+ }+ }},"settings": {+ "version": 1,"fields": {"allowControl": {"type": "boolean",@@ -76,6 +132,626 @@"default": false,"setup": true,"required": true+ },+ "mode": {+ "type": "enum",+ "options": [+ "both",+ "chat",+ "voice"+ ],+ "default": "both",+ "setup": true,+ "required": true,+ "label": "How do you want to talk to Optimus?",+ "description": "Chat: type to Mercury as usual. Listening: press a key, talk, and hear Mercury answer while it works on your screen.",+ "optionLabels": {+ "both": "⭐ Both: chat, plus a key to talk out loud (recommended)",+ "chat": "💬 Chat only: type to Mercury as usual",+ "voice": "🎙 Listening: press a key, talk, and hear Mercury answer"+ }+ },+ "hotkey": {+ "type": "string",+ "default": "ctrl+alt+m",+ "setup": true,+ "label": "Key to start and stop talking",+ "description": "Press it to start listening, press again to stop (or say goodbye). While Mercury is speaking, pressing it interrupts. Examples: ctrl+alt+m, ctrl+shift+space, f9. On a Mac, alt is Option and cmd is Command.",+ "when": {+ "mode": [+ "voice",+ "both"+ ]+ }+ },+ "bargeIn": {+ "type": "boolean",+ "default": false,+ "label": "I use headphones (let me interrupt by talking)",+ "description": "With speakers, Optimus mutes the mic while Mercury talks so it doesn't hear itself; press the key to interrupt. With headphones, turn this on to interrupt just by talking.",+ "group": "voice",+ "when": {+ "mode": [+ "voice",+ "both"+ ]+ }+ },+ "voiceEngine": {+ "type": "enum",+ "label": "Who listens and speaks?",+ "setup": true,+ "default": "openai",+ "description": "Who listens to you and speaks back. Change anytime in /plugins optimus.",+ "options": [+ "openai",+ "gemini",+ "grok",+ "elevenlabs",+ "azure",+ "qwen",+ "mercury"+ ],+ "optionLabels": {+ "openai": "⭐ OpenAI Realtime: recommended for the best results (uses your OpenAI key)",+ "gemini": "Google Gemini Live: cheapest, free tier, Hindi and Urdu",+ "grok": "xAI Grok Voice: uses your Grok provider",+ "elevenlabs": "ElevenLabs Realtime (experimental)",+ "azure": "Azure OpenAI Realtime",+ "qwen": "Alibaba Qwen-Omni Realtime",+ "mercury": "My own model: your Mercury model thinks; pick who listens and speaks"+ },+ "group": "voice",+ "setupWhenMissing": "provider:openai",+ "when": {+ "mode": [+ "voice",+ "both"+ ]+ }+ },+ "voiceModel": {+ "type": "string",+ "label": "OpenAI voice model",+ "default": "gpt-realtime-2.1",+ "description": "gpt-realtime-2.1, or gpt-realtime-2.1-mini (about 3x cheaper).",+ "when": {+ "voiceEngine": [+ "openai"+ ],+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "voice": {+ "type": "enum",+ "description": "Mercury's voice.",+ "options": [+ "marin",+ "cedar",+ "alloy",+ "ash",+ "ballad",+ "coral",+ "echo",+ "sage",+ "shimmer",+ "verse"+ ],+ "default": "marin",+ "label": "OpenAI voice",+ "when": {+ "voiceEngine": [+ "openai",+ "azure"+ ],+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "geminiKey": {+ "type": "secret",+ "secret": "GEMINI_API_KEY",+ "label": "Gemini API key",+ "setup": true,+ "required": true,+ "description": "From aistudio.google.com/apikey.",+ "when": {+ "voiceEngine": [+ "gemini"+ ],+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "geminiModel": {+ "type": "string",+ "label": "Gemini Live model",+ "default": "gemini-3.8-live",+ "when": {+ "voiceEngine": [+ "gemini"+ ],+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "geminiVoice": {+ "type": "string",+ "label": "Gemini voice",+ "default": "Kore",+ "description": "e.g. Kore, Puck, Charon, Aoede.",+ "when": {+ "voiceEngine": [+ "gemini"+ ],+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "grokModel": {+ "type": "string",+ "label": "Grok voice model",+ "default": "grok-voice-latest",+ "when": {+ "voiceEngine": [+ "grok"+ ],+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "grokVoice": {+ "type": "enum",+ "label": "Grok voice",+ "default": "eve",+ "options": [+ "eve",+ "ara",+ "leo",+ "rex",+ "sal",+ "atlas",+ "naksh",+ "celeste",+ "ursa",+ "sirius",+ "lumen"+ ],+ "when": {+ "voiceEngine": [+ "grok"+ ],+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "elevenlabsKey": {+ "type": "secret",+ "secret": "ELEVENLABS_API_KEY",+ "label": "ElevenLabs API key",+ "setup": true,+ "required": true,+ "when": [+ {+ "voiceEngine": [+ "elevenlabs"+ ],+ "mode": [+ "voice",+ "both"+ ]+ },+ {+ "voiceEngine": "mercury",+ "sttProvider": "elevenlabs",+ "mode": [+ "voice",+ "both"+ ]+ },+ {+ "voiceEngine": "mercury",+ "ttsProvider": "elevenlabs",+ "mode": [+ "voice",+ "both"+ ]+ }+ ],+ "group": "voice"+ },+ "elevenlabsModel": {+ "type": "enum",+ "label": "ElevenLabs Realtime model",+ "default": "eleven_realtime_v1_mini",+ "options": [+ "eleven_realtime_v1_mini",+ "eleven_realtime_v1_max"+ ],+ "when": {+ "voiceEngine": [+ "elevenlabs"+ ],+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "elevenlabsVoice": {+ "type": "string",+ "label": "ElevenLabs voice",+ "default": "brian",+ "when": {+ "voiceEngine": [+ "elevenlabs"+ ],+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "azureKey": {+ "type": "secret",+ "secret": "AZURE_OPENAI_API_KEY",+ "label": "Azure OpenAI API key",+ "setup": true,+ "required": true,+ "when": {+ "voiceEngine": [+ "azure"+ ],+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "azureEndpoint": {+ "type": "string",+ "label": "Azure endpoint",+ "setup": true,+ "required": true,+ "description": "e.g. myresource.openai.azure.com",+ "when": {+ "voiceEngine": [+ "azure"+ ],+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "azureDeployment": {+ "type": "string",+ "label": "Azure realtime deployment name",+ "setup": true,+ "default": "gpt-realtime-2.1",+ "when": {+ "voiceEngine": [+ "azure"+ ],+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "qwenKey": {+ "type": "secret",+ "secret": "DASHSCOPE_API_KEY",+ "label": "Alibaba Model Studio (DashScope) API key",+ "setup": true,+ "required": true,+ "when": {+ "voiceEngine": [+ "qwen"+ ],+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "qwenEndpoint": {+ "type": "string",+ "label": "Qwen endpoint host",+ "default": "dashscope-intl.aliyuncs.com",+ "description": "Your workspace host, e.g. {workspace}.ap-southeast-1.maas.aliyuncs.com",+ "when": {+ "voiceEngine": [+ "qwen"+ ],+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "qwenModel": {+ "type": "string",+ "label": "Qwen model",+ "default": "qwen3.8-omni-flash-realtime",+ "when": {+ "voiceEngine": [+ "qwen"+ ],+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "qwenVoice": {+ "type": "string",+ "label": "Qwen voice",+ "default": "Tina",+ "when": {+ "voiceEngine": [+ "qwen"+ ],+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "sttProvider": {+ "type": "enum",+ "label": "Who listens (speech to text)",+ "setup": true,+ "default": "deepgram",+ "options": [+ "deepgram",+ "assemblyai",+ "elevenlabs",+ "sarvam"+ ],+ "optionLabels": {+ "deepgram": "Deepgram Nova-3: fast, cheap, Hindi and Urdu",+ "assemblyai": "AssemblyAI Universal-3.6 Pro: Hindi and Urdu",+ "elevenlabs": "ElevenLabs Scribe v2",+ "sarvam": "Sarvam Saaras: Indian languages, incl. Urdu"+ },+ "when": {+ "voiceEngine": [+ "mercury"+ ],+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "sttLanguage": {+ "type": "enum",+ "label": "Language you'll speak",+ "default": "auto",+ "options": [+ "auto",+ "en",+ "hi",+ "ur"+ ],+ "optionLabels": {+ "auto": "Detect automatically",+ "en": "English",+ "hi": "Hindi",+ "ur": "Urdu"+ },+ "when": {+ "voiceEngine": [+ "mercury"+ ],+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "deepgramKey": {+ "type": "secret",+ "secret": "DEEPGRAM_API_KEY",+ "label": "Deepgram API key",+ "setup": true,+ "required": true,+ "when": [+ {+ "voiceEngine": "mercury",+ "sttProvider": "deepgram",+ "mode": [+ "voice",+ "both"+ ]+ },+ {+ "voiceEngine": "mercury",+ "ttsProvider": "deepgram",+ "mode": [+ "voice",+ "both"+ ]+ }+ ],+ "group": "voice"+ },+ "assemblyaiKey": {+ "type": "secret",+ "secret": "ASSEMBLYAI_API_KEY",+ "label": "AssemblyAI API key",+ "setup": true,+ "required": true,+ "when": {+ "voiceEngine": "mercury",+ "sttProvider": "assemblyai",+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "sarvamKey": {+ "type": "secret",+ "secret": "SARVAM_API_KEY",+ "label": "Sarvam API key",+ "setup": true,+ "required": true,+ "when": [+ {+ "voiceEngine": "mercury",+ "sttProvider": "sarvam",+ "mode": [+ "voice",+ "both"+ ]+ },+ {+ "voiceEngine": "mercury",+ "ttsProvider": "sarvam",+ "mode": [+ "voice",+ "both"+ ]+ }+ ],+ "group": "voice"+ },+ "ttsProvider": {+ "type": "enum",+ "label": "Who speaks (voice)",+ "setup": true,+ "default": "cartesia",+ "options": [+ "cartesia",+ "elevenlabs",+ "minimax",+ "sarvam",+ "deepgram"+ ],+ "optionLabels": {+ "cartesia": "Cartesia Sonic-3.6: very fast, Hindi, Hinglish and Urdu",+ "elevenlabs": "ElevenLabs Flash: 17k+ voices (Hindi, no Urdu)",+ "minimax": "MiniMax speech-2.8 (Hindi, no Urdu)",+ "sarvam": "Sarvam Bulbul: Indian voices (no Urdu)",+ "deepgram": "Deepgram Aura-2 (English and a few others)"+ },+ "when": {+ "voiceEngine": [+ "mercury"+ ],+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "cartesiaKey": {+ "type": "secret",+ "secret": "CARTESIA_API_KEY",+ "label": "Cartesia API key",+ "setup": true,+ "required": true,+ "when": {+ "voiceEngine": "mercury",+ "ttsProvider": "cartesia",+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "minimaxKey": {+ "type": "secret",+ "secret": "MINIMAX_API_KEY",+ "label": "MiniMax API key",+ "setup": true,+ "required": true,+ "when": {+ "voiceEngine": "mercury",+ "ttsProvider": "minimax",+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "ttsVoice": {+ "type": "string",+ "label": "Voice ID",+ "description": "Leave empty for the provider's default voice.",+ "default": "",+ "when": {+ "voiceEngine": [+ "mercury"+ ],+ "mode": [+ "voice",+ "both"+ ]+ },+ "group": "voice"+ },+ "maxSessionMinutes": {+ "type": "number",+ "default": 30,+ "label": "Longest listening session (minutes)",+ "description": "A session ends by itself after this long.",+ "group": "voice",+ "when": {+ "mode": [+ "voice",+ "both"+ ]+ }+ }+ },+ "groups": {+ "voice": {+ "label": "🎙 Voice",+ "description": "Who listens and speaks when you talk to Optimus. It uses the same voice keys as Mercury and the WhatsApp plugin, so a key added anywhere works here. OpenAI is recommended for the best results; every other option works too.",+ "readyUnless": [+ "provider:openai",+ "provider:grok"+ ]}}}