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: screenshots sized and routed per model (ADR-043); device token shown whole

Salman Qureshi8e6e8c109716
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9aecefed..57b61ba1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,20 @@
## Unreleased
+### Optimus: screenshots per model
+- **Cheaper screenshots.** Optimus took every screenshot at 1280×800, whatever the model. Mercury now asks for the size each model is billed least for:
+ - Claude and OpenAI: 1024×640, about 30–35% fewer image tokens.
+ - Gemini: 768×480, about 75% fewer.
+ - Open vision models: 896×560.
+
+ Optimus 0.5.2 follows this, and the model still clicks in the picture it saw. Use `zoom` for a closer look at small text. Set `MERCURY_SCREENSHOT_BOX=1280x800` to keep one size for every model.
+- **Vision models on OpenAI-compatible APIs can see the screen.** Before, a screenshot reached the model only on Claude and the OpenAI API. OpenRouter, LiteLLM, Mercury Cloud, Ollama and LM Studio vision models got no image at all and used Optimus blind. The screenshot now follows the tool result as an image.
+- **Models that can't see images** no longer cause a screenshot to be taken. With Optimus 0.5.2, `look` and `act` say which window is in front instead.
+- Vision models named "…-vl" (`nemotron-…-vl`, `kimi-vl`, InternVL, MiniCPM-V and others) are recognised as seeing images.
+
+### Fixed
+- The device token from `/server token` showed cut off on a terminal. The menu that shows it counted the token as one screen row while the terminal wrapped it over several, so redrawing the menu overwrote part of it. It is now shown whole.
+
### Video and music
- **Mercury makes videos and music.** Ask in your own words, use the desktop chat box's **Create** menu (it replaces the Image button; image, video or music), or type `/video <the shot>` (`--portrait`, `--seconds 6`) or `/music <style, mood, lyrics>` (`--instrumental`, `--seconds 60`).
- They take a minute or a few. Mercury says it has started and posts the clip or song into the same chat when it's ready, even if you've moved on. The desktop app shows it as a new message with a player, Telegram and WhatsApp receive the file, and the terminal shows where it was saved.
diff --git a/DECISIONS.md b/DECISIONS.md
index bd28b72b..0e67db8b 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -601,3 +601,43 @@
- **Verified live:** ElevenLabs Music (5 s, 4.2 s).
- **Shapes taken from the current docs, not confirmed live:** the Gemini Omni and Lyria request shapes (the test key is on the free tier, with no quota for them).
- **Implemented to the OpenAI shape, not exercised live:** the gateway Videos API.
+
+## ADR-043: Screenshots sized and routed per model
+
+- **Context:**
+ - **Optimus captured every screenshot the same way:** JPEG at quality 80, fitted to 1280×800, returned as base64 MCP image content.
+ - **Mercury passed the screenshot on only when the model saw images and its provider took images inside tool results** (Anthropic, OpenAI Responses). Every other vision model got none:
+ - OpenAI-compatible chat: OpenRouter, LiteLLM, Mercury Cloud, Ollama, LM Studio.
+ - The owner's `nemotron-3.5-super-vl`, for example, drove the screen blind.
+ - **Image pricing differs by family,** so one size overpays:
+ - Claude: about w·h/750 tokens.
+ - OpenAI: 85 + 170 per 512-px tile.
+ - Gemini: 258 per 768-px tile.
+ - Qwen-style models: 28-px patches.
+- **Decision:**
+ - **`core/vision-profile.ts` decides, per provider attempt, the route and the box.**
+ - Routes:
+ - `tool-result`: the provider takes images in tool results.
+ - `user-message`: the model sees images, but its API takes them only from the user.
+ - `none`: the model can't see images.
+ - Boxes by family: Claude and OpenAI 1024×640, Gemini 768×480, patch-based vision models 896×560, default 1024×640. `MERCURY_SCREENSHOT_BOX` overrides.
+ - The agent sets both per turn (turn-scoped, ADR-037) through `setToolVision`.
+ - **Size negotiation through the tool contract.**
+ - A plugin tool that takes screenshots declares a `mercury_screenshot` input parameter, or `screenshots: true` in its manifest.
+ - Mercury strips the parameter from the schema the model sees, and fills it on every call: `{ include, max_width, max_height }`.
+ - The plugin resizes the capture itself, so model coordinates map back exactly. Resizing in Mercury would break the mapping.
+ - Negotiating through the schema rather than a new manifest field keeps every mix of versions working. Older Mercury validates manifests strictly and would reject a new field.
+ - **Route `user-message` (payload-policy step 4):**
+ - The tool result says the screenshot follows.
+ - In `prepareStep`, the images held for each call are added as a user message right after that run of tool messages.
+ - Only the newest `KEEP_IMAGES` (2) are kept as images; older ones become the one-line note. The conversation the SDK keeps is untouched.
+ - Verified on the wire with the OpenAI chat converter: `image_url` in the user message after the tool message.
+ - **Route `none`:** Optimus 0.5.2 takes no capture. It sets the coordinate frame from the display size and reports the active window in text.
+ - **Vision detection:** now also recognises `-vl` names and other open vision families.
+- **Consequences:**
+ - **Fewer image tokens on every look/act:** about 35% on Claude, 30% on OpenAI, 75% on Gemini (estimates from the published rules).
+ - **More models can drive the screen:** vision models behind OpenAI-compatible APIs can now use Optimus.
+ - **Version mixes:**
+ - Optimus 0.5.1 with this Mercury: the route improvements apply, at the old size.
+ - Optimus 0.5.2 with an older Mercury: it uses its 1280×800 default.
+ - **Not exercised live:** the Optimus capture path. Its Rust changes are covered by unit tests (box parsing and fitting).
diff --git a/plugins/optimus/companion/Cargo.lock b/plugins/optimus/companion/Cargo.lock
index 7e49c6d9..5f158c01 100644
--- a/plugins/optimus/companion/Cargo.lock
+++ b/plugins/optimus/companion/Cargo.lock
@@ -1280,7 +1280,7 @@ dependencies = [
[[package]]
name = "mercury-optimus"
-version = "0.5.1"
+version = "0.5.2"
dependencies = [
"base64 0.22.1",
"block2",
diff --git a/plugins/optimus/companion/Cargo.toml b/plugins/optimus/companion/Cargo.toml
index 4fea7404..d4b46484 100644
--- a/plugins/optimus/companion/Cargo.toml
+++ b/plugins/optimus/companion/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "mercury-optimus"
-version = "0.5.1"
+version = "0.5.2"
edition = "2024"
rust-version = "1.94"
description = "Optimus: full computer control for Mercury (screen, mouse, keyboard, apps, voice)"
diff --git a/plugins/optimus/companion/src/main.rs b/plugins/optimus/companion/src/main.rs
index ed9e2873..dc499247 100644
--- a/plugins/optimus/companion/src/main.rs
+++ b/plugins/optimus/companion/src/main.rs
@@ -193,12 +193,29 @@ fn action_schema() -> Value {
},
"say": { "type": "string", "description": "A few words saying what this does, present tense ('Opening the compose box', 'Typing your post'). Spoken live when the owner is talking to you." },
"screenshot": { "type": "boolean", "description": "Return a screenshot afterwards (default true)." },
- "settle_ms": { "type": "integer", "minimum": 0, "maximum": 5000, "description": "Wait before that screenshot (default 500)." }
+ "settle_ms": { "type": "integer", "minimum": 0, "maximum": 5000, "description": "Wait before that screenshot (default 500)." },
+ "mercury_screenshot": screenshot_param()
},
"required": ["actions"]
})
}
+/// The screenshot size Mercury asks for, per the model in use (ADR-043).
+/// Declaring it is how Mercury knows this tool takes screenshots: it hides
+/// the parameter from the model and fills it in. An older Mercury shows it
+/// as an optional parameter the model can leave out.
+fn screenshot_param() -> Value {
+ json!({
+ "type": "object",
+ "description": "Set by Mercury; leave it out.",
+ "properties": {
+ "include": { "type": "boolean" },
+ "max_width": { "type": "integer" },
+ "max_height": { "type": "integer" }
+ }
+ })
+}
+
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, paste, press keys, scroll, drag, draw freehand. Returns a fresh screenshot. Pass `actions` as a list. To write text (posts, emails, articles) click the box, then use type: it types key by key like a person, so it works in every editor (up to 3,000 characters per type action; longer text in parts). Use paste only if typing fails. \"Sent\" means the input was sent, not that it worked: check the returned screenshot, and before telling the owner a task is done, look and confirm the result. FAILED means nothing (or not everything) happened. 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."),
@@ -215,7 +232,8 @@ fn tools() -> Value {
"type": "object",
"properties": {
"display": { "type": "integer", "minimum": 1 },
- "zoom": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 }
+ "zoom": { "type": "array", "items": { "type": "number" }, "minItems": 4, "maxItems": 4 },
+ "mercury_screenshot": screenshot_param()
}
}),
"act" | "act_consequential" => action_schema(),
diff --git a/plugins/optimus/companion/src/ops.rs b/plugins/optimus/companion/src/ops.rs
index a08d3d3d..b0ae5cff 100644
--- a/plugins/optimus/companion/src/ops.rs
+++ b/plugins/optimus/companion/src/ops.rs
@@ -18,9 +18,47 @@ 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).
+/// Screenshots fit in this box unless Mercury asks for another
+/// (`mercury_screenshot`, sized for the model in use: ADR-043).
const MAX_W: u32 = 1280;
const MAX_H: u32 = 800;
+/// Bounds on a box Mercury asks for.
+const MIN_BOX: u32 = 320;
+const MAX_BOX: u32 = 2560;
+
+/// What Mercury asked for this call: the box to fit screenshots in, and
+/// whether to take one at all (a model that can't see images gets none).
+#[derive(Clone, Copy, Debug, PartialEq)]
+struct ShotRequest {
+ include: bool,
+ max_w: u32,
+ max_h: u32,
+}
+
+impl ShotRequest {
+ fn from_args(args: &Value) -> Self {
+ let r = args.get("mercury_screenshot");
+ let dim = |k: &str, d: u32| {
+ r.and_then(|v| v.get(k)).and_then(Value::as_u64).map(|n| (n as u32).clamp(MIN_BOX, MAX_BOX)).unwrap_or(d)
+ };
+ ShotRequest {
+ include: r.and_then(|v| v.get("include")).and_then(Value::as_bool) != Some(false),
+ max_w: dim("max_width", MAX_W),
+ max_h: dim("max_height", MAX_H),
+ }
+ }
+
+ fn as_json(self) -> Value {
+ json!({ "include": self.include, "max_width": self.max_w, "max_height": self.max_h })
+ }
+}
+
+/// The size a w×h picture has once fitted in the box (never enlarged).
+fn fitted_size(w: u32, h: u32, max_w: u32, max_h: u32) -> (u32, u32) {
+ let (w, h) = (w.max(1), h.max(1));
+ let scale = (max_w as f64 / w as f64).min(max_h as f64 / h as f64).min(1.0);
+ (((w as f64 * scale).round() as u32).max(1), ((h as f64 * scale).round() as u32).max(1))
+}
const JPEG_QUALITY: u8 = 80;
/// The user moving the mouse this far during a batch stops Optimus.
const TAKEOVER_PX: i32 = 12;
@@ -151,6 +189,21 @@ impl Ops {
mon.width().map_err(err)?,
mon.height().map_err(err)?,
);
+ let req = ShotRequest::from_args(args);
+
+ // A model that can't see images: no capture, but the frame (for
+ // coordinates) and what's in front, in words.
+ if !req.include {
+ let (iw, ih) = fitted_size(w, h, req.max_w, req.max_h);
+ let shot = Shot { monitor: idx, x, y, w, h, img_w: iw, img_h: ih };
+ self.shot = Some(shot);
+ let mut text = format!("Display {} of {count} ({iw}×{ih}); no screenshot taken (this model can't see images).", idx + 1);
+ if let Some(f) = focused_window() {
+ text.push_str(&format!(" Active window: {f}."));
+ }
+ return Ok(json!({ "text": text }));
+ }
+
let full = {
let _hidden = crate::overlay::capture_guard();
mon.capture_image().map_err(|e| capture_error(&e.to_string()))?
@@ -170,7 +223,7 @@ impl Ops {
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);
+ let (img, iw, ih) = fit(crop, req.max_w, req.max_h);
return Ok(json!({
"text": format!(
"Zoom on [{}, {}, {}, {}] of the last screenshot, shown at {iw}×{ih}. Coordinates for actions still refer to the full screenshot.",
@@ -180,7 +233,7 @@ impl Ops {
}));
}
- let (img, iw, ih) = fit(full);
+ let (img, iw, ih) = fit(full, req.max_w, req.max_h);
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));
@@ -252,13 +305,17 @@ impl Ops {
text = format!("FAILED: {s} {text}");
}
text.push_str(" This only means the input was sent: check the screenshot below to see whether it actually worked before saying so.");
+ let req = ShotRequest::from_args(args);
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!({})) {
+ // The same size (or none) Mercury asked for on this call.
+ match self.look(&json!({ "mercury_screenshot": req.as_json() })) {
Ok(v) => {
text.push_str("\nScreen now: ");
text.push_str(v["text"].as_str().unwrap_or(""));
- out["image"] = v["image"].clone();
+ if !v["image"].is_null() {
+ out["image"] = v["image"].clone();
+ }
}
Err(e) => text.push_str(&format!("\n(No screenshot: {e})")),
}
@@ -497,10 +554,8 @@ fn err(e: impl std::fmt::Display) -> 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));
+fn fit(img: RgbaImage, max_w: u32, max_h: u32) -> (Value, u32, u32) {
+ let (nw, nh) = fitted_size(img.width(), img.height(), max_w, max_h);
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));
@@ -828,12 +883,29 @@ mod tests {
#[test]
fn fit_keeps_aspect() {
- let (_, w, h) = fit(RgbaImage::new(2880, 1800));
+ let (_, w, h) = fit(RgbaImage::new(2880, 1800), MAX_W, MAX_H);
assert_eq!((w, h), (1280, 800));
- let (_, w, h) = fit(RgbaImage::new(3840, 2160));
+ let (_, w, h) = fit(RgbaImage::new(3840, 2160), MAX_W, MAX_H);
assert_eq!((w, h), (1280, 720));
- let (_, w, h) = fit(RgbaImage::new(800, 600));
+ let (_, w, h) = fit(RgbaImage::new(800, 600), MAX_W, MAX_H);
assert_eq!((w, h), (800, 600));
+ // A smaller box from Mercury (a Gemini model): 768×480.
+ let (_, w, h) = fit(RgbaImage::new(2880, 1800), 768, 480);
+ assert_eq!((w, h), (768, 480));
+ }
+
+ #[test]
+ fn shot_request_from_mercury() {
+ // No hint (an older Mercury): the old box, with a screenshot.
+ assert_eq!(ShotRequest::from_args(&json!({})), ShotRequest { include: true, max_w: MAX_W, max_h: MAX_H });
+ let r = ShotRequest::from_args(&json!({ "mercury_screenshot": { "include": true, "max_width": 1024, "max_height": 640 } }));
+ assert_eq!(r, ShotRequest { include: true, max_w: 1024, max_h: 640 });
+ // Bounded either way, and "include: false" means no capture.
+ let r = ShotRequest::from_args(&json!({ "mercury_screenshot": { "include": false, "max_width": 10, "max_height": 99999 } }));
+ assert_eq!(r, ShotRequest { include: false, max_w: MIN_BOX, max_h: MAX_BOX });
+ // What the model saw keeps its aspect: a 2880×1800 display in a 1024×640 box.
+ assert_eq!(fitted_size(2880, 1800, 1024, 640), (1024, 640));
+ assert_eq!(fitted_size(3840, 2160, 1024, 640), (1024, 576));
}
}
diff --git a/plugins/optimus/mercury-plugin.template.json b/plugins/optimus/mercury-plugin.template.json
index 3c326a57..ccb27ead 100644
--- a/plugins/optimus/mercury-plugin.template.json
+++ b/plugins/optimus/mercury-plugin.template.json
@@ -2,7 +2,7 @@
"manifestVersion": 1,
"id": "optimus",
"name": "Optimus",
- "version": "0.5.1",
+ "version": "0.5.2",
"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",
diff --git a/src/capabilities/tool-images.ts b/src/capabilities/tool-images.ts
index 785f9583..1b797670 100644
--- a/src/capabilities/tool-images.ts
+++ b/src/capabilities/tool-images.ts
@@ -1,4 +1,5 @@
import { ScopedValue } from '../utils/turn-scope.js';
+import type { ImageRoute, ScreenshotBox, VisionProfile } from '../core/vision-profile.js';
export interface ToolImage {
data: string;
@@ -18,20 +19,51 @@ export const MAX_TOOL_IMAGE_CHARS = 8_000_000;
const MAX_PENDING = 32;
const pendingImages = new Map<string, ToolImage[]>();
-/** Whether the model of the calling turn can see images (per turn once claimed, ADR-037). */
-const imagesAllowed = new ScopedValue(true);
+/**
+ * How the calling turn's model takes images, and the screenshot size it is
+ * best served by (ADR-043; per turn once claimed, ADR-037).
+ */
+const vision = new ScopedValue<Pick<VisionProfile, 'route' | 'box'>>({ route: 'tool-result', box: { width: 1280, height: 800 } });
+export function setToolVision(profile: Pick<VisionProfile, 'route' | 'box'>): void {
+ vision.set({ route: profile.route, box: profile.box });
+}
+
+/** Older callers: a yes/no for "the model sees images in tool results". */
export function setToolImagesAllowed(allowed: boolean): void {
- imagesAllowed.set(allowed);
+ vision.set({ ...vision.get(), route: allowed ? 'tool-result' : 'none' });
}
export function toolImagesAllowed(): boolean {
- return imagesAllowed.get();
+ return vision.get().route !== 'none';
+}
+
+export function toolImageRoute(): ImageRoute {
+ return vision.get().route;
+}
+
+/**
+ * What a screenshot-taking tool is asked for (passed as `mercury_screenshot`
+ * to plugin tools that declare `screenshots: true`): the size, and whether
+ * to take one at all.
+ */
+export function screenshotRequest(): { include: boolean; max_width: number; max_height: number } {
+ const { route, box } = vision.get();
+ return { include: route !== 'none', max_width: box.width, max_height: box.height };
}
-/** Give the calling turn its own "model sees images" switch (no-op outside a turn). */
+export function screenshotBox(): ScreenshotBox {
+ return vision.get().box;
+}
+
+/** Give the calling turn its own image settings (no-op outside a turn). */
export function claimToolImagesForTurn(): void {
- imagesAllowed.claim();
+ vision.claim();
+}
+
+/** Images a tool call returned, for showing them after its result (route user-message). */
+export function heldImages(toolCallId: string): ToolImage[] | undefined {
+ return pendingImages.get(toolCallId);
}
export function usableImages(images: ToolImage[]): ToolImage[] {
@@ -53,9 +85,14 @@ export function attachedImagesNote(count: number): string {
export function toolOutputWithImages(toolCallId: string, text: string): ToolImageOutput {
const images = pendingImages.get(toolCallId);
if (!images?.length) return { type: 'text', value: text };
- if (!imagesAllowed.get()) {
+ const route = vision.get().route;
+ if (route === 'none') {
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.)` };
}
+ if (route === 'user-message') {
+ // This API takes images only from the user: the screenshot follows as its own message (payload-policy.ts).
+ return { type: 'text', value: `${text}\n(The screenshot follows as an image.)` };
+ }
return {
type: 'content',
value: [{ type: 'text', text }, ...images.map((image) => ({ type: 'image-data' as const, data: image.data, mediaType: image.mimeType }))],
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 910decfb..1ceea08a 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -115,7 +115,8 @@ import { handleBotsCommand as handleBotsCommandImpl } from './commands/bots-comm
import { modelSeesImages, withAttachments } from './attachments.js';
import { attachmentRefs } from '../web/api/uploads.js';
import { AlertGate } from './alert-gate.js';
-import { setPluginImagesAllowed } from '../plugins/tool-bridge.js';
+import { setToolVision } from '../capabilities/tool-images.js';
+import { visionProfile } from './vision-profile.js';
import { handleCallCommand } from '../plugins/call-schedule.js';
import { handlePluginsCommand, tryPluginCommand, hasPluginDialog, answerPluginDialog } from '../plugins/commands.js';
import { handleChatCommand as handleChatCommandImpl } from './commands/chat-command.js';
@@ -4496,7 +4497,11 @@ export class Agent {
// get plain text.
// Photos and PDFs from the chat go to models that can take them.
const seesImages = modelSeesImages(provider.name, provider.getModel(), provider.seesImages);
- setPluginImagesAllowed(seesImages && provider.supportsToolResultImages());
+ // How screenshots reach this model, and at what size (ADR-043): inside
+ // tool results, as an image message after them, or not at all.
+ const vision = visionProfile({ model: provider.getModel(), seesImages, toolResultImages: provider.supportsToolResultImages() });
+ setToolVision(vision);
+ logger.debug({ provider: provider.name, model: provider.getModel(), route: vision.route, box: vision.box }, 'Screenshot route for this model');
const providerMessages = withAttachments(
deepseekProviderOptions ? withReasoningParts(messages) : messages,
msg,
diff --git a/src/core/attachments.ts b/src/core/attachments.ts
index 49ca6cd9..01571965 100644
--- a/src/core/attachments.ts
+++ b/src/core/attachments.ts
@@ -39,6 +39,8 @@ export function modelSeesImages(provider: string, model: string, declared?: bool
const m = model.toLowerCase();
if (provider === 'deepseek') return false;
if (/gpt-4o|gpt-4\.1|gpt-5|chatgpt-4o|\bo[134](-|$)|claude|gemini|pixtral|llava|qwen.*vl|vision|grok-(2-vision|4)|llama-?4|mistral-(medium|small)-3|gemma-?3/.test(m)) return true;
+ // "-vl" / "_vl" / ":vl" model names (nemotron-…-vl, kimi-vl, glm-4.5v…) and other open vision families.
+ if (/(^|[-_.:/])vl($|[-_.:/])|internvl|minicpm-v|moondream|molmo|glm-4(\.\d)?v\b|ui-tars|holo/.test(m)) return true;
return false;
}
diff --git a/src/core/payload-policy.ts b/src/core/payload-policy.ts
index 3ef8dcf4..2300002b 100644
--- a/src/core/payload-policy.ts
+++ b/src/core/payload-policy.ts
@@ -13,6 +13,9 @@
* paying for it again (with the system prompt's marker: 3 of the 4
* breakpoints Anthropic allows). Other providers cache identical
* prefixes on their own and ignore the marker.
+ * 4. Screenshots for models whose API takes images only from the user
+ * (ADR-043, route "user-message"): each tool call's images follow its
+ * results as an image message, under the same keep-the-newest rule.
*/
export const KEEP_IMAGES = 2;
@@ -92,12 +95,67 @@ export function isAnthropicModel(model: unknown): boolean {
return typeof provider === 'string' && provider.startsWith('anthropic');
}
+/** Marks the image messages added for route "user-message" (so a later step recognises them). */
+export const TOOL_IMAGE_LEAD = '[Screenshot from the tool call above';
+
+interface HeldImage { data: string; mimeType: string }
+
+/**
+ * Route "user-message": after each run of tool messages, the images their
+ * calls returned, as a user message (newest KEEP_IMAGES calls only; older
+ * ones get a one-line note). The conversation the SDK keeps is untouched.
+ */
+function withToolImageMessages(list: Message[], imagesFor: (toolCallId: string) => HeldImage[] | undefined): Message[] {
+ // Which calls have images, oldest first.
+ const calls: string[] = [];
+ for (const m of list) {
+ if (m.role !== 'tool' || !Array.isArray(m.content)) continue;
+ for (const p of m.content as Part[]) {
+ const id = typeof p?.toolCallId === 'string' ? p.toolCallId : undefined;
+ if (p?.type === 'tool-result' && id && imagesFor(id)?.length) calls.push(id);
+ }
+ }
+ if (!calls.length) return list;
+ const keep = new Set(calls.slice(-KEEP_IMAGES));
+ const out: Message[] = [];
+ for (let i = 0; i < list.length; i++) {
+ const m = list[i];
+ out.push(m);
+ if (m.role !== 'tool' || list[i + 1]?.role === 'tool') continue;
+ // The end of a run of tool messages: what its calls showed.
+ const parts: Part[] = [];
+ let noted = false;
+ for (let j = i; j >= 0 && list[j].role === 'tool'; j--) {
+ for (const p of (Array.isArray(list[j].content) ? list[j].content : []) as Part[]) {
+ const id = typeof p?.toolCallId === 'string' ? p.toolCallId : undefined;
+ const images = id ? imagesFor(id) : undefined;
+ if (p?.type !== 'tool-result' || !id || !images?.length) continue;
+ if (keep.has(id)) {
+ parts.unshift(
+ { type: 'text', text: `${TOOL_IMAGE_LEAD} (${String(p.toolName ?? 'tool')})]` },
+ ...images.map((img) => ({ type: 'image', image: img.data, mediaType: img.mimeType })),
+ );
+ } else if (!noted) {
+ parts.unshift({ type: 'text', text: IMAGE_NOTE });
+ noted = true;
+ }
+ }
+ }
+ if (parts.length) out.push({ role: 'user', content: parts });
+ }
+ return out;
+}
+
/**
* The messages one step sends. Returns the input array itself when nothing
* needs to change, so a step without images or oversize results costs nothing.
*/
-export function shapeStepMessages<T>(messages: readonly T[], opts: { anthropicCache?: boolean } = {}): T[] {
- const list = messages as unknown as Message[];
+export function shapeStepMessages<T>(
+ messages: readonly T[],
+ opts: { anthropicCache?: boolean; toolImages?: { route: 'tool-result' | 'user-message' | 'none'; imagesFor: (toolCallId: string) => HeldImage[] | undefined } } = {},
+): T[] {
+ const original = messages as unknown as Message[];
+ const list = opts.toolImages?.route === 'user-message' ? withToolImageMessages(original, opts.toolImages.imagesFor) : original;
// Which tool results keep their images: the newest KEEP_IMAGES carrying any.
const imageResults: Array<[number, number]> = [];
list.forEach((m, mi) => {
@@ -136,5 +194,6 @@ export function shapeStepMessages<T>(messages: readonly T[], opts: { anthropicCa
changed = true;
}
}
+ // `list` is already a new array when screenshots were added (route user-message).
return (changed ? shaped : list) as unknown as T[];
}
diff --git a/src/core/tool-discovery.ts b/src/core/tool-discovery.ts
index 8bb959c7..b2964c27 100644
--- a/src/core/tool-discovery.ts
+++ b/src/core/tool-discovery.ts
@@ -1,6 +1,7 @@
/** Optional per-turn schema discovery for owner-installed plugin and MCP tools. */
import { tool, zodSchema, type ModelMessage, type Tool } from 'ai';
import { isAnthropicModel, shapeStepMessages } from './payload-policy.js';
+import { heldImages, toolImageRoute } from '../capabilities/tool-images.js';
import { z } from 'zod';
export const DISCOVER_TOOLS = 'discover_tools';
@@ -109,7 +110,9 @@ export class ToolDiscovery {
// (when asked), and the payload policy (ADR-039) — old screenshots out,
// oversize results capped, Anthropic conversation cache markers.
prepareStep: ({ stepNumber, messages, model }: { stepNumber: number; messages?: ModelMessage[]; model?: unknown }) => {
- const shaped = messages ? shapeStepMessages(messages, { anthropicCache: isAnthropicModel(model) }) : messages;
+ const shaped = messages
+ ? shapeStepMessages(messages, { anthropicCache: isAnthropicModel(model), toolImages: { route: toolImageRoute(), imagesFor: heldImages } })
+ : messages;
return {
...(discover ? { activeTools: active() } : {}),
...(options.forceFirstTool && stepNumber === 0 ? {
diff --git a/src/core/vision-profile.test.ts b/src/core/vision-profile.test.ts
new file mode 100644
index 00000000..dd9127c4
--- /dev/null
+++ b/src/core/vision-profile.test.ts
@@ -0,0 +1,134 @@
+import { describe, expect, it } from 'vitest';
+import { createOpenAI } from '@ai-sdk/openai';
+import { generateText } from 'ai';
+import { estimateImageTokens, visionFamily, visionProfile } from './vision-profile.js';
+import { KEEP_IMAGES, TOOL_IMAGE_LEAD, shapeStepMessages } from './payload-policy.js';
+import { modelSeesImages } from './attachments.js';
+import { screenshotContract } from '../plugins/tool-bridge.js';
+
+/**
+ * Screenshots per model (ADR-043): the size each family is billed least
+ * for, how the image reaches the model, and none for a model that can't see.
+ */
+describe('vision profile', () => {
+ it.each([
+ ['claude-opus-5-5', 'claude', 1024, 640],
+ ['gpt-5.2', 'openai', 1024, 640],
+ ['gemini-3.1-pro', 'gemini', 768, 480],
+ ['nemotron-3.5-super-vl:free', 'patch', 896, 560],
+ ['qwen2.5-vl-72b', 'patch', 896, 560],
+ ['some-new-model', 'default', 1024, 640],
+ ])('%s → %s, %ix%i', (model, family, w, h) => {
+ const p = visionProfile({ model, seesImages: true, toolResultImages: true }, {});
+ expect(p.family).toBe(family);
+ expect(p.box).toEqual({ width: w, height: h });
+ });
+
+ it('routes: in the tool result, as an image message, or none', () => {
+ expect(visionProfile({ model: 'claude-opus-5-5', seesImages: true, toolResultImages: true }, {}).route).toBe('tool-result');
+ expect(visionProfile({ model: 'nemotron-vl', seesImages: true, toolResultImages: false }, {}).route).toBe('user-message');
+ expect(visionProfile({ model: 'deepseek-chat', seesImages: false, toolResultImages: false }, {}).route).toBe('none');
+ });
+
+ it('the owner can set one size for every model', () => {
+ expect(visionProfile({ model: 'gemini-3', seesImages: true, toolResultImages: true }, { MERCURY_SCREENSHOT_BOX: '1280x800' }).box).toEqual({ width: 1280, height: 800 });
+ expect(visionProfile({ model: 'gemini-3', seesImages: true, toolResultImages: true }, { MERCURY_SCREENSHOT_BOX: 'huge' }).box).toEqual({ width: 768, height: 480 });
+ });
+
+ it('right-sized screenshots cost fewer tokens than the old fixed 1280×800', () => {
+ for (const family of ['claude', 'openai', 'gemini'] as const) {
+ const p = visionProfile({ model: family === 'openai' ? 'gpt-5' : family === 'claude' ? 'claude-x' : 'gemini-x', seesImages: true, toolResultImages: true }, {});
+ expect(estimateImageTokens(family, p.box.width, p.box.height)).toBeLessThan(estimateImageTokens(family, 1280, 800));
+ }
+ expect(estimateImageTokens('gemini', 768, 480)).toBe(258);
+ expect(estimateImageTokens('openai', 1024, 640)).toBe(765);
+ expect(visionFamily('o4-mini')).toBe('openai');
+ });
+
+ it('"-vl" models are recognised as seeing images', () => {
+ expect(modelSeesImages('mercuryCloud', 'nemotron-3.5-super-vl:free')).toBe(true);
+ expect(modelSeesImages('ollamaLocal', 'internvl3:8b')).toBe(true);
+ expect(modelSeesImages('openaiCompat', 'devstral-small')).toBe(false);
+ });
+});
+
+describe('a plugin that takes screenshots', () => {
+ it('declares it with a mercury_screenshot parameter, which the model never sees', () => {
+ const { inputSchema, screenshots } = screenshotContract({ type: 'object', properties: { zoom: { type: 'array' }, mercury_screenshot: { type: 'object' } }, required: ['mercury_screenshot'] });
+ expect(screenshots).toBe(true);
+ expect(inputSchema).toEqual({ type: 'object', properties: { zoom: { type: 'array' } }, required: [] });
+ expect(screenshotContract({ type: 'object', properties: { x: {} } }).screenshots).toBe(false);
+ expect(screenshotContract({ type: 'object', properties: {} }, true).screenshots).toBe(true);
+ });
+});
+
+describe('screenshots as image messages (APIs that take images only from the user)', () => {
+ const img = { data: 'AAAA', mimeType: 'image/jpeg' };
+ const held = new Map([['c1', [img]], ['c2', [img]], ['c3', [img]]]);
+ const step = (id: string) => [
+ { role: 'assistant', content: [{ type: 'tool-call', toolCallId: id, toolName: 'optimus__act', input: {} }] },
+ { role: 'tool', content: [{ type: 'tool-result', toolCallId: id, toolName: 'optimus__act', output: { type: 'text', value: 'Sent.\n(The screenshot follows as an image.)' } }] },
+ ];
+ const conversation = [{ role: 'user', content: 'do it' }, ...step('c1'), ...step('c2'), ...step('c3')];
+
+ it('follows each tool run, newest two as images, older ones as a note', () => {
+ const out = shapeStepMessages(conversation as never[], { toolImages: { route: 'user-message', imagesFor: (id) => held.get(id) } }) as Array<{ role: string; content: unknown }>;
+ const added = out.filter((m) => m.role === 'user' && Array.isArray(m.content));
+ expect(added).toHaveLength(3);
+ const images = added.map((m) => (m.content as Array<{ type: string }>).filter((p) => p.type === 'image').length);
+ expect(images).toEqual([0, 1, 1]);
+ expect(KEEP_IMAGES).toBe(2);
+ expect(JSON.stringify(added[2].content)).toContain(TOOL_IMAGE_LEAD);
+ // Each comes right after its tool message.
+ expect(out.map((m) => m.role)).toEqual(['user', 'assistant', 'tool', 'user', 'assistant', 'tool', 'user', 'assistant', 'tool', 'user']);
+ });
+
+ it('leaves other routes and screenshot-free turns alone', () => {
+ expect(shapeStepMessages(conversation as never[], { toolImages: { route: 'tool-result', imagesFor: (id) => held.get(id) } })).toBe(conversation);
+ expect(shapeStepMessages(conversation as never[], { toolImages: { route: 'user-message', imagesFor: () => undefined } })).toBe(conversation);
+ });
+
+ it('on the wire (OpenAI-compatible chat): an image_url part in a user message after the tool message', async () => {
+ let body: { messages: Array<{ role: string; content: unknown }> } = { messages: [] };
+ const fake = (async (_u: unknown, init?: RequestInit) => {
+ body = JSON.parse(String(init?.body));
+ return new Response(JSON.stringify({ id: 'x', object: 'chat.completion', created: 1, model: 'm', choices: [{ index: 0, message: { role: 'assistant', content: 'ok' }, finish_reason: 'stop' }] }), { headers: { 'content-type': 'application/json' } });
+ }) as typeof fetch;
+ const shaped = shapeStepMessages(step('c3') as never[], { toolImages: { route: 'user-message', imagesFor: (id) => held.get(id) } });
+ await generateText({ model: createOpenAI({ apiKey: 'k', baseURL: 'http://x/v1', fetch: fake }).chat('nemotron-vl'), messages: [{ role: 'user', content: 'go' }, ...shaped] as never });
+ const roles = body.messages.map((m) => m.role);
+ expect(roles).toEqual(['user', 'assistant', 'tool', 'user']);
+ const last = body.messages[3].content as Array<{ type: string; image_url?: { url: string } }>;
+ expect(last.find((p) => p.type === 'image_url')?.image_url?.url).toBe('data:image/jpeg;base64,AAAA');
+ });
+});
+
+describe('the bridge fills in the size for the model in use', () => {
+ it('passes mercury_screenshot to a screenshot tool, and tells the model how the image comes', async () => {
+ const bridge = await import('../plugins/tool-bridge.js');
+ const images = await import('../capabilities/tool-images.js');
+ bridge.resetToolBridge();
+ const calls: Array<Record<string, unknown>> = [];
+ bridge.publishTool({
+ pluginId: 'optimus', pluginName: 'Optimus', name: 'look', description: 'See the screen',
+ ...bridge.screenshotContract({ type: 'object', properties: { mercury_screenshot: { type: 'object' } } }),
+ readOnly: true, timeoutMs: 5000,
+ invoke: async (args) => { calls.push(args); return bridge.toolContent('Display 1 of 1.', [{ data: 'AAAA', mimeType: 'image/jpeg' }]); },
+ });
+ const tools = bridge.getPluginTools({ approvePluginTool: async () => true } as never);
+ const look = tools['optimus__look'] as unknown as { execute: (i: unknown, o: unknown) => Promise<string>; toModelOutput: (x: unknown) => unknown };
+
+ images.setToolVision({ route: 'user-message', box: { width: 896, height: 560 } });
+ await look.execute({}, { toolCallId: 't1' });
+ expect(calls[0].mercury_screenshot).toEqual({ include: true, max_width: 896, max_height: 560 });
+ expect(look.toModelOutput({ toolCallId: 't1', output: 'Display 1 of 1.\n[1 image attached]' })).toEqual({ type: 'text', value: 'Display 1 of 1.\n[1 image attached]\n(The screenshot follows as an image.)' });
+ expect(images.heldImages('t1')).toHaveLength(1);
+
+ images.setToolVision({ route: 'none', box: { width: 1024, height: 640 } });
+ await look.execute({}, { toolCallId: 't2' });
+ expect(calls[1].mercury_screenshot).toEqual({ include: false, max_width: 1024, max_height: 640 });
+
+ images.setToolVision({ route: 'tool-result', box: { width: 1024, height: 640 } });
+ bridge.resetToolBridge();
+ });
+});
diff --git a/src/core/vision-profile.ts b/src/core/vision-profile.ts
new file mode 100644
index 00000000..f9b7b117
--- /dev/null
+++ b/src/core/vision-profile.ts
@@ -0,0 +1,96 @@
+/**
+ * How the current model takes screenshots (ADR-043): whether it sees them,
+ * how they reach it, and how big they should be.
+ *
+ * A model is billed for an image by its pixels, by rules that differ per
+ * family, so one fixed size (Optimus used 1280×800 for every model) costs
+ * far more than needed on some and is never seen at all by others:
+ *
+ * Claude ≈ width × height / 750 tokens 1024×640 ≈ 874 (1280×800: 1,365)
+ * OpenAI 85 + 170 per 512-px tile (high) 1024×640 = 765 (1280×800: 1,105)
+ * Gemini 258 per 768-px tile 768×480 = 258 (1280×800: 1,032)
+ * Qwen-VL and other local vision models: 28-px patches, slow on big images.
+ *
+ * Route:
+ * tool-result the provider takes images inside tool results (Anthropic,
+ * OpenAI Responses): the screenshot stays with its tool call
+ * user-message the model sees images but its API only takes them from the
+ * user (OpenAI-compatible chat: OpenRouter, LiteLLM, Mercury
+ * Cloud, Ollama, LM Studio…): the screenshot follows the tool
+ * result as an image message (payload-policy.ts)
+ * none the model can't see images: no screenshot is taken at all;
+ * the tool still says which window is in front
+ *
+ * The size is passed to tools that declare `screenshots: true` in their
+ * plugin manifest; they shrink the capture themselves, so the coordinates
+ * the model clicks stay in the picture it saw.
+ */
+
+export type ImageRoute = 'tool-result' | 'user-message' | 'none';
+
+export interface ScreenshotBox {
+ width: number;
+ height: number;
+}
+
+export interface VisionProfile {
+ route: ImageRoute;
+ box: ScreenshotBox;
+ /** Which pricing rule applied (for logs and estimates). */
+ family: 'claude' | 'openai' | 'gemini' | 'patch' | 'default';
+}
+
+const BOXES: Record<VisionProfile['family'], ScreenshotBox> = {
+ claude: { width: 1024, height: 640 },
+ openai: { width: 1024, height: 640 },
+ gemini: { width: 768, height: 480 },
+ patch: { width: 896, height: 560 },
+ default: { width: 1024, height: 640 },
+};
+
+/** The family whose image pricing applies to this model id. */
+export function visionFamily(model: string): VisionProfile['family'] {
+ const m = model.toLowerCase();
+ if (/claude/.test(m)) return 'claude';
+ if (/gemini|gemma/.test(m)) return 'gemini';
+ if (/gpt|chatgpt|(^|[/:])o[1-9]\b|grok/.test(m)) return 'openai';
+ if (/qwen|llava|minicpm|internvl|moondream|molmo|pixtral|mistral|llama|nemotron|kimi|glm|(^|[-_.:/])vl($|[-_.:/])/.test(m)) return 'patch';
+ return 'default';
+}
+
+/** "1280x800" from MERCURY_SCREENSHOT_BOX: the owner's own size for every model. */
+function boxOverride(env: string | undefined): ScreenshotBox | undefined {
+ const m = /^\s*(\d{3,4})\s*[x×]\s*(\d{3,4})\s*$/i.exec(env ?? '');
+ if (!m) return undefined;
+ const width = Math.min(Math.max(Number(m[1]), 320), 3840);
+ const height = Math.min(Math.max(Number(m[2]), 240), 2160);
+ return { width, height };
+}
+
+export function visionProfile(input: { model: string; seesImages: boolean; toolResultImages: boolean }, env: NodeJS.ProcessEnv = process.env): VisionProfile {
+ const family = visionFamily(input.model);
+ const route: ImageRoute = !input.seesImages ? 'none' : input.toolResultImages ? 'tool-result' : 'user-message';
+ return { route, family, box: boxOverride(env.MERCURY_SCREENSHOT_BOX) ?? BOXES[family] };
+}
+
+/** Roughly what an image of this size costs this family, in input tokens. */
+export function estimateImageTokens(family: VisionProfile['family'], w: number, h: number): number {
+ switch (family) {
+ case 'claude':
+ return Math.ceil((w * h) / 750);
+ case 'openai': {
+ // Fit in 2048², then shortest side to 768, then 512-px tiles.
+ let s = Math.min(1, 2048 / Math.max(w, h));
+ let [x, y] = [w * s, h * s];
+ s = Math.min(1, 768 / Math.min(x, y));
+ [x, y] = [x * s, y * s];
+ return 85 + 170 * Math.ceil(x / 512) * Math.ceil(y / 512);
+ }
+ case 'gemini':
+ return w <= 384 && h <= 384 ? 258 : 258 * Math.ceil(w / 768) * Math.ceil(h / 768);
+ case 'patch':
+ return Math.ceil(w / 28) * Math.ceil(h / 28);
+ default:
+ return Math.ceil((w * h) / 750);
+ }
+}
diff --git a/src/plugins/runtime/in-process.ts b/src/plugins/runtime/in-process.ts
index 956074a8..cb257b39 100644
--- a/src/plugins/runtime/in-process.ts
+++ b/src/plugins/runtime/in-process.ts
@@ -19,7 +19,8 @@ import { assertFetchableTarget, MAX_REDIRECTS } from '../../utils/ssrf.js';
import { logger } from '../../utils/logger.js';
import { PLUGIN_API_VERSION, providerSecretNames, type PluginManifest, type PluginProviderId } from '../types.js';
import type { Disposable, PluginCommandDefinition, PluginContext, PluginModule, PluginToolDefinition } from '../sdk.js';
-import { publishCommand, publishTool, unpublishPlugin } from '../tool-bridge.js';
+import { publishCommand, publishTool,
+ screenshotContract, unpublishPlugin } from '../tool-bridge.js';
import type { PluginRuntime, RuntimeDeps } from './types.js';
export const IN_PROCESS_TIMEOUTS = { load: 10_000, activate: 15_000, deactivate: 5_000, dispose: 3_000 };
@@ -165,7 +166,7 @@ export class InProcessRuntime implements PluginRuntime {
pluginName: m.name,
name: decl.name,
description: decl.description,
- inputSchema: schema,
+ ...screenshotContract(schema, decl.screenshots),
readOnly: decl.readOnly,
timeoutMs: decl.timeoutMs,
invoke: async (args, toolSignal) => {
diff --git a/src/plugins/runtime/out-of-process.ts b/src/plugins/runtime/out-of-process.ts
index e1b560f9..2035d368 100644
--- a/src/plugins/runtime/out-of-process.ts
+++ b/src/plugins/runtime/out-of-process.ts
@@ -17,7 +17,8 @@ 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 { PLUGIN_IMAGE_TYPES, publishTool, toolContent, unpublishPlugin } from '../tool-bridge.js';
+import { PLUGIN_IMAGE_TYPES, publishTool,
+ screenshotContract, toolContent, unpublishPlugin } from '../tool-bridge.js';
import type { PluginRuntime, RuntimeDeps } from './types.js';
import { deviceFeed } from '../device-feed.js';
@@ -185,7 +186,7 @@ export class OutOfProcessRuntime implements PluginRuntime {
pluginName: this.manifest.name,
name: decl.name,
description: decl.description,
- inputSchema: schema,
+ ...screenshotContract(schema, decl.screenshots),
readOnly: decl.readOnly,
timeoutMs: decl.timeoutMs,
invoke: (args, signal) => this.callTool(decl.name, args, signal, decl.timeoutMs),
diff --git a/src/plugins/tool-bridge.ts b/src/plugins/tool-bridge.ts
index b4716351..49aafc10 100644
--- a/src/plugins/tool-bridge.ts
+++ b/src/plugins/tool-bridge.ts
@@ -18,6 +18,7 @@ import {
attachedImagesNote,
holdImages,
resetToolImages,
+ screenshotRequest,
setToolImagesAllowed,
toolImagesAllowed,
toolOutputWithImages,
@@ -35,6 +36,14 @@ export interface LiveTool {
inputSchema: Record<string, unknown>;
readOnly: boolean;
timeoutMs: number;
+ /**
+ * Returns screenshots (manifest `screenshots: true`): each call gets
+ * `mercury_screenshot: { include, max_width, max_height }` — the size the
+ * current model is best served by, or none for a model that can't see
+ * images (ADR-043). The plugin shrinks the capture itself, so coordinates
+ * stay in the picture the model saw.
+ */
+ screenshots?: boolean;
invoke(args: Record<string, unknown>, signal: AbortSignal): Promise<unknown>;
}
@@ -105,6 +114,24 @@ export function pluginToolAllowed(name: string, allow: readonly string[]): boole
return allow.includes(name) || allow.includes(`${m[1]}__*`);
}
+/** The input parameter through which Mercury sizes a plugin's screenshots (ADR-043). */
+export const SCREENSHOT_PARAM = 'mercury_screenshot';
+
+/**
+ * A plugin tool's input schema as the model sees it, and whether the tool
+ * takes screenshots: declared in the manifest (`screenshots: true`) or by a
+ * `mercury_screenshot` parameter in its schema. That parameter is Mercury's
+ * to fill, so the model never sees it.
+ */
+export function screenshotContract(schema: Record<string, unknown>, declared?: boolean): { inputSchema: Record<string, unknown>; screenshots: boolean } {
+ const props = schema.properties as Record<string, unknown> | undefined;
+ const inSchema = !!props && Object.prototype.hasOwnProperty.call(props, SCREENSHOT_PARAM);
+ if (!inSchema) return { inputSchema: schema, screenshots: declared === true };
+ const { [SCREENSHOT_PARAM]: _hidden, ...rest } = props!;
+ const required = Array.isArray(schema.required) ? (schema.required as unknown[]).filter((r) => r !== SCREENSHOT_PARAM) : schema.required;
+ return { inputSchema: { ...schema, properties: rest, ...(required !== undefined ? { required } : {}) }, screenshots: true };
+}
+
/** Publish a tool; returns its removal. A later registration with the same name replaces it. */
export function publishTool(t: LiveTool): () => void {
const full = pluginToolName(t.pluginId, t.name);
@@ -175,9 +202,11 @@ function wrap(t: LiveTool, permissions: PermissionManager): Tool {
toModelOutput: ({ toolCallId, output }) =>
toolOutputWithImages(toolCallId, typeof output === 'string' ? output : stringifyResult(output)),
execute: async (input, options) => {
- const args = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;
+ const given = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>;
+ // The model never sets this; Mercury does, for the model in use.
+ const args = t.screenshots ? { ...given, [SCREENSHOT_PARAM]: screenshotRequest() } : given;
if (!t.readOnly) {
- const approved = await permissions.approvePluginTool(full, `Run plugin tool ${t.pluginName} → ${t.name} with ${describeArgs(args)}`);
+ const approved = await permissions.approvePluginTool(full, `Run plugin tool ${t.pluginName} → ${t.name} with ${describeArgs(given)}`);
if (!approved) return `Not run: the plugin tool ${full} was not approved.`;
}
const ac = new AbortController();
diff --git a/src/plugins/types.ts b/src/plugins/types.ts
index d2c7d353..4577b8db 100644
--- a/src/plugins/types.ts
+++ b/src/plugins/types.ts
@@ -79,6 +79,11 @@ const toolDecl = z.object({
readOnly: z.boolean().default(false),
/** Per-call timeout; capped by Mercury at 300s. */
timeoutMs: z.number().int().min(1000).max(300_000).default(60_000),
+ /**
+ * The tool returns screenshots: Mercury passes `mercury_screenshot`
+ * ({ include, max_width, max_height }) sized for the model in use (ADR-043).
+ */
+ screenshots: z.boolean().optional(),
}).strict();
const commandDecl = z.object({
diff --git a/src/utils/arrow-select-rows.test.ts b/src/utils/arrow-select-rows.test.ts
new file mode 100644
index 00000000..524126ce
--- /dev/null
+++ b/src/utils/arrow-select-rows.test.ts
@@ -0,0 +1,50 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { stripVTControlCharacters } from 'node:util';
+import { screenRows, selectWithArrowKeys } from './arrow-select.js';
+
+/**
+ * A long, multi-line menu title — the device token /server shows to copy —
+ * is drawn whole, and a redraw clears exactly what was drawn. Counting one
+ * row per title cut the token off on the server's terminal.
+ */
+describe('menu titles that wrap', () => {
+ it('counts the rows wrapped lines fill', () => {
+ expect(screenRows(['short', 'x'.repeat(100), ''], 40)).toBe(1 + 3 + 1);
+ expect(screenRows(['\u001b[1mbold\u001b[22m'], 10)).toBe(1);
+ });
+
+ const realOut = { isTTY: process.stdout.isTTY, columns: process.stdout.columns, rows: process.stdout.rows };
+ const realIn = { isTTY: process.stdin.isTTY, setRawMode: (process.stdin as { setRawMode?: unknown }).setRawMode };
+ afterEach(() => {
+ Object.assign(process.stdout, realOut);
+ Object.assign(process.stdin, realIn);
+ vi.restoreAllMocks();
+ });
+
+ it('draws the whole token, and moves up by every row it drew before redrawing', async () => {
+ Object.assign(process.stdout, { isTTY: true, columns: 40, rows: 30 });
+ Object.assign(process.stdin, { isTTY: true, setRawMode: () => process.stdin });
+ const written: string[] = [];
+ vi.spyOn(process.stdout, 'write').mockImplementation((chunk: unknown) => { written.push(String(chunk)); return true; });
+ const ups: number[] = [];
+ const readline = await import('node:readline');
+ vi.spyOn(readline.default, 'moveCursor').mockImplementation((_s, _dx, dy) => { if (dy) ups.push(dy as number); return true; });
+ vi.spyOn(readline.default, 'cursorTo').mockImplementation(() => true);
+ vi.spyOn(readline.default, 'clearScreenDown').mockImplementation(() => true);
+
+ const token = `mct_${'a1B2c3D4e5'.repeat(9)}`; // 94 characters: wraps over 3 rows at 40 columns
+ const title = `Token for “Laptop” (shown only now):\n\n${token}\n\nPaste it into the device.`;
+ const pick = selectWithArrowKeys(title, [{ value: 'ok', label: "I've copied it" }, { value: 'b', label: 'Back' }]);
+ process.stdin.emit('keypress', '', { name: 'down' });
+ process.stdin.emit('keypress', '', { name: 'return' });
+ expect(await pick).toBe('b');
+
+ const frames = written.map((w) => stripVTControlCharacters(w)).filter((w) => w.includes('Token for'));
+ expect(frames.length).toBeGreaterThanOrEqual(2);
+ // The token is on screen in full, every time.
+ for (const f of frames) expect(f).toContain(token);
+ // The redraw went back up over every row of the first frame (wrapped token rows included).
+ const firstRows = screenRows(frames[0].split('\n'), 40);
+ expect(ups[0]).toBe(-(firstRows - 1));
+ });
+});
diff --git a/src/utils/arrow-select.ts b/src/utils/arrow-select.ts
index dd4dab42..2380005d 100644
--- a/src/utils/arrow-select.ts
+++ b/src/utils/arrow-select.ts
@@ -1,7 +1,20 @@
import readline from 'node:readline';
+import { stripVTControlCharacters } from 'node:util';
+import stringWidth from 'string-width';
import { closeAsk } from '../cli/ask.js';
import chalk from 'chalk';
+/**
+ * How many terminal rows these lines take: a line wider than the terminal
+ * wraps onto more rows. Counting one row per line under-moved the cursor
+ * on a redraw and overwrote part of a long title — a device token from
+ * /server showed cut off.
+ */
+export function screenRows(lines: string[], columns: number): number {
+ const cols = Math.max(1, columns);
+ return lines.reduce((rows, line) => rows + Math.max(1, Math.ceil(stringWidth(stripVTControlCharacters(line)) / cols)), 0);
+}
+
export interface ArrowSelectOption {
value: string;
label: string;
@@ -49,7 +62,8 @@ export async function selectWithArrowKeys(
),
);
let activeIndex = 0;
- let renderedLineCount = 0;
+ /** Rows the last render took on screen (wrapped lines count for each row they fill). */
+ let renderedRows = 0;
let windowStart = 0;
const topIndicator = (hasHiddenAbove: boolean) => (
@@ -60,18 +74,15 @@ export async function selectWithArrowKeys(
);
const writeLines = (lines: string[]) => {
- if (renderedLineCount > 0) {
- readline.moveCursor(stdout, 0, -(renderedLineCount - 1));
- }
-
- for (let index = 0; index < lines.length; index += 1) {
- readline.cursorTo(stdout, 0);
- readline.clearLine(stdout, 0);
- stdout.write(lines[index]);
- if (index < lines.length - 1) {
- stdout.write('\n');
- }
+ // Back to the top of what was drawn, clear it all, draw again: a redraw
+ // never leaves pieces of a longer frame, nor eats into a wrapped title.
+ if (renderedRows > 0) {
+ readline.moveCursor(stdout, 0, -(renderedRows - 1));
}
+ readline.cursorTo(stdout, 0);
+ readline.clearScreenDown(stdout);
+ stdout.write(lines.join('\n'));
+ renderedRows = screenRows(lines, stdout.columns || 80);
};
const render = () => {
@@ -85,7 +96,8 @@ export async function selectWithArrowKeys(
const hasHiddenAbove = windowStart > 0;
const hasHiddenBelow = windowStart + maxVisibleOptions < options.length;
const lines = [
- chalk.bold.white(` ${title}`),
+ // A title can span lines (a token to copy, an explanation): each is its own row, never cut.
+ ...title.split('\n').map((line) => (line ? chalk.bold.white(` ${line}`) : '')),
chalk.dim(` ${helperText}`),
'',
topIndicator(hasHiddenAbove),
@@ -101,7 +113,6 @@ export async function selectWithArrowKeys(
];
writeLines(lines);
- renderedLineCount = lines.length;
};
return await new Promise<string>((resolve, reject) => {
diff --git a/website/docs/reference/plugins.mdx b/website/docs/reference/plugins.mdx
index b736ab1a..553c4212 100644
--- a/website/docs/reference/plugins.mdx
+++ b/website/docs/reference/plugins.mdx
@@ -207,9 +207,37 @@ standard MCP `image` content:
- **Kept out of history.** The images go to the model with that one tool
result. Chat history, logs and memory only ever see the text.
- **Text-only models** get the text plus a note that an image was left out.
+- **Models whose API takes images only from the user** (OpenAI-compatible chat:
+ OpenRouter, LiteLLM, Mercury Cloud, Ollama, LM Studio) get the image in a
+ message right after the tool result. Only the newest two screenshots are kept.
Require `"pluginApi": "^1.2.0"` to use it.
+### Screenshots sized for the model
+
+Models are billed for an image by its pixels, by rules that differ per family.
+A tool that takes screenshots can let Mercury choose the size for the model in
+use by declaring a `mercury_screenshot` parameter in its input schema (or
+`"screenshots": true` on the tool in the manifest):
+
+```json
+"mercury_screenshot": { "type": "object", "description": "Set by Mercury; leave it out.",
+ "properties": { "include": { "type": "boolean" }, "max_width": { "type": "integer" }, "max_height": { "type": "integer" } } }
+```
+
+Mercury hides the parameter from the model and fills it on every call:
+
+- `max_width` × `max_height`: fit the screenshot in this box (never enlarge it).
+ For example, Claude and OpenAI get 1024×640, Gemini 768×480, and open vision
+ models 896×560. Shrink the capture yourself, so the coordinates the model
+ clicks stay in the picture it saw.
+- `include: false`: the model can't see images. Don't capture; say in text
+ what is on screen (for example, the active window).
+
+An older Mercury shows the parameter as optional, so the model may leave it out.
+Treat a missing value as your own default. The owner can set one size for
+every model with `MERCURY_SCREENSHOT_BOX=1280x800`.
+
## Chat channels (plugin API 1.1)
An out-of-process plugin can provide a chat channel. The channel types are