Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Detect CAPTCHA/bot walls and report real browser location to agents
Oleksandr Ivanchenko0fc471e40f0f
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rsindex feb1a8cb..9e7f73f4 100644--- a/src/drivers/mod.rs+++ b/src/drivers/mod.rs@@ -98,7 +98,7 @@ impl TurnInput {Every /act call returns the updated page (url, title, text, clickable), so you rarely need a separate read. \The current page state and its clickable labels are usually already in the request; act on them directly.\n\A 409 means the user has taken control: stop browser actions and wait for the user to return control. Never bypass the control API or connect to CDP directly.\n\- Report API errors honestly. Never claim a page opened unless navigation succeeded.\n\n\+ Report API errors honestly. Never claim a page opened unless navigation succeeded, and only describe content that appears in the returned page text. If a response has \"blocked\": true (CAPTCHA / bot check), follow its \"notice\" instead of claiming results.\n\n\[Speed]\n\The user is waiting in a live chat. Respond as fast as possible: answer directly when you can, use the fewest tool calls (usually one), \do not explore the filesystem, read source code or plan multi-step investigations to figure out how the browser works, and keep replies short.",diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rsindex d0a5acea..1533cda4 100644--- a/src/sandbox/browser.rs+++ b/src/sandbox/browser.rs@@ -102,6 +102,24 @@ pub enum BrowserError {Navigation(String),}+/// Recognises CAPTCHA / anti-bot interstitials that replace the requested content.+pub fn detect_bot_wall(url: &str, title: &str, text: &str) -> Option<&'static str> {+ let url = url.to_lowercase();+ let title = title.to_lowercase();+ let text = text.to_lowercase();+ if url.contains("google.") && url.contains("/sorry/") || text.contains("unusual traffic from your computer network") {+ return Some("Google \"unusual traffic\" CAPTCHA");+ }+ if title.starts_with("just a moment") || text.contains("checking your browser") || text.contains("checking if the site connection is secure") {+ return Some("Cloudflare bot check");+ }+ let captcha_markers = ["i'm not a robot", "i am not a robot", "are you a robot", "verify you are human", "verifying you are human", "prove you're human", "complete the captcha"];+ if captcha_markers.iter().any(|m| text.contains(m) || title.contains(m)) || url.contains("captcha") {+ return Some("CAPTCHA / human verification");+ }+ None+}+#[derive(Debug, Clone, Serialize, Deserialize)]pub struct NavigationResult {pub url: String,@@ -589,32 +607,24 @@ impl BrowserController {}*self.last_screenshot.lock().await = None;- // Extract title- let eval_res = self- .send_cdp_command(- "Runtime.evaluate",- json!({ "expression": "document.title", "returnByValue": true }),- )- .await- .ok();-- let title = eval_res- .as_ref()- .and_then(|r| r["result"]["value"].as_str())- .unwrap_or(target_url)- .to_string();-- *self.current_url.lock().await = Some(target_url.to_string());- *self.current_title.lock().await = Some(title.clone());+ // Report where the browser actually ended up (redirects, e.g. to a CAPTCHA page)+ let (url, title) = match self.sync_location().await {+ Some(loc) => loc,+ None => {+ *self.current_url.lock().await = Some(target_url.to_string());+ *self.current_title.lock().await = Some(target_url.to_string());+ (target_url.to_string(), target_url.to_string())+ }+ };// Automatically inject autofill and capture hooks- let _ = self.inject_autofill_and_capture(target_url).await;+ let _ = self.inject_autofill_and_capture(&url).await;// Automatically capture fresh screenshot on navigationself.capture_screenshot().await?;Ok(NavigationResult {- url: target_url.to_string(),+ url,title,status_code: 200,})diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rsindex e246d6d3..38563646 100644--- a/src/sandbox/mod.rs+++ b/src/sandbox/mod.rs@@ -2,6 +2,6 @@ pub mod browser;pub mod manager;pub mod service;-pub use browser::{BrowserController, BrowserError, NavigationResult, SavedCredential};+pub use browser::{detect_bot_wall, BrowserController, BrowserError, NavigationResult, SavedCredential};pub use manager::{ActiveSandbox, SandboxError, SandboxManager, ShellOutput};diff --git a/src/server/routes.rs b/src/server/routes.rsindex 329d907e..af822556 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -313,23 +313,30 @@ fn execute_single_turn(let preview = truncate_chars(&page_text, 3000);let _ = event_broadcast.send(RuntimeEvent::BrowserNavigated {team_id: sandbox_target.clone(),- url: target_url.clone(),+ url: nav.url.clone(),title: nav.title.clone(),status_code: nav.status_code,});if let Some(b64) = ctrl.last_screenshot.lock().await.clone() {let _ = event_broadcast.send(RuntimeEvent::BrowserScreenshot {team_id: sandbox_target.clone(),- url: target_url.clone(),+ url: nav.url.clone(),image_base64: b64,timestamp: chrono::Utc::now().to_rfc3339(),});}- let clickable = ctrl.list_clickables(30).await;- final_prompt = format!(- "{}\n\n[Sandbox Browser State: Successfully navigated the right-panel bot browser to {}. Title: \"{}\".\nClickable (topmost first): {}\nPage Content Preview:\n{}\n\nUse this page content to answer the user's request. NEVER attempt to open a desktop browser window.]",- prompt, target_url, nav.title, clickable.join(" | "), preview- );+ final_prompt = if let Some(kind) = crate::sandbox::detect_bot_wall(&nav.url, &nav.title, &page_text) {+ format!(+ "{}\n\n[Sandbox Browser State: Tried to open {} in the right-panel bot browser. {}]",+ prompt, target_url, bot_wall_notice(kind, &nav.url)+ )+ } else {+ let clickable = ctrl.list_clickables(30).await;+ format!(+ "{}\n\n[Sandbox Browser State: The right-panel bot browser is now on {}. Title: \"{}\".\nClickable (topmost first): {}\nPage Content Preview:\n{}\n\nUse this page content to answer the user's request; only describe what it actually shows. NEVER attempt to open a desktop browser window.]",+ prompt, nav.url, nav.title, clickable.join(" | "), preview+ )+ };}Err(crate::sandbox::BrowserError::Navigation(reason)) => {let shown_url = ctrl.current_url.lock().await.clone().unwrap_or_else(|| target_url.clone());@@ -415,14 +422,14 @@ fn execute_single_turn(if let Ok(nav) = ctrl.navigate(&bot_url).await {let _ = event_broadcast.send(RuntimeEvent::BrowserNavigated {team_id: sandbox_target.clone(),- url: bot_url.clone(),+ url: nav.url.clone(),title: nav.title.clone(),status_code: nav.status_code,});if let Some(b64) = ctrl.last_screenshot.lock().await.clone() {let _ = event_broadcast.send(RuntimeEvent::BrowserScreenshot {team_id: sandbox_target.clone(),- url: bot_url.clone(),+ url: nav.url.clone(),image_base64: b64,timestamp: chrono::Utc::now().to_rfc3339(),});@@ -783,22 +790,29 @@ pub async fn send_chat(let preview = truncate_chars(&page_text, 3000);let _ = event_broadcast.send(RuntimeEvent::BrowserNavigated {team_id: team_clone.id.clone(),- url: target_url.clone(),+ url: nav.url.clone(),title: nav.title.clone(),status_code: nav.status_code,});if let Some(b64) = ctrl.last_screenshot.lock().await.clone() {let _ = event_broadcast.send(RuntimeEvent::BrowserScreenshot {team_id: team_clone.id.clone(),- url: target_url.clone(),+ url: nav.url.clone(),image_base64: b64,timestamp: chrono::Utc::now().to_rfc3339(),});}- speaker_prompt = format!(- "{}\n\n[Sandbox Browser State: Successfully navigated the right-panel bot browser to {}. Title: \"{}\".\nPage Content Preview:\n{}\n\nUse this page content in your discussion analysis. NEVER attempt to open a desktop browser window.]",- speaker_prompt, target_url, nav.title, preview- );+ speaker_prompt = if let Some(kind) = crate::sandbox::detect_bot_wall(&nav.url, &nav.title, &page_text) {+ format!(+ "{}\n\n[Sandbox Browser State: Tried to open {}. {}]",+ speaker_prompt, target_url, bot_wall_notice(kind, &nav.url)+ )+ } else {+ format!(+ "{}\n\n[Sandbox Browser State: The right-panel bot browser is now on {}. Title: \"{}\".\nPage Content Preview:\n{}\n\nUse this page content in your discussion analysis; only describe what it actually shows. NEVER attempt to open a desktop browser window.]",+ speaker_prompt, nav.url, nav.title, preview+ )+ };}}}@@ -1572,32 +1586,30 @@ pub async fn navigate_sandbox(let ctrl = get_or_create_browser_controller(&state, &team_id).await.ok_or_else(browser_unavailable)?;let nav = ctrl.navigate(&payload.url).await.map_err(browser_request_failed)?;- let title = nav.title;- let status_code = nav.status_code;let _ = state.event_sender.send(RuntimeEvent::BrowserNavigated {team_id: team_id.clone(),- url: payload.url.clone(),- title: title.clone(),- status_code,+ url: nav.url.clone(),+ title: nav.title.clone(),+ status_code: nav.status_code,});if let Some(b64) = ctrl.last_screenshot.lock().await.clone() {let _ = state.event_sender.send(RuntimeEvent::BrowserScreenshot {team_id: team_id.clone(),- url: payload.url.clone(),+ url: nav.url.clone(),image_base64: b64,timestamp: chrono::Utc::now().to_rfc3339(),});}- Ok(Json(json!({- "status": "navigated",- "team_id": team_id,- "url": payload.url,- "title": title,- "status_code": status_code- })))+ // Return the real page so agents can't mistake a redirect/CAPTCHA for success+ let mut page = sandbox_page_state(&ctrl).await;+ page["status"] = json!(if page["blocked"].as_bool() == Some(true) { "blocked" } else { "navigated" });+ page["team_id"] = json!(team_id);+ page["requested_url"] = json!(payload.url);+ page["status_code"] = json!(nav.status_code);+ Ok(Json(page))}#[derive(Deserialize)]@@ -1683,12 +1695,29 @@ async fn sandbox_page_state(ctrl: &crate::sandbox::BrowserController) -> serde_j};let text = ctrl.extract_content().await.unwrap_or_default();let clickable = ctrl.list_clickables(40).await;- json!({+ let mut page = json!({"url": url,"title": title,"text": truncate_chars(&text, 2000),"clickable": clickable,- })+ "blocked": false,+ });+ if let Some(kind) = crate::sandbox::detect_bot_wall(&url, &title, &text) {+ page["blocked"] = json!(true);+ page["notice"] = json!(bot_wall_notice(kind, &url));+ }+ page+}++/// Instruction for the agent when a site answers with a CAPTCHA instead of content.+pub fn bot_wall_notice(kind: &str, url: &str) -> String {+ format!(+ "BLOCKED: the site answered with a {} ({}) instead of the requested content. \+ Do NOT describe results you have not seen. Tell the user plainly that the site blocked the automated browser, then either \+ retry once on another engine via the browser API and say you switched (web: https://www.bing.com/search?q=<query>, images: https://www.bing.com/images/search?q=<query>), \+ or offer that they solve the check themselves in the live browser panel.",+ kind, url+ )}async fn broadcast_sandbox_screenshot(state: &AppState, team_id: &str, ctrl: &crate::sandbox::BrowserController) {diff --git a/tests/browser_test.rs b/tests/browser_test.rsindex f2c99027..5a2308fe 100644--- a/tests/browser_test.rs+++ b/tests/browser_test.rs@@ -89,7 +89,9 @@ async fn test_mock_cdp_controller_lifecycle() {"Page.captureScreenshot" => json!({ "data": "dGVzdC1zY3JlZW5zaG90" }),"Runtime.evaluate" => {let expr = parsed["params"]["expression"].as_str().unwrap();- if expr == "document.title" {+ if expr == "[location.href, document.title]" {+ json!({ "result": { "type": "object", "value": ["https://kwants.internal/app", "Kwants Sandbox Test"] } })+ } else if expr == "document.title" {json!({ "result": { "type": "string", "value": "Kwants Sandbox Test" } })} else if expr.contains("clone.innerText") {json!({ "result": { "type": "string", "value": "Extracted DOM Content" } })@@ -653,3 +655,17 @@ async fn test_mock_cdp_interactive_control() {assert!(methods.contains(&"Page.captureScreenshot"));}++#[test]+fn detects_captcha_and_bot_check_pages() {+ use kwnt::sandbox::detect_bot_wall;+ assert!(detect_bot_wall(+ "https://www.google.com/sorry/index?continue=https://www.google.com/search%3Fq%3Dcat",+ "https://www.google.com/search?q=cat",+ "About this page Our systems have detected unusual traffic from your computer network.",+ )+ .is_some());+ assert!(detect_bot_wall("https://example.org/", "Just a moment...", "").is_some());+ assert!(detect_bot_wall("https://shop.example/", "Shop", "Please verify you are human to continue").is_some());+ assert!(detect_bot_wall("https://www.bing.com/images/search?q=cat", "cat - Bing images", "Cat pictures, kittens").is_none());+}