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: hand_back passes on the message the turn answers, not the newest

Ada (kwant bot)ac604dc5cb58
diff --git a/docs/channel-routing.md b/docs/channel-routing.md
index c6e1a354..a269371a 100644
--- a/docs/channel-routing.md
+++ b/docs/channel-routing.md
@@ -54,6 +54,9 @@ Returns `{status: "dispatched", user_message_id, kwant, kwant_id}`; the event
A routed bot can call `hand_back {reason}` ("not my area"). The message goes on once (basis
`handback`, with `handed_back_by`) to the next member that fits (fit ≥ 0.6), else the Concierge,
else the lead. A message takes at most one hop; a second `hand_back` is refused.
+The message handed on is the one the bot's turn was routed (`TurnOrigin::message_id`, the same id
+as its reply's `routing.message_id`), not the channel's newest message. A turn with no routed
+message (an @mention, a DM) can't hand back.
## Learning from the person
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index 59baf7a5..b2d50403 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -327,6 +327,9 @@ pub struct TurnOrigin {
pub member_ids: Vec<String>,
/// 0 in user chats, 1 in a delegation thread, …
pub depth: i64,
+ /// The person's channel message kwnt routed to this turn (its reply's `meta.routing.message_id`);
+ /// `hand_back` hands on exactly this one. `None` for @mentions, DMs and other unrouted turns.
+ pub message_id: Option<String>,
}
/// The synthetic http MCP server a turn reaches its own tools through. The token travels as a
diff --git a/src/server/rerouting.rs b/src/server/rerouting.rs
index bec5009e..8f539a88 100644
--- a/src/server/rerouting.rs
+++ b/src/server/rerouting.rs
@@ -4,8 +4,8 @@
//! - Ask: a fit from [`ASK_FROM`] up to [`ROUTE_AT`] with two candidates posts a card offering
//! those two bots and a general answer (the Concierge in #general, else the channel lead). The
//! message waits; `POST /api/route-choices/:id/resolve` (person only) runs the chosen bot's turn.
-//! - Hand-back: the `hand_back` tool, in a channel turn, sends the person's last message on to the
-//! next best bot here, else the Concierge (or the lead). One hop per message, ever.
+//! - Hand-back: the `hand_back` tool, in a routed channel turn, sends the message that turn answers
+//! on to the next best bot here, else the Concierge (or the lead). One hop per message, ever.
//!
//! Contract: /home/maus/shared/ship-software-safely/router-concierge/contract.md
@@ -260,7 +260,7 @@ pub async fn correct_route(State(state): State<AppState>, headers: HeaderMap, Js
pub fn tool() -> Value {
json!({
"name": HAND_BACK,
- "description": "Hand the person's last message in this channel back when it is clearly not your area, so kwnt sends it \
+ "description": "Hand the person's message you were routed in this channel back when it is clearly not your area, so kwnt sends it \
to the bot here that fits it best (or a generalist). Use it only when someone else is clearly better placed, not to \
avoid work. It works once per message. After it succeeds, end your turn with one short line saying who takes it; \
don't answer the request yourself.",
@@ -289,14 +289,19 @@ pub async fn tool_call(state: &AppState, scope: &SelfScope, args: &Value) -> Too
let Some(channel_id) = origin.channel_id.clone() else {
return ("hand_back works only for a message the person sent in a channel.".into(), true);
};
- match hand_back(state, &scope.kwant_id, &channel_id, &reason).await {
+ // The message this turn answers, never just the newest one: in a busy channel that can be
+ // another person's message routed to someone else
+ let Some(message_id) = origin.message_id.clone() else {
+ return ("hand_back works only for a message kwnt routed to you; this one was sent to you directly, so answer it.".into(), true);
+ };
+ match hand_back(state, &scope.kwant_id, &channel_id, &message_id, &reason).await {
Ok(to) => (format!("Handed to {to}. End your turn now with one short line saying {to} will take it; don't answer the request."), false),
Err(why) => (why, true),
}
}
-/// Sends the person's latest message in `channel_id` on from `from_id`; returns who takes it.
-pub(super) async fn hand_back(state: &AppState, from_id: &str, channel_id: &str, reason: &str) -> Result<String, String> {
+/// Sends the person's message `message_id` in `channel_id` on from `from_id`; returns who takes it.
+pub(super) async fn hand_back(state: &AppState, from_id: &str, channel_id: &str, message_id: &str, reason: &str) -> Result<String, String> {
let Ok(Some(channel)) = state.db.get_channel(channel_id).await else {
return Err("Could not find this channel.".into());
};
@@ -304,9 +309,9 @@ pub(super) async fn hand_back(state: &AppState, from_id: &str, channel_id: &str,
return Err("Could not find you.".into());
};
let space = SpaceId::new(&from.space_id);
- let messages = state.db.list_messages(channel_id, 50).await.unwrap_or_default();
- let Some(msg) = messages.iter().rev().find(|m| m.sender_role == "user") else {
- return Err("There's no message from the person here to hand back.".into());
+ let msg = match state.db.get_message(message_id).await {
+ Ok(Some(m)) if m.sender_role == "user" && m.channel_id.as_deref() == Some(channel_id) => m,
+ _ => return Err("Could not find the person's message you were answering, so it can't be handed back.".into()),
};
if state.db.handed_back(&msg.id).await.unwrap_or(true) {
return Err("This message was already handed back once; answer it as well as you can.".into());
diff --git a/src/server/routes.rs b/src/server/routes.rs
index fb1ff9d7..7c495c55 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -2296,6 +2296,7 @@ async fn run_kwant_turn_inner(
team_id: scope.team_context.as_ref().map(|t| t.id.clone()),
member_ids: scope.teammates.iter().map(|k| k.id.clone()).collect(),
depth: scope.delegation_depth,
+ message_id: opts.routing.as_ref().and_then(|r| r["message_id"].as_str()).map(str::to_string),
}),
cancel: Some(cancel_token.clone()),
turn_id: Some(tag.turn_id.clone()),
@@ -3446,7 +3447,6 @@ fn channel_members(channel: &crate::db::models::Channel, all_kwants: &[Kwant]) -
.collect()
}
-/// A reply's `meta.routing`: who Laya picked for a channel or team message and why.
/// The `meta.routing` a routed reply carries. `message_id` is the person's message it answers,
/// so "Wrong bot?" corrects and resends that message, not just the latest one.
pub(super) fn routing_meta(kwant: &Kwant, reason: &str, candidates: usize, fallback: bool, terms: &[String], basis: &str, message_id: &str) -> serde_json::Value {
diff --git a/tests/concierge_test.rs b/tests/concierge_test.rs
index 62f08ded..d56005bd 100644
--- a/tests/concierge_test.rs
+++ b/tests/concierge_test.rs
@@ -36,10 +36,13 @@ const FAKE_CLAUDE: &str = r#"#!/bin/sh
case "$1" in
auth) echo '{"loggedIn":true}'; exit 0 ;;
esac
+printf '%s\n' "$*" >> "$(dirname "$0")/prompts.log"
echo '{"type":"result","is_error":false,"num_turns":1,"result":"answer ok"}'
"#;
-fn fake_cli() {
+/// Installs the fake claude CLI once; returns its folder (it logs every turn's arguments to
+/// `prompts.log` there).
+fn fake_cli() -> &'static PathBuf {
static DONE: OnceLock<PathBuf> = OnceLock::new();
DONE.get_or_init(|| {
let bin = tempfile::tempdir().unwrap().keep().join("bin");
@@ -53,7 +56,7 @@ fn fake_cli() {
}
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) {
@@ -219,11 +222,16 @@ async fn call_as(app: &Router, uri: &str, token: &str, body: Value) -> (StatusCo
/// A turn of `bot` in `channel` with its own tools; returns the turn token.
async fn turn_token(state: &AppState, bot: &str, channel: &str) -> String {
+ answering_token(state, bot, channel, None).await
+}
+
+/// [`turn_token`] for a turn kwnt routed the person's message `message_id` to.
+async fn answering_token(state: &AppState, bot: &str, channel: &str, message_id: Option<&str>) -> String {
let k = state.db.get_kwant(bot).await.unwrap().unwrap();
let scope = SelfScope {
kwant_id: k.id.clone(),
kwant_name: k.name.clone(),
- origin: Some(TurnOrigin { channel_id: Some(channel.into()), ..Default::default() }),
+ origin: Some(TurnOrigin { channel_id: Some(channel.into()), message_id: message_id.map(str::to_string), ..Default::default() }),
turn_id: Some(format!("turn-{bot}")),
..Default::default()
};
@@ -329,7 +337,13 @@ async fn a_hand_back_takes_one_hop() {
assert_eq!(to, script);
let asked = last_user_message(&state, &general).await;
+ // A turn that wasn't routed a message (an @mention, a DM) has nothing to hand back
let token = turn_token(&state, &script, &general).await;
+ let (text, err) = hand_back(&app, &token, "Not mine").await;
+ assert!(err && text.contains("routed to you"), "{text}");
+ assert!(!state.db.handed_back(&asked).await.unwrap());
+
+ let token = answering_token(&state, &script, &general, Some(&asked)).await;
let (text, err) = hand_back(&app, &token, "").await;
assert!(err, "a reason is required: {text}");
let mut events = state.event_sender.subscribe();
@@ -341,7 +355,43 @@ async fn a_hand_back_takes_one_hop() {
assert_eq!(routing["message_id"], asked.as_str());
// One hop: Atlas can't bounce it on
- let token = turn_token(&state, &atlas, &general).await;
+ let token = answering_token(&state, &atlas, &general, Some(&asked)).await;
+ let (text, err) = hand_back(&app, &token, "Not mine either").await;
+ assert!(err && text.contains("already handed back"), "{text}");
+}
+
+/// In a busy channel a hand-back passes on the message the bot was answering, not the person's
+/// newest one: A goes to the Scriptwriter, B to Atlas, then the Scriptwriter hands A back.
+#[tokio::test]
+async fn a_hand_back_passes_on_the_message_it_answers_not_the_newest() {
+ 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 a_text = "Write a TikTok hook about the sitemap launch party";
+ let (to, _) = routed_to(&app, &state, &general, a_text).await;
+ assert_eq!(to, script);
+ let a = last_user_message(&state, &general).await;
+ let (to, _) = routed_to(&app, &state, &general, "Fix the crawl errors in our sitemap").await;
+ assert_eq!(to, atlas);
+ let b = last_user_message(&state, &general).await;
+ assert_ne!(a, b);
+
+ let token = answering_token(&state, &script, &general, Some(&a)).await;
+ let mut events = state.event_sender.subscribe();
+ let (text, err) = hand_back(&app, &token, "This is about the sitemap, not a script").await;
+ assert!(!err, "{text}");
+ let routing = next_reply_routing(&state, &mut events, &general).await;
+ assert_eq!((routing["basis"].as_str(), routing["kwant_id"].as_str()), (Some("handback"), Some(atlas.as_str())), "{routing}");
+ assert_eq!(routing["message_id"], a.as_str(), "A was handed on, not the newer B");
+ assert!(state.db.handed_back(&a).await.unwrap() && !state.db.handed_back(&b).await.unwrap());
+ let prompts = std::fs::read_to_string(fake_cli().join("prompts.log")).unwrap_or_default();
+ assert!(prompts.contains(&format!("{a_text}\n\n(kwnt routing note: Scriptwriter handed")), "the hand-back turn's prompt is A's text");
+ assert!(!prompts.contains("sitemap\n\n(kwnt routing note"), "B was never handed on");
+
+ // Still one hop for A
+ let token = answering_token(&state, &atlas, &general, Some(&a)).await;
let (text, err) = hand_back(&app, &token, "Not mine either").await;
assert!(err && text.contains("already handed back"), "{text}");
}
diff --git a/tests/spaces_isolation_test.rs b/tests/spaces_isolation_test.rs
index 2d0414ce..e8f60fb8 100644
--- a/tests/spaces_isolation_test.rs
+++ b/tests/spaces_isolation_test.rs
@@ -319,6 +319,7 @@ async fn delegation_without_a_member_list_stays_in_the_leads_space() {
team_id: None,
member_ids: Vec::new(),
depth: 0,
+ message_id: None,
}),
cancel: None,
turn_id: None,