mod cdp;
use anyhow::Context;
use serde_json::{json, Value};
use std::process::Command;
use std::sync::atomic::{AtomicBool, Ordering};
const DEFAULT_PORT: u16 = 9222;
pub struct BrowserModule {
sessions: tokio::sync::Mutex<std::collections::HashMap<u16, cdp::BrowserSession>>,
needs_reconnect: AtomicBool,
}
impl BrowserModule {
pub fn new() -> Self {
Self {
sessions: tokio::sync::Mutex::new(std::collections::HashMap::new()),
needs_reconnect: AtomicBool::new(false),
}
}
fn mark_needs_reconnect(&self) {
self.needs_reconnect.store(true, Ordering::Relaxed);
}
async fn get_session(&self, port: u16) -> anyhow::Result<tokio::sync::MutexGuard<'_, std::collections::HashMap<u16, cdp::BrowserSession>>> {
let mut guard = self.sessions.lock().await;
if guard.contains_key(&port) && self.needs_reconnect.swap(false, Ordering::Relaxed) {
let healthy = if let Some(session) = guard.get_mut(&port) {
tokio::time::timeout(
tokio::time::Duration::from_secs(1),
session.evaluate("1"),
)
.await
.map(|r| r.is_ok())
.unwrap_or(false)
} else {
false
};
if !healthy {
guard.remove(&port);
}
}
if !guard.contains_key(&port) {
let session = cdp::BrowserSession::connect(port).await?;
guard.insert(port, session);
}
Ok(guard)
}
pub fn get_tools(&self) -> Vec<Value> {
vec![
json!({
"name": "browser_launch",
"description": "Launch a browser (Firefox or Chrome) with remote debugging enabled. Returns the CDP port for use with other browser tools. The browser stays running until browser_close is called. Note: snap-packaged Firefox cannot bind debugging ports — use a native install or Chrome instead.",
"inputSchema": {
"type": "object",
"properties": {
"headless": { "type": "boolean", "description": "Run without visible window (default true)" },
"url": { "type": "string", "description": "Initial URL to open" },
"port": { "type": "number", "description": "CDP debugging port (default 9222)" },
"browser": { "type": "string", "description": "Browser to use: 'firefox' or 'chrome' (auto-detected if omitted)", "enum": ["firefox", "chrome"] }
},
"required": []
}
}),
json!({
"name": "browser_navigate",
"description": "Navigate to a URL in the browser. Waits for page load to complete.",
"inputSchema": {
"type": "object",
"properties": {
"url": { "type": "string", "description": "URL to navigate to" },
"port": { "type": "number", "description": "CDP port (default 9222)" }
},
"required": ["url"]
}
}),
json!({
"name": "browser_screenshot",
"description": "Take a screenshot of the current page. Returns an image. Much more reliable than screen_capture for web content since it captures the DOM directly.",
"inputSchema": {
"type": "object",
"properties": {
"full_page": { "type": "boolean", "description": "Capture full scrollable page, not just viewport (default false)" },
"port": { "type": "number", "description": "CDP port (default 9222)" }
},
"required": []
}
}),
json!({
"name": "browser_content",
"description": "Get the page content — title, URL, HTML, or extracted text.",
"inputSchema": {
"type": "object",
"properties": {
"format": {
"type": "string",
"description": "'text' (visible text), 'html' (full HTML), 'title' (page title), 'url' (current URL)",
"enum": ["text", "html", "title", "url"]
},
"port": { "type": "number", "description": "CDP port (default 9222)" }
},
"required": []
}
}),
json!({
"name": "browser_query",
"description": "Query DOM elements by CSS selector. Returns matching elements with text, attributes, and bounding boxes. Use this to find buttons, links, inputs — then click or fill them.",
"inputSchema": {
"type": "object",
"properties": {
"selector": { "type": "string", "description": "CSS selector (e.g. 'button', '.submit-btn', '#email', 'a[href*=login]')" },
"port": { "type": "number", "description": "CDP port (default 9222)" }
},
"required": ["selector"]
}
}),
json!({
"name": "browser_click",
"description": "Click a DOM element by CSS selector. More reliable than coordinate clicking — targets the element directly in the DOM.",
"inputSchema": {
"type": "object",
"properties": {
"selector": { "type": "string", "description": "CSS selector of element to click" },
"port": { "type": "number", "description": "CDP port (default 9222)" }
},
"required": ["selector"]
}
}),
json!({
"name": "browser_fill",
"description": "Fill a form input/textarea by CSS selector. Triggers input and change events.",
"inputSchema": {
"type": "object",
"properties": {
"selector": { "type": "string", "description": "CSS selector of the input field" },
"value": { "type": "string", "description": "Value to fill" },
"port": { "type": "number", "description": "CDP port (default 9222)" }
},
"required": ["selector", "value"]
}
}),
json!({
"name": "browser_eval",
"description": "Execute JavaScript in the page context. Returns the result. Can access DOM, make fetch calls, interact with page APIs.",
"inputSchema": {
"type": "object",
"properties": {
"expression": { "type": "string", "description": "JavaScript code to execute" },
"port": { "type": "number", "description": "CDP port (default 9222)" }
},
"required": ["expression"]
}
}),
json!({
"name": "browser_tabs",
"description": "List all open browser tabs with their titles, URLs, and IDs.",
"inputSchema": {
"type": "object",
"properties": {
"port": { "type": "number", "description": "CDP port (default 9222)" }
},
"required": []
}
}),
json!({
"name": "browser_close",
"description": "Close a browser tab or the entire browser.",
"inputSchema": {
"type": "object",
"properties": {
"tab_id": { "type": "string", "description": "Tab ID to close. If omitted, closes all tabs and kills the browser." },
"port": { "type": "number", "description": "CDP port (default 9222)" }
},
"required": []
}
}),
json!({
"name": "browser_wait",
"description": "Wait for a condition in the browser: element by CSS selector, text on page, URL match, or custom JS expression. Polls every 100ms. Essential for SPAs — call this after navigate to ensure content is rendered before interacting.",
"inputSchema": {
"type": "object",
"properties": {
"selector": { "type": "string", "description": "CSS selector to wait for (e.g. '.loaded', '#content', 'button[data-action]')" },
"text": { "type": "string", "description": "Text to wait for on the page (substring match)" },
"url": { "type": "string", "description": "URL substring to wait for (e.g. '/dashboard')" },
"expression": { "type": "string", "description": "JS expression that should return truthy when condition is met" },
"visible": { "type": "boolean", "description": "For selector: also require element has non-zero size (default true)" },
"timeout_ms": { "type": "number", "description": "Timeout in ms (default 30000)" },
"port": { "type": "number", "description": "CDP port (default 9222)" }
},
"required": []
}
}),
json!({
"name": "browser_scroll",
"description": "Scroll the page in a direction, by pixels, or scroll a specific element into view.",
"inputSchema": {
"type": "object",
"properties": {
"direction": { "type": "string", "description": "Scroll direction: 'up', 'down', 'left', 'right' (default 'down')", "enum": ["up", "down", "left", "right"] },
"pixels": { "type": "number", "description": "Pixels to scroll (default 300)" },
"selector": { "type": "string", "description": "CSS selector of element to scroll into view (overrides direction/pixels)" },
"port": { "type": "number", "description": "CDP port (default 9222)" }
},
"required": []
}
}),
json!({
"name": "browser_hover",
"description": "Hover over a DOM element to trigger CSS :hover styles and tooltip display.",
"inputSchema": {
"type": "object",
"properties": {
"selector": { "type": "string", "description": "CSS selector of element to hover" },
"port": { "type": "number", "description": "CDP port (default 9222)" }
},
"required": ["selector"]
}
}),
json!({
"name": "browser_select",
"description": "Select an option from a <select> dropdown by value or visible text.",
"inputSchema": {
"type": "object",
"properties": {
"selector": { "type": "string", "description": "CSS selector of the <select> element" },
"value": { "type": "string", "description": "Option value to select" },
"text": { "type": "string", "description": "Option visible text to select (used if value not provided)" },
"port": { "type": "number", "description": "CDP port (default 9222)" }
},
"required": ["selector"]
}
}),
]
}
pub async fn launch(&self, args: Value) -> anyhow::Result<Value> {
let headless = args["headless"].as_bool().unwrap_or(true);
let url = args["url"].as_str().unwrap_or("about:blank");
let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
let browser_pref = args["browser"].as_str();
let (browser_name, bin_path) = find_browser(browser_pref)?;
let mut cmd_args: Vec<String> = Vec::new();
match browser_name {
"firefox" => {
cmd_args.push(format!("--remote-debugging-port={}", port));
if headless {
cmd_args.push("--headless".to_string());
}
cmd_args.push(url.to_string());
}
"chrome" => {
cmd_args.push(format!("--remote-debugging-port={}", port));
if headless {
cmd_args.push("--headless=new".to_string());
}
cmd_args.push("--no-first-run".to_string());
cmd_args.push("--no-default-browser-check".to_string());
cmd_args.push("--disable-gpu".to_string());
cmd_args.push(url.to_string());
}
_ => unreachable!(),
}
let child = Command::new(&bin_path)
.args(&cmd_args)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.context(format!("Failed to launch {}", browser_name))?;
let pid = child.id();
let start = std::time::Instant::now();
let timeout = tokio::time::Duration::from_secs(15);
loop {
if start.elapsed() > timeout {
return Err(anyhow::anyhow!(
"Browser launched but CDP port {} not responding after 15s",
port
));
}
if let Ok(_) = cdp::BrowserSession::connect(port).await {
self.sessions.lock().await.remove(&port);
cdp::clear_browser_cache(port);
return Ok(json!({
"success": true,
"browser": browser_name,
"pid": pid,
"port": port,
"headless": headless,
"startup_ms": start.elapsed().as_millis()
}));
}
tokio::time::sleep(tokio::time::Duration::from_millis(300)).await;
}
}
fn is_transient_error(e: &anyhow::Error) -> bool {
let msg = e.to_string();
msg.contains("WebSocket") || msg.contains("timeout") || msg.contains("closed")
}
async fn handle_transient(&self, port: u16, attempt: usize) {
let delays = [200u64, 400, 800];
self.sessions.lock().await.remove(&port);
self.needs_reconnect.store(false, Ordering::Relaxed);
let delay = delays.get(attempt).copied().unwrap_or(800);
tokio::time::sleep(tokio::time::Duration::from_millis(delay)).await;
}
pub async fn navigate(&self, args: Value) -> anyhow::Result<Value> {
let url = args["url"].as_str().context("Missing 'url'")?;
let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
let result = async {
let mut guard = self.get_session(port).await?;
let session = guard.get_mut(&port).context("No browser session")?;
session.navigate(url).await?;
let title = session.get_title().await.unwrap_or_default();
Ok(json!({ "success": true, "url": url, "title": title }))
}.await;
if result.is_err() { self.mark_needs_reconnect(); }
result
}
pub async fn screenshot(&self, args: Value) -> anyhow::Result<Value> {
let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
let result: anyhow::Result<Value> = async {
let mut guard = self.get_session(port).await?;
let session = guard.get_mut(&port).context("No browser session")?;
let b64_data = session.screenshot().await?;
let byte_size = b64_data.len() * 3 / 4;
Ok(json!({
"content": [
{ "type": "image", "data": b64_data, "mimeType": "image/png" },
{ "type": "text", "text": serde_json::to_string_pretty(&json!({"bytes": byte_size}))? }
]
}))
}.await;
if result.is_err() { self.mark_needs_reconnect(); }
result
}
pub async fn content(&self, args: Value) -> anyhow::Result<Value> {
let format = args["format"].as_str().unwrap_or("text");
let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
let result: anyhow::Result<Value> = async {
let mut guard = self.get_session(port).await?;
let session = guard.get_mut(&port).context("No browser session")?;
match format {
"html" => {
let html = session.get_content().await?;
Ok(json!({ "format": "html", "length": html.len(), "content": html }))
}
"title" => {
let title = session.get_title().await?;
Ok(json!({ "format": "title", "title": title }))
}
"url" => {
let url = session.evaluate("window.location.href").await?;
Ok(json!({ "format": "url", "url": url }))
}
_ => {
let text = session.evaluate("document.body?.innerText || ''").await?;
let text_str = text.as_str().unwrap_or("");
Ok(json!({ "format": "text", "length": text_str.len(), "content": text_str }))
}
}
}.await;
if result.is_err() { self.mark_needs_reconnect(); }
result
}
pub async fn query(&self, args: Value) -> anyhow::Result<Value> {
let selector = args["selector"].as_str().context("Missing 'selector'")?;
let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
for attempt in 0..3 {
let result: anyhow::Result<Value> = async {
let mut guard = self.get_session(port).await?;
let session = guard.get_mut(&port).context("No browser session")?;
let elements = session.query_selector_all(selector).await?;
let count = elements.as_array().map(|a| a.len()).unwrap_or(0);
Ok(json!({ "selector": selector, "count": count, "elements": elements }))
}.await;
match result {
Ok(v) => return Ok(v),
Err(e) if Self::is_transient_error(&e) && attempt < 2 => {
self.handle_transient(port, attempt).await;
}
Err(e) => { self.mark_needs_reconnect(); return Err(e); }
}
}
unreachable!()
}
pub async fn click(&self, args: Value) -> anyhow::Result<Value> {
let selector = args["selector"].as_str().context("Missing 'selector'")?;
let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
for attempt in 0..3 {
let result: anyhow::Result<Value> = async {
let mut guard = self.get_session(port).await?;
let session = guard.get_mut(&port).context("No browser session")?;
let r = session.click_selector(selector).await?;
Ok(json!({ "selector": selector, "result": r }))
}.await;
match result {
Ok(v) => return Ok(v),
Err(e) if Self::is_transient_error(&e) && attempt < 2 => {
self.handle_transient(port, attempt).await;
}
Err(e) => { self.mark_needs_reconnect(); return Err(e); }
}
}
unreachable!()
}
pub async fn fill(&self, args: Value) -> anyhow::Result<Value> {
let selector = args["selector"].as_str().context("Missing 'selector'")?;
let value = args["value"].as_str().context("Missing 'value'")?;
let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
for attempt in 0..3 {
let result: anyhow::Result<Value> = async {
let mut guard = self.get_session(port).await?;
let session = guard.get_mut(&port).context("No browser session")?;
let r = session.fill_selector(selector, value).await?;
Ok(json!({ "selector": selector, "result": r }))
}.await;
match result {
Ok(v) => return Ok(v),
Err(e) if Self::is_transient_error(&e) && attempt < 2 => {
self.handle_transient(port, attempt).await;
}
Err(e) => { self.mark_needs_reconnect(); return Err(e); }
}
}
unreachable!()
}
pub async fn eval(&self, args: Value) -> anyhow::Result<Value> {
let expression = args["expression"].as_str().context("Missing 'expression'")?;
let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
let result: anyhow::Result<Value> = async {
let mut guard = self.get_session(port).await?;
let session = guard.get_mut(&port).context("No browser session")?;
let r = session.evaluate(expression).await?;
Ok(json!({ "expression": expression, "result": r }))
}.await;
if result.is_err() { self.mark_needs_reconnect(); }
result
}
pub async fn wait(&self, args: Value) -> anyhow::Result<Value> {
let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
let timeout_ms = args["timeout_ms"].as_u64().unwrap_or(30000);
let visible = args["visible"].as_bool().unwrap_or(true);
let condition_js = if let Some(selector) = args["selector"].as_str() {
let sel = cdp::js_escape(selector);
if visible {
format!(
"(function(){{ var el = document.querySelector('{}'); if (!el) return false; var r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0; }})()",
sel
)
} else {
format!("!!document.querySelector('{}')", sel)
}
} else if let Some(text) = args["text"].as_str() {
format!("(document.body?.innerText || '').includes('{}')", cdp::js_escape(text))
} else if let Some(url_pat) = args["url"].as_str() {
format!("window.location.href.includes('{}')", cdp::js_escape(url_pat))
} else if let Some(expr) = args["expression"].as_str() {
expr.to_string()
} else {
return Err(anyhow::anyhow!("Provide 'selector', 'text', 'url', or 'expression'"));
};
let result: anyhow::Result<Value> = async {
let mut guard = self.get_session(port).await?;
let session = guard.get_mut(&port).context("No browser session")?;
session.wait_for(&condition_js, timeout_ms).await
}.await;
if result.is_err() { self.mark_needs_reconnect(); }
result
}
pub async fn scroll(&self, args: Value) -> anyhow::Result<Value> {
let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
let direction = args["direction"].as_str().unwrap_or("down");
let pixels = args["pixels"].as_i64().unwrap_or(300);
let selector = args["selector"].as_str();
let result: anyhow::Result<Value> = async {
let mut guard = self.get_session(port).await?;
let session = guard.get_mut(&port).context("No browser session")?;
session.scroll_page(direction, pixels, selector).await
}.await;
if result.is_err() { self.mark_needs_reconnect(); }
result
}
pub async fn hover(&self, args: Value) -> anyhow::Result<Value> {
let selector = args["selector"].as_str().context("Missing 'selector'")?;
let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
let result: anyhow::Result<Value> = async {
let mut guard = self.get_session(port).await?;
let session = guard.get_mut(&port).context("No browser session")?;
session.hover_element(selector).await
}.await;
if result.is_err() { self.mark_needs_reconnect(); }
result
}
pub async fn select(&self, args: Value) -> anyhow::Result<Value> {
let selector = args["selector"].as_str().context("Missing 'selector'")?;
let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
let value = args["value"].as_str();
let text = args["text"].as_str();
let result: anyhow::Result<Value> = async {
let mut guard = self.get_session(port).await?;
let session = guard.get_mut(&port).context("No browser session")?;
session.select_option(selector, value, text).await
}.await;
if result.is_err() { self.mark_needs_reconnect(); }
result
}
pub async fn tabs(&self, args: Value) -> anyhow::Result<Value> {
let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
let result: anyhow::Result<Value> = async {
let mut guard = self.get_session(port).await?;
let session = guard.get_mut(&port).context("No browser session")?;
if session.browser_kind() == cdp::BrowserKind::Firefox {
let tree = session.send_raw("browsingContext.getTree", json!({})).await?;
let contexts = tree.get("contexts").and_then(|c| c.as_array()).cloned().unwrap_or_default();
let tabs: Vec<Value> = contexts.iter().map(|c| json!({
"id": c["context"],
"title": c.get("url").and_then(|u| u.as_str()).unwrap_or(""),
"url": c.get("url").and_then(|u| u.as_str()).unwrap_or(""),
})).collect();
Ok(json!({ "count": tabs.len(), "tabs": tabs }))
} else {
drop(guard);
let tabs = cdp::list_tabs(port).await?;
Ok(json!({ "count": tabs.len(), "tabs": tabs }))
}
}.await;
if result.is_err() { self.mark_needs_reconnect(); }
result
}
pub async fn close(&self, args: Value) -> anyhow::Result<Value> {
let port = args["port"].as_u64().unwrap_or(DEFAULT_PORT as u64) as u16;
let tab_id = args["tab_id"].as_str();
self.sessions.lock().await.remove(&port);
cdp::clear_browser_cache(port);
if let Some(id) = tab_id {
cdp::close_tab(port, id).await?;
Ok(json!({ "success": true, "closed": "tab", "tab_id": id }))
} else {
if let Ok(tabs) = cdp::list_tabs(port).await {
for tab in &tabs {
if let Some(id) = tab["id"].as_str() {
let _ = cdp::close_tab(port, id).await;
}
}
}
let _ = Command::new("fuser")
.args(["-k", &format!("{}/tcp", port)])
.output();
Ok(json!({ "success": true, "closed": "browser", "port": port }))
}
}
}
fn find_browser(preference: Option<&str>) -> anyhow::Result<(&'static str, String)> {
let firefox_bins = ["firefox", "firefox-esr"];
let chrome_bins = [
"google-chrome-stable",
"google-chrome",
"chromium-browser",
"chromium",
];
if let Some(pref) = preference {
let (label, bins): (&'static str, &[&str]) = if pref == "firefox" {
("firefox", &firefox_bins)
} else {
("chrome", &chrome_bins)
};
for bin in bins {
if let Some(path) = which(bin) {
return Ok((label, path));
}
}
return Err(anyhow::anyhow!(
"{} not found. Install it or try the other browser.",
pref
));
}
for bin in &firefox_bins {
if let Some(path) = which(bin) {
return Ok(("firefox", path));
}
}
for bin in &chrome_bins {
if let Some(path) = which(bin) {
return Ok(("chrome", path));
}
}
Err(anyhow::anyhow!(
"No browser found. Install Firefox or Chrome."
))
}
fn which(name: &str) -> Option<String> {
Command::new("which")
.arg(name)
.output()
.ok()
.filter(|o| o.status.success())
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
}