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.

Routing: whole-word keywords, Laya's low effort holds, more roles

Lin (kwant bot)7fd6826c3b5a
diff --git a/src/router/fallback.rs b/src/router/fallback.rs
index 62d536f4..9c58840a 100644
--- a/src/router/fallback.rs
+++ b/src/router/fallback.rs
@@ -1,31 +1,110 @@
use super::RouteDecision;
-/// Phrases that reliably mean a question needs careful, multi-step reasoning.
+/// Phrases that reliably mean a question needs careful, multi-step reasoning. Matched as whole words
+/// (see [`has_phrase`]), so "deep copy" or "security guards" don't count; bare "deep" is left out
+/// because it is usually part of a name ("deep copy", "deep link", "deep learning").
const DEEP_SIGNALS: &[&str] = &[
- "architecture", "architectural", "refactor", "complex", "deep", "benchmark", "security", "optimize",
- "investigate", "root cause", "root-cause", "tradeoff", "trade-off", "monolith", "microservice",
- "migrat", "postmortem", "post-mortem",
+ "architecture", "architectures", "architectural", "refactor", "refactoring", "refactored", "complex",
+ "complexity", "deep dive", "in-depth", "in depth", "benchmark", "benchmarking", "security", "optimize",
+ "optimise", "optimized", "optimised", "optimizing", "optimising", "optimization", "optimisation",
+ "investigate", "investigating", "investigation", "root cause", "root-cause", "tradeoff", "trade-off",
+ "trade off", "monolith", "monolithic", "microservice", "migrate", "migrated", "migrating", "migration",
+ "postmortem", "post-mortem",
];
-fn has_deep_signal(lower: &str) -> bool {
- DEEP_SIGNALS.iter().any(|s| lower.contains(s))
+/// Everyday phrases that contain a deep signal but ask for nothing deep.
+const NOT_DEEP: &[&str] = &["security guard", "security deposit", "social security", "security camera"];
+
+/// Words that, just before a signal, say the person doesn't want it ("don't refactor anything").
+const NEGATIONS: &[&str] = &["don't", "dont", "do not", "not", "no", "never", "without"];
+
+/// Lower-case words of `text`. Hyphens and apostrophes stay inside a word ("trade-off", "don't"), and
+/// are trimmed from its ends ("'deep copy'").
+pub(crate) fn words(text: &str) -> Vec<String> {
+ text.to_lowercase()
+ .replace('\u{2019}', "'")
+ .split(|c: char| !c.is_alphanumeric() && c != '-' && c != '\'')
+ .map(|w| w.trim_matches(|c| c == '-' || c == '\''))
+ .filter(|w| !w.is_empty())
+ .map(str::to_string)
+ .collect()
+}
+
+/// Where `phrase` (one or more words) starts in `words`. A word also matches its plural ("tradeoffs").
+fn phrase_at(words: &[String], phrase: &str) -> Vec<usize> {
+ let parts: Vec<&str> = phrase.split(' ').collect();
+ if parts.is_empty() || words.len() < parts.len() {
+ return Vec::new();
+ }
+ let same = |w: &str, p: &str| w == p || w.strip_suffix('s').is_some_and(|x| x == p) || w.strip_suffix("es").is_some_and(|x| x == p);
+ (0..=words.len() - parts.len())
+ .filter(|&i| parts.iter().enumerate().all(|(j, p)| same(&words[i + j], p)))
+ .collect()
+}
+
+/// True when `phrase` appears in `words` as whole words.
+pub(crate) fn has_phrase(words: &[String], phrase: &str) -> bool {
+ !phrase_at(words, phrase).is_empty()
}
+fn has_any(words: &[String], phrases: &[&str]) -> bool {
+ phrases.iter().any(|p| has_phrase(words, p))
+}
+
+/// A deep signal that isn't part of an everyday phrase and isn't negated just before it.
+fn has_deep_signal(text: &str) -> bool {
+ let mut ws = words(text);
+ for idiom in NOT_DEEP {
+ let len = idiom.split(' ').count();
+ for i in phrase_at(&ws, idiom) {
+ for w in &mut ws[i..i + len] {
+ w.clear();
+ }
+ }
+ }
+ let negated = |i: usize| {
+ let before = &ws[i.saturating_sub(2)..i];
+ NEGATIONS.iter().any(|n| has_phrase(before, n))
+ };
+ DEEP_SIGNALS.iter().any(|s| phrase_at(&ws, s).into_iter().any(|i| !negated(i)))
+}
+
+/// Chinese, Japanese and Korean text has no spaces between words.
+fn is_cjk(c: char) -> bool {
+ matches!(c as u32, 0x3040..=0x30FF | 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xAC00..=0xD7AF | 0xF900..=0xFAFF)
+}
+
+/// Roughly how many words `prompt` has: words between spaces, and about one per two CJK characters,
+/// so a Chinese paragraph isn't counted as one word.
+fn word_count(prompt: &str) -> usize {
+ prompt
+ .split_whitespace()
+ .map(|w| {
+ let cjk = w.chars().filter(|&c| is_cjk(c)).count();
+ if cjk == 0 { 1 } else { cjk.div_ceil(2) + usize::from(w.chars().any(|c| c.is_alphanumeric() && !is_cjk(c))) }
+ })
+ .sum()
+}
+
+/// Asks for a one-line answer ("in one line", "just tell me…").
+const BRIEF: &[&str] = &["in one line", "one-liner", "in one word", "just tell me", "quick question"];
+
/// Greetings, jokes and tiny one-liners never need deep reasoning.
fn is_trivial(prompt: &str, max_words: usize) -> bool {
let lower = prompt.to_lowercase();
- let first = lower.split(|c: char| !c.is_alphanumeric()).find(|w| !w.is_empty()).unwrap_or("");
- prompt.split_whitespace().count() <= max_words
+ let ws = words(prompt);
+ let first = ws.first().map(String::as_str).unwrap_or("");
+ word_count(prompt) <= max_words
|| matches!(first, "hi" | "hello" | "hey" | "ping" | "thanks" | "thank" | "yo")
|| lower.starts_with("say ")
|| lower.contains("joke")
|| lower.contains("who are you")
+ || has_any(&ws, BRIEF)
}
/// Keyword-only effort estimate, used when Laya is offline.
pub fn heuristic_effort(prompt: &str, context: &str) -> &'static str {
- let combined = format!("{} {}", prompt.to_lowercase(), context.to_lowercase());
- if has_deep_signal(&combined) || prompt.split_whitespace().count() >= 30 {
+ if has_deep_signal(prompt) || has_deep_signal(context) || word_count(prompt) >= 30 {
"high"
} else if is_trivial(prompt, 6) {
"low"
@@ -34,10 +113,12 @@ pub fn heuristic_effort(prompt: &str, context: &str) -> &'static str {
}
}
-/// Laya's effort answer is a weak signal (it rated greetings "medium" and root-cause or trade-off
-/// questions "low"), so unambiguous keyword signals override it in either direction.
+/// Laya's effort answer is a weak signal: it rated a multi-file refactor, a root-cause hunt and an
+/// architecture design "medium", so a clear keyword raises those to "high". But when Laya says "low"
+/// it is usually right about a keyword that is only mentioned ("don't refactor anything", "what is a
+/// deep copy, in one line"), so keywords never raise a "low". Greetings are always "low".
pub fn blend_effort(prompt: &str, laya_effort: &str) -> String {
- if has_deep_signal(&prompt.to_lowercase()) {
+ if laya_effort != "low" && has_deep_signal(prompt) {
"high".into()
} else if is_trivial(prompt, 3) {
"low".into()
@@ -46,6 +127,24 @@ pub fn blend_effort(prompt: &str, laya_effort: &str) -> String {
}
}
+/// Asks to keep the work on this machine. Bare "local" is not one of them: "localhost", "locale" and
+/// "my local coffee shop" aren't private.
+const PRIVATE: &[&str] = &[
+ "private", "confidential", "sensitive", "offline", "ollama", "local model", "local llm", "locally",
+ "on-device", "on device", "on my machine", "private data",
+];
+
+/// Needs long reasoning or writing.
+const REASONING: &[&str] = &[
+ "architecture", "architectural", "design doc", "tradeoff", "trade-off", "refactor", "refactoring",
+ "analysis", "philosophy", "essay",
+];
+
+/// Asks for code.
+const CODING: &[&str] = &[
+ "python", "rust", "javascript", "typescript", "code", "script", "regex", "algorithm", "function",
+];
+
/// Evaluates a prompt using local keyword scoring heuristics when Laya is offline.
pub fn heuristic_fallback(prompt: &str, context: &str) -> RouteDecision {
heuristic_fallback_with_models(prompt, context, &[])
@@ -57,9 +156,7 @@ pub fn heuristic_fallback_with_models(
context: &str,
available_models: &[String],
) -> RouteDecision {
- let lower_prompt = prompt.to_lowercase();
- let lower_context = context.to_lowercase();
- let combined = format!("{} {}", lower_prompt, lower_context);
+ let combined = words(&format!("{prompt} {context}"));
let effort_level = heuristic_effort(prompt, context).to_string();
@@ -68,11 +165,7 @@ pub fn heuristic_fallback_with_models(
};
// 1. Private / local check
- if (combined.contains("private")
- || combined.contains("confidential")
- || combined.contains("local")
- || combined.contains("offline")
- || combined.contains("sensitive"))
+ if has_any(&combined, PRIVATE)
&& is_available("local_ollama") {
return RouteDecision {
selected_model: "local_ollama".into(),
@@ -87,13 +180,7 @@ pub fn heuristic_fallback_with_models(
}
// 2. Complex architecture / multi-file / deep analysis check
- if (combined.contains("architecture")
- || combined.contains("design doc")
- || combined.contains("tradeoff")
- || combined.contains("refactor")
- || combined.contains("analysis")
- || combined.contains("philosophy")
- || combined.contains("essay"))
+ if has_any(&combined, REASONING)
&& is_available("claude") {
return RouteDecision {
selected_model: "claude".into(),
@@ -108,15 +195,7 @@ pub fn heuristic_fallback_with_models(
}
// 3. Direct coding / script / regex check
- if (combined.contains("python")
- || combined.contains("rust")
- || combined.contains("javascript")
- || combined.contains("typescript")
- || combined.contains("code")
- || combined.contains("script")
- || combined.contains("regex")
- || combined.contains("algorithm")
- || combined.contains("function"))
+ if has_any(&combined, CODING)
&& is_available("codex") {
return RouteDecision {
selected_model: "codex".into(),
diff --git a/src/router/laya.rs b/src/router/laya.rs
index 82d48bbc..db9fa8b7 100644
--- a/src/router/laya.rs
+++ b/src/router/laya.rs
@@ -103,31 +103,17 @@ impl LayaRouter {
}
}
- let payload = json!({
- "state": {
- "prompt": prompt,
- "context": context
- },
- "questions": {
- "model_selection": {
- "type": "choice",
- "instructions": "Which available model is best suited for this task?",
- "criteria": criteria
- },
- "effort_level": {
- "type": "choice",
- "instructions": "What reasoning effort / compute depth is needed for this task?",
- "criteria": {
- "low": "quick answers, greetings, short definitions, simple edits",
- "medium": "standard coding, explanations, moderate feature implementation",
- "high": "deep architecture, difficult bug root cause analysis, complex refactoring"
- }
- }
- }
- });
-
+ let payload = model_payload(prompt, context, criteria);
let endpoint = format!("{}/v1/systemone", self.base_url.trim_end_matches('/'));
+ let started = std::time::Instant::now();
+ let fallback = |why: &str| {
+ // Info, not debug: on a slow machine Laya can miss the 1.5s limit on most messages, and
+ // then keywords are routing without anyone knowing.
+ tracing::info!(elapsed_ms = started.elapsed().as_millis() as u64, reason = why, "Laya didn't pick the model for this message; using keyword fallback");
+ crate::router::fallback::heuristic_fallback_with_models(prompt, context, &candidate_models)
+ };
+
match self.client.post(&endpoint).json(&payload).send().await {
Ok(resp) if resp.status().is_success() => {
match resp.json::<serde_json::Value>().await {
@@ -141,26 +127,55 @@ impl LayaRouter {
return Ok(decision);
}
tracing::warn!("Laya response missing expected fields, using fallback");
- Ok(crate::router::fallback::heuristic_fallback_with_models(prompt, context, &candidate_models))
+ Ok(fallback("missing fields"))
}
Err(e) => {
tracing::warn!(error = %e, "Failed to parse Laya response body, using fallback");
- Ok(crate::router::fallback::heuristic_fallback_with_models(prompt, context, &candidate_models))
+ Ok(fallback(if e.is_timeout() { "timeout" } else { "unreadable body" }))
}
}
}
Ok(resp) => {
tracing::warn!(status = %resp.status(), "Laya service returned error, using fallback");
- Ok(crate::router::fallback::heuristic_fallback_with_models(prompt, context, &candidate_models))
+ Ok(fallback("error status"))
}
Err(e) => {
tracing::debug!(error = %e, "Laya service unreachable, using fallback");
- Ok(crate::router::fallback::heuristic_fallback_with_models(prompt, context, &candidate_models))
+ Ok(fallback(if e.is_timeout() { "timeout" } else { "unreachable" }))
}
}
}
}
+/// The `/v1/systemone` request for picking a model and effort. Laya's answers depend on the order of
+/// the questions and options it sees: with serde_json's default sorted maps, `effort_level` comes
+/// before `model_selection` and options are alphabetical, which measured 30/33 on the routing eval
+/// against 24-25/33 in written order (laya-eval/results.md, P5). A test pins the exact bytes.
+pub fn model_payload(prompt: &str, context: &str, criteria: serde_json::Map<String, serde_json::Value>) -> serde_json::Value {
+ json!({
+ "state": {
+ "prompt": prompt,
+ "context": context
+ },
+ "questions": {
+ "model_selection": {
+ "type": "choice",
+ "instructions": "Which available model is best suited for this task?",
+ "criteria": criteria
+ },
+ "effort_level": {
+ "type": "choice",
+ "instructions": "What reasoning effort / compute depth is needed for this task?",
+ "criteria": {
+ "low": "quick answers, greetings, short definitions, simple edits",
+ "medium": "standard coding, explanations, moderate feature implementation",
+ "high": "deep architecture, difficult bug root cause analysis, complex refactoring"
+ }
+ }
+ }
+ })
+}
+
/// Accepts either the Laya root (`http://host:8000`) or a full endpoint URL
/// (`http://host:8000/v1/systemone`) and returns the root, so paths are never doubled.
pub fn normalize_base_url(url: &str) -> String {
diff --git a/src/router/team.rs b/src/router/team.rs
index 7555cb4b..e98adcfd 100644
--- a/src/router/team.rs
+++ b/src/router/team.rs
@@ -126,11 +126,15 @@ impl LayaRouter {
lead_kwant_id: &str,
members: &[Kwant],
) -> ChannelRoute {
+ let started = std::time::Instant::now();
let laya = match self.query_laya_for_kwant(prompt, channel_name, members).await {
Ok(data) => laya_guess(&data, members),
Err(e) => {
+ let elapsed_ms = started.elapsed().as_millis() as u64;
if self.status().is_up() {
- tracing::warn!(error = %e, url = %self.base_url, "Laya channel routing failed, using keyword fallback");
+ tracing::warn!(error = %e, url = %self.base_url, elapsed_ms, "Laya channel routing failed, using keyword fallback");
+ } else {
+ tracing::info!(error = %e, elapsed_ms, "Laya didn't pick the bot for this message; using keyword fallback");
}
None
}
@@ -255,7 +259,7 @@ pub struct LayaGuess<'a> {
pub confident: bool,
}
-fn laya_guess<'a>(data: &serde_json::Value, members: &'a [Kwant]) -> Option<LayaGuess<'a>> {
+pub fn laya_guess<'a>(data: &serde_json::Value, members: &'a [Kwant]) -> Option<LayaGuess<'a>> {
let lead = data.get("answers")?.get("lead_kwant")?;
let kwant = resolve_kwant_choice(lead.get("choice")?.as_str()?, members)?;
let mut probs: Vec<f64> = lead
@@ -293,7 +297,7 @@ pub struct Pick<'a> {
pub terms: Vec<String>,
}
-/// Engineering roles and the words in a request that belong to them. A bot has a role when its title
+/// Roles and the words in a request that belong to them. A bot has a role when its title
/// (or, without a title, the first line of its persona) names it; Laya only compares titles, so it
/// can't tell that "strategy" in a trading repo is backend code, and picked Frontend for it.
struct Role {
@@ -309,6 +313,7 @@ const ROLES: &[Role] = &[
("ui", 2), ("ux", 2), ("frontend", 2), ("front-end", 2), ("page", 2), ("button", 2), ("css", 2),
("component", 2), ("layout", 2), ("screen", 2), ("react", 2), ("modal", 2), ("responsive", 2),
("style", 1), ("styling", 2), ("dashboard", 1), ("form", 1), ("color", 1), ("colour", 1), ("dark", 1),
+ ("screens", 2), ("pages", 1), ("ipad", 1), ("iphone", 1),
],
},
Role {
@@ -319,6 +324,8 @@ const ROLES: &[Role] = &[
("migration", 2), ("server", 2), ("service", 1), ("strategy", 2), ("strategies", 2), ("backtest", 2),
("trading", 2), ("indicator", 2), ("order", 1), ("orders", 1), ("algorithm", 2), ("query", 1),
("sql", 2), ("golang", 2), ("go", 1), ("rust", 1), ("function", 1), ("cli", 1), ("parser", 2),
+ ("python", 1), ("script", 2), ("scripts", 2), ("scrape", 2), ("scraper", 2), ("crash", 2),
+ ("crashes", 2), ("crashing", 2), ("traceback", 2), ("exception", 2), ("error", 1),
],
},
Role {
@@ -336,8 +343,62 @@ const ROLES: &[Role] = &[
("terraform", 2), ("outage", 2), ("uptime", 2), ("release", 1), ("logs", 1),
],
},
+ Role {
+ titles: &["designer", "design", "graphic", "visual", "brand", "branding", "illustrator", "art", "creative", "ux", "ui"],
+ signals: &[
+ ("logo", 2), ("logos", 2), ("palette", 2), ("mockup", 2), ("mockups", 2), ("wireframe", 2),
+ ("wireframes", 2), ("figma", 2), ("usability", 2), ("typography", 2), ("illustration", 2), ("icon", 2),
+ ("icons", 2), ("visuals", 2), ("branding", 2), ("redesign", 2), ("brand", 1), ("font", 1),
+ ("prettier", 1), ("design", 1), ("visual", 1), ("color", 1), ("colour", 1),
+ ],
+ },
+ Role {
+ titles: &["marketing", "marketer", "growth", "seo", "copywriter", "content", "social", "community", "pr"],
+ signals: &[
+ ("marketing", 2), ("seo", 2), ("landing-page", 2), ("copywriting", 2), ("campaign", 2),
+ ("campaigns", 2), ("ad", 2), ("ads", 2), ("tweet", 2), ("tweets", 2), ("newsletter", 2), ("blog", 2),
+ ("tagline", 2), ("slogan", 2), ("headline", 2), ("headlines", 2), ("announcement", 2),
+ ("instagram", 2), ("tiktok", 2), ("linkedin", 2), ("copy", 1), ("launch", 1), ("social", 1),
+ ("audience", 1), ("conversion", 1), ("post", 1),
+ ],
+ },
+ Role {
+ titles: &["research", "researcher", "analyst", "analytics", "insights"],
+ signals: &[
+ ("research", 2), ("market-size", 2), ("market-research", 2), ("survey", 2), ("surveys", 2),
+ ("churn", 2), ("retention", 2), ("trends", 2), ("insights", 2), ("study", 2), ("studies", 2),
+ ("market", 1), ("competitor", 1), ("competitors", 1), ("competition", 1), ("pricing", 1),
+ ("compare", 1), ("analyze", 1), ("analyse", 1), ("analysis", 1), ("data", 1), ("report", 1),
+ ("interviews", 1),
+ ],
+ },
];
+/// Titles that say "engineer" without saying which kind. They count as the backend (code) role, but
+/// only for a bot no other title word places: a "QA Engineer" is QA, a "Full-stack Software
+/// Engineer" writes the code.
+const GENERIC_ENGINEER_TITLES: &[&str] = &[
+ "engineer", "engineering", "developer", "dev", "software", "full-stack", "fullstack", "programmer", "coder", "swe",
+];
+
+/// Two words that mean something else together: a landing page is marketing, not a UI page.
+const COMPOUNDS: &[(&str, &str)] = &[("landing", "page"), ("market", "size"), ("market", "research")];
+
+/// [`tokens`] with [`COMPOUNDS`] joined by a hyphen, for role matching.
+fn role_words(text: &str) -> Vec<String> {
+ let mut out: Vec<String> = Vec::new();
+ for w in tokens(text) {
+ if let Some(prev) = out.last_mut() {
+ if COMPOUNDS.iter().any(|(a, b)| prev == a && w == *b) {
+ *prev = format!("{prev}-{w}");
+ continue;
+ }
+ }
+ out.push(w);
+ }
+ out
+}
+
fn tokens(text: &str) -> Vec<String> {
text.to_lowercase()
.split(|c: char| !c.is_alphanumeric() && c != '-')
@@ -349,10 +410,16 @@ fn tokens(text: &str) -> Vec<String> {
fn roles_of(kwant: &Kwant) -> Vec<&'static Role> {
let mut own = tokens(&kwant.title);
own.extend(tokens(&kwant.name));
- let mut roles: Vec<&Role> = ROLES.iter().filter(|r| r.titles.iter().any(|t| own.iter().any(|o| o == t))).collect();
- if roles.is_empty() && kwant.title.trim().is_empty() {
+ if kwant.title.trim().is_empty() {
+ own = tokens(&kwant.name);
let first = tokens(kwant.persona_prompt.split(['.', '\n']).next().unwrap_or(""));
- roles = ROLES.iter().filter(|r| r.titles.iter().any(|t| first.iter().any(|o| o == t))).collect();
+ if !ROLES.iter().any(|r| r.titles.iter().any(|t| own.iter().any(|o| o == t))) {
+ own = first;
+ }
+ }
+ let roles: Vec<&Role> = ROLES.iter().filter(|r| r.titles.iter().any(|t| own.iter().any(|o| o == t))).collect();
+ if roles.is_empty() && own.iter().any(|o| GENERIC_ENGINEER_TITLES.contains(&o.as_str())) {
+ return ROLES.iter().filter(|r| r.titles.contains(&"backend")).collect();
}
roles
}
@@ -444,8 +511,9 @@ pub fn pick_member<'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(&words, m))).map(|(m, (s, t))| (m, s, t)).collect();
+ members.iter().map(|m| (m, 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();
@@ -481,26 +549,41 @@ pub fn pick_member<'a>(
// rather than send the message to whoever happens to lead.
let matches: Vec<Vec<(String, usize)>> = members.iter().map(|m| relevance_terms(prompt, m)).collect();
let shared = |w: &str| matches.iter().filter(|terms| terms.iter().any(|(t, _)| t == w)).count() > 1;
- let scored: Vec<(&Kwant, usize, Vec<String>)> = members
+ // (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
.iter()
.zip(&roles)
.zip(&matches)
.map(|((m, (_, rs, rt)), terms)| {
let own: Vec<&(String, usize)> = terms.iter().filter(|(t, _)| !shared(t)).collect();
let s = own.iter().map(|(_, s)| s).sum::<usize>();
+ let named = own.iter().any(|(_, s)| *s >= 2);
let mut t: Vec<String> = own.iter().map(|(t, _)| t.clone()).collect();
for w in rt {
if !t.contains(w) {
t.push(w.clone());
}
}
- (m, s + rs, t)
+ (m, s + rs, t, named)
})
.collect();
- let top = scored.iter().map(|(_, s, _)| *s).max().unwrap_or(0);
+ let top = scored.iter().map(|(_, s, _, _)| *s).max().unwrap_or(0);
let best: Vec<usize> = (0..scored.len()).filter(|&i| top > 0 && scored[i].1 == top).collect();
+ // Words only in a bot's persona, or a weak role hint ("plan" in "writes test plans", "page"),
+ // are a guess too, so a clear Laya pick of another bot wins over them.
+ let laya_clear = laya.filter(|g| g.confident);
+ let weak = |i: usize| !scored[i].3;
+ if let ([i], Some(g)) = (best.as_slice(), laya_clear) {
+ if weak(*i) && scored[*i].0.id != g.kwant.id {
+ let reason = format!(
+ "Laya matched this to {}'s role ({}); the only words in your message that pointed elsewhere were in {}'s description",
+ g.kwant.name, g.kwant.title, scored[*i].0.name
+ );
+ return Some(Pick { kwant: g.kwant, basis: "skills", reason, terms: vec![] });
+ }
+ }
if let [i] = best.as_slice() {
- let (k, _, terms) = &scored[*i];
+ let (k, _, terms, _) = &scored[*i];
let how = format!("shares words with your message: {}", terms.join(", "));
return Some(chosen(k, terms.clone(), &how));
}
diff --git a/tests/laya_fallback_log_test.rs b/tests/laya_fallback_log_test.rs
new file mode 100644
index 00000000..576697c6
--- /dev/null
+++ b/tests/laya_fallback_log_test.rs
@@ -0,0 +1,83 @@
+//! When Laya misses its 1.5s limit, kwant routes by keywords. That has to show in the log at info, with
+//! how long it waited, or nobody can tell how often Laya actually decides (laya-eval: 31 of 33 model
+//! queries timed out on a 2-vCPU server, and the old log line was at debug).
+use kwnt::db::models::Kwant;
+use kwnt::router::LayaRouter;
+use std::io::Write;
+use std::sync::{Arc, Mutex};
+
+#[derive(Clone, Default)]
+struct Logs(Arc<Mutex<Vec<u8>>>);
+
+impl Write for Logs {
+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
+ self.0.lock().unwrap().extend_from_slice(buf);
+ Ok(buf.len())
+ }
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+}
+
+fn bot(id: &str, title: &str) -> Kwant {
+ Kwant {
+ space_id: kwnt::db::spaces::DEFAULT_SPACE_ID.into(),
+ id: id.into(),
+ name: id.into(),
+ title: title.into(),
+ persona_prompt: String::new(),
+ soul: String::new(),
+ avatar_sprite: String::new(),
+ driver_type: "api".into(),
+ preferred_model: "auto".into(),
+ temperature: 0.7,
+ max_tokens: 4096,
+ level: 1,
+ turns_completed: 0,
+ created_at: None,
+ }
+}
+
+/// The ms value of the first `elapsed_ms=` in `line`.
+fn elapsed(line: &str) -> u64 {
+ let rest = &line[line.find("elapsed_ms=").expect(line) + "elapsed_ms=".len()..];
+ rest.chars().take_while(char::is_ascii_digit).collect::<String>().parse().unwrap()
+}
+
+#[tokio::test]
+async fn a_laya_timeout_is_logged_at_info_with_the_wait() {
+ let logs = Logs::default();
+ let sink = logs.clone();
+ let subscriber = tracing_subscriber::fmt()
+ .with_max_level(tracing::Level::INFO)
+ .with_ansi(false)
+ .with_writer(move || sink.clone())
+ .finish();
+ tracing::subscriber::set_global_default(subscriber).unwrap();
+
+ // A Laya that accepts the connection and never answers
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let url = format!("http://{}", listener.local_addr().unwrap());
+ tokio::spawn(async move {
+ let mut held = Vec::new();
+ while let Ok((sock, _)) = listener.accept().await {
+ held.push(sock);
+ }
+ });
+ let router = LayaRouter::new(url);
+
+ let decision = router.route_prompt("Write a regex for ISO dates", "chat").await.unwrap();
+ assert!(decision.is_fallback);
+ let text = String::from_utf8_lossy(&logs.0.lock().unwrap()).into_owned();
+ let line = text.lines().find(|l| l.contains("Laya didn't pick the model")).unwrap_or_else(|| panic!("no info line:\n{text}"));
+ assert!(line.contains(" INFO ") && line.contains("timeout"), "{line}");
+ assert!((1400..10_000).contains(&elapsed(line)), "{line}");
+
+ let members = [bot("a", "Backend Engineer"), bot("b", "Designer")];
+ let route = router.route_channel_query_detailed("hello", "general", "a", &members).await;
+ assert!(route.fallback);
+ let text = String::from_utf8_lossy(&logs.0.lock().unwrap()).into_owned();
+ let line = text.lines().find(|l| l.contains("Laya didn't pick the bot")).unwrap_or_else(|| panic!("no info line:\n{text}"));
+ assert!(line.contains(" INFO "), "{line}");
+ assert!((1400..10_000).contains(&elapsed(line)), "{line}");
+}
diff --git a/tests/router_test.rs b/tests/router_test.rs
index 1a10a1ca..5f315fda 100644
--- a/tests/router_test.rs
+++ b/tests/router_test.rs
@@ -394,7 +394,9 @@ fn test_blend_effort_overrides_only_clear_signals() {
use kwnt::router::fallback::blend_effort;
assert_eq!(blend_effort("hi there", "medium"), "low");
assert_eq!(blend_effort("Tell me a joke about Kubernetes", "medium"), "low");
- assert_eq!(blend_effort("Should we split our monolith? Compare tradeoffs", "low"), "high");
+ assert_eq!(blend_effort("Should we split our monolith? Compare tradeoffs", "medium"), "high");
+ // Laya's "low" stands: a keyword alone no longer raises it (laya-eval a01, a03)
+ assert_eq!(blend_effort("Should we split our monolith? Compare tradeoffs", "low"), "low");
assert_eq!(blend_effort("Postgres latency doubled, find the root cause", "medium"), "high");
assert_eq!(blend_effort("Plan a 5-day trip to Lisbon in November", "medium"), "medium");
assert_eq!(blend_effort("Plan a 5-day trip to Lisbon in November", "low"), "low");
@@ -544,3 +546,170 @@ async fn channel_routing_reports_its_basis() {
let r = laya.route_channel_query_detailed("hello", "desk", "lead", &members[1..2]).await;
assert_eq!((r.kwant_id.as_str(), r.basis.as_str()), ("fe", "only"));
}
+
+// Cases below come from the Laya routing eval (shared/ship-software-safely/laya-eval/eval.json); the
+// id in each message is the eval prompt's id.
+
+const EVAL_MODELS: [&str; 4] = ["claude", "grok", "codex", "local_ollama"];
+
+fn offline_model(prompt: &str) -> String {
+ let models: Vec<String> = EVAL_MODELS.iter().map(|m| m.to_string()).collect();
+ kwnt::router::fallback::heuristic_fallback_with_models(prompt, "chat", &models).selected_model
+}
+
+#[test]
+fn offline_keywords_match_whole_words_only() {
+ // "local" inside another word, or a local business, is not a request to stay on this machine
+ for (id, prompt) in [
+ ("m17", "Why does my React app fail to reach localhost:3000 from inside the Docker container?"),
+ ("m18", "How do I set the locale to de_DE in a Python script for number formatting?"),
+ ("m25", "Is it safe to store JWTs in localStorage?"),
+ ("a07", "My local coffee shop wants a tagline for its new menu. Give me 5 ideas."),
+ ] {
+ assert_ne!(offline_model(prompt), "local_ollama", "{id}: {prompt}");
+ }
+ // "script" inside "description" is not code
+ assert_eq!(offline_model("Write a punchy product description for our handmade soy candle shop"), "claude", "m11");
+ assert_eq!(offline_model("I don't trust this vendor, draft a polite email asking for references"), "claude", "'rust' in 'trust'");
+
+ // Explicit requests still stay local
+ for (id, prompt) in [
+ ("m14", "Summarize my private medical lab results: total cholesterol 240, LDL 160, HDL 38"),
+ ("m15", "This is confidential: find duplicate entries in my password manager export"),
+ ("m16", "I'm offline on a plane. Rename these photos by date taken"),
+ ("-", "Use a local model for this, it's private data"),
+ ("-", "Run this locally with ollama"),
+ ] {
+ assert_eq!(offline_model(prompt), "local_ollama", "{id}: {prompt}");
+ }
+ // And whole words still route as before, plurals included
+ assert_eq!(offline_model("How do I set the locale to de_DE in a Python script for number formatting?"), "codex", "m18");
+ assert_eq!(offline_model("Write two Python scripts that rename every .jpeg file to .jpg"), "codex", "m21");
+ assert_eq!(offline_model("Design a multi-tenant billing system and explain the tradeoffs"), "claude", "m10");
+}
+
+#[test]
+fn negated_and_idiomatic_keywords_dont_make_offline_effort_high() {
+ use kwnt::router::fallback::heuristic_effort;
+ assert_eq!(heuristic_effort("Please don't refactor anything, just tell me what time zone Paris is in", "chat"), "low", "a01");
+ assert_ne!(heuristic_effort("Write a friendly reminder text for the security guards about the Friday night shift", "chat"), "high", "a02");
+ assert_eq!(heuristic_effort("Explain what a 'deep copy' is in Python in one line", "chat"), "low", "a03");
+ // Real signals still count
+ for (id, prompt) in [
+ ("m08", "Refactor the auth module across the 12 files in src/auth to use one Session trait and update every call site"),
+ ("m09", "Our checkout service times out under load but only on Tuesdays. Help me find the root cause; CPU and DB look normal."),
+ ("m10", "Design a multi-tenant billing system with usage-based pricing and explain the tradeoffs"),
+ ("-", "Do a security review of the login flow"),
+ ("-", "Plan the migration of our orders table"),
+ ] {
+ assert_eq!(heuristic_effort(prompt, "chat"), "high", "{id}: {prompt}");
+ }
+ // A Chinese paragraph is many words, not one trivial word
+ assert_ne!(heuristic_effort("请帮我分析这个微服务架构的取舍,并给出迁移方案", "chat"), "low", "m24");
+ assert_eq!(heuristic_effort("你好", "chat"), "low");
+}
+
+#[test]
+fn keywords_raise_layas_medium_but_not_its_low() {
+ use kwnt::router::fallback::blend_effort;
+ // Laya said medium; a clear keyword makes these high (m08-m10)
+ assert_eq!(blend_effort("Refactor the auth module across the 12 files in src/auth to use one Session trait and update every call site", "medium"), "high", "m08");
+ assert_eq!(blend_effort("Our checkout service times out under load but only on Tuesdays. Help me find the root cause; CPU and DB look normal.", "medium"), "high", "m09");
+ assert_eq!(blend_effort("Design a multi-tenant billing system with usage-based pricing and explain the tradeoffs", "medium"), "high", "m10");
+ // Laya said low; a keyword that is only mentioned doesn't overrule it (a01, a03)
+ assert_eq!(blend_effort("Please don't refactor anything, just tell me what time zone Paris is in", "low"), "low", "a01");
+ assert_eq!(blend_effort("Explain what a 'deep copy' is in Python in one line", "low"), "low", "a03");
+ // Not a deep signal at all (a02)
+ assert_eq!(blend_effort("Write a friendly reminder text for the security guards about the Friday night shift", "medium"), "medium", "a02");
+}
+
+#[test]
+fn laya_model_payload_keeps_its_measured_key_order() {
+ // Laya's picks depend on the order it sees questions and options in. Sorted keys (effort_level
+ // first, options alphabetical) scored 30/33 on the routing eval; written order scored 24-25/33.
+ // If this fails because serde_json's preserve_order got enabled, re-run the eval before accepting it.
+ let mut criteria = serde_json::Map::new();
+ criteria.insert("grok".into(), json!("g"));
+ criteria.insert("claude".into(), json!("c"));
+ criteria.insert("local_ollama".into(), json!("l"));
+ criteria.insert("codex".into(), json!("x"));
+ let payload = kwnt::router::laya::model_payload("hi", "chat", criteria);
+ assert_eq!(
+ serde_json::to_string(&payload).unwrap(),
+ concat!(
+ r#"{"questions":{"effort_level":{"criteria":{"high":"deep architecture, difficult bug root cause analysis, complex refactoring","#,
+ r#""low":"quick answers, greetings, short definitions, simple edits","#,
+ r#""medium":"standard coding, explanations, moderate feature implementation"},"#,
+ r#""instructions":"What reasoning effort / compute depth is needed for this task?","type":"choice"},"#,
+ r#""model_selection":{"criteria":{"claude":"c","codex":"x","grok":"g","local_ollama":"l"},"#,
+ r#""instructions":"Which available model is best suited for this task?","type":"choice"}},"#,
+ r#""state":{"context":"chat","prompt":"hi"}}"#,
+ )
+ );
+}
+
+/// The 5-bot team from the routing eval, each bot with its title and one-line persona.
+fn eval_team() -> Vec<Kwant> {
+ let bot = |name: &str, title: &str, persona: &str| {
+ let mut k = agent(&name.to_lowercase(), name, title);
+ k.persona_prompt = persona.into();
+ k
+ };
+ vec![
+ bot("Dev", "Full-stack Software Engineer", "You are a senior full-stack engineer who writes and reviews code."),
+ bot("Mia", "Marketing Manager", "You write marketing copy, campaigns and newsletters."),
+ bot("Remy", "Research Analyst", "You research markets and competitors and analyze data."),
+ bot("Dana", "UI/UX Designer", "You design interfaces, logos and brand visuals."),
+ bot("Quinn", "QA Engineer", "You test software and write test plans."),
+ ]
+}
+
+#[test]
+fn marketing_research_design_and_generic_engineers_have_roles() {
+ let members = eval_team();
+ let pick = |prompt: &str| kwnt::router::team::pick_member(prompt, "dev", &members, None, "channel lead").unwrap().kwant.name.clone();
+ for (id, prompt, who) in [
+ ("b03", "Write 5 tweets announcing our launch", "Mia"),
+ ("b13", "Improve the SEO of our landing page copy", "Mia"),
+ ("x02", "Write a test plan for our ad campaign A/B test", "Mia"),
+ ("b04", "Find three competitors and compare their pricing", "Remy"),
+ ("b07", "What's the market size for language-learning apps?", "Remy"),
+ ("b22", "Analyze our churn data and suggest why users leave", "Remy"),
+ ("b15", "Is the new checkout flow confusing? Do a usability review", "Dana"),
+ ("b21", "Make the onboarding screens prettier", "Dana"),
+ ("b06", "Design a new logo concept for the app", "Dana"),
+ ("b23", "Write a Python script to scrape competitor prices", "Dev"),
+ ("b02", "Fix the 500 error in the /orders endpoint", "Dev"),
+ ("b05", "Write test cases for the password reset flow", "Quinn"),
+ ] {
+ assert_eq!(pick(prompt), who, "{id}: {prompt}");
+ }
+ // A specific title wins over the generic "engineer": Quinn is QA, not backend
+ assert_eq!(pick("Add a database index to speed up the search queries"), "Dev", "b09");
+}
+
+#[test]
+fn a_clear_laya_pick_beats_words_only_in_a_persona() {
+ let members = eval_team();
+ let laya_says = |name: &str| {
+ let mut probs = serde_json::Map::new();
+ for m in &members {
+ probs.insert(m.name.clone(), json!(if m.name == name { 0.6 } else { 0.1 }));
+ }
+ json!({"answers": {"lead_kwant": {"choice": name, "probabilities": probs}}})
+ };
+ let route = |prompt: &str, laya: &serde_json::Value| {
+ let guess = kwnt::router::team::laya_guess(laya, &members);
+ let p = kwnt::router::team::pick_member(prompt, "dev", &members, guess, "channel lead").unwrap();
+ (p.kwant.name.clone(), p.basis)
+ };
+ // "plan" is only in Quinn's persona ("writes test plans"); Laya is sure it's Mia's
+ assert_eq!(route("Plan our content calendar for next month", &laya_says("Mia")), ("Mia".into(), "skills"));
+ // "review" is only in Dev's persona ("reviews code"); Laya is sure it's Dana's
+ assert_eq!(route("Give the checkout flow a quick review", &laya_says("Dana")), ("Dana".into(), "skills"));
+ // A near-tie from Laya doesn't override them
+ let unsure = json!({"answers": {"lead_kwant": {"choice": "Mia", "probabilities": {"Mia": 0.3, "Quinn": 0.25, "Dev": 0.2, "Remy": 0.15, "Dana": 0.1}}}});
+ assert_eq!(route("Plan our content calendar for next month", &unsure).0, "Quinn");
+ // A word in a bot's title still beats Laya: that is the role the person named
+ assert_eq!(route("Ask the designer about this", &laya_says("Mia")).0, "Dana");
+}