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: fit score, no Laya-only picks, Concierge for #general
Lin (kwant bot)e1d33f74cefb
diff --git a/docs/bot-actions.md b/docs/bot-actions.mdindex dba67c7d..05088dea 100644--- a/docs/bot-actions.md+++ b/docs/bot-actions.md@@ -17,6 +17,7 @@ to the turn's bot and its space. Code: `src/server/bot_actions.rs`, `src/db/bot_| `follow_up_create` | `at` (RFC 3339 with offset), `check`, `name?` | A one-off check-in by the calling bot in this chat or thread. Applied as `routine_create`, so undo deletes it || `bot_list` | – | Bots, models, accounts, installed tool servers || `bot_create` | `name`, `title`, `instructions`, `soul?`, `model?`, `profile_id?`, `avatar?` | Applied, undo deletes it if it has no history yet |+| `concierge_create` | (made by the app, not a tool) | Applied when #general gets its first message no specialist fits; the card is from the Concierge. Undo deletes it with its history, and it is never made again unasked. Not counted against `AUTO_HIRES_PER_DAY` || `bot_update` | `bot`, `name?`, `title?`, `instructions?`, `soul?`, `model?`, `profile_id?`, `avatar?`, `mcp_servers?` | Applied, undo restores fields, account and tool servers || `bot_delete` | `bot`, `reason?` | **Pending** until the person confirms; only bots with no history || `settings_get` | – | `timezone`, `location`, `max_turns_per_agent`, `max_turns_global`, `delegation_follow_up_minutes`, `notify_on` |diff --git a/src/router/sticky.rs b/src/router/sticky.rsindex 446bcd12..f2743eb5 100644--- a/src/router/sticky.rs+++ b/src/router/sticky.rs@@ -74,7 +74,10 @@ pub fn awaiting_answer<'a>(recent: &[Message], open: &[Question], members: &'a [/// on a clear match (a role's words, a bot's name, or Laya's confident pick). A greeting, a/// small reply or no match ("lead", "last", "several") stays with the bot that asked.pub fn yields_to_route(awaiting: &Awaiting<'_>, route: &crate::router::team::ChannelRoute) -> bool {- !awaiting.card && route.kwant_id != awaiting.kwant.id && matches!(route.basis.as_str(), "skills" | "keywords")+ !awaiting.card+ && route.kwant_id != awaiting.kwant.id+ && matches!(route.basis.as_str(), "skills" | "keywords")+ && route.fit >= crate::router::team::ROUTE_AT}/// Whether the last line of `text` asks the person something real: a question on it that isn't@@ -319,6 +322,8 @@ mod tests {fallback: false,matched_terms: vec![],basis: basis.into(),+ fit: 1.0,+ choices: vec![],}}diff --git a/src/router/team.rs b/src/router/team.rsindex 6bc4619e..bf4f0d53 100644--- a/src/router/team.rs+++ b/src/router/team.rs@@ -168,6 +168,8 @@ impl LayaRouter {fallback,matched_terms: p.terms,basis: p.basis.into(),+ fit: p.fit,+ choices: p.choices.iter().map(|k| k.id.clone()).collect(),},None => ChannelRoute {kwant_id: lead_kwant_id.to_string(),@@ -175,6 +177,8 @@ impl LayaRouter {fallback,matched_terms: Vec::new(),basis: "lead".into(),+ fit: 0.0,+ choices: Vec::new(),},};// Every pick Laya didn't make is logged with why, so the fallback rate can be read from the log@@ -346,8 +350,20 @@ pub struct Pick<'a> {pub basis: &'static str,pub reason: String,pub terms: Vec<String>,+ /// How well the message fits this pick, 0 to 1: word evidence (role signals, words in the+ /// bot's name, title or persona), with Laya's agreement only as a nudge. A pick with no word+ /// evidence is 0, whatever Laya guessed. See [`ROUTE_AT`] and [`ASK_FROM`].+ pub fit: f32,+ /// The best candidates when the pick is close: the picked bot first, then the runner-up.+ pub choices: Vec<&'a Kwant>,}+/// A channel message goes straight to the picked bot only at or above this fit.+pub const ROUTE_AT: f32 = 0.6;+/// From this fit up to [`ROUTE_AT`] the person is asked to choose between the best two bots (or a+/// general answer). Below it nothing in the message points at anyone.+pub const ASK_FROM: f32 = 0.4;+/// Roles and the words in a request that belong to them. A bot has a role when its title/// (or, without a title, the first line of its persona) names it; Laya only compares titles, so it/// can't tell that "strategy" in a trading repo is backend code, and picked Frontend for it.@@ -515,9 +531,21 @@ fn role_score(words: &[String], kwant: &Kwant) -> (usize, Vec<String>) {}}}+ // A role word in the bot's own name or title counts for it too: "tiktok" is on marketing's+ // list, but the "TikTok Scriptwriter" has it in its title+ for w in words {+ if !terms.contains(w) && in_own_title(kwant, w) && ROLES.iter().any(|r| r.signals.iter().any(|(s, _)| s == w)) {+ score += 2;+ terms.push(w.clone());+ }+ }(score, terms)}+fn in_own_title(kwant: &Kwant, w: &str) -> bool {+ tokens(&format!("{} {}", kwant.name, kwant.title)).iter().any(|t| t == w)+}+fn lead_of<'a>(lead_kwant_id: &str, members: &'a [Kwant]) -> &'a Kwant {members.iter().find(|m| m.id == lead_kwant_id).unwrap_or(&members[0])}@@ -563,7 +591,7 @@ pub fn pick_member_after<'a>(_ => None,};if let Some(k) = only {- return Some(Pick { kwant: k, basis: "only", reason: format!("{} is the only bot here that can answer", k.name), terms: vec![] });+ return Some(Pick { kwant: k, basis: "only", reason: format!("{} is the only bot here that can answer", k.name), terms: vec![], fit: 1.0, choices: vec![] });}let words = tokens(prompt);let lead = lead_of(lead_kwant_id, members);@@ -574,9 +602,10 @@ pub fn pick_member_after<'a>(lead.name,lead.title);- Pick { kwant: lead, basis: "several", reason, terms }+ Pick { kwant: lead, basis: "several", reason, terms, fit: 0.7, choices: vec![] }};- let chosen = |k: &'a Kwant, terms: Vec<String>, how: &str| {+ let laya_nudge = |k: &Kwant, base: f32| if base > 0.0 && laya.is_some_and(|g| g.kwant.id == k.id) { 0.1 } else { 0.0 };+ let chosen = |k: &'a Kwant, terms: Vec<String>, how: &str, base: f32| {let agree = laya.is_some_and(|g| g.kwant.id == k.id);let mut reason = format!("{} ({}) {how}", k.name, k.title);if agree {@@ -584,7 +613,8 @@ pub fn pick_member_after<'a>(} else if let Some(g) = laya {reason.push_str(&format!("; Laya guessed {} from titles alone, but nothing in the message points to that role", g.kwant.name));}- Pick { kwant: k, basis: if agree { "skills" } else { "keywords" }, reason, terms }+ let fit = (base + laya_nudge(k, base)).min(1.0);+ Pick { kwant: k, basis: if agree { "skills" } else { "keywords" }, reason, terms, fit, choices: vec![] }};// 1. @Named in the message: one @Name wins over plain names ("@Frontend why didn't you answer@@ -594,7 +624,7 @@ pub fn pick_member_after<'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")),+ [k] => return Some(chosen(k, vec![k.name.trim().to_lowercase()], "was @mentioned in your message", 1.0)),several => {let terms = several.iter().map(|k| k.name.trim().to_lowercase()).collect();let reason = format!(@@ -603,13 +633,13 @@ pub fn pick_member_after<'a>(lead.name,lead.title);- return Some(Pick { kwant: lead, basis: "several", reason, terms });+ return Some(Pick { kwant: lead, basis: "several", reason, terms, fit: 1.0, choices: vec![] });}}// 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"));+ return Some(chosen(k, vec![k.name.trim().to_lowercase()], "was named in your message", 1.0));}// 2. A request to put a team of bots together is no one specialist's work: the lead proposes@@ -619,7 +649,7 @@ pub fn pick_member_after<'a>("This asks to put a team of bots together, so it went to the {lead_word}, {} ({}), to propose them on one hire card for you to approve",lead.name, lead.title);- return Some(Pick { kwant: lead, basis: "team", reason, terms: vec![] });+ return Some(Pick { kwant: lead, basis: "team", reason, terms: vec![], fit: 1.0, choices: vec![] });}// 3. The request's words belong to a role@@ -632,6 +662,16 @@ pub fn pick_member_after<'a>(terms.dedup();terms.len()};+ // A word that reaches one bot through its own title and others only through their role's list+ // is that bot's+ let owners: Vec<&&(&Kwant, usize, Vec<String>)> = strong.iter().filter(|(m, _, t)| t.iter().any(|w| in_own_title(m, w))).collect();+ if let [owner] = owners.as_slice() {+ let (k, s, terms) = **owner;+ if strong.iter().all(|(_, _, t)| t.iter().all(|w| terms.contains(w))) {+ let how = format!("does this kind of work: your message mentions {}", terms.join(", "));+ return Some(chosen(k, terms.clone(), &how, (0.5 + 0.1 * *s as f32).min(1.0)));+ }+ }if !strong.is_empty() {let top = strong.iter().map(|(_, s, _)| *s).max().unwrap_or(0);let best: Vec<&&(&Kwant, usize, Vec<String>)> = strong.iter().filter(|(_, s, _)| *s == top).collect();@@ -639,6 +679,7 @@ pub fn pick_member_after<'a>(// is a tie the lead settles.if distinct_roles(&strong) > 1 || best.len() > 1 {let matched: Vec<&Kwant> = strong.iter().map(|(m, _, _)| *m).collect();+ let same_role_tie = distinct_roles(&strong) == 1;let mut terms: Vec<String> = Vec::new();for (_, _, t) in &strong {for w in t {@@ -647,11 +688,17 @@ pub fn pick_member_after<'a>(}}}- return Some(to_lead(matched, terms));+ let mut p = to_lead(matched.clone(), terms);+ if same_role_tie {+ // Two bots with the same role: a close call between them, not multi-role work+ p.fit = 0.5;+ p.choices = matched.into_iter().take(2).collect();+ }+ return Some(p);}- let (k, _, terms) = best[0];+ let (k, s, terms) = best[0];let how = format!("does this kind of work: your message mentions {}", terms.join(", "));- return Some(chosen(k, terms.clone(), &how));+ return Some(chosen(k, terms.clone(), &how, (0.5 + 0.1 * *s as f32).min(1.0)));}// 4. Shared words with a bot's name, title or persona (plus weak role hints). A word several@@ -691,27 +738,40 @@ pub fn pick_member_after<'a>("Laya matched this to {}'s role ({}); the only words in your message that pointed elsewhere were in {}'s description",g.kwant.name, g.kwant.title, scored[*i].0.name);- return Some(Pick { kwant: g.kwant, basis: "skills", reason, terms: vec![] });+ // Laya's titles-only guess against words only in a description: neither is evidence+ // enough on its own, so it's a close call between the two+ return Some(Pick { kwant: g.kwant, basis: "skills", reason, terms: vec![], fit: 0.5, choices: vec![g.kwant, scored[*i].0] });}}if let [i] = best.as_slice() {- let (k, _, terms, _) = &scored[*i];+ let (k, s, terms, named) = &scored[*i];let how = format!("shares words with your message: {}", terms.join(", "));- return Some(chosen(k, terms.clone(), &how));+ // One word only in a description is a hint (0.5); a word in the name or title, or two+ // description words, is enough to route+ let base = (0.4 + 0.1 * *s as f32 + if *named { 0.1 } else { 0.0 }).min(0.95);+ let mut p = chosen(k, terms.clone(), &how, base);+ let runner_up = (0..scored.len())+ .filter(|&j| j != *i && scored[j].1 > 0)+ .max_by_key(|&j| scored[j].1)+ .map(|j| scored[j].0);+ p.choices = std::iter::once(*k).chain(runner_up).collect();+ return Some(p);}+ let tied: Vec<&'a Kwant> = best.iter().map(|&i| scored[i].0).take(2).collect();- // 5. Nothing in the message matched: Laya's pick only when it was clear and there was something- // to match, else the bot that spoke last, else the lead- if let Some(g) = laya.filter(|g| g.confident && !is_small_talk(prompt)) {- let reason = format!("Laya matched this to {}'s role ({}); no words in your message named a role", g.kwant.name, g.kwant.title);- return Some(Pick { kwant: g.kwant, basis: "skills", reason, terms: vec![] });- }+ // 5. Nothing in the message matched (or two bots tied on words): the bot that spoke last, else+ // the lead, with no fit. Laya alone never picks: it sees only titles, and its confident guess+ // sent "Best place to eat corn dogs in Munich tomorrow?" to a TikTok scriptwriter. A tie is a+ // close call between the tied bots.+ let (fit, choices) = if tied.len() > 1 { (0.45, tied) } else { (0.0, vec![]) };if let Some(k) = last_speaker.and_then(|id| members.iter().find(|m| m.id == id)) {+ // "thanks", "make it shorter", "and for Berlin?" carry on with whoever is talking+ let fit = if choices.is_empty() && (is_small_talk(prompt) || reads_as_follow_up(prompt)) { ROUTE_AT } else { fit };let reason = format!("Nothing in your message named a role, so {} ({}), who spoke last here, carries on", k.name, k.title);- return Some(Pick { kwant: k, basis: "last", reason, terms: vec![] });+ return Some(Pick { kwant: k, basis: "last", reason, terms: vec![], fit, choices });}let reason = format!("No one's role matched this, so it went to the {lead_word}, {} ({})", lead.name, lead.title);- Some(Pick { kwant: lead, basis: "lead", reason, terms: vec![] })+ Some(Pick { kwant: lead, basis: "lead", reason, terms: vec![], fit, choices })}/// Everyday words that say nothing about whose work a request is. They never count as shared@@ -742,6 +802,41 @@ pub fn is_small_talk(prompt: &str) -> bool {&& words.iter().all(|w| SMALL_TALK.contains(&w.as_str()) || STOP_WORDS.contains(&w.as_str()))}+/// A short reply or one that leans on what was just said ("make it shorter", "and Berlin?", "what+/// about tomorrow"): it belongs to the bot that spoke last, even with nothing in it to match.+pub fn reads_as_follow_up(prompt: &str) -> bool {+ const STARTS: &[&str] = &[+ "and", "also", "then", "now", "so", "but", "ok", "okay", "it", "that", "this", "those", "these", "again",+ "another", "more", "same", "make", "shorter", "longer", "what about", "how about", "why", "can you make",+ ];+ let lower = prompt.trim().to_lowercase();+ let words: Vec<&str> = lower.split(|c: char| !c.is_alphanumeric() && c != '\'').filter(|w| !w.is_empty()).collect();+ if words.is_empty() {+ return false;+ }+ let joined = words.join(" ");+ words.len() <= 3 || STARTS.iter().any(|s| joined == *s || joined.starts_with(&format!("{s} ")))+}++/// What the channel does with a pick, given its fit and the room it was made in.+#[derive(Debug, Clone, PartialEq)]+pub enum Settle {+ /// Send it to the picked bot.+ Route,+ /// Nothing in the message points at anyone here: the Concierge answers.+ Concierge,+}++/// #general (every bot in the space) leans to the Concierge: a low score or a close call goes to it+/// rather than to whichever specialist happened to lead or speak last. Any other channel leans to+/// its own members, so a low score stays with the last speaker or lead as before.+pub fn settle(route: &ChannelRoute, general: bool, has_concierge: bool) -> Settle {+ if route.fit >= ROUTE_AT || !general || !has_concierge {+ return Settle::Route;+ }+ Settle::Concierge+}+/// Said to the lead with a team-building request, so it proposes the bots instead of treating the/// message as its own specialty.pub const TEAM_BUILDING_NOTE: &str = "(kwant routing note: this message asks to put a team of bots together, \@@ -1011,6 +1106,10 @@ pub struct ChannelRoute {pub matched_terms: Vec<String>,/// How the pick was made: see [`Pick::basis`].pub basis: String,+ /// See [`Pick::fit`].+ pub fit: f32,+ /// See [`Pick::choices`]: bot ids, best first.+ pub choices: Vec<String>,}fn calculate_kwant_relevance(prompt: &str, kwant: &Kwant) -> usize {@@ -1274,9 +1373,13 @@ mod tests {// A last speaker who isn't a member here doesn't countlet p = pick_member_after("hello there", "kwant-1", &members, None, "lead", Some("stranger")).unwrap();assert_eq!(p.kwant.id, "kwant-1", "{p:?}");- // Real work still goes to Laya's clear pick+ // Laya's clear pick alone no longer routes real work: nothing in the message named a role,+ // so it has no fit (the channel hands it to the Concierge in #general)let p = pick_member_after("Can you look into why the build broke?", "kwant-1", &members, guess, "lead", Some("kwant-3")).unwrap();- assert_eq!(p.kwant.id, "kwant-2", "{p:?}");+ assert_eq!((p.kwant.id.as_str(), p.basis, p.fit), ("kwant-3", "last", 0.0), "{p:?}");+ // A follow-up stays with the last speaker+ let p = pick_member_after("make it shorter", "kwant-1", &members, guess, "lead", Some("kwant-3")).unwrap();+ assert_eq!((p.kwant.id.as_str(), p.fit), ("kwant-3", ROUTE_AT), "{p:?}");assert!(is_small_talk("Hi") && is_small_talk("thanks, ok!") && !is_small_talk("hi, deploy the app"));assert!(!is_small_talk(""));}@@ -1316,7 +1419,7 @@ mod tests {#[test]fn a_low_confidence_guess_is_named_as_the_fallback_reason() {let (_, members) = make_test_fixture();- let route = |id: &str| ChannelRoute { kwant_id: id.into(), reason: String::new(), fallback: false, matched_terms: vec![], basis: "lead".into() };+ let route = |id: &str| ChannelRoute { kwant_id: id.into(), reason: String::new(), fallback: false, matched_terms: vec![], basis: "lead".into(), fit: 0.0, choices: vec![] };let unsure = Some(LayaGuess { kwant: &members[1], confident: false });assert_eq!(fallback_reason(unsure, &route("kwant-1")), Some("low confidence"));assert_eq!(fallback_reason(unsure, &route("kwant-2")), None);@@ -1325,3 +1428,103 @@ mod tests {assert_eq!(fallback_reason(None, &route("kwant-1")), None);}}++#[cfg(test)]+mod fit_tests {+ use super::*;++ fn bot(id: &str, name: &str, title: &str, persona: &str) -> Kwant {+ Kwant {+ id: id.into(),+ name: name.into(),+ title: title.into(),+ persona_prompt: persona.into(),+ soul: String::new(),+ avatar_sprite: String::new(),+ driver_type: "claude".into(),+ preferred_model: String::new(),+ temperature: 0.7,+ max_tokens: 4096,+ level: 1,+ turns_completed: 0,+ created_at: None,+ space_id: crate::db::spaces::DEFAULT_SPACE_ID.into(),+ }+ }++ fn general() -> Vec<Kwant> {+ vec![+ bot("k-lead", "Luna", "Booktun.ing Chief", "You coordinate the booktun.ing marketing team."),+ bot("k-script", "Scriptwriter", "TikTok Scriptwriter & Hook Specialist", "You write short TikTok video scripts and scroll-stopping hooks for book content."),+ bot("k-seo", "Atlas", "Technical SEO", "You audit sites for crawl errors, sitemaps and page speed."),+ ]+ }++ fn route_of(p: &Pick<'_>) -> ChannelRoute {+ ChannelRoute {+ kwant_id: p.kwant.id.clone(),+ reason: p.reason.clone(),+ fallback: false,+ matched_terms: p.terms.clone(),+ basis: p.basis.into(),+ fit: p.fit,+ choices: p.choices.iter().map(|k| k.id.clone()).collect(),+ }+ }++ /// Oleks 2026-11-01: in #general "Best place to eat corn dogs in Munich tomorrow?" went to the+ /// TikTok scriptwriter on Laya's confident titles-only guess. No word in it fits anyone, so it+ /// has no fit and #general hands it to the Concierge.+ #[test]+ fn corn_dogs_in_munich_go_to_the_concierge() {+ let members = general();+ let laya = Some(LayaGuess { kwant: &members[1], confident: true });+ let prompt = "Best place to eat corn dogs in Munich tomorrow?";+ for last in [None, Some("k-script"), Some("k-seo")] {+ let p = pick_member_after(prompt, "k-lead", &members, laya, "channel lead", last).unwrap();+ assert_eq!(p.fit, 0.0, "{p:?}");+ assert_ne!(p.basis, "skills", "{p:?}");+ assert_eq!(settle(&route_of(&p), true, true), Settle::Concierge);+ // Without a Concierge (the person removed it), or outside #general, today's behaviour+ assert_eq!(settle(&route_of(&p), true, false), Settle::Route);+ assert_eq!(settle(&route_of(&p), false, true), Settle::Route);+ }+ }++ #[test]+ fn a_clear_specialist_request_still_routes_straight_to_it() {+ let members = general();+ for laya in [None, Some(LayaGuess { kwant: &members[1], confident: true })] {+ let p = pick_member_after("Write a TikTok hook for this fantasy book", "k-lead", &members, laya, "channel lead", Some("k-seo")).unwrap();+ assert_eq!(p.kwant.id, "k-script", "{p:?}");+ assert!(p.fit >= ROUTE_AT, "{p:?}");+ assert_eq!(settle(&route_of(&p), true, true), Settle::Route);+ }+ let p = pick_member_after("Why is the sitemap missing pages?", "k-lead", &members, None, "channel lead", None).unwrap();+ assert_eq!(p.kwant.id, "k-seo", "{p:?}");+ assert!(p.fit >= ROUTE_AT, "{p:?}");+ }++ #[test]+ fn laya_only_nudges_a_pick_with_word_evidence() {+ let members = general();+ // One description-only word is a hint below the bar; Laya agreeing tips it over+ let prompt = "any thoughts on scroll-stopping openers?";+ let alone = pick_member_after(prompt, "k-lead", &members, None, "channel lead", None).unwrap();+ let agreed = pick_member_after(prompt, "k-lead", &members, Some(LayaGuess { kwant: &members[1], confident: true }), "channel lead", None).unwrap();+ assert_eq!(alone.kwant.id, "k-script", "{alone:?}");+ assert!(alone.fit < ROUTE_AT && alone.fit >= ASK_FROM, "{alone:?}");+ assert!(agreed.fit > alone.fit, "{agreed:?}");+ }++ #[test]+ fn follow_ups_and_greetings_stay_with_the_last_speaker() {+ let members = general();+ for prompt in ["thanks!", "make it shorter", "and for Berlin?", "what about the second one"] {+ let p = pick_member_after(prompt, "k-lead", &members, None, "channel lead", Some("k-script")).unwrap();+ assert_eq!((p.kwant.id.as_str(), p.basis), ("k-script", "last"), "{prompt}: {p:?}");+ assert_eq!(settle(&route_of(&p), true, true), Settle::Route, "{prompt}");+ }+ assert!(!reads_as_follow_up("Best place to eat corn dogs in Munich tomorrow?"));+ }+}diff --git a/src/server/bot_actions.rs b/src/server/bot_actions.rsindex 2c1b834f..cb24d681 100644--- a/src/server/bot_actions.rs+++ b/src/server/bot_actions.rs@@ -1110,6 +1110,38 @@ pub(super) async fn create_bot(state: &AppState, space: &SpaceId, spec: &Value)}}+/// Records an applied change the app made on its own (not in a bot's turn) with its card in the+/// action's channel, sent as `sender`.+pub(super) async fn record_with_card(state: &AppState, new: &NewBotAction, sender: &str) -> Result<BotAction, String> {+ let (a, card) = state+ .db+ .record_bot_action(new, |a| {+ Some((+ NewMessage {+ channel_id: a.channel_id.clone(),+ direct_kwant_id: a.direct_kwant_id.clone(),+ sender_role: "kwant".into(),+ sender_id: sender.to_string(),+ text: card_text(a),+ reasoning_content: None,+ tool_calls: None,+ tokens_used: 0,+ },+ MessageExtra { thread_id: None, meta: Some(card_meta(a)) },+ ))+ })+ .await+ .map_err(|e| {+ tracing::warn!(error = %e, action = %new.action, "could not record a bot action");+ "the change could not be logged".to_string()+ })?;+ if let Some(card) = card {+ let _ = state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&card).unwrap_or(Value::Null) });+ }+ let _ = state.event_sender.send(RuntimeEvent::BotActionUpdated { action: action_json(&a) });+ Ok(a)+}+/// Records an applied change that already shows on another card (a hire), without a card of its/// own; Undo goes through `POST /api/bot-actions/:id/undo` as usual.pub(super) async fn record_quiet(state: &AppState, new: &NewBotAction) -> Result<BotAction, String> {@@ -1837,6 +1869,9 @@ async fn undo_action(state: &AppState, a: &BotAction) -> Result<Option<String>,return Ok(id);}"bot_create" => delete_unused_bot(state, &target).await?,+ // The Concierge may have answered by now, so it goes the way the person deletes a bot; the+ // `concierge:<space>` setting stays, so it isn't made again unasked+ "concierge_create" => ok_or_conflict(super::routes::remove_bot(state, &target).await, "the Concierge can't be removed").await.map(|_| ())?,"bot_hire" => {let after = a.after_json();let ids: Vec<String> = serde_json::from_value(after["hired_kwant_ids"].clone()).unwrap_or_default();diff --git a/src/server/concierge.rs b/src/server/concierge.rsnew file mode 100644index 00000000..61a72797--- /dev/null+++ b/src/server/concierge.rs@@ -0,0 +1,112 @@+//! The Concierge: a generalist bot that answers in #general when no specialist fits the message.+//!+//! It is made on the first message nothing fits (with a card the person can undo), never counts+//! against the daily cap on bots made without a card, and is never picked by role scoring. Its id+//! is kept in the `concierge:<space>` setting: set and present is the Concierge; set but gone means+//! the person removed it, so #general goes back to the lead and it is never made again unasked.++use serde_json::json;++use super::AppState;+use crate::db::bot_actions::NewBotAction;+use crate::db::models::Kwant;+use crate::db::spaces::SpaceId;++pub const NAME: &str = "Concierge";+pub const TITLE: &str = "Generalist for everyday questions";+pub const INSTRUCTIONS: &str = "You answer the questions in #general that none of the specialist bots in this space \+ are for: everyday questions, recommendations, quick facts, planning and anything general. Answer directly and \+ briefly. When a question clearly belongs to a specialist here, say who in one line and answer what you can.";+pub const SOUL: &str = "Warm, quick and plain-spoken. You'd rather give a useful short answer than a long hedge.";++fn key(space: &SpaceId) -> String {+ format!("concierge:{}", space.as_str())+}++/// Serialises making the Concierge, so two messages at once don't make two.+static MAKING: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());++/// Where the space stands with its Concierge.+#[derive(Debug, Clone)]+pub enum State {+ /// Never made: the first message nothing fits makes it.+ None,+ Present(Box<Kwant>),+ /// The person removed it: never made again unasked.+ Removed,+}++pub async fn state(app: &AppState, space: &SpaceId, all_kwants: &[Kwant]) -> State {+ match app.db.get_setting(&key(space)).await.ok().flatten() {+ Some(id) => match all_kwants.iter().find(|k| k.id == id) {+ Some(k) => State::Present(Box::new(k.clone())),+ None => State::Removed,+ },+ None => State::None,+ }+}++/// The Concierge's id, if the space has one now: role scoring leaves it out.+pub async fn id(app: &AppState, space: &SpaceId, all_kwants: &[Kwant]) -> Option<String> {+ match state(app, space, all_kwants).await {+ State::Present(k) => Some(k.id),+ _ => None,+ }+}++/// The Concierge for a #general message nothing fits: the existing one, else a new one made now+/// with a card in `channel_id` the person can undo. `None` when the person removed it (or it+/// couldn't be made): the message stays with today's pick.+pub async fn for_no_match(app: &AppState, space: &SpaceId, channel_id: &str, all_kwants: &[Kwant]) -> Option<Kwant> {+ let _making = MAKING.lock().await;+ let fresh = app.db.list_kwants(space).await.unwrap_or_else(|_| all_kwants.to_vec());+ match state(app, space, &fresh).await {+ State::Present(k) => return Some(*k),+ State::Removed => return None,+ State::None => {}+ }+ // A bot the person already named Concierge is adopted rather than doubled+ if let Some(k) = fresh.iter().find(|k| k.name.trim().eq_ignore_ascii_case(NAME)) {+ let _ = app.db.set_setting(&key(space), &k.id).await;+ return Some(k.clone());+ }+ let spec = json!({+ "name": NAME,+ "title": TITLE,+ "instructions": INSTRUCTIONS,+ "soul": SOUL,+ "avatar": "default",+ "model": "auto",+ });+ let view = match super::bot_actions::create_bot(app, space, &spec).await {+ Ok(v) => v,+ Err(e) => {+ tracing::warn!(error = %e, space = %space.as_str(), "could not make the Concierge");+ return None;+ }+ };+ let id = view["id"].as_str().unwrap_or_default().to_string();+ if id.is_empty() {+ return None;+ }+ let _ = app.db.set_setting(&key(space), &id).await;+ let new = NewBotAction {+ space_id: space.as_str().to_string(),+ kwant_id: id.clone(),+ turn_id: None,+ channel_id: Some(channel_id.to_string()),+ direct_kwant_id: None,+ thread_id: None,+ // Not "bot_create": the daily cap on bots made without a card doesn't count it+ action: "concierge_create".into(),+ target_kind: "bot".into(),+ target_id: Some(id.clone()),+ summary: format!("added {NAME}, a generalist that answers in #general when no specialist fits"),+ before: None,+ after: Some(json!({"kwant_id": id, "name": NAME, "title": TITLE})),+ status: "applied".into(),+ };+ let _ = super::bot_actions::record_with_card(app, &new, NAME).await;+ tracing::info!(kwant_id = %id, space = %space.as_str(), "made the Concierge for a message no specialist fits");+ app.db.get_kwant(&id).await.ok().flatten()+}diff --git a/src/server/mod.rs b/src/server/mod.rsindex a28e2afe..af978da4 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -32,6 +32,7 @@ pub mod page_source;pub mod connection_suggest;pub mod bot_actions;pub mod hires;+pub mod concierge;pub mod import_routes;pub mod approval_modes;pub mod passwords;diff --git a/src/server/routes.rs b/src/server/routes.rsindex d50fff25..f3646fcf 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -383,6 +383,13 @@ pub async fn delete_kwant(State(state): State<AppState>, headers: axum::http::Heif let Err(r) = super::mcp_suggest::refuse_agent_tokens(&state, &headers, "only the person deletes a bot").await {return r;}+ remove_bot(&state, &id).await+}++/// [`delete_kwant`] once it is known the person asked for it (also their Undo of a Concierge card).+pub(super) async fn remove_bot(state: &AppState, id: &str) -> Response {+ let state = state.clone();+ let id = id.to_string();let bot = match state.db.get_kwant(&id).await {Ok(Some(b)) => b,Ok(None) => return api_error(StatusCode::NOT_FOUND, "bot not found"),@@ -2896,7 +2903,8 @@ async fn send_chat_inner(// A plain "…?" reply gives way when the message clearly belongs to another botif !a.card {if let Ok(Some(channel)) = state.db.get_channel(cid).await {- let members = channel_members(&channel, &all_kwants);+ let concierge = super::concierge::id(&state, &space, &all_kwants).await;+ let members = routing_members(&channel, &all_kwants, concierge.as_deref());if channel.routing_mode == "auto" && members.len() > 1 {let route = state.router@@ -3267,7 +3275,8 @@ async fn send_chat_inner(.find(|k| k.id == channel.lead_kwant_id).or_else(|| all_kwants.first()).cloned();- let members = channel_members(&channel, &all_kwants);+ let concierge = super::concierge::id(&state, &space, &all_kwants).await;+ let members = routing_members(&channel, &all_kwants, concierge.as_deref());if channel.routing_mode == "auto" && members.len() > 1 {let context_id = payload.channel_id.clone();@@ -3290,9 +3299,28 @@ async fn send_chat_inner(.await}};- let chosen = members.iter().find(|k| k.id == route.kwant_id).cloned().or(lead);+ let general = channel.name == "general";+ // #general leans to the Concierge when nothing fits (made now, the first time,+ // unless the person removed it); anywhere else the pick stands+ let mut route = route;+ let mut chosen = members.iter().find(|k| k.id == route.kwant_id).cloned().or(lead);+ let removed = matches!(super::concierge::state(&state, &space, &all_kwants).await, super::concierge::State::Removed);+ if crate::router::team::settle(&route, general, !removed) == crate::router::team::Settle::Concierge {+ if let Some(c) = super::concierge::for_no_match(&state, &space, &channel.id, &all_kwants).await {+ route.reason = format!(+ "Nothing in your message fits a specialist here, so {} answers it",+ c.name+ );+ route.basis = "concierge".into();+ route.kwant_id = c.id.clone();+ chosen = Some(c);+ }+ }if let Some(ref k) = chosen {routing = Some(routing_meta(k, &route.reason, members.len(), route.fallback, &route.matched_terms, &route.basis));+ if let Some(m) = routing.as_mut() {+ m["fit"] = json!(route.fit);+ }let _ = state.event_sender.send(RuntimeEvent::RoutingDecided {context_id,kwant_id: k.id.clone(),@@ -3339,6 +3367,12 @@ async fn send_chat_inner(}}+/// The bots role scoring picks from in `channel`: its members without the Concierge, which only+/// answers what no one else fits (see `super::concierge`).+fn routing_members(channel: &crate::db::models::Channel, all_kwants: &[Kwant], concierge: Option<&str>) -> Vec<Kwant> {+ channel_members(channel, all_kwants).into_iter().filter(|k| Some(k.id.as_str()) != concierge).collect()+}+/// The bots a channel message can be routed to. #general is the hub for every agent, including/// ones created after it was seeded; channels made before the lead was always a member still/// count the lead.diff --git a/tests/concierge_test.rs b/tests/concierge_test.rsnew file mode 100644index 00000000..d22bed5d--- /dev/null+++ b/tests/concierge_test.rs@@ -0,0 +1,177 @@+//! The Concierge in #general: a message no specialist fits goes to it (made on the first one,+//! with a card the person can undo), a clear specialist message doesn't, and once the person+//! removes it, it is never made again. A fake claude CLI answers turns.+//! Its own test binary: it changes PATH.++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{+ spaces::SpaceId,+ Database,+ },+ router::LayaRouter,+ server::{create_router, AppState},+ tools::ToolRunner,+ RuntimeEvent,+};+use serde_json::{json, Value};+use std::path::PathBuf;+use std::sync::OnceLock;+use std::time::Duration;+use tower::ServiceExt;++const FAKE_CLAUDE: &str = r#"#!/bin/sh+case "$1" in+ auth) echo '{"loggedIn":true}'; exit 0 ;;+esac+echo '{"type":"result","is_error":false,"num_turns":1,"result":"answer ok"}'+"#;++fn fake_cli() {+ static DONE: OnceLock<PathBuf> = OnceLock::new();+ DONE.get_or_init(|| {+ let bin = tempfile::tempdir().unwrap().keep().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()));+ bin+ });+}++async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {+ let req = Request::builder().method(method).uri(uri).header("content-type", "application/json");+ let body = body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty);+ let resp = app.clone().oneshot(req.body(body).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_else(|_| Value::String(String::from_utf8_lossy(&bytes).into())))+}++async fn ok(app: &Router, method: &str, uri: &str, body: Option<Value>) -> Value {+ let (s, v) = call(app, method, uri, body).await;+ assert!(s.is_success(), "{method} {uri}: {s} {v}");+ v+}++async fn setup() -> (Router, AppState, tempfile::TempDir) {+ fake_cli();+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let config = Config {+ data_dir: tmp.path().to_path_buf(),+ 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(tmp.path().join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ (create_router(state.clone()), state, tmp)+}++fn specialist(name: &str, title: &str, persona: &str) -> Value {+ json!({"name": name, "title": title, "persona_prompt": persona,+ "avatar_sprite": "s", "driver_type": "api", "preferred_model": "claude"})+}++/// Sends `prompt` to the channel and returns who it was routed to and how, once the turn ended.+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;+ tokio::time::timeout(Duration::from_secs(20), async {+ let mut pick = None;+ loop {+ match events.recv().await.map(|e| e.unscoped().clone()) {+ Ok(RuntimeEvent::RoutingDecided { kwant_id, basis, .. }) => pick = Some((kwant_id, basis)),+ Ok(RuntimeEvent::TurnEnded { .. }) => return pick.expect("routed"),+ Err(e) => panic!("events: {e}"),+ _ => {}+ }+ }+ })+ .await+ .expect("the message was handled")+}++/// Leaves only `keep` in the Default space, so the seeded starter bots don't take part.+async fn only(app: &Router, state: &AppState, keep: &[&str]) {+ for k in state.db.list_kwants(&SpaceId::default_space()).await.unwrap() {+ if !keep.contains(&k.id.as_str()) {+ ok(app, "DELETE", &format!("/api/kwants/{}", k.id), None).await;+ }+ }+}++async fn concierges(state: &AppState) -> Vec<String> {+ let all = state.db.list_kwants(&SpaceId::default_space()).await.unwrap();+ all.into_iter().filter(|k| k.name == "Concierge").map(|k| k.id).collect()+}++/// Oleks 2026-11-01: "Best place to eat corn dogs in Munich tomorrow?" in #general went to the+/// TikTok scriptwriter. Live HTTP path, Laya unreachable.+#[tokio::test]+async fn corn_dogs_go_to_the_concierge_and_undo_keeps_it_gone() {+ let (app, state, _tmp) = setup().await;+ let script = ok(&app, "POST", "/api/kwants", Some(specialist("Scriptwriter", "TikTok Scriptwriter & Hook Specialist",+ "You write short TikTok video scripts and scroll-stopping hooks for book content."))).await["id"].as_str().unwrap().to_string();+ let atlas = ok(&app, "POST", "/api/kwants", Some(specialist("Atlas", "Technical SEO", "You audit sites for crawl errors, sitemaps and page speed."))).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;++ // A clear specialist message: no Concierge is made+ let (to, basis) = routed_to(&app, &state, &general, "Write a TikTok hook for this fantasy book").await;+ assert_eq!((to.as_str(), basis.as_deref()), (script.as_str(), Some("keywords")));+ assert!(concierges(&state).await.is_empty());++ // Nothing fits: the Concierge is made, with a card, and answers+ let (to, basis) = routed_to(&app, &state, &general, "Best place to eat corn dogs in Munich tomorrow?").await;+ let made = concierges(&state).await;+ assert_eq!(made.len(), 1);+ assert_eq!((to.as_str(), basis.as_deref()), (made[0].as_str(), Some("concierge")));+ let actions = ok(&app, "GET", "/api/bot-actions", None).await;+ let list = actions.as_array().cloned().or_else(|| actions["actions"].as_array().cloned()).unwrap_or_default();+ let card = list.iter().find(|a| a["action"] == "concierge_create").expect("a Concierge card").clone();+ assert_eq!(card["target_id"], made[0].as_str());+ // It doesn't count against the daily cap on bots made without a card+ assert_eq!(state.db.auto_hires_today(&SpaceId::default_space()).await.unwrap(), 0);++ // The next one reuses it; role scoring never picks it, even for a word in its own title+ let (to, basis) = routed_to(&app, &state, &general, "Any good everyday questions to ask at a dinner party?").await;+ assert_eq!((to.as_str(), basis.as_deref()), (made[0].as_str(), Some("concierge")));+ assert_eq!(concierges(&state).await.len(), 1);++ // Undo removes it even though it has answered, and it isn't made again+ ok(&app, "POST", &format!("/api/bot-actions/{}/undo", card["id"].as_str().unwrap()), None).await;+ assert!(concierges(&state).await.is_empty());+ let (to, basis) = routed_to(&app, &state, &general, "Best place to eat corn dogs in Munich tomorrow?").await;+ assert_ne!(basis.as_deref(), Some("concierge"), "{to}");+ assert!(concierges(&state).await.is_empty(), "never made again unasked");+}++/// Outside #general a low score stays with the channel's own members.+#[tokio::test]+async fn other_channels_lean_to_their_own_members() {+ let (app, state, _tmp) = setup().await;+ let a = ok(&app, "POST", "/api/kwants", Some(specialist("Scriptwriter", "TikTok Scriptwriter", "Scripts and hooks."))).await["id"].as_str().unwrap().to_string();+ let b = ok(&app, "POST", "/api/kwants", Some(specialist("Atlas", "Technical SEO", "Crawl errors."))).await["id"].as_str().unwrap().to_string();+ let c = ok(&app, "POST", "/api/channels", Some(json!({"name": "content", "lead_kwant_id": a, "member_kwants": [a, b]}))).await;+ let (to, basis) = routed_to(&app, &state, c["id"].as_str().unwrap(), "Best place to eat corn dogs in Munich tomorrow?").await;+ assert_eq!((to.as_str(), basis.as_deref()), (a.as_str(), Some("lead")));+ assert!(concierges(&state).await.is_empty());+}diff --git a/tests/router_team_building_test.rs b/tests/router_team_building_test.rsindex 83fc3257..cf1cfb5a 100644--- a/tests/router_team_building_test.rs+++ b/tests/router_team_building_test.rs@@ -138,10 +138,12 @@ fn a_weak_overlap_does_not_pick_a_bot() {assert_eq!(pick.basis, "lead", "{msg}: {}", pick.reason);assert!(pick.reason.starts_with("No one's role matched this"), "{msg}: {}", pick.reason);}- // with nothing in the words, a clear Laya pick still wins, and an unsure one does not+ // with nothing in the words, even a clear Laya pick doesn't pick on its own: Laya sees only+ // titles (it sent "Best place to eat corn dogs in Munich tomorrow?" to a TikTok scriptwriter)let msg = "do everything needed to build something new";let sure = Some(LayaGuess { kwant: &members[2], confident: true });- assert_eq!(pick_member(msg, "fit", &members, sure, "channel lead").unwrap().kwant.id, "be");+ let pick = pick_member(msg, "fit", &members, sure, "channel lead").unwrap();+ assert_eq!((pick.kwant.id.as_str(), pick.basis, pick.fit), ("fit", "lead", 0.0));assert_eq!(pick_member(msg, "fit", &members, unsure_frontend(&members), "channel lead").unwrap().basis, "lead");}diff --git a/tests/router_test.rs b/tests/router_test.rsindex 90d37b49..8c01b573 100644--- a/tests/router_test.rs+++ b/tests/router_test.rs@@ -382,10 +382,12 @@ fn test_laya_team_discussion_uses_runner_up_as_second_speaker() {kwnt::router::parse_laya_team_answers("hi there", &lukewarm, &team, &members),Some(TeamDecision::Direct { kwant_id, .. }) if kwant_id == "a"));+ // Laya's pick alone (no word in the message reaches DevOps's title or role) no longer decides:+ // the lead takes itlet direct = json!({"answers": {"team_decision": {"choice": "direct"}, "lead_kwant": {"choice": "DevOps"}}});assert!(matches!(kwnt::router::parse_laya_team_answers("Who owns the deploy?", &direct, &team, &members),- Some(TeamDecision::Direct { kwant_id, .. }) if kwant_id == "c"+ Some(TeamDecision::Direct { kwant_id, .. }) if kwant_id == "a"));}@@ -514,11 +516,12 @@ fn a_weak_laya_pick_no_longer_overrides_the_role() {let (id, _, basis, _) = direct(kwnt::router::parse_laya_team_answers("Create a new test simple strategy", &agree, &team, &members).unwrap());assert_eq!((id.as_str(), basis.as_str()), ("be", "skills"));- // No words match: a clear Laya pick stands, a near-tie goes to the lead+ // No words match: Laya's pick never decides on its own, clear or not (Laya sees only titles;+ // its confident guess sent corn dogs in Munich to a TikTok scriptwriter), so the lead takes itlet clear = json!({"answers": {"team_decision": {"choice": "direct"},"lead_kwant": {"choice": "Ops", "probabilities": {"Ops": 0.7, "Lin": 0.1, "Ada": 0.1, "Pixel": 0.05, "Rigel": 0.05}}}});let (id, reason, basis, _) = direct(kwnt::router::parse_laya_team_answers("Is the box healthy?", &clear, &team, &members).unwrap());- assert_eq!((id.as_str(), basis.as_str()), ("sre", "skills"), "{reason}");+ assert_eq!((id.as_str(), basis.as_str()), ("lead", "lead"), "{reason}");let close = json!({"answers": {"team_decision": {"choice": "direct"},"lead_kwant": {"choice": "Pixel", "probabilities": {"Pixel": 0.3, "Lin": 0.25, "Ada": 0.25, "Ops": 0.1, "Rigel": 0.1}}}});let (id, _, basis, _) = direct(kwnt::router::parse_laya_team_answers("Is the box healthy?", &close, &team, &members).unwrap());