Skip to main content

oxi_agent/tools/browse/
browse_tool.rs

1//! Browse tool — render a web page and return its content.
2//!
3//! Opens exactly **one** tab per request and extracts all content from it.
4//! Never calls engine-level methods that would open additional tabs.
5
6use super::config::BrowseConfig;
7use super::engine::BrowserEngine;
8use super::helpers;
9use super::tab_guard::TabGuard;
10use crate::tools::{AgentTool, AgentToolResult, ToolContext, ToolError};
11use async_trait::async_trait;
12use serde_json::{json, Value};
13use std::sync::Arc;
14use tokio::sync::oneshot;
15
16/// Render a web page using the built-in headless browser.
17///
18/// Returns page content as markdown, html, text, or a list of links.
19pub struct BrowseTool {
20    engine: Arc<dyn BrowserEngine>,
21    config: BrowseConfig,
22}
23
24impl BrowseTool {
25    /// Create with the given engine and default config.
26    pub fn new(engine: Arc<dyn BrowserEngine>) -> Self {
27        Self {
28            engine,
29            config: BrowseConfig::default(),
30        }
31    }
32
33    /// Create with custom configuration.
34    pub fn with_config(engine: Arc<dyn BrowserEngine>, config: BrowseConfig) -> Self {
35        Self { engine, config }
36    }
37}
38
39#[async_trait]
40impl AgentTool for BrowseTool {
41    fn name(&self) -> &str {
42        "browse"
43    }
44
45    fn label(&self) -> &str {
46        "Browse"
47    }
48
49    fn description(&self) -> &str {
50        "Browse a web page with a built-in headless browser. Renders JavaScript-powered \
51         pages and returns content as markdown (default), html, or links. Use when \
52         web_search results are insufficient and you need to read the actual page content. \
53         Supports waiting for dynamic content via CSS selectors."
54    }
55
56    fn parameters_schema(&self) -> Value {
57        json!({
58            "type": "object",
59            "properties": {
60                "url": {
61                    "type": "string",
62                    "description": "URL to browse"
63                },
64                "format": {
65                    "type": "string",
66                    "enum": ["markdown", "html", "text", "links"],
67                    "default": "markdown",
68                    "description": "Output format: markdown (default), html, plain text, or list of links"
69                },
70                "selector": {
71                    "type": "string",
72                    "description": "CSS selector to extract only matching elements"
73                },
74                "wait_for": {
75                    "type": "string",
76                    "description": "CSS selector to wait for before extracting (for JS-rendered content)"
77                },
78                "screenshot": {
79                    "type": "boolean",
80                    "default": false,
81                    "description": "Include a PNG screenshot as an image block"
82                }
83            },
84            "required": ["url"]
85        })
86    }
87
88    fn on_progress(&self, callback: crate::tools::ProgressCallback) {
89        // The agent loop calls this *before* `execute`. The engine's
90        // background task (spawned by `OxiBrowserEngine::with_config`) will
91        // invoke `callback` with each browser event's `short_label()` for
92        // the duration of this tool call. The next tool call's `on_progress`
93        // will replace this one — there is no fan-out.
94        self.engine.progress_forwarder().set(callback);
95    }
96
97    async fn execute(
98        &self,
99        _tool_call_id: &str,
100        params: Value,
101        _signal: Option<oneshot::Receiver<()>>,
102        _ctx: &ToolContext,
103    ) -> Result<AgentToolResult, ToolError> {
104        let url = params["url"]
105            .as_str()
106            .ok_or_else(|| "Missing required parameter: url".to_string())?;
107
108        let format = params["format"].as_str().unwrap_or("markdown");
109        let selector = params["selector"].as_str();
110        let wait_for = params["wait_for"].as_str();
111        let want_screenshot = params["screenshot"].as_bool().unwrap_or(false);
112
113        tracing::info!(url = %url, format = %format, "browsing page");
114
115        // Open exactly one tab for this request
116        let raw_tab = self
117            .engine
118            .new_tab()
119            .await
120            .map_err(|e| format!("Failed to open browser tab: {}", e))?;
121        let guard = TabGuard::new(raw_tab);
122        let tab = guard.tab();
123
124        // Navigate
125        let page = tab
126            .goto(url)
127            .await
128            .map_err(|e| format!("Navigation failed: {}", e))?;
129
130        // Wait for dynamic content if requested
131        if let Some(sel) = wait_for {
132            tab.wait_for(sel, self.config.default_wait_timeout_ms)
133                .await
134                .map_err(|e| format!("wait_for '{}' failed: {}", sel, e))?;
135        }
136
137        // Build output — all from the same tab
138        let output = match format {
139            "html" => {
140                if let Some(sel) = selector {
141                    tab.query_all(sel)
142                        .await
143                        .map_err(|e| e.to_string())?
144                        .join("\n\n")
145                } else {
146                    page.html.clone()
147                }
148            }
149            "links" => {
150                let links = helpers::extract_links(tab).await?;
151                helpers::format_links(&links)
152            }
153            "text" => {
154                if let Some(sel) = selector {
155                    tab.query_all(sel)
156                        .await
157                        .map_err(|e| e.to_string())?
158                        .join("\n")
159                } else {
160                    page.markdown.clone()
161                }
162            }
163            _ => {
164                // "markdown" (default)
165                if let Some(sel) = selector {
166                    tab.query_all(sel)
167                        .await
168                        .map_err(|e| e.to_string())?
169                        .join("\n\n")
170                } else {
171                    page.markdown.clone()
172                }
173            }
174        };
175
176        let title = page.title.clone();
177        let final_url = page.url.clone();
178        let status = page.status;
179
180        // Screenshot from the same tab (no re-render)
181        let screenshot_blocks = if want_screenshot {
182            match tab.screenshot(self.config.screenshot_width).await {
183                Ok(png) => {
184                    let b64 =
185                        base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &png);
186                    let img =
187                        oxi_ai::ContentBlock::Image(oxi_ai::ImageContent::new(b64, "image/png"));
188                    Some(vec![img])
189                }
190                Err(e) => {
191                    tracing::warn!("screenshot failed for {}: {}", final_url, e);
192                    None
193                }
194            }
195        } else {
196            None
197        };
198
199        // Explicitly close the tab
200        guard.close().await;
201
202        let mut result = AgentToolResult::success(output).with_metadata(json!({
203            "url": final_url,
204            "title": title,
205            "status": status,
206        }));
207
208        if let Some(blocks) = screenshot_blocks {
209            result = result.with_content_blocks(blocks);
210        }
211
212        Ok(result)
213    }
214}