Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

Router: team-building requests go to the lead; weak overlaps pick no one

Lin (kwant bot)6d6e474ba853
diff --git a/frontend/src/routeReason.ts b/frontend/src/routeReason.ts
index cd3cfdf7..c6b62fc3 100644
--- a/frontend/src/routeReason.ts
+++ b/frontend/src/routeReason.ts
@@ -1,7 +1,7 @@
// The line under "Sending your question to X" on Laya's routing card: why that bot, in words that
// match how it was actually picked.
-export type RouteBasis = 'skills' | 'lead' | 'keywords' | 'only' | 'several' | 'discuss';
+export type RouteBasis = 'skills' | 'lead' | 'keywords' | 'only' | 'several' | 'discuss' | 'team';
export interface RouteReasonInput {
kwantName?: string;
@@ -29,6 +29,8 @@ export function routeReasonText(r: RouteReasonInput): string | null {
return `No one’s role matched this, so it went to the team lead, ${name}.`;
case 'only':
return `${name} is the only bot here that can answer.`;
+ case 'team':
+ return `This asks to put a team of bots together, so it went to the lead, ${name}, to propose them for you to approve.`;
case 'keywords':
return terms.length ? `Picked by matching words: ${terms.join(', ')}.` : 'Picked by matching words in your message.';
default:
diff --git a/frontend/tests/botCapabilities.test.mjs b/frontend/tests/botCapabilities.test.mjs
index c23dc7b2..ba685726 100644
--- a/frontend/tests/botCapabilities.test.mjs
+++ b/frontend/tests/botCapabilities.test.mjs
@@ -166,6 +166,7 @@ test('the routing line says when the team lead took it because no role matched',
assert.equal(m.routeReasonText({ kwantName: 'Ada', basis: 'lead', reason: 'Laya picked Ada (Tech Lead) as the best fit for this question' }), 'No one’s role matched this, so it went to the team lead, Ada.');
assert.equal(m.routeReasonText({ kwantName: 'Lin', reason: 'Laya picked Lin (Backend) as the best fit' }), 'Laya picked Lin (Backend) as the best fit');
assert.equal(m.routeReasonText({ basis: 'keywords', matchedTerms: ['strategy', 'go'] }), 'Picked by matching words: strategy, go.');
+ assert.equal(m.routeReasonText({ kwantName: 'FitnessCoach', basis: 'team' }), 'This asks to put a team of bots together, so it went to the lead, FitnessCoach, to propose them for you to approve.');
assert.match(m.routingLine({ kwant_name: 'Ada', basis: 'lead', candidate_count: 4 }, 'Work'), /^No one’s role matched, so the team lead Ada took it from 4 bots in Work$/);
});
@@ -203,6 +204,7 @@ const ROUTES = [
{ case: 'only-bot', basis: 'only', name: 'Lin', terms: [], reason: 'Lin is the only bot here that can answer' },
{ case: 'laya', basis: 'skills', name: 'Lin', terms: ['migration'], reason: 'Lin (Backend) does this kind of work: your message mentions migration; Laya picked the same bot' },
{ case: 'laya-titles', basis: 'skills', name: 'Lin', terms: [], reason: "Laya matched this to Lin's role (Backend); no words in your message named a role" },
+ { case: 'team-building', basis: 'team', name: 'FitnessCoach', terms: [], reason: 'This asks to put a team of bots together, so it went to the channel lead, FitnessCoach (Fitness Trainer), to propose them on one hire card for you to approve' },
{ case: 'discuss', basis: 'discuss', name: 'Ada', terms: [], reason: 'This needs several perspectives — starting a 4-turn team discussion led by Ada' },
];
diff --git a/src/router/team.rs b/src/router/team.rs
index b6f03e4d..30e8a160 100644
--- a/src/router/team.rs
+++ b/src/router/team.rs
@@ -286,7 +286,8 @@ pub struct Pick<'a> {
pub kwant: &'a Kwant,
/// `only` (one bot can answer), `keywords` (words in the message point to this bot's role or
/// name), `skills` (Laya and the words agree), `lead` (nothing matched), `several` (more than one
- /// role matched, so the lead coordinates). The UI words each one; see frontend/src/routeReason.ts.
+ /// role matched, so the lead coordinates), `team` (a request to put a team of bots together,
+ /// which the lead proposes on one hire card). The UI words each one; see frontend/src/routeReason.ts.
pub basis: &'static str,
pub reason: String,
pub terms: Vec<String>,
@@ -384,10 +385,11 @@ fn names(ks: &[&Kwant]) -> String {
}
}
-/// Routes one message to one member. In order: a bot named in the message; the one bot whose role
-/// the request's words belong to; the bot whose name, title or persona shares the most words; Laya's
-/// pick when it was clear. Anything else — nothing matched, or two roles matched — goes to the lead,
-/// who answers or hands parts on. The reason says which of these happened.
+/// Routes one message to one member. In order: a bot named in the message; the lead for a request
+/// to put a team of bots together; the one bot whose role the request's words belong to; the one
+/// bot whose name, title or persona clearly shares the most words (not one everyday word, not a
+/// tie); Laya's pick when it was clear. Anything else — nothing matched, or two roles matched —
+/// goes to the lead, who answers or hands parts on. The reason says which of these happened.
pub fn pick_member<'a>(
prompt: &str,
lead_kwant_id: &str,
@@ -431,7 +433,17 @@ pub fn pick_member<'a>(
return Some(chosen(k, vec![k.name.trim().to_lowercase()], "was named in your message"));
}
- // 2. The request's words belong to a role
+ // 2. A request to put a team of bots together is no one specialist's work: the lead proposes
+ // the bots on one hire card (see TEAM_BUILDING_NOTE)
+ if is_team_building_request(prompt) {
+ let reason = format!(
+ "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![] });
+ }
+
+ // 3. The request's words belong to a role
let roles: Vec<(&Kwant, usize, Vec<String>)> =
members.iter().map(|m| (m, role_score(&words, m))).map(|(m, (s, t))| (m, s, t)).collect();
let strong: Vec<&(&Kwant, usize, Vec<String>)> = roles.iter().filter(|(_, s, _)| *s >= 2).collect();
@@ -462,7 +474,9 @@ pub fn pick_member<'a>(
return Some(chosen(k, terms.clone(), &how));
}
- // 3. Shared words with a bot's name, title or persona (plus weak role hints)
+ // 4. Shared words with a bot's name, title or persona (plus weak role hints). One shared word
+ // in a persona is chance, not a match, and a tie is no pick: both fall through to step 5
+ // rather than send the message to whoever happens to lead.
let scored: Vec<(&Kwant, usize, Vec<String>)> = members
.iter()
.zip(&roles)
@@ -477,20 +491,17 @@ pub fn pick_member<'a>(
})
.collect();
let top = scored.iter().map(|(_, s, _)| *s).max().unwrap_or(0);
- if top > 0 {
- let best: Vec<&(&Kwant, usize, Vec<String>)> = scored.iter().filter(|(_, s, _)| *s == top).collect();
- if let [(k, _, terms)] = best.as_slice() {
+ let best: Vec<usize> = (0..scored.len()).filter(|&i| top > 0 && scored[i].1 == top).collect();
+ if let [i] = best.as_slice() {
+ // a hint of the bot's role ("orders" for a trading backend) counts on its own
+ if top >= MIN_SHARED_SCORE || roles[*i].1 > 0 {
+ let (k, _, terms) = &scored[*i];
let how = format!("shares words with your message: {}", terms.join(", "));
return Some(chosen(k, terms.clone(), &how));
}
- if let Some((k, _, terms)) = best.iter().find(|(m, _, _)| m.id == lead.id) {
- return Some(chosen(k, terms.clone(), "shares words with your message and leads here"));
- }
- let matched: Vec<&Kwant> = best.iter().map(|(m, _, _)| *m).collect();
- return Some(to_lead(matched, best.iter().flat_map(|(_, _, t)| t.clone()).collect()));
}
- // 4. Nothing in the message matched: Laya's pick only when it was clear, else the lead
+ // 5. Nothing in the message matched: Laya's pick only when it was clear, else the lead
if let Some(g) = laya.filter(|g| g.confident) {
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![] });
@@ -499,6 +510,74 @@ pub fn pick_member<'a>(
Some(Pick { kwant: lead, basis: "lead", reason, terms: vec![] })
}
+/// The least a shared-word match must score to pick a bot: a word in its title (2), or more than
+/// one word in its persona. A single persona word ("build" in a fitness coach's "build strength")
+/// is chance.
+const MIN_SHARED_SCORE: usize = 2;
+
+/// Everyday words that say nothing about whose work a request is. They never count as shared
+/// words with a bot's name, title or persona.
+const GENERIC_WORDS: &[&str] = &[
+ "team", "teams", "build", "building", "new", "need", "needed", "needs", "make", "making", "create",
+ "creating", "do", "doing", "done", "everything", "anything", "something", "thing", "things", "help",
+ "work", "working", "get", "start", "starting", "set", "setup", "analyze", "analyse", "analize", "bot",
+ "bots", "agent", "agents", "good", "best", "first", "next", "now", "today", "also", "just", "like",
+ "know", "look", "let", "lets", "let's", "go", "going", "think", "sure", "people", "way",
+];
+
+/// 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, \
+ so it came to you as the lead. Work out which bots it needs, then propose them all on one card with \
+ propose_hire, using members and new_team. The person approves the card; nothing is created before that.)";
+
+/// "Create a team to…", "hire a few bots", "assemble a squad of agents": a request to put bots
+/// together, as opposed to code that mentions teams ("build the team page", "add a team filter").
+pub fn is_team_building_request(prompt: &str) -> bool {
+ const VERBS: &[&str] = &[
+ "create", "assemble", "build", "form", "hire", "recruit", "staff", "put", "spin", "set", "make", "start",
+ ];
+ const GROUPS: &[&str] = &["team", "teams", "crew", "squad", "bots", "agents", "specialists"];
+ const MEMBERS: &[&str] = &["bot", "bots", "agent", "agents", "someone", "specialist", "specialists", "people"];
+ /// After the group word, these make it a thing in the app rather than bots to hire.
+ const OTHER_NOUNS: &[&str] = &[
+ "page", "view", "screen", "component", "api", "endpoint", "table", "model", "settings", "list", "filter",
+ "field", "route", "schema", "feature", "tab", "panel", "button", "modal", "form", "member", "members",
+ "picker", "selector", "test", "tests", "id", "name", "lead", "channel", "description", "instructions",
+ "workspace", "folder", "repo", "icon", "discussion", "meeting", "chat", "avatar", "card",
+ ];
+ /// What may stand between the verb and the group: "put together a small team", "spin up 3 agents".
+ const FILLER: &[&str] = &[
+ "a", "an", "the", "new", "small", "whole", "full", "together", "up", "my", "our", "some", "few", "couple",
+ "of", "dedicated", "startup", "little", "proper", "entire", "me", "us", "virtual", "ai",
+ ];
+ let words = tokens(prompt);
+ let is = |i: usize, set: &[&str]| words.get(i).is_some_and(|w| set.contains(&w.as_str()));
+ words.iter().enumerate().any(|(i, w)| {
+ // "hire a designer", "hire bots": hiring here is always about bots
+ if w == "hire" || w == "recruit" {
+ return (i + 1..i + 5).any(|j| is(j, MEMBERS) || is(j, GROUPS))
+ || words.get(i + 1).is_some_and(|x| matches!(x.as_str(), "a" | "an" | "some" | "more" | "new"));
+ }
+ // "what bots we need", "which agents do we need"
+ if matches!(w.as_str(), "what" | "which")
+ && is(i + 1, &["bots", "agents", "specialists"])
+ && (i + 2..i + 6).any(|j| words.get(j).is_some_and(|x| x == "need"))
+ {
+ return true;
+ }
+ // "create a team", "put together a small team of bots", "spin up 3 agents"
+ if !VERBS.contains(&w.as_str()) {
+ return false;
+ }
+ let mut j = i + 1;
+ while j < words.len() && j <= i + 5 && (is(j, FILLER) || words[j].chars().all(|c| c.is_ascii_digit())) {
+ j += 1;
+ }
+ is(j, GROUPS) && !is(j + 1, OTHER_NOUNS)
+ })
+}
+
/// "Create…", "Fix…", "Add…": a request to change code, which one role should do rather than discuss.
fn is_code_request(prompt: &str) -> bool {
const VERBS: &[&str] = &[
@@ -526,7 +605,7 @@ fn direct(pick: Option<Pick<'_>>, team: &Team) -> TeamDecision {
/// when it reads like a discussion ("Create a new test simple strategy" used to start one).
fn settles_without_discussion(prompt: &str, pick: &Option<Pick<'_>>) -> bool {
let Some(p) = pick else { return true };
- p.reason.contains("was named in your message") || (is_code_request(prompt) && matches!(p.basis, "keywords" | "skills" | "only"))
+ p.basis == "team" || p.reason.contains("was named in your message") || (is_code_request(prompt) && matches!(p.basis, "keywords" | "skills" | "only"))
}
pub fn parse_laya_team_answers(
@@ -684,7 +763,7 @@ fn relevance(prompt: &str, kwant: &Kwant) -> (usize, Vec<String>) {
let lower_prompt = prompt.to_lowercase();
let words: Vec<&str> = lower_prompt
.split(|c: char| !c.is_alphanumeric() && c != '-')
- .filter(|s| s.len() >= 3 && !STOP_WORDS.contains(s))
+ .filter(|s| s.len() >= 3 && !STOP_WORDS.contains(s) && !GENERIC_WORDS.contains(s))
.map(|s| if s.len() > 4 { s.strip_suffix('s').unwrap_or(s) } else { s })
.collect();
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 8764d361..3aec96d0 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -782,12 +782,19 @@ fn execute_single_turn(
state,
};
let prompt = payload.prompt.clone();
+ // the lead got a team-building request: say so, so it proposes the bots instead of answering
+ // as its own specialty (the saved message stays as the person wrote it)
+ let turn_prompt = if routing.as_ref().is_some_and(|r| r["basis"] == "team") {
+ format!("{prompt}\n\n{}", crate::router::team::TEAM_BUILDING_NOTE)
+ } else {
+ prompt.clone()
+ };
tokio::spawn(async move {
// Ends the job (its cancel keys) when the turn and its handoffs are done
let _job = job;
let opts = TurnOpts { routing, ..TurnOpts::default() };
- if let Some(reply) = run_kwant_turn(&scope, &target_kwant, prompt.clone(), opts).await {
+ if let Some(reply) = run_kwant_turn(&scope, &target_kwant, turn_prompt, opts).await {
run_handoffs(&scope, std::slice::from_ref(&target_kwant.id), &[(target_kwant.clone(), reply)], &prompt).await;
}
});
diff --git a/tests/router_team_building_test.rs b/tests/router_team_building_test.rs
new file mode 100644
index 00000000..812d8484
--- /dev/null
+++ b/tests/router_team_building_test.rs
@@ -0,0 +1,173 @@
+//! Routing in a space of unrelated bots: Oleks's "create a team to build a new startup…" went to
+//! FitnessCoach because the message shared one everyday word with it and it led the space.
+use kwnt::db::models::{Kwant, Team};
+use kwnt::router::team::{is_team_building_request, pick_member, LayaGuess};
+use kwnt::router::{heuristic_team_decision, LayaRouter, TeamDecision};
+
+const OLEKS: &str = "create a team to build a new startup. Analize what bots we need and do everythign needed";
+
+fn bot(id: &str, name: &str, title: &str, persona: &str) -> Kwant {
+ Kwant {
+ space_id: kwnt::db::spaces::DEFAULT_SPACE_ID.into(),
+ id: id.into(),
+ name: name.into(),
+ title: title.into(),
+ persona_prompt: persona.into(),
+ soul: String::new(),
+ avatar_sprite: "s".into(),
+ driver_type: "claude".into(),
+ preferred_model: "auto".into(),
+ temperature: 0.7,
+ max_tokens: 4096,
+ level: 1,
+ turns_completed: 0,
+ created_at: None,
+ }
+}
+
+/// The space from the screenshot, FitnessCoach leading. Personas use everyday words the way real
+/// ones do ("build strength", "builds APIs", "new habits").
+fn space() -> Vec<Kwant> {
+ vec![
+ bot("fit", "FitnessCoach", "Fitness Trainer",
+ "You are FitnessCoach. You build workout plans, help people build strength and start new habits they need."),
+ bot("travel", "TravelPlanner", "Travel Planner",
+ "You are TravelPlanner. You plan trips, compare flights and build itineraries for a new city."),
+ bot("be", "Backend", "Backend Engineer",
+ "You are Backend. You build APIs, services and databases and do code reviews."),
+ bot("sre", "SRE", "Site Reliability Engineer",
+ "You are SRE. You keep services up, build pipelines and handle deploys."),
+ bot("fe", "Frontend", "Frontend Engineer",
+ "You are Frontend. You build pages and components for a new web app."),
+ bot("qa", "QA", "QA Engineer", "You are QA. You write tests and find bugs before a release."),
+ ]
+}
+
+fn team() -> Team {
+ Team {
+ space_id: kwnt::db::spaces::DEFAULT_SPACE_ID.into(),
+ id: "t".into(),
+ name: "general".into(),
+ description: None,
+ workspace_path: None,
+ repo_url: None,
+ icon: "users".into(),
+ lead_kwant_id: "fit".into(),
+ member_kwants: "[]".into(),
+ created_at: None,
+ instructions: None,
+ }
+}
+
+fn unsure_frontend(members: &[Kwant]) -> Option<LayaGuess<'_>> {
+ Some(LayaGuess { kwant: &members[4], confident: false })
+}
+
+#[test]
+fn olekss_message_is_a_team_building_request_for_the_lead() {
+ let members = space();
+ for laya in [None, unsure_frontend(&members)] {
+ let pick = pick_member(OLEKS, "fit", &members, laya, "channel lead").unwrap();
+ assert_eq!((pick.kwant.id.as_str(), pick.basis), ("fit", "team"));
+ assert!(pick.reason.starts_with("This asks to put a team of bots together"), "{}", pick.reason);
+ assert!(pick.reason.contains("hire card"), "{}", pick.reason);
+ assert!(!pick.reason.contains("shares words"), "{}", pick.reason);
+ }
+}
+
+#[test]
+fn a_team_request_settles_without_a_discussion() {
+ let members = space();
+ match heuristic_team_decision(OLEKS, &team(), &members) {
+ TeamDecision::Direct { kwant_id, basis, .. } => assert_eq!((kwant_id.as_str(), basis.as_str()), ("fit", "team")),
+ other => panic!("expected the lead to take it, got {other:?}"),
+ }
+}
+
+#[tokio::test]
+async fn channel_route_for_olekss_message_states_the_intent() {
+ let members = space();
+ let laya = LayaRouter::new("http://127.0.0.1:9".into());
+ let r = laya.route_channel_query_detailed(OLEKS, "general", "fit", &members).await;
+ assert_eq!((r.kwant_id.as_str(), r.basis.as_str()), ("fit", "team"));
+ assert!(r.reason.contains("team of bots"), "{}", r.reason);
+}
+
+#[test]
+fn team_building_requests_are_recognised() {
+ for msg in [
+ OLEKS,
+ "Create a team for my podcast",
+ "hire a designer bot",
+ "Hire a copywriter",
+ "please recruit some agents to run marketing",
+ "put together a small team of agents for SEO",
+ "spin up 3 agents to research competitors",
+ "assemble a crew to plan the launch",
+ "what bots do we need for a newsletter?",
+ "Build me a team that can ship a mobile app",
+ ] {
+ assert!(is_team_building_request(msg), "{msg}");
+ }
+}
+
+#[test]
+fn code_and_everyday_requests_that_mention_teams_are_not() {
+ for msg in [
+ "build the team page",
+ "add a filter to the team members list",
+ "create a team settings tab",
+ "make the team picker accessible",
+ "build a dashboard for the team",
+ "fix the hire card layout",
+ "set the team lead to Backend",
+ "our team needs a faster deploy pipeline",
+ "create a new endpoint for bots",
+ "hello",
+ ] {
+ assert!(!is_team_building_request(msg), "{msg}");
+ }
+}
+
+/// One everyday word shared with a persona is no reason to pick a bot, even the lead.
+#[test]
+fn a_weak_overlap_does_not_pick_a_bot() {
+ let members = space();
+ for msg in ["do everything needed to build something new", "can you start on this now", "build it"] {
+ let pick = pick_member(msg, "fit", &members, None, "channel lead").unwrap();
+ 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
+ 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");
+ assert_eq!(pick_member(msg, "fit", &members, unsure_frontend(&members), "channel lead").unwrap().basis, "lead");
+}
+
+/// Real matches still route: a title word, or more than one persona word.
+#[test]
+fn clear_matches_still_route_to_the_specialist() {
+ let members = space();
+ let cases = [
+ ("plan my trips to Rome and compare flights", "travel"),
+ ("a workout to build strength", "fit"),
+ ("the api endpoint returns 500", "be"),
+ ("FitnessCoach, what should I eat today?", "fit"),
+ ("Backend, create a team of agents", "be"), // named wins over the intent
+ ];
+ for (msg, want) in cases {
+ let pick = pick_member(msg, "fit", &members, None, "channel lead").unwrap();
+ assert_eq!(pick.kwant.id, want, "{msg}: {}", pick.reason);
+ }
+}
+
+/// A tie between bots is no pick either: it is not settled by who leads.
+#[test]
+fn a_tie_is_not_settled_by_who_leads() {
+ let members = space();
+ // "new" is generic now; "itineraries"/"components" are one persona word each
+ let pick = pick_member("itineraries and components", "fit", &members, None, "channel lead").unwrap();
+ assert_ne!(pick.reason, "FitnessCoach (Fitness Trainer) shares words with your message and leads here");
+ assert!(!pick.reason.contains("leads here"), "{}", pick.reason);
+}