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 bot picked from the message's words may hand it back (M2)
Lin (kwant bot)8c74571466b5
diff --git a/src/router/team.rs b/src/router/team.rsindex 5a97c68b..da6b6f2c 100644--- a/src/router/team.rs+++ b/src/router/team.rs@@ -644,6 +644,11 @@ pub fn alike(a: &[String], b: &[String]) -> bool {/// Share of words a message must have in common with a learned one to route like it.pub const LEARNED_AT: f32 = 0.6;+/// How a pick's reason ends when the person named the bot ("Atlas (Technical SEO) was named in+/// your message"): the person chose it, even though its basis is "keywords" or "skills".+pub const NAMED: &str = "was named in your message";+pub const AT_MENTIONED: &str = "was @mentioned in your message";+/// A message's words for comparing it with another: no filler, plurals folded, each once. Words/// under three letters ("a", "in", "is", "to") and [`NOT_CONTENT`] say nothing about what a message/// is for, so "Is it ok to deploy on a Friday?" and "Is it ok to freeze a cake?" share none.@@ -760,7 +765,7 @@ pub fn pick_member_hinted<'a>(crate::router::handoff_mentions(prompt, &member_names).targets.into_iter().map(|i| &members[i]).collect();match at_named.as_slice() {[] => {}- [k] => return Some(chosen(k, vec![k.name.trim().to_lowercase()], "was @mentioned in your message", 1.0)),+ [k] => return Some(chosen(k, vec![k.name.trim().to_lowercase()], AT_MENTIONED, 1.0)),several => {let terms = several.iter().map(|k| k.name.trim().to_lowercase()).collect();let reason = format!(@@ -775,7 +780,7 @@ pub fn pick_member_hinted<'a>(// Named without @ ("Bea, can you…")let named: Vec<&Kwant> = members.iter().filter(|m| words.iter().any(|w| *w == m.name.trim().to_lowercase())).collect();if let [k] = named.as_slice() {- return Some(chosen(k, vec![k.name.trim().to_lowercase()], "was named in your message", 1.0));+ return Some(chosen(k, vec![k.name.trim().to_lowercase()], NAMED, 1.0));}// 1b. A greeting, thank-you or go-ahead ("ok go ahead") carries on with the bot that spoke lastdiff --git a/src/server/rerouting.rs b/src/server/rerouting.rsindex 8f539a88..41176419 100644--- a/src/server/rerouting.rs+++ b/src/server/rerouting.rs@@ -27,6 +27,27 @@ use serde_json::{json, Value};pub const HAND_BACK: &str = "hand_back";+/// Bases where kwnt's router picked the bot from the message's words (see [`routed_note`]).+const PICKED_FROM_WORDS: [&str; 3] = ["keywords", "skills", "learned"];++/// The note added to a channel turn whose bot kwnt's router picked from the message's words, so+/// the bot knows the person didn't choose it and may hand the message back (once: see+/// [`hand_back`]). `None` for every other turn: the person @mentioned or named the bot, a team+/// channel, the lead or the Concierge taking what fits no one, a pick on a card, a hand-back.+pub(super) fn routed_note(routing: &Value, team_channel: bool) -> Option<String> {+ let basis = routing["basis"].as_str()?;+ let reason = routing["reason"].as_str().unwrap_or_default();+ let named = [crate::router::team::NAMED, crate::router::team::AT_MENTIONED].iter().any(|n| reason.contains(n));+ if team_channel || named || !PICKED_FROM_WORDS.contains(&basis) || routing["message_id"].as_str().is_none() {+ return None;+ }+ Some(format!(+ "(kwant routing note: kwnt picked you for this message from its words; the person didn't choose you. If it is \+ clearly not your area and another bot here would do it better, call {HAND_BACK} with a one-line reason instead \+ of answering. Otherwise answer it.)"+ ))+}+/// The space's covers/avoids lists for routing among `members`, and what the person taught it.pub(super) async fn hints_for(state: &AppState, space: &SpaceId, members: &[Kwant]) -> Hints {let ids: Vec<String> = members.iter().map(|k| k.id.clone()).collect();@@ -384,3 +405,50 @@ async fn next_after_handback(let lead = all.iter().find(|k| k.id == channel.lead_kwant_id && k.id != from.id && members.iter().any(|m| m.id == k.id));lead.cloned().map(|k| (k, 0.0))}++#[cfg(test)]+mod tests {+ use super::*;++ /// Only a channel turn the router picked from the message's words gets the note, and the+ /// person's message isn't repeated in the bot's history because of it.+ #[test]+ fn only_a_turn_picked_from_the_words_gets_the_routed_note() {+ let routing = |basis: &str, reason: &str| json!({"basis": basis, "reason": reason, "message_id": "m1"});+ for basis in PICKED_FROM_WORDS {+ let note = routed_note(&routing(basis, "Atlas (Technical SEO) matched: sitemap"), false).expect(basis);+ assert!(note.contains(HAND_BACK), "{note}");+ assert_eq!(routed_note(&routing(basis, "matched"), true), None, "a team channel");+ }+ for basis in ["several", "lead", "last", "team", "only", "concierge", "ask", "asked", "handback"] {+ assert_eq!(routed_note(&routing(basis, "matched"), false), None, "{basis}");+ }+ for named in [+ "Atlas (Technical SEO) was named in your message",+ "Atlas (Technical SEO) was @mentioned in your message; Laya picked the same bot",+ ] {+ assert_eq!(routed_note(&routing("keywords", named), false), None, "{named}");+ }+ assert_eq!(routed_note(&json!({"basis": "keywords", "reason": "matched"}), false), None, "no message to hand back");+ assert_eq!(routed_note(&Value::Null, false), None);++ let asked = "Fix the sitemap for the launch";+ let mut history = vec![crate::db::models::Message {+ id: "m1".into(),+ channel_id: Some("c".into()),+ direct_kwant_id: None,+ sender_role: "user".into(),+ sender_id: "user".into(),+ text: asked.into(),+ reasoning_content: None,+ tool_calls: None,+ tokens_used: 0,+ created_at: None,+ thread_id: None,+ meta: None,+ }];+ let note = routed_note(&routing("keywords", "matched"), false).unwrap();+ crate::drivers::drop_current_message(&mut history, &format!("{asked}\n\n{note}"));+ assert!(history.is_empty(), "the prompt carries the message once");+ }+}diff --git a/src/server/routes.rs b/src/server/routes.rsindex 65d131f5..f3254238 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -927,6 +927,9 @@ fn execute_single_turn(} else if let Some(ids) = routing.as_ref().and_then(|r| r["similar_requests"].as_array()) {let ids: Vec<&str> = ids.iter().filter_map(serde_json::Value::as_str).collect();format!("{prompt}\n\n{}", super::concierge::hire_note(&ids))+ } else if let Some(note) = routing.as_ref().and_then(|r| super::rerouting::routed_note(r, scope.team_keys.is_some())) {+ // the router picked this bot from the message's words: it may hand it back once+ format!("{prompt}\n\n{note}")} else {prompt.clone()};diff --git a/tests/concierge_test.rs b/tests/concierge_test.rsindex a51496bb..72795aaf 100644--- a/tests/concierge_test.rs+++ b/tests/concierge_test.rs@@ -396,6 +396,51 @@ async fn a_hand_back_passes_on_the_message_it_answers_not_the_newest() {assert!(err && text.contains("already handed back"), "{text}");}+/// A turn the router picked from the message's words is told the person didn't choose the bot and+/// that it may hand the message back. An @mention, the Concierge and the hand-back turn aren't (QA+/// on 0.6.4: without being told, the live model handed back 0 of 3 off-topic messages).+#[tokio::test]+async fn only_a_routed_turn_is_told_it_may_hand_back() {+ let (app, state, _tmp) = setup().await;+ let script = ok(&app, "POST", "/api/kwants", Some(specialist("Scriptwriter", "TikTok Scriptwriter", "Scripts and hooks for book videos."))).await["id"].as_str().unwrap().to_string();+ let atlas = ok(&app, "POST", "/api/kwants", Some(specialist("Atlas", "Technical SEO", "Crawl errors and sitemaps."))).await["id"].as_str().unwrap().to_string();+ only(&app, &state, &[&script, &atlas]).await;+ let general = state.db.general_channel(&SpaceId::default_space()).await.unwrap().expect("#general").id;+ let note = "(kwant routing note: kwnt picked you";+ let log = || std::fs::read_to_string(fake_cli().join("prompts.log")).unwrap_or_default();++ let routed = "Write a TikTok hook about the lantern parade";+ let (to, basis) = routed_to(&app, &state, &general, routed).await;+ assert_eq!((to.as_str(), basis.as_deref()), (script.as_str(), Some("keywords")));+ assert!(log().contains(&format!("{routed}\n\n{note}")), "the routed turn is told");+ let asked = last_user_message(&state, &general).await;++ let named = "@Atlas check the lantern parade page";+ let mut events = state.event_sender.subscribe();+ ok(&app, "POST", "/api/chat/send", Some(json!({"channel_id": general, "prompt": named, "sender_id": "user"}))).await;+ assert!(next_reply_routing(&state, &mut events, &general).await.is_null(), "an @mention isn't routed");+ let (to, basis) = routed_to(&app, &state, &general, "Best place to watch the lantern parade in Munich tomorrow?").await;+ assert_eq!((to.as_str(), basis.as_deref()), (concierges(&state).await[0].as_str(), Some("concierge")));+ let prompts = log();+ assert!(prompts.contains(named) && prompts.contains("Best place to watch the lantern parade in Munich tomorrow?"), "both turns ran");+ assert!(!prompts.contains(&format!("{named}\n\n(kwant routing note")), "an @mention isn't told");+ assert!(!prompts.contains("Munich tomorrow?\n\n(kwant routing note"), "the Concierge isn't told");++ // The turn it is handed back to isn't told, and can't hand it on again+ let token = answering_token(&state, &script, &general, Some(&asked)).await;+ let mut events = state.event_sender.subscribe();+ let (text, err) = hand_back(&app, &token, "Lantern parades are not book scripts").await;+ assert!(!err, "{text}");+ let routing = next_reply_routing(&state, &mut events, &general).await;+ assert_eq!(routing["basis"], "handback", "{routing}");+ let prompts = log();+ assert!(prompts.contains("not their area: Lantern parades are not book scripts. Answer it.)"), "the hand-back turn ran");+ assert!(!prompts.contains("not their area: Lantern parades are not book scripts. Answer it.)\n\n(kwant routing note"));+ let token = answering_token(&state, routing["kwant_id"].as_str().unwrap(), &general, Some(&asked)).await;+ let (text, err) = hand_back(&app, &token, "Not mine either").await;+ assert!(err && text.contains("already handed back"), "{text}");+}+/// A TikTok link in the person's message names an account, not a teammate: "@munichspots" in it/// made the send fail with 400, as an @mention of a bot that isn't here.#[tokio::test]