1pub mod config;
16mod llm;
17mod ollama;
18pub mod profiles;
19mod selection;
20mod strategies;
21pub mod weights;
22
23use crate::backends::ExternalTask;
24use crate::cooldown;
25use crate::cooldown::{
26 cooldown_until, is_agent_degraded, is_agent_in_cooldown, is_model_in_cooldown,
27 list_degraded_agents, record_agent_success, refresh_degraded_agents, sync_from_kv,
28};
29use crate::engine::agents::opencode;
30use crate::store::WaitingOnDependency;
31use crate::store::{TaskStore, get_task_field_direct, store_log_activity};
32use crate::sys::cmd_cache;
33pub use config::{RouterConfig, parse_pool_entry};
34use llm::{LlmRouter, TIMEOUT_PREFIX};
35use serde::{Deserialize, Serialize};
36use std::collections::HashSet;
37use std::fmt;
38use std::fmt::Debug;
39use std::fmt::Formatter;
40use std::sync::Arc;
41use tokio::task;
42pub use weights::AgentWeights;
43
44fn fmt_degraded(degraded: &[String]) -> String {
45 if degraded.is_empty() {
46 String::new()
47 } else {
48 format!(" (degraded: {})", degraded.join(", "))
49 }
50}
51
52fn is_max_turns_error(err_msg: &str) -> bool {
54 let lower = err_msg.to_ascii_lowercase();
55 lower.contains("max turns reached") || lower.contains("reached the maximum number of turns")
56}
57
58#[derive(Debug, thiserror::Error)]
63pub enum AllAgentsCooledError {
64 #[error("all agents/models in cooldown for {scope}{}", fmt_degraded(.degraded))]
65 AllCooled {
66 scope: String,
67 remaining_secs: Option<u64>,
68 degraded: Vec<String>,
69 },
70}
71
72impl AllAgentsCooledError {
73 pub fn new(scope: String, remaining_secs: Option<u64>) -> Self {
75 Self::AllCooled {
76 scope,
77 remaining_secs,
78 degraded: list_degraded_agents()
79 .into_iter()
80 .map(|(agent, _reason)| agent)
81 .collect(),
82 }
83 }
84
85 pub fn scope(&self) -> &str {
89 match self {
90 Self::AllCooled { scope, .. } => scope,
91 }
92 }
93
94 pub fn remaining_secs(&self) -> Option<u64> {
96 match self {
97 Self::AllCooled { remaining_secs, .. } => *remaining_secs,
98 }
99 }
100
101 pub fn degraded(&self) -> &[String] {
103 match self {
104 Self::AllCooled { degraded, .. } => degraded,
105 }
106 }
107}
108
109#[derive(Debug, thiserror::Error)]
111pub enum RouteResultError {
112 #[error("no agent configured for task {task_id}")]
114 NoAgent { task_id: String },
115 #[error(transparent)]
117 Other(#[from] anyhow::Error),
118}
119
120#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
122pub struct RouteResult {
123 pub agent: String,
125 pub model: Option<String>,
127 pub complexity: String,
129 pub estimate: u8,
131 pub reason: String,
133 pub profile: AgentProfile,
135 pub warning: Option<String>,
137}
138
139#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
141pub struct AgentProfile {
142 pub role: String,
144 pub tools: Vec<String>,
146 pub constraints: Vec<String>,
148 #[serde(default, skip_serializing_if = "Option::is_none")]
150 pub execution: Option<config::NamedProfile>,
151}
152
153impl AgentProfile {
154 pub fn default_from_config(config: &RouterConfig) -> Self {
156 Self {
157 role: "general".to_string(),
158 tools: config.allowed_tools.clone(),
159 constraints: vec![],
160 execution: None,
161 }
162 }
163}
164
165impl RouteResult {
166 pub(crate) fn resolve_model(
169 config: &RouterConfig,
170 agent: &str,
171 complexity: &str,
172 task_id: &str,
173 ) -> (Option<String>, Option<String>) {
174 match config.model_for_complexity_or_adjacent(agent, complexity, task_id) {
175 Some((model, tier)) if tier != complexity => {
176 let warning =
177 format!("no available {complexity} model for {agent}; using {tier} tier");
178 (Some(model), Some(warning))
179 }
180 Some((model, _)) => (Some(model), None),
181 None => (None, None),
182 }
183 }
184
185 pub fn from_config(
190 agent: String,
191 complexity: String,
192 reason: String,
193 config: &RouterConfig,
194 task_id: &str,
195 ) -> Self {
196 let (model, warning) = Self::resolve_model(config, &agent, &complexity, task_id);
197 Self {
198 agent,
199 model,
200 complexity,
201 estimate: 0,
202 reason,
203 profile: AgentProfile::default_from_config(config),
204 warning,
205 }
206 }
207}
208
209#[expect(
211 clippy::struct_field_names,
212 reason = "the router holds sub-routers whose names say which backend they use"
213)]
214pub struct Router {
215 pub config: RouterConfig,
217 pub available_agents: Vec<String>,
219 pub weights: AgentWeights,
221 llm_router: Arc<LlmRouter>,
224 ollama_router: Option<ollama::OllamaRouter>,
226 pub(crate) rr_index: usize,
228 pub(crate) last_agent: Option<String>,
230 pub(crate) review_rr_index: usize,
232 pub(crate) router_pool: Vec<(String, String)>,
235 pub(crate) pool_index: usize,
237 pub(crate) host_agents: Option<HashSet<String>>,
240}
241
242impl Debug for Router {
243 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
244 f.debug_struct("Router")
245 .field("config", &self.config)
246 .field("available_agents", &self.available_agents)
247 .field("weights", &self.weights)
248 .field("ollama_router", &self.ollama_router)
249 .field("rr_index", &self.rr_index)
250 .field("last_agent", &self.last_agent)
251 .field("review_rr_index", &self.review_rr_index)
252 .field("router_pool", &self.router_pool)
253 .field("pool_index", &self.pool_index)
254 .field("host_agents", &self.host_agents)
255 .finish_non_exhaustive()
256 }
257}
258
259impl Router {
260 pub fn available_agent_count(&self) -> usize {
261 self.available_agents.len()
262 }
263
264 pub fn review_agents_all_cooled(&self) -> bool {
266 !self.available_agents.is_empty() && self.healthy_agent_count("review") == 0
267 }
268
269 pub fn has_routable_review_agent(&self) -> bool {
270 !self.available_agents.is_empty() && self.healthy_agent_count("review") > 0
271 }
272
273 pub fn model_for_complexity(
274 &self,
275 agent: &str,
276 complexity: &str,
277 task_id: &str,
278 ) -> Option<String> {
279 self.config.model_for_complexity(agent, complexity, task_id)
280 }
281
282 pub fn new(config: RouterConfig) -> Self {
284 let available_agents = Self::discover_agents(&config.agents);
285 let weights = config.agent_weights(&available_agents);
286 let router_pool = Self::expand_pool(&config);
287 tracing::info!(
288 pool = ?router_pool,
289 fallback = %config.effective_fallback(),
290 "router LLM pool initialized"
291 );
292 if config.uses_opencode() {
295 opencode::prime_free_model_cache();
296 }
297 let ollama_router = if config.mode == "local" {
298 Some(ollama::OllamaRouter::new(&config))
299 } else {
300 None
301 };
302 Self {
303 config,
304 available_agents,
305 weights,
306 llm_router: Arc::new(LlmRouter::new()),
307 ollama_router,
308 rr_index: 0,
309 last_agent: None,
310 review_rr_index: 0,
311 router_pool,
312 pool_index: 0,
313 host_agents: None,
314 }
315 }
316
317 pub fn from_config() -> Self {
319 Self::new(RouterConfig::from_config())
320 }
321
322 #[cfg(test)]
325 pub(crate) fn new_for_test(config: RouterConfig, available_agents: Vec<String>) -> Self {
326 let mut weights = AgentWeights {
327 base_weights: config.weights.clone(),
328 ..Default::default()
329 };
330 weights.ensure_agents(&available_agents);
331 let router_pool = Self::expand_pool(&config);
332 Self {
333 config,
334 available_agents,
335 weights,
336 llm_router: Arc::new(LlmRouter::new()),
337 ollama_router: None,
338 rr_index: 0,
339 last_agent: None,
340 review_rr_index: 0,
341 router_pool,
342 pool_index: 0,
343 host_agents: None,
344 }
345 }
346
347 fn advance_pool_index_after_attempt(&mut self, idx: usize, pool_len: usize) {
348 debug_assert!(pool_len > 0, "router pool must not be empty");
349 self.pool_index = (idx + 1) % pool_len;
350 }
351
352 fn discover_agents(configured_agents: &[String]) -> Vec<String> {
355 let mut agents = Vec::new();
356 for agent in configured_agents {
357 if cmd_cache::command_exists(agent) {
358 agents.push(agent.clone());
359 }
360 }
361 agents
362 }
363
364 fn expand_pool(config: &RouterConfig) -> Vec<(String, String)> {
371 let raw_pool = config.effective_pool();
372 let mut expanded: Vec<(String, String)> = Vec::new();
373
374 for entry in &raw_pool {
375 if entry == "opencode:free" {
376 let free_models = Self::discover_free_opencode_models();
377 if free_models.is_empty() {
378 tracing::debug!("opencode:free expanded to nothing — skipping");
379 } else {
380 tracing::debug!(models = ?free_models, "opencode:free expanded");
381 for model in free_models {
382 expanded.push(("opencode".to_string(), model));
383 }
384 }
385 } else {
386 let (agent, model) = parse_pool_entry(entry);
387 expanded.push((agent, model));
388 }
389 }
390
391 if expanded.is_empty() {
392 let (agent, model) = parse_pool_entry(&config.effective_fallback());
394 tracing::debug!(
395 agent = %agent, model = %model,
396 "pool empty after expansion, using fallback as sole pool entry"
397 );
398 expanded.push((agent, model));
399 }
400
401 expanded
402 }
403
404 async fn expand_pool_async(config: &RouterConfig) -> Vec<(String, String)> {
407 let raw_pool = config.effective_pool();
408 let mut expanded: Vec<(String, String)> = Vec::new();
409
410 for entry in &raw_pool {
411 if entry == "opencode:free" {
412 let free_models = Self::discover_free_opencode_models_async().await;
413 if free_models.is_empty() {
414 tracing::debug!("opencode:free expanded to nothing — skipping (async)");
415 } else {
416 tracing::debug!(models = ?free_models, "opencode:free expanded (async)");
417 for model in free_models {
418 expanded.push(("opencode".to_string(), model));
419 }
420 }
421 } else {
422 let (agent, model) = parse_pool_entry(entry);
423 expanded.push((agent, model));
424 }
425 }
426
427 if expanded.is_empty() {
428 let (agent, model) = parse_pool_entry(&config.effective_fallback());
430 tracing::debug!(
431 agent = %agent, model = %model,
432 "pool empty after async expansion, using fallback as sole pool entry"
433 );
434 expanded.push((agent, model));
435 }
436
437 expanded
438 }
439
440 pub async fn reload_async(&mut self) {
443 let new_config = RouterConfig::from_config();
444 let new_agents = Self::discover_agents(&new_config.agents);
445 let new_pool = Self::expand_pool_async(&new_config).await;
446 tracing::info!(
447 mode = %new_config.mode,
448 agents = ?new_agents,
449 fallback = %new_config.fallback_executor,
450 weighted_rr = new_config.weighted_round_robin,
451 pool = ?new_pool,
452 "router reloaded (async)"
453 );
454 self.config = new_config;
455 self.available_agents.clone_from(&new_agents);
456 self.weights.ensure_agents(&new_agents);
458 self.router_pool = new_pool;
459 self.pool_index = 0;
460 self.ollama_router = if self.config.mode == "local" {
462 Some(ollama::OllamaRouter::new(&self.config))
463 } else {
464 None
465 };
466 }
467
468 fn discover_free_opencode_models() -> Vec<String> {
469 opencode::discover_free_opencode_models()
470 }
471
472 async fn discover_free_opencode_models_async() -> Vec<String> {
473 task::spawn_blocking(Self::discover_free_opencode_models)
474 .await
475 .unwrap_or_default()
476 }
477
478 pub async fn refresh_health(&self, store: &Arc<TaskStore>) {
483 sync_from_kv(store).await;
490
491 let agents = self.available_agents.clone();
492 let model_checker = |agent: &str| -> bool { self.agent_has_any_available_model(agent) };
493 refresh_degraded_agents(
494 store,
495 &agents,
496 &model_checker,
497 config::health_check_window_hours(),
498 config::degraded_rate_limit_threshold(),
499 )
500 .await;
501 }
502
503 pub fn is_agent_available(&self, agent: &str) -> bool {
505 self.available_agents.contains(&agent.to_string())
506 }
507
508 fn agent_has_any_available_model(&self, agent: &str) -> bool {
512 ["simple", "medium", "complex", "review"]
513 .iter()
514 .any(|comp| self.config.has_available_model_for_complexity(agent, comp))
515 }
516
517 fn agent_has_available_model_for_coding_tiers(&self, agent: &str) -> bool {
526 ["medium", "complex"]
527 .iter()
528 .all(|comp| self.config.has_available_model_for_complexity(agent, comp))
529 }
530
531 pub fn set_host_agents(&mut self, agents: Option<HashSet<String>>) {
533 self.host_agents = agents;
534 }
535
536 fn agent_is_routable(&self, agent: &str, complexity: &str) -> bool {
537 if !self.is_agent_available(agent) {
538 return false;
539 }
540
541 if self
542 .host_agents
543 .as_ref()
544 .is_some_and(|a| !a.contains(agent))
545 {
546 tracing::debug!(agent, "agent skipped: no online host of the repo has it");
547 return false;
548 }
549 if is_agent_in_cooldown(agent) {
550 tracing::debug!(agent, "agent skipped: in cooldown");
551 return false;
552 }
553 if is_agent_degraded(agent) {
554 tracing::debug!(agent, "agent skipped: degraded (pre-emptive health check)");
555 return false;
556 }
557 if self.config.weighted_round_robin {
561 let weight = self.weights.get_weight(agent);
562 if weight < config::SKIP_LIMITED_THRESHOLD {
563 tracing::debug!(
564 agent,
565 weight,
566 "agent considered degraded by weight threshold, skipping"
567 );
568 return false;
569 }
570 }
571 if !self
572 .config
573 .has_available_model_in_any_tier(agent, complexity)
574 {
575 tracing::debug!(agent, complexity, "agent skipped: no available model");
576 return false;
577 }
578 true
579 }
580
581 fn available_agents_for_complexity(&self, complexity: &str) -> Vec<String> {
582 self.available_agents
583 .iter()
584 .filter(|agent| self.agent_is_routable(agent, complexity))
585 .cloned()
586 .collect()
587 }
588
589 pub fn healthy_agent_count(&self, complexity: &str) -> usize {
592 self.available_agents_for_complexity(complexity).len()
593 }
594
595 pub fn is_degraded(&self, threshold: usize) -> bool {
598 self.healthy_agent_count("simple") < threshold
599 }
600
601 pub fn earliest_cooldown_until(&self, complexity: Option<&str>) -> Option<i64> {
602 let mut earliest: Option<i64> = None;
603
604 for agent in &self.available_agents {
605 if let Some(until) = cooldown_until(agent) {
606 earliest = Some(earliest.map_or(until, |current| current.min(until)));
607 }
608
609 if let Some(comp) = complexity
610 && let Some(pool) = self.config.model_pool_for_complexity(agent, comp)
611 {
612 for model in pool {
613 let key = format!("{agent}:{model}");
614 if let Some(until) = cooldown_until(&key) {
615 earliest = Some(earliest.map_or(until, |current| current.min(until)));
616 }
617 }
618 }
619 }
620
621 earliest
622 }
623
624 fn earliest_pool_cooldown(&self) -> Option<i64> {
629 let mut earliest: Option<i64> = None;
630 for (agent, model) in &self.router_pool {
631 let key = format!("{agent}:{model}");
632 if let Some(until) = cooldown_until(&key) {
633 earliest = Some(earliest.map_or(until, |current| current.min(until)));
634 }
635 }
636 earliest
637 }
638
639 fn wait_for_cooldown(&self, complexity: Option<&str>) -> anyhow::Result<()> {
640 let now = chrono::Utc::now().timestamp();
647 let Some(earliest) = self.earliest_cooldown_until(complexity) else {
648 tracing::warn!(
652 scope = complexity.unwrap_or("all agents"),
653 "all agents degraded (no cooldown timestamp available) — skipping task, will retry after backoff"
654 );
655 return Err(AllAgentsCooledError::new(
657 complexity.unwrap_or("all agents").to_string(),
658 None,
659 )
660 .into());
661 };
662
663 let remaining = earliest.saturating_sub(now);
664 if remaining > 0 {
665 let scope_str = complexity.unwrap_or("all agents").to_string();
666 tracing::warn!(
667 remaining_secs = remaining,
668 scope = %scope_str,
669 "all agents/models cooled — routing is unavailable until cooldown expires; failing fast to let tick retry"
670 );
671 return Err(AllAgentsCooledError::new(scope_str, u64::try_from(remaining).ok()).into());
674 }
675
676 Ok(())
677 }
678
679 pub fn next_round_robin_agent(&mut self, exclude: &[&str], complexity: &str) -> Option<String> {
684 let candidates = self.available_agents_for_complexity(complexity);
687 if candidates.is_empty() {
688 return None;
689 }
690 let idx = self.review_rr_index;
691 let n = candidates.len();
692
693 let agent = (0..n)
695 .map(|offset| &candidates[(idx + offset) % n])
696 .find(|a| !exclude.contains(&a.as_str()))
697 .cloned()
698 .or_else(|| candidates.first().cloned())?;
700
701 self.review_rr_index = (idx + 1) % candidates.len().max(1);
702 Some(agent)
703 }
704
705 async fn skip_no_code_agent(
709 &self,
710 store: &Arc<TaskStore>,
711 repo: &str,
712 task_id: &str,
713 candidates: &[String],
714 ) -> Option<Vec<String>> {
715 let no_code_agent = get_task_field_direct(store, repo, task_id, "no_code_last_agent")
716 .await
717 .unwrap_or_else(|| {
718 tracing::warn!(
719 task_id,
720 "no_code_last_agent DB read returned None — loop detection may be impaired"
721 );
722 String::new()
723 });
724 if no_code_agent.is_empty() || !candidates.iter().any(|a| a == &no_code_agent) {
725 return None;
726 }
727 let filtered: Vec<String> = candidates
728 .iter()
729 .filter(|a| a.as_str() != no_code_agent)
730 .cloned()
731 .collect();
732 if filtered.is_empty() {
733 tracing::warn!(
734 task_id,
735 no_code_agent = %no_code_agent,
736 "all available agents are the no-code agent — cannot skip"
737 );
738 return None;
739 }
740 tracing::info!(
741 task_id,
742 skipped = %no_code_agent,
743 remaining = ?filtered,
744 "skipping no-code agent, routing to alternative"
745 );
746 Some(filtered)
747 }
748
749 pub async fn route(
758 &mut self,
759 task: &ExternalTask,
760 store: &Arc<TaskStore>,
761 repo: &str,
762 ) -> anyhow::Result<RouteResult> {
763 match store.resolve_id_by_external(repo, &task.id.0).await {
769 Ok(Some(id)) => match store.block_claim_if_waiting(id).await {
770 Ok(Some(blockers)) => {
771 return Err(WaitingOnDependency { blockers }.into());
772 }
773 Ok(None) => {}
774 Err(err) => return Err(err),
775 },
776 Ok(None) => {}
777 Err(err) => return Err(err),
778 }
779
780 loop {
781 let store_agent = match store.get_agent_by_external_id(repo, &task.id.0).await {
787 Ok(Some(agent)) => {
788 if !agent.is_empty() && self.config.has_agent(&agent) {
790 Some(agent)
791 } else {
792 None
793 }
794 }
795 Ok(None) => None,
796 Err(e) => {
797 tracing::warn!(
798 repo,
799 task_id = %task.id.0,
800 err = %e,
801 "failed to fetch stored agent, falling back to label/LLM routing"
802 );
803 None
804 }
805 };
806
807 if store_agent.is_none()
809 && let Some(result) = self.route_profile(task)?
810 {
811 self.log_route_activity(store, repo, &task.id.0, &result, None)
812 .await;
813 return Ok(result);
814 }
815
816 let resolved_agent = store_agent.or_else(|| {
818 strategies::extract_agent_from_labels(&self.config.agents, &task.labels)
819 });
820
821 if let Some(agent) = resolved_agent {
822 let complexity = strategies::extract_complexity_from_labels(&task.labels);
823 if self.agent_is_routable(&agent, &complexity) {
832 let (model, tier_warning) =
833 RouteResult::resolve_model(&self.config, &agent, &complexity, &task.id.0);
834
835 if model.is_some() {
843 tracing::debug!(
844 task_id = %task.id.0,
845 agent = %agent,
846 complexity = %complexity,
847 "routed via label"
848 );
849 let mut result = RouteResult::from_config(
850 agent.clone(),
851 complexity.clone(),
852 format!("label agent:{agent}"),
853 &self.config,
854 &task.id.0,
855 );
856 result.profile.role = format!("{agent} specialist");
859 result.model = model.clone();
860 result.warning = tier_warning;
861 self.log_route_activity(store, repo, &task.id.0, &result, None)
862 .await;
863 return Ok(result);
864 }
865 tracing::warn!(task_id = %task.id.0, agent = %agent, "label agent has no available model — falling through to LLM routing");
870 }
871
872 let candidates = self.available_agents_for_complexity(&complexity);
873 if candidates.is_empty() {
874 self.wait_for_cooldown(Some(&complexity))?;
875 continue;
876 }
877 }
879
880 let complexity = strategies::extract_complexity_from_labels(&task.labels);
881
882 let mut candidates = self.available_agents_for_complexity(&complexity);
884 if candidates.is_empty() {
885 self.wait_for_cooldown(Some(&complexity))?;
886 continue;
887 }
888
889 if let Some(filtered) = self
894 .skip_no_code_agent(store, repo, &task.id.0, &candidates)
895 .await
896 {
897 candidates = filtered;
898 }
899
900 if self.config.weighted_round_robin {
902 let result = strategies::route_via_weighted_round_robin(
903 &candidates,
904 &self.weights,
905 &self.config,
906 task,
907 &mut self.last_agent,
908 )?;
909 self.log_route_activity(store, repo, &task.id.0, &result, None)
910 .await;
911 return Ok(result);
912 }
913
914 if self.config.mode == "round_robin" || self.config.mode == "profile" {
916 tracing::debug!(task_id = %task.id.0, "routing via round-robin mode");
917 let result = strategies::route_via_round_robin_stateful(
918 &candidates,
919 &self.config,
920 task,
921 &mut self.rr_index,
922 &mut self.last_agent,
923 )?;
924 self.log_route_activity(store, repo, &task.id.0, &result, None)
925 .await;
926 return Ok(result);
927 }
928
929 if self.config.mode == "local" {
931 tracing::debug!(task_id = %task.id.0, ollama_url = %self.config.ollama_url, "routing via local Ollama");
932 let ollama_router = self
933 .ollama_router
934 .as_ref()
935 .expect("ollama_router must be initialized in Router::new when mode=local");
936 match ollama_router.route(task, &self.config).await {
937 Ok(result) => {
938 self.log_route_activity(store, repo, &task.id.0, &result, None)
939 .await;
940 return Ok(result);
941 }
942 Err(e) => {
943 tracing::warn!(
944 task_id = %task.id.0,
945 error = %e,
946 "Ollama routing failed, falling back to round-robin"
947 );
948 let result = strategies::route_via_round_robin_stateful(
949 &candidates,
950 &self.config,
951 task,
952 &mut self.rr_index,
953 &mut self.last_agent,
954 )?;
955 self.log_route_activity(store, repo, &task.id.0, &result, None)
956 .await;
957 return Ok(result);
958 }
959 }
960 }
961
962 let route_attempts = self.get_route_attempts(&task.id.0, store, repo).await;
964
965 if route_attempts >= self.config.max_route_attempts {
966 tracing::warn!(
967 task_id = %task.id.0,
968 attempts = route_attempts,
969 max = self.config.max_route_attempts,
970 "max LLM route attempts reached, falling back to round-robin"
971 );
972 let candidates = self.available_agents_for_complexity(&complexity);
973 if candidates.is_empty() {
974 self.wait_for_cooldown(Some(&complexity))?;
975 continue;
976 }
977 let result = strategies::route_via_round_robin_stateful(
978 &candidates,
979 &self.config,
980 task,
981 &mut self.rr_index,
982 &mut self.last_agent,
983 )?;
984 self.log_route_activity(store, repo, &task.id.0, &result, None)
985 .await;
986 return Ok(result);
987 }
988
989 tracing::debug!(task_id = %task.id.0, "starting LLM routing");
991
992 match self.route_with_llm(task, repo).await {
993 Ok(result) => {
994 let candidates = self.available_agents_for_complexity(&result.complexity);
995 if candidates.is_empty() {
996 self.wait_for_cooldown(Some(&result.complexity))?;
997 continue;
998 }
999
1000 let no_code_agent =
1003 get_task_field_direct(store, repo, &task.id.0, "no_code_last_agent")
1004 .await
1005 .unwrap_or_else(|| {
1006 tracing::warn!(task_id = %task.id.0, "no_code_last_agent DB read returned None — loop detection may be impaired");
1007 String::new()
1008 });
1009 if result.agent == no_code_agent {
1010 let fallback_agent = candidates
1012 .iter()
1013 .find(|a| a.as_str() != no_code_agent)
1014 .cloned()
1015 .unwrap_or_else(|| candidates[0].clone());
1016 if fallback_agent.as_str() == no_code_agent {
1017 tracing::warn!(
1018 task_id = %task.id.0,
1019 no_code_agent = %no_code_agent,
1020 complexity = %result.complexity,
1021 "all available agents are the no-code agent — waiting for another agent"
1022 );
1023 self.wait_for_cooldown(Some(&result.complexity))?;
1024 continue;
1025 }
1026 tracing::info!(
1027 task_id = %task.id.0,
1028 llm_selected = %result.agent,
1029 skipped = %no_code_agent,
1030 fallback = %fallback_agent,
1031 "LLM selected the no-code agent — routing to alternative"
1032 );
1033 let (fallback_model, _) = RouteResult::resolve_model(
1034 &self.config,
1035 &fallback_agent,
1036 &result.complexity,
1037 &task.id.0,
1038 );
1039
1040 self.set_route_attempts(&task.id.0, 0, store, repo).await;
1041 let result = RouteResult {
1042 agent: fallback_agent.clone(),
1043 model: fallback_model,
1044 complexity: result.complexity.clone(),
1045 estimate: result.estimate,
1046 reason: format!(
1047 "LLM selected no-code agent {}; routed to {}",
1048 result.agent, fallback_agent
1049 ),
1050 profile: result.profile.clone(),
1051 warning: Some(format!(
1052 "LLM selected no-code agent {}; used fallback {}",
1053 result.agent, fallback_agent
1054 )),
1055 };
1056 self.log_route_activity(store, repo, &task.id.0, &result, None)
1057 .await;
1058 return Ok(result);
1059 }
1060
1061 let model_cooled = result
1062 .model
1063 .as_deref()
1064 .is_some_and(|model| is_model_in_cooldown(&result.agent, model));
1065 if !candidates.contains(&result.agent) || model_cooled {
1066 let fallback_agent = candidates
1067 .iter()
1068 .find(|agent| *agent != &result.agent)
1069 .cloned()
1070 .unwrap_or_else(|| candidates[0].clone());
1071 let (fallback_model, _) = RouteResult::resolve_model(
1072 &self.config,
1073 &fallback_agent,
1074 &result.complexity,
1075 &task.id.0,
1076 );
1077
1078 if fallback_model.is_none() && fallback_agent == result.agent {
1084 tracing::warn!(
1085 task_id = %task.id.0,
1086 agent = %result.agent,
1087 complexity = %result.complexity,
1088 "LLM-selected model(s) are cooled for the only available agent; waiting for cooldown"
1089 );
1090 self.wait_for_cooldown(Some(&result.complexity))?;
1091 continue;
1092 }
1093
1094 if fallback_agent == result.agent {
1098 tracing::warn!(
1099 task_id = %task.id.0,
1100 agent = %result.agent,
1101 complexity = %result.complexity,
1102 "LLM-selected model was cooled; selecting an alternative model for the same agent"
1103 );
1104 } else {
1105 tracing::warn!(
1106 task_id = %task.id.0,
1107 agent = %result.agent,
1108 fallback = %fallback_agent,
1109 complexity = %result.complexity,
1110 "LLM selected cooled agent/model; rerouting to available agent"
1111 );
1112 }
1113
1114 self.set_route_attempts(&task.id.0, 0, store, repo).await;
1116
1117 let reason = if fallback_agent == result.agent {
1118 format!(
1119 "LLM selected cooled model; using same agent {fallback_agent} with different model"
1120 )
1121 } else {
1122 format!("LLM selected cooled agent/model; rerouted to {fallback_agent}")
1123 };
1124
1125 let result = RouteResult {
1126 agent: fallback_agent.clone(),
1127 model: fallback_model,
1128 complexity: result.complexity.clone(),
1129 estimate: result.estimate,
1130 reason: reason.clone(),
1131 profile: result.profile.clone(),
1132 warning: Some(if fallback_agent == result.agent {
1133 "LLM-selected model was cooled; selected alternative model for same agent"
1134 .to_string()
1135 } else {
1136 "LLM-selected agent/model was cooled; rerouted to available agent"
1137 .to_string()
1138 }),
1139 };
1140 self.log_route_activity(store, repo, &task.id.0, &result, None)
1141 .await;
1142 return Ok(result);
1143 }
1144
1145 self.set_route_attempts(&task.id.0, 0, store, repo).await;
1147 tracing::info!(
1148 task_id = %task.id.0,
1149 agent = %result.agent,
1150 complexity = %result.complexity,
1151 "routed via LLM"
1152 );
1153 self.log_route_activity(store, repo, &task.id.0, &result, None)
1154 .await;
1155 return Ok(result);
1156 }
1157 Err(e) => {
1158 if let Some(err) = e.downcast_ref::<AllAgentsCooledError>() {
1159 let scope = err.scope();
1160 tracing::warn!(scope = %scope, "router cooldown gate tripped");
1161 let scope_opt = match scope {
1165 "all agents" | "router pool" => None,
1166 _ => Some(scope),
1167 };
1168 self.wait_for_cooldown(scope_opt)?;
1169 continue;
1170 }
1171
1172 let new_attempts = route_attempts + 1;
1173 self.set_route_attempts(&task.id.0, new_attempts, store, repo)
1174 .await;
1175 tracing::warn!(
1176 task_id = %task.id.0,
1177 error = %e,
1178 error_chain = ?e,
1179 attempt = new_attempts,
1180 max = self.config.max_route_attempts,
1181 "LLM routing failed"
1182 );
1183
1184 if new_attempts >= self.config.max_route_attempts {
1185 tracing::info!(
1186 task_id = %task.id.0,
1187 "falling back to round-robin after {} failed attempts",
1188 new_attempts
1189 );
1190 let candidates = self.available_agents_for_complexity(&complexity);
1191 if candidates.is_empty() {
1192 self.wait_for_cooldown(Some(&complexity))?;
1193 continue;
1194 }
1195 let result = strategies::route_via_round_robin_stateful(
1196 &candidates,
1197 &self.config,
1198 task,
1199 &mut self.rr_index,
1200 &mut self.last_agent,
1201 )?;
1202 self.log_route_activity(store, repo, &task.id.0, &result, None)
1203 .await;
1204 return Ok(result);
1205 }
1206
1207 let candidates = self.available_agents_for_complexity(&complexity);
1208 if candidates.is_empty() {
1209 self.wait_for_cooldown(Some(&complexity))?;
1210 continue;
1211 }
1212 let result = strategies::route_via_fallback(
1213 &candidates,
1214 &self.config,
1215 task,
1216 Some(&self.weights),
1217 )?;
1218 self.log_route_activity(store, repo, &task.id.0, &result, None)
1219 .await;
1220 return Ok(result);
1221 }
1222 }
1223 }
1224 }
1225
1226 async fn get_route_attempts(&self, task_id: &str, store: &Arc<TaskStore>, repo: &str) -> u32 {
1228 match store.resolve_task_id(repo, task_id).await {
1229 Ok(Some(store_id)) => store
1230 .get(store_id)
1231 .await
1232 .map_or(0, |t| u32::try_from(t.route_attempts).unwrap_or(0)),
1233 _ => 0,
1234 }
1235 }
1236
1237 async fn set_route_attempts(
1239 &self,
1240 task_id: &str,
1241 attempts: u32,
1242 store: &Arc<TaskStore>,
1243 repo: &str,
1244 ) {
1245 if let Ok(Some(store_id)) = store.resolve_task_id(repo, task_id).await
1246 && let Err(e) = store
1247 .set_fields(store_id, &[("route_attempts", serde_json::json!(attempts))])
1248 .await
1249 {
1250 tracing::warn!(task_id, error = %e, "failed to store route_attempts");
1251 }
1252 }
1253
1254 async fn log_route_activity(
1256 &self,
1257 store: &Arc<TaskStore>,
1258 repo: &str,
1259 task_id: &str,
1260 result: &RouteResult,
1261 from_agent: Option<&str>,
1262 ) {
1263 let details = serde_json::json!({
1264 "reason": result.reason,
1265 "complexity": result.complexity,
1266 "role": result.profile.role,
1267 "warning": result.warning,
1268 });
1269 let event_type = if from_agent.is_some() {
1270 "rerouted"
1271 } else {
1272 "routed"
1273 };
1274 store_log_activity(
1275 &Some(Arc::clone(store)),
1276 repo,
1277 task_id,
1278 event_type,
1279 None,
1280 Some("routed"),
1281 Some(&result.agent),
1282 result.model.as_deref(),
1283 Some(&details),
1284 )
1285 .await;
1286 }
1287
1288 async fn route_with_llm(
1294 &mut self,
1295 task: &ExternalTask,
1296 repo: &str,
1297 ) -> anyhow::Result<RouteResult> {
1298 let uncooled_agents: Vec<String> = self
1308 .available_agents
1309 .iter()
1310 .filter(|a| {
1311 !is_agent_in_cooldown(a)
1312 && !is_agent_degraded(a)
1313 && self.agent_has_available_model_for_coding_tiers(a)
1314 })
1315 .cloned()
1316 .collect();
1317 if uncooled_agents.is_empty() {
1318 return Err(AllAgentsCooledError::new("all agents".to_string(), None).into());
1319 }
1320 let llm_agents = uncooled_agents;
1321
1322 let pool = self.router_pool.clone();
1323 let n = pool.len();
1324 let start = self.pool_index;
1325 let mut last_err: Option<anyhow::Error> = None;
1326 let mut attempted_any = false;
1327
1328 for i in 0..n {
1330 let idx = (start + i) % n;
1331 let (agent, model) = &pool[idx];
1332 let model_str = model.as_str();
1333
1334 if cooldown::is_model_in_cooldown(agent, model_str) {
1335 tracing::debug!(agent, model = model_str, "pool entry on cooldown, skipping");
1336 continue;
1337 }
1338
1339 attempted_any = true;
1341
1342 let model_opt = if model_str.is_empty() {
1343 None
1344 } else {
1345 Some(model_str)
1346 };
1347
1348 match self
1349 .llm_router
1350 .route_with_llm_using(
1351 task,
1352 &llm_agents,
1353 &self.config,
1354 &mut self.last_agent,
1355 repo,
1356 agent,
1357 model_opt,
1358 )
1359 .await
1360 {
1361 Ok(result) => {
1362 self.advance_pool_index_after_attempt(idx, n);
1364 tracing::debug!(
1365 agent,
1366 model = model_str,
1367 pool_idx = idx,
1368 "router LLM pool entry succeeded"
1369 );
1370 record_agent_success(agent, model_str).await;
1371 return Ok(result);
1372 }
1373 Err(e) => {
1374 let err_msg = e.to_string();
1375 let is_timeout = err_msg.contains(TIMEOUT_PREFIX);
1376 if is_timeout {
1377 self.advance_pool_index_after_attempt(idx, n);
1387 tracing::warn!(
1388 agent,
1389 model = model_str,
1390 next_pool_idx = self.pool_index,
1391 "router LLM pool entry timed out — recording cooldown, will retry next tick"
1392 );
1393 cooldown::record_model_failure(agent, model_str).await;
1394 return Err(e);
1395 }
1396 if is_max_turns_error(&err_msg) {
1397 tracing::warn!(
1398 agent,
1399 model = model_str,
1400 error = %e,
1401 "pool entry hit max turns — trying next without cooldown"
1402 );
1403 } else {
1404 tracing::warn!(
1405 agent,
1406 model = model_str,
1407 error = %e,
1408 "pool entry failed, recording cooldown and trying next"
1409 );
1410 if !cooldown::record_credit_exhaustion_from_message(
1411 agent,
1412 Some(model_str),
1413 &err_msg,
1414 )
1415 .await
1416 {
1417 cooldown::record_model_failure(agent, model_str).await;
1418 }
1419 }
1420 last_err = Some(e);
1421 self.advance_pool_index_after_attempt(idx, n);
1422 }
1423 }
1424 }
1425
1426 if !attempted_any {
1431 let now = chrono::Utc::now().timestamp();
1432 let earliest = self.earliest_pool_cooldown();
1433 if let Some(until) = earliest {
1434 let remaining = until.saturating_sub(now);
1436 tracing::warn!(
1437 remaining_secs = remaining,
1438 pool = ?pool,
1439 "all router LLM pool entries on cooldown — will try fallback"
1440 );
1441 } else {
1443 return Err(last_err
1446 .unwrap_or_else(|| anyhow::anyhow!("all router LLM pool entries exhausted")));
1447 }
1448 }
1449
1450 let fallback = self.config.effective_fallback();
1452 let (fb_agent, fb_model) = parse_pool_entry(&fallback);
1453 let fb_model_str = fb_model.as_str();
1454
1455 let fallback_already_tried = pool.iter().any(|(a, m)| a == &fb_agent && m == &fb_model);
1457
1458 if !fallback_already_tried && !cooldown::is_model_in_cooldown(&fb_agent, fb_model_str) {
1459 tracing::info!(
1460 agent = %fb_agent,
1461 model = %fb_model_str,
1462 "all pool entries exhausted — trying fallback router LLM"
1463 );
1464 let fb_model_opt = if fb_model_str.is_empty() {
1465 None
1466 } else {
1467 Some(fb_model_str)
1468 };
1469 match self
1470 .llm_router
1471 .route_with_llm_using(
1472 task,
1473 &llm_agents,
1474 &self.config,
1475 &mut self.last_agent,
1476 repo,
1477 &fb_agent,
1478 fb_model_opt,
1479 )
1480 .await
1481 {
1482 Ok(result) => {
1483 record_agent_success(&fb_agent, fb_model_str).await;
1484 return Ok(result);
1485 }
1486 Err(e) => {
1487 let err_msg = e.to_string();
1488 let is_timeout = err_msg.contains(TIMEOUT_PREFIX);
1489 if is_timeout {
1490 cooldown::record_model_failure(&fb_agent, fb_model_str).await;
1493 tracing::warn!(
1494 agent = %fb_agent,
1495 model = %fb_model_str,
1496 "fallback router LLM timed out — returning immediately to unblock tick loop"
1497 );
1498 return Err(e);
1499 }
1500 tracing::warn!(
1501 agent = %fb_agent,
1502 model = %fb_model_str,
1503 error = %e,
1504 "fallback router LLM also failed"
1505 );
1506 if !is_max_turns_error(&err_msg) {
1507 cooldown::record_model_failure(&fb_agent, fb_model_str).await;
1508 }
1509 last_err = Some(e);
1510 }
1511 }
1512 }
1513
1514 Err(last_err.unwrap_or_else(|| anyhow::anyhow!("all router LLM pool entries exhausted")))
1515 }
1516
1517 pub fn record_rate_limit(&mut self, agent: &str) {
1521 self.weights.record_rate_limit(agent);
1522 }
1523
1524 pub fn record_success(&mut self, agent: &str) {
1526 self.weights.record_success(agent);
1527 }
1528
1529 pub fn tick_weight_recovery(&mut self) {
1534 self.weights.tick_recovery();
1535 }
1536
1537 pub async fn store_route_result(
1539 &self,
1540 task_id: &str,
1541 result: &RouteResult,
1542 store: &Arc<TaskStore>,
1543 repo: &str,
1544 ) -> anyhow::Result<()> {
1545 if let Ok(Some(store_id)) = store.resolve_task_id(repo, task_id).await {
1546 store
1547 .set_fields(
1548 store_id,
1549 &[
1550 ("agent", serde_json::json!(result.agent)),
1551 ("complexity", serde_json::json!(result.complexity)),
1552 ("route_reason", serde_json::json!(result.reason)),
1553 (
1554 "agent_profile",
1555 serde_json::json!(serde_json::to_string(&result.profile)?),
1556 ),
1557 (
1558 "model",
1559 serde_json::json!(result.model.as_deref().unwrap_or("")),
1560 ),
1561 ],
1562 )
1563 .await?;
1564 }
1565 Ok(())
1566 }
1567}
1568
1569pub async fn get_route_result(
1571 store: &Arc<TaskStore>,
1572 repo: &str,
1573 task_id: &str,
1574) -> Result<RouteResult, RouteResultError> {
1575 let store_id = store
1576 .resolve_task_id(repo, task_id)
1577 .await
1578 .map_err(RouteResultError::Other)?
1579 .ok_or_else(|| {
1580 RouteResultError::Other(anyhow::anyhow!("task {task_id} not found in store"))
1581 })?;
1582 let task = store.get(store_id).await.map_err(RouteResultError::Other)?;
1583
1584 let agent = task
1585 .agent
1586 .clone()
1587 .filter(|a| !a.is_empty())
1588 .ok_or_else(|| RouteResultError::NoAgent {
1589 task_id: task_id.to_string(),
1590 })?;
1591
1592 let complexity = if task.complexity.is_empty() {
1593 "medium".to_string()
1594 } else {
1595 task.complexity.clone()
1596 };
1597
1598 let reason = task.route_reason.clone();
1599 let model = task.model.clone().filter(|m| !m.is_empty());
1600 let profile = AgentProfile {
1604 execution: serde_json::from_str::<AgentProfile>(&task.agent_profile)
1605 .ok()
1606 .and_then(|stored| stored.execution)
1607 .filter(|p| p.matches_route(&agent, model.as_deref())),
1608 ..AgentProfile::default()
1609 };
1610
1611 let config = RouterConfig::from_config();
1615 let model = model.filter(|m| {
1616 let complexities = ["simple", "medium", "complex", "review"];
1617 let all_pools: Vec<Vec<String>> = complexities
1619 .iter()
1620 .filter_map(|comp| config.model_pool_for_complexity(&agent, comp))
1621 .collect();
1622 if all_pools.is_empty() {
1624 return true;
1625 }
1626 let valid = all_pools.iter().any(|pool| pool.contains(m))
1627 || profile
1628 .execution
1629 .as_ref()
1630 .is_some_and(|p| p.matches_route(&agent, Some(m)));
1631 if !valid {
1632 tracing::warn!(
1633 task_id,
1634 agent,
1635 model = %m,
1636 "discarding stale model: not in agent's model pools"
1637 );
1638 }
1639 valid
1640 });
1641
1642 let original_model = task.model.clone().filter(|m| !m.is_empty());
1645 let mut model = model;
1646 if original_model.is_some() && model.is_none() {
1647 model = config.model_for_complexity(&agent, &complexity, task_id);
1648 let stale_model = original_model.as_deref().unwrap_or("unknown");
1649 let stale_err = format!(
1650 "stale model discarded: {stale_model} not in {agent} model pools, using {}",
1651 model.as_deref().unwrap_or("the agent default")
1652 );
1653 if let Err(e) = store
1654 .set_fields(
1655 store_id,
1656 &[
1657 (
1658 "model",
1659 serde_json::json!(model.clone().unwrap_or_default()),
1660 ),
1661 ("last_error", serde_json::json!(stale_err)),
1662 ],
1663 )
1664 .await
1665 {
1666 tracing::warn!(task_id = %task_id, error = %e, "failed to clear stale model from store — will retry on next dispatch");
1668 }
1669 }
1670
1671 Ok(RouteResult {
1672 agent,
1673 model,
1674 complexity,
1675 estimate: 0,
1676 reason,
1677 profile,
1678 warning: None,
1679 })
1680}
1681
1682#[cfg(test)]
1683#[expect(
1684 clippy::float_cmp,
1685 reason = "the weights are stored constants, so they compare exactly"
1686)]
1687mod tests;