Skip to main content

nenjo_tools/
browser.rs

1//! Browser automation tool with pluggable backends.
2//!
3//! By default this uses Vercel's `agent-browser` CLI for automation.
4//! Optionally, a Rust-native backend can be enabled at build time via
5//! `--features browser-native` and selected through config.
6//! Computer-use (OS-level) actions are supported via an optional sidecar endpoint.
7#![allow(unexpected_cfgs)]
8
9use crate::security::SecurityPolicy;
10use crate::{Tool, ToolCategory, ToolResult};
11use anyhow::Context;
12use async_trait::async_trait;
13use serde::{Deserialize, Serialize};
14use serde_json::{Value, json};
15use std::net::ToSocketAddrs;
16use std::process::Stdio;
17use std::sync::Arc;
18use std::time::Duration;
19use tokio::process::Command;
20use tracing::debug;
21
22/// Computer-use sidecar settings.
23#[derive(Debug, Clone)]
24pub struct ComputerUseConfig {
25    pub endpoint: String,
26    pub api_key: Option<String>,
27    pub timeout_ms: u64,
28    pub allow_remote_endpoint: bool,
29    pub window_allowlist: Vec<String>,
30    pub max_coordinate_x: Option<i64>,
31    pub max_coordinate_y: Option<i64>,
32}
33
34impl Default for ComputerUseConfig {
35    fn default() -> Self {
36        Self {
37            endpoint: "http://127.0.0.1:8787/v1/actions".into(),
38            api_key: None,
39            timeout_ms: 15_000,
40            allow_remote_endpoint: false,
41            window_allowlist: Vec::new(),
42            max_coordinate_x: None,
43            max_coordinate_y: None,
44        }
45    }
46}
47
48/// Browser automation tool using pluggable backends.
49pub struct BrowserTool {
50    security: Arc<SecurityPolicy>,
51    allowed_domains: Vec<String>,
52    session_name: Option<String>,
53    backend: String,
54    // Used only when `browser-native` feature is enabled.
55    #[allow(dead_code)]
56    native_headless: bool,
57    #[allow(dead_code)]
58    native_webdriver_url: String,
59    #[allow(dead_code)]
60    native_chrome_path: Option<String>,
61    computer_use: ComputerUseConfig,
62    #[cfg(feature = "browser-native")]
63    native_state: tokio::sync::Mutex<native_backend::NativeBrowserState>,
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67enum BrowserBackendKind {
68    AgentBrowser,
69    RustNative,
70    ComputerUse,
71    Auto,
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75enum ResolvedBackend {
76    AgentBrowser,
77    RustNative,
78    ComputerUse,
79}
80
81impl BrowserBackendKind {
82    fn parse(raw: &str) -> anyhow::Result<Self> {
83        let key = raw.trim().to_ascii_lowercase().replace('-', "_");
84        match key.as_str() {
85            "agent_browser" | "agentbrowser" => Ok(Self::AgentBrowser),
86            "rust_native" | "native" => Ok(Self::RustNative),
87            "computer_use" | "computeruse" => Ok(Self::ComputerUse),
88            "auto" => Ok(Self::Auto),
89            _ => anyhow::bail!(
90                "Unsupported browser backend '{raw}'. Use 'agent_browser', 'rust_native', 'computer_use', or 'auto'"
91            ),
92        }
93    }
94
95    fn as_str(self) -> &'static str {
96        match self {
97            Self::AgentBrowser => "agent_browser",
98            Self::RustNative => "rust_native",
99            Self::ComputerUse => "computer_use",
100            Self::Auto => "auto",
101        }
102    }
103}
104
105/// Response from agent-browser --json commands
106#[derive(Debug, Deserialize)]
107struct AgentBrowserResponse {
108    success: bool,
109    data: Option<Value>,
110    error: Option<String>,
111}
112
113/// Response format from computer-use sidecar.
114#[derive(Debug, Deserialize)]
115struct ComputerUseResponse {
116    #[serde(default)]
117    success: Option<bool>,
118    #[serde(default)]
119    data: Option<Value>,
120    #[serde(default)]
121    error: Option<String>,
122}
123
124/// Supported browser actions
125#[derive(Debug, Clone, Serialize, Deserialize)]
126#[serde(rename_all = "snake_case")]
127pub enum BrowserAction {
128    /// Navigate to a URL
129    Open { url: String },
130    /// Get accessibility snapshot with refs
131    Snapshot {
132        #[serde(default)]
133        interactive_only: bool,
134        #[serde(default)]
135        compact: bool,
136        #[serde(default)]
137        depth: Option<u32>,
138    },
139    /// Click an element by ref or selector
140    Click { selector: String },
141    /// Fill a form field
142    Fill { selector: String, value: String },
143    /// Type text into focused element
144    Type { selector: String, text: String },
145    /// Get text content of element
146    GetText { selector: String },
147    /// Get page title
148    GetTitle,
149    /// Get current URL
150    GetUrl,
151    /// Take screenshot
152    Screenshot {
153        #[serde(default)]
154        path: Option<String>,
155        #[serde(default)]
156        full_page: bool,
157    },
158    /// Wait for element or time
159    Wait {
160        #[serde(default)]
161        selector: Option<String>,
162        #[serde(default)]
163        ms: Option<u64>,
164        #[serde(default)]
165        text: Option<String>,
166    },
167    /// Press a key
168    Press { key: String },
169    /// Hover over element
170    Hover { selector: String },
171    /// Scroll page
172    Scroll {
173        direction: String,
174        #[serde(default)]
175        pixels: Option<u32>,
176    },
177    /// Check if element is visible
178    IsVisible { selector: String },
179    /// Close browser
180    Close,
181    /// Find element by semantic locator
182    Find {
183        by: String, // role, text, label, placeholder, testid
184        value: String,
185        action: String, // click, fill, text, hover
186        #[serde(default)]
187        fill_value: Option<String>,
188    },
189}
190
191impl BrowserTool {
192    pub fn new(
193        security: Arc<SecurityPolicy>,
194        allowed_domains: Vec<String>,
195        session_name: Option<String>,
196    ) -> Self {
197        Self::new_with_backend(
198            security,
199            allowed_domains,
200            session_name,
201            "agent_browser".into(),
202            true,
203            "http://127.0.0.1:9515".into(),
204            None,
205            ComputerUseConfig::default(),
206        )
207    }
208
209    #[allow(clippy::too_many_arguments)]
210    pub fn new_with_backend(
211        security: Arc<SecurityPolicy>,
212        allowed_domains: Vec<String>,
213        session_name: Option<String>,
214        backend: String,
215        native_headless: bool,
216        native_webdriver_url: String,
217        native_chrome_path: Option<String>,
218        computer_use: ComputerUseConfig,
219    ) -> Self {
220        Self {
221            security,
222            allowed_domains: normalize_domains(allowed_domains),
223            session_name,
224            backend,
225            native_headless,
226            native_webdriver_url,
227            native_chrome_path,
228            computer_use,
229            #[cfg(feature = "browser-native")]
230            native_state: tokio::sync::Mutex::new(native_backend::NativeBrowserState::default()),
231        }
232    }
233
234    /// Check if agent-browser CLI is available
235    pub async fn is_agent_browser_available() -> bool {
236        Command::new("agent-browser")
237            .arg("--version")
238            .stdout(Stdio::null())
239            .stderr(Stdio::null())
240            .status()
241            .await
242            .map(|s| s.success())
243            .unwrap_or(false)
244    }
245
246    /// Backward-compatible alias.
247    pub async fn is_available() -> bool {
248        Self::is_agent_browser_available().await
249    }
250
251    fn configured_backend(&self) -> anyhow::Result<BrowserBackendKind> {
252        BrowserBackendKind::parse(&self.backend)
253    }
254
255    fn rust_native_compiled() -> bool {
256        cfg!(feature = "browser-native")
257    }
258
259    fn rust_native_available(&self) -> bool {
260        #[cfg(feature = "browser-native")]
261        {
262            native_backend::NativeBrowserState::is_available(
263                self.native_headless,
264                &self.native_webdriver_url,
265                self.native_chrome_path.as_deref(),
266            )
267        }
268        #[cfg(not(feature = "browser-native"))]
269        {
270            false
271        }
272    }
273
274    fn computer_use_endpoint_url(&self) -> anyhow::Result<reqwest::Url> {
275        if self.computer_use.timeout_ms == 0 {
276            anyhow::bail!("browser.computer_use.timeout_ms must be > 0");
277        }
278
279        let endpoint = self.computer_use.endpoint.trim();
280        if endpoint.is_empty() {
281            anyhow::bail!("browser.computer_use.endpoint cannot be empty");
282        }
283
284        let parsed = reqwest::Url::parse(endpoint).map_err(|_| {
285            anyhow::anyhow!(
286                "Invalid browser.computer_use.endpoint: '{endpoint}'. Expected http(s) URL"
287            )
288        })?;
289
290        let scheme = parsed.scheme();
291        if scheme != "http" && scheme != "https" {
292            anyhow::bail!("browser.computer_use.endpoint must use http:// or https://");
293        }
294
295        let host = parsed
296            .host_str()
297            .ok_or_else(|| anyhow::anyhow!("browser.computer_use.endpoint must include host"))?;
298
299        let host_is_private = is_private_host(host);
300        if !self.computer_use.allow_remote_endpoint && !host_is_private {
301            anyhow::bail!(
302                "browser.computer_use.endpoint host '{host}' is public. Set browser.computer_use.allow_remote_endpoint=true to allow it"
303            );
304        }
305
306        if self.computer_use.allow_remote_endpoint && !host_is_private && scheme != "https" {
307            anyhow::bail!(
308                "browser.computer_use.endpoint must use https:// when allow_remote_endpoint=true and host is public"
309            );
310        }
311
312        Ok(parsed)
313    }
314
315    fn computer_use_available(&self) -> anyhow::Result<bool> {
316        let endpoint = self.computer_use_endpoint_url()?;
317        Ok(endpoint_reachable(&endpoint, Duration::from_millis(500)))
318    }
319
320    async fn resolve_backend(&self) -> anyhow::Result<ResolvedBackend> {
321        let configured = self.configured_backend()?;
322
323        match configured {
324            BrowserBackendKind::AgentBrowser => {
325                if Self::is_agent_browser_available().await {
326                    Ok(ResolvedBackend::AgentBrowser)
327                } else {
328                    anyhow::bail!(
329                        "browser.backend='{}' but agent-browser CLI is unavailable. Install with: npm install -g agent-browser",
330                        configured.as_str()
331                    )
332                }
333            }
334            BrowserBackendKind::RustNative => {
335                if !Self::rust_native_compiled() {
336                    anyhow::bail!(
337                        "browser.backend='rust_native' requires build feature 'browser-native'"
338                    );
339                }
340                if !self.rust_native_available() {
341                    anyhow::bail!(
342                        "Rust-native browser backend is enabled but WebDriver endpoint is unreachable. Set browser.native_webdriver_url and start a compatible driver"
343                    );
344                }
345                Ok(ResolvedBackend::RustNative)
346            }
347            BrowserBackendKind::ComputerUse => {
348                if !self.computer_use_available()? {
349                    anyhow::bail!(
350                        "browser.backend='computer_use' but sidecar endpoint is unreachable. Check browser.computer_use.endpoint and sidecar status"
351                    );
352                }
353                Ok(ResolvedBackend::ComputerUse)
354            }
355            BrowserBackendKind::Auto => {
356                if Self::rust_native_compiled() && self.rust_native_available() {
357                    return Ok(ResolvedBackend::RustNative);
358                }
359                if Self::is_agent_browser_available().await {
360                    return Ok(ResolvedBackend::AgentBrowser);
361                }
362
363                let computer_use_err = match self.computer_use_available() {
364                    Ok(true) => return Ok(ResolvedBackend::ComputerUse),
365                    Ok(false) => None,
366                    Err(err) => Some(err.to_string()),
367                };
368
369                if Self::rust_native_compiled() {
370                    if let Some(err) = computer_use_err {
371                        anyhow::bail!(
372                            "browser.backend='auto' found no usable backend (agent-browser missing, rust-native unavailable, computer-use invalid: {err})"
373                        );
374                    }
375                    anyhow::bail!(
376                        "browser.backend='auto' found no usable backend (agent-browser missing, rust-native unavailable, computer-use sidecar unreachable)"
377                    )
378                }
379
380                if let Some(err) = computer_use_err {
381                    anyhow::bail!(
382                        "browser.backend='auto' needs agent-browser CLI, browser-native, or valid computer-use sidecar (error: {err})"
383                    );
384                }
385
386                anyhow::bail!(
387                    "browser.backend='auto' needs agent-browser CLI, browser-native, or computer-use sidecar"
388                )
389            }
390        }
391    }
392
393    /// Validate URL against allowlist
394    fn validate_url(&self, url: &str) -> anyhow::Result<()> {
395        let url = url.trim();
396
397        if url.is_empty() {
398            anyhow::bail!("URL cannot be empty");
399        }
400
401        // Block file:// URLs — browser file access bypasses all SSRF and
402        // domain-allowlist controls and can exfiltrate arbitrary local files.
403        if url.starts_with("file://") {
404            anyhow::bail!("file:// URLs are not allowed in browser automation");
405        }
406
407        if !url.starts_with("https://") && !url.starts_with("http://") {
408            anyhow::bail!("Only http:// and https:// URLs are allowed");
409        }
410
411        if self.allowed_domains.is_empty() {
412            anyhow::bail!(
413                "Browser tool enabled but no allowed_domains configured. \
414                Add [browser].allowed_domains in config.toml"
415            );
416        }
417
418        let host = extract_host(url)?;
419
420        if is_private_host(&host) {
421            anyhow::bail!("Blocked local/private host: {host}");
422        }
423
424        if !host_matches_allowlist(&host, &self.allowed_domains) {
425            anyhow::bail!("Host '{host}' not in browser.allowed_domains");
426        }
427
428        Ok(())
429    }
430
431    /// Execute an agent-browser command
432    async fn run_command(&self, args: &[&str]) -> anyhow::Result<AgentBrowserResponse> {
433        let mut cmd = Command::new("agent-browser");
434
435        // Add session if configured
436        if let Some(ref session) = self.session_name {
437            cmd.arg("--session").arg(session);
438        }
439
440        // Add --json for machine-readable output
441        cmd.args(args).arg("--json");
442
443        debug!("Running: agent-browser {} --json", args.join(" "));
444
445        let output = cmd
446            .stdout(Stdio::piped())
447            .stderr(Stdio::piped())
448            .output()
449            .await?;
450
451        let stdout = String::from_utf8_lossy(&output.stdout);
452        let stderr = String::from_utf8_lossy(&output.stderr);
453
454        if !stderr.is_empty() {
455            debug!("agent-browser stderr: {}", stderr);
456        }
457
458        // Parse JSON response
459        if let Ok(resp) = serde_json::from_str::<AgentBrowserResponse>(&stdout) {
460            return Ok(resp);
461        }
462
463        // Fallback for non-JSON output
464        if output.status.success() {
465            Ok(AgentBrowserResponse {
466                success: true,
467                data: Some(json!({ "output": stdout.trim() })),
468                error: None,
469            })
470        } else {
471            Ok(AgentBrowserResponse {
472                success: false,
473                data: None,
474                error: Some(stderr.trim().to_string()),
475            })
476        }
477    }
478
479    /// Execute a browser action via agent-browser CLI
480    #[allow(clippy::too_many_lines)]
481    async fn execute_agent_browser_action(
482        &self,
483        action: BrowserAction,
484    ) -> anyhow::Result<ToolResult> {
485        match action {
486            BrowserAction::Open { url } => {
487                self.validate_url(&url)?;
488                let resp = self.run_command(&["open", &url]).await?;
489                self.to_result(resp)
490            }
491
492            BrowserAction::Snapshot {
493                interactive_only,
494                compact,
495                depth,
496            } => {
497                let mut args = vec!["snapshot"];
498                if interactive_only {
499                    args.push("-i");
500                }
501                if compact {
502                    args.push("-c");
503                }
504                let depth_str;
505                if let Some(d) = depth {
506                    args.push("-d");
507                    depth_str = d.to_string();
508                    args.push(&depth_str);
509                }
510                let resp = self.run_command(&args).await?;
511                self.to_result(resp)
512            }
513
514            BrowserAction::Click { selector } => {
515                let resp = self.run_command(&["click", &selector]).await?;
516                self.to_result(resp)
517            }
518
519            BrowserAction::Fill { selector, value } => {
520                let resp = self.run_command(&["fill", &selector, &value]).await?;
521                self.to_result(resp)
522            }
523
524            BrowserAction::Type { selector, text } => {
525                let resp = self.run_command(&["type", &selector, &text]).await?;
526                self.to_result(resp)
527            }
528
529            BrowserAction::GetText { selector } => {
530                let resp = self.run_command(&["get", "text", &selector]).await?;
531                self.to_result(resp)
532            }
533
534            BrowserAction::GetTitle => {
535                let resp = self.run_command(&["get", "title"]).await?;
536                self.to_result(resp)
537            }
538
539            BrowserAction::GetUrl => {
540                let resp = self.run_command(&["get", "url"]).await?;
541                self.to_result(resp)
542            }
543
544            BrowserAction::Screenshot { path, full_page } => {
545                let mut args = vec!["screenshot"];
546                if let Some(ref p) = path {
547                    args.push(p);
548                }
549                if full_page {
550                    args.push("--full");
551                }
552                let resp = self.run_command(&args).await?;
553                self.to_result(resp)
554            }
555
556            BrowserAction::Wait { selector, ms, text } => {
557                let mut args = vec!["wait"];
558                let ms_str;
559                if let Some(sel) = selector.as_ref() {
560                    args.push(sel);
561                } else if let Some(millis) = ms {
562                    ms_str = millis.to_string();
563                    args.push(&ms_str);
564                } else if let Some(ref t) = text {
565                    args.push("--text");
566                    args.push(t);
567                }
568                let resp = self.run_command(&args).await?;
569                self.to_result(resp)
570            }
571
572            BrowserAction::Press { key } => {
573                let resp = self.run_command(&["press", &key]).await?;
574                self.to_result(resp)
575            }
576
577            BrowserAction::Hover { selector } => {
578                let resp = self.run_command(&["hover", &selector]).await?;
579                self.to_result(resp)
580            }
581
582            BrowserAction::Scroll { direction, pixels } => {
583                let mut args = vec!["scroll", &direction];
584                let px_str;
585                if let Some(px) = pixels {
586                    px_str = px.to_string();
587                    args.push(&px_str);
588                }
589                let resp = self.run_command(&args).await?;
590                self.to_result(resp)
591            }
592
593            BrowserAction::IsVisible { selector } => {
594                let resp = self.run_command(&["is", "visible", &selector]).await?;
595                self.to_result(resp)
596            }
597
598            BrowserAction::Close => {
599                let resp = self.run_command(&["close"]).await?;
600                self.to_result(resp)
601            }
602
603            BrowserAction::Find {
604                by,
605                value,
606                action,
607                fill_value,
608            } => {
609                let mut args = vec!["find", &by, &value, &action];
610                if let Some(ref fv) = fill_value {
611                    args.push(fv);
612                }
613                let resp = self.run_command(&args).await?;
614                self.to_result(resp)
615            }
616        }
617    }
618
619    #[allow(clippy::unused_async)]
620    async fn execute_rust_native_action(
621        &self,
622        action: BrowserAction,
623    ) -> anyhow::Result<ToolResult> {
624        #[cfg(feature = "browser-native")]
625        {
626            let mut state = self.native_state.lock().await;
627
628            let output = state
629                .execute_action(
630                    action,
631                    self.native_headless,
632                    &self.native_webdriver_url,
633                    self.native_chrome_path.as_deref(),
634                )
635                .await?;
636
637            Ok(ToolResult {
638                success: true,
639                output: serde_json::to_string_pretty(&output).unwrap_or_default(),
640                error: None,
641            })
642        }
643
644        #[cfg(not(feature = "browser-native"))]
645        {
646            let _ = action;
647            anyhow::bail!(
648                "Rust-native browser backend is not compiled. Rebuild with --features browser-native"
649            )
650        }
651    }
652
653    fn validate_coordinate(&self, key: &str, value: i64, max: Option<i64>) -> anyhow::Result<()> {
654        if value < 0 {
655            anyhow::bail!("'{key}' must be >= 0")
656        }
657        if let Some(limit) = max {
658            if limit < 0 {
659                anyhow::bail!("Configured coordinate limit for '{key}' must be >= 0")
660            }
661            if value > limit {
662                anyhow::bail!("'{key}'={value} exceeds configured limit {limit}")
663            }
664        }
665        Ok(())
666    }
667
668    fn read_required_i64(
669        &self,
670        params: &serde_json::Map<String, Value>,
671        key: &str,
672    ) -> anyhow::Result<i64> {
673        params
674            .get(key)
675            .and_then(Value::as_i64)
676            .ok_or_else(|| anyhow::anyhow!("Missing or invalid '{key}' parameter"))
677    }
678
679    fn validate_computer_use_action(
680        &self,
681        action: &str,
682        params: &serde_json::Map<String, Value>,
683    ) -> anyhow::Result<()> {
684        match action {
685            "open" => {
686                let url = params
687                    .get("url")
688                    .and_then(Value::as_str)
689                    .ok_or_else(|| anyhow::anyhow!("Missing 'url' for open action"))?;
690                self.validate_url(url)?;
691            }
692            "mouse_move" | "mouse_click" => {
693                let x = self.read_required_i64(params, "x")?;
694                let y = self.read_required_i64(params, "y")?;
695                self.validate_coordinate("x", x, self.computer_use.max_coordinate_x)?;
696                self.validate_coordinate("y", y, self.computer_use.max_coordinate_y)?;
697            }
698            "mouse_drag" => {
699                let from_x = self.read_required_i64(params, "from_x")?;
700                let from_y = self.read_required_i64(params, "from_y")?;
701                let to_x = self.read_required_i64(params, "to_x")?;
702                let to_y = self.read_required_i64(params, "to_y")?;
703                self.validate_coordinate("from_x", from_x, self.computer_use.max_coordinate_x)?;
704                self.validate_coordinate("to_x", to_x, self.computer_use.max_coordinate_x)?;
705                self.validate_coordinate("from_y", from_y, self.computer_use.max_coordinate_y)?;
706                self.validate_coordinate("to_y", to_y, self.computer_use.max_coordinate_y)?;
707            }
708            _ => {}
709        }
710        Ok(())
711    }
712
713    async fn execute_computer_use_action(
714        &self,
715        action: &str,
716        args: &Value,
717    ) -> anyhow::Result<ToolResult> {
718        let endpoint = self.computer_use_endpoint_url()?;
719
720        let mut params = args
721            .as_object()
722            .cloned()
723            .ok_or_else(|| anyhow::anyhow!("browser args must be a JSON object"))?;
724        params.remove("action");
725
726        self.validate_computer_use_action(action, &params)?;
727
728        let payload = json!({
729            "action": action,
730            "params": params,
731            "policy": {
732                "allowed_domains": self.allowed_domains,
733                "window_allowlist": self.computer_use.window_allowlist,
734                "max_coordinate_x": self.computer_use.max_coordinate_x,
735                "max_coordinate_y": self.computer_use.max_coordinate_y,
736            },
737            "metadata": {
738                "session_name": self.session_name,
739                "source": "nenjo.browser",
740                "version": env!("CARGO_PKG_VERSION"),
741            }
742        });
743
744        let client = reqwest::Client::new();
745        let mut request = client
746            .post(endpoint)
747            .timeout(Duration::from_millis(self.computer_use.timeout_ms))
748            .json(&payload);
749
750        if let Some(api_key) = self.computer_use.api_key.as_deref() {
751            let token = api_key.trim();
752            if !token.is_empty() {
753                request = request.bearer_auth(token);
754            }
755        }
756
757        let response = request.send().await.with_context(|| {
758            format!(
759                "Failed to call computer-use sidecar at {}",
760                self.computer_use.endpoint
761            )
762        })?;
763
764        let status = response.status();
765        let body = response
766            .text()
767            .await
768            .context("Failed to read computer-use sidecar response body")?;
769
770        if let Ok(parsed) = serde_json::from_str::<ComputerUseResponse>(&body) {
771            if status.is_success() && parsed.success.unwrap_or(true) {
772                let output = parsed
773                    .data
774                    .map(|data| serde_json::to_string_pretty(&data).unwrap_or_default())
775                    .unwrap_or_else(|| {
776                        serde_json::to_string_pretty(&json!({
777                            "backend": "computer_use",
778                            "action": action,
779                            "ok": true,
780                        }))
781                        .unwrap_or_default()
782                    });
783
784                return Ok(ToolResult {
785                    success: true,
786                    output,
787                    error: None,
788                });
789            }
790
791            let error = parsed.error.or_else(|| {
792                if status.is_success() && parsed.success == Some(false) {
793                    Some("computer-use sidecar returned success=false".to_string())
794                } else {
795                    Some(format!(
796                        "computer-use sidecar request failed with status {status}"
797                    ))
798                }
799            });
800
801            return Ok(ToolResult {
802                success: false,
803                output: String::new(),
804                error,
805            });
806        }
807
808        if status.is_success() {
809            return Ok(ToolResult {
810                success: true,
811                output: body,
812                error: None,
813            });
814        }
815
816        Ok(ToolResult {
817            success: false,
818            output: String::new(),
819            error: Some(format!(
820                "computer-use sidecar request failed with status {status}: {}",
821                body.trim()
822            )),
823        })
824    }
825
826    async fn execute_action(
827        &self,
828        action: BrowserAction,
829        backend: ResolvedBackend,
830    ) -> anyhow::Result<ToolResult> {
831        match backend {
832            ResolvedBackend::AgentBrowser => self.execute_agent_browser_action(action).await,
833            ResolvedBackend::RustNative => self.execute_rust_native_action(action).await,
834            ResolvedBackend::ComputerUse => anyhow::bail!(
835                "Internal error: computer_use backend must be handled before BrowserAction parsing"
836            ),
837        }
838    }
839
840    #[allow(clippy::unnecessary_wraps, clippy::unused_self)]
841    fn to_result(&self, resp: AgentBrowserResponse) -> anyhow::Result<ToolResult> {
842        if resp.success {
843            let output = resp
844                .data
845                .map(|d| serde_json::to_string_pretty(&d).unwrap_or_default())
846                .unwrap_or_default();
847            Ok(ToolResult {
848                success: true,
849                output,
850                error: None,
851            })
852        } else {
853            Ok(ToolResult {
854                success: false,
855                output: String::new(),
856                error: resp.error,
857            })
858        }
859    }
860}
861
862#[allow(clippy::too_many_lines)]
863#[async_trait]
864impl Tool for BrowserTool {
865    fn category(&self) -> ToolCategory {
866        ToolCategory::ReadWrite
867    }
868
869    fn name(&self) -> &str {
870        "browser"
871    }
872
873    fn description(&self) -> &str {
874        concat!(
875            "Web/browser automation with pluggable backends (agent-browser, rust-native, computer_use). ",
876            "Supports DOM actions plus optional OS-level actions (mouse_move, mouse_click, mouse_drag, ",
877            "key_type, key_press, screen_capture) through a computer-use sidecar. Use 'snapshot' to map ",
878            "interactive elements to refs (@e1, @e2). Enforces browser.allowed_domains for open actions."
879        )
880    }
881
882    fn parameters_schema(&self) -> Value {
883        json!({
884            "type": "object",
885            "properties": {
886                "action": {
887                    "type": "string",
888                    "enum": ["open", "snapshot", "click", "fill", "type", "get_text",
889                             "get_title", "get_url", "screenshot", "wait", "press",
890                             "hover", "scroll", "is_visible", "close", "find",
891                             "mouse_move", "mouse_click", "mouse_drag", "key_type",
892                             "key_press", "screen_capture"],
893                    "description": "Browser action to perform (OS-level actions require backend=computer_use)"
894                },
895                "url": {
896                    "type": "string",
897                    "description": "URL to navigate to (for 'open' action)"
898                },
899                "selector": {
900                    "type": "string",
901                    "description": "Element selector: @ref (e.g. @e1), CSS (#id, .class), or text=..."
902                },
903                "value": {
904                    "type": "string",
905                    "description": "Value to fill or type"
906                },
907                "text": {
908                    "type": "string",
909                    "description": "Text to type or wait for"
910                },
911                "key": {
912                    "type": "string",
913                    "description": "Key to press (Enter, Tab, Escape, etc.)"
914                },
915                "x": {
916                    "type": "integer",
917                    "description": "Screen X coordinate (computer_use: mouse_move/mouse_click)"
918                },
919                "y": {
920                    "type": "integer",
921                    "description": "Screen Y coordinate (computer_use: mouse_move/mouse_click)"
922                },
923                "from_x": {
924                    "type": "integer",
925                    "description": "Drag source X coordinate (computer_use: mouse_drag)"
926                },
927                "from_y": {
928                    "type": "integer",
929                    "description": "Drag source Y coordinate (computer_use: mouse_drag)"
930                },
931                "to_x": {
932                    "type": "integer",
933                    "description": "Drag target X coordinate (computer_use: mouse_drag)"
934                },
935                "to_y": {
936                    "type": "integer",
937                    "description": "Drag target Y coordinate (computer_use: mouse_drag)"
938                },
939                "button": {
940                    "type": "string",
941                    "enum": ["left", "right", "middle"],
942                    "description": "Mouse button for computer_use mouse_click"
943                },
944                "direction": {
945                    "type": "string",
946                    "enum": ["up", "down", "left", "right"],
947                    "description": "Scroll direction"
948                },
949                "pixels": {
950                    "type": "integer",
951                    "description": "Pixels to scroll"
952                },
953                "interactive_only": {
954                    "type": "boolean",
955                    "description": "For snapshot: only show interactive elements"
956                },
957                "compact": {
958                    "type": "boolean",
959                    "description": "For snapshot: remove empty structural elements"
960                },
961                "depth": {
962                    "type": "integer",
963                    "description": "For snapshot: limit tree depth"
964                },
965                "full_page": {
966                    "type": "boolean",
967                    "description": "For screenshot: capture full page"
968                },
969                "path": {
970                    "type": "string",
971                    "description": "File path for screenshot"
972                },
973                "ms": {
974                    "type": "integer",
975                    "description": "Milliseconds to wait"
976                },
977                "by": {
978                    "type": "string",
979                    "enum": ["role", "text", "label", "placeholder", "testid"],
980                    "description": "For find: semantic locator type"
981                },
982                "find_action": {
983                    "type": "string",
984                    "enum": ["click", "fill", "text", "hover", "check"],
985                    "description": "For find: action to perform on found element"
986                },
987                "fill_value": {
988                    "type": "string",
989                    "description": "For find with fill action: value to fill"
990                }
991            },
992            "required": ["action"]
993        })
994    }
995
996    async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
997        // Security checks
998        if !self.security.can_act() {
999            return Ok(ToolResult {
1000                success: false,
1001                output: String::new(),
1002                error: Some("Action blocked: autonomy is read-only".into()),
1003            });
1004        }
1005
1006        if !self.security.record_action() {
1007            return Ok(ToolResult {
1008                success: false,
1009                output: String::new(),
1010                error: Some("Action blocked: rate limit exceeded".into()),
1011            });
1012        }
1013
1014        let backend = match self.resolve_backend().await {
1015            Ok(selected) => selected,
1016            Err(error) => {
1017                return Ok(ToolResult {
1018                    success: false,
1019                    output: String::new(),
1020                    error: Some(error.to_string()),
1021                });
1022            }
1023        };
1024
1025        // Parse action from args
1026        let action_str = args
1027            .get("action")
1028            .and_then(|v| v.as_str())
1029            .ok_or_else(|| anyhow::anyhow!("Missing 'action' parameter"))?;
1030
1031        if !is_supported_browser_action(action_str) {
1032            return Ok(ToolResult {
1033                success: false,
1034                output: String::new(),
1035                error: Some(format!("Unknown action: {action_str}")),
1036            });
1037        }
1038
1039        if backend == ResolvedBackend::ComputerUse {
1040            return self.execute_computer_use_action(action_str, &args).await;
1041        }
1042
1043        let action = match action_str {
1044            "open" => {
1045                let url = args
1046                    .get("url")
1047                    .and_then(|v| v.as_str())
1048                    .ok_or_else(|| anyhow::anyhow!("Missing 'url' for open action"))?;
1049                BrowserAction::Open { url: url.into() }
1050            }
1051            "snapshot" => BrowserAction::Snapshot {
1052                interactive_only: args
1053                    .get("interactive_only")
1054                    .and_then(serde_json::Value::as_bool)
1055                    .unwrap_or(true), // Default to interactive for AI
1056                compact: args
1057                    .get("compact")
1058                    .and_then(serde_json::Value::as_bool)
1059                    .unwrap_or(true),
1060                depth: args
1061                    .get("depth")
1062                    .and_then(serde_json::Value::as_u64)
1063                    .map(|d| u32::try_from(d).unwrap_or(u32::MAX)),
1064            },
1065            "click" => {
1066                let selector = args
1067                    .get("selector")
1068                    .and_then(|v| v.as_str())
1069                    .ok_or_else(|| anyhow::anyhow!("Missing 'selector' for click"))?;
1070                BrowserAction::Click {
1071                    selector: selector.into(),
1072                }
1073            }
1074            "fill" => {
1075                let selector = args
1076                    .get("selector")
1077                    .and_then(|v| v.as_str())
1078                    .ok_or_else(|| anyhow::anyhow!("Missing 'selector' for fill"))?;
1079                let value = args
1080                    .get("value")
1081                    .and_then(|v| v.as_str())
1082                    .ok_or_else(|| anyhow::anyhow!("Missing 'value' for fill"))?;
1083                BrowserAction::Fill {
1084                    selector: selector.into(),
1085                    value: value.into(),
1086                }
1087            }
1088            "type" => {
1089                let selector = args
1090                    .get("selector")
1091                    .and_then(|v| v.as_str())
1092                    .ok_or_else(|| anyhow::anyhow!("Missing 'selector' for type"))?;
1093                let text = args
1094                    .get("text")
1095                    .and_then(|v| v.as_str())
1096                    .ok_or_else(|| anyhow::anyhow!("Missing 'text' for type"))?;
1097                BrowserAction::Type {
1098                    selector: selector.into(),
1099                    text: text.into(),
1100                }
1101            }
1102            "get_text" => {
1103                let selector = args
1104                    .get("selector")
1105                    .and_then(|v| v.as_str())
1106                    .ok_or_else(|| anyhow::anyhow!("Missing 'selector' for get_text"))?;
1107                BrowserAction::GetText {
1108                    selector: selector.into(),
1109                }
1110            }
1111            "get_title" => BrowserAction::GetTitle,
1112            "get_url" => BrowserAction::GetUrl,
1113            "screenshot" => BrowserAction::Screenshot {
1114                path: args.get("path").and_then(|v| v.as_str()).map(String::from),
1115                full_page: args
1116                    .get("full_page")
1117                    .and_then(serde_json::Value::as_bool)
1118                    .unwrap_or(false),
1119            },
1120            "wait" => BrowserAction::Wait {
1121                selector: args
1122                    .get("selector")
1123                    .and_then(|v| v.as_str())
1124                    .map(String::from),
1125                ms: args.get("ms").and_then(serde_json::Value::as_u64),
1126                text: args.get("text").and_then(|v| v.as_str()).map(String::from),
1127            },
1128            "press" => {
1129                let key = args
1130                    .get("key")
1131                    .and_then(|v| v.as_str())
1132                    .ok_or_else(|| anyhow::anyhow!("Missing 'key' for press"))?;
1133                BrowserAction::Press { key: key.into() }
1134            }
1135            "hover" => {
1136                let selector = args
1137                    .get("selector")
1138                    .and_then(|v| v.as_str())
1139                    .ok_or_else(|| anyhow::anyhow!("Missing 'selector' for hover"))?;
1140                BrowserAction::Hover {
1141                    selector: selector.into(),
1142                }
1143            }
1144            "scroll" => {
1145                let direction = args
1146                    .get("direction")
1147                    .and_then(|v| v.as_str())
1148                    .ok_or_else(|| anyhow::anyhow!("Missing 'direction' for scroll"))?;
1149                BrowserAction::Scroll {
1150                    direction: direction.into(),
1151                    pixels: args
1152                        .get("pixels")
1153                        .and_then(serde_json::Value::as_u64)
1154                        .map(|p| u32::try_from(p).unwrap_or(u32::MAX)),
1155                }
1156            }
1157            "is_visible" => {
1158                let selector = args
1159                    .get("selector")
1160                    .and_then(|v| v.as_str())
1161                    .ok_or_else(|| anyhow::anyhow!("Missing 'selector' for is_visible"))?;
1162                BrowserAction::IsVisible {
1163                    selector: selector.into(),
1164                }
1165            }
1166            "close" => BrowserAction::Close,
1167            "find" => {
1168                let by = args
1169                    .get("by")
1170                    .and_then(|v| v.as_str())
1171                    .ok_or_else(|| anyhow::anyhow!("Missing 'by' for find"))?;
1172                let value = args
1173                    .get("value")
1174                    .and_then(|v| v.as_str())
1175                    .ok_or_else(|| anyhow::anyhow!("Missing 'value' for find"))?;
1176                let action = args
1177                    .get("find_action")
1178                    .and_then(|v| v.as_str())
1179                    .ok_or_else(|| anyhow::anyhow!("Missing 'find_action' for find"))?;
1180                BrowserAction::Find {
1181                    by: by.into(),
1182                    value: value.into(),
1183                    action: action.into(),
1184                    fill_value: args
1185                        .get("fill_value")
1186                        .and_then(|v| v.as_str())
1187                        .map(String::from),
1188                }
1189            }
1190            _ => {
1191                return Ok(ToolResult {
1192                    success: false,
1193                    output: String::new(),
1194                    error: Some(format!(
1195                        "Action '{action_str}' is unavailable for backend '{}'",
1196                        match backend {
1197                            ResolvedBackend::AgentBrowser => "agent_browser",
1198                            ResolvedBackend::RustNative => "rust_native",
1199                            ResolvedBackend::ComputerUse => "computer_use",
1200                        }
1201                    )),
1202                });
1203            }
1204        };
1205
1206        self.execute_action(action, backend).await
1207    }
1208}
1209
1210#[cfg(feature = "browser-native")]
1211mod native_backend {
1212    use super::BrowserAction;
1213    use anyhow::{Context, Result};
1214    use base64::Engine;
1215    use fantoccini::actions::{InputSource, MouseActions, PointerAction};
1216    use fantoccini::key::Key;
1217    use fantoccini::{Client, ClientBuilder, Locator};
1218    use serde_json::{Map, Value, json};
1219    use std::net::{TcpStream, ToSocketAddrs};
1220    use std::time::Duration;
1221
1222    #[derive(Default)]
1223    pub struct NativeBrowserState {
1224        client: Option<Client>,
1225    }
1226
1227    impl NativeBrowserState {
1228        pub fn is_available(
1229            _headless: bool,
1230            webdriver_url: &str,
1231            _chrome_path: Option<&str>,
1232        ) -> bool {
1233            webdriver_endpoint_reachable(webdriver_url, Duration::from_millis(500))
1234        }
1235
1236        #[allow(clippy::too_many_lines)]
1237        pub async fn execute_action(
1238            &mut self,
1239            action: BrowserAction,
1240            headless: bool,
1241            webdriver_url: &str,
1242            chrome_path: Option<&str>,
1243        ) -> Result<Value> {
1244            match action {
1245                BrowserAction::Open { url } => {
1246                    self.ensure_session(headless, webdriver_url, chrome_path)
1247                        .await?;
1248                    let client = self.active_client()?;
1249                    client
1250                        .goto(&url)
1251                        .await
1252                        .with_context(|| format!("Failed to open URL: {url}"))?;
1253                    let current_url = client
1254                        .current_url()
1255                        .await
1256                        .context("Failed to read current URL after navigation")?;
1257
1258                    Ok(json!({
1259                        "backend": "rust_native",
1260                        "action": "open",
1261                        "url": current_url.as_str(),
1262                    }))
1263                }
1264                BrowserAction::Snapshot {
1265                    interactive_only,
1266                    compact,
1267                    depth,
1268                } => {
1269                    let client = self.active_client()?;
1270                    let snapshot = client
1271                        .execute(
1272                            &snapshot_script(interactive_only, compact, depth.map(i64::from)),
1273                            vec![],
1274                        )
1275                        .await
1276                        .context("Failed to evaluate snapshot script")?;
1277
1278                    Ok(json!({
1279                        "backend": "rust_native",
1280                        "action": "snapshot",
1281                        "data": snapshot,
1282                    }))
1283                }
1284                BrowserAction::Click { selector } => {
1285                    let client = self.active_client()?;
1286                    find_element(client, &selector).await?.click().await?;
1287
1288                    Ok(json!({
1289                        "backend": "rust_native",
1290                        "action": "click",
1291                        "selector": selector,
1292                    }))
1293                }
1294                BrowserAction::Fill { selector, value } => {
1295                    let client = self.active_client()?;
1296                    let element = find_element(client, &selector).await?;
1297                    let _ = element.clear().await;
1298                    element.send_keys(&value).await?;
1299
1300                    Ok(json!({
1301                        "backend": "rust_native",
1302                        "action": "fill",
1303                        "selector": selector,
1304                    }))
1305                }
1306                BrowserAction::Type { selector, text } => {
1307                    let client = self.active_client()?;
1308                    find_element(client, &selector)
1309                        .await?
1310                        .send_keys(&text)
1311                        .await?;
1312
1313                    Ok(json!({
1314                        "backend": "rust_native",
1315                        "action": "type",
1316                        "selector": selector,
1317                        "typed": text.len(),
1318                    }))
1319                }
1320                BrowserAction::GetText { selector } => {
1321                    let client = self.active_client()?;
1322                    let text = find_element(client, &selector).await?.text().await?;
1323
1324                    Ok(json!({
1325                        "backend": "rust_native",
1326                        "action": "get_text",
1327                        "selector": selector,
1328                        "text": text,
1329                    }))
1330                }
1331                BrowserAction::GetTitle => {
1332                    let client = self.active_client()?;
1333                    let title = client.title().await.context("Failed to read page title")?;
1334
1335                    Ok(json!({
1336                        "backend": "rust_native",
1337                        "action": "get_title",
1338                        "title": title,
1339                    }))
1340                }
1341                BrowserAction::GetUrl => {
1342                    let client = self.active_client()?;
1343                    let url = client
1344                        .current_url()
1345                        .await
1346                        .context("Failed to read current URL")?;
1347
1348                    Ok(json!({
1349                        "backend": "rust_native",
1350                        "action": "get_url",
1351                        "url": url.as_str(),
1352                    }))
1353                }
1354                BrowserAction::Screenshot { path, full_page } => {
1355                    let client = self.active_client()?;
1356                    let png = client
1357                        .screenshot()
1358                        .await
1359                        .context("Failed to capture screenshot")?;
1360                    let mut payload = json!({
1361                        "backend": "rust_native",
1362                        "action": "screenshot",
1363                        "full_page": full_page,
1364                        "bytes": png.len(),
1365                    });
1366
1367                    if let Some(path_str) = path {
1368                        std::fs::write(&path_str, &png)
1369                            .with_context(|| format!("Failed to write screenshot to {path_str}"))?;
1370                        payload["path"] = Value::String(path_str);
1371                    } else {
1372                        payload["png_base64"] =
1373                            Value::String(base64::engine::general_purpose::STANDARD.encode(&png));
1374                    }
1375
1376                    Ok(payload)
1377                }
1378                BrowserAction::Wait { selector, ms, text } => {
1379                    let client = self.active_client()?;
1380                    if let Some(sel) = selector.as_ref() {
1381                        wait_for_selector(client, sel).await?;
1382                        Ok(json!({
1383                            "backend": "rust_native",
1384                            "action": "wait",
1385                            "selector": sel,
1386                        }))
1387                    } else if let Some(duration_ms) = ms {
1388                        tokio::time::sleep(Duration::from_millis(duration_ms)).await;
1389                        Ok(json!({
1390                            "backend": "rust_native",
1391                            "action": "wait",
1392                            "ms": duration_ms,
1393                        }))
1394                    } else if let Some(needle) = text.as_ref() {
1395                        let xpath = xpath_contains_text(needle);
1396                        client
1397                            .wait()
1398                            .for_element(Locator::XPath(&xpath))
1399                            .await
1400                            .with_context(|| {
1401                                format!("Timed out waiting for text to appear: {needle}")
1402                            })?;
1403                        Ok(json!({
1404                            "backend": "rust_native",
1405                            "action": "wait",
1406                            "text": needle,
1407                        }))
1408                    } else {
1409                        tokio::time::sleep(Duration::from_millis(250)).await;
1410                        Ok(json!({
1411                            "backend": "rust_native",
1412                            "action": "wait",
1413                            "ms": 250,
1414                        }))
1415                    }
1416                }
1417                BrowserAction::Press { key } => {
1418                    let client = self.active_client()?;
1419                    let key_input = webdriver_key(&key);
1420                    match client.active_element().await {
1421                        Ok(element) => {
1422                            element.send_keys(&key_input).await?;
1423                        }
1424                        Err(_) => {
1425                            find_element(client, "body")
1426                                .await?
1427                                .send_keys(&key_input)
1428                                .await?;
1429                        }
1430                    }
1431
1432                    Ok(json!({
1433                        "backend": "rust_native",
1434                        "action": "press",
1435                        "key": key,
1436                    }))
1437                }
1438                BrowserAction::Hover { selector } => {
1439                    let client = self.active_client()?;
1440                    let element = find_element(client, &selector).await?;
1441                    hover_element(client, &element).await?;
1442
1443                    Ok(json!({
1444                        "backend": "rust_native",
1445                        "action": "hover",
1446                        "selector": selector,
1447                    }))
1448                }
1449                BrowserAction::Scroll { direction, pixels } => {
1450                    let client = self.active_client()?;
1451                    let amount = i64::from(pixels.unwrap_or(600));
1452                    let (dx, dy) = match direction.as_str() {
1453                        "up" => (0, -amount),
1454                        "down" => (0, amount),
1455                        "left" => (-amount, 0),
1456                        "right" => (amount, 0),
1457                        _ => anyhow::bail!(
1458                            "Unsupported scroll direction '{direction}'. Use up/down/left/right"
1459                        ),
1460                    };
1461
1462                    let position = client
1463                        .execute(
1464                            "window.scrollBy(arguments[0], arguments[1]); return { x: window.scrollX, y: window.scrollY };",
1465                            vec![json!(dx), json!(dy)],
1466                        )
1467                        .await
1468                        .context("Failed to execute scroll script")?;
1469
1470                    Ok(json!({
1471                        "backend": "rust_native",
1472                        "action": "scroll",
1473                        "position": position,
1474                    }))
1475                }
1476                BrowserAction::IsVisible { selector } => {
1477                    let client = self.active_client()?;
1478                    let visible = find_element(client, &selector)
1479                        .await?
1480                        .is_displayed()
1481                        .await?;
1482
1483                    Ok(json!({
1484                        "backend": "rust_native",
1485                        "action": "is_visible",
1486                        "selector": selector,
1487                        "visible": visible,
1488                    }))
1489                }
1490                BrowserAction::Close => {
1491                    if let Some(client) = self.client.take() {
1492                        let _ = client.close().await;
1493                    }
1494
1495                    Ok(json!({
1496                        "backend": "rust_native",
1497                        "action": "close",
1498                        "closed": true,
1499                    }))
1500                }
1501                BrowserAction::Find {
1502                    by,
1503                    value,
1504                    action,
1505                    fill_value,
1506                } => {
1507                    let client = self.active_client()?;
1508                    let selector = selector_for_find(&by, &value);
1509                    let element = find_element(client, &selector).await?;
1510
1511                    let payload = match action.as_str() {
1512                        "click" => {
1513                            element.click().await?;
1514                            json!({"result": "clicked"})
1515                        }
1516                        "fill" => {
1517                            let fill = fill_value.ok_or_else(|| {
1518                                anyhow::anyhow!("find_action='fill' requires fill_value")
1519                            })?;
1520                            let _ = element.clear().await;
1521                            element.send_keys(&fill).await?;
1522                            json!({"result": "filled", "typed": fill.len()})
1523                        }
1524                        "text" => {
1525                            let text = element.text().await?;
1526                            json!({"result": "text", "text": text})
1527                        }
1528                        "hover" => {
1529                            hover_element(client, &element).await?;
1530                            json!({"result": "hovered"})
1531                        }
1532                        "check" => {
1533                            let checked_before = element_checked(&element).await?;
1534                            if !checked_before {
1535                                element.click().await?;
1536                            }
1537                            let checked_after = element_checked(&element).await?;
1538                            json!({
1539                                "result": "checked",
1540                                "checked_before": checked_before,
1541                                "checked_after": checked_after,
1542                            })
1543                        }
1544                        _ => anyhow::bail!(
1545                            "Unsupported find_action '{action}'. Use click/fill/text/hover/check"
1546                        ),
1547                    };
1548
1549                    Ok(json!({
1550                        "backend": "rust_native",
1551                        "action": "find",
1552                        "by": by,
1553                        "value": value,
1554                        "selector": selector,
1555                        "data": payload,
1556                    }))
1557                }
1558            }
1559        }
1560
1561        async fn ensure_session(
1562            &mut self,
1563            headless: bool,
1564            webdriver_url: &str,
1565            chrome_path: Option<&str>,
1566        ) -> Result<()> {
1567            if self.client.is_some() {
1568                return Ok(());
1569            }
1570
1571            let mut capabilities: Map<String, Value> = Map::new();
1572            let mut chrome_options: Map<String, Value> = Map::new();
1573            let mut args: Vec<Value> = Vec::new();
1574
1575            if headless {
1576                args.push(Value::String("--headless=new".to_string()));
1577                args.push(Value::String("--disable-gpu".to_string()));
1578            }
1579
1580            if !args.is_empty() {
1581                chrome_options.insert("args".to_string(), Value::Array(args));
1582            }
1583
1584            if let Some(path) = chrome_path {
1585                let trimmed = path.trim();
1586                if !trimmed.is_empty() {
1587                    chrome_options.insert("binary".to_string(), Value::String(trimmed.to_string()));
1588                }
1589            }
1590
1591            if !chrome_options.is_empty() {
1592                capabilities.insert(
1593                    "goog:chromeOptions".to_string(),
1594                    Value::Object(chrome_options),
1595                );
1596            }
1597
1598            let mut builder =
1599                ClientBuilder::rustls().context("Failed to initialize rustls connector")?;
1600            if !capabilities.is_empty() {
1601                builder.capabilities(capabilities);
1602            }
1603
1604            let client = builder
1605                .connect(webdriver_url)
1606                .await
1607                .with_context(|| {
1608                    format!(
1609                        "Failed to connect to WebDriver at {webdriver_url}. Start chromedriver/geckodriver first"
1610                    )
1611                })?;
1612
1613            self.client = Some(client);
1614            Ok(())
1615        }
1616
1617        fn active_client(&self) -> Result<&Client> {
1618            self.client.as_ref().ok_or_else(|| {
1619                anyhow::anyhow!("No active native browser session. Run browser action='open' first")
1620            })
1621        }
1622    }
1623
1624    fn webdriver_endpoint_reachable(webdriver_url: &str, timeout: Duration) -> bool {
1625        let parsed = match reqwest::Url::parse(webdriver_url) {
1626            Ok(url) => url,
1627            Err(_) => return false,
1628        };
1629
1630        if parsed.scheme() != "http" && parsed.scheme() != "https" {
1631            return false;
1632        }
1633
1634        let host = match parsed.host_str() {
1635            Some(h) if !h.is_empty() => h,
1636            _ => return false,
1637        };
1638
1639        let port = parsed.port_or_known_default().unwrap_or(4444);
1640        let mut addrs = match (host, port).to_socket_addrs() {
1641            Ok(iter) => iter,
1642            Err(_) => return false,
1643        };
1644
1645        let addr = match addrs.next() {
1646            Some(a) => a,
1647            None => return false,
1648        };
1649
1650        TcpStream::connect_timeout(&addr, timeout).is_ok()
1651    }
1652
1653    fn selector_for_find(by: &str, value: &str) -> String {
1654        let escaped = css_attr_escape(value);
1655        match by {
1656            "role" => format!(r#"[role=\"{escaped}\"]"#),
1657            "label" => format!("label={value}"),
1658            "placeholder" => format!(r#"[placeholder=\"{escaped}\"]"#),
1659            "testid" => format!(r#"[data-testid=\"{escaped}\"]"#),
1660            _ => format!("text={value}"),
1661        }
1662    }
1663
1664    async fn wait_for_selector(client: &Client, selector: &str) -> Result<()> {
1665        match parse_selector(selector) {
1666            SelectorKind::Css(css) => {
1667                client
1668                    .wait()
1669                    .for_element(Locator::Css(&css))
1670                    .await
1671                    .with_context(|| format!("Timed out waiting for selector '{selector}'"))?;
1672            }
1673            SelectorKind::XPath(xpath) => {
1674                client
1675                    .wait()
1676                    .for_element(Locator::XPath(&xpath))
1677                    .await
1678                    .with_context(|| format!("Timed out waiting for selector '{selector}'"))?;
1679            }
1680        }
1681        Ok(())
1682    }
1683
1684    async fn find_element(
1685        client: &Client,
1686        selector: &str,
1687    ) -> Result<fantoccini::elements::Element> {
1688        let element = match parse_selector(selector) {
1689            SelectorKind::Css(css) => client
1690                .find(Locator::Css(&css))
1691                .await
1692                .with_context(|| format!("Failed to find element by CSS '{css}'"))?,
1693            SelectorKind::XPath(xpath) => client
1694                .find(Locator::XPath(&xpath))
1695                .await
1696                .with_context(|| format!("Failed to find element by XPath '{xpath}'"))?,
1697        };
1698        Ok(element)
1699    }
1700
1701    async fn hover_element(client: &Client, element: &fantoccini::elements::Element) -> Result<()> {
1702        let actions = MouseActions::new("mouse".to_string()).then(PointerAction::MoveToElement {
1703            element: element.clone(),
1704            duration: Some(Duration::from_millis(150)),
1705            x: 0.0,
1706            y: 0.0,
1707        });
1708
1709        client
1710            .perform_actions(actions)
1711            .await
1712            .context("Failed to perform hover action")?;
1713        let _ = client.release_actions().await;
1714        Ok(())
1715    }
1716
1717    async fn element_checked(element: &fantoccini::elements::Element) -> Result<bool> {
1718        let checked = element
1719            .prop("checked")
1720            .await
1721            .context("Failed to read checkbox checked property")?
1722            .unwrap_or_default()
1723            .to_ascii_lowercase();
1724        Ok(matches!(checked.as_str(), "true" | "checked" | "1"))
1725    }
1726
1727    enum SelectorKind {
1728        Css(String),
1729        XPath(String),
1730    }
1731
1732    fn parse_selector(selector: &str) -> SelectorKind {
1733        let trimmed = selector.trim();
1734        if let Some(text_query) = trimmed.strip_prefix("text=") {
1735            return SelectorKind::XPath(xpath_contains_text(text_query));
1736        }
1737
1738        if let Some(label_query) = trimmed.strip_prefix("label=") {
1739            let literal = xpath_literal(label_query);
1740            return SelectorKind::XPath(format!(
1741                "(//label[contains(normalize-space(.), {literal})]/following::*[self::input or self::textarea or self::select][1] | //*[@aria-label and contains(normalize-space(@aria-label), {literal})] | //label[contains(normalize-space(.), {literal})])"
1742            ));
1743        }
1744
1745        if trimmed.starts_with('@') {
1746            let escaped = css_attr_escape(trimmed);
1747            return SelectorKind::Css(format!(r#"[data-zc-ref=\"{escaped}\"]"#));
1748        }
1749
1750        SelectorKind::Css(trimmed.to_string())
1751    }
1752
1753    fn css_attr_escape(input: &str) -> String {
1754        input
1755            .replace('\\', "\\\\")
1756            .replace('"', "\\\"")
1757            .replace('\n', " ")
1758    }
1759
1760    fn xpath_contains_text(text: &str) -> String {
1761        format!("//*[contains(normalize-space(.), {})]", xpath_literal(text))
1762    }
1763
1764    fn xpath_literal(input: &str) -> String {
1765        if !input.contains('"') {
1766            return format!("\"{input}\"");
1767        }
1768        if !input.contains('\'') {
1769            return format!("'{input}'");
1770        }
1771
1772        let segments: Vec<&str> = input.split('"').collect();
1773        let mut parts: Vec<String> = Vec::new();
1774        for (index, part) in segments.iter().enumerate() {
1775            if !part.is_empty() {
1776                parts.push(format!("\"{part}\""));
1777            }
1778            if index + 1 < segments.len() {
1779                parts.push("'\"'".to_string());
1780            }
1781        }
1782
1783        if parts.is_empty() {
1784            "\"\"".to_string()
1785        } else {
1786            format!("concat({})", parts.join(","))
1787        }
1788    }
1789
1790    fn webdriver_key(key: &str) -> String {
1791        match key.trim().to_ascii_lowercase().as_str() {
1792            "enter" => Key::Enter.to_string(),
1793            "return" => Key::Return.to_string(),
1794            "tab" => Key::Tab.to_string(),
1795            "escape" | "esc" => Key::Escape.to_string(),
1796            "backspace" => Key::Backspace.to_string(),
1797            "delete" => Key::Delete.to_string(),
1798            "space" => Key::Space.to_string(),
1799            "arrowup" | "up" => Key::Up.to_string(),
1800            "arrowdown" | "down" => Key::Down.to_string(),
1801            "arrowleft" | "left" => Key::Left.to_string(),
1802            "arrowright" | "right" => Key::Right.to_string(),
1803            "home" => Key::Home.to_string(),
1804            "end" => Key::End.to_string(),
1805            "pageup" => Key::PageUp.to_string(),
1806            "pagedown" => Key::PageDown.to_string(),
1807            other => other.to_string(),
1808        }
1809    }
1810
1811    fn snapshot_script(interactive_only: bool, compact: bool, depth: Option<i64>) -> String {
1812        let depth_literal = depth
1813            .map(|level| level.to_string())
1814            .unwrap_or_else(|| "null".to_string());
1815
1816        format!(
1817            r#"(() => {{
1818  const interactiveOnly = {interactive_only};
1819  const compact = {compact};
1820  const maxDepth = {depth_literal};
1821  const nodes = [];
1822  const root = document.body || document.documentElement;
1823  let counter = 0;
1824
1825  const isVisible = (el) => {{
1826    const style = window.getComputedStyle(el);
1827    if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity || 1) === 0) {{
1828      return false;
1829    }}
1830    const rect = el.getBoundingClientRect();
1831    return rect.width > 0 && rect.height > 0;
1832  }};
1833
1834  const isInteractive = (el) => {{
1835    if (el.matches('a,button,input,select,textarea,summary,[role],*[tabindex]')) return true;
1836    return typeof el.onclick === 'function';
1837  }};
1838
1839  const describe = (el, depth) => {{
1840    const interactive = isInteractive(el);
1841    const text = (el.innerText || el.textContent || '').trim().replace(/\s+/g, ' ').slice(0, 140);
1842    if (interactiveOnly && !interactive) return;
1843    if (compact && !interactive && !text) return;
1844
1845    const ref = '@e' + (++counter);
1846    el.setAttribute('data-zc-ref', ref);
1847    nodes.push({{
1848      ref,
1849      depth,
1850      tag: el.tagName.toLowerCase(),
1851      id: el.id || null,
1852      role: el.getAttribute('role'),
1853      text,
1854      interactive,
1855    }});
1856  }};
1857
1858  const walk = (el, depth) => {{
1859    if (!(el instanceof Element)) return;
1860    if (maxDepth !== null && depth > maxDepth) return;
1861    if (isVisible(el)) {{
1862      describe(el, depth);
1863    }}
1864    for (const child of el.children) {{
1865      walk(child, depth + 1);
1866      if (nodes.length >= 400) return;
1867    }}
1868  }};
1869
1870  if (root) walk(root, 0);
1871
1872  return {{
1873    title: document.title,
1874    url: window.location.href,
1875    count: nodes.length,
1876    nodes,
1877  }};
1878}})();"#
1879        )
1880    }
1881}
1882
1883// ── Helper functions ─────────────────────────────────────────────
1884
1885fn is_supported_browser_action(action: &str) -> bool {
1886    matches!(
1887        action,
1888        "open"
1889            | "snapshot"
1890            | "click"
1891            | "fill"
1892            | "type"
1893            | "get_text"
1894            | "get_title"
1895            | "get_url"
1896            | "screenshot"
1897            | "wait"
1898            | "press"
1899            | "hover"
1900            | "scroll"
1901            | "is_visible"
1902            | "close"
1903            | "find"
1904            | "mouse_move"
1905            | "mouse_click"
1906            | "mouse_drag"
1907            | "key_type"
1908            | "key_press"
1909            | "screen_capture"
1910    )
1911}
1912
1913fn normalize_domains(domains: Vec<String>) -> Vec<String> {
1914    domains
1915        .into_iter()
1916        .map(|d| d.trim().to_lowercase())
1917        .filter(|d| !d.is_empty())
1918        .collect()
1919}
1920
1921fn endpoint_reachable(endpoint: &reqwest::Url, timeout: Duration) -> bool {
1922    let host = match endpoint.host_str() {
1923        Some(host) if !host.is_empty() => host,
1924        _ => return false,
1925    };
1926
1927    let port = match endpoint.port_or_known_default() {
1928        Some(port) => port,
1929        None => return false,
1930    };
1931
1932    let mut addrs = match (host, port).to_socket_addrs() {
1933        Ok(addrs) => addrs,
1934        Err(_) => return false,
1935    };
1936
1937    let addr = match addrs.next() {
1938        Some(addr) => addr,
1939        None => return false,
1940    };
1941
1942    std::net::TcpStream::connect_timeout(&addr, timeout).is_ok()
1943}
1944
1945fn extract_host(url_str: &str) -> anyhow::Result<String> {
1946    // Simple host extraction without url crate
1947    let url = url_str.trim();
1948    let without_scheme = url
1949        .strip_prefix("https://")
1950        .or_else(|| url.strip_prefix("http://"))
1951        .or_else(|| url.strip_prefix("file://"))
1952        .unwrap_or(url);
1953
1954    // Extract host — handle bracketed IPv6 addresses like [::1]:8080
1955    let authority = without_scheme.split('/').next().unwrap_or(without_scheme);
1956
1957    let host = if authority.starts_with('[') {
1958        // IPv6: take everything up to and including the closing ']'
1959        authority.find(']').map_or(authority, |i| &authority[..=i])
1960    } else {
1961        // IPv4 or hostname: take everything before the port separator
1962        authority.split(':').next().unwrap_or(authority)
1963    };
1964
1965    if host.is_empty() {
1966        anyhow::bail!("Invalid URL: no host");
1967    }
1968
1969    Ok(host.to_lowercase())
1970}
1971
1972fn is_private_host(host: &str) -> bool {
1973    // Strip brackets from IPv6 addresses like [::1]
1974    let bare = host
1975        .strip_prefix('[')
1976        .and_then(|h| h.strip_suffix(']'))
1977        .unwrap_or(host);
1978
1979    if bare == "localhost" || bare.ends_with(".localhost") {
1980        return true;
1981    }
1982
1983    // .local TLD (mDNS)
1984    if bare
1985        .rsplit('.')
1986        .next()
1987        .is_some_and(|label| label == "local")
1988    {
1989        return true;
1990    }
1991
1992    // Parse as IP address to catch all representations (decimal, hex, octal, mapped)
1993    if let Ok(ip) = bare.parse::<std::net::IpAddr>() {
1994        return match ip {
1995            std::net::IpAddr::V4(v4) => is_non_global_v4(v4),
1996            std::net::IpAddr::V6(v6) => is_non_global_v6(v6),
1997        };
1998    }
1999
2000    false
2001}
2002
2003/// Returns `true` for any IPv4 address that is not globally routable.
2004fn is_non_global_v4(v4: std::net::Ipv4Addr) -> bool {
2005    let [a, b, _, _] = v4.octets();
2006    v4.is_loopback()
2007        || v4.is_private()
2008        || v4.is_link_local()
2009        || v4.is_unspecified()
2010        || v4.is_broadcast()
2011        || v4.is_multicast()
2012        // Shared address space (100.64/10)
2013        || (a == 100 && (64..=127).contains(&b))
2014        // Reserved (240.0.0.0/4)
2015        || a >= 240
2016        // Documentation (192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24)
2017        || (a == 192 && b == 0)
2018        || (a == 198 && b == 51)
2019        || (a == 203 && b == 0)
2020        // Benchmarking (198.18.0.0/15)
2021        || (a == 198 && (18..=19).contains(&b))
2022}
2023
2024/// Returns `true` for any IPv6 address that is not globally routable.
2025fn is_non_global_v6(v6: std::net::Ipv6Addr) -> bool {
2026    let segs = v6.segments();
2027    v6.is_loopback()
2028        || v6.is_unspecified()
2029        || v6.is_multicast()
2030        // Unique-local (fc00::/7) — IPv6 equivalent of RFC 1918
2031        || (segs[0] & 0xfe00) == 0xfc00
2032        // Link-local (fe80::/10)
2033        || (segs[0] & 0xffc0) == 0xfe80
2034        // IPv4-mapped addresses
2035        || v6.to_ipv4_mapped().is_some_and(is_non_global_v4)
2036}
2037
2038fn host_matches_allowlist(host: &str, allowed: &[String]) -> bool {
2039    allowed.iter().any(|pattern| {
2040        if pattern == "*" {
2041            return true;
2042        }
2043        if pattern.starts_with("*.") {
2044            // Wildcard subdomain match
2045            let suffix = &pattern[1..]; // ".example.com"
2046            host.ends_with(suffix) || host == &pattern[2..]
2047        } else {
2048            // Exact match or subdomain
2049            host == pattern || host.ends_with(&format!(".{pattern}"))
2050        }
2051    })
2052}
2053
2054#[cfg(test)]
2055mod tests {
2056    use super::*;
2057
2058    #[test]
2059    fn normalize_domains_works() {
2060        let domains = vec![
2061            "  Example.COM  ".into(),
2062            "docs.example.com".into(),
2063            String::new(),
2064        ];
2065        let normalized = normalize_domains(domains);
2066        assert_eq!(normalized, vec!["example.com", "docs.example.com"]);
2067    }
2068
2069    #[test]
2070    fn extract_host_works() {
2071        assert_eq!(
2072            extract_host("https://example.com/path").unwrap(),
2073            "example.com"
2074        );
2075        assert_eq!(
2076            extract_host("https://Sub.Example.COM:8080/").unwrap(),
2077            "sub.example.com"
2078        );
2079    }
2080
2081    #[test]
2082    fn extract_host_handles_ipv6() {
2083        // IPv6 with brackets (required for URLs with ports)
2084        assert_eq!(extract_host("https://[::1]/path").unwrap(), "[::1]");
2085        // IPv6 with brackets and port
2086        assert_eq!(
2087            extract_host("https://[2001:db8::1]:8080/path").unwrap(),
2088            "[2001:db8::1]"
2089        );
2090        // IPv6 with brackets, trailing slash
2091        assert_eq!(extract_host("https://[fe80::1]/").unwrap(), "[fe80::1]");
2092    }
2093
2094    #[test]
2095    fn is_private_host_detects_local() {
2096        assert!(is_private_host("localhost"));
2097        assert!(is_private_host("app.localhost"));
2098        assert!(is_private_host("printer.local"));
2099        assert!(is_private_host("127.0.0.1"));
2100        assert!(is_private_host("192.168.1.1"));
2101        assert!(is_private_host("10.0.0.1"));
2102        assert!(!is_private_host("example.com"));
2103        assert!(!is_private_host("google.com"));
2104    }
2105
2106    #[test]
2107    fn is_private_host_blocks_multicast_and_reserved() {
2108        assert!(is_private_host("224.0.0.1")); // multicast
2109        assert!(is_private_host("255.255.255.255")); // broadcast
2110        assert!(is_private_host("100.64.0.1")); // shared address space
2111        assert!(is_private_host("240.0.0.1")); // reserved
2112        assert!(is_private_host("192.0.2.1")); // documentation
2113        assert!(is_private_host("198.51.100.1")); // documentation
2114        assert!(is_private_host("203.0.113.1")); // documentation
2115        assert!(is_private_host("198.18.0.1")); // benchmarking
2116    }
2117
2118    #[test]
2119    fn is_private_host_catches_ipv6() {
2120        assert!(is_private_host("::1"));
2121        assert!(is_private_host("[::1]"));
2122        assert!(is_private_host("0.0.0.0"));
2123    }
2124
2125    #[test]
2126    fn is_private_host_catches_mapped_ipv4() {
2127        // IPv4-mapped IPv6 addresses
2128        assert!(is_private_host("::ffff:127.0.0.1"));
2129        assert!(is_private_host("::ffff:10.0.0.1"));
2130        assert!(is_private_host("::ffff:192.168.1.1"));
2131    }
2132
2133    #[test]
2134    fn is_private_host_catches_ipv6_private_ranges() {
2135        // Unique-local (fc00::/7)
2136        assert!(is_private_host("fd00::1"));
2137        assert!(is_private_host("fc00::1"));
2138        // Link-local (fe80::/10)
2139        assert!(is_private_host("fe80::1"));
2140        // Public IPv6 should pass
2141        assert!(!is_private_host("2001:db8::1"));
2142    }
2143
2144    #[test]
2145    fn validate_url_blocks_ipv6_ssrf() {
2146        let security = Arc::new(SecurityPolicy::default());
2147        let tool = BrowserTool::new(security, vec!["*".into()], None);
2148        assert!(tool.validate_url("https://[::1]/").is_err());
2149        assert!(tool.validate_url("https://[::ffff:127.0.0.1]/").is_err());
2150        assert!(
2151            tool.validate_url("https://[::ffff:10.0.0.1]:8080/")
2152                .is_err()
2153        );
2154    }
2155
2156    #[test]
2157    fn host_matches_allowlist_exact() {
2158        let allowed = vec!["example.com".into()];
2159        assert!(host_matches_allowlist("example.com", &allowed));
2160        assert!(host_matches_allowlist("sub.example.com", &allowed));
2161        assert!(!host_matches_allowlist("notexample.com", &allowed));
2162    }
2163
2164    #[test]
2165    fn host_matches_allowlist_wildcard() {
2166        let allowed = vec!["*.example.com".into()];
2167        assert!(host_matches_allowlist("sub.example.com", &allowed));
2168        assert!(host_matches_allowlist("example.com", &allowed));
2169        assert!(!host_matches_allowlist("other.com", &allowed));
2170    }
2171
2172    #[test]
2173    fn host_matches_allowlist_star() {
2174        let allowed = vec!["*".into()];
2175        assert!(host_matches_allowlist("anything.com", &allowed));
2176        assert!(host_matches_allowlist("example.org", &allowed));
2177    }
2178
2179    #[test]
2180    fn browser_backend_parser_accepts_supported_values() {
2181        assert_eq!(
2182            BrowserBackendKind::parse("agent_browser").unwrap(),
2183            BrowserBackendKind::AgentBrowser
2184        );
2185        assert_eq!(
2186            BrowserBackendKind::parse("rust-native").unwrap(),
2187            BrowserBackendKind::RustNative
2188        );
2189        assert_eq!(
2190            BrowserBackendKind::parse("computer_use").unwrap(),
2191            BrowserBackendKind::ComputerUse
2192        );
2193        assert_eq!(
2194            BrowserBackendKind::parse("auto").unwrap(),
2195            BrowserBackendKind::Auto
2196        );
2197    }
2198
2199    #[test]
2200    fn browser_backend_parser_rejects_unknown_values() {
2201        assert!(BrowserBackendKind::parse("playwright").is_err());
2202    }
2203
2204    #[test]
2205    fn browser_tool_default_backend_is_agent_browser() {
2206        let security = Arc::new(SecurityPolicy::default());
2207        let tool = BrowserTool::new(security, vec!["example.com".into()], None);
2208        assert_eq!(
2209            tool.configured_backend().unwrap(),
2210            BrowserBackendKind::AgentBrowser
2211        );
2212    }
2213
2214    #[test]
2215    fn browser_tool_accepts_auto_backend_config() {
2216        let security = Arc::new(SecurityPolicy::default());
2217        let tool = BrowserTool::new_with_backend(
2218            security,
2219            vec!["example.com".into()],
2220            None,
2221            "auto".into(),
2222            true,
2223            "http://127.0.0.1:9515".into(),
2224            None,
2225            ComputerUseConfig::default(),
2226        );
2227        assert_eq!(tool.configured_backend().unwrap(), BrowserBackendKind::Auto);
2228    }
2229
2230    #[test]
2231    fn browser_tool_accepts_computer_use_backend_config() {
2232        let security = Arc::new(SecurityPolicy::default());
2233        let tool = BrowserTool::new_with_backend(
2234            security,
2235            vec!["example.com".into()],
2236            None,
2237            "computer_use".into(),
2238            true,
2239            "http://127.0.0.1:9515".into(),
2240            None,
2241            ComputerUseConfig::default(),
2242        );
2243        assert_eq!(
2244            tool.configured_backend().unwrap(),
2245            BrowserBackendKind::ComputerUse
2246        );
2247    }
2248
2249    #[test]
2250    fn computer_use_endpoint_rejects_public_http_by_default() {
2251        let security = Arc::new(SecurityPolicy::default());
2252        let tool = BrowserTool::new_with_backend(
2253            security,
2254            vec!["example.com".into()],
2255            None,
2256            "computer_use".into(),
2257            true,
2258            "http://127.0.0.1:9515".into(),
2259            None,
2260            ComputerUseConfig {
2261                endpoint: "http://computer-use.example.com/v1/actions".into(),
2262                ..ComputerUseConfig::default()
2263            },
2264        );
2265
2266        assert!(tool.computer_use_endpoint_url().is_err());
2267    }
2268
2269    #[test]
2270    fn computer_use_endpoint_requires_https_for_public_remote() {
2271        let security = Arc::new(SecurityPolicy::default());
2272        let tool = BrowserTool::new_with_backend(
2273            security,
2274            vec!["example.com".into()],
2275            None,
2276            "computer_use".into(),
2277            true,
2278            "http://127.0.0.1:9515".into(),
2279            None,
2280            ComputerUseConfig {
2281                endpoint: "https://computer-use.example.com/v1/actions".into(),
2282                allow_remote_endpoint: true,
2283                ..ComputerUseConfig::default()
2284            },
2285        );
2286
2287        assert!(tool.computer_use_endpoint_url().is_ok());
2288    }
2289
2290    #[test]
2291    fn computer_use_coordinate_validation_applies_limits() {
2292        let security = Arc::new(SecurityPolicy::default());
2293        let tool = BrowserTool::new_with_backend(
2294            security,
2295            vec!["example.com".into()],
2296            None,
2297            "computer_use".into(),
2298            true,
2299            "http://127.0.0.1:9515".into(),
2300            None,
2301            ComputerUseConfig {
2302                max_coordinate_x: Some(100),
2303                max_coordinate_y: Some(100),
2304                ..ComputerUseConfig::default()
2305            },
2306        );
2307
2308        assert!(
2309            tool.validate_coordinate("x", 50, tool.computer_use.max_coordinate_x)
2310                .is_ok()
2311        );
2312        assert!(
2313            tool.validate_coordinate("x", 101, tool.computer_use.max_coordinate_x)
2314                .is_err()
2315        );
2316        assert!(
2317            tool.validate_coordinate("y", -1, tool.computer_use.max_coordinate_y)
2318                .is_err()
2319        );
2320    }
2321
2322    #[test]
2323    fn browser_tool_name() {
2324        let security = Arc::new(SecurityPolicy::default());
2325        let tool = BrowserTool::new(security, vec!["example.com".into()], None);
2326        assert_eq!(tool.name(), "browser");
2327    }
2328
2329    #[test]
2330    fn browser_tool_validates_url() {
2331        let security = Arc::new(SecurityPolicy::default());
2332        let tool = BrowserTool::new(security, vec!["example.com".into()], None);
2333
2334        // Valid
2335        assert!(tool.validate_url("https://example.com").is_ok());
2336        assert!(tool.validate_url("https://sub.example.com/path").is_ok());
2337
2338        // Invalid - not in allowlist
2339        assert!(tool.validate_url("https://other.com").is_err());
2340
2341        // Invalid - private host
2342        assert!(tool.validate_url("https://localhost").is_err());
2343        assert!(tool.validate_url("https://127.0.0.1").is_err());
2344
2345        // Invalid - not https
2346        assert!(tool.validate_url("ftp://example.com").is_err());
2347
2348        // file:// URLs blocked (local file exfiltration risk)
2349        assert!(tool.validate_url("file:///tmp/test.html").is_err());
2350    }
2351
2352    #[test]
2353    fn browser_tool_empty_allowlist_blocks() {
2354        let security = Arc::new(SecurityPolicy::default());
2355        let tool = BrowserTool::new(security, vec![], None);
2356        assert!(tool.validate_url("https://example.com").is_err());
2357    }
2358}