Skip to main content

nexo_plugin_browser/
tool.rs

1//! Agent-callable browser tools.
2//!
3//! Wraps every `BrowserCmd` variant as an individual `ToolHandler` so
4//! the LLM can drive Chrome directly instead of the host code having
5//! to round-trip through the broker. Each tool holds an
6//! `Arc<BrowserPlugin>` and calls `plugin.execute(...)` to reach the
7//! live CDP session.
8//!
9//! Registration happens in `main.rs` once per agent that has
10//! `plugins: [browser]` in its yaml — same gating model as
11//! `MemoryTool`.
12//!
13//! Naming convention: `browser_<verb>` so the relevance filter and
14//! per-agent `allowed_tools` globs ("browser_*") work cleanly.
15
16use std::sync::Arc;
17
18use async_trait::async_trait;
19use nexo_core::agent::context::AgentContext;
20use nexo_core::agent::tool_registry::ToolHandler;
21use nexo_llm::ToolDef;
22use serde_json::{json, Value};
23
24use crate::command::{BrowserCmd, BrowserResult};
25use crate::plugin::BrowserPlugin;
26
27/// Shared constructor helper — every tool gets the same plugin handle.
28fn shared_plugin_arg(plugin: &Arc<BrowserPlugin>) -> Arc<BrowserPlugin> {
29    Arc::clone(plugin)
30}
31
32/// Translate a `BrowserResult` into a JSON value the LLM can consume.
33/// Errors surface as `{ok: false, error: "..."}` so the model can
34/// react (retry, ask the user, abandon) instead of the tool call
35/// disappearing into an opaque failure.
36fn result_to_json(res: BrowserResult) -> Value {
37    if !res.ok {
38        return json!({
39            "ok": false,
40            "error": res.error.unwrap_or_else(|| "unknown error".into()),
41        });
42    }
43    let mut out = json!({ "ok": true });
44    let obj = out.as_object_mut().unwrap();
45    if let Some(r) = res.result {
46        obj.insert("result".into(), r);
47    }
48    if let Some(d) = res.data {
49        obj.insert("png_base64".into(), Value::String(d));
50    }
51    if let Some(s) = res.snapshot {
52        obj.insert("snapshot".into(), Value::String(s));
53    }
54    out
55}
56
57// ── Navigate ─────────────────────────────────────────────────────────
58
59pub struct BrowserNavigateTool {
60    plugin: Arc<BrowserPlugin>,
61}
62
63impl BrowserNavigateTool {
64    pub fn new(plugin: &Arc<BrowserPlugin>) -> Self {
65        Self {
66            plugin: shared_plugin_arg(plugin),
67        }
68    }
69
70    pub fn tool_def() -> ToolDef {
71        ToolDef {
72            name: "browser_navigate".into(),
73            description: "Navigate the managed Chrome session to the given URL. \
74                Waits for the page's load event. Returns `{ok, error?}`. \
75                Use this before `browser_snapshot` / `browser_click` / \
76                `browser_fill` on a new page."
77                .into(),
78            parameters: json!({
79                "type": "object",
80                "properties": {
81                    "url": {
82                        "type": "string",
83                        "description": "Absolute URL (http/https). Relative URLs are rejected."
84                    }
85                },
86                "required": ["url"]
87            }),
88        }
89    }
90}
91
92#[async_trait]
93impl ToolHandler for BrowserNavigateTool {
94    async fn call(&self, _ctx: &AgentContext, args: Value) -> anyhow::Result<Value> {
95        let url = args["url"]
96            .as_str()
97            .ok_or_else(|| anyhow::anyhow!("browser_navigate requires `url`"))?
98            .to_string();
99        Ok(result_to_json(
100            self.plugin.execute(BrowserCmd::Navigate { url }).await,
101        ))
102    }
103}
104
105// ── Click ────────────────────────────────────────────────────────────
106
107pub struct BrowserClickTool {
108    plugin: Arc<BrowserPlugin>,
109}
110
111impl BrowserClickTool {
112    pub fn new(plugin: &Arc<BrowserPlugin>) -> Self {
113        Self {
114            plugin: shared_plugin_arg(plugin),
115        }
116    }
117
118    pub fn tool_def() -> ToolDef {
119        ToolDef {
120            name: "browser_click".into(),
121            description: "Click a DOM element. `target` is either an element \
122                reference emitted by `browser_snapshot` (e.g. `@e12`) or a \
123                CSS selector (e.g. `button[type=submit]`). Prefer element \
124                refs — they're stable across DOM mutations within a single \
125                snapshot turn."
126                .into(),
127            parameters: json!({
128                "type": "object",
129                "properties": {
130                    "target": {
131                        "type": "string",
132                        "description": "Element ref (`@eN`) or CSS selector."
133                    }
134                },
135                "required": ["target"]
136            }),
137        }
138    }
139}
140
141#[async_trait]
142impl ToolHandler for BrowserClickTool {
143    async fn call(&self, _ctx: &AgentContext, args: Value) -> anyhow::Result<Value> {
144        let target = args["target"]
145            .as_str()
146            .ok_or_else(|| anyhow::anyhow!("browser_click requires `target`"))?
147            .to_string();
148        Ok(result_to_json(
149            self.plugin.execute(BrowserCmd::Click { target }).await,
150        ))
151    }
152}
153
154// ── Fill ─────────────────────────────────────────────────────────────
155
156pub struct BrowserFillTool {
157    plugin: Arc<BrowserPlugin>,
158}
159
160impl BrowserFillTool {
161    pub fn new(plugin: &Arc<BrowserPlugin>) -> Self {
162        Self {
163            plugin: shared_plugin_arg(plugin),
164        }
165    }
166
167    pub fn tool_def() -> ToolDef {
168        ToolDef {
169            name: "browser_fill".into(),
170            description: "Type a value into an input / textarea / \
171                contenteditable element. `target` follows the same rules \
172                as `browser_click`. `value` replaces the element's current \
173                contents — there's no append mode. For multi-step forms, \
174                call once per field."
175                .into(),
176            parameters: json!({
177                "type": "object",
178                "properties": {
179                    "target": {
180                        "type": "string",
181                        "description": "Element ref (`@eN`) or CSS selector for the input."
182                    },
183                    "value": {
184                        "type": "string",
185                        "description": "Text to type. Special keys (Enter, Tab) are NOT interpreted — use `browser_evaluate` for keyboard shortcuts."
186                    }
187                },
188                "required": ["target", "value"]
189            }),
190        }
191    }
192}
193
194#[async_trait]
195impl ToolHandler for BrowserFillTool {
196    async fn call(&self, _ctx: &AgentContext, args: Value) -> anyhow::Result<Value> {
197        let target = args["target"]
198            .as_str()
199            .ok_or_else(|| anyhow::anyhow!("browser_fill requires `target`"))?
200            .to_string();
201        let value = args["value"]
202            .as_str()
203            .ok_or_else(|| anyhow::anyhow!("browser_fill requires `value`"))?
204            .to_string();
205        Ok(result_to_json(
206            self.plugin
207                .execute(BrowserCmd::Fill { target, value })
208                .await,
209        ))
210    }
211}
212
213// ── Screenshot ──────────────────────────────────────────────────────
214
215pub struct BrowserScreenshotTool {
216    plugin: Arc<BrowserPlugin>,
217}
218
219impl BrowserScreenshotTool {
220    pub fn new(plugin: &Arc<BrowserPlugin>) -> Self {
221        Self {
222            plugin: shared_plugin_arg(plugin),
223        }
224    }
225
226    pub fn tool_def() -> ToolDef {
227        ToolDef {
228            name: "browser_screenshot".into(),
229            description: "Capture the current viewport as a base64-encoded \
230                PNG. Returned in the `png_base64` field — vision-capable \
231                models receive it directly. Use `browser_snapshot` instead \
232                when you only need text-level DOM info (cheaper, faster)."
233                .into(),
234            parameters: json!({ "type": "object", "properties": {} }),
235        }
236    }
237}
238
239#[async_trait]
240impl ToolHandler for BrowserScreenshotTool {
241    async fn call(&self, _ctx: &AgentContext, _args: Value) -> anyhow::Result<Value> {
242        Ok(result_to_json(
243            self.plugin.execute(BrowserCmd::Screenshot).await,
244        ))
245    }
246}
247
248// ── Evaluate ────────────────────────────────────────────────────────
249
250pub struct BrowserEvaluateTool {
251    plugin: Arc<BrowserPlugin>,
252}
253
254impl BrowserEvaluateTool {
255    pub fn new(plugin: &Arc<BrowserPlugin>) -> Self {
256        Self {
257            plugin: shared_plugin_arg(plugin),
258        }
259    }
260
261    pub fn tool_def() -> ToolDef {
262        ToolDef {
263            name: "browser_evaluate".into(),
264            description: "Run arbitrary JavaScript in the page context and \
265                return its value as JSON (`result` field). Useful for \
266                reading computed state (`document.title`, \
267                `window.location.href`, form values), triggering \
268                keyboard events, scrolling, etc. The expression's return \
269                value must be JSON-serialisable — wrap complex objects in \
270                `JSON.stringify` if needed."
271                .into(),
272            parameters: json!({
273                "type": "object",
274                "properties": {
275                    "script": {
276                        "type": "string",
277                        "description": "JS expression or statement. Multi-line OK. Implicit return on the last expression."
278                    }
279                },
280                "required": ["script"]
281            }),
282        }
283    }
284}
285
286#[async_trait]
287impl ToolHandler for BrowserEvaluateTool {
288    async fn call(&self, _ctx: &AgentContext, args: Value) -> anyhow::Result<Value> {
289        let script = args["script"]
290            .as_str()
291            .ok_or_else(|| anyhow::anyhow!("browser_evaluate requires `script`"))?
292            .to_string();
293        Ok(result_to_json(
294            self.plugin.execute(BrowserCmd::Evaluate { script }).await,
295        ))
296    }
297}
298
299// ── Snapshot ────────────────────────────────────────────────────────
300
301pub struct BrowserSnapshotTool {
302    plugin: Arc<BrowserPlugin>,
303}
304
305impl BrowserSnapshotTool {
306    pub fn new(plugin: &Arc<BrowserPlugin>) -> Self {
307        Self {
308            plugin: shared_plugin_arg(plugin),
309        }
310    }
311
312    pub fn tool_def() -> ToolDef {
313        ToolDef {
314            name: "browser_snapshot".into(),
315            description: "Return a text representation of the current DOM \
316                with element references (`@e1`, `@e2`, …) you can pass to \
317                `browser_click` / `browser_fill` / `browser_scroll_to`. \
318                Includes visible text, semantic role, and hrefs. This is \
319                the primary way for the model to 'see' the page when \
320                vision isn't available. Call after navigate / click to \
321                refresh the refs — they're only stable within one snapshot."
322                .into(),
323            parameters: json!({ "type": "object", "properties": {} }),
324        }
325    }
326}
327
328#[async_trait]
329impl ToolHandler for BrowserSnapshotTool {
330    async fn call(&self, _ctx: &AgentContext, _args: Value) -> anyhow::Result<Value> {
331        Ok(result_to_json(
332            self.plugin.execute(BrowserCmd::Snapshot).await,
333        ))
334    }
335}
336
337// ── Scroll ──────────────────────────────────────────────────────────
338
339pub struct BrowserScrollToTool {
340    plugin: Arc<BrowserPlugin>,
341}
342
343impl BrowserScrollToTool {
344    pub fn new(plugin: &Arc<BrowserPlugin>) -> Self {
345        Self {
346            plugin: shared_plugin_arg(plugin),
347        }
348    }
349
350    pub fn tool_def() -> ToolDef {
351        ToolDef {
352            name: "browser_scroll_to".into(),
353            description: "Scroll an element into view. Useful when the \
354                snapshot shows refs to items below the fold — `click` \
355                works on off-screen elements but many UIs only bind \
356                handlers after the element scrolls into view."
357                .into(),
358            parameters: json!({
359                "type": "object",
360                "properties": {
361                    "target": {
362                        "type": "string",
363                        "description": "Element ref (`@eN`) or CSS selector."
364                    }
365                },
366                "required": ["target"]
367            }),
368        }
369    }
370}
371
372#[async_trait]
373impl ToolHandler for BrowserScrollToTool {
374    async fn call(&self, _ctx: &AgentContext, args: Value) -> anyhow::Result<Value> {
375        let target = args["target"]
376            .as_str()
377            .ok_or_else(|| anyhow::anyhow!("browser_scroll_to requires `target`"))?
378            .to_string();
379        Ok(result_to_json(
380            self.plugin.execute(BrowserCmd::ScrollTo { target }).await,
381        ))
382    }
383}
384
385// ── Derived helpers (JS-backed) ─────────────────────────────────────
386
387/// `browser_current_url` — reads `location.href` via evaluate. Not a
388/// separate CDP command; implemented on top of `Evaluate` for symmetry
389/// with the other tools. Saves the LLM one round-trip of figuring out
390/// the right script.
391pub struct BrowserCurrentUrlTool {
392    plugin: Arc<BrowserPlugin>,
393}
394
395impl BrowserCurrentUrlTool {
396    pub fn new(plugin: &Arc<BrowserPlugin>) -> Self {
397        Self {
398            plugin: shared_plugin_arg(plugin),
399        }
400    }
401
402    pub fn tool_def() -> ToolDef {
403        ToolDef {
404            name: "browser_current_url".into(),
405            description: "Return the current page URL. Implemented as a \
406                shortcut over `browser_evaluate` so the model doesn't \
407                have to remember `location.href`. Returned in `result`."
408                .into(),
409            parameters: json!({ "type": "object", "properties": {} }),
410        }
411    }
412}
413
414#[async_trait]
415impl ToolHandler for BrowserCurrentUrlTool {
416    async fn call(&self, _ctx: &AgentContext, _args: Value) -> anyhow::Result<Value> {
417        Ok(result_to_json(
418            self.plugin
419                .execute(BrowserCmd::Evaluate {
420                    script: "location.href".into(),
421                })
422                .await,
423        ))
424    }
425}
426
427/// `browser_wait_for` — polls a CSS selector until it appears (or
428/// timeout). Built on evaluate with a bounded retry loop so we don't
429/// add a new CDP command just for this.
430pub struct BrowserWaitForTool {
431    plugin: Arc<BrowserPlugin>,
432}
433
434impl BrowserWaitForTool {
435    pub fn new(plugin: &Arc<BrowserPlugin>) -> Self {
436        Self {
437            plugin: shared_plugin_arg(plugin),
438        }
439    }
440
441    pub fn tool_def() -> ToolDef {
442        ToolDef {
443            name: "browser_wait_for".into(),
444            description: "Poll a CSS selector every 250 ms until it \
445                appears in the DOM, up to `timeout_ms` (default 5000). \
446                Returns `{ok: true, found: bool}`. Use before \
447                `browser_click` on elements that arrive after an XHR / \
448                SPA navigation."
449                .into(),
450            parameters: json!({
451                "type": "object",
452                "properties": {
453                    "selector": {
454                        "type": "string",
455                        "description": "CSS selector the element must match."
456                    },
457                    "timeout_ms": {
458                        "type": "integer",
459                        "description": "Max wait in milliseconds. Default 5000, capped at 30000."
460                    }
461                },
462                "required": ["selector"]
463            }),
464        }
465    }
466}
467
468#[async_trait]
469impl ToolHandler for BrowserWaitForTool {
470    async fn call(&self, _ctx: &AgentContext, args: Value) -> anyhow::Result<Value> {
471        let selector = args["selector"]
472            .as_str()
473            .ok_or_else(|| anyhow::anyhow!("browser_wait_for requires `selector`"))?
474            .to_string();
475        let timeout_ms = args["timeout_ms"].as_u64().unwrap_or(5_000).min(30_000);
476        let deadline = std::time::Instant::now() + std::time::Duration::from_millis(timeout_ms);
477        loop {
478            let script = format!(
479                "!!document.querySelector({})",
480                serde_json::to_string(&selector)?
481            );
482            let res = self.plugin.execute(BrowserCmd::Evaluate { script }).await;
483            if res.ok {
484                if let Some(Value::Bool(true)) = res.result.as_ref() {
485                    return Ok(json!({"ok": true, "found": true}));
486                }
487            }
488            if std::time::Instant::now() >= deadline {
489                return Ok(json!({"ok": true, "found": false}));
490            }
491            tokio::time::sleep(std::time::Duration::from_millis(250)).await;
492        }
493    }
494}
495
496/// `browser_go_back` / `browser_go_forward` — history navigation via
497/// `evaluate`. Explicit tools save the LLM from having to know the
498/// `history.back()` / `history.forward()` snippets.
499pub struct BrowserGoBackTool {
500    plugin: Arc<BrowserPlugin>,
501}
502
503impl BrowserGoBackTool {
504    pub fn new(plugin: &Arc<BrowserPlugin>) -> Self {
505        Self {
506            plugin: shared_plugin_arg(plugin),
507        }
508    }
509
510    pub fn tool_def() -> ToolDef {
511        ToolDef {
512            name: "browser_go_back".into(),
513            description: "Navigate one step back in the browser history \
514                (equivalent to clicking the back button). Returns `{ok}`."
515                .into(),
516            parameters: json!({ "type": "object", "properties": {} }),
517        }
518    }
519}
520
521#[async_trait]
522impl ToolHandler for BrowserGoBackTool {
523    async fn call(&self, _ctx: &AgentContext, _args: Value) -> anyhow::Result<Value> {
524        Ok(result_to_json(
525            self.plugin
526                .execute(BrowserCmd::Evaluate {
527                    script: "history.back()".into(),
528                })
529                .await,
530        ))
531    }
532}
533
534pub struct BrowserGoForwardTool {
535    plugin: Arc<BrowserPlugin>,
536}
537
538impl BrowserGoForwardTool {
539    pub fn new(plugin: &Arc<BrowserPlugin>) -> Self {
540        Self {
541            plugin: shared_plugin_arg(plugin),
542        }
543    }
544
545    pub fn tool_def() -> ToolDef {
546        ToolDef {
547            name: "browser_go_forward".into(),
548            description: "Navigate one step forward in the browser history. \
549                Only succeeds if the user (or a prior tool call) just went \
550                back. Returns `{ok}`."
551                .into(),
552            parameters: json!({ "type": "object", "properties": {} }),
553        }
554    }
555}
556
557#[async_trait]
558impl ToolHandler for BrowserGoForwardTool {
559    async fn call(&self, _ctx: &AgentContext, _args: Value) -> anyhow::Result<Value> {
560        Ok(result_to_json(
561            self.plugin
562                .execute(BrowserCmd::Evaluate {
563                    script: "history.forward()".into(),
564                })
565                .await,
566        ))
567    }
568}
569
570/// `browser_press_key` — keyboard synthesis via `evaluate`. Useful for
571/// Enter-to-submit, Tab-next-field, Escape-to-close modal, etc.
572pub struct BrowserPressKeyTool {
573    plugin: Arc<BrowserPlugin>,
574}
575
576impl BrowserPressKeyTool {
577    pub fn new(plugin: &Arc<BrowserPlugin>) -> Self {
578        Self {
579            plugin: shared_plugin_arg(plugin),
580        }
581    }
582
583    pub fn tool_def() -> ToolDef {
584        ToolDef {
585            name: "browser_press_key".into(),
586            description: "Dispatch a synthetic KeyboardEvent (keydown + \
587                keyup) on the currently focused element. Handles common \
588                keys by name: `Enter`, `Tab`, `Escape`, `ArrowUp`, \
589                `ArrowDown`, `ArrowLeft`, `ArrowRight`. Any other value \
590                is treated as a literal character."
591                .into(),
592            parameters: json!({
593                "type": "object",
594                "properties": {
595                    "key": {
596                        "type": "string",
597                        "description": "Key name (Enter, Tab, Escape, Arrow*) or literal character."
598                    }
599                },
600                "required": ["key"]
601            }),
602        }
603    }
604}
605
606const ALLOWED_KEY_NAMES: &[&str] = &[
607    "Enter",
608    "Tab",
609    "Escape",
610    "ArrowUp",
611    "ArrowDown",
612    "ArrowLeft",
613    "ArrowRight",
614    "Backspace",
615    "Delete",
616    "Home",
617    "End",
618    "PageUp",
619    "PageDown",
620    "Space",
621];
622
623#[async_trait]
624impl ToolHandler for BrowserPressKeyTool {
625    async fn call(&self, _ctx: &AgentContext, args: Value) -> anyhow::Result<Value> {
626        let key = args["key"]
627            .as_str()
628            .ok_or_else(|| anyhow::anyhow!("browser_press_key requires `key`"))?;
629        // Restrict `key` to either a known named key (above) or a
630        // single Unicode character. Embedding an arbitrary LLM-supplied
631        // string into the eval'd JS body was a script-injection vector
632        // — serialization protected quote breakout but not larger
633        // sequences like `"x';alert(1);//"`.
634        let named = ALLOWED_KEY_NAMES.contains(&key);
635        let is_single_char = key.chars().count() == 1
636            && key.chars().next().map(|c| !c.is_control()).unwrap_or(false);
637        if !named && !is_single_char {
638            anyhow::bail!(
639                "browser_press_key rejected: expected a known key name or a single character, got `{key}`"
640            );
641        }
642        let script = format!(
643            r#"(function() {{
644                const k = {};
645                const map = {{
646                    Enter:      {{ key: 'Enter',      code: 'Enter',      keyCode: 13 }},
647                    Tab:        {{ key: 'Tab',        code: 'Tab',        keyCode: 9  }},
648                    Escape:     {{ key: 'Escape',     code: 'Escape',     keyCode: 27 }},
649                    ArrowUp:    {{ key: 'ArrowUp',    code: 'ArrowUp',    keyCode: 38 }},
650                    ArrowDown:  {{ key: 'ArrowDown',  code: 'ArrowDown',  keyCode: 40 }},
651                    ArrowLeft:  {{ key: 'ArrowLeft',  code: 'ArrowLeft',  keyCode: 37 }},
652                    ArrowRight: {{ key: 'ArrowRight', code: 'ArrowRight', keyCode: 39 }}
653                }};
654                const spec = map[k] || {{ key: k, code: k, keyCode: k.charCodeAt(0) }};
655                const target = document.activeElement || document.body;
656                target.dispatchEvent(new KeyboardEvent('keydown', {{ ...spec, bubbles: true }}));
657                target.dispatchEvent(new KeyboardEvent('keyup',   {{ ...spec, bubbles: true }}));
658                return true;
659            }})()"#,
660            serde_json::to_string(key)?
661        );
662        Ok(result_to_json(
663            self.plugin.execute(BrowserCmd::Evaluate { script }).await,
664        ))
665    }
666}
667
668// ── Registration helper ─────────────────────────────────────────────
669
670/// Register every browser tool on the given `ToolRegistry`. Call once
671/// per agent whose yaml lists `browser` in `plugins:`. Bundling the
672/// registration here means adding a new tool only requires editing this
673/// file, not every call site.
674pub fn register_all(
675    registry: &nexo_core::agent::tool_registry::ToolRegistry,
676    plugin: &Arc<BrowserPlugin>,
677) {
678    registry.register(
679        BrowserNavigateTool::tool_def(),
680        BrowserNavigateTool::new(plugin),
681    );
682    registry.register(BrowserClickTool::tool_def(), BrowserClickTool::new(plugin));
683    registry.register(BrowserFillTool::tool_def(), BrowserFillTool::new(plugin));
684    registry.register(
685        BrowserScreenshotTool::tool_def(),
686        BrowserScreenshotTool::new(plugin),
687    );
688    registry.register(
689        BrowserEvaluateTool::tool_def(),
690        BrowserEvaluateTool::new(plugin),
691    );
692    registry.register(
693        BrowserSnapshotTool::tool_def(),
694        BrowserSnapshotTool::new(plugin),
695    );
696    registry.register(
697        BrowserScrollToTool::tool_def(),
698        BrowserScrollToTool::new(plugin),
699    );
700    registry.register(
701        BrowserCurrentUrlTool::tool_def(),
702        BrowserCurrentUrlTool::new(plugin),
703    );
704    registry.register(
705        BrowserWaitForTool::tool_def(),
706        BrowserWaitForTool::new(plugin),
707    );
708    registry.register(
709        BrowserGoBackTool::tool_def(),
710        BrowserGoBackTool::new(plugin),
711    );
712    registry.register(
713        BrowserGoForwardTool::tool_def(),
714        BrowserGoForwardTool::new(plugin),
715    );
716    registry.register(
717        BrowserPressKeyTool::tool_def(),
718        BrowserPressKeyTool::new(plugin),
719    );
720}