Skip to main content

nexo_plugin_browser/
dispatch.rs

1//! Subprocess-side tool dispatcher.
2//!
3//! Replicates the per-tool logic from
4//! `proyecto/crates/plugins/browser/src/tool.rs::Browser*Tool::call`
5//! without requiring an `AgentContext` (which the subprocess
6//! cannot construct). Each branch matches the in-tree behaviour
7//! 1:1; the goal is bit-for-bit parity, not feature evolution.
8//!
9//! When the in-tree tool.rs gains new args / behaviours,
10//! mirror the change here. Same applies to `tool_defs.rs` for the
11//! schema. CI lint follow-up `81.17.c.tool-defs-drift-test`
12//! validates that this file stays in sync.
13
14use std::sync::Arc;
15
16use anyhow::anyhow;
17use nexo_microapp_sdk::plugin::ToolInvocationError;
18use serde_json::{json, Value};
19
20use crate::command::{BrowserCmd, BrowserResult};
21use crate::plugin::BrowserPlugin;
22
23/// Convert a [`BrowserResult`] into a JSON value matching what
24/// the in-tree `Browser*Tool::call` methods produce. Mirrors the
25/// private helper in
26/// `proyecto/crates/plugins/browser/src/tool.rs::result_to_json`
27/// (kept private upstream — duplicated here so the standalone
28/// repo doesn't need to mutate the copied tool.rs).
29fn result_to_json(res: BrowserResult) -> Value {
30    if !res.ok {
31        return json!({
32            "ok": false,
33            "error": res.error.unwrap_or_else(|| "unknown error".into()),
34        });
35    }
36    let mut out = json!({ "ok": true });
37    let obj = out.as_object_mut().unwrap();
38    if let Some(r) = res.result {
39        obj.insert("result".into(), r);
40    }
41    if let Some(d) = res.data {
42        obj.insert("png_base64".into(), Value::String(d));
43    }
44    if let Some(s) = res.snapshot {
45        obj.insert("snapshot".into(), Value::String(s));
46    }
47    out
48}
49
50/// Allowed named keys for `browser_press_key`. Mirrors
51/// `proyecto/crates/plugins/browser/src/tool.rs::ALLOWED_KEY_NAMES`.
52const ALLOWED_KEY_NAMES: &[&str] = &[
53    "Enter", "Tab", "Escape",
54    "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight",
55    "Backspace", "Delete", "Home", "End", "PageUp", "PageDown",
56    "Space",
57];
58
59/// Match `tool_name` against the 12 `browser_*` tools and dispatch
60/// to the matching `BrowserPlugin::execute` flow. Returns a JSON
61/// `Value` ready to land in the `tool.invoke` reply's `result`
62/// field, or [`ToolInvocationError`] for the host's
63/// `RemoteToolHandler` decoder.
64pub async fn dispatch_browser_tool(
65    plugin: Arc<BrowserPlugin>,
66    tool_name: &str,
67    args: Value,
68) -> Result<Value, ToolInvocationError> {
69    match tool_name {
70        "browser_navigate" => {
71            let url = arg_string(&args, "url", "browser_navigate")?;
72            Ok(result_to_json(
73                plugin.execute(BrowserCmd::Navigate { url }).await,
74            ))
75        }
76        "browser_click" => {
77            let target = arg_string(&args, "target", "browser_click")?;
78            Ok(result_to_json(
79                plugin.execute(BrowserCmd::Click { target }).await,
80            ))
81        }
82        "browser_fill" => {
83            let target = arg_string(&args, "target", "browser_fill")?;
84            let value = arg_string(&args, "value", "browser_fill")?;
85            Ok(result_to_json(
86                plugin.execute(BrowserCmd::Fill { target, value }).await,
87            ))
88        }
89        "browser_screenshot" => {
90            Ok(result_to_json(plugin.execute(BrowserCmd::Screenshot).await))
91        }
92        "browser_evaluate" => {
93            let script = arg_string(&args, "script", "browser_evaluate")?;
94            Ok(result_to_json(
95                plugin.execute(BrowserCmd::Evaluate { script }).await,
96            ))
97        }
98        "browser_snapshot" => {
99            Ok(result_to_json(plugin.execute(BrowserCmd::Snapshot).await))
100        }
101        "browser_scroll_to" => {
102            let target = arg_string(&args, "target", "browser_scroll_to")?;
103            Ok(result_to_json(
104                plugin.execute(BrowserCmd::ScrollTo { target }).await,
105            ))
106        }
107        "browser_current_url" => {
108            Ok(result_to_json(
109                plugin
110                    .execute(BrowserCmd::Evaluate {
111                        script: "location.href".into(),
112                    })
113                    .await,
114            ))
115        }
116        "browser_wait_for" => {
117            let selector = arg_string(&args, "selector", "browser_wait_for")?;
118            let timeout_ms = args["timeout_ms"].as_u64().unwrap_or(5_000).min(30_000);
119            let deadline =
120                std::time::Instant::now() + std::time::Duration::from_millis(timeout_ms);
121            loop {
122                let script = format!(
123                    "!!document.querySelector({})",
124                    serde_json::to_string(&selector)
125                        .map_err(|e| ToolInvocationError::ExecutionFailed(e.to_string()))?
126                );
127                let res = plugin.execute(BrowserCmd::Evaluate { script }).await;
128                if res.ok {
129                    if let Some(Value::Bool(true)) = res.result.as_ref() {
130                        return Ok(json!({"ok": true, "found": true}));
131                    }
132                }
133                if std::time::Instant::now() >= deadline {
134                    return Ok(json!({"ok": true, "found": false}));
135                }
136                tokio::time::sleep(std::time::Duration::from_millis(250)).await;
137            }
138        }
139        "browser_go_back" => {
140            Ok(result_to_json(
141                plugin
142                    .execute(BrowserCmd::Evaluate {
143                        script: "history.back()".into(),
144                    })
145                    .await,
146            ))
147        }
148        "browser_go_forward" => {
149            Ok(result_to_json(
150                plugin
151                    .execute(BrowserCmd::Evaluate {
152                        script: "history.forward()".into(),
153                    })
154                    .await,
155            ))
156        }
157        "browser_press_key" => {
158            let key = args["key"]
159                .as_str()
160                .ok_or_else(|| {
161                    ToolInvocationError::ArgumentInvalid(
162                        "browser_press_key requires `key`".into(),
163                    )
164                })?
165                .to_string();
166            let named = ALLOWED_KEY_NAMES.contains(&key.as_str());
167            let is_single_char = key.chars().count() == 1
168                && key.chars().next().map(|c| !c.is_control()).unwrap_or(false);
169            if !named && !is_single_char {
170                return Err(ToolInvocationError::ArgumentInvalid(format!(
171                    "browser_press_key rejected: expected a known key name or a single character, got `{key}`"
172                )));
173            }
174            let script = format!(
175                r#"(function() {{
176                    const k = {};
177                    const map = {{
178                        Enter:      {{ key: 'Enter',      code: 'Enter',      keyCode: 13 }},
179                        Tab:        {{ key: 'Tab',        code: 'Tab',        keyCode: 9  }},
180                        Escape:     {{ key: 'Escape',     code: 'Escape',     keyCode: 27 }},
181                        ArrowUp:    {{ key: 'ArrowUp',    code: 'ArrowUp',    keyCode: 38 }},
182                        ArrowDown:  {{ key: 'ArrowDown',  code: 'ArrowDown',  keyCode: 40 }},
183                        ArrowLeft:  {{ key: 'ArrowLeft',  code: 'ArrowLeft',  keyCode: 37 }},
184                        ArrowRight: {{ key: 'ArrowRight', code: 'ArrowRight', keyCode: 39 }}
185                    }};
186                    const spec = map[k] || {{ key: k, code: k, keyCode: k.charCodeAt(0) }};
187                    const target = document.activeElement || document.body;
188                    target.dispatchEvent(new KeyboardEvent('keydown', {{ ...spec, bubbles: true }}));
189                    target.dispatchEvent(new KeyboardEvent('keyup',   {{ ...spec, bubbles: true }}));
190                    return true;
191                }})()"#,
192                serde_json::to_string(&key)
193                    .map_err(|e| ToolInvocationError::ExecutionFailed(e.to_string()))?
194            );
195            Ok(result_to_json(
196                plugin.execute(BrowserCmd::Evaluate { script }).await,
197            ))
198        }
199        other => Err(ToolInvocationError::NotFound(other.to_string())),
200    }
201}
202
203fn arg_string(
204    args: &Value,
205    field: &str,
206    tool_name: &str,
207) -> Result<String, ToolInvocationError> {
208    args[field]
209        .as_str()
210        .ok_or_else(|| {
211            ToolInvocationError::ArgumentInvalid(format!(
212                "{tool_name} requires `{field}` (string)"
213            ))
214        })
215        .map(str::to_string)
216}
217
218// Bridge to anyhow for tests if ever needed.
219#[allow(dead_code)]
220fn anyhow_to_invocation(e: anyhow::Error) -> ToolInvocationError {
221    ToolInvocationError::ExecutionFailed(format!("{e:#}"))
222}
223
224// Suppress unused import warning when anyhow is not invoked.
225#[allow(dead_code)]
226fn _suppress() -> anyhow::Error {
227    anyhow!("unused")
228}