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: ask on close calls, hand-back, covers/avoids

Lin (kwant bot)5016a62cb4e3
diff --git a/docs/bot-actions.md b/docs/bot-actions.md
index 05088dea..d22617eb 100644
--- a/docs/bot-actions.md
+++ b/docs/bot-actions.md
@@ -18,6 +18,7 @@ to the turn's bot and its space. Code: `src/server/bot_actions.rs`, `src/db/bot_
| `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` |
+| `hand_back` | `reason` | Only in a top-level channel turn (not threads or delegated turns): "not my area". The message goes on once to the next bot that fits, the Concierge or the lead; see `docs/channel-routing.md` |
| `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/docs/channel-routing.md b/docs/channel-routing.md
new file mode 100644
index 00000000..6b227cab
--- /dev/null
+++ b/docs/channel-routing.md
@@ -0,0 +1,43 @@
+# Channel routing
+
+A message in a channel without an @mention goes to the member that fits it best. Code:
+`src/router/team.rs` (scoring), `src/server/concierge.rs`, `src/server/rerouting.rs`.
+
+## Fit
+
+Each pick has a `fit` from 0 to 1, saved on the reply as `meta.routing.fit`.
+
+| Fit | What happens |
+|---|---|
+| ≥ 0.6 | Routed to the best member |
+| 0.4–0.6, two candidates | The person is asked (basis `ask`), in any channel. Never for @mentions or DMs |
+| < 0.4 in #general | The Concierge answers (basis `concierge`), made on first need |
+| < 0.4 elsewhere | The channel's own members, as before (lead or last speaker) |
+
+Laya's titles-only guess is a tiebreaker only; it no longer picks a bot on its own.
+
+## covers / avoids
+
+`GET /api/kwants`, `GET /api/kwants/:id` and `PUT /api/kwants/:id` carry `covers: [string]` and
+`avoids: [string]` (at most 20 entries of 60 characters; trimmed, duplicates dropped ignoring
+case). On `PUT`, a list left out stays as it is and `[]` clears it. A covered entry counts double
+in scoring; an avoided entry keeps the bot out unless it is @mentioned. Empty lists change nothing.
+Only the Concierge gets defaults.
+
+## Asking
+
+`POST /api/chat/send` returns `{status: "asking", user_message_id, route_choice_id,
+card_message_id, choices: [{kwant_id, name, title}], general: {label, name, kwant_id}}` and posts a
+system card with `meta.kind = "route_choice"`. No turn runs until the person chooses:
+
+`POST /api/route-choices/:id/resolve` with `{kwant_id}` (one of the offered bots) or
+`{general: true}` (the Concierge in #general, else the channel lead). Person only (403 for bot
+tokens); 404 unknown, 409 already chosen, 400 for neither/both or a bot that wasn't offered.
+Returns `{status: "dispatched", user_message_id, kwant, kwant_id}`; the event
+`route_choice_updated {choice}` carries the updated card meta.
+
+## Hand-back
+
+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.
diff --git a/src/db/bot_actions.rs b/src/db/bot_actions.rs
index 1fc16037..738d317a 100644
--- a/src/db/bot_actions.rs
+++ b/src/db/bot_actions.rs
@@ -352,6 +352,7 @@ impl Database {
"DELETE FROM kwant_mcp_servers WHERE kwant_id = ?1",
"DELETE FROM api_contexts WHERE kwant_id = ?1",
"DELETE FROM model_usage WHERE kwant_id = ?1",
+ "DELETE FROM kwant_scope WHERE kwant_id = ?1",
] {
sqlx::query(sql).bind(id).execute(&mut *tx).await?;
}
diff --git a/src/db/mod.rs b/src/db/mod.rs
index b7ad0fa3..31d0bc57 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -35,6 +35,7 @@ pub mod auditor;
pub mod foundry;
pub mod automation;
pub mod truth_ledger;
+pub mod routing;
/// What a space's #general says about itself.
pub const GENERAL_DESCRIPTION: &str = "Everyone in this space. Laya picks who answers.";
@@ -174,6 +175,7 @@ impl Database {
db.migrate_mission_graph().await?;
db.migrate_checkpoints().await?;
db.migrate_autofix().await?;
+ db.migrate_routing().await?;
if spaces {
let migration = db.migrate_spaces(data_dir, fresh).await?;
db.require_spaces_schema(&migration).await?;
diff --git a/src/db/models.rs b/src/db/models.rs
index 11721e16..f5e07287 100644
--- a/src/db/models.rs
+++ b/src/db/models.rs
@@ -347,6 +347,13 @@ pub struct KwantView {
/// Which sites the bot's browser may open.
#[serde(flatten)]
pub browser: super::browser_sites::BrowserSites,
+ #[serde(default)]
+ /// What the bot is for, in the person's words: routing counts these like words in its title.
+ pub covers: Vec<String>,
+ #[serde(default)]
+ /// What it is not for: a message with one of these words isn't routed to it by its role or
+ /// words (naming or @mentioning it still is).
+ pub avoids: Vec<String>,
}
/// One LLM account for an engine. Holds no secret: API keys live in `llm_profile_secrets`.
diff --git a/src/db/profiles.rs b/src/db/profiles.rs
index d7406ef0..e3a435dc 100644
--- a/src/db/profiles.rs
+++ b/src/db/profiles.rs
@@ -308,11 +308,14 @@ impl Database {
pub async fn kwant_views(&self, space: &SpaceId) -> Result<Vec<KwantView>, DbError> {
let kwants = self.list_kwants(space).await?;
let mut bindings = self.list_kwant_bindings(space).await?;
+ let ids: Vec<String> = kwants.iter().map(|k| k.id.clone()).collect();
+ let mut scopes = self.scopes_for(&ids).await?;
let mut views = Vec::with_capacity(kwants.len());
for kwant in kwants {
let (profile_id, profile_failover) = bindings.remove(&kwant.id).unwrap_or((None, true));
let browser = self.browser_sites(&kwant.id).await?;
- views.push(KwantView { kwant, profile_id, profile_failover, browser });
+ let scope = scopes.remove(&kwant.id).unwrap_or_default();
+ views.push(KwantView { kwant, profile_id, profile_failover, browser, covers: scope.covers, avoids: scope.avoids });
}
Ok(views)
}
@@ -324,11 +327,14 @@ impl Database {
let (profile_id, profile_failover) =
self.get_kwant_binding(id).await?.unwrap_or((None, true));
let browser = self.browser_sites(id).await?;
+ let scope = self.get_scope(id).await?;
Ok(Some(KwantView {
kwant,
profile_id,
profile_failover,
browser,
+ covers: scope.covers,
+ avoids: scope.avoids,
}))
}
}
diff --git a/src/db/routing.rs b/src/db/routing.rs
new file mode 100644
index 00000000..d6367f70
--- /dev/null
+++ b/src/db/routing.rs
@@ -0,0 +1,223 @@
+//! What channel routing keeps between messages: each bot's covers/avoids lists, the choices the
+//! person was asked to make on a close call, and the one hand-back a message may take.
+
+use super::{Database, DbError};
+use chrono::{DateTime, Utc};
+use serde::Serialize;
+use sqlx::FromRow;
+use std::collections::HashMap;
+use uuid::Uuid;
+
+/// Entries a covers or avoids list keeps.
+pub const MAX_SCOPE_ENTRIES: usize = 20;
+/// Characters one entry keeps.
+pub const MAX_SCOPE_ENTRY_CHARS: usize = 60;
+
+/// What a bot is for and not for, in the person's words ("restaurants", "travel"). Empty lists
+/// leave routing as it was.
+#[derive(Debug, Clone, Default, Serialize, PartialEq)]
+pub struct Scope {
+ pub covers: Vec<String>,
+ pub avoids: Vec<String>,
+}
+
+/// Trims, drops blanks and repeats (ignoring case), and caps the list; `Err` names what's wrong.
+pub fn clean_scope_list(raw: &[String]) -> Result<Vec<String>, String> {
+ let mut out: Vec<String> = Vec::new();
+ for e in raw {
+ let e = e.trim();
+ if e.is_empty() || out.iter().any(|o| o.eq_ignore_ascii_case(e)) {
+ continue;
+ }
+ if e.chars().count() > MAX_SCOPE_ENTRY_CHARS {
+ return Err(format!("each entry is at most {MAX_SCOPE_ENTRY_CHARS} characters"));
+ }
+ out.push(e.to_string());
+ }
+ if out.len() > MAX_SCOPE_ENTRIES {
+ return Err(format!("at most {MAX_SCOPE_ENTRIES} entries"));
+ }
+ Ok(out)
+}
+
+/// A close call the person was asked to settle: the best two bots, or a general answer.
+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]
+pub struct RouteChoice {
+ pub id: String,
+ pub space_id: String,
+ pub channel_id: String,
+ /// The person's message waiting for the choice.
+ pub user_message_id: String,
+ /// What the chosen bot is sent: the message with any attachment notes.
+ #[serde(skip)]
+ pub prompt: String,
+ /// The card that asks.
+ pub card_message_id: Option<String>,
+ /// JSON array of the offered bot ids, best first.
+ pub choices: String,
+ /// "open" or "resolved".
+ pub status: String,
+ pub chosen_kwant_id: Option<String>,
+ /// True when the person picked a general answer.
+ pub general: bool,
+ pub created_at: DateTime<Utc>,
+ pub resolved_at: Option<DateTime<Utc>>,
+}
+
+impl RouteChoice {
+ pub fn choice_ids(&self) -> Vec<String> {
+ serde_json::from_str(&self.choices).unwrap_or_default()
+ }
+}
+
+impl Database {
+ pub(super) async fn migrate_routing(&self) -> Result<(), DbError> {
+ for stmt in [
+ "CREATE TABLE IF NOT EXISTS kwant_scope (
+ kwant_id TEXT PRIMARY KEY,
+ covers TEXT NOT NULL DEFAULT '[]',
+ avoids TEXT NOT NULL DEFAULT '[]'
+ )",
+ "CREATE TABLE IF NOT EXISTS route_choices (
+ id TEXT PRIMARY KEY,
+ space_id TEXT NOT NULL,
+ channel_id TEXT NOT NULL,
+ user_message_id TEXT NOT NULL UNIQUE,
+ prompt TEXT NOT NULL,
+ card_message_id TEXT,
+ choices TEXT NOT NULL,
+ status TEXT NOT NULL CHECK (status IN ('open', 'resolved')),
+ chosen_kwant_id TEXT,
+ general INTEGER NOT NULL DEFAULT 0,
+ created_at TIMESTAMP NOT NULL,
+ resolved_at TIMESTAMP
+ )",
+ // One hand-back per message, ever: a second "not my area" can't bounce it on
+ "CREATE TABLE IF NOT EXISTS route_handbacks (
+ id TEXT PRIMARY KEY,
+ user_message_id TEXT NOT NULL UNIQUE,
+ from_kwant_id TEXT NOT NULL,
+ to_kwant_id TEXT NOT NULL,
+ reason TEXT NOT NULL,
+ created_at TIMESTAMP NOT NULL
+ )",
+ ] {
+ sqlx::query(stmt).execute(&self.pool).await?;
+ }
+ Ok(())
+ }
+
+ pub async fn get_scope(&self, kwant_id: &str) -> Result<Scope, DbError> {
+ Ok(self.scopes_for(&[kwant_id.to_string()]).await?.remove(kwant_id).unwrap_or_default())
+ }
+
+ /// The scopes of `kwant_ids` that have one; a bot without a row has empty lists.
+ pub async fn scopes_for(&self, kwant_ids: &[String]) -> Result<HashMap<String, Scope>, DbError> {
+ let rows: Vec<(String, String, String)> = sqlx::query_as("SELECT kwant_id, covers, avoids FROM kwant_scope").fetch_all(&self.pool).await?;
+ Ok(rows
+ .into_iter()
+ .filter(|(id, _, _)| kwant_ids.contains(id))
+ .map(|(id, c, a)| {
+ let scope = Scope { covers: serde_json::from_str(&c).unwrap_or_default(), avoids: serde_json::from_str(&a).unwrap_or_default() };
+ (id, scope)
+ })
+ .collect())
+ }
+
+ /// Replaces the lists given (`None` keeps that list as it is).
+ pub async fn set_scope(&self, kwant_id: &str, covers: Option<&[String]>, avoids: Option<&[String]>) -> Result<Scope, DbError> {
+ let mut scope = self.get_scope(kwant_id).await?;
+ if let Some(c) = covers {
+ scope.covers = c.to_vec();
+ }
+ if let Some(a) = avoids {
+ scope.avoids = a.to_vec();
+ }
+ sqlx::query("INSERT INTO kwant_scope (kwant_id, covers, avoids) VALUES (?1, ?2, ?3) ON CONFLICT(kwant_id) DO UPDATE SET covers = ?2, avoids = ?3")
+ .bind(kwant_id)
+ .bind(serde_json::to_string(&scope.covers).unwrap_or_else(|_| "[]".into()))
+ .bind(serde_json::to_string(&scope.avoids).unwrap_or_else(|_| "[]".into()))
+ .execute(&self.pool)
+ .await?;
+ Ok(scope)
+ }
+
+ pub async fn add_route_choice(&self, space_id: &str, channel_id: &str, user_message_id: &str, prompt: &str, choices: &[String]) -> Result<RouteChoice, DbError> {
+ let id = Uuid::new_v4().to_string();
+ sqlx::query(
+ "INSERT INTO route_choices (id, space_id, channel_id, user_message_id, prompt, choices, status, created_at)
+ VALUES (?1, ?2, ?3, ?4, ?7, ?5, 'open', ?6)",
+ )
+ .bind(&id)
+ .bind(space_id)
+ .bind(channel_id)
+ .bind(user_message_id)
+ .bind(serde_json::to_string(choices).unwrap_or_else(|_| "[]".into()))
+ .bind(Utc::now())
+ .bind(prompt)
+ .execute(&self.pool)
+ .await?;
+ Ok(self.get_route_choice(&id).await?.expect("just inserted"))
+ }
+
+ pub async fn set_route_choice_card(&self, id: &str, card_message_id: &str) -> Result<(), DbError> {
+ sqlx::query("UPDATE route_choices SET card_message_id = ?2 WHERE id = ?1").bind(id).bind(card_message_id).execute(&self.pool).await?;
+ Ok(())
+ }
+
+ pub async fn get_route_choice(&self, id: &str) -> Result<Option<RouteChoice>, DbError> {
+ Ok(sqlx::query_as("SELECT * FROM route_choices WHERE id = ?1").bind(id).fetch_optional(&self.pool).await?)
+ }
+
+ /// Settles an open choice; `false` when it was already settled (a second tap does nothing).
+ pub async fn resolve_route_choice(&self, id: &str, kwant_id: &str, general: bool) -> Result<bool, DbError> {
+ let done = sqlx::query(
+ "UPDATE route_choices SET status = 'resolved', chosen_kwant_id = ?2, general = ?3, resolved_at = ?4
+ WHERE id = ?1 AND status = 'open'",
+ )
+ .bind(id)
+ .bind(kwant_id)
+ .bind(general)
+ .bind(Utc::now())
+ .execute(&self.pool)
+ .await?;
+ Ok(done.rows_affected() == 1)
+ }
+
+ /// Records the one hand-back of `user_message_id`; `false` when it already took its hop.
+ pub async fn add_route_handback(&self, user_message_id: &str, from: &str, to: &str, reason: &str) -> Result<bool, DbError> {
+ let done = sqlx::query(
+ "INSERT OR IGNORE INTO route_handbacks (id, user_message_id, from_kwant_id, to_kwant_id, reason, created_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
+ )
+ .bind(Uuid::new_v4().to_string())
+ .bind(user_message_id)
+ .bind(from)
+ .bind(to)
+ .bind(reason)
+ .bind(Utc::now())
+ .execute(&self.pool)
+ .await?;
+ Ok(done.rows_affected() == 1)
+ }
+
+ pub async fn handed_back(&self, user_message_id: &str) -> Result<bool, DbError> {
+ let row: Option<(String,)> =
+ sqlx::query_as("SELECT id FROM route_handbacks WHERE user_message_id = ?1").bind(user_message_id).fetch_optional(&self.pool).await?;
+ Ok(row.is_some())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn scope_lists_are_cleaned_and_capped() {
+ let raw = vec![" food ".into(), "".into(), "Food".into(), "travel".into()];
+ assert_eq!(clean_scope_list(&raw).unwrap(), vec!["food".to_string(), "travel".to_string()]);
+ assert!(clean_scope_list(&["x".repeat(61)]).is_err());
+ let many: Vec<String> = (0..21).map(|i| format!("t{i}")).collect();
+ assert!(clean_scope_list(&many).is_err());
+ }
+}
diff --git a/src/drivers/events.rs b/src/drivers/events.rs
index e968ce4f..84a9a197 100644
--- a/src/drivers/events.rs
+++ b/src/drivers/events.rs
@@ -117,6 +117,10 @@ pub enum RuntimeEvent {
/// whole proposal with its `card`. See `crate::db::hires` and docs/bot-actions.md → "Hiring".
#[serde(rename = "hire_updated", alias = "HireUpdated")]
HireUpdated { hire: Value },
+ /// A close call the person was asked to settle was asked or settled; `choice` is its card's
+ /// meta (see `crate::server::rerouting`).
+ #[serde(rename = "route_choice_updated", alias = "RouteChoiceUpdated")]
+ RouteChoiceUpdated { choice: Value },
/// Flight School (C4): a bot proposed a tier, or the person granted, declined or kwant marked
/// a proposal stale. `capability` is `{space_id, kwant_id, task_class, proposal?}`; clients
/// reload `GET /api/capabilities`. See docs/mission-control.md §14.
diff --git a/src/router/team.rs b/src/router/team.rs
index bf4f0d53..27fef70b 100644
--- a/src/router/team.rs
+++ b/src/router/team.rs
@@ -138,6 +138,20 @@ impl LayaRouter {
lead_kwant_id: &str,
members: &[Kwant],
last_speaker: Option<&str>,
+ ) -> ChannelRoute {
+ self.route_channel_query_hinted(prompt, channel_name, lead_kwant_id, members, last_speaker, &Hints::default()).await
+ }
+
+ /// [`Self::route_channel_query_after`] with what the space knows beyond names and titles: each
+ /// bot's covers/avoids lists (see [`Hints`]).
+ pub async fn route_channel_query_hinted(
+ &self,
+ prompt: &str,
+ channel_name: &str,
+ lead_kwant_id: &str,
+ members: &[Kwant],
+ last_speaker: Option<&str>,
+ hints: &Hints,
) -> ChannelRoute {
let started = std::time::Instant::now();
let mut why_not_laya = None;
@@ -161,7 +175,7 @@ impl LayaRouter {
}
};
let fallback = laya.is_none();
- let route = match pick_member_after(prompt, lead_kwant_id, members, laya, "channel lead", last_speaker) {
+ let route = match pick_member_hinted(prompt, lead_kwant_id, members, laya, "channel lead", last_speaker, hints) {
Some(p) => ChannelRoute {
kwant_id: p.kwant.id.clone(),
reason: if fallback { format!("{}. {}", p.reason, self.offline_note()) } else { p.reason },
@@ -584,6 +598,56 @@ pub fn pick_member_after<'a>(
laya: Option<LayaGuess<'a>>,
lead_word: &str,
last_speaker: Option<&str>,
+) -> Option<Pick<'a>> {
+ pick_member_hinted(prompt, lead_kwant_id, members, laya, lead_word, last_speaker, &Hints::default())
+}
+
+/// What a space knows about its bots beyond names and titles.
+#[derive(Debug, Clone, Default)]
+pub struct Hints {
+ /// Each bot's covers/avoids lists, by bot id. A bot without one routes as before.
+ pub scopes: std::collections::HashMap<String, crate::db::routing::Scope>,
+}
+
+impl Hints {
+ /// The entries of `kwant`'s covers list that the message has every word of.
+ fn covered(&self, kwant: &Kwant, words: &[String]) -> Vec<String> {
+ self.scopes.get(&kwant.id).map(|s| s.covers.iter().filter(|e| entry_in(e, words)).map(|e| e.to_lowercase()).collect()).unwrap_or_default()
+ }
+
+ /// The message has every word of an entry in `kwant`'s avoids list.
+ fn avoids(&self, kwant: &Kwant, words: &[String]) -> bool {
+ self.scopes.get(&kwant.id).is_some_and(|s| s.avoids.iter().any(|e| entry_in(e, words)))
+ }
+}
+
+/// Words compared for covers/avoids: lowercased, a plural's "s" dropped ("restaurants" ~ "restaurant").
+fn scope_words(text: &str) -> Vec<String> {
+ tokens(text)
+ .into_iter()
+ .filter(|w| !STOP_WORDS.contains(&w.as_str()))
+ .map(|w| if w.len() > 4 { w.strip_suffix('s').map(str::to_string).unwrap_or(w) } else { w })
+ .collect()
+}
+
+/// Every word of a covers/avoids entry ("street food") is in the message.
+fn entry_in(entry: &str, words: &[String]) -> bool {
+ let need = scope_words(entry);
+ !need.is_empty() && need.iter().all(|n| words.contains(n))
+}
+
+/// [`pick_member_after`] with [`Hints`]: an entry of a bot's covers list in the message counts
+/// like a word of its title, and an entry of its avoids list keeps role and word matching off it
+/// (naming or @mentioning it still picks it).
+#[allow(clippy::too_many_arguments)]
+pub fn pick_member_hinted<'a>(
+ prompt: &str,
+ lead_kwant_id: &str,
+ members: &'a [Kwant],
+ laya: Option<LayaGuess<'a>>,
+ lead_word: &str,
+ last_speaker: Option<&str>,
+ hints: &Hints,
) -> Option<Pick<'a>> {
let only = match members {
[] => return None,
@@ -654,8 +718,13 @@ pub fn pick_member_after<'a>(
// 3. The request's words belong to a role
let role_words = role_words(prompt);
- let roles: Vec<(&Kwant, usize, Vec<String>)> =
- members.iter().map(|m| (m, role_score(&role_words, m))).map(|(m, (s, t))| (m, s, t)).collect();
+ let scope_words = scope_words(prompt);
+ let avoided = |k: &Kwant| hints.avoids(k, &scope_words);
+ let roles: Vec<(&Kwant, usize, Vec<String>)> = members
+ .iter()
+ .map(|m| (m, if avoided(m) { (0, vec![]) } else { role_score(&role_words, m) }))
+ .map(|(m, (s, t))| (m, s, t))
+ .collect();
let strong: Vec<&(&Kwant, usize, Vec<String>)> = roles.iter().filter(|(_, s, _)| *s >= 2).collect();
let distinct_roles = |set: &[&(&Kwant, usize, Vec<String>)]| {
let mut terms: Vec<Vec<String>> = set.iter().map(|(_, _, t)| { let mut t = t.clone(); t.sort(); t }).collect();
@@ -706,7 +775,22 @@ pub fn pick_member_after<'a>(
// "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();
+ // An entry of a bot's covers list counts like a word of its title.
+ let matches: Vec<Vec<(String, usize)>> = members
+ .iter()
+ .map(|m| {
+ if avoided(m) {
+ return vec![];
+ }
+ let mut terms = relevance_terms(prompt, m);
+ for e in hints.covered(m, &scope_words) {
+ if !terms.iter().any(|(t, _)| *t == e) {
+ terms.push((e, 2));
+ }
+ }
+ terms
+ })
+ .collect();
let shared = |w: &str| matches.iter().filter(|terms| terms.iter().any(|(t, _)| t == w)).count() > 1;
// (bot, score, terms, whether a term matched its name or title rather than only its persona)
let scored: Vec<(&Kwant, usize, Vec<String>, bool)> = members
@@ -764,7 +848,7 @@ pub fn pick_member_after<'a>(
// 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)) {
+ if let Some(k) = last_speaker.and_then(|id| members.iter().find(|m| m.id == id)).filter(|k| !avoided(k)) {
// "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);
@@ -823,18 +907,28 @@ pub fn reads_as_follow_up(prompt: &str) -> bool {
pub enum Settle {
/// Send it to the picked bot.
Route,
+ /// A close call: ask the person to choose between these two bots (ids, best first) or a
+ /// general answer.
+ Ask(Vec<String>),
/// 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.
+/// A fit of at least [`ROUTE_AT`] routes. A close call ([`ASK_FROM`] up to [`ROUTE_AT`], with two
+/// candidates) asks the person. Below that, #general (every bot in the space) leans to the
+/// Concierge 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 {
+ if route.fit >= ROUTE_AT {
return Settle::Route;
}
- Settle::Concierge
+ if route.fit >= ASK_FROM && route.choices.len() >= 2 {
+ return Settle::Ask(route.choices.iter().take(2).cloned().collect());
+ }
+ if general && has_concierge {
+ return Settle::Concierge;
+ }
+ Settle::Route
}
/// Said to the lead with a team-building request, so it proposes the bots instead of treating the
@@ -1527,4 +1621,58 @@ mod fit_tests {
}
assert!(!reads_as_follow_up("Best place to eat corn dogs in Munich tomorrow?"));
}
+
+ fn hints(id: &str, covers: &[&str], avoids: &[&str]) -> Hints {
+ let scope = crate::db::routing::Scope {
+ covers: covers.iter().map(|s| s.to_string()).collect(),
+ avoids: avoids.iter().map(|s| s.to_string()).collect(),
+ };
+ Hints { scopes: [(id.to_string(), scope)].into_iter().collect() }
+ }
+
+ /// Two bots with the same role and the same words: a close call, so the person is asked to
+ /// choose between them (or a general answer), in #general and elsewhere. @mentions never ask.
+ #[test]
+ fn a_close_call_asks_the_person() {
+ let members = vec![
+ bot("k-fe", "Bea", "Frontend engineer", "You build the app's pages."),
+ bot("k-web", "Cy", "Web developer", "You build websites."),
+ bot("k-seo", "Atlas", "Technical SEO", "You audit sites."),
+ ];
+ let p = pick_member_after("The button CSS is off on mobile Safari", "k-seo", &members, None, "channel lead", None).unwrap();
+ assert!((ASK_FROM..ROUTE_AT).contains(&p.fit), "{p:?}");
+ let ask = Settle::Ask(vec!["k-fe".into(), "k-web".into()]);
+ assert_eq!(settle(&route_of(&p), true, true), ask);
+ assert_eq!(settle(&route_of(&p), false, false), ask);
+ let p = pick_member_after("@Bea the button CSS is off", "k-seo", &members, None, "channel lead", None).unwrap();
+ assert_eq!((p.kwant.id.as_str(), settle(&route_of(&p), true, true)), ("k-fe", Settle::Route));
+ }
+
+ /// An entry of a bot's covers list counts like a word of its title; empty lists change nothing.
+ #[test]
+ fn covers_route_a_message_to_the_bot_that_covers_it() {
+ let members = general();
+ let prompt = "Best place to eat corn dogs in Munich tomorrow?";
+ let none = pick_member_hinted(prompt, "k-lead", &members, None, "channel lead", None, &Hints::default()).unwrap();
+ assert_eq!(none.fit, 0.0);
+ let h = hints("k-lead", &["corn dogs", "restaurants"], &[]);
+ let p = pick_member_hinted(prompt, "k-lead", &members, None, "channel lead", None, &h).unwrap();
+ assert_eq!(p.kwant.id, "k-lead", "{p:?}");
+ assert!(p.fit >= ROUTE_AT, "{p:?}");
+ // A plural matches its singular entry
+ let p = pick_member_hinted("Any restaurants near the venue?", "k-seo", &members, None, "channel lead", None, &h).unwrap();
+ assert_eq!(p.kwant.id, "k-lead", "{p:?}");
+ }
+
+ /// An entry of a bot's avoids list keeps role and word matching off it; naming it still works.
+ #[test]
+ fn avoids_keep_a_bot_out_unless_it_is_named() {
+ let members = general();
+ let h = hints("k-script", &[], &["fantasy"]);
+ let prompt = "Write a TikTok hook for this fantasy book";
+ let p = pick_member_hinted(prompt, "k-lead", &members, None, "channel lead", Some("k-script"), &h).unwrap();
+ assert_ne!(p.kwant.id, "k-script", "{p:?}");
+ let p = pick_member_hinted("Scriptwriter, a hook for this fantasy book", "k-lead", &members, None, "channel lead", None, &h).unwrap();
+ assert_eq!(p.kwant.id, "k-script", "{p:?}");
+ }
}
diff --git a/src/server/concierge.rs b/src/server/concierge.rs
index 61a72797..a4e2dfa3 100644
--- a/src/server/concierge.rs
+++ b/src/server/concierge.rs
@@ -17,6 +17,12 @@ 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.";
+/// What it covers, seeded when it is made so the person sees (and can edit) what it is for. Role
+/// scoring never picks it, so these only describe it.
+pub const COVERS: &[&str] = &[
+ "everyday questions", "recommendations", "food", "restaurants", "travel", "places", "events", "quick facts",
+ "planning", "shopping", "general knowledge",
+];
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 {
@@ -90,6 +96,8 @@ pub async fn for_no_match(app: &AppState, space: &SpaceId, channel_id: &str, all
return None;
}
let _ = app.db.set_setting(&key(space), &id).await;
+ let covers: Vec<String> = COVERS.iter().map(|c| c.to_string()).collect();
+ let _ = app.db.set_scope(&id, Some(&covers), None).await;
let new = NewBotAction {
space_id: space.as_str().to_string(),
kwant_id: id.clone(),
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index 10eb4d40..59baf7a5 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -521,6 +521,9 @@ fn tool_list(scope: &SelfScope, board: bool) -> Value {
if scope.sandbox_target.is_some() {
list.extend(browser_tools());
}
+ if scope.origin.as_ref().is_some_and(|o| o.channel_id.is_some() && o.thread_id.is_none() && o.depth == 0) {
+ list.push(super::rerouting::tool());
+ }
if scope.origin.is_some() {
list.extend(delegation_tools());
list.extend(super::attachments::tools());
@@ -1105,6 +1108,7 @@ async fn call_tool(
Some(target) => call_browser_tool(state, scope, target, name, args).await,
None => (format!("Unknown tool {name}."), true),
},
+ super::rerouting::HAND_BACK => super::rerouting::tool_call(state, scope, args).await,
"skill_propose" => super::skills::tool_propose(state, scope, args).await,
super::missions::foundry::TOOL => super::missions::foundry::call(state, scope, args).await,
"skill_get" => super::skills::tool_get(state, scope, args).await,
diff --git a/src/server/mod.rs b/src/server/mod.rs
index af978da4..1902e668 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -33,6 +33,7 @@ pub mod connection_suggest;
pub mod bot_actions;
pub mod hires;
pub mod concierge;
+pub mod rerouting;
pub mod import_routes;
pub mod approval_modes;
pub mod passwords;
@@ -326,6 +327,7 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/bot-actions/:id/undo", post(bot_actions::undo))
.route("/api/bot-actions/:id/confirm", post(bot_actions::confirm))
.route("/api/bot-actions/:id/decline", post(bot_actions::decline))
+ .route("/api/route-choices/:id/resolve", post(rerouting::resolve_route))
.route("/api/hires", get(hires::list))
.route("/api/hires/:id/accept", post(hires::accept_route))
.route("/api/hires/:id/deny", post(hires::deny_route))
diff --git a/src/server/rerouting.rs b/src/server/rerouting.rs
new file mode 100644
index 00000000..75e441a7
--- /dev/null
+++ b/src/server/rerouting.rs
@@ -0,0 +1,326 @@
+//! A channel message that doesn't go straight to one bot: a close call the person settles on a
+//! card ("ask"), and a bot handing a message it got back as not its area ("handback").
+//!
+//! - 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.
+//!
+//! Contract: /home/maus/shared/ship-software-safely/router-concierge/contract.md
+
+use super::continuity::SelfScope;
+use super::AppState;
+use crate::db::models::{Kwant, MessageExtra, NewMessage};
+use crate::db::routing::RouteChoice;
+use crate::db::spaces::SpaceId;
+use crate::drivers::events::RuntimeEvent;
+use crate::router::team::{Hints, ROUTE_AT};
+use axum::{
+ extract::{Path, State},
+ http::{HeaderMap, StatusCode},
+ response::{IntoResponse, Response},
+ Json,
+};
+use serde::Deserialize;
+use serde_json::{json, Value};
+
+pub const HAND_BACK: &str = "hand_back";
+
+/// The space's covers/avoids lists for routing among `members`.
+pub(super) async fn hints_for(state: &AppState, members: &[Kwant]) -> Hints {
+ let ids: Vec<String> = members.iter().map(|k| k.id.clone()).collect();
+ Hints { scopes: state.db.scopes_for(&ids).await.unwrap_or_default() }
+}
+
+fn error(status: StatusCode, msg: &str) -> Response {
+ (status, Json(json!({"error": msg}))).into_response()
+}
+
+/// Who answers "Answer generally": the Concierge in #general (made now if needed, unless the
+/// person removed it), else the channel's lead. `None` only when neither exists.
+async fn general_answerer(state: &AppState, space: &SpaceId, channel: &crate::db::models::Channel, all: &[Kwant]) -> Option<Kwant> {
+ if channel.name == "general" {
+ if let Some(c) = super::concierge::for_no_match(state, space, &channel.id, all).await {
+ return Some(c);
+ }
+ }
+ all.iter().find(|k| k.id == channel.lead_kwant_id).cloned()
+}
+
+/// The words on the general option, before anyone is made: "Concierge" when #general has one or
+/// would make one, else the lead's name.
+async fn general_label(state: &AppState, space: &SpaceId, channel: &crate::db::models::Channel, all: &[Kwant]) -> (String, Option<String>) {
+ if channel.name == "general" {
+ match super::concierge::state(state, space, all).await {
+ super::concierge::State::Present(k) => return (k.name.clone(), Some(k.id.clone())),
+ super::concierge::State::None => return (super::concierge::NAME.to_string(), None),
+ super::concierge::State::Removed => {}
+ }
+ }
+ match all.iter().find(|k| k.id == channel.lead_kwant_id) {
+ Some(k) => (k.name.clone(), Some(k.id.clone())),
+ None => (String::new(), None),
+ }
+}
+
+fn card_meta(c: &RouteChoice, offered: &[Kwant], general: &(String, Option<String>), reason: &str) -> Value {
+ json!({
+ "kind": "route_choice",
+ "route_choice_id": c.id,
+ "space_id": c.space_id,
+ "channel_id": c.channel_id,
+ "user_message_id": c.user_message_id,
+ "status": c.status,
+ "reason": reason,
+ "choices": offered.iter().map(|k| json!({"kwant_id": k.id, "name": k.name, "title": k.title})).collect::<Vec<_>>(),
+ "general": {"label": "Answer generally", "name": general.0, "kwant_id": general.1},
+ "chosen_kwant_id": c.chosen_kwant_id,
+ "chose_general": c.general,
+ })
+}
+
+fn card_text(offered: &[Kwant]) -> String {
+ let names: Vec<String> = offered.iter().map(|k| format!("{} ({})", k.name, k.title)).collect();
+ format!("Who should answer this? It could be {}, or a general answer.", names.join(" or "))
+}
+
+/// Posts the card asking who answers `user_message_id` and returns the send route's response
+/// (`status: "asking"`). No turn runs until the person chooses.
+#[allow(clippy::too_many_arguments)]
+pub(super) async fn ask(
+ state: &AppState,
+ space: &SpaceId,
+ channel: &crate::db::models::Channel,
+ all: &[Kwant],
+ user_message_id: &str,
+ prompt: &str,
+ offered: &[Kwant],
+ reason: &str,
+) -> Result<Value, StatusCode> {
+ let ids: Vec<String> = offered.iter().map(|k| k.id.clone()).collect();
+ let c = state
+ .db
+ .add_route_choice(space.as_str(), &channel.id, user_message_id, prompt, &ids)
+ .await
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
+ let general = general_label(state, space, channel, all).await;
+ let meta = card_meta(&c, offered, &general, reason);
+ let msg = NewMessage {
+ channel_id: Some(channel.id.clone()),
+ direct_kwant_id: None,
+ sender_role: "system".into(),
+ sender_id: "kwnt".into(),
+ text: card_text(offered),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ };
+ let card = state
+ .db
+ .insert_message_with(&msg, &MessageExtra { thread_id: None, meta: Some(meta.clone()) })
+ .await
+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
+ let _ = state.db.set_route_choice_card(&c.id, &card.id).await;
+ let _ = state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&card).unwrap_or(Value::Null) });
+ let _ = state.event_sender.send(RuntimeEvent::RouteChoiceUpdated { choice: meta.clone() });
+ tracing::info!(route_choice = %c.id, channel = %channel.id, "asked the person who answers a close call");
+ Ok(json!({
+ "status": "asking",
+ "user_message_id": user_message_id,
+ "route_choice_id": c.id,
+ "card_message_id": card.id,
+ "choices": meta["choices"],
+ "general": meta["general"],
+ }))
+}
+
+#[derive(Debug, Deserialize)]
+pub struct ResolveBody {
+ #[serde(default)]
+ pub kwant_id: Option<String>,
+ #[serde(default)]
+ pub general: bool,
+}
+
+/// `POST /api/route-choices/:id/resolve` `{kwant_id}` or `{general: true}`: the person settles a
+/// close call and the chosen bot answers the waiting message. Person only. 409 when it was
+/// already settled, 400 for a bot that wasn't offered.
+pub async fn resolve_route(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>, Json(body): Json<ResolveBody>) -> Response {
+ if let Err(r) = super::mcp_suggest::refuse_agent_tokens(&state, &headers, "only the person chooses who answers").await {
+ return r;
+ }
+ let Ok(Some(c)) = state.db.get_route_choice(&id).await else {
+ return error(StatusCode::NOT_FOUND, "no such choice");
+ };
+ if c.status != "open" {
+ return error(StatusCode::CONFLICT, "already chosen");
+ }
+ let space = SpaceId::new(&c.space_id);
+ let Ok(Some(channel)) = state.db.get_channel(&c.channel_id).await else {
+ return error(StatusCode::NOT_FOUND, "the channel is gone");
+ };
+ let all = state.db.list_kwants(&space).await.unwrap_or_default();
+ let offered: Vec<Kwant> = c.choice_ids().iter().filter_map(|i| all.iter().find(|k| &k.id == i).cloned()).collect();
+ let kwant = match (&body.kwant_id, body.general) {
+ (Some(_), true) | (None, false) => return error(StatusCode::BAD_REQUEST, "send kwant_id or general: true"),
+ (Some(k), false) => match offered.iter().find(|o| &o.id == k) {
+ Some(o) => o.clone(),
+ None => return error(StatusCode::BAD_REQUEST, "that bot wasn't offered"),
+ },
+ (None, true) => match general_answerer(&state, &space, &channel, &all).await {
+ Some(k) => k,
+ None => return error(StatusCode::CONFLICT, "no one here can answer generally"),
+ },
+ };
+ match state.db.resolve_route_choice(&id, &kwant.id, body.general).await {
+ Ok(true) => {}
+ Ok(false) => return error(StatusCode::CONFLICT, "already chosen"),
+ Err(_) => return error(StatusCode::INTERNAL_SERVER_ERROR, "could not save the choice"),
+ }
+ let c = state.db.get_route_choice(&id).await.ok().flatten().unwrap_or(c);
+ let general = general_label(&state, &space, &channel, &all).await;
+ let reason = if body.general {
+ format!("You asked for a general answer, so {} answers", kwant.name)
+ } else {
+ format!("You chose {} ({}) for this", kwant.name, kwant.title)
+ };
+ let meta = card_meta(&c, &offered, &general, &reason);
+ if let Some(mid) = &c.card_message_id {
+ let _ = state.db.set_message_meta(mid, &meta).await;
+ }
+ let _ = state.event_sender.send(RuntimeEvent::RouteChoiceUpdated { choice: meta });
+ let candidates = offered.len() + 1;
+ let mut routing = super::routes::routing_meta(&kwant, &reason, candidates, false, &[], "ask");
+ routing["route_choice_id"] = json!(c.id);
+ let (st, k, um, ch, prompt) = (state.clone(), kwant.clone(), c.user_message_id.clone(), c.channel_id.clone(), c.prompt.clone());
+ tokio::spawn(async move {
+ if let Err(e) = super::routes::run_routed_turn(&st, &k, Some(ch), None, prompt, Some(routing), vec![um]).await {
+ tracing::warn!(error = %e, kwant = %k.id, "the chosen bot's turn didn't finish");
+ }
+ });
+ Json(json!({"status": "dispatched", "user_message_id": c.user_message_id, "kwant": kwant.name, "kwant_id": kwant.id})).into_response()
+}
+
+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 \
+ 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.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "reason": {"type": "string", "description": "Why this isn't your area, in one sentence for the person"},
+ },
+ "required": ["reason"],
+ },
+ })
+}
+
+type ToolResult = (String, bool);
+
+/// The `hand_back` tool: one hop to the next best bot, else the Concierge, else the lead.
+pub async fn tool_call(state: &AppState, scope: &SelfScope, args: &Value) -> ToolResult {
+ let reason = args["reason"].as_str().map(str::trim).filter(|r| !r.is_empty());
+ let Some(reason) = reason else {
+ return ("Say why in `reason`.".into(), true);
+ };
+ let reason: String = reason.chars().take(300).collect();
+ let Some(origin) = scope.origin.as_ref().filter(|o| o.depth == 0 && o.thread_id.is_none()) else {
+ return ("hand_back works only for a message the person sent in a channel.".into(), true);
+ };
+ 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 {
+ 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> {
+ let Ok(Some(channel)) = state.db.get_channel(channel_id).await else {
+ return Err("Could not find this channel.".into());
+ };
+ let Ok(Some(from)) = state.db.get_kwant(from_id).await else {
+ 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());
+ };
+ 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());
+ }
+ let all = state.db.list_kwants(&space).await.unwrap_or_default();
+ let concierge = super::concierge::id(state, &space, &all).await;
+ let members: Vec<Kwant> = super::routes::routing_members(&channel, &all, concierge.as_deref()).into_iter().filter(|k| k.id != from.id).collect();
+ let to = next_after_handback(state, &space, &channel, &all, &members, &from, &msg.text, concierge.as_deref()).await;
+ let Some((to, fit)) = to else {
+ return Err("No one else here fits it better; answer it as well as you can.".into());
+ };
+ match state.db.add_route_handback(&msg.id, &from.id, &to.id, reason).await {
+ Ok(true) => {}
+ Ok(false) => return Err("This message was already handed back once; answer it as well as you can.".into()),
+ Err(_) => return Err("Could not hand it back.".into()),
+ }
+ let why = format!("{} handed this back (\"{reason}\"), so {} ({}) takes it", from.name, to.name, to.title);
+ let mut routing = super::routes::routing_meta(&to, &why, members.len() + 1, false, &[], "handback");
+ routing["fit"] = json!(fit);
+ routing["handed_back_by"] = json!(from.id);
+ let prompt = format!(
+ "{}\n\n(kwnt routing note: {} handed this message to you as not their area: {reason}. Answer it.)",
+ msg.text, from.name
+ );
+ tracing::info!(from = %from.id, to = %to.id, message = %msg.id, "a bot handed a message back");
+ let (st, k, um) = (state.clone(), to.clone(), msg.id.clone());
+ let ch = channel.id.clone();
+ tokio::spawn(async move {
+ if let Err(e) = super::routes::run_routed_turn(&st, &k, Some(ch), None, prompt, Some(routing), vec![um]).await {
+ tracing::warn!(error = %e, kwant = %k.id, "the hand-back turn didn't finish");
+ }
+ });
+ Ok(to.name)
+}
+
+/// Who takes a handed-back message: the next best member when it fits (at least [`ROUTE_AT`]),
+/// else the Concierge (#general, made if needed; anywhere it already exists), else the lead.
+/// Never the bot that handed it back.
+#[allow(clippy::too_many_arguments)]
+async fn next_after_handback(
+ state: &AppState,
+ space: &SpaceId,
+ channel: &crate::db::models::Channel,
+ all: &[Kwant],
+ members: &[Kwant],
+ from: &Kwant,
+ text: &str,
+ concierge: Option<&str>,
+) -> Option<(Kwant, f32)> {
+ if !members.is_empty() {
+ let hints = hints_for(state, members).await;
+ let lead = if channel.lead_kwant_id == from.id { members[0].id.clone() } else { channel.lead_kwant_id.clone() };
+ let route = state.router.route_channel_query_hinted(text, &channel.name, &lead, members, None, &hints).await;
+ if route.fit >= ROUTE_AT {
+ if let Some(k) = members.iter().find(|k| k.id == route.kwant_id) {
+ return Some((k.clone(), route.fit));
+ }
+ }
+ }
+ if concierge != Some(from.id.as_str()) {
+ let c = if channel.name == "general" {
+ super::concierge::for_no_match(state, space, &channel.id, all).await
+ } else {
+ concierge.and_then(|id| all.iter().find(|k| k.id == id)).cloned()
+ };
+ if let Some(c) = c {
+ return Some((c, 0.0));
+ }
+ }
+ let lead = all.iter().find(|k| k.id == channel.lead_kwant_id && k.id != from.id && members.iter().any(|m| m.id == k.id));
+ lead.cloned().map(|k| (k, 0.0))
+}
diff --git a/src/server/routes.rs b/src/server/routes.rs
index f3646fcf..b7435225 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -179,6 +179,11 @@ pub struct UpdateKwantRequest {
binding: ProfileBinding,
#[serde(flatten)]
browser: BrowserSitesUpdate,
+ /// Left out: the list stays as it is. `[]` clears it.
+ #[serde(default)]
+ covers: Option<Vec<String>>,
+ #[serde(default)]
+ avoids: Option<Vec<String>>,
}
type SiteList = Option<Vec<String>>;
@@ -337,6 +342,8 @@ pub async fn update_kwant(
check_binding(&state, &space, &payload.binding, &payload.base.preferred_model)
.await
.map_err(IntoResponse::into_response)?;
+ let covers = payload.covers.as_deref().map(crate::db::routing::clean_scope_list).transpose().map_err(|e| api_error(StatusCode::BAD_REQUEST, format!("covers: {e}")))?;
+ let avoids = payload.avoids.as_deref().map(crate::db::routing::clean_scope_list).transpose().map_err(|e| api_error(StatusCode::BAD_REQUEST, format!("avoids: {e}")))?;
let clash = format!("a bot called {} already exists in this space", payload.base.name);
match state.db.update_kwant(&id, &payload.base).await {
Ok(Some(_)) => {}
@@ -349,6 +356,9 @@ pub async fn update_kwant(
.set_browser_sites(&id, allowed_sites.as_deref(), blocked_sites.as_deref(), payload.browser.browser_block_private_network)
.await
.map_err(|e| db_error(&e, ""))?;
+ if covers.is_some() || avoids.is_some() {
+ state.db.set_scope(&id, covers.as_deref(), avoids.as_deref()).await.map_err(|e| db_error(&e, ""))?;
+ }
kwant_view_json(&state, &id).await.map_err(IntoResponse::into_response)
}
@@ -916,11 +926,26 @@ pub(super) async fn run_routine_turn(
channel_id: Option<String>,
thread_id: Option<String>,
prompt: String,
+) -> Result<Option<String>, String> {
+ run_routed_turn(state, kwant, channel_id, thread_id, prompt, None, Vec::new()).await
+}
+
+/// [`run_routine_turn`] with the routing card for the reply (`meta.routing`) and extra stop keys
+/// (the person's message): a channel message the person routed by choosing a bot, or one a bot
+/// handed back (see [`super::rerouting`]).
+pub(super) async fn run_routed_turn(
+ state: &AppState,
+ kwant: &Kwant,
+ channel_id: Option<String>,
+ thread_id: Option<String>,
+ prompt: String,
+ routing: Option<serde_json::Value>,
+ stop_keys: Vec<String>,
) -> Result<Option<String>, String> {
let context_key = thread_id.clone().or_else(|| channel_id.clone()).unwrap_or_else(|| kwant.id.clone());
- let job = state.turns.start_job([context_key.clone()]);
+ let job = state.turns.start_job(std::iter::once(context_key.clone()).chain(stop_keys));
let scope = scope_for(state, kwant, channel_id, thread_id, &job, 0).await?;
- let reply = try_kwant_turn(&scope, kwant, prompt.clone(), TurnOpts::default()).await;
+ let reply = try_kwant_turn(&scope, kwant, prompt.clone(), TurnOpts { routing, ..TurnOpts::default() }).await;
let reply = continue_once_if_capped(&scope, kwant, reply, false).await;
match reply {
Ok(text) => {
@@ -3241,6 +3266,8 @@ async fn send_chat_inner(
} else {
// Target single Kwant
let mut routing = None;
+ // A close call the person settles on a card: (channel, the two bots offered, why)
+ let mut asking: Option<(crate::db::models::Channel, Vec<Kwant>, String)> = None;
let target_kwant = if let Some(kname) = kwant_mention {
all_kwants
.iter()
@@ -3279,6 +3306,7 @@ async fn send_chat_inner(
let members = routing_members(&channel, &all_kwants, concierge.as_deref());
if channel.routing_mode == "auto" && members.len() > 1 {
+ let hints = super::rerouting::hints_for(&state, &members).await;
let context_id = payload.channel_id.clone();
let _ = state.event_sender.send(RuntimeEvent::RoutingStarted {
context_id: context_id.clone(),
@@ -3289,12 +3317,13 @@ async fn send_chat_inner(
None => {
state
.router
- .route_channel_query_after(
+ .route_channel_query_hinted(
&payload.prompt,
&channel.name,
&channel.lead_kwant_id,
&members,
last_speaker.as_deref(),
+ &hints,
)
.await
}
@@ -3305,16 +3334,31 @@ async fn send_chat_inner(
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);
+ match 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);
+ }
+ }
+ crate::router::team::Settle::Ask(ids) => {
+ let offered: Vec<Kwant> =
+ ids.iter().filter_map(|id| members.iter().find(|k| &k.id == id).cloned()).collect();
+ if offered.len() == 2 {
+ route.reason = format!(
+ "This could be for {} or {}, so you're asked who answers",
+ offered[0].name, offered[1].name
+ );
+ route.basis = "ask".into();
+ asking = Some((channel.clone(), offered, route.reason.clone()));
+ }
}
+ crate::router::team::Settle::Route => {}
}
if let Some(ref k) = chosen {
routing = Some(routing_meta(k, &route.reason, members.len(), route.fallback, &route.matched_terms, &route.basis));
@@ -3346,6 +3390,12 @@ async fn send_chat_inner(
}
.ok_or(StatusCode::BAD_REQUEST)?;
+ if let Some((channel, offered, reason)) = asking {
+ // No turn until the person chooses (POST /api/route-choices/:id/resolve)
+ drop(job);
+ let v = super::rerouting::ask(&state, &space, &channel, &all_kwants, &saved_user_msg.id, &payload.prompt, &offered, &reason).await?;
+ return Ok(Json(v));
+ }
let team_keys = active_team.as_ref().map(|t| (t.id.clone(), t.name.clone()));
execute_single_turn(
state.clone(),
@@ -3369,7 +3419,7 @@ 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> {
+pub(super) 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()
}
@@ -3388,7 +3438,7 @@ fn channel_members(channel: &crate::db::models::Channel, all_kwants: &[Kwant]) -
}
/// A reply's `meta.routing`: who Laya picked for a channel or team message and why.
-fn routing_meta(kwant: &Kwant, reason: &str, candidates: usize, fallback: bool, terms: &[String], basis: &str) -> serde_json::Value {
+pub(super) fn routing_meta(kwant: &Kwant, reason: &str, candidates: usize, fallback: bool, terms: &[String], basis: &str) -> serde_json::Value {
json!({
"basis": basis,
"kwant_id": kwant.id,
diff --git a/src/server/sse.rs b/src/server/sse.rs
index 482d99c0..c0744036 100644
--- a/src/server/sse.rs
+++ b/src/server/sse.rs
@@ -93,6 +93,7 @@ pub fn owners(event: &RuntimeEvent) -> Vec<Owner> {
}
E::BotActionUpdated { action: v }
| E::HireUpdated { hire: v }
+ | E::RouteChoiceUpdated { choice: v }
| E::CapabilityChanged { capability: v }
| E::FactChanged { fact: v }
| E::FactDispute { dispute: v } => {
@@ -326,6 +327,7 @@ mod tests {
| E::McpSuggestionUpdated { .. }
| E::BotActionUpdated { .. }
| E::HireUpdated { .. }
+ | E::RouteChoiceUpdated { .. }
| E::CapabilityChanged { .. }
| E::FactChanged { .. }
| E::FactDispute { .. }
diff --git a/tests/concierge_test.rs b/tests/concierge_test.rs
index d22bed5d..42b23ae6 100644
--- a/tests/concierge_test.rs
+++ b/tests/concierge_test.rs
@@ -1,6 +1,8 @@
//! 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.
+//! Also the close calls the person settles on a card, a bot handing a message back, and the
+//! covers/avoids lists on the bot routes.
//! Its own test binary: it changes PATH.
use axum::{
@@ -16,7 +18,10 @@ use kwnt::{
Database,
},
router::LayaRouter,
- server::{create_router, AppState},
+ server::{
+ continuity::{SelfScope, TurnOrigin},
+ create_router, mcp_runtime, AppState,
+ },
tools::ToolRunner,
RuntimeEvent,
};
@@ -175,3 +180,155 @@ async fn other_channels_lean_to_their_own_members() {
assert_eq!((to.as_str(), basis.as_deref()), (a.as_str(), Some("lead")));
assert!(concierges(&state).await.is_empty());
}
+
+async fn call_as(app: &Router, uri: &str, token: &str, body: Value) -> (StatusCode, Value) {
+ let req = Request::builder()
+ .method("POST")
+ .uri(uri)
+ .header("content-type", "application/json")
+ .header("authorization", format!("Bearer {token}"));
+ let resp = app.clone().oneshot(req.body(Body::from(body.to_string())).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(Value::Null))
+}
+
+/// 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 {
+ 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() }),
+ turn_id: Some(format!("turn-{bot}")),
+ ..Default::default()
+ };
+ mcp_runtime::prepare_turn_with_self(state, &k, Some(format!("turn-{bot}")), None, Some(scope)).await.unwrap().1
+}
+
+async fn hand_back(app: &Router, token: &str, reason: &str) -> (String, bool) {
+ let rpc = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "hand_back", "arguments": {"reason": reason}}});
+ let (s, v) = call_as(app, "/api/mcp/self", token, rpc).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ (v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string(), v["result"]["isError"].as_bool().unwrap_or(false))
+}
+
+/// Waits for the next turn to end and returns the routing of the reply it saved in `channel`.
+async fn next_reply_routing(state: &AppState, events: &mut tokio::sync::broadcast::Receiver<RuntimeEvent>, channel: &str) -> Value {
+ tokio::time::timeout(Duration::from_secs(20), async {
+ loop {
+ if let Ok(RuntimeEvent::TurnEnded { .. }) = events.recv().await.map(|e| e.unscoped().clone()) {
+ break;
+ }
+ }
+ })
+ .await
+ .expect("the turn ended");
+ let msgs = state.db.list_messages(channel, 50).await.unwrap();
+ let reply = msgs.iter().rev().find(|m| m.sender_role == "kwant").expect("a reply");
+ let meta: Value = reply.meta.as_deref().and_then(|m| serde_json::from_str(m).ok()).unwrap_or(Value::Null);
+ meta["routing"].clone()
+}
+
+/// A close call (two bots with the same role and words) posts a card instead of a turn; the
+/// person's choice runs that bot once, and "answer generally" in #general goes to the Concierge.
+#[tokio::test]
+async fn a_close_call_asks_and_the_choice_answers() {
+ let (app, state, _tmp) = setup().await;
+ let fe = ok(&app, "POST", "/api/kwants", Some(specialist("Bea", "Frontend engineer", "You build the app's pages."))).await["id"].as_str().unwrap().to_string();
+ let web = ok(&app, "POST", "/api/kwants", Some(specialist("Cy", "Web developer", "You build websites."))).await["id"].as_str().unwrap().to_string();
+ only(&app, &state, &[&fe, &web]).await;
+ let general = state.db.general_channel(&SpaceId::default_space()).await.unwrap().expect("#general").id;
+
+ let v = ok(&app, "POST", "/api/chat/send", Some(json!({"channel_id": general, "prompt": "The button CSS is off on mobile Safari", "sender_id": "user"}))).await;
+ assert_eq!(v["status"], "asking", "{v}");
+ let ids: Vec<&str> = v["choices"].as_array().unwrap().iter().map(|c| c["kwant_id"].as_str().unwrap()).collect();
+ assert_eq!(ids.len(), 2);
+ assert!(ids.contains(&fe.as_str()) && ids.contains(&web.as_str()), "{v}");
+ assert_eq!(v["general"]["name"], "Concierge");
+ let choice = v["route_choice_id"].as_str().unwrap().to_string();
+ let card = state.db.list_messages(&general, 50).await.unwrap().into_iter().find(|m| Some(m.id.as_str()) == v["card_message_id"].as_str()).expect("the card");
+ let meta: Value = serde_json::from_str(card.meta.as_deref().unwrap_or("null")).unwrap();
+ assert_eq!(meta["kind"], "route_choice");
+ let uri = format!("/api/route-choices/{choice}/resolve");
+
+ // Only an offered bot, only one way, only the person
+ let (s, _) = call(&app, "POST", &uri, Some(json!({"kwant_id": "nope"}))).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST);
+ let (s, _) = call(&app, "POST", &uri, Some(json!({}))).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST);
+ let token = turn_token(&state, &fe, &general).await;
+ let (s, _) = call_as(&app, &uri, &token, json!({"kwant_id": web})).await;
+ assert_eq!(s, StatusCode::FORBIDDEN);
+
+ let mut events = state.event_sender.subscribe();
+ let v = ok(&app, "POST", &uri, Some(json!({"kwant_id": web}))).await;
+ assert_eq!((v["status"].as_str(), v["kwant_id"].as_str()), (Some("dispatched"), Some(web.as_str())));
+ let routing = next_reply_routing(&state, &mut events, &general).await;
+ assert_eq!((routing["basis"].as_str(), routing["kwant_id"].as_str()), (Some("ask"), Some(web.as_str())), "{routing}");
+ let (s, _) = call(&app, "POST", &uri, Some(json!({"kwant_id": fe}))).await;
+ assert_eq!(s, StatusCode::CONFLICT, "a second tap does nothing");
+
+ // "Answer generally" in #general: the Concierge, made now
+ let v = ok(&app, "POST", "/api/chat/send", Some(json!({"channel_id": general, "prompt": "Is the CSS grid off on the button?", "sender_id": "user"}))).await;
+ assert_eq!(v["status"], "asking", "{v}");
+ let mut events = state.event_sender.subscribe();
+ let v = ok(&app, "POST", &format!("/api/route-choices/{}/resolve", v["route_choice_id"].as_str().unwrap()), Some(json!({"general": true}))).await;
+ let made = concierges(&state).await;
+ assert_eq!(made.len(), 1);
+ assert_eq!(v["kwant_id"].as_str(), Some(made[0].as_str()));
+ let routing = next_reply_routing(&state, &mut events, &general).await;
+ assert_eq!(routing["basis"], "ask", "{routing}");
+ assert_eq!(state.db.get_scope(&made[0]).await.unwrap().covers.len(), kwnt::server::concierge::COVERS.len());
+}
+
+/// "Not my area": the message goes on once, to the next bot that fits or the Concierge; a second
+/// hand-back of the same message is refused.
+#[tokio::test]
+async fn a_hand_back_takes_one_hop() {
+ 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 (to, _) = routed_to(&app, &state, &general, "Write a TikTok hook about the sitemap launch party").await;
+ assert_eq!(to, script);
+
+ let token = turn_token(&state, &script, &general).await;
+ let (text, err) = hand_back(&app, &token, "").await;
+ assert!(err, "a reason is required: {text}");
+ 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}");
+ assert!(text.contains("Atlas"), "{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}");
+
+ // One hop: Atlas can't bounce it on
+ let token = turn_token(&state, &atlas, &general).await;
+ let (text, err) = hand_back(&app, &token, "Not mine either").await;
+ assert!(err && text.contains("already handed back"), "{text}");
+}
+
+/// The bot routes read and update covers/avoids; left out, a list stays as it is.
+#[tokio::test]
+async fn covers_and_avoids_are_read_and_updated() {
+ let (app, _state, _tmp) = setup().await;
+ let bot = ok(&app, "POST", "/api/kwants", Some(specialist("Chef", "Recipe planner", "Meals."))).await;
+ assert_eq!((bot["covers"].clone(), bot["avoids"].clone()), (json!([]), json!([])));
+ let id = bot["id"].as_str().unwrap();
+ let mut body = specialist("Chef", "Recipe planner", "Meals.");
+ body["covers"] = json!([" restaurants ", "Restaurants", "street food"]);
+ body["avoids"] = json!(["wine"]);
+ let v = ok(&app, "PUT", &format!("/api/kwants/{id}"), Some(body)).await;
+ assert_eq!((v["covers"].clone(), v["avoids"].clone()), (json!(["restaurants", "street food"]), json!(["wine"])));
+ let v = ok(&app, "PUT", &format!("/api/kwants/{id}"), Some(specialist("Chef", "Recipe planner", "Meals."))).await;
+ assert_eq!(v["covers"], json!(["restaurants", "street food"]));
+ let mut body = specialist("Chef", "Recipe planner", "Meals.");
+ body["avoids"] = json!(["x".repeat(61)]);
+ let (s, _) = call(&app, "PUT", &format!("/api/kwants/{id}"), Some(body)).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST);
+ let list = ok(&app, "GET", "/api/kwants", None).await;
+ let listed = list.as_array().unwrap().iter().find(|k| k["id"] == id).unwrap().clone();
+ assert_eq!(listed["avoids"], json!(["wine"]));
+}