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