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.

feat(router): Laya picks the responding agent in #general and shows routing in chat

Oleksandr Ivanchenko788b2ae47cf2
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 4b45ff34..4ca6b823 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1,7 +1,7 @@
import React, { useState, useEffect, useRef } from 'react';
import { AppHeader } from './components/AppHeader';
import { Sidebar, Kwant, Channel, Team } from './components/Sidebar';
-import { ChatView, ChatMessage, DiscussionState } from './components/ChatView';
+import { ChatView, ChatMessage, DiscussionState, RoutingState } from './components/ChatView';
import { PendingApproval } from './components/ModernApprovalCard';
import { SettingsModal } from './components/SettingsModal';
import { NewAgentModal } from './components/NewAgentModal';
@@ -30,6 +30,7 @@ export const App: React.FC = () => {
isChannelRef.current = isChannel;
const messagesCacheRef = useRef<Record<string, ChatMessage[]>>({});
const [discussionState, setDiscussionState] = useState<DiscussionState>({ inProgress: false });
+ const [routingState, setRoutingState] = useState<RoutingState | null>(null);
const discussionInProgressRef = useRef(false);
const kwantsRef = useRef<Kwant[]>(kwants);
kwantsRef.current = kwants;
@@ -147,6 +148,43 @@ export const App: React.FC = () => {
case 'ThinkingDelta':
setStreamingThinking(event.data);
break;
+ case 'routing_started':
+ case 'RoutingStarted': {
+ const ctx = event.data?.context_id;
+ const targetId = streamingContextIdRef.current;
+ if (ctx && targetId && ctx !== targetId) break;
+ setRoutingState({
+ phase: 'deciding',
+ contextId: ctx || targetId || undefined,
+ candidates: event.data?.candidates || [],
+ });
+ setStreamingSpeakerName('Laya');
+ streamingSpeakerNameRef.current = 'Laya';
+ break;
+ }
+ case 'routing_decided':
+ case 'RoutingDecided': {
+ const ctx = event.data?.context_id;
+ const targetId = streamingContextIdRef.current;
+ if (ctx && targetId && ctx !== targetId) break;
+ const name: string = event.data?.kwant_name;
+ setRoutingState((prev) => ({
+ phase: 'decided',
+ contextId: ctx || targetId || undefined,
+ candidates: prev?.candidates || [],
+ kwantId: event.data?.kwant_id,
+ kwantName: name,
+ kwantTitle: event.data?.kwant_title,
+ reason: event.data?.reason,
+ mode: event.data?.mode,
+ }));
+ if (name) {
+ setStreamingSpeakerName(name);
+ streamingSpeakerNameRef.current = name;
+ }
+ playSfx('blip');
+ break;
+ }
case 'ApprovalRequired':
setPendingApproval({
id: event.data.id,
@@ -220,6 +258,7 @@ export const App: React.FC = () => {
case 'DiscussionCompleted': {
discussionInProgressRef.current = false;
setDiscussionState({ inProgress: false });
+ setRoutingState(null);
setIsStreaming(false);
setStreamingText('');
setStreamingThinking('');
@@ -260,6 +299,7 @@ export const App: React.FC = () => {
.catch(() => {});
}
if (!discussionInProgressRef.current) {
+ setRoutingState(null);
setIsStreaming(false);
setStreamingContextId(null);
streamingContextIdRef.current = null;
@@ -351,6 +391,7 @@ export const App: React.FC = () => {
case 'Error': {
discussionInProgressRef.current = false;
setDiscussionState({ inProgress: false });
+ setRoutingState(null);
setIsStreaming(false);
setStreamingContextId(null);
streamingContextIdRef.current = null;
@@ -388,6 +429,7 @@ export const App: React.FC = () => {
}
discussionInProgressRef.current = false;
setDiscussionState({ inProgress: false });
+ setRoutingState(null);
setIsStreaming(false);
setStreamingContextId(null);
streamingContextIdRef.current = null;
@@ -416,6 +458,7 @@ export const App: React.FC = () => {
discussionInProgressRef.current = false;
setDiscussionState({ inProgress: false });
+ setRoutingState(null);
setIsStreaming(true);
setStreamingContextId(targetId);
streamingContextIdRef.current = targetId;
@@ -453,6 +496,7 @@ export const App: React.FC = () => {
});
} catch (err) {
console.error('Failed sending chat:', err);
+ setRoutingState(null);
setIsStreaming(false);
setStreamingContextId(null);
streamingContextIdRef.current = null;
@@ -897,6 +941,7 @@ export const App: React.FC = () => {
kwants={kwants}
teams={teams}
discussionState={isDiscussionActiveHere ? discussionState : { inProgress: false }}
+ routingState={isCurrentContextStreaming ? routingState : null}
onCancelDiscussion={handleCancelDiscussion}
teamMembers={currentTeamMembers}
teamId={activeSandboxId}
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index 0c435bb4..613c61fd 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -27,6 +27,23 @@ export interface DiscussionState {
totalTurns?: number;
}
+export interface RoutingCandidate {
+ id: string;
+ name: string;
+ title: string;
+}
+
+export interface RoutingState {
+ phase: 'deciding' | 'decided';
+ contextId?: string;
+ candidates: RoutingCandidate[];
+ kwantId?: string;
+ kwantName?: string;
+ kwantTitle?: string;
+ reason?: string;
+ mode?: 'direct' | 'discuss' | string;
+}
+
export interface ChatViewProps {
title: string;
subtitle: string;
@@ -41,6 +58,7 @@ export interface ChatViewProps {
kwants?: Array<{ id: string; name: string; title: string; avatar_sprite: string }>;
teams?: Array<{ id: string; name: string; description?: string; member_kwants?: string[] }>;
discussionState?: DiscussionState;
+ routingState?: RoutingState | null;
onCancelDiscussion?: () => void;
teamMembers?: Array<{ id: string; name: string; title: string; avatar_sprite: string }>;
teamId?: string;
@@ -79,6 +97,76 @@ export const renderFormattedText = (text: string): React.ReactNode => {
});
};
+const LayaRoutingCard: React.FC<{ routing: RoutingState }> = ({ routing }) => {
+ const deciding = routing.phase === 'deciding';
+ const isDiscuss = routing.mode === 'discuss';
+
+ return (
+ <div className="flex items-start gap-3.5 w-full max-w-5xl" aria-live="polite">
+ <div className="w-[34px] h-[34px] flex-shrink-0 rounded-full bg-violet-500/15 border border-violet-500/40 flex items-center justify-center shadow-sm shadow-violet-500/10">
+ <Sparkles size={16} className={`text-violet-300 ${deciding ? 'animate-pulse' : ''}`} />
+ </div>
+ <div className="flex flex-col items-start min-w-0 flex-1 max-w-4xl">
+ <div className="flex items-center gap-2 mb-1.5 text-[11px] text-zinc-400 font-medium">
+ <span className="text-zinc-200">Laya</span>
+ <span className="text-zinc-500">· router</span>
+ </div>
+ <div className="px-4 py-3 rounded-2xl rounded-tl-sm bg-violet-950/20 border border-violet-500/20 text-sm text-zinc-200 shadow-sm w-full">
+ {deciding ? (
+ <div className="flex items-center gap-2">
+ <span>Choosing who's best to answer your question</span>
+ <span className="inline-flex gap-0.5" aria-hidden="true">
+ {[0, 1, 2].map((i) => (
+ <span
+ key={i}
+ className="w-1 h-1 rounded-full bg-violet-300 animate-bounce"
+ style={{ animationDelay: `${i * 150}ms` }}
+ />
+ ))}
+ </span>
+ </div>
+ ) : (
+ <div className="flex flex-col gap-0.5">
+ <div className="flex items-center gap-1.5 flex-wrap">
+ <span>{isDiscuss ? 'Starting a team discussion led by' : 'Sending your question to'}</span>
+ <span className="font-semibold text-violet-200">{routing.kwantName}</span>
+ {routing.kwantTitle && <span className="text-zinc-400 text-xs">({routing.kwantTitle})</span>}
+ </div>
+ {routing.reason && <span className="text-xs text-zinc-400">{routing.reason}</span>}
+ </div>
+ )}
+
+ {routing.candidates.length > 0 && (
+ <div className="mt-2.5 flex items-center gap-1.5 flex-wrap">
+ {routing.candidates.map((c, i) => {
+ const chosen = !deciding && c.id === routing.kwantId;
+ return (
+ <div
+ key={c.id}
+ title={`${c.name} — ${c.title}`}
+ className={`flex items-center gap-1.5 pl-0.5 pr-2.5 py-0.5 rounded-full border text-[11px] transition-all duration-300 ${
+ chosen
+ ? 'border-violet-400/60 bg-violet-500/20 text-violet-100 scale-105'
+ : deciding
+ ? 'border-zinc-700/60 bg-zinc-900/60 text-zinc-300 animate-pulse'
+ : 'border-zinc-800 bg-zinc-900/40 text-zinc-500 opacity-50'
+ }`}
+ style={deciding ? { animationDelay: `${i * 200}ms` } : undefined}
+ >
+ <ModernAvatar role={c.name} name={c.name} size={18} />
+ <span>{c.name}</span>
+ {chosen && <Check size={11} className="text-violet-300" />}
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+};
+
export const ChatView: React.FC<ChatViewProps> = ({
title,
subtitle,
@@ -93,6 +181,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
kwants: kwantsProp,
teams: teamsProp,
discussionState,
+ routingState,
onCancelDiscussion,
teamMembers,
teamId,
@@ -244,7 +333,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
- }, [messages, streamingText, streamingThinking, pendingApproval]);
+ }, [messages, streamingText, streamingThinking, pendingApproval, routingState]);
const toggleThought = (id: string) => {
setOpenThoughts((prev) => ({ ...prev, [id]: !prev[id] }));
@@ -524,8 +613,13 @@ export const ChatView: React.FC<ChatViewProps> = ({
);
})}
+ {/* Laya routing: which agent will answer */}
+ {isStreaming && routingState && !discussionState?.inProgress && (
+ <LayaRoutingCard routing={routingState} />
+ )}
+
{/* Live Streaming Assistant Message */}
- {isStreaming && (
+ {isStreaming && routingState?.phase !== 'deciding' && (
<div className="flex items-start gap-3.5 w-full max-w-5xl">
<ModernAvatar
role={
diff --git a/src/drivers/events.rs b/src/drivers/events.rs
index 05c5481c..2220a5fb 100644
--- a/src/drivers/events.rs
+++ b/src/drivers/events.rs
@@ -64,8 +64,30 @@ pub enum RuntimeEvent {
container_name: String,
is_running: bool,
},
+ #[serde(rename = "routing_started", alias = "RoutingStarted")]
+ RoutingStarted {
+ context_id: Option<String>,
+ candidates: Vec<RoutingCandidate>,
+ },
+ #[serde(rename = "routing_decided", alias = "RoutingDecided")]
+ RoutingDecided {
+ context_id: Option<String>,
+ kwant_id: String,
+ kwant_name: String,
+ kwant_title: String,
+ reason: String,
+ /// "direct" for a single responder, "discuss" for a multi-turn team discussion.
+ mode: String,
+ },
Error {
code: String,
message: String,
},
}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct RoutingCandidate {
+ pub id: String,
+ pub name: String,
+ pub title: String,
+}
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs
index a62a0a3f..c2b3060e 100644
--- a/src/drivers/mod.rs
+++ b/src/drivers/mod.rs
@@ -4,7 +4,7 @@ pub mod events;
pub use api::ApiDriver;
pub use cli::{find_cli_binary, CliDriver};
-pub use events::RuntimeEvent;
+pub use events::{RoutingCandidate, RuntimeEvent};
use crate::db::models::{Kwant, Message};
use async_trait::async_trait;
diff --git a/src/router/mod.rs b/src/router/mod.rs
index f1c622fb..ac1bdcd7 100644
--- a/src/router/mod.rs
+++ b/src/router/mod.rs
@@ -6,7 +6,10 @@ pub mod team;
pub use fallback::heuristic_fallback;
pub use laya::LayaRouter;
pub use tags::{parse_mentions, parse_mentions_with_lookup, TagMention};
-pub use team::{heuristic_team_decision, parse_laya_team_answers, TeamDecision};
+pub use team::{
+ heuristic_pick_kwant, heuristic_team_decision, parse_laya_kwant_choice, parse_laya_team_answers,
+ TeamDecision,
+};
use serde::{Deserialize, Serialize};
use thiserror::Error;
diff --git a/src/router/team.rs b/src/router/team.rs
index 4f1dd982..4bcec54e 100644
--- a/src/router/team.rs
+++ b/src/router/team.rs
@@ -103,6 +103,113 @@ impl LayaRouter {
Err("Laya response missing valid team orchestration fields".into())
}
+
+ /// Picks the single best-suited kwant among channel members to answer a prompt.
+ /// Returns `(kwant_id, reason)`. Falls back to keyword heuristics when Laya is unreachable.
+ pub async fn route_channel_query(
+ &self,
+ prompt: &str,
+ channel_name: &str,
+ lead_kwant_id: &str,
+ members: &[Kwant],
+ ) -> (String, String) {
+ match self.query_laya_for_kwant(prompt, channel_name, members).await {
+ Ok(choice) => choice,
+ Err(e) => {
+ tracing::debug!(error = %e, "Laya channel routing unavailable or failed, using heuristic fallback");
+ let (kwant, reason) = heuristic_pick_kwant(prompt, lead_kwant_id, members)
+ .map(|(k, r)| (k.id.clone(), r))
+ .unwrap_or_else(|| (lead_kwant_id.to_string(), "Routed to channel lead".into()));
+ (kwant, reason)
+ }
+ }
+ }
+
+ async fn query_laya_for_kwant(
+ &self,
+ prompt: &str,
+ channel_name: &str,
+ members: &[Kwant],
+ ) -> Result<(String, String), String> {
+ let mut kwant_criteria = serde_json::Map::new();
+ for m in members {
+ let desc = format!("{} ({}): {}", m.name, m.title, m.persona_prompt);
+ kwant_criteria.insert(m.id.clone(), serde_json::Value::String(desc));
+ }
+
+ let payload = json!({
+ "state": {
+ "prompt": prompt,
+ "channel": channel_name
+ },
+ "questions": {
+ "lead_kwant": {
+ "type": "choice",
+ "instructions": "Which kwant is best suited to answer this question?",
+ "criteria": kwant_criteria
+ }
+ }
+ });
+
+ let endpoint = format!("{}/v1/systemone", self.base_url.trim_end_matches('/'));
+ let resp = self
+ .client
+ .post(&endpoint)
+ .json(&payload)
+ .send()
+ .await
+ .map_err(|e| e.to_string())?;
+
+ if !resp.status().is_success() {
+ return Err(format!("Laya HTTP status {}", resp.status()));
+ }
+
+ let data: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?;
+ parse_laya_kwant_choice(&data, members)
+ .ok_or_else(|| "Laya response missing valid kwant choice".into())
+ }
+}
+
+/// Extracts a valid member kwant choice from a Laya `answers.lead_kwant` response.
+pub fn parse_laya_kwant_choice(data: &serde_json::Value, members: &[Kwant]) -> Option<(String, String)> {
+ let choice = data
+ .get("answers")?
+ .get("lead_kwant")?
+ .get("choice")?
+ .as_str()?;
+ let kwant = members.iter().find(|m| m.id == choice || m.name.eq_ignore_ascii_case(choice))?;
+ Some((
+ kwant.id.clone(),
+ format!("Laya picked {} ({}) as the best fit for this question", kwant.name, kwant.title),
+ ))
+}
+
+/// Picks the member with the highest domain-keyword relevance, or the lead when nothing matches.
+pub fn heuristic_pick_kwant<'a>(
+ prompt: &str,
+ lead_kwant_id: &str,
+ members: &'a [Kwant],
+) -> Option<(&'a Kwant, String)> {
+ let (best, score) = members
+ .iter()
+ .map(|m| (m, calculate_kwant_relevance(prompt, m)))
+ .fold(None, |acc: Option<(&Kwant, usize)>, (m, s)| match acc {
+ Some((_, best_s)) if best_s >= s => acc,
+ _ => Some((m, s)),
+ })?;
+
+ if score > 0 {
+ Some((
+ best,
+ format!("Selected {} ({}) based on domain expertise", best.name, best.title),
+ ))
+ } else {
+ let lead = members.iter().find(|m| m.id == lead_kwant_id).unwrap_or(&members[0]);
+ Some((
+ lead,
+ format!("No specialist matched; {} ({}) is taking it as channel lead", lead.name, lead.title),
+ ))
+ }
}
pub fn parse_laya_team_answers(
@@ -260,26 +367,40 @@ fn is_complex_query(prompt: &str) -> bool {
false
}
+const STOP_WORDS: &[&str] = &[
+ "the", "and", "for", "you", "your", "are", "with", "this", "that", "what", "how", "can", "please",
+ "from", "into", "about", "have", "has", "was", "were", "will", "would", "should", "could", "our",
+ "who", "why", "when", "where", "which", "they", "them", "then", "than", "there", "here", "all",
+ "any", "not", "but", "out", "use", "using", "does", "did", "its", "it's", "some", "need", "want",
+];
+
fn calculate_kwant_relevance(prompt: &str, kwant: &Kwant) -> usize {
let lower_prompt = prompt.to_lowercase();
let words: Vec<&str> = lower_prompt
.split(|c: char| !c.is_alphanumeric() && c != '-')
- .filter(|s| s.len() >= 3)
+ .filter(|s| s.len() >= 3 && !STOP_WORDS.contains(s))
+ .map(|s| if s.len() > 4 { s.strip_suffix('s').unwrap_or(s) } else { s })
.collect();
let name_lower = kwant.name.to_lowercase();
let title_lower = kwant.title.to_lowercase();
let prompt_lower = kwant.persona_prompt.to_lowercase();
+ // Short words must match a whole token; longer ones may prefix-match ("container" ~ "containerization")
+ let matches = |text: &str, w: &str| {
+ text.split(|c: char| !c.is_alphanumeric() && c != '-')
+ .any(|tok| tok == w || (w.len() >= 4 && tok.starts_with(w)))
+ };
+
let mut score = 0;
for w in words {
- if name_lower.contains(w) {
+ if matches(&name_lower, w) {
score += 3;
}
- if title_lower.contains(w) {
+ if matches(&title_lower, w) {
score += 2;
}
- if prompt_lower.contains(w) {
+ if matches(&prompt_lower, w) {
score += 1;
}
}
@@ -381,6 +502,26 @@ mod tests {
}
}
+ #[test]
+ fn test_heuristic_pick_kwant_by_expertise_and_lead_fallback() {
+ let (_, members) = make_test_fixture();
+ let (k, _) = heuristic_pick_kwant("check deployment pipeline", "kwant-1", &members).unwrap();
+ assert_eq!(k.id, "kwant-2");
+ let (k, reason) = heuristic_pick_kwant("open google.com", "kwant-1", &members).unwrap();
+ assert_eq!(k.id, "kwant-1");
+ assert!(reason.contains("channel lead"));
+ assert!(heuristic_pick_kwant("hi", "kwant-1", &[]).is_none());
+ }
+
+ #[test]
+ fn test_parse_laya_kwant_choice() {
+ let (_, members) = make_test_fixture();
+ let ok = json!({ "answers": { "lead_kwant": { "choice": "kwant-2" } } });
+ assert_eq!(parse_laya_kwant_choice(&ok, &members).unwrap().0, "kwant-2");
+ let unknown = json!({ "answers": { "lead_kwant": { "choice": "ghost" } } });
+ assert!(parse_laya_kwant_choice(&unknown, &members).is_none());
+ }
+
#[test]
fn test_parse_laya_team_answers_json() {
let (team, members) = make_test_fixture();
diff --git a/src/server/routes.rs b/src/server/routes.rs
index a2086bff..aa50b665 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -1,7 +1,7 @@
use super::AppState;
use crate::broker::ApprovalDecision;
use crate::db::models::*;
-use crate::drivers::{find_cli_binary, resolve_driver_for_model, RuntimeEvent, TurnInput};
+use crate::drivers::{find_cli_binary, resolve_driver_for_model, RoutingCandidate, RuntimeEvent, TurnInput};
use crate::router::{parse_mentions_with_lookup, TagMention, TeamDecision};
use axum::{
extract::{Path, Query, State},
@@ -204,6 +204,17 @@ async fn get_configured_endpoint(db: &crate::db::Database, target_model: &str) -
}
}
+fn routing_candidates(members: &[Kwant]) -> Vec<RoutingCandidate> {
+ members
+ .iter()
+ .map(|k| RoutingCandidate {
+ id: k.id.clone(),
+ name: k.name.clone(),
+ title: k.title.clone(),
+ })
+ .collect()
+}
+
fn execute_single_turn(
state: AppState,
target_kwant: Kwant,
@@ -578,6 +589,12 @@ pub async fn send_chat(
members = all_kwants.clone();
}
+ let routing_context_id = payload.channel_id.clone().or_else(|| payload.kwant_id.clone());
+ let _ = state.event_sender.send(RuntimeEvent::RoutingStarted {
+ context_id: routing_context_id.clone(),
+ candidates: routing_candidates(&members),
+ });
+
let team_decision = state
.router
.route_team_query(&payload.prompt, &team, &members)
@@ -592,6 +609,15 @@ pub async fn send_chat(
.unwrap_or(&members[0])
.clone();
+ let _ = state.event_sender.send(RuntimeEvent::RoutingDecided {
+ context_id: routing_context_id,
+ kwant_id: target_kwant.id.clone(),
+ kwant_name: target_kwant.name.clone(),
+ kwant_title: target_kwant.title.clone(),
+ reason: reason.clone(),
+ mode: "direct".into(),
+ });
+
let _ = state.event_sender.send(RuntimeEvent::ThinkingDelta(format!(
"🔮 Laya Team Router: Routed to {} ({}) — {}",
target_kwant.name, target_kwant.title, reason
@@ -622,6 +648,23 @@ pub async fn send_chat(
speakers,
plan,
} => {
+ if let Some(lead) = speakers
+ .first()
+ .and_then(|sid| all_kwants.iter().find(|k| &k.id == sid))
+ {
+ let _ = state.event_sender.send(RuntimeEvent::RoutingDecided {
+ context_id: routing_context_id,
+ kwant_id: lead.id.clone(),
+ kwant_name: lead.name.clone(),
+ kwant_title: lead.title.clone(),
+ reason: format!(
+ "This needs several perspectives — starting a {}-turn team discussion led by {}",
+ turns, lead.name
+ ),
+ mode: "discuss".into(),
+ });
+ }
+
let _ = state.event_sender.send(RuntimeEvent::ThinkingDelta(format!(
"🔮 Laya Team Router: Initiating {}-turn autonomous discussion with @{}",
turns, team.name
@@ -865,10 +908,48 @@ pub async fn send_chat(
.cloned()
} else if let Some(cid) = &payload.channel_id {
if let Ok(Some(channel)) = state.db.get_channel(cid).await {
- all_kwants
+ let lead = all_kwants
.iter()
.find(|k| k.id == channel.lead_kwant_id)
- .cloned()
+ .or_else(|| all_kwants.first())
+ .cloned();
+ // #general is the hub for every agent, including ones created after it was seeded
+ let members: Vec<Kwant> = if channel.name == "general" {
+ all_kwants.clone()
+ } else {
+ let member_ids: Vec<String> =
+ serde_json::from_str(&channel.member_kwants).unwrap_or_default();
+ member_ids
+ .iter()
+ .filter_map(|mid| all_kwants.iter().find(|k| &k.id == mid).cloned())
+ .collect()
+ };
+
+ if channel.routing_mode == "auto" && members.len() > 1 {
+ let context_id = payload.channel_id.clone();
+ let _ = state.event_sender.send(RuntimeEvent::RoutingStarted {
+ context_id: context_id.clone(),
+ candidates: routing_candidates(&members),
+ });
+ let (chosen_id, reason) = state
+ .router
+ .route_channel_query(&payload.prompt, &channel.name, &channel.lead_kwant_id, &members)
+ .await;
+ let chosen = members.iter().find(|k| k.id == chosen_id).cloned().or(lead);
+ if let Some(ref k) = chosen {
+ let _ = state.event_sender.send(RuntimeEvent::RoutingDecided {
+ context_id,
+ kwant_id: k.id.clone(),
+ kwant_name: k.name.clone(),
+ kwant_title: k.title.clone(),
+ reason,
+ mode: "direct".into(),
+ });
+ }
+ chosen
+ } else {
+ lead
+ }
} else {
all_kwants.first().cloned()
}