Skip to main content

nexo_plugin_browser/
dispatch.rs

1//! Subprocess-side tool dispatcher.
2//!
3//! Maps each `browser_*` tool name to a [`BrowserPlugin::execute`]
4//! flow without requiring an `AgentContext` (which the subprocess
5//! cannot construct). Tool argument schemas live in
6//! `tool_defs.rs` — keep the two in sync when adding or changing
7//! a tool.
8
9use std::sync::Arc;
10
11use anyhow::anyhow;
12use nexo_microapp_sdk::plugin::ToolInvocationError;
13use serde_json::{json, Value};
14
15use crate::command::{BrowserCmd, BrowserResult};
16use crate::instance_registry;
17use crate::plugin::BrowserPlugin;
18
19/// Resolve the `BrowserPlugin` that should service this `tool.invoke`
20/// call. Four cases:
21///
22/// 1. Explicit `instance` arg → look up in [`instance_registry`].
23///    Unknown label ⇒ `ArgumentInvalid`.
24/// 2. No arg + exactly 1 instance declared → use it (compat shim).
25/// 3. No arg + 0 instances declared → fall back to `legacy` (the
26///    per-`agent_id` plugin from `main.rs::shared_plugin_for`).
27/// 4. No arg + N > 1 instances declared → `ArgumentInvalid`
28///    (ambiguous — caller must name an instance).
29///
30/// The instance arg is **not** stripped from `args` here; tool
31/// handlers ignore unknown keys, so leaving it in keeps this fn
32/// non-mutating.
33pub fn resolve_plugin_or_legacy(
34    args: &Value,
35    agent_id: &str,
36    legacy: Arc<BrowserPlugin>,
37) -> Result<Arc<BrowserPlugin>, ToolInvocationError> {
38    resolve_plugin_or_legacy_gated(args, agent_id, legacy, true)
39}
40
41/// Variant of [`resolve_plugin_or_legacy`] that lets the caller
42/// opt out of the legacy per-`agent_id` fallback (dispatch case 3).
43/// Wired from `main.rs::on_tool` via
44/// [`ProfileLimits::legacy_per_agent_enabled`]. The 0.4.0 plan is
45/// to flip the env default so this off-path becomes the norm.
46pub fn resolve_plugin_or_legacy_gated(
47    args: &Value,
48    agent_id: &str,
49    legacy: Arc<BrowserPlugin>,
50    legacy_enabled: bool,
51) -> Result<Arc<BrowserPlugin>, ToolInvocationError> {
52    let requested = args.get("instance").and_then(|v| v.as_str());
53
54    if let Some(name) = requested {
55        // Case 1 — explicit instance.
56        let plugin = instance_registry::lookup(name).ok_or_else(|| {
57            ToolInvocationError::ArgumentInvalid(format!(
58                "browser instance `{name}` not declared in config"
59            ))
60        })?;
61        gate_allow_agents(&plugin, agent_id)?;
62        return Ok(plugin);
63    }
64
65    let registered = instance_registry::entries();
66    match registered.len() {
67        0 => {
68            // Case 3 — legacy per-agent_id fallback.
69            if !legacy_enabled {
70                return Err(ToolInvocationError::Unavailable(
71                    "no declared browser instances; configure browser.yaml \
72                     or set NEXO_PLUGIN_BROWSER_LEGACY_PER_AGENT=1 to allow \
73                     implicit per-agent fallback"
74                        .into(),
75                ));
76            }
77            Ok(legacy)
78        }
79        1 => {
80            // Case 2 — implicit single declared instance.
81            let (_, plugin) = registered.into_iter().next().unwrap();
82            gate_allow_agents(&plugin, agent_id)?;
83            Ok(plugin)
84        }
85        _ => Err(ToolInvocationError::ArgumentInvalid(
86            "browser plugin has multiple instances declared; pass `instance` arg"
87                .into(),
88        )),
89    }
90}
91
92fn gate_allow_agents(
93    plugin: &Arc<BrowserPlugin>,
94    agent_id: &str,
95) -> Result<(), ToolInvocationError> {
96    let allow = plugin.allow_agents();
97    if allow.is_empty() {
98        return Ok(());
99    }
100    if agent_id.is_empty() || !allow.iter().any(|a| a == agent_id) {
101        return Err(ToolInvocationError::ArgumentInvalid(format!(
102            "agent `{agent_id}` not in allow_agents for this browser instance"
103        )));
104    }
105    Ok(())
106}
107
108/// Convert a [`BrowserResult`] into the JSON value that lands in
109/// a `tool.invoke` reply's `result` field.
110fn result_to_json(res: BrowserResult) -> Value {
111    if !res.ok {
112        return json!({
113            "ok": false,
114            "error": res.error.unwrap_or_else(|| "unknown error".into()),
115        });
116    }
117    let mut out = json!({ "ok": true });
118    let obj = out.as_object_mut().unwrap();
119    if let Some(r) = res.result {
120        obj.insert("result".into(), r);
121    }
122    if let Some(d) = res.data {
123        obj.insert("png_base64".into(), Value::String(d));
124    }
125    if let Some(s) = res.snapshot {
126        obj.insert("snapshot".into(), Value::String(s));
127    }
128    out
129}
130
131/// Allowed named keys for `browser_press_key`.
132const ALLOWED_KEY_NAMES: &[&str] = &[
133    "Enter", "Tab", "Escape",
134    "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight",
135    "Backspace", "Delete", "Home", "End", "PageUp", "PageDown",
136    "Space",
137];
138
139/// Match `tool_name` against the `browser_*` tools and dispatch
140/// to the matching `BrowserPlugin::execute` flow. Returns a JSON
141/// `Value` ready to land in the `tool.invoke` reply's `result`
142/// field, or [`ToolInvocationError`] for the host's
143/// `RemoteToolHandler` decoder.
144pub async fn dispatch_browser_tool(
145    plugin: Arc<BrowserPlugin>,
146    tool_name: &str,
147    args: Value,
148) -> Result<Value, ToolInvocationError> {
149    match tool_name {
150        "browser_navigate" => {
151            let url = arg_string(&args, "url", "browser_navigate")?;
152            Ok(result_to_json(
153                plugin.execute(BrowserCmd::Navigate { url }).await,
154            ))
155        }
156        "browser_click" => {
157            let target = arg_string(&args, "target", "browser_click")?;
158            Ok(result_to_json(
159                plugin.execute(BrowserCmd::Click { target }).await,
160            ))
161        }
162        "browser_fill" => {
163            let target = arg_string(&args, "target", "browser_fill")?;
164            let value = arg_string(&args, "value", "browser_fill")?;
165            Ok(result_to_json(
166                plugin.execute(BrowserCmd::Fill { target, value }).await,
167            ))
168        }
169        "browser_screenshot" => {
170            Ok(result_to_json(plugin.execute(BrowserCmd::Screenshot).await))
171        }
172        "browser_evaluate" => {
173            let script = arg_string(&args, "script", "browser_evaluate")?;
174            Ok(result_to_json(
175                plugin.execute(BrowserCmd::Evaluate { script }).await,
176            ))
177        }
178        "browser_snapshot" => {
179            Ok(result_to_json(plugin.execute(BrowserCmd::Snapshot).await))
180        }
181        "browser_scroll_to" => {
182            let target = arg_string(&args, "target", "browser_scroll_to")?;
183            Ok(result_to_json(
184                plugin.execute(BrowserCmd::ScrollTo { target }).await,
185            ))
186        }
187        "browser_current_url" => {
188            Ok(result_to_json(
189                plugin
190                    .execute(BrowserCmd::Evaluate {
191                        script: "location.href".into(),
192                    })
193                    .await,
194            ))
195        }
196        "browser_wait_for" => {
197            let selector = arg_string(&args, "selector", "browser_wait_for")?;
198            let timeout_ms = args["timeout_ms"].as_u64().unwrap_or(5_000).min(30_000);
199            let deadline =
200                std::time::Instant::now() + std::time::Duration::from_millis(timeout_ms);
201            loop {
202                let script = format!(
203                    "!!document.querySelector({})",
204                    serde_json::to_string(&selector)
205                        .map_err(|e| ToolInvocationError::ExecutionFailed(e.to_string()))?
206                );
207                let res = plugin.execute(BrowserCmd::Evaluate { script }).await;
208                if res.ok {
209                    if let Some(Value::Bool(true)) = res.result.as_ref() {
210                        return Ok(json!({"ok": true, "found": true}));
211                    }
212                }
213                if std::time::Instant::now() >= deadline {
214                    return Ok(json!({"ok": true, "found": false}));
215                }
216                tokio::time::sleep(std::time::Duration::from_millis(250)).await;
217            }
218        }
219        "browser_go_back" => {
220            Ok(result_to_json(
221                plugin
222                    .execute(BrowserCmd::Evaluate {
223                        script: "history.back()".into(),
224                    })
225                    .await,
226            ))
227        }
228        "browser_go_forward" => {
229            Ok(result_to_json(
230                plugin
231                    .execute(BrowserCmd::Evaluate {
232                        script: "history.forward()".into(),
233                    })
234                    .await,
235            ))
236        }
237        "browser_press_key" => {
238            let key = args["key"]
239                .as_str()
240                .ok_or_else(|| {
241                    ToolInvocationError::ArgumentInvalid(
242                        "browser_press_key requires `key`".into(),
243                    )
244                })?
245                .to_string();
246            let named = ALLOWED_KEY_NAMES.contains(&key.as_str());
247            let is_single_char = key.chars().count() == 1
248                && key.chars().next().map(|c| !c.is_control()).unwrap_or(false);
249            if !named && !is_single_char {
250                return Err(ToolInvocationError::ArgumentInvalid(format!(
251                    "browser_press_key rejected: expected a known key name or a single character, got `{key}`"
252                )));
253            }
254            let script = format!(
255                r#"(function() {{
256                    const k = {};
257                    const map = {{
258                        Enter:      {{ key: 'Enter',      code: 'Enter',      keyCode: 13 }},
259                        Tab:        {{ key: 'Tab',        code: 'Tab',        keyCode: 9  }},
260                        Escape:     {{ key: 'Escape',     code: 'Escape',     keyCode: 27 }},
261                        ArrowUp:    {{ key: 'ArrowUp',    code: 'ArrowUp',    keyCode: 38 }},
262                        ArrowDown:  {{ key: 'ArrowDown',  code: 'ArrowDown',  keyCode: 40 }},
263                        ArrowLeft:  {{ key: 'ArrowLeft',  code: 'ArrowLeft',  keyCode: 37 }},
264                        ArrowRight: {{ key: 'ArrowRight', code: 'ArrowRight', keyCode: 39 }}
265                    }};
266                    const spec = map[k] || {{ key: k, code: k, keyCode: k.charCodeAt(0) }};
267                    const target = document.activeElement || document.body;
268                    target.dispatchEvent(new KeyboardEvent('keydown', {{ ...spec, bubbles: true }}));
269                    target.dispatchEvent(new KeyboardEvent('keyup',   {{ ...spec, bubbles: true }}));
270                    return true;
271                }})()"#,
272                serde_json::to_string(&key)
273                    .map_err(|e| ToolInvocationError::ExecutionFailed(e.to_string()))?
274            );
275            Ok(result_to_json(
276                plugin.execute(BrowserCmd::Evaluate { script }).await,
277            ))
278        }
279        other => Err(ToolInvocationError::NotFound(other.to_string())),
280    }
281}
282
283fn arg_string(
284    args: &Value,
285    field: &str,
286    tool_name: &str,
287) -> Result<String, ToolInvocationError> {
288    args[field]
289        .as_str()
290        .ok_or_else(|| {
291            ToolInvocationError::ArgumentInvalid(format!(
292                "{tool_name} requires `{field}` (string)"
293            ))
294        })
295        .map(str::to_string)
296}
297
298// Bridge to anyhow for tests if ever needed.
299#[allow(dead_code)]
300fn anyhow_to_invocation(e: anyhow::Error) -> ToolInvocationError {
301    ToolInvocationError::ExecutionFailed(format!("{e:#}"))
302}
303
304// Suppress unused import warning when anyhow is not invoked.
305#[allow(dead_code)]
306fn _suppress() -> anyhow::Error {
307    anyhow!("unused")
308}