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
Bot browser: no guessed addresses, refuse file paths (#140)
Lin (kwant bot)6348d9f3b6d9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d705b4b8..c95827ab 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -62,6 +62,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).- **Choices in channels show as chips, not raw text.** A bot's `[DECISIONS] …` block in a teamdiscussion or a "While you were away" post now becomes choice chips you can change, as in directchats. A garbled block (two choices on one line, no closing tag, in a code fence) is removed, never shown.+- **The bot browser no longer opens addresses it guessed.** A message with "open" or "browser" and a+ folder path like `/Users/…/dev/KORB` sent the browser to that path on the site already open+ (`github.com/Users/…`, a 404), and a bot reply that mentioned a server like `registry-1.docker.io`+ opened it on its own. Before a turn the browser now opens only a full `http://` or `https://` link in+ the message, and a reply never moves it. A file path or `file://` address given to the browser is+ refused with a note to read local files with file tools.- **A restart no longer leaves an audit running.** An audit cut off mid-turn by a restart ends`interrupted` and says so in the task's history; one still waiting to start runs after the restart(or is skipped if the auditor was turned off).diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rsindex 6d2b878b..26461c1b 100644--- a/src/sandbox/browser.rs+++ b/src/sandbox/browser.rs@@ -122,6 +122,34 @@ pub enum BrowserError {/// The browser works, but the page itself could not be loaded (DNS, TLS, refused, ...).#[error("Page could not be loaded: {0}")]Navigation(String),+ /// A file path (or file:// address) handed to the browser; see [`refuse_file_path`].+ #[error("{0}")]+ NotWebAddress(String),+}++/// Refuses an address that is a file on the computer before it reaches Chrome, so it is never+/// read as a page on the site already open. file:// is refused in every mode: in Local mode it+/// would show the bot any file on the person's computer, past the folders and approvals its+/// file tools keep to.+pub fn refuse_file_path(target: &str) -> Result<(), BrowserError> {+ let t = target.trim();+ if t.get(..5).is_some_and(|scheme| scheme.eq_ignore_ascii_case("file:")) {+ return Err(BrowserError::NotWebAddress(format!(+ "{t} is a file:// address, which the browser doesn't open. Read local files with your file tools \+ (Read, or cat in the shell); the browser opens http:// and https:// pages."+ )));+ }+ let b = t.as_bytes();+ let drive = b.len() >= 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && matches!(b[2], b'\\' | b'/');+ let path = drive || ["/", "~", "\\", "./", "../", ".\\", "..\\"].iter().any(|p| t.starts_with(p));+ if path {+ return Err(BrowserError::NotWebAddress(format!(+ "{t} is a file path on the computer, not a web address, so the browser didn't open it. \+ Read local files with your file tools (Read, or cat in the shell); the browser opens \+ http:// and https:// pages."+ )));+ }+ Ok(())}/// Recognises CAPTCHA / anti-bot interstitials that replace the requested content.@@ -855,6 +883,7 @@ impl BrowserController {}pub async fn navigate_unlocked(&self, target_url: &str) -> Result<NavigationResult, BrowserError> {+ refuse_file_path(target_url)?;let _ = self.collect_captured_credentials().await;let _ = self.send_cdp_command("Page.enable", json!({})).await;let res = selfdiff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rsindex 9946ef3c..1c287df5 100644--- a/src/sandbox/mod.rs+++ b/src/sandbox/mod.rs@@ -6,7 +6,7 @@ pub mod manager;pub mod service;pub mod vault;-pub use browser::{detect_bot_wall, BrowserController, BrowserError, NavigationResult, PendingCapture};+pub use browser::{detect_bot_wall, refuse_file_path, BrowserController, BrowserError, NavigationResult, PendingCapture};pub use credentials::{Credential, CredentialMeta, CredentialStore, EncryptedFileStore};pub use manager::{ActiveSandbox, SandboxError, SandboxManager, ShellOutput};diff --git a/src/server/routes.rs b/src/server/routes.rsindex ef197c27..4314d527 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -831,7 +831,8 @@ fn execute_single_turn(tokio::spawn(async move {// Ends the job (its cancel keys) when the turn and its handoffs are donelet _job = job;- let opts = TurnOpts { routing, ..TurnOpts::default() };+ // A full link in the person's own message may open the bot browser first+ let opts = TurnOpts { routing, nav_prompt: Some(prompt.clone()), ..TurnOpts::default() };if let Some(reply) = run_kwant_turn(&scope, &target_kwant, turn_prompt, opts).await {run_handoffs(&scope, std::slice::from_ref(&target_kwant.id), &[(target_kwant.clone(), reply)], &prompt).await;// Several bots asked the person something: one list of it all (when the chain is over)@@ -1393,7 +1394,7 @@ async fn run_discussion(scope: &TurnScope, team: &Team, planned: Vec<Kwant>, uselet opts = TurnOpts {label: Some(discussion::turn_label(turn, &team.name)),// Only the opening turn may navigate the bot browser for a URL in the user's message- nav_prompt: Some(if opening { user_prompt.to_string() } else { String::new() }),+ nav_prompt: opening.then(|| user_prompt.to_string()),discussion: Some(opening.then(|| discussion::question_label(&kwant.name, &team.name))),routing: None,on_started: None,@@ -1447,7 +1448,6 @@ async fn run_discussion(scope: &TurnScope, team: &Team, planned: Vec<Kwant>, use});let opts = TurnOpts {label: Some(discussion::summary_label(&team.name, &contributors)),- nav_prompt: Some(String::new()),discussion: None,routing: None,on_started: None,@@ -1464,7 +1464,9 @@ async fn run_discussion(scope: &TurnScope, team: &Team, planned: Vec<Kwant>, usepub(super) struct TurnOpts {/// Saved as the message's `reasoning_content` instead of the driver's reasoning.pub(super) label: Option<String>,- /// Text checked for a URL to open in the bot browser; defaults to the prompt.+ /// The person's own message, checked for a full link to open in the bot browser before the+ /// turn. `None` (hand-offs, routines, follow-ups and other prompts kwnt or a bot wrote) never+ /// moves the browser.nav_prompt: Option<String>,/// Discussion reply handling: `[PASS]` replies aren't saved; `Some(label)` lets an `[ASK_USER]`/// reply be saved as a question for the user under that label.@@ -1514,6 +1516,12 @@ impl TurnOpts {pub(super) fn always_asking(label: &str) -> Self {TurnOpts { label: Some(label.to_string()), always_ask: true, ..Default::default() }}++ /// The link to open in the bot browser before the turn: only a full link in the person's own+ /// message, never one in a prompt kwnt or a bot wrote.+ fn nav_target(&self) -> Option<String> {+ self.nav_prompt.as_deref().and_then(detect_url_in_prompt)+ }}/// Runs one kwant turn: picks model/effort, syncs the bot browser, streams the reply and saves it.@@ -1930,9 +1938,8 @@ async fn run_kwant_turn_inner(};let mut final_prompt = prompt.clone();- let nav_prompt = opts.nav_prompt.as_deref().unwrap_or(&prompt);// A replay opens no page: the bot's browser isn't its scratch folder- let target_url_opt = if opts.rehearse.is_some() { None } else { detect_url_with_context(nav_prompt, active_browser_url.as_deref()) };+ let target_url_opt = if opts.rehearse.is_some() { None } else { opts.nav_target() };if let Some(target_url) = target_url_opt {event_broadcast.send(RuntimeEvent::ThinkingDelta(format!(@@ -2435,30 +2442,8 @@ async fn run_kwant_turn_inner(let _ = db.drop_parked_for_chat(&target_kwant.id, scope.channel_id.as_deref(), scope.kwant_id.as_deref(), scope.thread_id.as_deref()).await;- // Post-turn sync: If bot response outputs a URL, sync navigation so the user sees it in Sandbox VM- if let Some(bot_url) = extract_url_from_text(&output.text) {- if let Some(ctrl) = get_or_create_browser_controller(state, &sandbox_target).await {- let curr = ctrl.current_url.lock().await.clone().unwrap_or_default();- if curr != bot_url && !bot_url.contains("localhost") && !bot_url.contains("127.0.0.1") {- if let Ok(nav) = ctrl.navigate(&bot_url).await {- event_broadcast.send(RuntimeEvent::BrowserNavigated {- team_id: sandbox_target.clone(),- url: nav.url.clone(),- title: nav.title.clone(),- status_code: nav.status_code,- });- if let Some(b64) = ctrl.last_screenshot.lock().await.clone() {- event_broadcast.send(RuntimeEvent::BrowserScreenshot {- team_id: sandbox_target.clone(),- url: nav.url.clone(),- image_base64: b64,- timestamp: chrono::Utc::now().to_rfc3339(),- });- }- }- }- }- }+ // A bot reply never moves the browser: the first domain-like word in it (e.g. Docker's+ // registry-1.docker.io) opened as a 404. The bot opens pages itself with its browser tools.// Counts toward the chain's token budget (see `super::budget`)let fresh = output.usage.map_or(output.tokens_used as u64, |u| u.fresh());@@ -3198,11 +3183,12 @@ async fn send_to_thread(let job = state.turns.start_job([saved.id.clone(), thread.id.clone()]);let scope = scope_for(&state, &kwant, None, Some(thread.id.clone()), &job, depth).await.map_err(|_| StatusCode::NOT_FOUND)?;+ let opts = TurnOpts { nav_prompt: Some(payload.prompt.clone()), ..TurnOpts::default() };let prompt = payload.prompt + ¬e;let target = kwant.clone();tokio::spawn(async move {let _job = job;- run_kwant_turn(&scope, &target, prompt, TurnOpts::default()).await;+ run_kwant_turn(&scope, &target, prompt, opts).await;});Ok(Json(json!({"status": "dispatched",@@ -3922,110 +3908,19 @@ pub async fn resolve_sandbox_target_info(state: &AppState, target_id: &str) -> O}}-const EXCLUDED_EXTENSIONS: &[&str] = &[- "rs", "ts", "tsx", "js", "jsx", "json", "toml", "yaml", "yml", "md",- "txt", "log", "lock", "png", "jpg", "jpeg", "gif", "svg", "css", "html",- "sh", "py", "go", "c", "cpp", "h", "java", "kt", "rb", "php", "sql",-];--pub fn extract_url_from_text(text: &str) -> Option<String> {- for word in text.split_whitespace() {- let clean = word.trim_matches(|c: char| {- !c.is_alphanumeric() && c != '.' && c != '/' && c != ':' && c != '-' && c != '_' && c != '?' && c != '=' && c != '&' && c != '#'- });- if clean.starts_with("http://") || clean.starts_with("https://") {- return Some(clean.to_string());- }- if !clean.contains('@') && clean.contains('.') && !clean.starts_with('.') && !clean.ends_with('.') {- let host_part = clean.split('/').next().unwrap_or("");- let parts: Vec<&str> = host_part.split('.').collect();- if parts.len() >= 2 {- let tld = parts.last().unwrap_or(&"");- let tld_lower = tld.to_lowercase();- if tld.len() >= 2- && tld.len() <= 12- && tld.chars().all(|c| c.is_ascii_alphabetic())- && !EXCLUDED_EXTENSIONS.contains(&tld_lower.as_str())- {- let valid_labels = parts.iter().all(|label| {- !label.is_empty()- && !label.starts_with('-')- && !label.ends_with('-')- && label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')- });- if valid_labels {- return Some(format!("https://{}", clean));- }- }- }- }- }- None-}--pub fn detect_url_with_context(prompt: &str, current_url: Option<&str>) -> Option<String> {- let lower = prompt.to_lowercase();- let is_browser_request = lower.contains("browser")- || lower.contains("open ")- || lower.contains("navigate")- || lower.contains("go to ")- || lower.contains("browse ")- || lower.contains("visit ")- || lower.contains("search for ")- || lower.contains("look up ")- || lower.contains("http://")- || lower.contains("https://");-- if let Some(direct_url) = extract_url_from_text(prompt) {- if is_browser_request || prompt.split_whitespace().count() <= 3 {- return Some(direct_url);- }- }-- if !is_browser_request {- return None;- }-- // Relative navigation if active current_url exists- if let Some(curr) = current_url {- let curr = curr.trim();- if (curr.starts_with("http://") || curr.starts_with("https://")) && !curr.contains("about:blank") && !curr.contains("example.com") {- let origin = if let Some(idx) = curr[8..].find('/') {- &curr[..8 + idx]- } else {- curr- };-- for word in prompt.split_whitespace() {- let clean = word.trim_matches(|c: char| !c.is_alphanumeric() && c != '/');- if clean.starts_with('/') && clean.len() > 1 {- return Some(format!("{}{}", origin, clean));- }- }-- if lower.contains("playlist") {- return Some(format!("{}/playlists", origin));- } else if lower.contains("explore") {- return Some(format!("{}/explore", origin));- } else if lower.contains("search") && !lower.contains("google") {- return Some(format!("{}/search", origin));- } else if lower.contains("login") || lower.contains("sign in") {- return Some(format!("{}/login", origin));- } else if lower.contains("settings") {- return Some(format!("{}/settings", origin));- } else if lower.contains("about") {- return Some(format!("{}/about", origin));- } else if lower.contains("home") {- return Some(origin.to_string());- }- }- }-- None-}-+/// The page to open before a bot starts: the first full `http://` or `https://` link in the+/// message, nothing else. kwant used to guess here (bare domains, a `/word` joined to the page+/// already open, "settings"/"home"/"search" pages), which sent a Mac folder path+/// `/Users/…` to `github.com/Users/…`. Anything else the bot opens itself with its browser tools.pub fn detect_url_in_prompt(prompt: &str) -> Option<String> {- detect_url_with_context(prompt, None)+ prompt.split_whitespace().find_map(|word| {+ let start = word.find("http://").or_else(|| word.find("https://"))?;+ let link = word[start..].trim_end_matches(|c: char| {+ matches!(c, '.' | ',' | ';' | ':' | '!' | '?' | ')' | ']' | '}' | '>' | '"' | '\'' | '`' | '*')+ });+ let parsed = reqwest::Url::parse(link).ok()?;+ (matches!(parsed.scheme(), "http" | "https") && parsed.host_str().is_some()).then(|| link.to_string())+ })}pub async fn get_or_create_browser_controller(@@ -4077,6 +3972,7 @@ fn browser_unavailable(state: &AppState) -> (StatusCode, Json<serde_json::Value>fn browser_request_failed(error: crate::sandbox::BrowserError) -> (StatusCode, Json<serde_json::Value>) {if matches!(error, crate::sandbox::BrowserError::HumanControl) { return (StatusCode::CONFLICT, Json(json!({"error": error.to_string()}))); }+ if matches!(error, crate::sandbox::BrowserError::NotWebAddress(_)) { return (StatusCode::BAD_REQUEST, Json(json!({"error": error.to_string()}))); }if let crate::sandbox::BrowserError::Navigation(reason) = &error {return (StatusCode::UNPROCESSABLE_ENTITY, Json(json!({"error": format!("The site could not be reached ({}). The browser is working; check the address.", reason)@@ -4470,6 +4366,19 @@ pub async fn execute_tool(mod tests {use super::{scrub_urls, turn_failed_text};+ #[test]+ fn only_the_persons_own_message_can_open_a_link_before_a_turn() {+ use super::TurnOpts;+ // hand-offs, routines and follow-ups pass no nav prompt, even when theirs has a full link+ assert_eq!(TurnOpts::default().nav_target(), None);+ assert_eq!(TurnOpts::always_asking("x").nav_target(), None);+ let person = |text: &str| TurnOpts { nav_prompt: Some(text.into()), ..TurnOpts::default() };+ assert_eq!(person("open https://example.org please").nav_target(), Some("https://example.org".into()));+ // Oleks's two cases stay put even in the person's own message+ assert_eq!(person("open the browser at /Users/oleksandr.ivanchenko/dev/KORB").nav_target(), None);+ assert_eq!(person("pulling from registry-1.docker.io failed").nav_target(), None);+ }+#[test]fn a_saved_turn_failure_hides_secrets_and_home_folders() {let tag = crate::drivers::events::TurnTag {diff --git a/tests/browser_test.rs b/tests/browser_test.rsindex eef23fbb..5c84466e 100644--- a/tests/browser_test.rs+++ b/tests/browser_test.rs@@ -39,6 +39,63 @@ async fn test_browser_controller_connection_failure() {}}+/// Oleks's Mac: a bot gave the browser /Users/…/dev/KORB/… while it was on github.com and+/// landed on github.com/Users/… (404). A path never reaches Chrome: nothing listens on 65530, so+/// any attempt to talk to it would come back as Http instead.+#[tokio::test]+async fn a_file_path_is_refused_before_the_browser_is_asked() {+ let controller = BrowserController::new(65530);+ for path in [+ "/Users/oleksandr.ivanchenko/dev/KORB/docker-compose.yml",+ " /home/kwnt/notes.md",+ "~/dev/KORB",+ "./web/src/styles/global.css",+ "../README.md",+ "C:\\Users\\me\\file.txt",+ "c:/Users/me/file.txt",+ "\\\\server\\share",+ "file:///Users/me/secret.txt",+ "FILE:///etc/passwd",+ ] {+ match controller.navigate(path).await {+ Err(BrowserError::NotWebAddress(msg)) => {+ assert!(msg.contains("file tools"), "{path}: {msg}");+ assert!(msg.contains("http://"), "{path}: {msg}");+ }+ other => panic!("{path}: expected NotWebAddress, got {other:?}"),+ }+ assert!(matches!(controller.navigate_unlocked(path).await, Err(BrowserError::NotWebAddress(_))), "{path}");+ }+ assert_eq!(controller.current_url.lock().await.as_deref(), None);+}++#[test]+fn web_addresses_still_pass_the_file_path_check() {+ use kwnt::sandbox::refuse_file_path;+ for url in [+ "https://github.com/alexsergivan/kwant",+ "http://localhost:5174/search",+ "https://example.com/Users/profile",+ "about:blank",+ "data:text/html,<p>hi</p>",+ ] {+ assert!(refuse_file_path(url).is_ok(), "{url}");+ }+}++#[tokio::test]+async fn the_browser_tool_tells_the_bot_to_use_file_tools_for_a_path() {+ let controller = BrowserController::new(65530);+ let err = kwnt::tools::sandbox::browser_navigate_with_controller(+ Some(&controller),+ &json!({"url": "/Users/oleksandr.ivanchenko/dev/KORB/web"}),+ )+ .await+ .unwrap_err()+ .to_string();+ assert!(err.contains("not a web address") && err.contains("file tools"), "{err}");+}+#[tokio::test]async fn test_mock_cdp_controller_lifecycle() {let http_listener = TcpListener::bind("127.0.0.1:0").await.unwrap();diff --git a/tests/server_test.rs b/tests/server_test.rsindex 57683031..76151fcb 100644--- a/tests/server_test.rs+++ b/tests/server_test.rs@@ -675,43 +675,33 @@ async fn test_sandbox_interaction_errors_are_not_reported_as_success() {}}-#[tokio::test]-async fn test_url_extraction_and_relative_navigation() {- use kwnt::server::routes::{detect_url_in_prompt, detect_url_with_context, extract_url_from_text};-- // 1. Modern TLD (.ing) extraction- let url = extract_url_from_text("please open example.org for me");- assert_eq!(url, Some("https://example.org".to_string()));-- // 2. Code extensions must not be treated as URLs- assert_eq!(extract_url_from_text("read src/main.rs"), None);- assert_eq!(extract_url_from_text("check file.json"), None);-- // 3. Direct URL in prompt detection+/// The bot browser opens a page on its own only for a full http(s) link in the message. It used+/// to guess: a `/Users/…` folder path was joined to the open github.com page, and "settings" or+/// "home" became pages on the open site.+#[test]+fn only_a_full_link_opens_the_browser_before_a_turn() {+ use kwnt::server::routes::detect_url_in_prompt;++ assert_eq!(detect_url_in_prompt("open https://example.org/a?b=1 for me"), Some("https://example.org/a?b=1".into()));+ assert_eq!(detect_url_in_prompt("see (https://example.org/x)."), Some("https://example.org/x".into()));+ assert_eq!(detect_url_in_prompt("browse http://localhost:5174/search, please"), Some("http://localhost:5174/search".into()));++ // Oleks's case: a folder path with "open"/"browser" in the messageassert_eq!(- detect_url_in_prompt("open example.org"),- Some("https://example.org".to_string())- );-- // 4. Relative navigation with active browser context- let rel_playlist = detect_url_with_context(- "open some playlist page",- Some("https://example.org"),- );- assert_eq!(rel_playlist, Some("https://example.org/playlists".to_string()));-- let rel_path = detect_url_with_context(- "navigate to /explore",- Some("https://example.org"),- );- assert_eq!(rel_path, Some("https://example.org/explore".to_string()));-- // 5. Explicit navigation to another site overrides active browser context- let override_url = detect_url_with_context(- "open youtube.com",- Some("https://example.org"),+ detect_url_in_prompt("open the browser and check /Users/oleksandr.ivanchenko/dev/KORB/web/src/styles/global.css"),+ None);- assert_eq!(override_url, Some("https://youtube.com".to_string()));+ assert_eq!(detect_url_in_prompt("navigate to /explore"), None);+ assert_eq!(detect_url_in_prompt("open some playlist page"), None);+ assert_eq!(detect_url_in_prompt("open the settings"), None);+ assert_eq!(detect_url_in_prompt("go to home"), None);+ // Bare domains and file names are no longer guessed at+ assert_eq!(detect_url_in_prompt("open example.org"), None);+ assert_eq!(detect_url_in_prompt("pulled from registry-1.docker.io"), None);+ assert_eq!(detect_url_in_prompt("read src/main.rs"), None);+ // file:// and other schemes are never opened+ assert_eq!(detect_url_in_prompt("open file:///Users/me/a.txt"), None);+ assert_eq!(detect_url_in_prompt("open https://"), None);}#[tokio::test]