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 and handoffs: one distinctive word reaches its bot; everyday team phrases hire no one; code mentions are said

Lin (kwant bot)8d84fed92d26
diff --git a/src/router/tags.rs b/src/router/tags.rs
index 84e20124..154883ef 100644
--- a/src/router/tags.rs
+++ b/src/router/tags.rs
@@ -104,7 +104,8 @@ const NOT_A_BOT: [&str; 7] = ["you", "user", "me", "here", "channel", "team", "p
pub struct HandoffMentions {
/// Teammates handed the turn, as indices into `names`, in order of first mention.
pub targets: Vec<usize>,
- /// Teammates mentioned only inside a ``` code block.
+ /// Teammates mentioned only inside code: a ``` or ~~~ block, or inline code that is more
+ /// than the name.
pub in_code_block: Vec<usize>,
/// `@Name`s in prose that match no teammate, as written, once each.
pub unknown: Vec<String>,
@@ -112,18 +113,19 @@ pub struct HandoffMentions {
/// Reads the @mentions in `text` against `names`. Prose mentions count, and so does inline
/// code that is just a teammate's name (`` `@Growth` ``: models often format names that way).
-/// Other inline code, ``` code blocks and email addresses hand nothing on.
+/// Other inline code, ``` and ~~~ code blocks and email addresses hand nothing on; a teammate
+/// mentioned only there is listed in `in_code_block`, so the caller can say so.
pub fn handoff_mentions(text: &str, names: &[&str]) -> HandoffMentions {
let is_name = |tag: &str| names.iter().position(|n| n.eq_ignore_ascii_case(tag));
let chars: Vec<char> = text.chars().collect();
let find = |from: usize, pat: &[char]| (from..=chars.len().saturating_sub(pat.len())).find(|&j| chars[j..].starts_with(pat));
- let fence = ['`', '`', '`'];
+ let fences = [['`', '`', '`'], ['~', '~', '~']];
let mut prose = String::with_capacity(text.len());
let mut fenced = String::new();
let mut i = 0;
while i < chars.len() {
- if chars[i..].starts_with(&fence) {
- let end = find(i + 3, &fence).unwrap_or(chars.len());
+ if let Some(fence) = fences.iter().find(|f| chars[i..].starts_with(&f[..])) {
+ let end = find(i + 3, fence).unwrap_or(chars.len());
fenced.extend(&chars[i + 3..end]);
fenced.push('\n');
prose.push(' ');
@@ -132,10 +134,16 @@ pub fn handoff_mentions(text: &str, names: &[&str]) -> HandoffMentions {
match find(i + 1, &['`']) {
Some(end) => {
let span: String = chars[i + 1..end].iter().collect();
- let span = span.trim();
+ // `@Growth.` is still just the name
+ let span = span.trim().trim_end_matches(['.', ',', ':', ';', '!', '?']);
match span.strip_prefix('@').filter(|tag| is_name(tag).is_some()) {
Some(tag) => prose.push_str(&format!(" @{tag} ")),
- None => prose.push(' '),
+ None => {
+ // `run @Growth now` is code, but the mention is said, not dropped
+ fenced.push_str(span);
+ fenced.push('\n');
+ prose.push(' ');
+ }
}
i = end + 1;
}
@@ -226,6 +234,23 @@ mod tests {
assert_eq!((m.targets, m.in_code_block), (vec![1], vec![]));
}
+ /// Rigel's gaps: inline code with a trailing period is still the name, inline code that is
+ /// more than the name is reported instead of dropped, and ~~~ blocks are code like ```.
+ #[test]
+ fn inline_code_mentions_hand_on_or_are_reported() {
+ let names = ["Product", "Growth", "Dev"];
+ assert_eq!(handoff_mentions("`@Growth.` please draft the plan", &names).targets, vec![1]);
+ assert_eq!(handoff_mentions("over to `@Growth:`", &names).targets, vec![1]);
+ let m = handoff_mentions("`run @Growth now`", &names);
+ assert_eq!((m.targets, m.in_code_block), (vec![], vec![1]));
+ let m = handoff_mentions("~~~\n@Dev deploy\n~~~\nthat's all", &names);
+ assert_eq!((m.targets, m.in_code_block), (vec![], vec![2]));
+ let m = handoff_mentions("~~~\n@Dev\n~~~ then @Dev", &names);
+ assert_eq!((m.targets, m.in_code_block), (vec![2], vec![]));
+ // an email in inline code is still no mention at all
+ assert_eq!(handoff_mentions("`[email protected]`", &names), HandoffMentions::default());
+ }
+
#[test]
fn test_mention_methods() {
let k = TagMention::Kwant("Architect".into());
diff --git a/src/router/team.rs b/src/router/team.rs
index 30e8a160..ec9786bd 100644
--- a/src/router/team.rs
+++ b/src/router/team.rs
@@ -474,14 +474,21 @@ pub fn pick_member<'a>(
return Some(chosen(k, terms.clone(), &how));
}
- // 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
+ // 4. Shared words with a bot's name, title or persona (plus weak role hints). A word several
+ // bots share says nothing about which of them it is for ("plan" for a fitness coach's
+ // "workout plans" and a travel planner), so it counts for none of them; one word only one
+ // bot has ("workout", "flight") is enough. A tie is no pick: both fall through to step 5
// rather than send the message to whoever happens to lead.
+ let matches: Vec<Vec<(String, usize)>> = members.iter().map(|m| relevance_terms(prompt, m)).collect();
+ let shared = |w: &str| matches.iter().filter(|terms| terms.iter().any(|(t, _)| t == w)).count() > 1;
let scored: Vec<(&Kwant, usize, Vec<String>)> = members
.iter()
.zip(&roles)
- .map(|(m, (_, rs, rt))| {
- let (s, mut t) = relevance(prompt, m);
+ .zip(&matches)
+ .map(|((m, (_, rs, rt)), terms)| {
+ let own: Vec<&(String, usize)> = terms.iter().filter(|(t, _)| !shared(t)).collect();
+ let s = own.iter().map(|(_, s)| s).sum::<usize>();
+ let mut t: Vec<String> = own.iter().map(|(t, _)| t.clone()).collect();
for w in rt {
if !t.contains(w) {
t.push(w.clone());
@@ -493,12 +500,9 @@ pub fn pick_member<'a>(
let top = scored.iter().map(|(_, s, _)| *s).max().unwrap_or(0);
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));
- }
+ let (k, _, terms) = &scored[*i];
+ let how = format!("shares words with your message: {}", terms.join(", "));
+ return Some(chosen(k, terms.clone(), &how));
}
// 5. Nothing in the message matched: Laya's pick only when it was clear, else the lead
@@ -510,11 +514,6 @@ 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] = &[
@@ -537,6 +536,8 @@ pub fn is_team_building_request(prompt: &str) -> bool {
const VERBS: &[&str] = &[
"create", "assemble", "build", "form", "hire", "recruit", "staff", "put", "spin", "set", "make", "start",
];
+ /// Verbs that also go with a team in everyday use, so they need a bot word too.
+ const WEAK_VERBS: &[&str] = &["put", "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.
@@ -574,7 +575,12 @@ pub fn is_team_building_request(prompt: &str) -> bool {
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)
+ if !is(j, GROUPS) || is(j + 1, OTHER_NOUNS) {
+ return false;
+ }
+ // "put the team on the dashboard", "make the team happy": everyday verbs only put a team of
+ // bots together when bots are said ("put together a team of agents", "make 3 bots")
+ !WEAK_VERBS.contains(&w.as_str()) || is(j, MEMBERS) || (j + 1..j + 4).any(|k| is(k, MEMBERS))
})
}
@@ -760,6 +766,13 @@ pub fn matched_terms(prompt: &str, kwant: &Kwant) -> Vec<String> {
}
fn relevance(prompt: &str, kwant: &Kwant) -> (usize, Vec<String>) {
+ let terms = relevance_terms(prompt, kwant);
+ (terms.iter().map(|(_, s)| s).sum(), terms.into_iter().map(|(t, _)| t).collect())
+}
+
+/// The prompt words that matched `kwant`'s name (3), title (2) or persona (1), each with its score,
+/// in prompt order, without repeats.
+fn relevance_terms(prompt: &str, kwant: &Kwant) -> Vec<(String, usize)> {
let lower_prompt = prompt.to_lowercase();
let words: Vec<&str> = lower_prompt
.split(|c: char| !c.is_alphanumeric() && c != '-')
@@ -777,10 +790,9 @@ fn relevance(prompt: &str, kwant: &Kwant) -> (usize, Vec<String>) {
.any(|tok| tok == w || (w.len() >= 4 && tok.starts_with(w)))
};
- let mut score = 0;
- let mut terms: Vec<String> = Vec::new();
+ let mut terms: Vec<(String, usize)> = Vec::new();
for w in words {
- let before = score;
+ let mut score = 0;
if matches(&name_lower, w) {
score += 3;
}
@@ -790,11 +802,11 @@ fn relevance(prompt: &str, kwant: &Kwant) -> (usize, Vec<String>) {
if matches(&prompt_lower, w) {
score += 1;
}
- if score > before && !terms.iter().any(|t| t == w) {
- terms.push(w.to_string());
+ if score > 0 && !terms.iter().any(|(t, _)| t == w) {
+ terms.push((w.to_string(), score));
}
}
- (score, terms)
+ terms
}
fn generate_discussion_plan(speakers: &[String], members: &[Kwant]) -> Vec<String> {
diff --git a/src/server/routes.rs b/src/server/routes.rs
index c271a10c..93dca929 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -936,7 +936,7 @@ async fn run_handoffs(scope: &TurnScope, already_spoken: &[String], replies: &[(
report_skipped(scope, skipped).await;
}
-const IN_CODE_BLOCK: &str = "the mention was inside a code block";
+const IN_CODE_BLOCK: &str = "the mention was inside code. Write the name as plain text to ask them";
/// Says in the chat, and logs, each @mention that handed nothing on: "Growth wasn't asked: <why>".
/// An empty reason means no teammate has that name; it's worked out here.
diff --git a/tests/router_team_building_test.rs b/tests/router_team_building_test.rs
index 812d8484..a010f354 100644
--- a/tests/router_team_building_test.rs
+++ b/tests/router_team_building_test.rs
@@ -171,3 +171,60 @@ fn a_tie_is_not_settled_by_who_leads() {
assert_ne!(pick.reason, "FitnessCoach (Fitness Trainer) shares words with your message and leads here");
assert!(!pick.reason.contains("leads here"), "{}", pick.reason);
}
+
+/// Rigel's regressions (report §3): with Backend leading, a plain request for one specialist
+/// fell to the lead after generic words stopped counting. One word only that bot has still wins.
+#[test]
+fn one_distinctive_word_reaches_the_specialist_whoever_leads() {
+ let members = space();
+ let cases = [
+ ("log my meals and workouts", "fit"),
+ ("create a workout schedule for the week", "fit"),
+ ("start a new habit tracker", "fit"),
+ ("book a flight and hotel", "travel"),
+ ("create a bot that tracks flights", "travel"),
+ ("plan a trip to Rome", "travel"),
+ ];
+ for lead in ["be", "fit", "fe"] {
+ for (msg, want) in cases {
+ let pick = pick_member(msg, lead, &members, None, "channel lead").unwrap();
+ assert_eq!(pick.kwant.id, want, "lead {lead}, {msg}: {}", pick.reason);
+ assert!(!is_team_building_request(msg), "{msg}");
+ }
+ }
+}
+
+/// "plan" is in Travel Planner's title and in FitnessCoach's "workout plans", so it says nothing
+/// about which of them it is for; "workout" does.
+#[test]
+fn a_word_two_bots_share_does_not_beat_one_only_one_has() {
+ let members = space();
+ for lead in ["be", "fit", "travel"] {
+ for msg in ["need a new workout plan", "create a new workout plan", "plan my workout routine"] {
+ let pick = pick_member(msg, lead, &members, None, "channel lead").unwrap();
+ assert_eq!(pick.kwant.id, "fit", "lead {lead}, {msg}: {}", pick.reason);
+ }
+ }
+}
+
+/// put/make/start go with a team in everyday use; without a bot word they are no hire request.
+#[test]
+fn everyday_team_phrases_get_no_hire_card() {
+ let members = space();
+ for (msg, want) in [
+ ("put the team on the dashboard", Some("fe")),
+ ("make the team happy", None),
+ ("start the team standup notes", None),
+ ] {
+ assert!(!is_team_building_request(msg), "{msg}");
+ let pick = pick_member(msg, "be", &members, None, "channel lead").unwrap();
+ assert_ne!(pick.basis, "team", "{msg}: {}", pick.reason);
+ if let Some(want) = want {
+ assert_eq!(pick.kwant.id, want, "{msg}: {}", pick.reason);
+ }
+ }
+ // with a bot word they still are
+ for msg in ["put together a team of agents for SEO", "make a team of bots for my shop", "start a new team of agents"] {
+ assert!(is_team_building_request(msg), "{msg}");
+ }
+}