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::fmt;
37use std::fmt::Debug;
38use std::fmt::Formatter;
39use std::sync::Arc;
40use tokio::task;
41pub use weights::AgentWeights;
42
43fn fmt_degraded(degraded: &[String]) -> String {
44 if degraded.is_empty() {
45 String::new()
46 } else {
47 format!(" (degraded: {})", degraded.join(", "))
48 }
49}
50
51fn is_max_turns_error(err_msg: &str) -> bool {
53 let lower = err_msg.to_ascii_lowercase();
54 lower.contains("max turns reached") || lower.contains("reached the maximum number of turns")
55}
56
57#[derive(Debug, thiserror::Error)]
62pub enum AllAgentsCooledError {
63 #[error("all agents/models in cooldown for {scope}{}", fmt_degraded(.degraded))]
64 AllCooled {
65 scope: String,
66 remaining_secs: Option<u64>,
67 degraded: Vec<String>,
68 },
69}
70
71impl AllAgentsCooledError {
72 pub fn new(scope: String, remaining_secs: Option<u64>) -> Self {
74 Self::AllCooled {
75 scope,
76 remaining_secs,
77 degraded: list_degraded_agents()
78 .into_iter()
79 .map(|(agent, _reason)| agent)
80 .collect(),
81 }
82 }
83
84 pub fn scope(&self) -> &str {
88 match self {
89 Self::AllCooled { scope, .. } => scope,
90 }
91 }
92
93 pub fn remaining_secs(&self) -> Option<u64> {
95 match self {
96 Self::AllCooled { remaining_secs, .. } => *remaining_secs,
97 }
98 }
99
100 pub fn degraded(&self) -> &[String] {
102 match self {
103 Self::AllCooled { degraded, .. } => degraded,
104 }
105 }
106}
107
108#[derive(Debug, thiserror::Error)]
110pub enum RouteResultError {
111 #[error("no agent configured for task {task_id}")]
113 NoAgent { task_id: String },
114 #[error(transparent)]
116 Other(#[from] anyhow::Error),
117}
118
119#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
121pub struct RouteResult {
122 pub agent: String,
124 pub model: Option<String>,
126 pub complexity: String,
128 pub estimate: u8,
130 pub reason: String,
132 pub profile: AgentProfile,
134 pub warning: Option<String>,
136}
137
138#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
140pub struct AgentProfile {
141 pub role: String,
143 pub tools: Vec<String>,
145 pub constraints: Vec<String>,
147 #[serde(default, skip_serializing_if = "Option::is_none")]
149 pub execution: Option<config::NamedProfile>,
150}
151
152impl AgentProfile {
153 pub fn default_from_config(config: &RouterConfig) -> Self {
155 Self {
156 role: "general".to_string(),
157 tools: config.allowed_tools.clone(),
158 constraints: vec![],
159 execution: None,
160 }
161 }
162}
163
164impl RouteResult {
165 pub(crate) fn resolve_model(
168 config: &RouterConfig,
169 agent: &str,
170 complexity: &str,
171 task_id: &str,
172 ) -> (Option<String>, Option<String>) {
173 match config.model_for_complexity_or_adjacent(agent, complexity, task_id) {
174 Some((model, tier)) if tier != complexity => {
175 let warning =
176 format!("no available {complexity} model for {agent}; using {tier} tier");
177 (Some(model), Some(warning))
178 }
179 Some((model, _)) => (Some(model), None),
180 None => (None, None),
181 }
182 }
183
184 pub fn from_config(
189 agent: String,
190 complexity: String,
191 reason: String,
192 config: &RouterConfig,
193 task_id: &str,
194 ) -> Self {
195 let (model, warning) = Self::resolve_model(config, &agent, &complexity, task_id);
196 Self {
197 agent,
198 model,
199 complexity,
200 estimate: 0,
201 reason,
202 profile: AgentProfile::default_from_config(config),
203 warning,
204 }
205 }
206}
207
208#[expect(
210 clippy::struct_field_names,
211 reason = "the router holds sub-routers whose names say which backend they use"
212)]
213pub struct Router {
214 pub config: RouterConfig,
216 pub available_agents: Vec<String>,
218 pub weights: AgentWeights,
220 llm_router: Arc<LlmRouter>,
223 ollama_router: Option<ollama::OllamaRouter>,
225 pub(crate) rr_index: usize,
227 pub(crate) last_agent: Option<String>,
229 pub(crate) review_rr_index: usize,
231 pub(crate) router_pool: Vec<(String, String)>,
234 pub(crate) pool_index: usize,
236}
237
238impl Debug for Router {
239 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
240 f.debug_struct("Router")
241 .field("config", &self.config)
242 .field("available_agents", &self.available_agents)
243 .field("weights", &self.weights)
244 .field("ollama_router", &self.ollama_router)
245 .field("rr_index", &self.rr_index)
246 .field("last_agent", &self.last_agent)
247 .field("review_rr_index", &self.review_rr_index)
248 .field("router_pool", &self.router_pool)
249 .field("pool_index", &self.pool_index)
250 .finish_non_exhaustive()
251 }
252}
253
254impl Router {
255 pub fn available_agent_count(&self) -> usize {
256 self.available_agents.len()
257 }
258
259 pub fn review_agents_all_cooled(&self) -> bool {
261 !self.available_agents.is_empty() && self.healthy_agent_count("review") == 0
262 }
263
264 pub fn has_routable_review_agent(&self) -> bool {
265 !self.available_agents.is_empty() && self.healthy_agent_count("review") > 0
266 }
267
268 pub fn model_for_complexity(
269 &self,
270 agent: &str,
271 complexity: &str,
272 task_id: &str,
273 ) -> Option<String> {
274 self.config.model_for_complexity(agent, complexity, task_id)
275 }
276
277 pub fn new(config: RouterConfig) -> Self {
279 let available_agents = Self::discover_agents(&config.agents);
280 let weights = config.agent_weights(&available_agents);
281 let router_pool = Self::expand_pool(&config);
282 tracing::info!(
283 pool = ?router_pool,
284 fallback = %config.effective_fallback(),
285 "router LLM pool initialized"
286 );
287 if config.uses_opencode() {
290 opencode::prime_free_model_cache();
291 }
292 let ollama_router = if config.mode == "local" {
293 Some(ollama::OllamaRouter::new(&config))
294 } else {
295 None
296 };
297 Self {
298 config,
299 available_agents,
300 weights,
301 llm_router: Arc::new(LlmRouter::new()),
302 ollama_router,
303 rr_index: 0,
304 last_agent: None,
305 review_rr_index: 0,
306 router_pool,
307 pool_index: 0,
308 }
309 }
310
311 pub fn from_config() -> Self {
313 Self::new(RouterConfig::from_config())
314 }
315
316 #[cfg(test)]
319 pub(crate) fn new_for_test(config: RouterConfig, available_agents: Vec<String>) -> Self {
320 let mut weights = AgentWeights {
321 base_weights: config.weights.clone(),
322 ..Default::default()
323 };
324 weights.ensure_agents(&available_agents);
325 let router_pool = Self::expand_pool(&config);
326 Self {
327 config,
328 available_agents,
329 weights,
330 llm_router: Arc::new(LlmRouter::new()),
331 ollama_router: None,
332 rr_index: 0,
333 last_agent: None,
334 review_rr_index: 0,
335 router_pool,
336 pool_index: 0,
337 }
338 }
339
340 fn advance_pool_index_after_attempt(&mut self, idx: usize, pool_len: usize) {
341 debug_assert!(pool_len > 0, "router pool must not be empty");
342 self.pool_index = (idx + 1) % pool_len;
343 }
344
345 fn discover_agents(configured_agents: &[String]) -> Vec<String> {
348 let mut agents = Vec::new();
349 for agent in configured_agents {
350 if cmd_cache::command_exists(agent) {
351 agents.push(agent.clone());
352 }
353 }
354 agents
355 }
356
357 fn expand_pool(config: &RouterConfig) -> Vec<(String, String)> {
364 let raw_pool = config.effective_pool();
365 let mut expanded: Vec<(String, String)> = Vec::new();
366
367 for entry in &raw_pool {
368 if entry == "opencode:free" {
369 let free_models = Self::discover_free_opencode_models();
370 if free_models.is_empty() {
371 tracing::debug!("opencode:free expanded to nothing — skipping");
372 } else {
373 tracing::debug!(models = ?free_models, "opencode:free expanded");
374 for model in free_models {
375 expanded.push(("opencode".to_string(), model));
376 }
377 }
378 } else {
379 let (agent, model) = parse_pool_entry(entry);
380 expanded.push((agent, model));
381 }
382 }
383
384 if expanded.is_empty() {
385 let (agent, model) = parse_pool_entry(&config.effective_fallback());
387 tracing::debug!(
388 agent = %agent, model = %model,
389 "pool empty after expansion, using fallback as sole pool entry"
390 );
391 expanded.push((agent, model));
392 }
393
394 expanded
395 }
396
397 async fn expand_pool_async(config: &RouterConfig) -> Vec<(String, String)> {
400 let raw_pool = config.effective_pool();
401 let mut expanded: Vec<(String, String)> = Vec::new();
402
403 for entry in &raw_pool {
404 if entry == "opencode:free" {
405 let free_models = Self::discover_free_opencode_models_async().await;
406 if free_models.is_empty() {
407 tracing::debug!("opencode:free expanded to nothing — skipping (async)");
408 } else {
409 tracing::debug!(models = ?free_models, "opencode:free expanded (async)");
410 for model in free_models {
411 expanded.push(("opencode".to_string(), model));
412 }
413 }
414 } else {
415 let (agent, model) = parse_pool_entry(entry);
416 expanded.push((agent, model));
417 }
418 }
419
420 if expanded.is_empty() {
421 let (agent, model) = parse_pool_entry(&config.effective_fallback());
423 tracing::debug!(
424 agent = %agent, model = %model,
425 "pool empty after async expansion, using fallback as sole pool entry"
426 );
427 expanded.push((agent, model));
428 }
429
430 expanded
431 }
432
433 pub async fn reload_async(&mut self) {
436 let new_config = RouterConfig::from_config();
437 let new_agents = Self::discover_agents(&new_config.agents);
438 let new_pool = Self::expand_pool_async(&new_config).await;
439 tracing::info!(
440 mode = %new_config.mode,
441 agents = ?new_agents,
442 fallback = %new_config.fallback_executor,
443 weighted_rr = new_config.weighted_round_robin,
444 pool = ?new_pool,
445 "router reloaded (async)"
446 );
447 self.config = new_config;
448 self.available_agents.clone_from(&new_agents);
449 self.weights.ensure_agents(&new_agents);
451 self.router_pool = new_pool;
452 self.pool_index = 0;
453 self.ollama_router = if self.config.mode == "local" {
455 Some(ollama::OllamaRouter::new(&self.config))
456 } else {
457 None
458 };
459 }
460
461 fn discover_free_opencode_models() -> Vec<String> {
462 opencode::discover_free_opencode_models()
463 }
464
465 async fn discover_free_opencode_models_async() -> Vec<String> {
466 task::spawn_blocking(Self::discover_free_opencode_models)
467 .await
468 .unwrap_or_default()
469 }
470
471 pub async fn refresh_health(&self, store: &Arc<TaskStore>) {
476 sync_from_kv(store).await;
483
484 let agents = self.available_agents.clone();
485 let model_checker = |agent: &str| -> bool { self.agent_has_any_available_model(agent) };
486 refresh_degraded_agents(
487 store,
488 &agents,
489 &model_checker,
490 config::health_check_window_hours(),
491 config::degraded_rate_limit_threshold(),
492 )
493 .await;
494 }
495
496 pub fn is_agent_available(&self, agent: &str) -> bool {
498 self.available_agents.contains(&agent.to_string())
499 }
500
501 fn agent_has_any_available_model(&self, agent: &str) -> bool {
505 ["simple", "medium", "complex", "review"]
506 .iter()
507 .any(|comp| self.config.has_available_model_for_complexity(agent, comp))
508 }
509
510 fn agent_has_available_model_for_coding_tiers(&self, agent: &str) -> bool {
519 ["medium", "complex"]
520 .iter()
521 .all(|comp| self.config.has_available_model_for_complexity(agent, comp))
522 }
523
524 fn agent_is_routable(&self, agent: &str, complexity: &str) -> bool {
525 if !self.is_agent_available(agent) {
526 return false;
527 }
528 if is_agent_in_cooldown(agent) {
529 tracing::debug!(agent, "agent skipped: in cooldown");
530 return false;
531 }
532 if is_agent_degraded(agent) {
533 tracing::debug!(agent, "agent skipped: degraded (pre-emptive health check)");
534 return false;
535 }
536 if self.config.weighted_round_robin {
540 let weight = self.weights.get_weight(agent);
541 if weight < config::SKIP_LIMITED_THRESHOLD {
542 tracing::debug!(
543 agent,
544 weight,
545 "agent considered degraded by weight threshold, skipping"
546 );
547 return false;
548 }
549 }
550 if !self
551 .config
552 .has_available_model_in_any_tier(agent, complexity)
553 {
554 tracing::debug!(agent, complexity, "agent skipped: no available model");
555 return false;
556 }
557 true
558 }
559
560 fn available_agents_for_complexity(&self, complexity: &str) -> Vec<String> {
561 self.available_agents
562 .iter()
563 .filter(|agent| self.agent_is_routable(agent, complexity))
564 .cloned()
565 .collect()
566 }
567
568 pub fn healthy_agent_count(&self, complexity: &str) -> usize {
571 self.available_agents_for_complexity(complexity).len()
572 }
573
574 pub fn is_degraded(&self, threshold: usize) -> bool {
577 self.healthy_agent_count("simple") < threshold
578 }
579
580 pub fn earliest_cooldown_until(&self, complexity: Option<&str>) -> Option<i64> {
581 let mut earliest: Option<i64> = None;
582
583 for agent in &self.available_agents {
584 if let Some(until) = cooldown_until(agent) {
585 earliest = Some(earliest.map_or(until, |current| current.min(until)));
586 }
587
588 if let Some(comp) = complexity
589 && let Some(pool) = self.config.model_pool_for_complexity(agent, comp)
590 {
591 for model in pool {
592 let key = format!("{agent}:{model}");
593 if let Some(until) = cooldown_until(&key) {
594 earliest = Some(earliest.map_or(until, |current| current.min(until)));
595 }
596 }
597 }
598 }
599
600 earliest
601 }
602
603 fn earliest_pool_cooldown(&self) -> Option<i64> {
608 let mut earliest: Option<i64> = None;
609 for (agent, model) in &self.router_pool {
610 let key = format!("{agent}:{model}");
611 if let Some(until) = cooldown_until(&key) {
612 earliest = Some(earliest.map_or(until, |current| current.min(until)));
613 }
614 }
615 earliest
616 }
617
618 fn wait_for_cooldown(&self, complexity: Option<&str>) -> anyhow::Result<()> {
619 let now = chrono::Utc::now().timestamp();
626 let Some(earliest) = self.earliest_cooldown_until(complexity) else {
627 tracing::warn!(
631 scope = complexity.unwrap_or("all agents"),
632 "all agents degraded (no cooldown timestamp available) — skipping task, will retry after backoff"
633 );
634 return Err(AllAgentsCooledError::new(
636 complexity.unwrap_or("all agents").to_string(),
637 None,
638 )
639 .into());
640 };
641
642 let remaining = earliest.saturating_sub(now);
643 if remaining > 0 {
644 let scope_str = complexity.unwrap_or("all agents").to_string();
645 tracing::warn!(
646 remaining_secs = remaining,
647 scope = %scope_str,
648 "all agents/models cooled — routing is unavailable until cooldown expires; failing fast to let tick retry"
649 );
650 return Err(AllAgentsCooledError::new(scope_str, u64::try_from(remaining).ok()).into());
653 }
654
655 Ok(())
656 }
657
658 pub fn next_round_robin_agent(&mut self, exclude: &[&str], complexity: &str) -> Option<String> {
663 let candidates = self.available_agents_for_complexity(complexity);
666 if candidates.is_empty() {
667 return None;
668 }
669 let idx = self.review_rr_index;
670 let n = candidates.len();
671
672 let agent = (0..n)
674 .map(|offset| &candidates[(idx + offset) % n])
675 .find(|a| !exclude.contains(&a.as_str()))
676 .cloned()
677 .or_else(|| candidates.first().cloned())?;
679
680 self.review_rr_index = (idx + 1) % candidates.len().max(1);
681 Some(agent)
682 }
683
684 async fn skip_no_code_agent(
688 &self,
689 store: &Arc<TaskStore>,
690 repo: &str,
691 task_id: &str,
692 candidates: &[String],
693 ) -> Option<Vec<String>> {
694 let no_code_agent = get_task_field_direct(store, repo, task_id, "no_code_last_agent")
695 .await
696 .unwrap_or_else(|| {
697 tracing::warn!(
698 task_id,
699 "no_code_last_agent DB read returned None — loop detection may be impaired"
700 );
701 String::new()
702 });
703 if no_code_agent.is_empty() || !candidates.iter().any(|a| a == &no_code_agent) {
704 return None;
705 }
706 let filtered: Vec<String> = candidates
707 .iter()
708 .filter(|a| a.as_str() != no_code_agent)
709 .cloned()
710 .collect();
711 if filtered.is_empty() {
712 tracing::warn!(
713 task_id,
714 no_code_agent = %no_code_agent,
715 "all available agents are the no-code agent — cannot skip"
716 );
717 return None;
718 }
719 tracing::info!(
720 task_id,
721 skipped = %no_code_agent,
722 remaining = ?filtered,
723 "skipping no-code agent, routing to alternative"
724 );
725 Some(filtered)
726 }
727
728 pub async fn route(
737 &mut self,
738 task: &ExternalTask,
739 store: &Arc<TaskStore>,
740 repo: &str,
741 ) -> anyhow::Result<RouteResult> {
742 match store.resolve_id_by_external(repo, &task.id.0).await {
748 Ok(Some(id)) => match store.block_claim_if_waiting(id).await {
749 Ok(Some(blockers)) => {
750 return Err(WaitingOnDependency { blockers }.into());
751 }
752 Ok(None) => {}
753 Err(err) => return Err(err),
754 },
755 Ok(None) => {}
756 Err(err) => return Err(err),
757 }
758
759 loop {
760 let store_agent = match store.get_agent_by_external_id(repo, &task.id.0).await {
766 Ok(Some(agent)) => {
767 if !agent.is_empty() && self.config.has_agent(&agent) {
769 Some(agent)
770 } else {
771 None
772 }
773 }
774 Ok(None) => None,
775 Err(e) => {
776 tracing::warn!(
777 repo,
778 task_id = %task.id.0,
779 err = %e,
780 "failed to fetch stored agent, falling back to label/LLM routing"
781 );
782 None
783 }
784 };
785
786 if store_agent.is_none()
788 && let Some(result) = self.route_profile(task)?
789 {
790 self.log_route_activity(store, repo, &task.id.0, &result, None)
791 .await;
792 return Ok(result);
793 }
794
795 let resolved_agent = store_agent.or_else(|| {
797 strategies::extract_agent_from_labels(&self.config.agents, &task.labels)
798 });
799
800 if let Some(agent) = resolved_agent {
801 let complexity = strategies::extract_complexity_from_labels(&task.labels);
802 if self.agent_is_routable(&agent, &complexity) {
811 let (model, tier_warning) =
812 RouteResult::resolve_model(&self.config, &agent, &complexity, &task.id.0);
813
814 if model.is_some() {
822 tracing::debug!(
823 task_id = %task.id.0,
824 agent = %agent,
825 complexity = %complexity,
826 "routed via label"
827 );
828 let mut result = RouteResult::from_config(
829 agent.clone(),
830 complexity.clone(),
831 format!("label agent:{agent}"),
832 &self.config,
833 &task.id.0,
834 );
835 result.profile.role = format!("{agent} specialist");
838 result.model = model.clone();
839 result.warning = tier_warning;
840 self.log_route_activity(store, repo, &task.id.0, &result, None)
841 .await;
842 return Ok(result);
843 }
844 tracing::warn!(task_id = %task.id.0, agent = %agent, "label agent has no available model — falling through to LLM routing");
849 }
850
851 let candidates = self.available_agents_for_complexity(&complexity);
852 if candidates.is_empty() {
853 self.wait_for_cooldown(Some(&complexity))?;
854 continue;
855 }
856 }
858
859 let complexity = strategies::extract_complexity_from_labels(&task.labels);
860
861 let mut candidates = self.available_agents_for_complexity(&complexity);
863 if candidates.is_empty() {
864 self.wait_for_cooldown(Some(&complexity))?;
865 continue;
866 }
867
868 if let Some(filtered) = self
873 .skip_no_code_agent(store, repo, &task.id.0, &candidates)
874 .await
875 {
876 candidates = filtered;
877 }
878
879 if self.config.weighted_round_robin {
881 let result = strategies::route_via_weighted_round_robin(
882 &candidates,
883 &self.weights,
884 &self.config,
885 task,
886 &mut self.last_agent,
887 )?;
888 self.log_route_activity(store, repo, &task.id.0, &result, None)
889 .await;
890 return Ok(result);
891 }
892
893 if self.config.mode == "round_robin" || self.config.mode == "profile" {
895 tracing::debug!(task_id = %task.id.0, "routing via round-robin mode");
896 let result = strategies::route_via_round_robin_stateful(
897 &candidates,
898 &self.config,
899 task,
900 &mut self.rr_index,
901 &mut self.last_agent,
902 )?;
903 self.log_route_activity(store, repo, &task.id.0, &result, None)
904 .await;
905 return Ok(result);
906 }
907
908 if self.config.mode == "local" {
910 tracing::debug!(task_id = %task.id.0, ollama_url = %self.config.ollama_url, "routing via local Ollama");
911 let ollama_router = self
912 .ollama_router
913 .as_ref()
914 .expect("ollama_router must be initialized in Router::new when mode=local");
915 match ollama_router.route(task, &self.config).await {
916 Ok(result) => {
917 self.log_route_activity(store, repo, &task.id.0, &result, None)
918 .await;
919 return Ok(result);
920 }
921 Err(e) => {
922 tracing::warn!(
923 task_id = %task.id.0,
924 error = %e,
925 "Ollama routing failed, falling back to round-robin"
926 );
927 let result = strategies::route_via_round_robin_stateful(
928 &candidates,
929 &self.config,
930 task,
931 &mut self.rr_index,
932 &mut self.last_agent,
933 )?;
934 self.log_route_activity(store, repo, &task.id.0, &result, None)
935 .await;
936 return Ok(result);
937 }
938 }
939 }
940
941 let route_attempts = self.get_route_attempts(&task.id.0, store, repo).await;
943
944 if route_attempts >= self.config.max_route_attempts {
945 tracing::warn!(
946 task_id = %task.id.0,
947 attempts = route_attempts,
948 max = self.config.max_route_attempts,
949 "max LLM route attempts reached, falling back to round-robin"
950 );
951 let candidates = self.available_agents_for_complexity(&complexity);
952 if candidates.is_empty() {
953 self.wait_for_cooldown(Some(&complexity))?;
954 continue;
955 }
956 let result = strategies::route_via_round_robin_stateful(
957 &candidates,
958 &self.config,
959 task,
960 &mut self.rr_index,
961 &mut self.last_agent,
962 )?;
963 self.log_route_activity(store, repo, &task.id.0, &result, None)
964 .await;
965 return Ok(result);
966 }
967
968 tracing::debug!(task_id = %task.id.0, "starting LLM routing");
970
971 match self.route_with_llm(task, repo).await {
972 Ok(result) => {
973 let candidates = self.available_agents_for_complexity(&result.complexity);
974 if candidates.is_empty() {
975 self.wait_for_cooldown(Some(&result.complexity))?;
976 continue;
977 }
978
979 let no_code_agent =
982 get_task_field_direct(store, repo, &task.id.0, "no_code_last_agent")
983 .await
984 .unwrap_or_else(|| {
985 tracing::warn!(task_id = %task.id.0, "no_code_last_agent DB read returned None — loop detection may be impaired");
986 String::new()
987 });
988 if result.agent == no_code_agent {
989 let fallback_agent = candidates
991 .iter()
992 .find(|a| a.as_str() != no_code_agent)
993 .cloned()
994 .unwrap_or_else(|| candidates[0].clone());
995 if fallback_agent.as_str() == no_code_agent {
996 tracing::warn!(
997 task_id = %task.id.0,
998 no_code_agent = %no_code_agent,
999 complexity = %result.complexity,
1000 "all available agents are the no-code agent — waiting for another agent"
1001 );
1002 self.wait_for_cooldown(Some(&result.complexity))?;
1003 continue;
1004 }
1005 tracing::info!(
1006 task_id = %task.id.0,
1007 llm_selected = %result.agent,
1008 skipped = %no_code_agent,
1009 fallback = %fallback_agent,
1010 "LLM selected the no-code agent — routing to alternative"
1011 );
1012 let (fallback_model, _) = RouteResult::resolve_model(
1013 &self.config,
1014 &fallback_agent,
1015 &result.complexity,
1016 &task.id.0,
1017 );
1018
1019 self.set_route_attempts(&task.id.0, 0, store, repo).await;
1020 let result = RouteResult {
1021 agent: fallback_agent.clone(),
1022 model: fallback_model,
1023 complexity: result.complexity.clone(),
1024 estimate: result.estimate,
1025 reason: format!(
1026 "LLM selected no-code agent {}; routed to {}",
1027 result.agent, fallback_agent
1028 ),
1029 profile: result.profile.clone(),
1030 warning: Some(format!(
1031 "LLM selected no-code agent {}; used fallback {}",
1032 result.agent, fallback_agent
1033 )),
1034 };
1035 self.log_route_activity(store, repo, &task.id.0, &result, None)
1036 .await;
1037 return Ok(result);
1038 }
1039
1040 let model_cooled = result
1041 .model
1042 .as_deref()
1043 .is_some_and(|model| is_model_in_cooldown(&result.agent, model));
1044 if !candidates.contains(&result.agent) || model_cooled {
1045 let fallback_agent = candidates
1046 .iter()
1047 .find(|agent| *agent != &result.agent)
1048 .cloned()
1049 .unwrap_or_else(|| candidates[0].clone());
1050 let (fallback_model, _) = RouteResult::resolve_model(
1051 &self.config,
1052 &fallback_agent,
1053 &result.complexity,
1054 &task.id.0,
1055 );
1056
1057 if fallback_model.is_none() && fallback_agent == result.agent {
1063 tracing::warn!(
1064 task_id = %task.id.0,
1065 agent = %result.agent,
1066 complexity = %result.complexity,
1067 "LLM-selected model(s) are cooled for the only available agent; waiting for cooldown"
1068 );
1069 self.wait_for_cooldown(Some(&result.complexity))?;
1070 continue;
1071 }
1072
1073 if fallback_agent == result.agent {
1077 tracing::warn!(
1078 task_id = %task.id.0,
1079 agent = %result.agent,
1080 complexity = %result.complexity,
1081 "LLM-selected model was cooled; selecting an alternative model for the same agent"
1082 );
1083 } else {
1084 tracing::warn!(
1085 task_id = %task.id.0,
1086 agent = %result.agent,
1087 fallback = %fallback_agent,
1088 complexity = %result.complexity,
1089 "LLM selected cooled agent/model; rerouting to available agent"
1090 );
1091 }
1092
1093 self.set_route_attempts(&task.id.0, 0, store, repo).await;
1095
1096 let reason = if fallback_agent == result.agent {
1097 format!(
1098 "LLM selected cooled model; using same agent {fallback_agent} with different model"
1099 )
1100 } else {
1101 format!("LLM selected cooled agent/model; rerouted to {fallback_agent}")
1102 };
1103
1104 let result = RouteResult {
1105 agent: fallback_agent.clone(),
1106 model: fallback_model,
1107 complexity: result.complexity.clone(),
1108 estimate: result.estimate,
1109 reason: reason.clone(),
1110 profile: result.profile.clone(),
1111 warning: Some(if fallback_agent == result.agent {
1112 "LLM-selected model was cooled; selected alternative model for same agent"
1113 .to_string()
1114 } else {
1115 "LLM-selected agent/model was cooled; rerouted to available agent"
1116 .to_string()
1117 }),
1118 };
1119 self.log_route_activity(store, repo, &task.id.0, &result, None)
1120 .await;
1121 return Ok(result);
1122 }
1123
1124 self.set_route_attempts(&task.id.0, 0, store, repo).await;
1126 tracing::info!(
1127 task_id = %task.id.0,
1128 agent = %result.agent,
1129 complexity = %result.complexity,
1130 "routed via LLM"
1131 );
1132 self.log_route_activity(store, repo, &task.id.0, &result, None)
1133 .await;
1134 return Ok(result);
1135 }
1136 Err(e) => {
1137 if let Some(err) = e.downcast_ref::<AllAgentsCooledError>() {
1138 let scope = err.scope();
1139 tracing::warn!(scope = %scope, "router cooldown gate tripped");
1140 let scope_opt = match scope {
1144 "all agents" | "router pool" => None,
1145 _ => Some(scope),
1146 };
1147 self.wait_for_cooldown(scope_opt)?;
1148 continue;
1149 }
1150
1151 let new_attempts = route_attempts + 1;
1152 self.set_route_attempts(&task.id.0, new_attempts, store, repo)
1153 .await;
1154 tracing::warn!(
1155 task_id = %task.id.0,
1156 error = %e,
1157 error_chain = ?e,
1158 attempt = new_attempts,
1159 max = self.config.max_route_attempts,
1160 "LLM routing failed"
1161 );
1162
1163 if new_attempts >= self.config.max_route_attempts {
1164 tracing::info!(
1165 task_id = %task.id.0,
1166 "falling back to round-robin after {} failed attempts",
1167 new_attempts
1168 );
1169 let candidates = self.available_agents_for_complexity(&complexity);
1170 if candidates.is_empty() {
1171 self.wait_for_cooldown(Some(&complexity))?;
1172 continue;
1173 }
1174 let result = strategies::route_via_round_robin_stateful(
1175 &candidates,
1176 &self.config,
1177 task,
1178 &mut self.rr_index,
1179 &mut self.last_agent,
1180 )?;
1181 self.log_route_activity(store, repo, &task.id.0, &result, None)
1182 .await;
1183 return Ok(result);
1184 }
1185
1186 let candidates = self.available_agents_for_complexity(&complexity);
1187 if candidates.is_empty() {
1188 self.wait_for_cooldown(Some(&complexity))?;
1189 continue;
1190 }
1191 let result = strategies::route_via_fallback(
1192 &candidates,
1193 &self.config,
1194 task,
1195 Some(&self.weights),
1196 )?;
1197 self.log_route_activity(store, repo, &task.id.0, &result, None)
1198 .await;
1199 return Ok(result);
1200 }
1201 }
1202 }
1203 }
1204
1205 async fn get_route_attempts(&self, task_id: &str, store: &Arc<TaskStore>, repo: &str) -> u32 {
1207 match store.resolve_task_id(repo, task_id).await {
1208 Ok(Some(store_id)) => store
1209 .get(store_id)
1210 .await
1211 .map_or(0, |t| u32::try_from(t.route_attempts).unwrap_or(0)),
1212 _ => 0,
1213 }
1214 }
1215
1216 async fn set_route_attempts(
1218 &self,
1219 task_id: &str,
1220 attempts: u32,
1221 store: &Arc<TaskStore>,
1222 repo: &str,
1223 ) {
1224 if let Ok(Some(store_id)) = store.resolve_task_id(repo, task_id).await
1225 && let Err(e) = store
1226 .set_fields(store_id, &[("route_attempts", serde_json::json!(attempts))])
1227 .await
1228 {
1229 tracing::warn!(task_id, error = %e, "failed to store route_attempts");
1230 }
1231 }
1232
1233 async fn log_route_activity(
1235 &self,
1236 store: &Arc<TaskStore>,
1237 repo: &str,
1238 task_id: &str,
1239 result: &RouteResult,
1240 from_agent: Option<&str>,
1241 ) {
1242 let details = serde_json::json!({
1243 "reason": result.reason,
1244 "complexity": result.complexity,
1245 "role": result.profile.role,
1246 "warning": result.warning,
1247 });
1248 let event_type = if from_agent.is_some() {
1249 "rerouted"
1250 } else {
1251 "routed"
1252 };
1253 store_log_activity(
1254 &Some(Arc::clone(store)),
1255 repo,
1256 task_id,
1257 event_type,
1258 None,
1259 Some("routed"),
1260 Some(&result.agent),
1261 result.model.as_deref(),
1262 Some(&details),
1263 )
1264 .await;
1265 }
1266
1267 async fn route_with_llm(
1273 &mut self,
1274 task: &ExternalTask,
1275 repo: &str,
1276 ) -> anyhow::Result<RouteResult> {
1277 let uncooled_agents: Vec<String> = self
1287 .available_agents
1288 .iter()
1289 .filter(|a| {
1290 !is_agent_in_cooldown(a)
1291 && !is_agent_degraded(a)
1292 && self.agent_has_available_model_for_coding_tiers(a)
1293 })
1294 .cloned()
1295 .collect();
1296 if uncooled_agents.is_empty() {
1297 return Err(AllAgentsCooledError::new("all agents".to_string(), None).into());
1298 }
1299 let llm_agents = uncooled_agents;
1300
1301 let pool = self.router_pool.clone();
1302 let n = pool.len();
1303 let start = self.pool_index;
1304 let mut last_err: Option<anyhow::Error> = None;
1305 let mut attempted_any = false;
1306
1307 for i in 0..n {
1309 let idx = (start + i) % n;
1310 let (agent, model) = &pool[idx];
1311 let model_str = model.as_str();
1312
1313 if cooldown::is_model_in_cooldown(agent, model_str) {
1314 tracing::debug!(agent, model = model_str, "pool entry on cooldown, skipping");
1315 continue;
1316 }
1317
1318 attempted_any = true;
1320
1321 let model_opt = if model_str.is_empty() {
1322 None
1323 } else {
1324 Some(model_str)
1325 };
1326
1327 match self
1328 .llm_router
1329 .route_with_llm_using(
1330 task,
1331 &llm_agents,
1332 &self.config,
1333 &mut self.last_agent,
1334 repo,
1335 agent,
1336 model_opt,
1337 )
1338 .await
1339 {
1340 Ok(result) => {
1341 self.advance_pool_index_after_attempt(idx, n);
1343 tracing::debug!(
1344 agent,
1345 model = model_str,
1346 pool_idx = idx,
1347 "router LLM pool entry succeeded"
1348 );
1349 record_agent_success(agent, model_str).await;
1350 return Ok(result);
1351 }
1352 Err(e) => {
1353 let err_msg = e.to_string();
1354 let is_timeout = err_msg.contains(TIMEOUT_PREFIX);
1355 if is_timeout {
1356 self.advance_pool_index_after_attempt(idx, n);
1366 tracing::warn!(
1367 agent,
1368 model = model_str,
1369 next_pool_idx = self.pool_index,
1370 "router LLM pool entry timed out — recording cooldown, will retry next tick"
1371 );
1372 cooldown::record_model_failure(agent, model_str).await;
1373 return Err(e);
1374 }
1375 if is_max_turns_error(&err_msg) {
1376 tracing::warn!(
1377 agent,
1378 model = model_str,
1379 error = %e,
1380 "pool entry hit max turns — trying next without cooldown"
1381 );
1382 } else {
1383 tracing::warn!(
1384 agent,
1385 model = model_str,
1386 error = %e,
1387 "pool entry failed, recording cooldown and trying next"
1388 );
1389 if !cooldown::record_credit_exhaustion_from_message(
1390 agent,
1391 Some(model_str),
1392 &err_msg,
1393 )
1394 .await
1395 {
1396 cooldown::record_model_failure(agent, model_str).await;
1397 }
1398 }
1399 last_err = Some(e);
1400 self.advance_pool_index_after_attempt(idx, n);
1401 }
1402 }
1403 }
1404
1405 if !attempted_any {
1410 let now = chrono::Utc::now().timestamp();
1411 let earliest = self.earliest_pool_cooldown();
1412 if let Some(until) = earliest {
1413 let remaining = until.saturating_sub(now);
1415 tracing::warn!(
1416 remaining_secs = remaining,
1417 pool = ?pool,
1418 "all router LLM pool entries on cooldown — will try fallback"
1419 );
1420 } else {
1422 return Err(last_err
1425 .unwrap_or_else(|| anyhow::anyhow!("all router LLM pool entries exhausted")));
1426 }
1427 }
1428
1429 let fallback = self.config.effective_fallback();
1431 let (fb_agent, fb_model) = parse_pool_entry(&fallback);
1432 let fb_model_str = fb_model.as_str();
1433
1434 let fallback_already_tried = pool.iter().any(|(a, m)| a == &fb_agent && m == &fb_model);
1436
1437 if !fallback_already_tried && !cooldown::is_model_in_cooldown(&fb_agent, fb_model_str) {
1438 tracing::info!(
1439 agent = %fb_agent,
1440 model = %fb_model_str,
1441 "all pool entries exhausted — trying fallback router LLM"
1442 );
1443 let fb_model_opt = if fb_model_str.is_empty() {
1444 None
1445 } else {
1446 Some(fb_model_str)
1447 };
1448 match self
1449 .llm_router
1450 .route_with_llm_using(
1451 task,
1452 &llm_agents,
1453 &self.config,
1454 &mut self.last_agent,
1455 repo,
1456 &fb_agent,
1457 fb_model_opt,
1458 )
1459 .await
1460 {
1461 Ok(result) => {
1462 record_agent_success(&fb_agent, fb_model_str).await;
1463 return Ok(result);
1464 }
1465 Err(e) => {
1466 let err_msg = e.to_string();
1467 let is_timeout = err_msg.contains(TIMEOUT_PREFIX);
1468 if is_timeout {
1469 cooldown::record_model_failure(&fb_agent, fb_model_str).await;
1472 tracing::warn!(
1473 agent = %fb_agent,
1474 model = %fb_model_str,
1475 "fallback router LLM timed out — returning immediately to unblock tick loop"
1476 );
1477 return Err(e);
1478 }
1479 tracing::warn!(
1480 agent = %fb_agent,
1481 model = %fb_model_str,
1482 error = %e,
1483 "fallback router LLM also failed"
1484 );
1485 if !is_max_turns_error(&err_msg) {
1486 cooldown::record_model_failure(&fb_agent, fb_model_str).await;
1487 }
1488 last_err = Some(e);
1489 }
1490 }
1491 }
1492
1493 Err(last_err.unwrap_or_else(|| anyhow::anyhow!("all router LLM pool entries exhausted")))
1494 }
1495
1496 pub fn record_rate_limit(&mut self, agent: &str) {
1500 self.weights.record_rate_limit(agent);
1501 }
1502
1503 pub fn record_success(&mut self, agent: &str) {
1505 self.weights.record_success(agent);
1506 }
1507
1508 pub fn tick_weight_recovery(&mut self) {
1513 self.weights.tick_recovery();
1514 }
1515
1516 pub async fn store_route_result(
1518 &self,
1519 task_id: &str,
1520 result: &RouteResult,
1521 store: &Arc<TaskStore>,
1522 repo: &str,
1523 ) -> anyhow::Result<()> {
1524 if let Ok(Some(store_id)) = store.resolve_task_id(repo, task_id).await {
1525 store
1526 .set_fields(
1527 store_id,
1528 &[
1529 ("agent", serde_json::json!(result.agent)),
1530 ("complexity", serde_json::json!(result.complexity)),
1531 ("route_reason", serde_json::json!(result.reason)),
1532 (
1533 "agent_profile",
1534 serde_json::json!(serde_json::to_string(&result.profile)?),
1535 ),
1536 (
1537 "model",
1538 serde_json::json!(result.model.as_deref().unwrap_or("")),
1539 ),
1540 ],
1541 )
1542 .await?;
1543 }
1544 Ok(())
1545 }
1546}
1547
1548pub async fn get_route_result(
1550 store: &Arc<TaskStore>,
1551 repo: &str,
1552 task_id: &str,
1553) -> Result<RouteResult, RouteResultError> {
1554 let store_id = store
1555 .resolve_task_id(repo, task_id)
1556 .await
1557 .map_err(RouteResultError::Other)?
1558 .ok_or_else(|| {
1559 RouteResultError::Other(anyhow::anyhow!("task {task_id} not found in store"))
1560 })?;
1561 let task = store.get(store_id).await.map_err(RouteResultError::Other)?;
1562
1563 let agent = task
1564 .agent
1565 .clone()
1566 .filter(|a| !a.is_empty())
1567 .ok_or_else(|| RouteResultError::NoAgent {
1568 task_id: task_id.to_string(),
1569 })?;
1570
1571 let complexity = if task.complexity.is_empty() {
1572 "medium".to_string()
1573 } else {
1574 task.complexity.clone()
1575 };
1576
1577 let reason = task.route_reason.clone();
1578 let model = task.model.clone().filter(|m| !m.is_empty());
1579 let profile = AgentProfile {
1583 execution: serde_json::from_str::<AgentProfile>(&task.agent_profile)
1584 .ok()
1585 .and_then(|stored| stored.execution)
1586 .filter(|p| p.matches_route(&agent, model.as_deref())),
1587 ..AgentProfile::default()
1588 };
1589
1590 let config = RouterConfig::from_config();
1594 let model = model.filter(|m| {
1595 let complexities = ["simple", "medium", "complex", "review"];
1596 let all_pools: Vec<Vec<String>> = complexities
1598 .iter()
1599 .filter_map(|comp| config.model_pool_for_complexity(&agent, comp))
1600 .collect();
1601 if all_pools.is_empty() {
1603 return true;
1604 }
1605 let valid = all_pools.iter().any(|pool| pool.contains(m))
1606 || profile
1607 .execution
1608 .as_ref()
1609 .is_some_and(|p| p.matches_route(&agent, Some(m)));
1610 if !valid {
1611 tracing::warn!(
1612 task_id,
1613 agent,
1614 model = %m,
1615 "discarding stale model: not in agent's model pools"
1616 );
1617 }
1618 valid
1619 });
1620
1621 let original_model = task.model.clone().filter(|m| !m.is_empty());
1624 let mut model = model;
1625 if original_model.is_some() && model.is_none() {
1626 model = config.model_for_complexity(&agent, &complexity, task_id);
1627 let stale_model = original_model.as_deref().unwrap_or("unknown");
1628 let stale_err = format!(
1629 "stale model discarded: {stale_model} not in {agent} model pools, using {}",
1630 model.as_deref().unwrap_or("the agent default")
1631 );
1632 if let Err(e) = store
1633 .set_fields(
1634 store_id,
1635 &[
1636 (
1637 "model",
1638 serde_json::json!(model.clone().unwrap_or_default()),
1639 ),
1640 ("last_error", serde_json::json!(stale_err)),
1641 ],
1642 )
1643 .await
1644 {
1645 tracing::warn!(task_id = %task_id, error = %e, "failed to clear stale model from store — will retry on next dispatch");
1647 }
1648 }
1649
1650 Ok(RouteResult {
1651 agent,
1652 model,
1653 complexity,
1654 estimate: 0,
1655 reason,
1656 profile,
1657 warning: None,
1658 })
1659}
1660
1661#[cfg(test)]
1662#[expect(
1663 clippy::float_cmp,
1664 reason = "the weights are stored constants, so they compare exactly"
1665)]
1666mod tests;