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
Approvals: "Always this session" lasts for the one conversation it was given in
Lin (kwant bot)b66c999d118e
diff --git a/src/broker/mod.rs b/src/broker/mod.rsindex a39e6f6d..911cc707 100644--- a/src/broker/mod.rs+++ b/src/broker/mod.rs@@ -22,8 +22,9 @@ pub struct ApprovalRequest {#[derive(Clone, Debug, Default)]pub struct PermissionBroker {pending: Arc<Mutex<HashMap<String, oneshot::Sender<ApprovalDecision>>>>,- /// (kwant_id, tool_name) pairs the user chose "always allow" for, until kwnt restarts.- always_allowed: Arc<Mutex<HashSet<(String, String)>>>,+ /// (kwant_id, conversation, tool_name) the user chose "always allow" for: that bot may use+ /// that tool again in that one conversation, until kwnt restarts.+ always_allowed: Arc<Mutex<HashSet<(String, String, String)>>>,}impl PermissionBroker {@@ -69,17 +70,26 @@ impl PermissionBroker {self.pending.lock().await.remove(ticket_id).is_some()}- /// Remembers an "always allow" answer for this kwant and tool for the rest of the session.- pub async fn allow_for_session(&self, kwant_id: &str, tool_name: &str) {- self.always_allowed.lock().await.insert((kwant_id.to_string(), tool_name.to_string()));+ /// Remembers an "always allow" answer for this kwant and tool in one conversation (a thread,+ /// else the channel or direct chat). Another conversation with the same bot asks again.+ pub async fn allow_for_session(&self, kwant_id: &str, conversation: &str, tool_name: &str) {+ self.always_allowed.lock().await.insert((+ kwant_id.to_string(),+ conversation.to_string(),+ tool_name.to_string(),+ ));}/// Forgets a deleted bot's "always allow" answers.pub async fn forget_kwant(&self, kwant_id: &str) {- self.always_allowed.lock().await.retain(|(k, _)| k != kwant_id);+ self.always_allowed.lock().await.retain(|(k, _, _)| k != kwant_id);}- pub async fn is_allowed_for_session(&self, kwant_id: &str, tool_name: &str) -> bool {- self.always_allowed.lock().await.contains(&(kwant_id.to_string(), tool_name.to_string()))+ pub async fn is_allowed_for_session(&self, kwant_id: &str, conversation: &str, tool_name: &str) -> bool {+ self.always_allowed.lock().await.contains(&(+ kwant_id.to_string(),+ conversation.to_string(),+ tool_name.to_string(),+ ))}}diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rsindex 2fdf2d52..3998feb0 100644--- a/src/server/mcp_runtime.rs+++ b/src/server/mcp_runtime.rs@@ -120,6 +120,8 @@ pub struct BrokerApprover {pub broker: PermissionBroker,pub events: broadcast::Sender<RuntimeEvent>,pub timeout: Duration,+ /// The conversation "always allow" answers are kept for (see [`turn_conversation`]).+ pub conversation: String,}/// Withdraws the ticket if the waiting turn is cancelled (its future dropped) mid-wait.@@ -148,7 +150,7 @@ impl Drop for TicketGuard {#[async_trait]impl ToolApprover for BrokerApprover {async fn approve(&self, req: ToolApprovalRequest) -> bool {- if self.broker.is_allowed_for_session(&req.kwant_id, &req.tool_name).await {+ if self.broker.is_allowed_for_session(&req.kwant_id, &self.conversation, &req.tool_name).await {return true;}let details = match &req.builtin {@@ -212,7 +214,7 @@ impl ToolApprover for BrokerApprover {match decision {Ok(Ok(ApprovalDecision::AllowOnce)) => true,Ok(Ok(ApprovalDecision::AlwaysAllowSession)) => {- self.broker.allow_for_session(&req.kwant_id, &req.tool_name).await;+ self.broker.allow_for_session(&req.kwant_id, &self.conversation, &req.tool_name).await;true}Ok(Ok(ApprovalDecision::Deny)) | Ok(Err(_)) => false,@@ -235,6 +237,19 @@ fn max_tool_iterations(setting: Option<String>) -> usize {.clamp(1, 50)}+/// The conversation a turn runs in: its thread, else its channel or direct chat. A turn kwnt+/// isn't tracking (no turn id, or not started through the turn registry) is its own+/// conversation, so an "always allow" there lasts only that turn.+fn turn_conversation(state: &AppState, turn_id: &str) -> String {+ state+ .turns+ .active_turns()+ .into_iter()+ .find(|t| t.turn_id == turn_id)+ .map(|t| t.thread_id.unwrap_or(t.context_id))+ .unwrap_or_else(|| format!("turn:{turn_id}"))+}+/// Address agent CLIs on this host use to reach kwnt.fn local_base_url(state: &AppState) -> String {let host = match state.config.host.as_str() {@@ -284,11 +299,13 @@ pub async fn prepare_turn_with_self(servers.push(super::continuity::self_server(&local_base_url(state), &token));}let setting = state.db.get_setting("mcp_max_tool_iterations").await.ok().flatten();+ let turn_id = turn_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());let broker_approver: Arc<dyn ToolApprover> = Arc::new(BrokerApprover {db: state.db.clone(),broker: state.broker.clone(),events: state.event_sender.clone(),timeout: APPROVAL_TIMEOUT,+ conversation: turn_conversation(state, &turn_id),});let ctx = McpTurnContext {servers,@@ -303,7 +320,6 @@ pub async fn prepare_turn_with_self(max_tool_iterations: max_tool_iterations(setting),records: Default::default(),};- let turn_id = turn_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());let session = PermissionSession::new(kwant.id.clone(), kwant.name.clone(), turn_id, ctx.clone(), cwd);state.mcp_sessions.lock().await.insert(token.clone(), session);if let (true, Some(scope)) = (self_tools, self_scope) {diff --git a/tests/builtin_tools_test.rs b/tests/builtin_tools_test.rsindex d374ae70..102b51b4 100644--- a/tests/builtin_tools_test.rs+++ b/tests/builtin_tools_test.rs@@ -1,7 +1,7 @@//! claude's own tools through kwnt's permission prompt: lookups and writes inside the bot's//! working folder run without a card; writes outside it and shell commands show the person an-//! approval card ("Always this session" is honoured); tools from servers the bot doesn't have-//! are refused.+//! approval card ("Always this session" is honoured, in that one conversation only); tools+//! from servers the bot doesn't have are refused.use axum::{body::{to_bytes, Body},@@ -167,3 +167,80 @@ async fn without_a_folder_every_write_asks() {assert_eq!(ask.await.unwrap()["behavior"], "deny");assert!(!state.broker.is_pending(&id).await);}++/// Registers a running turn of `bot` in `thread` and opens its permission session.+async fn turn_in_thread(state: &AppState, bot: &kwnt::db::models::Kwant, turn_id: &str, thread: &str) -> String {+ state.turns.set_turn(kwnt::server::turns::ActiveTurn {+ turn_id: turn_id.into(),+ kwant_id: bot.id.clone(),+ context_id: bot.id.clone(),+ thread_id: Some(thread.into()),+ state: "running".into(),+ since: chrono::Utc::now(),+ });+ let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), ..Default::default() };+ mcp_runtime::prepare_turn_with_self(state, bot, Some(turn_id.into()), None, Some(scope)).await.unwrap().1+}++#[tokio::test]+async fn always_this_session_lasts_for_one_conversation() {+ let (app, state, _tmp) = setup().await;+ let bot = state.db.list_kwants(&SpaceId::default_space()).await.unwrap().remove(0);+ let mut events = state.event_sender.subscribe();+ let bash = |cmd: &str| json!({"command": cmd, "description": "Run it"});++ // Chat A: "Always this session" for Bash+ let a1 = turn_in_thread(&state, &bot, "turn-a1", "chat-a").await;+ let ask = tokio::spawn({+ let (app, token) = (app.clone(), a1.clone());+ async move { claude_asks(&app, &token, "Bash", json!({"command": "touch x", "description": "Run it"})).await }+ });+ let (id, _) = next_card(&mut events).await;+ post(&app, &format!("/api/approvals/{id}/resolve"), json!({"decision": "always_allow"})).await;+ assert_eq!(ask.await.unwrap()["behavior"], "allow");+ mcp_runtime::finish_turn(&state, &a1).await;+ state.turns.end_turn("turn-a1");++ // Chat A's next turn: no card+ let a2 = turn_in_thread(&state, &bot, "turn-a2", "chat-a").await;+ assert_eq!(claude_asks(&app, &a2, "Bash", bash("touch y")).await["behavior"], "allow");+ assert!(state.broker.pending_ids().await.is_empty(), "chat A remembers the answer");+ // Only that tool: Write outside the folder still asks in chat A+ let ask = tokio::spawn({+ let (app, token) = (app.clone(), a2.clone());+ async move { claude_asks(&app, &token, "Write", json!({"file_path": "/tmp/x.txt", "content": "x"})).await }+ });+ let (id, details) = next_card(&mut events).await;+ assert_eq!(details["tool"], "Write");+ post(&app, &format!("/api/approvals/{id}/resolve"), json!({"decision": "deny"})).await;+ assert_eq!(ask.await.unwrap()["behavior"], "deny");++ // Chat B with the same bot: asks again+ let b1 = turn_in_thread(&state, &bot, "turn-b1", "chat-b").await;+ let ask = tokio::spawn({+ let (app, token) = (app.clone(), b1.clone());+ async move { claude_asks(&app, &token, "Bash", json!({"command": "touch z", "description": "Run it"})).await }+ });+ let (id, details) = next_card(&mut events).await;+ assert_eq!(details["arguments"]["command"], "touch z");+ post(&app, &format!("/api/approvals/{id}/resolve"), json!({"decision": "deny"})).await;+ assert_eq!(ask.await.unwrap()["behavior"], "deny");++ // A turn kwnt isn't tracking is its own conversation+ let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), ..Default::default() };+ let (_, loose) = mcp_runtime::prepare_turn_with_self(&state, &bot, None, None, Some(scope)).await.unwrap();+ let ask = tokio::spawn({+ let (app, token) = (app.clone(), loose.clone());+ async move { claude_asks(&app, &token, "Bash", json!({"command": "touch w", "description": "Run it"})).await }+ });+ let (id, _) = next_card(&mut events).await;+ post(&app, &format!("/api/approvals/{id}/resolve"), json!({"decision": "deny"})).await;+ assert_eq!(ask.await.unwrap()["behavior"], "deny");++ // A restart (a fresh broker) forgets every answer+ assert!(!PermissionBroker::new().is_allowed_for_session(&bot.id, "chat-a", "Bash").await);+ assert!(state.broker.is_allowed_for_session(&bot.id, "chat-a", "Bash").await);+ for t in [a2, b1, loose] {+ mcp_runtime::finish_turn(&state, &t).await;+ }+}diff --git a/tests/mcp_gateway_test.rs b/tests/mcp_gateway_test.rsindex 18578de6..9c69b535 100644--- a/tests/mcp_gateway_test.rs+++ b/tests/mcp_gateway_test.rs@@ -181,6 +181,7 @@ async fn gateway_calls_wait_for_the_approval_card() {broker: state.broker.clone(),events: state.event_sender.clone(),timeout: Duration::from_secs(10),+ conversation: "conv-test".into(),});register(&state, "card-tok", approver).await;let mut events = state.event_sender.subscribe();@@ -237,6 +238,7 @@ async fn ending_the_turn_cancels_a_call_waiting_for_its_card() {broker: state.broker.clone(),events: state.event_sender.clone(),timeout: Duration::from_secs(300),+ conversation: "conv-test".into(),});let marker = format!("KWNT_TEST_MARK_{}", uuid::Uuid::new_v4().simple());let mut server = echo_server();diff --git a/tests/mcp_runtime_test.rs b/tests/mcp_runtime_test.rsindex 5f7c3411..e4e1f2e4 100644--- a/tests/mcp_runtime_test.rs+++ b/tests/mcp_runtime_test.rs@@ -105,6 +105,7 @@ fn approver(state: &AppState, timeout: Duration) -> Arc<BrokerApprover> {broker: state.broker.clone(),events: state.event_sender.clone(),timeout,+ conversation: "conv-test".into(),})}