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
Accounts: a profile's turns ignore this machine's Claude provider; notice names the account
Lin (kwant bot)8c4ace53beeb
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rsindex 84cd253e..1a0a504a 100644--- a/src/drivers/cli.rs+++ b/src/drivers/cli.rs@@ -639,15 +639,16 @@ impl Driver for CliDriver {let effort = input.effort_level.as_deref().unwrap_or("medium");- let _ = event_tx- .send(RuntimeEvent::ThinkingDelta(format!(- "Invoking local {} CLI (model: {}, effort: {}, binary: {})...",- self.tool_kind,- input.model.as_deref().unwrap_or("default"),- effort,- bin_path- )))- .await;+ // Kept out of the chat: the turn's "Running on" notice already names the engine and+ // account, and the same binary runs every account+ tracing::info!(+ cli = %self.tool_kind,+ model = input.model.as_deref().unwrap_or("default"),+ effort,+ binary = %bin_path,+ profile_home = self.profile_env.is_some(),+ "invoking local CLI"+ );let system_prompt = input.format_system_prompt();let effective_prompt = build_cli_prompt(&input);diff --git a/src/profiles/mod.rs b/src/profiles/mod.rsindex d746bb83..594e9070 100644--- a/src/profiles/mod.rs+++ b/src/profiles/mod.rs@@ -72,6 +72,12 @@ impl Engine {"ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","CLAUDE_CODE_OAUTH_REFRESH_TOKEN",+ // A provider or proxy set for this machine (e.g. Bedrock) would run the+ // profile's turns there instead of on its own login+ "CLAUDE_CODE_USE_BEDROCK",+ "CLAUDE_CODE_USE_VERTEX",+ "CLAUDE_CODE_USE_FOUNDRY",+ "ANTHROPIC_BASE_URL",],Engine::Codex => &["OPENAI_API_KEY", "CODEX_API_KEY"],Engine::Grok => &["XAI_API_KEY", "GROK_AUTH_PATH"],@@ -387,6 +393,9 @@ mod tests {);assert!(env.remove.contains(&"ANTHROPIC_API_KEY".to_string()));assert!(env.remove.contains(&"CLAUDE_CODE_OAUTH_TOKEN".to_string()));+ for provider in ["CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY", "ANTHROPIC_BASE_URL"] {+ assert!(env.remove.contains(&provider.to_string()), "{provider}");+ }let env = CliEnv::for_home(Engine::Codex, home);assert_eq!(env.set[0].0, "CODEX_HOME");assert!(env.remove.contains(&"OPENAI_API_KEY".to_string()));diff --git a/src/profiles/status.rs b/src/profiles/status.rsindex 487d6467..ba1711fe 100644--- a/src/profiles/status.rs+++ b/src/profiles/status.rs@@ -186,16 +186,29 @@ pub(crate) fn claude_status(stdout: &str) -> ProfileStatus {return ProfileStatus::default();};let signed_in = v["loggedIn"].as_bool();- let label = ["email", "emailAddress", "account", "authMethod"]+ // An auth method like "third_party" isn't an account: name the provider it runs on instead+ let label = ["email", "emailAddress", "account"].iter().find_map(|k| v[*k].as_str().filter(|s| !s.is_empty()))- .map(|s| s.chars().take(80).collect());+ .map(|s| s.chars().take(80).collect())+ .or_else(|| (v["authMethod"] == "third_party").then(|| third_party_name(v["apiProvider"].as_str())));ProfileStatus {signed_in,account_label: if signed_in == Some(true) { label } else { None },}}+/// What Claude Code runs on when it's set up for another provider instead of a Claude login.+fn third_party_name(provider: Option<&str>) -> String {+ match provider {+ Some("bedrock") => "Amazon Bedrock",+ Some("vertex") => "Google Vertex AI",+ Some("foundry") => "Microsoft Foundry",+ _ => "a third-party provider",+ }+ .into()+}+pub(crate) fn codex_status(success: bool, stdout: &str, stderr: &str) -> ProfileStatus {let text = format!("{stdout}\n{stderr}");let line = text@@ -236,6 +249,11 @@ mod tests {});assert_eq!(claude_status("garbage"), ProfileStatus::default());+ // Set up for Bedrock (as this machine's env can do): the provider, never "third_party"+ let s = claude_status(r#"{"loggedIn":true,"authMethod":"third_party","apiProvider":"bedrock"}"#);+ assert_eq!(s.account_label.as_deref(), Some("Amazon Bedrock"));+ let s = claude_status(r#"{"loggedIn":true,"authMethod":"claude.ai"}"#);+ assert_eq!(s.account_label, None);let s = codex_status(true, "Logged in using ChatGPT\n", "");assert_eq!(s.signed_in, Some(true));assert_eq!(s.account_label.as_deref(), Some("Logged in using ChatGPT"));diff --git a/src/server/profile_turn.rs b/src/server/profile_turn.rsindex 1530bfba..6d89e396 100644--- a/src/server/profile_turn.rs+++ b/src/server/profile_turn.rs@@ -69,6 +69,15 @@ pub fn profile_engine(p: &LlmProfile) -> Option<EngineId> {}}+/// The account a turn on `engine` runs on, for its "Running on" notice: the profile's name,+/// else "This machine" for a CLI's own login. API keys from Settings and Ollama have none.+pub fn account_name(profile: Option<&LlmProfile>, engine: EngineId) -> Option<String> {+ match profile {+ Some(p) => Some(p.name.clone()),+ None => (engine.kind() == crate::drivers::engines::EngineKind::Cli).then(|| "This machine".into()),+ }+}+/// An engine turned off in Settings is off for every account on it too.fn profile_engine_on(state: &AppState, p: &LlmProfile) -> bool {profile_engine(p).is_none_or(|e| state.engines.is_enabled(e))diff --git a/src/server/routes.rs b/src/server/routes.rsindex ecc29abf..e92cffdd 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -1110,7 +1110,10 @@ async fn run_kwant_turn_inner(}}- let engine = crate::profiles::Engine::parse(&target_model);+ // A routed model id like "claude-sonnet" still runs on Claude's accounts, never+ // straight on this machine's login+ let engine = crate::profiles::Engine::parse(&target_model)+ .or_else(|| crate::profiles::Engine::from_model(&target_model));let candidates = super::profile_turn::plan(state, engine, &target_kwant.id).await;let attempts: Vec<Option<LlmProfile>> = if candidates.is_empty() {vec![None]@@ -1236,8 +1239,11 @@ async fn run_kwant_turn_inner(input.model = if unlisted_api { None } else { choice.as_ref().and_then(|c| c.run_id()).map(str::to_string) };if let Some(e) = runs_on {event_broadcast.send(RuntimeEvent::ThinkingDelta(format!(- "Running on {} · {}{}",+ "Running on {}{} · {}{}",e.name(),+ super::profile_turn::account_name(profile.as_ref(), e)+ .map(|a| format!(" · {a}"))+ .unwrap_or_default(),input.model.as_deref().unwrap_or("default model"),choice.as_ref()diff --git a/tests/account_notice_test.rs b/tests/account_notice_test.rsnew file mode 100644index 00000000..15554a63--- /dev/null+++ b/tests/account_notice_test.rs@@ -0,0 +1,159 @@+//! Oleks's setup: "This machine" turned off, Personal on. A turn runs on Personal's own login+//! even when this machine's env points Claude Code at another provider, and its first status+//! line names the account. Its own test binary: it changes PATH and the process env.++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::Database,+ drivers::RuntimeEvent,+ router::LayaRouter,+ server::{create_router, AppState},+ tools::ToolRunner,+};+use serde_json::{json, Value};+use std::time::Duration;+use tower::ServiceExt;++const FAKE_CLAUDE: &str = r#"#!/bin/sh+case "$1" in+ auth) echo '{"loggedIn":true,"email":"[email protected]"}'; exit 0 ;;+esac+echo "{\"type\":\"result\",\"is_error\":false,\"num_turns\":1,\"result\":\"home=$(basename "${CLAUDE_CONFIG_DIR:-host}") bedrock=${CLAUDE_CODE_USE_BEDROCK:-none} base=${ANTHROPIC_BASE_URL:-none}\",\"usage\":{\"input_tokens\":3,\"output_tokens\":4}}"+"#;++async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {+ let resp = app+ .clone()+ .oneshot(+ Request::builder()+ .method(method)+ .uri(uri)+ .header("content-type", "application/json")+ .body(+ body.map(|v| Body::from(v.to_string()))+ .unwrap_or_else(Body::empty),+ )+ .unwrap(),+ )+ .await+ .unwrap();+ let s = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (s, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+}++/// Sends a prompt and collects the turn's events up to `turn_ended`.+async fn run_turn(app: &Router, state: &AppState, kwant_id: &str) -> Vec<RuntimeEvent> {+ let mut rx = state.event_sender.subscribe();+ let (s, v) = call(+ app,+ "POST",+ "/api/chat/send",+ Some(json!({"kwant_id": kwant_id, "prompt": "hi", "sender_id": "user"})),+ )+ .await;+ assert_eq!(s, StatusCode::OK, "{v}");+ let mut events = Vec::new();+ tokio::time::timeout(Duration::from_secs(60), async {+ while let Ok(e) = rx.recv().await {+ let end = matches!(&e, RuntimeEvent::TurnEnded { kwant_id: k, .. } if k == kwant_id);+ // Turn events arrive tagged with their turn; the test looks at what happened+ events.push(e.unscoped().clone());+ if end {+ break;+ }+ }+ })+ .await+ .expect("turn did not end");+ events+}++#[tokio::test]+async fn personal_turn_names_its_account_and_ignores_this_machines_provider() {+ let tmp = tempfile::tempdir().unwrap();+ let bin = tmp.path().join("bin");+ std::fs::create_dir_all(&bin).unwrap();+ let fake = bin.join("claude");+ std::fs::write(&fake, FAKE_CLAUDE).unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));+ // This machine's Claude Code runs on Bedrock through a proxy; Personal must not+ std::env::set_var("CLAUDE_CODE_USE_BEDROCK", "1");+ std::env::set_var("ANTHROPIC_BASE_URL", "http://127.0.0.1:9/proxy");++ let data = tmp.path().join("data");+ let db = Database::init(&data).await.unwrap();+ let config = Config {+ data_dir: data.clone(),+ laya_url: "http://127.0.0.1:9".into(),+ browser_cdp_url: Some("http://127.0.0.1:9".into()),+ ..Config::default()+ };+ let state = AppState::new(+ config.clone(),+ db,+ ToolRunner::new(data.join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ let app = create_router(state.clone());++ let (s, personal) = call(+ &app,+ "POST",+ "/api/profiles",+ Some(json!({"engine": "claude", "name": "Personal", "kind": "cli_home", "is_default": true, "priority": 100})),+ )+ .await;+ assert!(s.is_success(), "{personal}");+ let personal_id = personal["id"].as_str().unwrap().to_string();+ let (s, _) = call(&app, "PATCH", "/api/profiles/prf_system_claude", Some(json!({"enabled": false}))).await;+ assert_eq!(s, StatusCode::OK);++ let (_, kwants) = call(&app, "GET", "/api/kwants", None).await;+ let k = kwants[0].clone();+ let kid = k["id"].as_str().unwrap().to_string();+ let mut body = k.clone();+ body.as_object_mut().unwrap().retain(|key, _| {+ ["name", "title", "persona_prompt", "soul", "avatar_sprite"].contains(&key.as_str())+ });+ body["preferred_model"] = json!("claude:haiku");+ let (s, v) = call(&app, "PUT", &format!("/api/kwants/{kid}"), Some(body)).await;+ assert_eq!(s, StatusCode::OK, "{v}");++ let events = run_turn(&app, &state, &kid).await;+ let text: String = events+ .iter()+ .filter_map(|e| match e {+ RuntimeEvent::TextDelta(t) => Some(t.as_str()),+ _ => None,+ })+ .collect();+ let notes: Vec<&str> = events+ .iter()+ .filter_map(|e| match e {+ RuntimeEvent::ThinkingDelta(t) => Some(t.as_str()),+ _ => None,+ })+ .collect();+ // Ran with Personal's own home, and without this machine's provider or proxy+ assert!(text.contains(&format!("home={personal_id}")), "{text}");+ assert!(text.contains("bedrock=none base=none"), "{text}");+ // The status line says which account, and never shows the CLI's path+ assert!(+ notes.iter().any(|n| n.starts_with("Running on Claude Code CLI · Personal · haiku")),+ "{notes:?}"+ );+ assert!(!notes.iter().any(|n| n.contains("This machine") || n.contains("binary")), "{notes:?}");+}diff --git a/tests/engine_model_test.rs b/tests/engine_model_test.rsindex e502fd6d..8318f2b5 100644--- a/tests/engine_model_test.rs+++ b/tests/engine_model_test.rs@@ -237,7 +237,7 @@ async fn laya_picks_model_tier_pins_and_engine_switches() {let (text, notes) = turn(&app, &state, &kid, "hi").await;assert!(text.contains("hello from fake claude"), "{text}");assert!(last_argv(tmp.path(), "claude").contains("--model haiku"), "{}", last_argv(tmp.path(), "claude"));- assert!(notes.iter().any(|n| n.contains("Running on Claude Code CLI · haiku (fast tier)")), "{notes:?}");+ assert!(notes.iter().any(|n| n.contains("Running on Claude Code CLI · This machine · haiku (fast tier)")), "{notes:?}");let r = ran_on(&state, &kid).await;assert_eq!((r["engine"].clone(), r["family"].clone(), r["model"].clone(), r["tier"].clone(), r["picked_by"].clone(), r["effort"].clone()),