Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(plugins): plugin API 1.2 (tool images, desktop permission) and Optimus groundwork

Salman Qureshid5b927789eb4
diff --git a/.github/workflows/plugin-optimus.yml b/.github/workflows/plugin-optimus.yml
new file mode 100644
index 00000000..66813b92
--- /dev/null
+++ b/.github/workflows/plugin-optimus.yml
@@ -0,0 +1,87 @@
+name: plugin-optimus
+
+# Builds the Optimus plugin's companion for each platform and uploads the
+# packaged plugins as workflow artifacts. Nothing is released or published.
+on:
+ push:
+ paths:
+ - 'plugins/optimus/**'
+ - '.github/workflows/plugin-optimus.yml'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - { os: ubuntu-24.04, target: x86_64-unknown-linux-gnu, platform: linux-x64 }
+ - { os: ubuntu-24.04-arm, target: aarch64-unknown-linux-gnu, platform: linux-arm64 }
+ - { os: macos-14, target: aarch64-apple-darwin, platform: darwin-arm64 }
+ - { os: macos-14, target: x86_64-apple-darwin, platform: darwin-x64 }
+ - { os: windows-latest, target: x86_64-pc-windows-msvc, platform: win32-x64 }
+ runs-on: ${{ matrix.os }}
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@stable
+ with:
+ targets: ${{ matrix.target }}
+ - uses: actions/cache@v4
+ with:
+ path: |
+ ~/.cargo/registry
+ ~/.cargo/git
+ plugins/optimus/companion/target
+ 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
+ - name: Build
+ working-directory: plugins/optimus/companion
+ run: cargo build --release --locked --target ${{ matrix.target }} || cargo build --release --target ${{ matrix.target }}
+ - name: Unit tests
+ if: matrix.platform == 'linux-x64'
+ working-directory: plugins/optimus/companion
+ run: cargo test --release --target ${{ matrix.target }}
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ - name: Package
+ run: |
+ ext=""; [ "${{ matrix.platform }}" = "win32-x64" ] && ext=".exe"
+ node plugins/optimus/package.mjs "plugins/optimus/companion/target/${{ matrix.target }}/release/mercury-optimus$ext" ${{ matrix.platform }} dist
+ ls -la dist
+ - uses: actions/upload-artifact@v4
+ with:
+ name: mercury-plugin-optimus-${{ matrix.platform }}
+ path: dist/*
+ if-no-files-found: error
+ retention-days: 30
+
+ conformance:
+ # Install the Linux package into Mercury from this commit and run the
+ # plugin conformance kit (handshake, start, stop, restart).
+ needs: build
+ runs-on: ubuntu-24.04
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ cache: npm
+ - run: npm ci
+ - run: npm run build
+ - uses: actions/download-artifact@v4
+ with:
+ name: mercury-plugin-optimus-linux-x64
+ path: dist-plugin
+ - name: Validate
+ run: |
+ mkdir pkg && tar -xzf dist-plugin/mercury-plugin-linux-x64.tgz -C pkg
+ MERCURY_HOME="$RUNNER_TEMP/mh" MERCURY_PLUGIN_CATALOG_URL=off node dist/index.js plugins validate pkg
diff --git a/plugins/optimus/companion/Cargo.toml b/plugins/optimus/companion/Cargo.toml
new file mode 100644
index 00000000..44171645
--- /dev/null
+++ b/plugins/optimus/companion/Cargo.toml
@@ -0,0 +1,25 @@
+[package]
+name = "mercury-optimus"
+version = "0.1.0"
+edition = "2024"
+rust-version = "1.94"
+description = "Optimus: full computer control for Mercury (screen, mouse, keyboard, apps)"
+license = "MIT"
+publish = false
+
+[dependencies]
+xcap = "0.9"
+enigo = "0.6"
+image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
+base64 = "0.22"
+serde_json = "1"
+
+[target.'cfg(windows)'.dependencies]
+windows-sys = { version = "0.61", features = ["Win32_UI_HiDpi", "Win32_Foundation", "Win32_UI_WindowsAndMessaging"] }
+
+[profile.release]
+opt-level = 3
+lto = "fat"
+codegen-units = 1
+panic = "abort"
+strip = true
diff --git a/plugins/optimus/companion/src/mac.rs b/plugins/optimus/companion/src/mac.rs
new file mode 100644
index 00000000..060469d9
--- /dev/null
+++ b/plugins/optimus/companion/src/mac.rs
@@ -0,0 +1,348 @@
+//! macOS: run the screen and input work inside Optimus.app.
+//!
+//! macOS charges privacy permissions (Accessibility, Screen Recording) to the
+//! app that launched a process. Spawned by Mercury from a terminal, the grant
+//! would go to Terminal and cover every script it runs. So the plugin process
+//! builds `Optimus.app` from its own binary, signs it with a certificate made
+//! on this Mac (no Apple account involved), and launches it through
+//! LaunchServices, where it is its own app. The two talk over a Unix socket,
+//! one JSON object per line.
+//!
+//! The certificate stays the same across updates, so macOS keeps the
+//! permissions: a code signature's identity here is "this bundle id, signed by
+//! this certificate", not the binary's hash.
+
+use std::fs;
+use std::io::{BufRead, BufReader, Write};
+use std::os::unix::fs::PermissionsExt;
+use std::os::unix::net::{UnixListener, UnixStream};
+use std::path::{Path, PathBuf};
+use std::process::Command;
+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)";
+const P12_PASSWORD: &str = "mercury-optimus";
+const PANE_ACCESSIBILITY: &str = "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility";
+const PANE_SCREEN: &str = "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture";
+
+#[link(name = "ApplicationServices", kind = "framework")]
+unsafe extern "C" {
+ fn AXIsProcessTrusted() -> bool;
+}
+
+#[link(name = "CoreGraphics", kind = "framework")]
+unsafe extern "C" {
+ fn CGPreflightScreenCaptureAccess() -> bool;
+ fn CGRequestScreenCaptureAccess() -> bool;
+}
+
+// ── Inside Optimus.app ─────────────────────────────────────────────────
+
+pub fn permission_report(request: bool) -> Value {
+ let (mut ax, mut screen) = unsafe { (AXIsProcessTrusted(), CGPreflightScreenCaptureAccess()) };
+ if request {
+ if !screen {
+ // Registers Optimus in the Screen Recording list and shows the system prompt once.
+ screen = unsafe { CGRequestScreenCaptureAccess() };
+ }
+ if !ax {
+ // Creating an input source with the prompt option adds Optimus to the Accessibility list.
+ let _ = enigo::Enigo::new(&enigo::Settings { open_prompt_to_get_permissions: true, ..Default::default() });
+ ax = unsafe { AXIsProcessTrusted() };
+ }
+ if !ax {
+ let _ = Command::new("open").arg(PANE_ACCESSIBILITY).status();
+ } else if !screen {
+ let _ = Command::new("open").arg(PANE_SCREEN).status();
+ }
+ }
+ let mark = |b: bool| if b { "✅" } else { "❌" };
+ let mut text = format!(
+ "macOS permissions for Optimus:\n{} Accessibility (mouse and keyboard)\n{} Screen Recording (see the screen)",
+ mark(ax),
+ mark(screen)
+ );
+ if !ax || !screen {
+ text.push_str(
+ "\nTo fix: System Settings → Privacy & Security, turn on \"Optimus\" under each one that's off. \
+ If Screen Recording asks to quit and reopen, Optimus restarts by itself on its next use. \
+ macOS asks to confirm Screen Recording again about once a month.",
+ );
+ }
+ json!({ "ready": ax && screen, "accessibility": ax, "screenRecording": screen, "text": text })
+}
+
+/// `optimus agent --socket <path>`: serve one connection, then exit.
+pub fn agent_main(socket: &Path) -> ! {
+ let _ = fs::remove_file(socket);
+ let listener = match UnixListener::bind(socket) {
+ Ok(l) => l,
+ Err(e) => {
+ eprintln!("optimus agent: can't listen on {}: {e}", socket.display());
+ std::process::exit(1);
+ }
+ };
+ let _ = fs::set_permissions(socket, fs::Permissions::from_mode(0o600));
+ // Nobody connecting within a minute means the plugin went away.
+ let _ = listener.set_nonblocking(true);
+ let deadline = Instant::now() + Duration::from_secs(60);
+ let stream = loop {
+ match listener.accept() {
+ Ok((s, _)) => break s,
+ Err(e) if e.kind() == std::io::ErrorKind::WouldBlock && Instant::now() < deadline => {
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ Err(_) => std::process::exit(0),
+ }
+ };
+ 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);
+ 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> {
+ 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");
+ ensure_bundle(&app, &dir)?;
+
+ // Short path: Unix socket paths are limited to ~104 bytes.
+ let socket = std::env::temp_dir().join(format!("mercury-optimus-{}.sock", std::process::id()));
+ let _ = fs::remove_file(&socket);
+ let status = Command::new("open")
+ .args(["-n", "-g"])
+ .arg(&app)
+ .args(["--args", "agent", "--socket"])
+ .arg(&socket)
+ .status()
+ .map_err(|e| format!("can't launch Optimus.app: {e}"))?;
+ if !status.success() {
+ return Err("macOS refused to launch Optimus.app".into());
+ }
+ let deadline = Instant::now() + Duration::from_secs(15);
+ let stream = loop {
+ match UnixStream::connect(&socket) {
+ Ok(s) => break s,
+ Err(_) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(100)),
+ 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)
+}
+
+fn ensure_bundle(app: &Path, dir: &Path) -> Result<(), String> {
+ let me = std::env::current_exe().map_err(|e| e.to_string())?;
+ let exe = app.join("Contents/MacOS/optimus");
+ let mine = fs::read(&me).map_err(|e| e.to_string())?;
+ // Signing rewrites the copy, so compare against a stamp of the source binary.
+ let stamp_file = dir.join("optimus-app.stamp");
+ let stamp = {
+ use std::hash::{Hash, Hasher};
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ mine.hash(&mut h);
+ format!("{}-{:x}", env!("CARGO_PKG_VERSION"), h.finish())
+ };
+ let fresh = exe.exists() && fs::read_to_string(&stamp_file).map(|s| s == stamp).unwrap_or(false) && signed(app);
+ if fresh {
+ return Ok(());
+ }
+ fs::create_dir_all(exe.parent().unwrap()).map_err(|e| e.to_string())?;
+ fs::write(&exe, &mine).map_err(|e| format!("can't write Optimus.app: {e}"))?;
+ fs::set_permissions(&exe, fs::Permissions::from_mode(0o755)).map_err(|e| e.to_string())?;
+ fs::write(app.join("Contents/Info.plist"), info_plist()).map_err(|e| e.to_string())?;
+ // Downloads made by Mercury aren't quarantined, but a copied browser download might be.
+ let _ = Command::new("xattr").args(["-dr", "com.apple.quarantine"]).arg(app).status();
+ sign(app, &dir.join("signing"))?;
+ fs::write(&stamp_file, stamp).map_err(|e| e.to_string())
+}
+
+fn signed(app: &Path) -> bool {
+ Command::new("codesign")
+ .args(["--verify", "--strict"])
+ .arg(app)
+ .output()
+ .map(|o| o.status.success())
+ .unwrap_or(false)
+}
+
+fn info_plist() -> String {
+ format!(
+ r#"<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleIdentifier</key><string>{BUNDLE_ID}</string>
+ <key>CFBundleName</key><string>Optimus</string>
+ <key>CFBundleDisplayName</key><string>Optimus</string>
+ <key>CFBundleExecutable</key><string>optimus</string>
+ <key>CFBundlePackageType</key><string>APPL</string>
+ <key>CFBundleShortVersionString</key><string>{v}</string>
+ <key>CFBundleVersion</key><string>{v}</string>
+ <key>LSUIElement</key><true/>
+ <key>LSMinimumSystemVersion</key><string>12.0</string>
+ <key>NSMicrophoneUsageDescription</key><string>Optimus listens when you talk to Mercury.</string>
+ <key>NSAppleEventsUsageDescription</key><string>Optimus controls apps when Mercury asks it to.</string>
+</dict>
+</plist>
+"#,
+ v = env!("CARGO_PKG_VERSION")
+ )
+}
+
+fn run(cmd: &mut Command) -> Result<String, String> {
+ let out = cmd.output().map_err(|e| format!("{:?}: {e}", cmd.get_program()))?;
+ if !out.status.success() {
+ return Err(format!(
+ "{} failed: {}",
+ cmd.get_program().to_string_lossy(),
+ String::from_utf8_lossy(&out.stderr).trim()
+ ));
+ }
+ Ok(String::from_utf8_lossy(&out.stdout).into_owned())
+}
+
+/// Sign the bundle with this Mac's own Optimus certificate, made once.
+///
+/// The identity lives in `signing/identity.p12`. For each signing it goes
+/// into a throwaway keychain that is on the search list only for the
+/// duration of the `codesign` call: the user's login keychain is never
+/// touched and no password prompt appears.
+fn sign(app: &Path, dir: &Path) -> Result<(), String> {
+ fs::create_dir_all(dir).map_err(|e| e.to_string())?;
+ let _ = fs::set_permissions(dir, fs::Permissions::from_mode(0o700));
+ let p12 = dir.join("identity.p12");
+ if !p12.exists() {
+ make_identity(dir, &p12)?;
+ }
+ let keychain = dir.join(format!("signing-{}.keychain-db", std::process::id()));
+ let kc = keychain.to_string_lossy().to_string();
+ let kc_pass = format!("optimus-{}", std::process::id());
+ let _ = Command::new("security").args(["delete-keychain", &kc]).output();
+ let original = run(Command::new("security").args(["list-keychains", "-d", "user"]))?;
+ let original: Vec<String> = original.lines().map(|l| l.trim().trim_matches('"').to_string()).filter(|l| !l.is_empty()).collect();
+
+ let result = (|| {
+ run(Command::new("security").args(["create-keychain", "-p", &kc_pass, &kc]))?;
+ run(Command::new("security").args(["unlock-keychain", "-p", &kc_pass, &kc]))?;
+ run(Command::new("security").args(["set-keychain-settings", &kc]))?;
+ run(Command::new("security")
+ .args(["import"])
+ .arg(&p12)
+ .args(["-k", &kc, "-P", P12_PASSWORD, "-T", "/usr/bin/codesign", "-f", "pkcs12"]))?;
+ run(Command::new("security").args(["set-key-partition-list", "-S", "apple-tool:,apple:", "-s", "-k", &kc_pass, &kc]))?;
+ let mut list = original.clone();
+ list.push(kc.clone());
+ run(Command::new("security").args(["list-keychains", "-d", "user", "-s"]).args(&list))?;
+ run(Command::new("codesign")
+ .args(["--force", "--sign", CERT_NAME, "--keychain", &kc, "--identifier", BUNDLE_ID])
+ .arg(app))
+ })();
+
+ // Always restore the search list and remove the throwaway keychain.
+ let _ = Command::new("security").args(["list-keychains", "-d", "user", "-s"]).args(&original).output();
+ let _ = Command::new("security").args(["delete-keychain", &kc]).output();
+ let _ = fs::remove_file(&keychain);
+ result.map(|_| ()).map_err(|e| format!("couldn't sign Optimus.app: {e}"))
+}
+
+fn make_identity(dir: &Path, p12: &Path) -> Result<(), String> {
+ let cnf = dir.join("cert.cnf");
+ let key = dir.join("key.pem");
+ let cert = dir.join("cert.pem");
+ fs::write(
+ &cnf,
+ format!(
+ "[req]\ndistinguished_name=dn\nx509_extensions=ext\nprompt=no\n[dn]\nCN={CERT_NAME}\n\
+ [ext]\nbasicConstraints=critical,CA:false\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=critical,codeSigning\n"
+ ),
+ )
+ .map_err(|e| e.to_string())?;
+ run(Command::new("/usr/bin/openssl")
+ .args(["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "36500", "-keyout"])
+ .arg(&key)
+ .arg("-out")
+ .arg(&cert)
+ .arg("-config")
+ .arg(&cnf))?;
+ let export = |legacy: bool| {
+ let mut c = Command::new("/usr/bin/openssl");
+ c.arg("pkcs12").arg("-export");
+ if legacy {
+ c.arg("-legacy");
+ }
+ c.arg("-inkey").arg(&key).arg("-in").arg(&cert).arg("-out").arg(p12);
+ c.args(["-passout", &format!("pass:{P12_PASSWORD}"), "-name", CERT_NAME]);
+ run(&mut c)
+ };
+ // LibreSSL (macOS) has no -legacy flag; OpenSSL 3 needs it for macOS to read the file.
+ export(false).or_else(|_| export(true))?;
+ let _ = fs::set_permissions(p12, fs::Permissions::from_mode(0o600));
+ let _ = fs::remove_file(&key);
+ let _ = fs::remove_file(&cnf);
+ Ok(())
+}
diff --git a/plugins/optimus/companion/src/ops.rs b/plugins/optimus/companion/src/ops.rs
new file mode 100644
index 00000000..17e98507
--- /dev/null
+++ b/plugins/optimus/companion/src/ops.rs
@@ -0,0 +1,626 @@
+//! What Optimus does to the computer: screenshots, mouse, keyboard, apps.
+//!
+//! Every operation takes JSON arguments and returns JSON:
+//! { "text": "...", "image": { "data": <base64>, "mimeType": "image/jpeg" } }
+//! (image optional). On macOS this runs inside Optimus.app (see mac.rs), so
+//! the OS permissions belong to Optimus; elsewhere it runs in the plugin
+//! process itself.
+//!
+//! Coordinates the model sends are pixels in the most recent screenshot.
+//! They're mapped back to the screen through the geometry of that shot, so
+//! HiDPI scaling and multi-monitor offsets never reach the model.
+
+use std::time::{Duration, Instant};
+
+use base64::Engine as _;
+use enigo::{Axis, Button, Coordinate, Direction, Enigo, Key, Keyboard, Mouse, Settings};
+use serde_json::{Value, json};
+use xcap::image::{DynamicImage, RgbaImage, codecs::jpeg::JpegEncoder, imageops::FilterType};
+use xcap::{Monitor, Window};
+
+/// Screenshots fit in this box (what computer-use models are tuned for).
+const MAX_W: u32 = 1280;
+const MAX_H: u32 = 800;
+const JPEG_QUALITY: u8 = 80;
+/// The user moving the mouse this far during a batch stops Optimus.
+const TAKEOVER_PX: i32 = 12;
+const MAX_ACTIONS: usize = 40;
+const MAX_TYPE_CHARS: usize = 4000;
+
+/// Where the last screenshot came from, to map its pixels back to the screen.
+#[derive(Clone, Copy)]
+struct Shot {
+ monitor: usize,
+ /// Monitor origin and size in input coordinates (points on macOS, pixels elsewhere).
+ x: i32,
+ y: i32,
+ w: u32,
+ h: u32,
+ /// The screenshot's size as the model saw it.
+ img_w: u32,
+ img_h: u32,
+}
+
+impl Shot {
+ fn to_screen(&self, px: f64, py: f64) -> Result<(i32, i32), String> {
+ if !(0.0..=self.img_w as f64).contains(&px) || !(0.0..=self.img_h as f64).contains(&py) {
+ return Err(format!(
+ "({px}, {py}) is outside the last screenshot ({}×{}); use coordinates from the latest screenshot",
+ self.img_w, self.img_h
+ ));
+ }
+ let sx = self.x as f64 + px * self.w as f64 / self.img_w as f64;
+ let sy = self.y as f64 + py * self.h as f64 / self.img_h as f64;
+ Ok((sx.round() as i32, sy.round() as i32))
+ }
+ fn to_image(&self, sx: i32, sy: i32) -> Option<(i64, i64)> {
+ let px = (sx - self.x) as f64 * self.img_w as f64 / self.w as f64;
+ let py = (sy - self.y) as f64 * self.img_h as f64 / self.h as f64;
+ if px < 0.0 || py < 0.0 || px > self.img_w as f64 || py > self.img_h as f64 {
+ return None;
+ }
+ Some((px.round() as i64, py.round() as i64))
+ }
+}
+
+pub struct Ops {
+ enigo: Option<Enigo>,
+ shot: Option<Shot>,
+}
+
+pub type OpResult = Result<Value, String>;
+
+impl Default for Ops {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl Ops {
+ pub fn new() -> Self {
+ #[cfg(windows)]
+ unsafe {
+ // Real pixels everywhere: otherwise Windows scales coordinates and captures.
+ use windows_sys::Win32::UI::HiDpi::{DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, SetProcessDpiAwarenessContext};
+ SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
+ }
+ Ops { enigo: None, shot: None }
+ }
+
+ fn enigo(&mut self) -> Result<&mut Enigo, String> {
+ if self.enigo.is_none() {
+ let settings = Settings { open_prompt_to_get_permissions: false, ..Settings::default() };
+ self.enigo = Some(Enigo::new(&settings).map_err(|e| format!("can't control the mouse and keyboard: {e}{}", permission_hint()))?);
+ }
+ Ok(self.enigo.as_mut().unwrap())
+ }
+
+ fn cursor(&mut self) -> Option<(i32, i32)> {
+ self.enigo().ok()?.location().ok()
+ }
+
+ pub fn run(&mut self, op: &str, args: &Value) -> OpResult {
+ match op {
+ "look" => self.look(args),
+ "act" => self.act(args),
+ "open" => open_target(args),
+ "windows" => windows(),
+ "permissions" => self.permissions(args),
+ other => Err(format!("unknown operation {other}")),
+ }
+ }
+
+ // ── Seeing ─────────────────────────────────────────────────────────
+
+ fn pick_monitor(&mut self, args: &Value) -> Result<(usize, Monitor), String> {
+ let monitors = Monitor::all().map_err(|e| capture_error(&e.to_string()))?;
+ if monitors.is_empty() {
+ return Err("no display found".into());
+ }
+ if let Some(n) = args.get("display").and_then(Value::as_u64) {
+ let i = (n as usize).saturating_sub(1);
+ return monitors.into_iter().enumerate().nth(i).ok_or_else(|| format!("there is no display {n}"));
+ }
+ // Default: the display the cursor is on, else the main one.
+ let cursor = self.cursor();
+ let idx = monitors
+ .iter()
+ .position(|m| match (cursor, m.x(), m.y(), m.width(), m.height()) {
+ (Some((cx, cy)), Ok(x), Ok(y), Ok(w), Ok(h)) => cx >= x && cy >= y && cx < x + w as i32 && cy < y + h as i32,
+ _ => false,
+ })
+ .or_else(|| monitors.iter().position(|m| m.is_primary().unwrap_or(false)))
+ .unwrap_or(0);
+ Ok((idx, monitors.into_iter().nth(idx).unwrap()))
+ }
+
+ fn look(&mut self, args: &Value) -> OpResult {
+ let display = match (args.get("display"), self.shot) {
+ (Some(d), _) => d.clone(),
+ (None, Some(s)) if args.get("zoom").is_some() => json!(s.monitor + 1),
+ _ => Value::Null,
+ };
+ let (idx, mon) = self.pick_monitor(&json!({ "display": display }))?;
+ let count = Monitor::all().map(|m| m.len()).unwrap_or(1);
+ let (x, y, w, h) = (
+ mon.x().map_err(err)?,
+ mon.y().map_err(err)?,
+ mon.width().map_err(err)?,
+ mon.height().map_err(err)?,
+ );
+ let full = mon.capture_image().map_err(|e| capture_error(&e.to_string()))?;
+
+ // Zoom: a closer look at part of the last screenshot. Coordinates keep
+ // referring to the full screenshot, so the zoom never moves the frame.
+ if let Some(z) = args.get("zoom").and_then(Value::as_array) {
+ let shot = self.shot.ok_or("take a screenshot (look) before zooming")?;
+ let n: Vec<f64> = z.iter().filter_map(Value::as_f64).collect();
+ if n.len() != 4 || n[2] <= n[0] || n[3] <= n[1] {
+ return Err("zoom is [x0, y0, x1, y1] in the last screenshot's pixels".into());
+ }
+ let fx = full.width() as f64 / shot.img_w as f64;
+ let fy = full.height() as f64 / shot.img_h as f64;
+ let (cx, cy) = ((n[0] * fx).max(0.0) as u32, (n[1] * fy).max(0.0) as u32);
+ let cw = (((n[2] - n[0]) * fx) as u32).clamp(1, full.width().saturating_sub(cx).max(1));
+ let ch = (((n[3] - n[1]) * fy) as u32).clamp(1, full.height().saturating_sub(cy).max(1));
+ let crop = xcap::image::imageops::crop_imm(&full, cx, cy, cw, ch).to_image();
+ let (img, iw, ih) = fit(crop);
+ return Ok(json!({
+ "text": format!(
+ "Zoom on [{}, {}, {}, {}] of the last screenshot, shown at {iw}×{ih}. Coordinates for actions still refer to the full screenshot.",
+ n[0], n[1], n[2], n[3]
+ ),
+ "image": img,
+ }));
+ }
+
+ let (img, iw, ih) = fit(full);
+ let shot = Shot { monitor: idx, x, y, w, h, img_w: iw, img_h: ih };
+ self.shot = Some(shot);
+ let cursor = self.cursor().and_then(|(cx, cy)| shot.to_image(cx, cy));
+ let focused = focused_window();
+ let mut text = format!("Display {} of {count}, screenshot {iw}×{ih}.", idx + 1);
+ if let Some((cx, cy)) = cursor {
+ text.push_str(&format!(" Mouse at ({cx}, {cy})."));
+ }
+ if let Some(f) = focused {
+ text.push_str(&format!(" Active window: {f}."));
+ }
+ text.push_str(" Use pixel coordinates from this screenshot for actions.");
+ Ok(json!({ "text": text, "image": img }))
+ }
+
+ // ── Acting ─────────────────────────────────────────────────────────
+
+ fn act(&mut self, args: &Value) -> OpResult {
+ let actions = args.get("actions").and_then(Value::as_array).ok_or("actions must be a list")?;
+ if actions.is_empty() {
+ return Err("no actions given".into());
+ }
+ if actions.len() > MAX_ACTIONS {
+ return Err(format!("at most {MAX_ACTIONS} actions per call"));
+ }
+ let mut done: Vec<String> = Vec::new();
+ let mut last_set: Option<(i32, i32)> = None;
+ let mut stopped: Option<String> = None;
+
+ for (i, a) in actions.iter().enumerate() {
+ // The user moved the mouse since our last move: they're taking over.
+ if let Some((lx, ly)) = last_set {
+ if let Some((cx, cy)) = self.cursor() {
+ if (cx - lx).abs() > TAKEOVER_PX || (cy - ly).abs() > TAKEOVER_PX {
+ stopped = Some(format!(
+ "Stopped before action {}: you moved the mouse, so Optimus handed control back.",
+ i + 1
+ ));
+ break;
+ }
+ }
+ }
+ match self.one(a, &mut last_set) {
+ Ok(d) => done.push(d),
+ Err(e) => {
+ stopped = Some(format!("Action {} failed: {e}", i + 1));
+ break;
+ }
+ }
+ }
+ // Let the screen settle, then show what happened (unless asked not to).
+ let mut out = json!({});
+ let mut text = if done.is_empty() { "Nothing was done.".to_string() } else { format!("Done: {}.", done.join("; ")) };
+ if let Some(s) = &stopped {
+ text.push(' ');
+ text.push_str(s);
+ }
+ if args.get("screenshot").and_then(Value::as_bool) != Some(false) {
+ std::thread::sleep(Duration::from_millis(args.get("settle_ms").and_then(Value::as_u64).unwrap_or(500).min(5000)));
+ match self.look(&json!({})) {
+ Ok(v) => {
+ text.push_str("\nScreen now: ");
+ text.push_str(v["text"].as_str().unwrap_or(""));
+ out["image"] = v["image"].clone();
+ }
+ Err(e) => text.push_str(&format!("\n(No screenshot: {e})")),
+ }
+ }
+ out["text"] = json!(text);
+ if stopped.is_some() {
+ out["stopped"] = json!(true);
+ }
+ Ok(out)
+ }
+
+ fn point(&self, a: &Value, xk: &str, yk: &str) -> Result<Option<(i32, i32)>, String> {
+ match (a.get(xk).and_then(Value::as_f64), a.get(yk).and_then(Value::as_f64)) {
+ (Some(x), Some(y)) => {
+ let shot = self.shot.ok_or("take a screenshot (look) first, so coordinates have a frame")?;
+ shot.to_screen(x, y).map(Some)
+ }
+ (None, None) => Ok(None),
+ _ => Err(format!("{xk} and {yk} go together")),
+ }
+ }
+
+ fn one(&mut self, a: &Value, last_set: &mut Option<(i32, i32)>) -> Result<String, String> {
+ let kind = a.get("type").and_then(Value::as_str).ok_or("each action needs a type")?;
+ let at = self.point(a, "x", "y")?;
+ let label = |what: &str| match (a.get("x"), a.get("y")) {
+ (Some(x), Some(y)) => format!("{what} at ({x}, {y})"),
+ _ => what.to_string(),
+ };
+ let e = self.enigo()?;
+ let move_to = |e: &mut Enigo, p: (i32, i32), last: &mut Option<(i32, i32)>| -> Result<(), String> {
+ e.move_mouse(p.0, p.1, Coordinate::Abs).map_err(err)?;
+ *last = Some(p);
+ std::thread::sleep(Duration::from_millis(30));
+ Ok(())
+ };
+ match kind {
+ "click" | "double_click" | "triple_click" | "right_click" | "middle_click" => {
+ if let Some(p) = at {
+ move_to(e, p, last_set)?;
+ }
+ let button = match kind {
+ "right_click" => Button::Right,
+ "middle_click" => Button::Middle,
+ _ => Button::Left,
+ };
+ let times = match kind {
+ "double_click" => 2,
+ "triple_click" => 3,
+ _ => 1,
+ };
+ let mods = parse_mods(a.get("modifiers").and_then(Value::as_str).unwrap_or(""))?;
+ for m in &mods {
+ e.key(*m, Direction::Press).map_err(err)?;
+ }
+ for n in 0..times {
+ if n > 0 {
+ std::thread::sleep(Duration::from_millis(60));
+ }
+ e.button(button, Direction::Click).map_err(err)?;
+ }
+ for m in mods.iter().rev() {
+ e.key(*m, Direction::Release).map_err(err)?;
+ }
+ Ok(label(&kind.replace('_', " ")))
+ }
+ "move" => {
+ move_to(e, at.ok_or("move needs x and y")?, last_set)?;
+ Ok(label("moved the mouse"))
+ }
+ "mouse_down" | "mouse_up" => {
+ if let Some(p) = at {
+ move_to(e, p, last_set)?;
+ }
+ let d = if kind == "mouse_down" { Direction::Press } else { Direction::Release };
+ e.button(Button::Left, d).map_err(err)?;
+ Ok(label(&kind.replace('_', " ")))
+ }
+ "drag" => {
+ let from = at.ok_or("drag needs x and y (start)")?;
+ let to = self.point(a, "to_x", "to_y")?.ok_or("drag needs to_x and to_y (end)")?;
+ let e = self.enigo()?;
+ move_to(e, from, last_set)?;
+ e.button(Button::Left, Direction::Press).map_err(err)?;
+ for s in 1..=12 {
+ let t = s as f64 / 12.0;
+ let p = (
+ from.0 + ((to.0 - from.0) as f64 * t).round() as i32,
+ from.1 + ((to.1 - from.1) as f64 * t).round() as i32,
+ );
+ e.move_mouse(p.0, p.1, Coordinate::Abs).map_err(err)?;
+ std::thread::sleep(Duration::from_millis(16));
+ }
+ *last_set = Some(to);
+ e.button(Button::Left, Direction::Release).map_err(err)?;
+ Ok(format!("dragged to ({}, {})", a["to_x"], a["to_y"]))
+ }
+ "type" => {
+ let text = a.get("text").and_then(Value::as_str).ok_or("type needs text")?;
+ if text.chars().count() > MAX_TYPE_CHARS {
+ return Err(format!("type at most {MAX_TYPE_CHARS} characters at a time"));
+ }
+ if let Some(p) = at {
+ move_to(e, p, last_set)?;
+ e.button(Button::Left, Direction::Click).map_err(err)?;
+ }
+ e.text(text).map_err(err)?;
+ Ok(format!("typed {} characters", text.chars().count()))
+ }
+ "key" => {
+ let combo = a.get("keys").and_then(Value::as_str).ok_or("key needs keys, e.g. \"cmd+t\" or \"enter\"")?;
+ let repeat = a.get("repeat").and_then(Value::as_u64).unwrap_or(1).clamp(1, 50);
+ let (mods, main) = parse_combo(combo)?;
+ for _ in 0..repeat {
+ for m in &mods {
+ e.key(*m, Direction::Press).map_err(err)?;
+ }
+ e.key(main, Direction::Click).map_err(err)?;
+ for m in mods.iter().rev() {
+ e.key(*m, Direction::Release).map_err(err)?;
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ Ok(if repeat > 1 { format!("pressed {combo} ×{repeat}") } else { format!("pressed {combo}") })
+ }
+ "scroll" => {
+ if let Some(p) = at {
+ move_to(e, p, last_set)?;
+ }
+ let dir = a.get("direction").and_then(Value::as_str).unwrap_or("down");
+ let amount = a.get("amount").and_then(Value::as_i64).unwrap_or(3).clamp(1, 30) as i32;
+ let (len, axis) = match dir {
+ "down" => (amount, Axis::Vertical),
+ "up" => (-amount, Axis::Vertical),
+ "right" => (amount, Axis::Horizontal),
+ "left" => (-amount, Axis::Horizontal),
+ other => return Err(format!("scroll direction is up, down, left or right, not {other}")),
+ };
+ e.scroll(len, axis).map_err(err)?;
+ Ok(label(&format!("scrolled {dir} {amount}")))
+ }
+ "wait" => {
+ let s = a.get("seconds").and_then(Value::as_f64).unwrap_or(1.0).clamp(0.0, 10.0);
+ let until = Instant::now() + Duration::from_secs_f64(s);
+ while Instant::now() < until {
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ Ok(format!("waited {s}s"))
+ }
+ other => Err(format!("unknown action type {other}")),
+ }
+ }
+
+ // ── Permissions ────────────────────────────────────────────────────
+
+ fn permissions(&mut self, args: &Value) -> OpResult {
+ let request = args.get("request").and_then(Value::as_bool).unwrap_or(false);
+ #[cfg(target_os = "macos")]
+ {
+ let _ = &self.enigo;
+ Ok(crate::mac::permission_report(request))
+ }
+ #[cfg(not(target_os = "macos"))]
+ {
+ let _ = request;
+ Ok(other_os_report())
+ }
+ }
+}
+
+#[cfg(not(target_os = "macos"))]
+fn other_os_report() -> Value {
+ if cfg!(windows) {
+ return json!({
+ "ready": true,
+ "text": "Windows: Optimus can see the screen and use the mouse and keyboard. Windows running as administrator (Task Manager, installers) can't be controlled unless Optimus runs in admin mode.",
+ });
+ }
+ let session = std::env::var("XDG_SESSION_TYPE").unwrap_or_default();
+ if session == "wayland" || std::env::var("WAYLAND_DISPLAY").is_ok() {
+ return json!({
+ "ready": false,
+ "text": "Linux (Wayland): screenshots go through the desktop's screen-sharing prompt, and mouse/keyboard control only reaches X11 (XWayland) apps for now. An X11 session gives Optimus full control.",
+ });
+ }
+ json!({ "ready": true, "text": "Linux (X11): Optimus can see the screen and use the mouse and keyboard." })
+}
+
+fn permission_hint() -> &'static str {
+ if cfg!(target_os = "macos") { " (allow Optimus in System Settings → Privacy & Security → Accessibility)" } else { "" }
+}
+
+fn capture_error(e: &str) -> String {
+ if cfg!(target_os = "macos") {
+ format!("can't take a screenshot: {e} (allow Optimus in System Settings → Privacy & Security → Screen Recording, then try again)")
+ } else {
+ format!("can't take a screenshot: {e}")
+ }
+}
+
+fn err(e: impl std::fmt::Display) -> String {
+ e.to_string()
+}
+
+/// Shrink to the model's box and encode as JPEG.
+fn fit(img: RgbaImage) -> (Value, u32, u32) {
+ let (w, h) = (img.width().max(1), img.height().max(1));
+ let scale = (MAX_W as f64 / w as f64).min(MAX_H as f64 / h as f64).min(1.0);
+ let (nw, nh) = (((w as f64 * scale).round() as u32).max(1), ((h as f64 * scale).round() as u32).max(1));
+ let rgb = DynamicImage::ImageRgba8(img).resize_exact(nw, nh, FilterType::Triangle).to_rgb8();
+ let mut buf = Vec::new();
+ let _ = JpegEncoder::new_with_quality(&mut buf, JPEG_QUALITY).encode_image(&DynamicImage::ImageRgb8(rgb));
+ (
+ json!({ "data": base64::engine::general_purpose::STANDARD.encode(&buf), "mimeType": "image/jpeg" }),
+ nw,
+ nh,
+ )
+}
+
+fn focused_window() -> Option<String> {
+ let w = Window::all().ok()?.into_iter().find(|w| w.is_focused().unwrap_or(false))?;
+ let app = w.app_name().unwrap_or_default();
+ let title = w.title().unwrap_or_default();
+ Some(if title.is_empty() || title == app { app } else { format!("{app} — {title}") })
+}
+
+fn windows() -> OpResult {
+ let mut list = Window::all().map_err(|e| capture_error(&e.to_string()))?;
+ list.sort_by_key(|w| -w.z().unwrap_or(0));
+ let lines: Vec<String> = list
+ .iter()
+ .filter(|w| !w.is_minimized().unwrap_or(false) && w.width().unwrap_or(0) > 40 && w.height().unwrap_or(0) > 40)
+ .filter_map(|w| {
+ let app = w.app_name().ok()?;
+ if app.is_empty() {
+ return None;
+ }
+ let title = w.title().unwrap_or_default();
+ let focus = if w.is_focused().unwrap_or(false) { " (active)" } else { "" };
+ Some(if title.is_empty() { format!("- {app}{focus}") } else { format!("- {app} — {title}{focus}") })
+ })
+ .take(30)
+ .collect();
+ Ok(json!({ "text": if lines.is_empty() { "No windows are open.".to_string() } else { format!("Open windows, front first:\n{}", lines.join("\n")) } }))
+}
+
+/// Open an app by name, a URL, or a file/folder.
+fn open_target(args: &Value) -> OpResult {
+ let target = args.get("target").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty()).ok_or("open needs a target: an app name, a URL or a path")?;
+ let is_url = target.contains("://") || target.starts_with("mailto:");
+ let is_path = std::path::Path::new(target).exists();
+ let status = if cfg!(target_os = "macos") {
+ let mut c = std::process::Command::new("open");
+ if !is_url && !is_path {
+ c.arg("-a");
+ }
+ c.arg(target).status()
+ } else if cfg!(windows) {
+ std::process::Command::new("cmd").args(["/C", "start", "", target]).status()
+ } else if is_url || is_path {
+ std::process::Command::new("xdg-open").arg(target).status()
+ } else {
+ std::process::Command::new("gtk-launch")
+ .arg(target)
+ .status()
+ .and_then(|s| if s.success() { Ok(s) } else { std::process::Command::new(target).spawn().map(|_| s) })
+ };
+ match status {
+ Ok(s) if s.success() => {
+ std::thread::sleep(Duration::from_millis(800));
+ Ok(json!({ "text": format!("Opened {target}. Take a screenshot (look) to see it.") }))
+ }
+ Ok(_) => Err(format!("couldn't open {target} (no app, URL or file by that name)")),
+ Err(e) => Err(format!("couldn't open {target}: {e}")),
+ }
+}
+
+// ── Keys ──────────────────────────────────────────────────────────────
+
+fn key_named(name: &str) -> Result<Key, String> {
+ let n = name.trim().to_ascii_lowercase();
+ let k = match n.as_str() {
+ "cmd" | "command" | "meta" | "super" | "win" | "windows" => Key::Meta,
+ "ctrl" | "control" => Key::Control,
+ "shift" => Key::Shift,
+ "alt" | "option" | "opt" => Key::Alt,
+ "enter" | "return" => Key::Return,
+ "tab" => Key::Tab,
+ "esc" | "escape" => Key::Escape,
+ "backspace" => Key::Backspace,
+ "delete" | "del" => Key::Delete,
+ "space" | "spacebar" => Key::Space,
+ "up" | "arrowup" => Key::UpArrow,
+ "down" | "arrowdown" => Key::DownArrow,
+ "left" | "arrowleft" => Key::LeftArrow,
+ "right" | "arrowright" => Key::RightArrow,
+ "home" => Key::Home,
+ "end" => Key::End,
+ "pageup" | "page_up" => Key::PageUp,
+ "pagedown" | "page_down" => Key::PageDown,
+ "capslock" => Key::CapsLock,
+ "plus" => Key::Unicode('+'),
+ "minus" => Key::Unicode('-'),
+ "f1" => Key::F1,
+ "f2" => Key::F2,
+ "f3" => Key::F3,
+ "f4" => Key::F4,
+ "f5" => Key::F5,
+ "f6" => Key::F6,
+ "f7" => Key::F7,
+ "f8" => Key::F8,
+ "f9" => Key::F9,
+ "f10" => Key::F10,
+ "f11" => Key::F11,
+ "f12" => Key::F12,
+ _ => {
+ let mut chars = name.trim().chars();
+ match (chars.next(), chars.next()) {
+ (Some(c), None) => Key::Unicode(c.to_ascii_lowercase()),
+ _ => return Err(format!("unknown key \"{name}\"")),
+ }
+ }
+ };
+ Ok(k)
+}
+
+fn is_modifier(k: Key) -> bool {
+ matches!(k, Key::Meta | Key::Control | Key::Shift | Key::Alt)
+}
+
+/// "cmd+shift+t" → ([Meta, Shift], t)
+fn parse_combo(combo: &str) -> Result<(Vec<Key>, Key), String> {
+ let parts: Vec<&str> = combo.split('+').filter(|p| !p.trim().is_empty()).collect();
+ // A literal "+" ("cmd++") leaves an empty last part.
+ let parts = if combo.trim_end().ends_with("++") || combo.trim() == "+" { [parts, vec!["plus"]].concat() } else { parts };
+ let (last, mods) = parts.split_last().ok_or("no key given")?;
+ let mods = mods.iter().map(|m| key_named(m)).collect::<Result<Vec<_>, _>>()?;
+ if let Some(m) = mods.iter().find(|m| !is_modifier(**m)) {
+ return Err(format!("{m:?} isn't a modifier; send separate key actions for a sequence"));
+ }
+ Ok((mods, key_named(last)?))
+}
+
+fn parse_mods(s: &str) -> Result<Vec<Key>, String> {
+ s.split('+').map(str::trim).filter(|p| !p.is_empty()).map(key_named).collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn combos() {
+ let (m, k) = parse_combo("cmd+shift+t").unwrap();
+ assert_eq!(m, vec![Key::Meta, Key::Shift]);
+ assert_eq!(k, Key::Unicode('t'));
+ assert_eq!(parse_combo("Enter").unwrap(), (vec![], Key::Return));
+ assert_eq!(parse_combo("ctrl++").unwrap(), (vec![Key::Control], Key::Unicode('+')));
+ assert!(parse_combo("a+b").is_err());
+ assert!(parse_combo("cmd+nope").is_err());
+ }
+
+ #[test]
+ fn mapping_round_trips() {
+ // A 2560×1600 Retina display reported as 1440×900 points, shown at 1280×800.
+ let s = Shot { monitor: 0, x: 0, y: 0, w: 1440, h: 900, img_w: 1280, img_h: 800 };
+ assert_eq!(s.to_screen(640.0, 400.0).unwrap(), (720, 450));
+ assert_eq!(s.to_image(720, 450), Some((640, 400)));
+ assert!(s.to_screen(1300.0, 10.0).is_err());
+ // A second display to the left.
+ let s = Shot { monitor: 1, x: -1920, y: 0, w: 1920, h: 1080, img_w: 1280, img_h: 720 };
+ assert_eq!(s.to_screen(0.0, 0.0).unwrap(), (-1920, 0));
+ assert_eq!(s.to_screen(1280.0, 720.0).unwrap(), (0, 1080));
+ }
+
+ #[test]
+ fn fit_keeps_aspect() {
+ let (_, w, h) = fit(RgbaImage::new(2880, 1800));
+ assert_eq!((w, h), (1280, 800));
+ let (_, w, h) = fit(RgbaImage::new(3840, 2160));
+ assert_eq!((w, h), (1280, 720));
+ let (_, w, h) = fit(RgbaImage::new(800, 600));
+ assert_eq!((w, h), (800, 600));
+ }
+}
diff --git a/plugins/optimus/mercury-plugin.template.json b/plugins/optimus/mercury-plugin.template.json
new file mode 100644
index 00000000..f9e5caf3
--- /dev/null
+++ b/plugins/optimus/mercury-plugin.template.json
@@ -0,0 +1,82 @@
+{
+ "manifestVersion": 1,
+ "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.",
+ "kind": "out-of-process",
+ "author": "Cosmic Stack",
+ "homepage": "https://github.com/cosmicstack-labs/mercury-agent/tree/main/plugins/optimus",
+ "license": "MIT",
+ "engines": {
+ "mercury": ">=1.3.9 <2.0.0",
+ "pluginApi": "^1.2.0"
+ },
+ "server": {
+ "command": "bin/mercury-optimus",
+ "args": [],
+ "platforms": {
+ "win32-x64": {
+ "command": "bin/mercury-optimus.exe",
+ "args": []
+ }
+ }
+ },
+ "contributes": {
+ "tools": [
+ {
+ "name": "look",
+ "description": "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).",
+ "readOnly": true,
+ "timeoutMs": 30000
+ },
+ {
+ "name": "act",
+ "description": "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.",
+ "readOnly": true,
+ "timeoutMs": 120000
+ },
+ {
+ "name": "act_consequential",
+ "description": "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.",
+ "readOnly": false,
+ "timeoutMs": 120000
+ },
+ {
+ "name": "open",
+ "description": "Open an app by name (\"Safari\", \"Blender\", \"Notepad\"), a URL, or a file/folder path. Faster and more reliable than clicking through menus.",
+ "readOnly": true,
+ "timeoutMs": 30000
+ },
+ {
+ "name": "windows",
+ "description": "List open windows (app and title), front first.",
+ "readOnly": true,
+ "timeoutMs": 15000
+ },
+ {
+ "name": "permissions",
+ "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
+ }
+ ]
+ },
+ "permissions": {
+ "network": [],
+ "secrets": [],
+ "desktop": true
+ },
+ "settings": {
+ "fields": {
+ "allowControl": {
+ "type": "boolean",
+ "label": "Let Optimus control this computer?",
+ "description": "Optimus sees your screen and uses the mouse and keyboard in any app. It asks before anything that submits, sends, pays, deletes or installs, and stops the moment you move the mouse.",
+ "default": false,
+ "setup": true,
+ "required": true
+ }
+ }
+ }
+}
diff --git a/plugins/optimus/package.mjs b/plugins/optimus/package.mjs
new file mode 100644
index 00000000..4534c320
--- /dev/null
+++ b/plugins/optimus/package.mjs
@@ -0,0 +1,40 @@
+// Build a per-platform plugin package from a compiled companion binary:
+// node plugins/optimus/package.mjs <binary> <platform-key> <out-dir>
+// Writes <out-dir>/mercury-plugin-<platform-key>.tgz containing the
+// manifest (with this platform and the binary's SHA-256 pinned), the
+// binary under bin/, and the README.
+import { createHash } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { chmodSync, copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { basename, dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const [binary, platform, outDir] = process.argv.slice(2);
+if (!binary || !platform || !outDir) {
+ console.error('usage: node package.mjs <binary> <platform-key> <out-dir>');
+ process.exit(2);
+}
+const here = dirname(fileURLToPath(import.meta.url));
+const manifest = JSON.parse(readFileSync(join(here, 'mercury-plugin.template.json'), 'utf8'));
+const exe = platform.startsWith('win32') ? 'mercury-optimus.exe' : 'mercury-optimus';
+const rel = `bin/${exe}`;
+
+const stage = mkdtempSync(join(tmpdir(), 'mercury-optimus-pkg-'));
+mkdirSync(join(stage, 'bin'));
+copyFileSync(binary, join(stage, rel));
+chmodSync(join(stage, rel), 0o755);
+copyFileSync(join(here, 'README.md'), join(stage, 'README.md'));
+
+manifest.platforms = [platform];
+manifest.checksums = { [rel]: createHash('sha256').update(readFileSync(join(stage, rel))).digest('hex') };
+writeFileSync(join(stage, 'mercury-plugin.json'), `${JSON.stringify(manifest, null, 2)}\n`);
+
+mkdirSync(outDir, { recursive: true });
+const out = resolve(outDir, `mercury-plugin-${platform}.tgz`);
+// Archive name relative to cwd: GNU tar on Windows reads "D:\\…" as a remote host.
+execFileSync('tar', ['-czf', basename(out), '-C', stage, 'mercury-plugin.json', 'bin', 'README.md'], { cwd: dirname(out) });
+const sha = createHash('sha256').update(readFileSync(out)).digest('hex');
+writeFileSync(`${out}.sha256`, `${sha} mercury-plugin-${platform}.tgz\n`);
+rmSync(stage, { recursive: true, force: true });
+console.log(`${out}\n${sha}`);
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 4aadac52..dae022c1 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -96,7 +96,8 @@ import { createTaskSurface } from './task-surface.js';
import { buildFileChangePreview } from '../utils/file-preview.js';
import { whatsNewText } from '../utils/whats-new.js';
import { handleBotsCommand as handleBotsCommandImpl } from './commands/bots-command.js';
-import { withAttachments } from './attachments.js';
+import { modelSeesImages, withAttachments } from './attachments.js';
+import { setPluginImagesAllowed } from '../plugins/tool-bridge.js';
import { handleCallCommand } from '../plugins/call-schedule.js';
import { handlePluginsCommand, tryPluginCommand, pluginCommandHelp, hasPluginDialog, answerPluginDialog } from '../plugins/commands.js';
import { handleChatCommand as handleChatCommandImpl } from './commands/chat-command.js';
@@ -3164,6 +3165,7 @@ export class Agent {
// passed back with assistant turns (issue #24); other providers
// get plain text.
// Photos and PDFs from the chat go to models that can take them.
+ setPluginImagesAllowed(modelSeesImages(provider.name, provider.getModel()));
const providerMessages = withAttachments(deepseekProviderOptions ? withReasoningParts(messages) : messages, msg, provider.name, provider.getModel());
// Per-provider output ceiling: a 32K request is rejected outright by
// providers with smaller limits and burned a halve-and-retry round.
diff --git a/src/plugins/commands.ts b/src/plugins/commands.ts
index 0247849a..0c7e6b74 100644
--- a/src/plugins/commands.ts
+++ b/src/plugins/commands.ts
@@ -82,6 +82,7 @@ function describe(i: PluginListItem): string {
const p = i.permissions;
lines.push(`Network: ${p?.network.length ? p.network.join(', ') : 'none'}`);
lines.push(`Secrets it can read: ${p?.secrets.length ? p.secrets.join(', ') : 'none'}`);
+ if (p?.desktop) lines.push('⚠️ Controls this computer: it can see your screen, move the mouse and type, in any app.');
for (const m of i.missing ?? []) lines.push(`⚠️ ${m.unlocks} is off: needs ${m.needs}. ${m.fix}`);
const providers = Object.keys(i.permissions?.providers ?? {});
if (providers.length) lines.push(`Uses your Mercury providers: ${providers.join(', ')}`);
diff --git a/src/plugins/runtime/out-of-process.ts b/src/plugins/runtime/out-of-process.ts
index 1f62c7fc..36a5c600 100644
--- a/src/plugins/runtime/out-of-process.ts
+++ b/src/plugins/runtime/out-of-process.ts
@@ -17,7 +17,7 @@ import { resolve } from 'node:path';
import { createInterface } from 'node:readline';
import { PLUGIN_API_VERSION, type PluginManifest } from '../types.js';
import { currentPlatform } from '../store.js';
-import { publishTool, unpublishPlugin } from '../tool-bridge.js';
+import { PLUGIN_IMAGE_TYPES, publishTool, toolContent, unpublishPlugin } from '../tool-bridge.js';
import type { PluginRuntime, RuntimeDeps } from './types.js';
export const OUT_OF_PROCESS = {
@@ -187,12 +187,20 @@ export class OutOfProcessRuntime implements PluginRuntime {
private async callTool(name: string, args: Record<string, unknown>, signal: AbortSignal, timeoutMs: number): Promise<unknown> {
if (!this.ready) throw new Error('the plugin process is not running');
const res = (await this.request('tools/call', { name, arguments: args }, timeoutMs + 1000, signal)) as {
- content?: Array<{ type: string; text?: string }>;
+ content?: Array<{ type: string; text?: string; data?: string; mimeType?: string }>;
isError?: boolean;
structuredContent?: unknown;
};
- const text = (res?.content ?? []).map((c) => (c.type === 'text' ? c.text ?? '' : `[${c.type} content]`)).join('\n');
+ const parts = res?.content ?? [];
+ const isImage = (c: (typeof parts)[number]) => c.type === 'image' && typeof c.data === 'string' && PLUGIN_IMAGE_TYPES.has(c.mimeType ?? '');
+ const images = parts.filter(isImage).map((c) => ({ data: c.data!, mimeType: c.mimeType! }));
+ const text = parts
+ .filter((c) => !isImage(c))
+ .map((c) => (c.type === 'text' ? c.text ?? '' : `[${c.type} content]`))
+ .join('\n');
if (res?.isError) throw new Error(text || 'the tool reported an error');
+ // Plugin API 1.2: images (screenshots) go to the model as images, not text.
+ if (images.length) return toolContent(text, images);
return text || (res?.structuredContent !== undefined ? res.structuredContent : 'Done.');
}
diff --git a/src/plugins/tool-bridge.test.ts b/src/plugins/tool-bridge.test.ts
new file mode 100644
index 00000000..eed99599
--- /dev/null
+++ b/src/plugins/tool-bridge.test.ts
@@ -0,0 +1,62 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import type { PermissionManager } from '../capabilities/permissions.js';
+import { getPluginTools, publishTool, resetToolBridge, setPluginImagesAllowed, toolContent } from './tool-bridge.js';
+
+const PNG = 'iVBORw0KGgo=';
+
+function liveTool(result: unknown) {
+ return {
+ pluginId: 'shots',
+ pluginName: 'Shots',
+ name: 'look',
+ description: 'Take a screenshot',
+ inputSchema: { type: 'object', properties: {} },
+ readOnly: true,
+ timeoutMs: 5000,
+ invoke: async () => result,
+ };
+}
+
+async function run(result: unknown, callId = 'call-1') {
+ publishTool(liveTool(result));
+ const t = getPluginTools({} as PermissionManager)['shots__look'] as any;
+ const output = await t.execute({}, { toolCallId: callId, messages: [] });
+ const model = await t.toModelOutput({ toolCallId: callId, input: {}, output });
+ return { output, model };
+}
+
+describe('plugin tool images (plugin API 1.2)', () => {
+ afterEach(() => {
+ resetToolBridge();
+ setPluginImagesAllowed(true);
+ });
+
+ it('keeps images out of the text result and gives them to the model', async () => {
+ const { output, model } = await run(toolContent('Screen 1 of 1', [{ data: PNG, mimeType: 'image/png' }]));
+ expect(output).toBe('Screen 1 of 1\n[1 image attached]');
+ expect(output).not.toContain(PNG);
+ expect(model).toEqual({
+ type: 'content',
+ value: [{ type: 'text', text: output }, { type: 'image-data', data: PNG, mediaType: 'image/png' }],
+ });
+ });
+
+ it('plain text results stay text', async () => {
+ const { output, model } = await run('done');
+ expect(output).toBe('done');
+ expect(model).toEqual({ type: 'text', value: 'done' });
+ });
+
+ it('drops unsupported image types and caps the count', async () => {
+ const many = Array.from({ length: 6 }, () => ({ data: PNG, mimeType: 'image/png' }));
+ const { model } = await run(toolContent('x', [{ data: PNG, mimeType: 'image/tiff' }, ...many]));
+ expect(model.value.filter((p: { type: string }) => p.type === 'image-data')).toHaveLength(4);
+ });
+
+ it('tells a text-only model the image was left out', async () => {
+ setPluginImagesAllowed(false);
+ const { model } = await run(toolContent('Screen', [{ data: PNG, mimeType: 'image/png' }]));
+ expect(model.type).toBe('text');
+ expect(model.value).toContain("can't view images");
+ });
+});
diff --git a/src/plugins/tool-bridge.ts b/src/plugins/tool-bridge.ts
index 8a8250b2..fa5d670d 100644
--- a/src/plugins/tool-bridge.ts
+++ b/src/plugins/tool-bridge.ts
@@ -35,6 +35,54 @@ export interface PluginCommandHandler {
}
const MAX_RESULT_CHARS = 100_000;
+
+/** Image types a plugin tool may return (plugin API 1.2), e.g. screenshots. */
+export const PLUGIN_IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif']);
+/** Images per result, and base64 characters per image (~6 MB decoded). */
+const MAX_IMAGES = 4;
+const MAX_IMAGE_CHARS = 8_000_000;
+
+export interface PluginImage {
+ data: string;
+ mimeType: string;
+}
+
+const CONTENT = Symbol('mercury.pluginToolContent');
+
+/** A tool result with images for the model, besides its text. */
+export interface PluginToolContent {
+ [CONTENT]: true;
+ text: string;
+ images: PluginImage[];
+}
+
+export function toolContent(text: string, images: PluginImage[]): PluginToolContent {
+ return { [CONTENT]: true, text, images };
+}
+
+function isToolContent(v: unknown): v is PluginToolContent {
+ return !!v && typeof v === 'object' && (v as Record<symbol, unknown>)[CONTENT] === true;
+}
+
+/**
+ * Images waiting to be attached to their tool result, by tool call id.
+ * execute() returns text only (so logs, history and learning never carry
+ * base64); toModelOutput() adds the images when the result goes to the model.
+ * Bounded: a result the SDK never converts can't leak memory.
+ */
+const pendingImages = new Map<string, PluginImage[]>();
+/** Whether the model in use can take images (set by the agent before each provider call). */
+let imagesAllowed = true;
+
+export function setPluginImagesAllowed(allowed: boolean): void {
+ imagesAllowed = allowed;
+}
+const MAX_PENDING = 32;
+
+function holdImages(callId: string, images: PluginImage[]): void {
+ pendingImages.set(callId, images);
+ while (pendingImages.size > MAX_PENDING) pendingImages.delete(pendingImages.keys().next().value as string);
+}
const TOOL_NAME_RE = /^([a-z][a-z0-9-]{1,30}[a-z0-9])__([a-z][a-z0-9_]{0,29})$/;
const liveTools = new Map<string, LiveTool>();
@@ -130,6 +178,16 @@ function wrap(t: LiveTool, permissions: PermissionManager): Tool {
return tool<Record<string, unknown>, string>({
description: `[Plugin: ${t.pluginName}] ${t.description}`,
inputSchema: jsonSchema<Record<string, unknown>>(t.inputSchema as Parameters<typeof jsonSchema>[0]),
+ toModelOutput: ({ toolCallId, output }) => {
+ const text = typeof output === 'string' ? output : stringifyResult(output);
+ const images = pendingImages.get(toolCallId);
+ if (!images?.length) return { type: 'text', value: text };
+ if (!imagesAllowed) return { type: 'text', value: `${text}\n(The current model can't view images, so the attached image was left out. Say so if it matters.)` };
+ return {
+ type: 'content',
+ value: [{ type: 'text', text }, ...images.map((i) => ({ type: 'image-data' as const, data: i.data, mediaType: i.mimeType }))],
+ };
+ },
execute: async (input, options) => {
const args = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;
if (!t.readOnly) {
@@ -151,6 +209,12 @@ function wrap(t: LiveTool, permissions: PermissionManager): Tool {
try {
const result = await Promise.race([Promise.resolve().then(() => t.invoke(args, ac.signal)), timeout]);
outcomeSink(t.pluginId, { ok: true });
+ if (isToolContent(result)) {
+ const images = result.images.filter((i) => PLUGIN_IMAGE_TYPES.has(i.mimeType) && i.data.length <= MAX_IMAGE_CHARS).slice(0, MAX_IMAGES);
+ if (images.length && options?.toolCallId) holdImages(options.toolCallId, images);
+ const note = images.length ? `\n[${images.length} image${images.length > 1 ? 's' : ''} attached]` : '';
+ return stringifyResult(`${result.text || 'Done.'}${note}`);
+ }
return stringifyResult(result);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
@@ -181,6 +245,7 @@ export function getPluginTools(permissions: PermissionManager, opts: { readOnlyO
/** Test hook. */
export function resetToolBridge(): void {
+ pendingImages.clear();
liveTools.clear();
liveCommands.clear();
outcomeSink = () => {};
diff --git a/src/plugins/types.ts b/src/plugins/types.ts
index 07afe5e8..9aa8de64 100644
--- a/src/plugins/types.ts
+++ b/src/plugins/types.ts
@@ -24,7 +24,7 @@ export const MANIFEST_VERSION = 1 as const;
* Minor bumps only add; a major bump is a breaking change and the previous
* major stays supported for at least two Mercury minor releases.
*/
-export const PLUGIN_API_VERSION = '1.1.0';
+export const PLUGIN_API_VERSION = '1.2.0';
export const PLUGIN_ID_RE = /^[a-z][a-z0-9-]{1,30}[a-z0-9]$/;
/** Tool and command names a plugin declares (before namespacing). */
@@ -181,6 +181,12 @@ export const manifestSchema = z.object({
network: z.array(z.string().min(1).max(253)).max(32).default([]),
/** Secret names from ~/.mercury/.env the plugin may read. Nothing else is visible to it. */
secrets: z.array(z.string().regex(SECRET_NAME_RE)).max(16).default([]),
+ /**
+ * Plugin API 1.2: the plugin controls this computer (sees the screen,
+ * moves the mouse and types). Shown to the owner as a warning in
+ * /plugins info; the plugin must also ask for consent in its own setup.
+ */
+ desktop: z.boolean().optional(),
/**
* Secrets the plugin works without, and what they unlock, e.g.
* { "OPENAI_API_KEY": "Voice calls" }. A missing one is reported to the