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
Router: a routed reply names the message it answers (meta.routing.message_id)
Lin (kwant bot)0dab9a11e41e
diff --git a/docs/channel-routing.md b/docs/channel-routing.mdindex 5fbc889d..c6e1a354 100644--- a/docs/channel-routing.md+++ b/docs/channel-routing.md@@ -5,7 +5,10 @@ A message in a channel without an @mention goes to the member that fits it best.## Fit-Each pick has a `fit` from 0 to 1, saved on the reply as `meta.routing.fit`.+Each pick has a `fit` from 0 to 1, saved on the reply as `meta.routing.fit`. Every routed reply+also saves `meta.routing.message_id`, the person's message it answers (for an ask card, the+message the card was for; for a hand-back, the message handed on), so "Wrong bot?" corrects that+message and not just the latest one.| Fit | What happens ||---|---|diff --git a/src/server/rerouting.rs b/src/server/rerouting.rsindex c4795897..bec5009e 100644--- a/src/server/rerouting.rs+++ b/src/server/rerouting.rs@@ -204,7 +204,7 @@ pub async fn resolve_route(State(state): State<AppState>, headers: HeaderMap, Palearn(&state, &space, &c.user_message_id, &kwant.id, "ask").await;}let candidates = offered.len() + 1;- let mut routing = super::routes::routing_meta(&kwant, &reason, candidates, false, &[], "ask");+ let mut routing = super::routes::routing_meta(&kwant, &reason, candidates, false, &[], "ask", &c.user_message_id);routing["route_choice_id"] = json!(c.id);let (st, k, um, ch, prompt) = (state.clone(), kwant.clone(), c.user_message_id.clone(), c.channel_id.clone(), c.prompt.clone());tokio::spawn(async move {@@ -324,7 +324,7 @@ pub(super) async fn hand_back(state: &AppState, from_id: &str, channel_id: &str,Err(_) => return Err("Could not hand it back.".into()),}let why = format!("{} handed this back (\"{reason}\"), so {} ({}) takes it", from.name, to.name, to.title);- let mut routing = super::routes::routing_meta(&to, &why, members.len() + 1, false, &[], "handback");+ let mut routing = super::routes::routing_meta(&to, &why, members.len() + 1, false, &[], "handback", &msg.id);routing["fit"] = json!(fit);routing["handed_back_by"] = json!(from.id);let prompt = format!(diff --git a/src/server/routes.rs b/src/server/routes.rsindex d3cb0881..fb1ff9d7 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -3159,7 +3159,7 @@ async fn send_chat_inner(// The team router doesn't say which path it took; Laya being down means keywords didlet fallback = !state.router.status().is_up();let basis = if basis.is_empty() { "skills".to_string() } else { basis };- let routing = routing_meta(&target_kwant, &reason, members.len(), fallback, &matched_terms, &basis);+ let routing = routing_meta(&target_kwant, &reason, members.len(), fallback, &matched_terms, &basis, &saved_user_msg.id);let _ = state.event_sender.send(RuntimeEvent::RoutingDecided {context_id: routing_context_id,kwant_id: target_kwant.id.clone(),@@ -3284,7 +3284,7 @@ async fn send_chat_inner(} else if let Some((asker, _)) = awaiting.clone() {let reason = format!("{} asked you a question here, so your reply goes back to {}", asker.name, asker.name);let candidates = chat_teammates.len().max(1);- routing = Some(routing_meta(&asker, &reason, candidates, false, &[], "asked"));+ routing = Some(routing_meta(&asker, &reason, candidates, false, &[], "asked", &saved_user_msg.id));let _ = state.event_sender.send(RuntimeEvent::RoutingDecided {context_id: payload.channel_id.clone(),kwant_id: asker.id.clone(),@@ -3367,7 +3367,7 @@ async fn send_chat_inner(crate::router::team::Settle::Route => {}}if let Some(ref k) = chosen {- routing = Some(routing_meta(k, &route.reason, members.len(), route.fallback, &route.matched_terms, &route.basis));+ routing = Some(routing_meta(k, &route.reason, members.len(), route.fallback, &route.matched_terms, &route.basis, &saved_user_msg.id));if let Some(m) = routing.as_mut() {m["fit"] = json!(route.fit);if let Some(ids) = similar.take() {@@ -3447,9 +3447,12 @@ fn channel_members(channel: &crate::db::models::Channel, all_kwants: &[Kwant]) -}/// A reply's `meta.routing`: who Laya picked for a channel or team message and why.-pub(super) fn routing_meta(kwant: &Kwant, reason: &str, candidates: usize, fallback: bool, terms: &[String], basis: &str) -> serde_json::Value {+/// The `meta.routing` a routed reply carries. `message_id` is the person's message it answers,+/// so "Wrong bot?" corrects and resends that message, not just the latest one.+pub(super) fn routing_meta(kwant: &Kwant, reason: &str, candidates: usize, fallback: bool, terms: &[String], basis: &str, message_id: &str) -> serde_json::Value {json!({"basis": basis,+ "message_id": message_id,"kwant_id": kwant.id,"kwant_name": kwant.name,"reason": reason,diff --git a/tests/concierge_test.rs b/tests/concierge_test.rsindex d41501c2..62f08ded 100644--- a/tests/concierge_test.rs+++ b/tests/concierge_test.rs@@ -97,9 +97,32 @@ fn specialist(name: &str, title: &str, persona: &str) -> Value {}/// Sends `prompt` to the channel and returns who it was routed to and how, once the turn ended.+/// Also checks the reply names the message it answers (`meta.routing.message_id`), on every path+/// these tests route through (keywords, the Concierge, learned).async fn routed_to(app: &Router, state: &AppState, channel: &str, prompt: &str) -> (String, Option<String>) {let mut events = state.event_sender.subscribe();- ok(app, "POST", "/api/chat/send", Some(json!({"channel_id": channel, "prompt": prompt, "sender_id": "user"}))).await;+ let sent = ok(app, "POST", "/api/chat/send", Some(json!({"channel_id": channel, "prompt": prompt, "sender_id": "user"}))).await;+ let pick = wait_routed(&mut events).await;+ let routing = latest_routing(state, channel).await;+ let asked = sent["user_message_id"].as_str().expect("the message id");+ assert_eq!(asked, last_user_message(state, channel).await);+ assert_eq!((routing["message_id"].as_str(), routing["kwant_id"].as_str()), (Some(asked), Some(pick.0.as_str())), "{routing}");+ pick+}++/// The `meta.routing` of the newest routed reply in `channel`.+async fn latest_routing(state: &AppState, channel: &str) -> Value {+ let msgs = state.db.list_messages(channel, 50).await.unwrap();+ msgs.iter()+ .rev()+ .filter(|m| m.sender_role == "kwant")+ .filter_map(|m| m.meta.as_deref().and_then(|m| serde_json::from_str::<Value>(m).ok()))+ .map(|m| m["routing"].clone())+ .find(|r| !r.is_null())+ .expect("a routed reply")+}++async fn wait_routed(events: &mut tokio::sync::broadcast::Receiver<RuntimeEvent>) -> (String, Option<String>) {tokio::time::timeout(Duration::from_secs(20), async {let mut pick = None;loop {@@ -248,6 +271,7 @@ async fn a_close_call_asks_and_the_choice_answers() {assert!(ids.contains(&fe.as_str()) && ids.contains(&web.as_str()), "{v}");assert_eq!(v["general"]["name"], "Concierge");let choice = v["route_choice_id"].as_str().unwrap().to_string();+ let asked = v["user_message_id"].as_str().expect("the message id").to_string();let card = state.db.list_messages(&general, 50).await.unwrap().into_iter().find(|m| Some(m.id.as_str()) == v["card_message_id"].as_str()).expect("the card");let meta: Value = serde_json::from_str(card.meta.as_deref().unwrap_or("null")).unwrap();assert_eq!(meta["kind"], "route_choice");@@ -270,17 +294,25 @@ async fn a_close_call_asks_and_the_choice_answers() {assert_eq!((v["status"].as_str(), v["kwant_id"].as_str()), (Some("dispatched"), Some(made[0].as_str())));let routing = next_reply_routing(&state, &mut events, &general).await;assert_eq!(routing["basis"], "ask", "{routing}");+ assert_eq!(routing["message_id"], asked.as_str(), "the reply names the message the card was for");let (s, _) = call(&app, "POST", &uri, Some(json!({"kwant_id": fe}))).await;assert_eq!(s, StatusCode::CONFLICT, "a second tap does nothing");// A general answer teaches routing nothing, so a similar message asks again; the pick answerslet v = ok(&app, "POST", "/api/chat/send", Some(json!({"channel_id": general, "prompt": "Is the CSS grid off on the button?", "sender_id": "user"}))).await;assert_eq!(v["status"], "asking", "{v}");+ let asked = v["user_message_id"].as_str().expect("the message id").to_string();+ let second = v["route_choice_id"].as_str().unwrap().to_string();+ // A later message in the channel (asking too) doesn't become the one the tap answers+ let later = ok(&app, "POST", "/api/chat/send", Some(json!({"channel_id": general, "prompt": "Is the button CSS off on desktop Safari too?", "sender_id": "user"}))).await;+ assert_eq!(later["status"], "asking", "{later}");+ assert_ne!(later["user_message_id"], asked.as_str());let mut events = state.event_sender.subscribe();- let v = ok(&app, "POST", &format!("/api/route-choices/{}/resolve", v["route_choice_id"].as_str().unwrap()), Some(json!({"kwant_id": web}))).await;+ let v = ok(&app, "POST", &format!("/api/route-choices/{second}/resolve"), Some(json!({"kwant_id": web}))).await;assert_eq!((v["status"].as_str(), v["kwant_id"].as_str()), (Some("dispatched"), Some(web.as_str())));let routing = next_reply_routing(&state, &mut events, &general).await;assert_eq!((routing["basis"].as_str(), routing["kwant_id"].as_str()), (Some("ask"), Some(web.as_str())), "{routing}");+ assert_eq!(routing["message_id"], asked.as_str(), "the tapped card's message, not the newest one");assert_eq!(state.db.get_scope(&made[0]).await.unwrap().covers.len(), kwnt::server::concierge::COVERS.len());}@@ -295,6 +327,7 @@ async fn a_hand_back_takes_one_hop() {let general = state.db.general_channel(&SpaceId::default_space()).await.unwrap().expect("#general").id;let (to, _) = routed_to(&app, &state, &general, "Write a TikTok hook about the sitemap launch party").await;assert_eq!(to, script);+ let asked = last_user_message(&state, &general).await;let token = turn_token(&state, &script, &general).await;let (text, err) = hand_back(&app, &token, "").await;@@ -305,6 +338,7 @@ async fn a_hand_back_takes_one_hop() {assert!(text.contains("Atlas"), "{text}");let routing = next_reply_routing(&state, &mut events, &general).await;assert_eq!((routing["basis"].as_str(), routing["kwant_id"].as_str()), (Some("handback"), Some(atlas.as_str())), "{routing}");+ assert_eq!(routing["message_id"], asked.as_str());// One hop: Atlas can't bounce it onlet token = turn_token(&state, &atlas, &general).await;