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.

Handoffs: one teammate is asked by mention at most twice per message; `` spans are code

Lin (kwant bot)84ffd4f2c970
diff --git a/src/router/tags.rs b/src/router/tags.rs
index 154883ef..19f2b3b5 100644
--- a/src/router/tags.rs
+++ b/src/router/tags.rs
@@ -131,11 +131,16 @@ pub fn handoff_mentions(text: &str, names: &[&str]) -> HandoffMentions {
prose.push(' ');
i = (end + 3).min(chars.len());
} else if chars[i] == '`' {
- match find(i + 1, &['`']) {
+ // A span opens and closes with the same number of backticks (`` x `` like ` x `)
+ let run = chars[i..].iter().take_while(|&&c| c == '`').count();
+ let close = (i + run..chars.len()).find(|&j| {
+ chars[j] == '`' && chars[j - 1] != '`' && chars[j..].iter().take_while(|&&c| c == '`').count() == run
+ });
+ match close {
Some(end) => {
- let span: String = chars[i + 1..end].iter().collect();
- // `@Growth.` is still just the name
- let span = span.trim().trim_end_matches(['.', ',', ':', ';', '!', '?']);
+ let span: String = chars[i + run..end].iter().collect();
+ // `@Growth.` is still just the name, and so is `` `@Growth` ``
+ let span = span.trim().trim_matches('`').trim_end_matches(['.', ',', ':', ';', '!', '?']);
match span.strip_prefix('@').filter(|tag| is_name(tag).is_some()) {
Some(tag) => prose.push_str(&format!(" @{tag} ")),
None => {
@@ -145,12 +150,12 @@ pub fn handoff_mentions(text: &str, names: &[&str]) -> HandoffMentions {
prose.push(' ');
}
}
- i = end + 1;
+ i = end + run;
}
- // A lone backtick is just a character
+ // Unmatched backticks are just characters
None => {
prose.push(' ');
- i += 1;
+ i += run;
}
}
} else {
@@ -247,6 +252,14 @@ mod tests {
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![]));
+ // double-backtick spans are inline code too
+ let m = handoff_mentions("``run @Dev now`` then ``@Growth``", &names);
+ assert_eq!((m.targets, m.in_code_block), (vec![1], vec![2]));
+ assert_eq!(handoff_mentions("`` `@Growth` `` go", &names).targets, vec![1]);
+ let m = handoff_mentions("`` a ` @Dev `` ok", &names);
+ assert_eq!((m.targets, m.in_code_block), (vec![], vec![2]));
+ // an unmatched run is plain text, and a later single span still pairs up
+ assert_eq!(handoff_mentions("`` @Dev and `x`", &names).targets, vec![2]);
// an email in inline code is still no mention at all
assert_eq!(handoff_mentions("`[email protected]`", &names), HandoffMentions::default());
}
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 93dca929..19167168 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -758,6 +758,9 @@ const MAX_HANDOFFS: usize = 4;
/// Delegations a lead's @mentions may start for one user message, follow-up rounds included:
/// a lead resumed with results can hand on again, but never in an endless loop.
pub const MAX_DELEGATIONS_PER_REQUEST: usize = 8;
+/// How often one teammate may be handed work by @mention for one user message, so two bots
+/// naming each other stop after a couple of rounds instead of running to the total cap.
+pub const MAX_MENTION_DELEGATIONS_PER_BOT: usize = 2;
#[allow(clippy::too_many_arguments)]
fn execute_single_turn(
@@ -989,7 +992,8 @@ async fn is_team_channel_lead(scope: &TurnScope, kwant: &Kwant) -> bool {
/// delegate tool), and when the last one ends the lead is resumed once with every result to give
/// the user one answer; that follow-up may hand on again. `just_reported` teammates (whose results
/// the follow-up is about) aren't sent it again by a mention, and one user message starts at most
-/// [`MAX_DELEGATIONS_PER_REQUEST`]. Every mention that hands nothing on is said in the channel.
+/// [`MAX_DELEGATIONS_PER_REQUEST`], at most [`MAX_MENTION_DELEGATIONS_PER_BOT`] to any one
+/// teammate. Every mention that hands nothing on is said in the channel.
/// Teammates the lead already delegated to from this channel (with the tool) aren't sent it twice.
async fn delegate_mentions(scope: &TurnScope, lead: &Kwant, text: &str, user_prompt: &str, just_reported: &[String]) {
let Some(cid) = scope.channel_id.clone() else { return };
@@ -1013,8 +1017,9 @@ async fn delegate_mentions(scope: &TurnScope, lead: &Kwant, text: &str, user_pro
// Delegations this user message already started, counting earlier follow-up rounds
let messages = scope.state.db.list_messages(&cid, 100).await.unwrap_or_default();
let since = messages.iter().rev().find(|m| m.sender_role == "user").or(messages.first()).and_then(|m| m.created_at);
- let started = mine.iter().filter(|d| d.continue_lead && since.is_some_and(|t| d.created_at >= t)).count();
- let mut room = MAX_DELEGATIONS_PER_REQUEST.saturating_sub(started);
+ let this_request: Vec<_> = mine.iter().filter(|d| d.continue_lead && since.is_some_and(|t| d.created_at >= t)).collect();
+ let mut room = MAX_DELEGATIONS_PER_REQUEST.saturating_sub(this_request.len());
+ let asked = |id: &str| this_request.iter().filter(|d| d.specialist_kwant_id == id).count();
let mut targets: Vec<&Kwant> = Vec::new();
for i in found.targets {
@@ -1026,6 +1031,11 @@ async fn delegate_mentions(scope: &TurnScope, lead: &Kwant, text: &str, user_pro
skipped.push((k.name.clone(), format!("{} just reported back on this. For a correction, delegate a concrete task", k.name)));
} else if open.contains(&k.id.as_str()) {
skipped.push((k.name.clone(), format!("{} is still working on an earlier task from this chat", k.name)));
+ } else if asked(&k.id) >= MAX_MENTION_DELEGATIONS_PER_BOT {
+ skipped.push((
+ k.name.clone(),
+ format!("{} was already asked {MAX_MENTION_DELEGATIONS_PER_BOT} times for this request. Send a new message to go on", k.name),
+ ));
} else {
targets.push(k);
}
diff --git a/tests/delegation_test.rs b/tests/delegation_test.rs
index 341a42e7..fd33b041 100644
--- a/tests/delegation_test.rs
+++ b/tests/delegation_test.rs
@@ -1013,6 +1013,57 @@ async fn mentions_that_hand_nothing_on_are_said_in_the_channel() {
assert!(!delegated_growth, "over the limit, Growth isn't asked");
}
+/// Rigel's ping-pong (2026-10-21): two bots naming each other ran all 8 rounds of a request. One
+/// teammate is now handed work by mention at most twice per user message; the third mention is
+/// said in the channel and starts nothing.
+#[tokio::test]
+async fn one_teammate_is_asked_by_mention_at_most_twice_per_request() {
+ let env = setup().await;
+ let lead = name(&env, &env.lead).await;
+ let growth = add_bot(&env, "Growth").await;
+ let channel = team_channel_with(&env, "startup-pingpong", &[&env.lead, &env.specialist, &growth]).await;
+ say_in(&env, &channel, &format!("@{lead} Plan the launch REPLYTAG:plan")).await;
+ wait_for("the lead's reply", || async { channel_messages(&env, &channel).await.iter().any(|m| m.text.contains("answer plan")) }).await;
+
+ // Growth already ran twice for this message (earlier rounds, both ended)
+ for _ in 0..per_bot_limit() {
+ let (_, d) = env
+ .state
+ .db
+ .create_delegation(&kwnt::db::threads::NewDelegation {
+ lead_kwant_id: env.lead.clone(),
+ specialist_kwant_id: growth.clone(),
+ origin_channel_id: Some(channel.clone()),
+ origin_kwant_id: None,
+ origin_thread_id: None,
+ team_id: None,
+ task: "earlier round".into(),
+ title: "Earlier round".into(),
+ continue_lead: true,
+ depth: 1,
+ follow_up_at: None,
+ })
+ .await
+ .unwrap();
+ assert!(env.state.db.finish_delegation(&d.id, "completed", None, None).await.unwrap());
+ }
+ // The specialist reports back and the lead's follow-up names Growth a third time
+ let last = delegate_from(&env, &channel, &env.specialist, "Review REPLYTAG:rev", "Review FOLLOWUP:Growth").await;
+ wait_for("the review", || async { delegation_status(&env, &last).await == "completed" }).await;
+ let note = || async { refusals(&channel_messages(&env, &channel).await).into_iter().find(|n| n.starts_with("Growth wasn't asked")) };
+ wait_for("the per-teammate notice", || async { note().await.is_some() }).await;
+ let note = note().await.unwrap();
+ assert_eq!(note, "Growth wasn't asked: Growth was already asked 2 times for this request. Send a new message to go on");
+ tokio::time::sleep(Duration::from_millis(1000)).await;
+ let to_growth = env.state.db.list_delegations(Some(&env.lead), None, 50).await.unwrap().iter().filter(|d| d.specialist_kwant_id == growth).count();
+ assert_eq!(to_growth, per_bot_limit(), "no third delegation to Growth");
+ assert_eq!(refusals(&channel_messages(&env, &channel).await).len(), 1, "one notice, no flood");
+}
+
+fn per_bot_limit() -> usize {
+ kwnt::server::routes::MAX_MENTION_DELEGATIONS_PER_BOT
+}
+
fn routes_limit() -> usize {
kwnt::server::routes::MAX_DELEGATIONS_PER_REQUEST
}