Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

Merge Laya routing indicator, live sandbox viewer and speedups

Oleksandr Ivanchenkobb77a0116c6c
diff --cc src/drivers/mod.rs
index b145a5c3,44870641..feb1a8cb
--- a/src/drivers/mod.rs
+++ b/src/drivers/mod.rs
@@@ -43,10 -43,22 +43,13 @@@ pub struct TurnInput
pub effort_level: Option<String>,
pub team_context: Option<TeamContext>,
pub workspace_dir: Option<std::path::PathBuf>,
+ #[serde(default)]
+ pub browser_api_url: Option<String>,
+ /// Sandbox whose browser is shown to the user for this conversation (team, channel or kwant).
+ #[serde(default)]
+ pub sandbox_id: Option<String>,
}
-static API_PORT: std::sync::OnceLock<u16> = std::sync::OnceLock::new();
-
-/// Records the port the HTTP server listens on, so agents get working sandbox API URLs.
-pub fn set_api_port(port: u16) {
- let _ = API_PORT.set(port);
-}
-
-fn api_port() -> u16 {
- *API_PORT.get().unwrap_or(&8899)
-}
-
impl TurnInput {
pub fn format_system_prompt(&self) -> String {
let base = format!(
@@@ -73,16 -85,33 +76,33 @@@
"\n\nRespond clearly in character.".to_string()
};
- let browser_api = self.browser_api_url.clone().unwrap_or_else(|| {
- format!("http://127.0.0.1:{}/api/sandbox/{}", crate::config::DEFAULT_PORT, self.thread_id)
+ let sandbox_target = self
+ .sandbox_id
+ .clone()
+ .or_else(|| self.team_context.as_ref().map(|t| t.id.clone()))
+ .unwrap_or_else(|| self.kwant.id.clone());
-
- let api = format!("http://127.0.0.1:{}/api/sandbox/{}", api_port(), sandbox_target);
++ let api = self.browser_api_url.clone().unwrap_or_else(|| {
++ format!("http://127.0.0.1:{}/api/sandbox/{}", crate::config::DEFAULT_PORT, sandbox_target)
+ });
let sandbox_rules = format!(
- "\n\n[Bot Browser]\nYour browser session is displayed in the user's right panel. Shell execution uses a separate container.\n\
- Browser API: {browser_api}\n\
- Never open a host desktop browser. To navigate, use curl -sS --fail-with-body -X POST '{browser_api}/navigate' -H 'Content-Type: application/json' -d '{{\"url\":\"<url>\"}}'.\n\
- To inspect the current view: curl -sS --fail-with-body '{browser_api}/screenshot'.\n\
- "\n\n[Virtual Machine Sandbox & Right-Panel In-Container Browser]\n\
- You have an isolated Sandbox Virtual Machine with a headless Chromium browser displayed live in the user's right-side UI panel. The user can browse in it too.\n\
- Sandbox ID: {sandbox}\n\
- CRITICAL BROWSING INSTRUCTIONS:\n\
- 1. NEVER execute host desktop commands (e.g. `open <url>`, `start <url>`, `xdg-open`) or attempt to launch browser windows on the user's desktop!\n\
- 2. All web browsing must happen inside the right-side Sandbox browser, using ONLY these commands (the full API, do not search for more):\n\
- - Open a page: curl -s -X POST {api}/navigate -H 'Content-Type: application/json' -d '{{\"url\":\"<url>\"}}'\n\
- - Read the page (url, title, text, clickable labels): curl -s {api}/page\n\
- - Click a button/link/field by its visible label: curl -s -X POST {api}/act -H 'Content-Type: application/json' -d '{{\"action\":\"click_text\",\"text\":\"<label>\"}}'\n\
- - Type into the focused field: curl -s -X POST {api}/act -H 'Content-Type: application/json' -d '{{\"action\":\"type\",\"text\":\"<text>\"}}'\n\
- - Press a key: curl -s -X POST {api}/act -H 'Content-Type: application/json' -d '{{\"action\":\"key\",\"key\":\"Enter\"}}'\n\
- - Scroll: curl -s -X POST {api}/act -H 'Content-Type: application/json' -d '{{\"action\":\"scroll\",\"delta_y\":600}}'\n\
- Every /act call returns the updated page (url, title, text, clickable), so you rarely need a separate read.\n\
- 3. The current page state and its clickable labels are usually already in the request. Act on them directly.\n\n\
++ "\n\n[Bot Browser]\n\
++ Your browser session is displayed live in the user's right panel; the user can browse in it too. Shell execution uses a separate container.\n\
++ Browser API: {api}\n\
++ Never open a host desktop browser (no `open <url>`, `xdg-open`, etc.). Use ONLY these commands (the full API, do not search for more):\n\
++ - Open a page: curl -sS -X POST '{api}/navigate' -H 'Content-Type: application/json' -d '{{\"url\":\"<url>\"}}'\n\
++ - Read the page (url, title, text, clickable labels): curl -sS '{api}/page'\n\
++ - Click a button/link/field by its visible label: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"click_text\",\"text\":\"<label>\"}}'\n\
++ - Type into the focused field: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"type\",\"text\":\"<text>\"}}'\n\
++ - Press a key: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"key\",\"key\":\"Enter\"}}'\n\
++ - Scroll: curl -sS -X POST '{api}/act' -H 'Content-Type: application/json' -d '{{\"action\":\"scroll\",\"delta_y\":600}}'\n\
++ 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."
++ Report API errors honestly. Never claim a page opened unless navigation succeeded.\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.",
- sandbox = sandbox_target,
+ api = api,
);
format!("{}{}{}", base, team_block, sandbox_rules)
diff --cc src/server/mod.rs
index c33cb353,f0fa5e4a..41191d9c
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@@ -90,7 -86,8 +90,9 @@@ pub fn create_router(state: AppState) -
.route("/api/sandbox/:team_id/restart", post(routes::restart_sandbox))
.route("/api/sandbox/:team_id/navigate", post(routes::navigate_sandbox))
.route("/api/sandbox/:team_id/interact", post(routes::interact_sandbox))
+ .route("/api/sandbox/:team_id/stream", get(browser_stream::upgrade))
+ .route("/api/sandbox/:team_id/page", get(routes::get_sandbox_page))
+ .route("/api/sandbox/:team_id/act", post(routes::act_sandbox))
.route("/api/sandbox/:team_id/passwords", get(routes::get_saved_passwords).post(routes::save_password))
.route("/api/sandbox/:team_id/passwords/:id", delete(routes::delete_password))
.route("/api/events", get(sse::sse_handler))
diff --cc src/server/routes.rs
index 2b8c5dac,37a19548..f8f8f7ba
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@@ -302,17 -324,26 +324,26 @@@ fn execute_single_turn
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: \"{}\".\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, preview
- "{}\n\n[Sandbox Browser State: Successfully navigated the right-panel Sandbox VM 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.]",
++ "{}\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
);
}
}
} else if let Some(ref curr_url) = active_browser_url {
if !curr_url.is_empty() && !curr_url.contains("about:blank") && !curr_url.contains("example.com") {
+ let (title, page_text, clickable) = match active_ctrl {
+ Some(ref ctrl) => (
+ ctrl.current_title.lock().await.clone().unwrap_or_default(),
+ ctrl.extract_content().await.unwrap_or_default(),
+ ctrl.list_clickables(30).await,
+ ),
+ None => (String::new(), String::new(), Vec::new()),
+ };
final_prompt = format!(
- "{}\n\n[Active Sandbox Browser State: The right-panel bot browser is currently viewing: {}. Maintain context on this website. Do not suggest or switch to other services like YouTube unless explicitly requested.]",
- prompt, curr_url
- "{}\n\n[Active Sandbox Browser State: The right-panel Sandbox VM browser (shared live with the user, who may have clicked or typed in it) is currently viewing: {}. Title: \"{}\".\nClickable (topmost first, e.g. dialog buttons): {}\nPage Content Preview:\n{}\n\nMaintain context on this website. Do not suggest or switch to other services like YouTube unless explicitly requested.]",
++ "{}\n\n[Active Sandbox Browser State: The right-panel bot browser (shared live with the user, who may have clicked or typed in it) is currently viewing: {}. Title: \"{}\".\nClickable (topmost first, e.g. dialog buttons): {}\nPage Content Preview:\n{}\n\nMaintain context on this website. Do not suggest or switch to other services like YouTube unless explicitly requested.]",
+ prompt, curr_url, title, clickable.join(" | "), truncate_chars(&page_text, 3000)
);
}
}
@@@ -1390,11 -1511,35 +1489,24 @@@ fn browser_request_failed(error: crate:
pub async fn get_browser_screenshot(
State(state): State<AppState>,
Path(team_id): Path<String>,
-) -> Result<Json<serde_json::Value>, StatusCode> {
- let controller = get_or_create_browser_controller(&state, &team_id).await;
-
- let placeholder = crate::tools::sandbox::PLACEHOLDER_PNG;
- let (b64, url, title) = if let Some(ctrl) = controller {
- let previous_url = ctrl.current_url.lock().await.clone();
- if let Some((new_url, new_title)) = ctrl.sync_location().await {
- if previous_url.as_deref() != Some(new_url.as_str()) {
- let _ = state.event_sender.send(RuntimeEvent::BrowserNavigated {
- team_id: team_id.clone(),
- url: new_url,
- title: new_title,
- status_code: 200,
- });
- }
+) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
+ let ctrl = get_or_create_browser_controller(&state, &team_id).await
+ .ok_or_else(browser_unavailable)?;
++ // The user may have navigated in the live viewer; keep url/title (and other viewers) in sync
++ let previous_url = ctrl.current_url.lock().await.clone();
++ if let Some((new_url, new_title)) = ctrl.sync_location().await {
++ if previous_url.as_deref() != Some(new_url.as_str()) {
++ let _ = state.event_sender.send(RuntimeEvent::BrowserNavigated {
++ team_id: team_id.clone(),
++ url: new_url,
++ title: new_title,
++ status_code: 200,
++ });
+ }
- let shot = match ctrl.capture_screenshot().await {
- Ok(img) => img,
- Err(_) => {
- let lock = ctrl.last_screenshot.lock().await;
- lock.clone().unwrap_or_else(|| placeholder.to_string())
- }
- };
- let curr_url = ctrl.current_url.lock().await.clone().unwrap_or_default();
- let curr_title = ctrl.current_title.lock().await.clone().unwrap_or_default();
- (shot, curr_url, curr_title)
- } else {
- (placeholder.to_string(), String::new(), String::new())
- };
++ }
+ let b64 = ctrl.capture_screenshot().await.map_err(browser_request_failed)?;
+ let url = ctrl.current_url.lock().await.clone().unwrap_or_default();
++ let title = ctrl.current_title.lock().await.clone().unwrap_or_default();
let timestamp = chrono::Utc::now().to_rfc3339();
@@@ -1536,6 -1745,103 +1649,104 @@@ pub async fn interact_sandbox
})))
}
+ /// Compact, text-only page state for agents (no base64 image to wade through).
-async fn sandbox_page_state(ctrl: &crate::sandbox::browser::BrowserController) -> serde_json::Value {
++async fn sandbox_page_state(ctrl: &crate::sandbox::BrowserController) -> serde_json::Value {
+ let (url, title) = match ctrl.sync_location().await {
+ Some(loc) => loc,
+ None => (
+ ctrl.current_url.lock().await.clone().unwrap_or_default(),
+ ctrl.current_title.lock().await.clone().unwrap_or_default(),
+ ),
+ };
+ let text = ctrl.extract_content().await.unwrap_or_default();
+ let clickable = ctrl.list_clickables(40).await;
+ json!({
+ "url": url,
+ "title": title,
+ "text": truncate_chars(&text, 2000),
+ "clickable": clickable,
+ })
+ }
+
-async fn broadcast_sandbox_screenshot(state: &AppState, team_id: &str, ctrl: &crate::sandbox::browser::BrowserController) {
++async fn broadcast_sandbox_screenshot(state: &AppState, team_id: &str, ctrl: &crate::sandbox::BrowserController) {
+ if let Some(b64) = ctrl.last_screenshot.lock().await.clone() {
+ let url = ctrl.current_url.lock().await.clone().unwrap_or_default();
+ let _ = state.event_sender.send(RuntimeEvent::BrowserScreenshot {
+ team_id: team_id.to_string(),
+ url,
+ image_base64: b64,
+ timestamp: chrono::Utc::now().to_rfc3339(),
+ });
+ }
+ }
+
+ pub async fn get_sandbox_page(
+ State(state): State<AppState>,
+ Path(team_id): Path<String>,
-) -> Result<Json<serde_json::Value>, StatusCode> {
++) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
+ let ctrl = get_or_create_browser_controller(&state, &team_id)
+ .await
- .ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
++ .ok_or_else(browser_unavailable)?;
+ Ok(Json(sandbox_page_state(&ctrl).await))
+ }
+
+ /// Agent-facing action endpoint: performs one action and returns the resulting page state,
+ /// so an agent can act and answer without extra round-trips.
+ pub async fn act_sandbox(
+ State(state): State<AppState>,
+ Path(team_id): Path<String>,
+ Json(payload): Json<InteractPayload>,
-) -> Result<Json<serde_json::Value>, StatusCode> {
++) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
+ let ctrl = get_or_create_browser_controller(&state, &team_id)
+ .await
- .ok_or(StatusCode::SERVICE_UNAVAILABLE)?;
++ .ok_or_else(browser_unavailable)?;
++ let _permit = ctrl.control.try_read().map_err(|_| browser_request_failed(crate::sandbox::BrowserError::HumanControl))?;
+ let text = payload.text.clone().unwrap_or_default();
+ let result: Result<String, String> = match payload.action.as_str() {
+ "click_text" | "click" if !text.is_empty() => ctrl
+ .click_text(&text)
+ .await
+ .map(|label| format!("clicked \"{}\"", label))
+ .map_err(|e| e.to_string()),
+ "type" => ctrl
+ .interact_type(&text)
+ .await
+ .map(|_| format!("typed {} chars", text.chars().count()))
+ .map_err(|e| e.to_string()),
+ "key" => {
+ let key = payload.key.clone().unwrap_or_else(|| "Enter".into());
+ ctrl.interact_key(&key, payload.code.as_deref())
+ .await
+ .map(|_| format!("pressed {}", key))
+ .map_err(|e| e.to_string())
+ }
+ "scroll" => ctrl
+ .interact_scroll(640, 400, 0.0, payload.delta_y.unwrap_or(600.0))
+ .await
+ .map(|_| "scrolled".to_string())
+ .map_err(|e| e.to_string()),
+ other => Err(format!(
+ "Unknown action \"{}\". Use click_text (with text), type (with text), key (with key) or scroll (with delta_y).",
+ other
+ )),
+ };
+ broadcast_sandbox_screenshot(&state, &team_id, &ctrl).await;
+ let mut page = sandbox_page_state(&ctrl).await;
+ match result {
+ Ok(done) => page["result"] = json!(done),
+ Err(err) => page["error"] = json!(err),
+ }
+ if let Some(url) = page["url"].as_str() {
+ let _ = state.event_sender.send(RuntimeEvent::BrowserNavigated {
+ team_id: team_id.clone(),
+ url: url.to_string(),
+ title: page["title"].as_str().unwrap_or("").to_string(),
+ status_code: 200,
+ });
+ }
+ Ok(Json(page))
+ }
+
pub async fn execute_tool(
state: &AppState,
team_id: Option<&str>,