1pub mod config;
16mod llm;
17mod ollama;
18pub mod profiles;
19mod selection;
20mod strategies;
21pub mod weights;
22
23use crate::backends::ExternalTask;
24use crate::cmd_cache;
25use crate::engine::cooldown;
26use crate::engine::cooldown::{
27 cooldown_until, is_agent_degraded, is_agent_in_cooldown, is_model_in_cooldown,
28 list_degraded_agents, record_agent_success, refresh_degraded_agents, sync_from_kv,
29};
30use crate::engine::runner::agents::opencode;
31use crate::engine::runner::response;
32use crate::store::WaitingOnDependency;
33use crate::store::{TaskStore, get_task_field_direct, store_log_activity};
34pub use config::{RouterConfig, parse_pool_entry};
35use llm::{LlmRouter, TIMEOUT_PREFIX};
36use serde::{Deserialize, Serialize};
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}
238
239impl Debug for Router {
240 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
241 f.debug_struct("Router")
242 .field("config", &self.config)
243 .field("available_agents", &self.available_agents)
244 .field("weights", &self.weights)
245 .field("ollama_router", &self.ollama_router)
246 .field("rr_index", &self.rr_index)
247 .field("last_agent", &self.last_agent)
248 .field("review_rr_index", &self.review_rr_index)
249 .field("router_pool", &self.router_pool)
250 .field("pool_index", &self.pool_index)
251 .finish_non_exhaustive()
252 }
253}
254
255impl Router {
256 pub fn new(config: RouterConfig) -> Self {
258 let available_agents = Self::discover_agents(&config.agents);
259 let mut weights = AgentWeights {
260 base_weights: config.weights.clone(),
261 ..Default::default()
262 };
263 weights.ensure_agents_with_weights(&available_agents, &config.weights);
264 if !config.weights.is_empty() {
265 tracing::info!(
266 weights = ?config.weights,
267 "configured agent routing weights"
268 );
269 }
270 let router_pool = Self::expand_pool(&config);
271 tracing::info!(
272 pool = ?router_pool,
273 fallback = %config.effective_fallback(),
274 "router LLM pool initialized"
275 );
276 if config.uses_opencode() {
279 opencode::prime_free_model_cache();
280 }
281 let ollama_router = if config.mode == "local" {
282 Some(ollama::OllamaRouter::new(&config))
283 } else {
284 None
285 };
286 Self {
287 config,
288 available_agents,
289 weights,
290 llm_router: Arc::new(LlmRouter::new()),
291 ollama_router,
292 rr_index: 0,
293 last_agent: None,
294 review_rr_index: 0,
295 router_pool,
296 pool_index: 0,
297 }
298 }
299
300 pub fn from_config() -> Self {
302 Self::new(RouterConfig::from_config())
303 }
304
305 #[cfg(test)]
308 pub(crate) fn new_for_test(config: RouterConfig, available_agents: Vec<String>) -> Self {
309 let mut weights = AgentWeights {
310 base_weights: config.weights.clone(),
311 ..Default::default()
312 };
313 weights.ensure_agents(&available_agents);
314 let router_pool = Self::expand_pool(&config);
315 Self {
316 config,
317 available_agents,
318 weights,
319 llm_router: Arc::new(LlmRouter::new()),
320 ollama_router: None,
321 rr_index: 0,
322 last_agent: None,
323 review_rr_index: 0,
324 router_pool,
325 pool_index: 0,
326 }
327 }
328
329 fn advance_pool_index_after_attempt(&mut self, idx: usize, pool_len: usize) {
330 debug_assert!(pool_len > 0, "router pool must not be empty");
331 self.pool_index = (idx + 1) % pool_len;
332 }
333
334 fn discover_agents(configured_agents: &[String]) -> Vec<String> {
337 let mut agents = Vec::new();
338 for agent in configured_agents {
339 if cmd_cache::command_exists(agent) {
340 agents.push(agent.clone());
341 }
342 }
343 agents
344 }
345
346 fn expand_pool(config: &RouterConfig) -> Vec<(String, String)> {
353 let raw_pool = config.effective_pool();
354 let mut expanded: Vec<(String, String)> = Vec::new();
355
356 for entry in &raw_pool {
357 if entry == "opencode:free" {
358 let free_models = Self::discover_free_opencode_models();
359 if free_models.is_empty() {
360 tracing::debug!("opencode:free expanded to nothing — skipping");
361 } else {
362 tracing::debug!(models = ?free_models, "opencode:free expanded");
363 for model in free_models {
364 expanded.push(("opencode".to_string(), model));
365 }
366 }
367 } else {
368 let (agent, model) = parse_pool_entry(entry);
369 expanded.push((agent, model));
370 }
371 }
372
373 if expanded.is_empty() {
374 let (agent, model) = parse_pool_entry(&config.effective_fallback());
376 tracing::debug!(
377 agent = %agent, model = %model,
378 "pool empty after expansion, using fallback as sole pool entry"
379 );
380 expanded.push((agent, model));
381 }
382
383 expanded
384 }
385
386 async fn expand_pool_async(config: &RouterConfig) -> Vec<(String, String)> {
389 let raw_pool = config.effective_pool();
390 let mut expanded: Vec<(String, String)> = Vec::new();
391
392 for entry in &raw_pool {
393 if entry == "opencode:free" {
394 let free_models = Self::discover_free_opencode_models_async().await;
395 if free_models.is_empty() {
396 tracing::debug!("opencode:free expanded to nothing — skipping (async)");
397 } else {
398 tracing::debug!(models = ?free_models, "opencode:free expanded (async)");
399 for model in free_models {
400 expanded.push(("opencode".to_string(), model));
401 }
402 }
403 } else {
404 let (agent, model) = parse_pool_entry(entry);
405 expanded.push((agent, model));
406 }
407 }
408
409 if expanded.is_empty() {
410 let (agent, model) = parse_pool_entry(&config.effective_fallback());
412 tracing::debug!(
413 agent = %agent, model = %model,
414 "pool empty after async expansion, using fallback as sole pool entry"
415 );
416 expanded.push((agent, model));
417 }
418
419 expanded
420 }
421
422 pub async fn reload_async(&mut self) {
425 let new_config = RouterConfig::from_config();
426 let new_agents = Self::discover_agents(&new_config.agents);
427 let new_pool = Self::expand_pool_async(&new_config).await;
428 tracing::info!(
429 mode = %new_config.mode,
430 agents = ?new_agents,
431 fallback = %new_config.fallback_executor,
432 weighted_rr = new_config.weighted_round_robin,
433 pool = ?new_pool,
434 "router reloaded (async)"
435 );
436 self.config = new_config;
437 self.available_agents.clone_from(&new_agents);
438 self.weights.ensure_agents(&new_agents);
440 self.router_pool = new_pool;
441 self.pool_index = 0;
442 self.ollama_router = if self.config.mode == "local" {
444 Some(ollama::OllamaRouter::new(&self.config))
445 } else {
446 None
447 };
448 }
449
450 fn discover_free_opencode_models() -> Vec<String> {
451 opencode::discover_free_opencode_models()
452 }
453
454 async fn discover_free_opencode_models_async() -> Vec<String> {
455 task::spawn_blocking(Self::discover_free_opencode_models)
456 .await
457 .unwrap_or_default()
458 }
459
460 pub async fn refresh_health(&self, store: &Arc<TaskStore>) {
465 sync_from_kv(store).await;
472
473 let agents = self.available_agents.clone();
474 let model_checker = |agent: &str| -> bool { self.agent_has_any_available_model(agent) };
475 refresh_degraded_agents(
476 store,
477 &agents,
478 &model_checker,
479 config::health_check_window_hours(),
480 config::degraded_rate_limit_threshold(),
481 )
482 .await;
483 }
484
485 pub fn is_agent_available(&self, agent: &str) -> bool {
487 self.available_agents.contains(&agent.to_string())
488 }
489
490 fn agent_has_any_available_model(&self, agent: &str) -> bool {
494 ["simple", "medium", "complex", "review"]
495 .iter()
496 .any(|comp| self.config.has_available_model_for_complexity(agent, comp))
497 }
498
499 fn agent_has_available_model_for_coding_tiers(&self, agent: &str) -> bool {
508 ["medium", "complex"]
509 .iter()
510 .all(|comp| self.config.has_available_model_for_complexity(agent, comp))
511 }
512
513 fn agent_is_routable(&self, agent: &str, complexity: &str) -> bool {
514 if !self.is_agent_available(agent) {
515 return false;
516 }
517 if is_agent_in_cooldown(agent) {
518 tracing::debug!(agent, "agent skipped: in cooldown");
519 return false;
520 }
521 if is_agent_degraded(agent) {
522 tracing::debug!(agent, "agent skipped: degraded (pre-emptive health check)");
523 return false;
524 }
525 if self.config.weighted_round_robin {
529 let weight = self.weights.get_weight(agent);
530 if weight < config::SKIP_LIMITED_THRESHOLD {
531 tracing::debug!(
532 agent,
533 weight,
534 "agent considered degraded by weight threshold, skipping"
535 );
536 return false;
537 }
538 }
539 if !self
540 .config
541 .has_available_model_in_any_tier(agent, complexity)
542 {
543 tracing::debug!(agent, complexity, "agent skipped: no available model");
544 return false;
545 }
546 true
547 }
548
549 fn available_agents_for_complexity(&self, complexity: &str) -> Vec<String> {
550 self.available_agents
551 .iter()
552 .filter(|agent| self.agent_is_routable(agent, complexity))
553 .cloned()
554 .collect()
555 }
556
557 pub fn healthy_agent_count(&self, complexity: &str) -> usize {
560 self.available_agents_for_complexity(complexity).len()
561 }
562
563 pub fn is_degraded(&self, threshold: usize) -> bool {
566 self.healthy_agent_count("simple") < threshold
567 }
568
569 pub fn earliest_cooldown_until(&self, complexity: Option<&str>) -> Option<i64> {
570 let mut earliest: Option<i64> = None;
571
572 for agent in &self.available_agents {
573 if let Some(until) = cooldown_until(agent) {
574 earliest = Some(earliest.map_or(until, |current| current.min(until)));
575 }
576
577 if let Some(comp) = complexity
578 && let Some(pool) = self.config.model_pool_for_complexity(agent, comp)
579 {
580 for model in pool {
581 let key = format!("{agent}:{model}");
582 if let Some(until) = cooldown_until(&key) {
583 earliest = Some(earliest.map_or(until, |current| current.min(until)));
584 }
585 }
586 }
587 }
588
589 earliest
590 }
591
592 fn earliest_pool_cooldown(&self) -> Option<i64> {
597 let mut earliest: Option<i64> = None;
598 for (agent, model) in &self.router_pool {
599 let key = format!("{agent}:{model}");
600 if let Some(until) = cooldown_until(&key) {
601 earliest = Some(earliest.map_or(until, |current| current.min(until)));
602 }
603 }
604 earliest
605 }
606
607 fn wait_for_cooldown(&self, complexity: Option<&str>) -> anyhow::Result<()> {
608 let now = chrono::Utc::now().timestamp();
615 let Some(earliest) = self.earliest_cooldown_until(complexity) else {
616 tracing::warn!(
620 scope = complexity.unwrap_or("all agents"),
621 "all agents degraded (no cooldown timestamp available) — skipping task, will retry after backoff"
622 );
623 return Err(AllAgentsCooledError::new(
625 complexity.unwrap_or("all agents").to_string(),
626 None,
627 )
628 .into());
629 };
630
631 let remaining = earliest.saturating_sub(now);
632 if remaining > 0 {
633 let scope_str = complexity.unwrap_or("all agents").to_string();
634 tracing::warn!(
635 remaining_secs = remaining,
636 scope = %scope_str,
637 "all agents/models cooled — routing is unavailable until cooldown expires; failing fast to let tick retry"
638 );
639 return Err(AllAgentsCooledError::new(scope_str, u64::try_from(remaining).ok()).into());
642 }
643
644 Ok(())
645 }
646
647 pub fn next_round_robin_agent(&mut self, exclude: &[&str], complexity: &str) -> Option<String> {
652 let candidates = self.available_agents_for_complexity(complexity);
655 if candidates.is_empty() {
656 return None;
657 }
658 let idx = self.review_rr_index;
659 let n = candidates.len();
660
661 let agent = (0..n)
663 .map(|offset| &candidates[(idx + offset) % n])
664 .find(|a| !exclude.contains(&a.as_str()))
665 .cloned()
666 .or_else(|| candidates.first().cloned())?;
668
669 self.review_rr_index = (idx + 1) % candidates.len().max(1);
670 Some(agent)
671 }
672
673 async fn skip_no_code_agent(
677 &self,
678 store: &Arc<TaskStore>,
679 repo: &str,
680 task_id: &str,
681 candidates: &[String],
682 ) -> Option<Vec<String>> {
683 let no_code_agent = get_task_field_direct(store, repo, task_id, "no_code_last_agent")
684 .await
685 .unwrap_or_else(|| {
686 tracing::warn!(
687 task_id,
688 "no_code_last_agent DB read returned None — loop detection may be impaired"
689 );
690 String::new()
691 });
692 if no_code_agent.is_empty() || !candidates.iter().any(|a| a == &no_code_agent) {
693 return None;
694 }
695 let filtered: Vec<String> = candidates
696 .iter()
697 .filter(|a| a.as_str() != no_code_agent)
698 .cloned()
699 .collect();
700 if filtered.is_empty() {
701 tracing::warn!(
702 task_id,
703 no_code_agent = %no_code_agent,
704 "all available agents are the no-code agent — cannot skip"
705 );
706 return None;
707 }
708 tracing::info!(
709 task_id,
710 skipped = %no_code_agent,
711 remaining = ?filtered,
712 "skipping no-code agent, routing to alternative"
713 );
714 Some(filtered)
715 }
716
717 pub async fn route(
726 &mut self,
727 task: &ExternalTask,
728 store: &Arc<TaskStore>,
729 repo: &str,
730 ) -> anyhow::Result<RouteResult> {
731 match store.resolve_id_by_external(repo, &task.id.0).await {
737 Ok(Some(id)) => match store.block_claim_if_waiting(id).await {
738 Ok(Some(blockers)) => {
739 return Err(WaitingOnDependency { blockers }.into());
740 }
741 Ok(None) => {}
742 Err(err) => return Err(err),
743 },
744 Ok(None) => {}
745 Err(err) => return Err(err),
746 }
747
748 loop {
749 let store_agent = match store.get_agent_by_external_id(repo, &task.id.0).await {
755 Ok(Some(agent)) => {
756 if !agent.is_empty() && self.config.agents.iter().any(|cfg| cfg == &agent) {
758 Some(agent)
759 } else {
760 None
761 }
762 }
763 Ok(None) => None,
764 Err(e) => {
765 tracing::warn!(
766 repo,
767 task_id = %task.id.0,
768 err = %e,
769 "failed to fetch stored agent, falling back to label/LLM routing"
770 );
771 None
772 }
773 };
774
775 if store_agent.is_none()
777 && let Some(result) = self.route_profile(task)?
778 {
779 self.log_route_activity(store, repo, &task.id.0, &result, None)
780 .await;
781 return Ok(result);
782 }
783
784 let resolved_agent = store_agent.or_else(|| {
786 strategies::extract_agent_from_labels(&self.config.agents, &task.labels)
787 });
788
789 if let Some(agent) = resolved_agent {
790 let complexity = strategies::extract_complexity_from_labels(&task.labels);
791 if self.agent_is_routable(&agent, &complexity) {
800 let (model, tier_warning) =
801 RouteResult::resolve_model(&self.config, &agent, &complexity, &task.id.0);
802
803 if model.is_some() {
811 tracing::debug!(
812 task_id = %task.id.0,
813 agent = %agent,
814 complexity = %complexity,
815 "routed via label"
816 );
817 let mut result = RouteResult::from_config(
818 agent.clone(),
819 complexity.clone(),
820 format!("label agent:{agent}"),
821 &self.config,
822 &task.id.0,
823 );
824 result.profile.role = format!("{agent} specialist");
827 result.model = model.clone();
828 result.warning = tier_warning;
829 self.log_route_activity(store, repo, &task.id.0, &result, None)
830 .await;
831 return Ok(result);
832 }
833 tracing::warn!(task_id = %task.id.0, agent = %agent, "label agent has no available model — falling through to LLM routing");
838 }
839
840 let candidates = self.available_agents_for_complexity(&complexity);
841 if candidates.is_empty() {
842 self.wait_for_cooldown(Some(&complexity))?;
843 continue;
844 }
845 }
847
848 let complexity = strategies::extract_complexity_from_labels(&task.labels);
849
850 let mut candidates = self.available_agents_for_complexity(&complexity);
852 if candidates.is_empty() {
853 self.wait_for_cooldown(Some(&complexity))?;
854 continue;
855 }
856
857 if let Some(filtered) = self
862 .skip_no_code_agent(store, repo, &task.id.0, &candidates)
863 .await
864 {
865 candidates = filtered;
866 }
867
868 if self.config.weighted_round_robin {
870 let result = strategies::route_via_weighted_round_robin(
871 &candidates,
872 &self.weights,
873 &self.config,
874 task,
875 &mut self.last_agent,
876 )?;
877 self.log_route_activity(store, repo, &task.id.0, &result, None)
878 .await;
879 return Ok(result);
880 }
881
882 if self.config.mode == "round_robin" || self.config.mode == "profile" {
884 tracing::debug!(task_id = %task.id.0, "routing via round-robin mode");
885 let result = strategies::route_via_round_robin_stateful(
886 &candidates,
887 &self.config,
888 task,
889 &mut self.rr_index,
890 &mut self.last_agent,
891 )?;
892 self.log_route_activity(store, repo, &task.id.0, &result, None)
893 .await;
894 return Ok(result);
895 }
896
897 if self.config.mode == "local" {
899 tracing::debug!(task_id = %task.id.0, ollama_url = %self.config.ollama_url, "routing via local Ollama");
900 let ollama_router = self
901 .ollama_router
902 .as_ref()
903 .expect("ollama_router must be initialized in Router::new when mode=local");
904 match ollama_router.route(task, &self.config).await {
905 Ok(result) => {
906 self.log_route_activity(store, repo, &task.id.0, &result, None)
907 .await;
908 return Ok(result);
909 }
910 Err(e) => {
911 tracing::warn!(
912 task_id = %task.id.0,
913 error = %e,
914 "Ollama routing failed, falling back to round-robin"
915 );
916 let result = strategies::route_via_round_robin_stateful(
917 &candidates,
918 &self.config,
919 task,
920 &mut self.rr_index,
921 &mut self.last_agent,
922 )?;
923 self.log_route_activity(store, repo, &task.id.0, &result, None)
924 .await;
925 return Ok(result);
926 }
927 }
928 }
929
930 let route_attempts = self.get_route_attempts(&task.id.0, store, repo).await;
932
933 if route_attempts >= self.config.max_route_attempts {
934 tracing::warn!(
935 task_id = %task.id.0,
936 attempts = route_attempts,
937 max = self.config.max_route_attempts,
938 "max LLM route attempts reached, falling back to round-robin"
939 );
940 let candidates = self.available_agents_for_complexity(&complexity);
941 if candidates.is_empty() {
942 self.wait_for_cooldown(Some(&complexity))?;
943 continue;
944 }
945 let result = strategies::route_via_round_robin_stateful(
946 &candidates,
947 &self.config,
948 task,
949 &mut self.rr_index,
950 &mut self.last_agent,
951 )?;
952 self.log_route_activity(store, repo, &task.id.0, &result, None)
953 .await;
954 return Ok(result);
955 }
956
957 tracing::debug!(task_id = %task.id.0, "starting LLM routing");
959
960 match self.route_with_llm(task, repo).await {
961 Ok(result) => {
962 let candidates = self.available_agents_for_complexity(&result.complexity);
963 if candidates.is_empty() {
964 self.wait_for_cooldown(Some(&result.complexity))?;
965 continue;
966 }
967
968 let no_code_agent =
971 get_task_field_direct(store, repo, &task.id.0, "no_code_last_agent")
972 .await
973 .unwrap_or_else(|| {
974 tracing::warn!(task_id = %task.id.0, "no_code_last_agent DB read returned None — loop detection may be impaired");
975 String::new()
976 });
977 if result.agent == no_code_agent {
978 let fallback_agent = candidates
980 .iter()
981 .find(|a| a.as_str() != no_code_agent)
982 .cloned()
983 .unwrap_or_else(|| candidates[0].clone());
984 if fallback_agent.as_str() == no_code_agent {
985 tracing::warn!(
986 task_id = %task.id.0,
987 no_code_agent = %no_code_agent,
988 complexity = %result.complexity,
989 "all available agents are the no-code agent — waiting for another agent"
990 );
991 self.wait_for_cooldown(Some(&result.complexity))?;
992 continue;
993 }
994 tracing::info!(
995 task_id = %task.id.0,
996 llm_selected = %result.agent,
997 skipped = %no_code_agent,
998 fallback = %fallback_agent,
999 "LLM selected the no-code agent — routing to alternative"
1000 );
1001 let (fallback_model, _) = RouteResult::resolve_model(
1002 &self.config,
1003 &fallback_agent,
1004 &result.complexity,
1005 &task.id.0,
1006 );
1007
1008 self.set_route_attempts(&task.id.0, 0, store, repo).await;
1009 let result = RouteResult {
1010 agent: fallback_agent.clone(),
1011 model: fallback_model,
1012 complexity: result.complexity.clone(),
1013 estimate: result.estimate,
1014 reason: format!(
1015 "LLM selected no-code agent {}; routed to {}",
1016 result.agent, fallback_agent
1017 ),
1018 profile: result.profile.clone(),
1019 warning: Some(format!(
1020 "LLM selected no-code agent {}; used fallback {}",
1021 result.agent, fallback_agent
1022 )),
1023 };
1024 self.log_route_activity(store, repo, &task.id.0, &result, None)
1025 .await;
1026 return Ok(result);
1027 }
1028
1029 let model_cooled = result
1030 .model
1031 .as_deref()
1032 .is_some_and(|model| is_model_in_cooldown(&result.agent, model));
1033 if !candidates.contains(&result.agent) || model_cooled {
1034 let fallback_agent = candidates
1035 .iter()
1036 .find(|agent| *agent != &result.agent)
1037 .cloned()
1038 .unwrap_or_else(|| candidates[0].clone());
1039 let (fallback_model, _) = RouteResult::resolve_model(
1040 &self.config,
1041 &fallback_agent,
1042 &result.complexity,
1043 &task.id.0,
1044 );
1045
1046 if fallback_model.is_none() && fallback_agent == result.agent {
1052 tracing::warn!(
1053 task_id = %task.id.0,
1054 agent = %result.agent,
1055 complexity = %result.complexity,
1056 "LLM-selected model(s) are cooled for the only available agent; waiting for cooldown"
1057 );
1058 self.wait_for_cooldown(Some(&result.complexity))?;
1059 continue;
1060 }
1061
1062 if fallback_agent == result.agent {
1066 tracing::warn!(
1067 task_id = %task.id.0,
1068 agent = %result.agent,
1069 complexity = %result.complexity,
1070 "LLM-selected model was cooled; selecting an alternative model for the same agent"
1071 );
1072 } else {
1073 tracing::warn!(
1074 task_id = %task.id.0,
1075 agent = %result.agent,
1076 fallback = %fallback_agent,
1077 complexity = %result.complexity,
1078 "LLM selected cooled agent/model; rerouting to available agent"
1079 );
1080 }
1081
1082 self.set_route_attempts(&task.id.0, 0, store, repo).await;
1084
1085 let reason = if fallback_agent == result.agent {
1086 format!(
1087 "LLM selected cooled model; using same agent {fallback_agent} with different model"
1088 )
1089 } else {
1090 format!("LLM selected cooled agent/model; rerouted to {fallback_agent}")
1091 };
1092
1093 let result = RouteResult {
1094 agent: fallback_agent.clone(),
1095 model: fallback_model,
1096 complexity: result.complexity.clone(),
1097 estimate: result.estimate,
1098 reason: reason.clone(),
1099 profile: result.profile.clone(),
1100 warning: Some(if fallback_agent == result.agent {
1101 "LLM-selected model was cooled; selected alternative model for same agent"
1102 .to_string()
1103 } else {
1104 "LLM-selected agent/model was cooled; rerouted to available agent"
1105 .to_string()
1106 }),
1107 };
1108 self.log_route_activity(store, repo, &task.id.0, &result, None)
1109 .await;
1110 return Ok(result);
1111 }
1112
1113 self.set_route_attempts(&task.id.0, 0, store, repo).await;
1115 tracing::info!(
1116 task_id = %task.id.0,
1117 agent = %result.agent,
1118 complexity = %result.complexity,
1119 "routed via LLM"
1120 );
1121 self.log_route_activity(store, repo, &task.id.0, &result, None)
1122 .await;
1123 return Ok(result);
1124 }
1125 Err(e) => {
1126 if let Some(err) = e.downcast_ref::<AllAgentsCooledError>() {
1127 let scope = err.scope();
1128 tracing::warn!(scope = %scope, "router cooldown gate tripped");
1129 let scope_opt = match scope {
1133 "all agents" | "router pool" => None,
1134 _ => Some(scope),
1135 };
1136 self.wait_for_cooldown(scope_opt)?;
1137 continue;
1138 }
1139
1140 let new_attempts = route_attempts + 1;
1141 self.set_route_attempts(&task.id.0, new_attempts, store, repo)
1142 .await;
1143 tracing::warn!(
1144 task_id = %task.id.0,
1145 error = %e,
1146 error_chain = ?e,
1147 attempt = new_attempts,
1148 max = self.config.max_route_attempts,
1149 "LLM routing failed"
1150 );
1151
1152 if new_attempts >= self.config.max_route_attempts {
1153 tracing::info!(
1154 task_id = %task.id.0,
1155 "falling back to round-robin after {} failed attempts",
1156 new_attempts
1157 );
1158 let candidates = self.available_agents_for_complexity(&complexity);
1159 if candidates.is_empty() {
1160 self.wait_for_cooldown(Some(&complexity))?;
1161 continue;
1162 }
1163 let result = strategies::route_via_round_robin_stateful(
1164 &candidates,
1165 &self.config,
1166 task,
1167 &mut self.rr_index,
1168 &mut self.last_agent,
1169 )?;
1170 self.log_route_activity(store, repo, &task.id.0, &result, None)
1171 .await;
1172 return Ok(result);
1173 }
1174
1175 let candidates = self.available_agents_for_complexity(&complexity);
1176 if candidates.is_empty() {
1177 self.wait_for_cooldown(Some(&complexity))?;
1178 continue;
1179 }
1180 let result = strategies::route_via_fallback(
1181 &candidates,
1182 &self.config,
1183 task,
1184 Some(&self.weights),
1185 )?;
1186 self.log_route_activity(store, repo, &task.id.0, &result, None)
1187 .await;
1188 return Ok(result);
1189 }
1190 }
1191 }
1192 }
1193
1194 async fn get_route_attempts(&self, task_id: &str, store: &Arc<TaskStore>, repo: &str) -> u32 {
1196 match store.resolve_task_id(repo, task_id).await {
1197 Ok(Some(store_id)) => store
1198 .get(store_id)
1199 .await
1200 .map_or(0, |t| u32::try_from(t.route_attempts).unwrap_or(0)),
1201 _ => 0,
1202 }
1203 }
1204
1205 async fn set_route_attempts(
1207 &self,
1208 task_id: &str,
1209 attempts: u32,
1210 store: &Arc<TaskStore>,
1211 repo: &str,
1212 ) {
1213 if let Ok(Some(store_id)) = store.resolve_task_id(repo, task_id).await
1214 && let Err(e) = store
1215 .set_fields(store_id, &[("route_attempts", serde_json::json!(attempts))])
1216 .await
1217 {
1218 tracing::warn!(task_id, error = %e, "failed to store route_attempts");
1219 }
1220 }
1221
1222 async fn log_route_activity(
1224 &self,
1225 store: &Arc<TaskStore>,
1226 repo: &str,
1227 task_id: &str,
1228 result: &RouteResult,
1229 from_agent: Option<&str>,
1230 ) {
1231 let details = serde_json::json!({
1232 "reason": result.reason,
1233 "complexity": result.complexity,
1234 "role": result.profile.role,
1235 "warning": result.warning,
1236 });
1237 let event_type = if from_agent.is_some() {
1238 "rerouted"
1239 } else {
1240 "routed"
1241 };
1242 store_log_activity(
1243 &Some(Arc::clone(store)),
1244 repo,
1245 task_id,
1246 event_type,
1247 None,
1248 Some("routed"),
1249 Some(&result.agent),
1250 result.model.as_deref(),
1251 Some(&details),
1252 )
1253 .await;
1254 }
1255
1256 async fn route_with_llm(
1262 &mut self,
1263 task: &ExternalTask,
1264 repo: &str,
1265 ) -> anyhow::Result<RouteResult> {
1266 let uncooled_agents: Vec<String> = self
1276 .available_agents
1277 .iter()
1278 .filter(|a| {
1279 !is_agent_in_cooldown(a)
1280 && !is_agent_degraded(a)
1281 && self.agent_has_available_model_for_coding_tiers(a)
1282 })
1283 .cloned()
1284 .collect();
1285 if uncooled_agents.is_empty() {
1286 return Err(AllAgentsCooledError::new("all agents".to_string(), None).into());
1287 }
1288 let llm_agents = uncooled_agents;
1289
1290 let pool = self.router_pool.clone();
1291 let n = pool.len();
1292 let start = self.pool_index;
1293 let mut last_err: Option<anyhow::Error> = None;
1294 let mut attempted_any = false;
1295
1296 for i in 0..n {
1298 let idx = (start + i) % n;
1299 let (agent, model) = &pool[idx];
1300 let model_str = model.as_str();
1301
1302 if response::is_model_in_cooldown(agent, model_str) {
1303 tracing::debug!(agent, model = model_str, "pool entry on cooldown, skipping");
1304 continue;
1305 }
1306
1307 attempted_any = true;
1309
1310 let model_opt = if model_str.is_empty() {
1311 None
1312 } else {
1313 Some(model_str)
1314 };
1315
1316 match self
1317 .llm_router
1318 .route_with_llm_using(
1319 task,
1320 &llm_agents,
1321 &self.config,
1322 &mut self.last_agent,
1323 repo,
1324 agent,
1325 model_opt,
1326 )
1327 .await
1328 {
1329 Ok(result) => {
1330 self.advance_pool_index_after_attempt(idx, n);
1332 tracing::debug!(
1333 agent,
1334 model = model_str,
1335 pool_idx = idx,
1336 "router LLM pool entry succeeded"
1337 );
1338 record_agent_success(agent, model_str).await;
1339 return Ok(result);
1340 }
1341 Err(e) => {
1342 let err_msg = e.to_string();
1343 let is_timeout = err_msg.contains(TIMEOUT_PREFIX);
1344 if is_timeout {
1345 self.advance_pool_index_after_attempt(idx, n);
1355 tracing::warn!(
1356 agent,
1357 model = model_str,
1358 next_pool_idx = self.pool_index,
1359 "router LLM pool entry timed out — recording cooldown, will retry next tick"
1360 );
1361 response::record_model_failure(agent, model_str).await;
1362 return Err(e);
1363 }
1364 if is_max_turns_error(&err_msg) {
1365 tracing::warn!(
1366 agent,
1367 model = model_str,
1368 error = %e,
1369 "pool entry hit max turns — trying next without cooldown"
1370 );
1371 } else {
1372 tracing::warn!(
1373 agent,
1374 model = model_str,
1375 error = %e,
1376 "pool entry failed, recording cooldown and trying next"
1377 );
1378 if !cooldown::record_credit_exhaustion_from_message(
1379 agent,
1380 Some(model_str),
1381 &err_msg,
1382 )
1383 .await
1384 {
1385 response::record_model_failure(agent, model_str).await;
1386 }
1387 }
1388 last_err = Some(e);
1389 self.advance_pool_index_after_attempt(idx, n);
1390 }
1391 }
1392 }
1393
1394 if !attempted_any {
1399 let now = chrono::Utc::now().timestamp();
1400 let earliest = self.earliest_pool_cooldown();
1401 if let Some(until) = earliest {
1402 let remaining = until.saturating_sub(now);
1404 tracing::warn!(
1405 remaining_secs = remaining,
1406 pool = ?pool,
1407 "all router LLM pool entries on cooldown — will try fallback"
1408 );
1409 } else {
1411 return Err(last_err
1414 .unwrap_or_else(|| anyhow::anyhow!("all router LLM pool entries exhausted")));
1415 }
1416 }
1417
1418 let fallback = self.config.effective_fallback();
1420 let (fb_agent, fb_model) = parse_pool_entry(&fallback);
1421 let fb_model_str = fb_model.as_str();
1422
1423 let fallback_already_tried = pool.iter().any(|(a, m)| a == &fb_agent && m == &fb_model);
1425
1426 if !fallback_already_tried && !response::is_model_in_cooldown(&fb_agent, fb_model_str) {
1427 tracing::info!(
1428 agent = %fb_agent,
1429 model = %fb_model_str,
1430 "all pool entries exhausted — trying fallback router LLM"
1431 );
1432 let fb_model_opt = if fb_model_str.is_empty() {
1433 None
1434 } else {
1435 Some(fb_model_str)
1436 };
1437 match self
1438 .llm_router
1439 .route_with_llm_using(
1440 task,
1441 &llm_agents,
1442 &self.config,
1443 &mut self.last_agent,
1444 repo,
1445 &fb_agent,
1446 fb_model_opt,
1447 )
1448 .await
1449 {
1450 Ok(result) => {
1451 record_agent_success(&fb_agent, fb_model_str).await;
1452 return Ok(result);
1453 }
1454 Err(e) => {
1455 let err_msg = e.to_string();
1456 let is_timeout = err_msg.contains(TIMEOUT_PREFIX);
1457 if is_timeout {
1458 response::record_model_failure(&fb_agent, fb_model_str).await;
1461 tracing::warn!(
1462 agent = %fb_agent,
1463 model = %fb_model_str,
1464 "fallback router LLM timed out — returning immediately to unblock tick loop"
1465 );
1466 return Err(e);
1467 }
1468 tracing::warn!(
1469 agent = %fb_agent,
1470 model = %fb_model_str,
1471 error = %e,
1472 "fallback router LLM also failed"
1473 );
1474 if !is_max_turns_error(&err_msg) {
1475 response::record_model_failure(&fb_agent, fb_model_str).await;
1476 }
1477 last_err = Some(e);
1478 }
1479 }
1480 }
1481
1482 Err(last_err.unwrap_or_else(|| anyhow::anyhow!("all router LLM pool entries exhausted")))
1483 }
1484
1485 pub fn record_rate_limit(&mut self, agent: &str) {
1489 self.weights.record_rate_limit(agent);
1490 }
1491
1492 pub fn record_success(&mut self, agent: &str) {
1494 self.weights.record_success(agent);
1495 }
1496
1497 pub fn tick_weight_recovery(&mut self) {
1502 self.weights.tick_recovery();
1503 }
1504
1505 pub async fn store_route_result(
1507 &self,
1508 task_id: &str,
1509 result: &RouteResult,
1510 store: &Arc<TaskStore>,
1511 repo: &str,
1512 ) -> anyhow::Result<()> {
1513 if let Ok(Some(store_id)) = store.resolve_task_id(repo, task_id).await {
1514 store
1515 .set_fields(
1516 store_id,
1517 &[
1518 ("agent", serde_json::json!(result.agent)),
1519 ("complexity", serde_json::json!(result.complexity)),
1520 ("route_reason", serde_json::json!(result.reason)),
1521 (
1522 "agent_profile",
1523 serde_json::json!(serde_json::to_string(&result.profile)?),
1524 ),
1525 (
1526 "model",
1527 serde_json::json!(result.model.as_deref().unwrap_or("")),
1528 ),
1529 ],
1530 )
1531 .await?;
1532 }
1533 Ok(())
1534 }
1535}
1536
1537pub async fn get_route_result(
1539 store: &Arc<TaskStore>,
1540 repo: &str,
1541 task_id: &str,
1542) -> Result<RouteResult, RouteResultError> {
1543 let store_id = store
1544 .resolve_task_id(repo, task_id)
1545 .await
1546 .map_err(RouteResultError::Other)?
1547 .ok_or_else(|| {
1548 RouteResultError::Other(anyhow::anyhow!("task {task_id} not found in store"))
1549 })?;
1550 let task = store.get(store_id).await.map_err(RouteResultError::Other)?;
1551
1552 let agent = task
1553 .agent
1554 .clone()
1555 .filter(|a| !a.is_empty())
1556 .ok_or_else(|| RouteResultError::NoAgent {
1557 task_id: task_id.to_string(),
1558 })?;
1559
1560 let complexity = if task.complexity.is_empty() {
1561 "medium".to_string()
1562 } else {
1563 task.complexity.clone()
1564 };
1565
1566 let reason = task.route_reason.clone();
1567 let model = task.model.clone().filter(|m| !m.is_empty());
1568 let profile = AgentProfile {
1572 execution: serde_json::from_str::<AgentProfile>(&task.agent_profile)
1573 .ok()
1574 .and_then(|stored| stored.execution)
1575 .filter(|p| p.matches_route(&agent, model.as_deref())),
1576 ..AgentProfile::default()
1577 };
1578
1579 let config = RouterConfig::from_config();
1583 let model = model.filter(|m| {
1584 let complexities = ["simple", "medium", "complex", "review"];
1585 let all_pools: Vec<Vec<String>> = complexities
1587 .iter()
1588 .filter_map(|comp| config.model_pool_for_complexity(&agent, comp))
1589 .collect();
1590 if all_pools.is_empty() {
1592 return true;
1593 }
1594 let valid = all_pools.iter().any(|pool| pool.contains(m))
1595 || profile
1596 .execution
1597 .as_ref()
1598 .is_some_and(|p| p.matches_route(&agent, Some(m)));
1599 if !valid {
1600 tracing::warn!(
1601 task_id,
1602 agent,
1603 model = %m,
1604 "discarding stale model: not in agent's model pools"
1605 );
1606 }
1607 valid
1608 });
1609
1610 let original_model = task.model.clone().filter(|m| !m.is_empty());
1613 let mut model = model;
1614 if original_model.is_some() && model.is_none() {
1615 model = config.model_for_complexity(&agent, &complexity, task_id);
1616 let stale_model = original_model.as_deref().unwrap_or("unknown");
1617 let stale_err = format!(
1618 "stale model discarded: {stale_model} not in {agent} model pools, using {}",
1619 model.as_deref().unwrap_or("the agent default")
1620 );
1621 if let Err(e) = store
1622 .set_fields(
1623 store_id,
1624 &[
1625 (
1626 "model",
1627 serde_json::json!(model.clone().unwrap_or_default()),
1628 ),
1629 ("last_error", serde_json::json!(stale_err)),
1630 ],
1631 )
1632 .await
1633 {
1634 tracing::warn!(task_id = %task_id, error = %e, "failed to clear stale model from store — will retry on next dispatch");
1636 }
1637 }
1638
1639 Ok(RouteResult {
1640 agent,
1641 model,
1642 complexity,
1643 estimate: 0,
1644 reason,
1645 profile,
1646 warning: None,
1647 })
1648}
1649
1650#[cfg(test)]
1651#[expect(
1652 clippy::float_cmp,
1653 reason = "the weights are stored constants, so they compare exactly"
1654)]
1655mod tests;