Skip to main content

switchyard_runner/
algorithm.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Schema-neutral algorithm configuration and construction.
5
6use std::collections::{BTreeMap, BTreeSet, HashMap};
7use std::error::Error;
8use std::fmt::{Display, Formatter};
9use std::path::PathBuf;
10use std::sync::Arc;
11
12use libsy::{
13    AdvisorGate, AdvisorGateConfig, Algorithm, BreakerConfig, CapabilityJudgeConfig,
14    ClassifierContractConfig, ClassifierResponseFormat, ClassifyTrigger, CompositeJudgeConfig,
15    CompositeRouter, CustomClassifierConfig, CustomClassifierPolicy, DEFAULT_UNMATCHED_STEPS,
16    DecisionChoice, DecisionJudgeConfig, DirectClassifierConfig, EscalationJudgeConfig,
17    GateTrigger, HandoffNoteConfig, LlmCapabilityConfig, LlmClassifierConfig, LlmFallback,
18    LlmTaskClassifier, Noop, Passthrough, PickerMode, Random, RuntimeModels, StageRouter,
19    StageRouterConfig, SubagentRouter, SubagentRouterConfig, TaskClassifierConfig, ToolSemantics,
20    Vgr, VgrConfig,
21};
22use serde::Deserialize;
23use strum_macros::IntoStaticStr;
24use switchyard_protocol::{Category, ModelId};
25
26/// Error returned when an algorithm description cannot be constructed.
27#[derive(Debug)]
28pub struct AlgorithmConfigError {
29    message: String,
30    source: Option<Box<dyn Error + Send + Sync>>,
31}
32
33impl AlgorithmConfigError {
34    fn new(message: impl Into<String>) -> Self {
35        Self {
36            message: message.into(),
37            source: None,
38        }
39    }
40
41    fn with_source(message: impl Into<String>, source: impl Error + Send + Sync + 'static) -> Self {
42        Self {
43            message: message.into(),
44            source: Some(Box::new(source)),
45        }
46    }
47}
48
49impl Display for AlgorithmConfigError {
50    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
51        formatter.write_str(&self.message)
52    }
53}
54
55impl Error for AlgorithmConfigError {
56    fn source(&self) -> Option<&(dyn Error + 'static)> {
57        self.source.as_deref().map(|source| source as _)
58    }
59}
60
61type AlgorithmResult<T> = Result<T, AlgorithmConfigError>;
62
63/// How a custom classifier turns the judge's JSON verdict into a target.
64#[derive(Clone, Debug, Deserialize)]
65#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
66pub enum ClassifierPolicyConfig {
67    /// Reads the target name straight out of the judge's verdict.
68    TargetSelector {
69        /// JSON Pointer to the name, such as `/decision/target`.
70        selector: String,
71    },
72}
73
74/// Which of the four `llm_classifier` behaviors a route uses.
75#[derive(Clone, Copy, Debug, Deserialize)]
76#[serde(rename_all = "snake_case")]
77pub enum ClassifierMode {
78    /// Judges the request first, then serves the strong or weak target.
79    Capability,
80    /// Serves the weak target first and judges the finished turn, moving to the
81    /// strong target once the session latches.
82    Escalation,
83    /// Judges against your own JSON schema and routes to any configured target.
84    Custom,
85    /// Asks a decision target to select one configured model group.
86    Direct,
87}
88
89impl ClassifierPolicyConfig {
90    fn into_libsy(self) -> CustomClassifierPolicy {
91        match self {
92            Self::TargetSelector { selector } => CustomClassifierPolicy::target_selector(selector),
93        }
94    }
95}
96
97#[derive(Clone, Debug)]
98enum LlmClassifierModeConfig {
99    Capability(CapabilityClassifierRouteConfig),
100    Escalation(EscalationClassifierRouteConfig),
101    Custom(CustomClassifierRouteConfig),
102    Direct {
103        models: CategoryModelConfig,
104        default_target: Category,
105        config: DirectClassifierConfig,
106    },
107}
108
109#[derive(Clone, Debug)]
110struct CapabilityClassifierRouteConfig {
111    classifier_target: String,
112    fail_open: bool,
113    strong_target: String,
114    weak_target: String,
115    judge: CapabilityJudgeRouteConfig,
116    classify_trigger: ClassifyTrigger,
117    message_hash_fallback: bool,
118    recent_turn_window: Option<usize>,
119    judge_max_images: Option<usize>,
120}
121
122impl CapabilityClassifierRouteConfig {
123    fn into_task_config(self) -> TaskClassifierConfig {
124        let judge = match self.judge {
125            CapabilityJudgeRouteConfig::Llm(judge) => CapabilityJudgeConfig::Llm(judge),
126            CapabilityJudgeRouteConfig::Decision(judge) => {
127                let defaults = DecisionJudgeConfig::default();
128                CapabilityJudgeConfig::Decision(DecisionJudgeConfig {
129                    cutoff: judge.cutoff,
130                    instructions: judge.instructions,
131                    choices: judge.choices.unwrap_or(defaults.choices),
132                    apply_cutoff_to: judge.apply_cutoff_to.unwrap_or(defaults.apply_cutoff_to),
133                })
134            }
135        };
136        TaskClassifierConfig {
137            judge,
138            fail_open: self.fail_open,
139            classify_trigger: self.classify_trigger,
140            message_hash_fallback: self.message_hash_fallback,
141            recent_turn_window: self.recent_turn_window,
142            judge_max_images: self.judge_max_images,
143        }
144    }
145}
146
147#[derive(Clone, Debug)]
148enum CapabilityJudgeRouteConfig {
149    Llm(LlmCapabilityConfig),
150    Decision(DecisionJudgeRouteConfig),
151}
152
153#[derive(Clone, Debug)]
154struct EscalationClassifierRouteConfig {
155    classifier_target: String,
156    strong_target: String,
157    weak_target: String,
158    prompt: Option<String>,
159    response_format_type: ClassifierResponseFormat,
160    max_output_tokens: u64,
161    judge_deadline_ms: Option<u64>,
162    judge: EscalationJudgeConfig,
163}
164
165#[derive(Clone, Debug)]
166struct CustomClassifierRouteConfig {
167    models: CategoryModelConfig,
168    default_target: Category,
169    prompt: String,
170    response_schema: String,
171    policy: ClassifierPolicyConfig,
172    classify_trigger: ClassifyTrigger,
173    message_hash_fallback: bool,
174    recent_turn_window: Option<usize>,
175    judge_max_images: Option<usize>,
176    max_output_tokens: u64,
177    judge_deadline_ms: Option<u64>,
178}
179
180/// Runtime model groups for a custom classifier, keyed by group name.
181///
182/// `any` and `judge` are required; `capable` and `efficient` carry tier meaning
183/// when present. Any other key is a deployment-defined group the policy may
184/// select by name, which is what lets one route choose between more than two
185/// models. Ordered so error messages and derived target lists do not depend on
186/// hash iteration.
187#[derive(Clone, Debug, Default, Deserialize)]
188#[serde(transparent)]
189pub struct CategoryModelConfig(BTreeMap<String, Vec<String>>);
190
191impl CategoryModelConfig {
192    fn restrict_to(&mut self, allowed: &BTreeSet<&str>) {
193        for models in self.0.values_mut() {
194            models.retain(|model| allowed.contains(model.as_str()));
195        }
196    }
197
198    fn validate(&self, route_name: &str, default_target: &Category) -> AlgorithmResult<()> {
199        for category in [Category::Any, Category::Judge] {
200            if self.get(&category).is_empty() {
201                return Err(AlgorithmConfigError::new(format!(
202                    "llm_classifier route {route_name} models.{} must contain at least one target",
203                    category.as_str()
204                )));
205            }
206        }
207        if self.get(default_target).is_empty() {
208            return Err(AlgorithmConfigError::new(format!(
209                "llm_classifier route {route_name} models.{} must contain at least one target because it is the default_target",
210                default_target.as_str()
211            )));
212        }
213        // Every group name parses, so a typo would otherwise build fine and then
214        // abstain on every request. `any` is the fallback pool the router checks
215        // the selected target against, so a group outside it can never be served.
216        let any = self.get(&Category::Any);
217        for (name, models) in &self.0 {
218            if name == Category::Judge.as_str() || name == Category::Any.as_str() {
219                continue;
220            }
221            if let Some(missing) = models.iter().find(|model| !any.contains(model)) {
222                return Err(AlgorithmConfigError::new(format!(
223                    "llm_classifier route {route_name} models.{name} lists target {missing}, which must also appear in models.any"
224                )));
225            }
226        }
227        Ok(())
228    }
229
230    fn get(&self, category: &Category) -> &[String] {
231        self.0.get(category.as_str()).map_or(&[], Vec::as_slice)
232    }
233
234    /// Every configured target name, judge included.
235    fn all_names(&self) -> Vec<&str> {
236        Self::deduped(self.0.values().flatten())
237    }
238
239    /// The completion targets: every group except the judge's own candidates.
240    ///
241    /// `any` leads because it is the deployment's stated fallback order, and
242    /// callers read this order to pick a route's representative target.
243    fn routing_names(&self) -> Vec<&str> {
244        let others = self
245            .0
246            .iter()
247            .filter(|(name, _)| {
248                *name != Category::Judge.as_str() && *name != Category::Any.as_str()
249            })
250            .flat_map(|(_, models)| models);
251        Self::deduped(self.get(&Category::Any).iter().chain(others))
252    }
253
254    fn deduped<'a>(names: impl Iterator<Item = &'a String>) -> Vec<&'a str> {
255        let mut seen = BTreeSet::new();
256        names
257            .map(String::as_str)
258            .filter(|name| seen.insert(*name))
259            .collect()
260    }
261
262    fn groups(&self) -> impl Iterator<Item = (Category, Vec<String>)> + '_ {
263        self.0
264            .iter()
265            .filter_map(|(name, models)| Some((name.parse::<Category>().ok()?, models.clone())))
266    }
267}
268
269/// Routing by a decision model's choice probability.
270#[derive(Clone, Debug, Default, Deserialize)]
271#[serde(deny_unknown_fields)]
272pub struct DecisionJudgeRouteConfig {
273    /// Route capable when the `apply_cutoff_to` probability is strictly above
274    /// this cutoff. Uses the library default when omitted.
275    pub cutoff: Option<f64>,
276    /// Replaces the default decision instructions.
277    pub instructions: Option<String>,
278    /// Replaces the default `capable` and `efficient` choices.
279    pub choices: Option<Vec<DecisionChoice>>,
280    /// Choice ID whose probability is compared with the cutoff. Defaults to `capable`.
281    pub apply_cutoff_to: Option<String>,
282}
283
284/// Settings for an `llm_classifier` route. Which fields are required depends on
285/// the [`ClassifierMode`]; using a field from the wrong mode is an error.
286#[derive(Clone, Debug, Default, Deserialize)]
287#[serde(default, deny_unknown_fields)]
288pub struct LlmClassifierRouteConfig {
289    /// Target the judge is called through. Never a routing destination itself.
290    pub classifier_target: String,
291    /// Mode to run. Defaults to escalation when `escalation` is set, otherwise capability.
292    pub mode: Option<ClassifierMode>,
293    /// Capability and escalation modes: the capable tier.
294    pub strong_target: Option<String>,
295    /// Capability and escalation modes: the efficient tier.
296    pub weak_target: Option<String>,
297    /// Capability mode: lowest solve probability that still routes to the weak
298    /// target, from 0 to 1.
299    pub base_threshold: Option<f64>,
300    /// Capability mode: how much to raise the threshold when the judge is
301    /// uncertain. Added once for an uncertain verdict and twice for unsupported.
302    pub threshold_step: Option<f64>,
303    /// Capability mode: threshold steps for an unmatched verdict (no capability rule
304    /// applies). 1 by default, the same as uncertain; 2 treats it like unsupported.
305    pub unmatched_steps: Option<u8>,
306    /// Capability and direct modes: routes to the capable tier or `default_target` when
307    /// the judge call fails. Defaults to true in these modes.
308    pub fail_open: Option<bool>,
309    /// How often the judge runs: every request, once per user turn, or once per session.
310    pub classify_trigger: ClassifyTrigger,
311    /// Reuses the session's target by hashing the first user message when no
312    /// session ID is available. Needs `classify_trigger = "new_session"`.
313    pub message_hash_fallback: bool,
314    /// How many trailing turns the judge sees. Unset shows it the opening task
315    /// and the latest user follow-up only.
316    pub recent_turn_window: Option<usize>,
317    /// Image cap for the latest user instruction message; zero omits its images from the judge.
318    #[serde(default)]
319    pub judge_max_images: Option<usize>,
320    /// Replaces the packaged judge prompt. Required in custom mode.
321    pub prompt: Option<String>,
322    /// How the judge is asked for structured output. Use `json_object` when the
323    /// provider cannot do JSON Schema.
324    pub response_format_type: ClassifierResponseFormat,
325    /// Most completion tokens the judge verdict may use.
326    #[serde(default = "default_classifier_max_output_tokens")]
327    pub max_output_tokens: u64,
328    /// Whole-consultation bound on the judge call in milliseconds; expiry follows the
329    /// route's `fail_open` setting. Unset leaves the consultation unbounded.
330    #[serde(default)]
331    pub judge_deadline_ms: Option<u64>,
332    /// Escalation mode: how many escalate verdicts latch the session, and how
333    /// much of the transcript the judge sees.
334    pub escalation: Option<EscalationJudgeConfig>,
335    /// Capability mode: use a decision target as the judge, with a capable-or-efficient choice.
336    pub decision: Option<DecisionJudgeRouteConfig>,
337    /// Custom and direct modes: runtime model groups. In direct mode, every non-empty
338    /// group except `judge` and `any` is an option the decision target may select.
339    pub models: Option<CategoryModelConfig>,
340    /// Custom and direct modes: category used when the judge fails or its verdict
341    /// cannot be routed.
342    pub default_target: Option<String>,
343    /// Custom mode: JSON Schema the verdict must match, written as a string.
344    pub response_schema: Option<String>,
345    /// Custom mode: how to read the chosen target out of the verdict.
346    pub policy: Option<ClassifierPolicyConfig>,
347}
348
349/// Routing policy applied only to delegated sub-agent work, nested inside a
350/// `passthrough` or `stage_router` route.
351#[derive(Clone, Debug, Deserialize)]
352#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
353pub enum SubagentRouteConfig {
354    /// Sends all sub-agent work to one target.
355    Passthrough {
356        /// Target that serves sub-agent requests.
357        target: String,
358    },
359    /// Judges each sub-agent request. Only [`ClassifierMode::Custom`] is supported here.
360    LlmClassifier(Box<LlmClassifierRouteConfig>),
361}
362
363impl SubagentRouteConfig {
364    fn routing_target_names(&self) -> Vec<&str> {
365        match self {
366            Self::Passthrough { target } => vec![target],
367            Self::LlmClassifier(classifier) => classifier
368                .models
369                .as_ref()
370                .map(CategoryModelConfig::routing_names)
371                .unwrap_or_default(),
372        }
373    }
374
375    fn judge_target_names(&self) -> Vec<&str> {
376        match self {
377            Self::Passthrough { .. } => Vec::new(),
378            Self::LlmClassifier(classifier) => classifier
379                .models
380                .as_ref()
381                .map(|models| models.get(&Category::Judge))
382                .unwrap_or_default()
383                .iter()
384                .map(String::as_str)
385                .collect(),
386        }
387    }
388}
389
390/// A routing algorithm described by configured target names. Converting it to `&str` gives
391/// the route's `type`, such as `stage_router`.
392#[derive(Clone, Debug, Deserialize, IntoStaticStr)]
393#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
394#[strum(serialize_all = "snake_case")]
395pub enum AlgorithmSpec {
396    /// Replies `OK` without calling any model. Useful for smoke tests.
397    Noop {},
398    /// Splits traffic across several targets.
399    Random {
400        /// Target names to choose from.
401        targets: Vec<String>,
402        /// Relative weights in `targets` order. Equal weights when unset.
403        weights: Option<Vec<f64>>,
404        /// Makes the sequence of choices repeatable.
405        seed: Option<u64>,
406    },
407    /// Sends every request to one target.
408    Passthrough {
409        /// Target that serves the request.
410        target: String,
411        /// Separate policy for delegated sub-agent work.
412        #[serde(default)]
413        subagents: Option<SubagentRouteConfig>,
414    },
415    /// Asks a judge model which target should serve the request.
416    LlmClassifier {
417        /// Judge and tier settings, written directly in the route table.
418        #[serde(flatten)]
419        config: LlmClassifierRouteConfig,
420    },
421    /// Picks a tier per turn by scoring signals from recent tool results.
422    StageRouter {
423        capable_target: String,
424        efficient_target: String,
425        #[serde(default)]
426        capable_first_threshold: f64,
427        #[serde(flatten)]
428        settings: StageSettingsConfig,
429        /// Tier to use when the signals are not confident.
430        picker: PickerMode,
431        /// Judge consulted for turns the tool signals cannot decide.
432        #[serde(default)]
433        classifier: Option<StageClassifierConfig>,
434        /// Separate policy for delegated sub-agent work.
435        #[serde(default)]
436        subagents: Option<SubagentRouteConfig>,
437    },
438    /// Picks a routing strategy automatically, preset with recommended knobs.
439    /// Currently a `stage_router` with `picker = "efficient_first"` and
440    /// `confidence_threshold = 0.5`; change `build_algorithm`'s `Auto` arm to
441    /// repoint it at a different algorithm or preset.
442    Auto {
443        /// The capable tier.
444        capable_target: String,
445        /// The efficient tier.
446        efficient_target: String,
447    },
448    /// A judge picks the tier at each user turn; a stage router runs the turns within it.
449    Composite {
450        /// Judge that picks the tier. Called through its own target.
451        classifier: StageClassifierConfig,
452        /// The stage router the judge hands off to.
453        stage: StageTierConfig,
454        /// Settings for the profile selected by an efficient verdict.
455        #[serde(default)]
456        efficient: Option<Box<StageProfileConfig>>,
457        /// Settings for the profile selected by a capable verdict.
458        #[serde(default)]
459        capable: Option<Box<StageProfileConfig>>,
460        /// Separate policy for delegated sub-agent work.
461        #[serde(default)]
462        subagents: Option<SubagentRouteConfig>,
463    },
464    /// Serves every turn from one target, and has a second model review some of
465    /// those turns before the caller sees them.
466    Advisor {
467        /// Serves every client-visible turn.
468        executor_target: String,
469        /// Reviews gated turns. Never a routing destination.
470        advisor_target: String,
471        /// Replaces the built-in APPROVE/REDO reviewer prompt.
472        #[serde(default)]
473        reviewer_system_prompt: Option<String>,
474        /// Replaces the built-in text put in front of a REDO plan.
475        #[serde(default)]
476        redo_feedback_prefix: Option<String>,
477        /// What fires a review.
478        #[serde(default)]
479        gate_trigger: AdvisorTriggerConfig,
480        /// Regular expression for the `pattern` trigger. Required by it, and unused otherwise.
481        #[serde(default)]
482        gate_trigger_pattern: Option<String>,
483        /// How many reviews one session may spend.
484        #[serde(default = "default_max_reviews")]
485        max_reviews: u32,
486        /// Reviews a turn after this many assistant turns, as a mid-task
487        /// checkpoint. Zero turns the checkpoint off.
488        #[serde(default)]
489        gate_stall_turns: u32,
490        /// Tool results a turn needs before it can be reviewed. Skips early chatty turns.
491        #[serde(default)]
492        gate_min_tool_results: u32,
493        /// Most output tokens one review may use.
494        #[serde(default = "default_advisor_max_tokens")]
495        advisor_max_tokens: u64,
496        /// Sampling temperature for reviews. Left off the request when unset.
497        #[serde(default)]
498        advisor_temperature: Option<f64>,
499        /// Size cap on the transcript sent to the advisor. Longer transcripts
500        /// are trimmed from the middle.
501        #[serde(default = "default_transcript_max_chars")]
502        transcript_max_chars: usize,
503        /// Lets the turn through when the advisor fails, instead of erroring.
504        #[serde(default = "default_fail_open")]
505        fail_open: bool,
506    },
507    Vgr {
508        #[serde(flatten)]
509        config: VgrRouteConfig,
510    },
511    /// Routes using a checkpoint-backed prefill classifier.
512    PrefillRouter {
513        /// Target names in checkpoint output order.
514        targets: Vec<String>,
515        /// Tensor-only router checkpoint path.
516        checkpoint: PathBuf,
517        /// PyTorch device used for encoder inference, such as `cpu`, `cuda`, or
518        /// `cuda:0`. Auto-detected when omitted.
519        device: Option<String>,
520        /// Directory where Hugging Face caches the downloaded encoder and tokenizer.
521        cache_dir: Option<PathBuf>,
522        /// Maximum tokenized encoder input length; longer prompts are truncated.
523        max_length: Option<usize>,
524        /// Maximum prompts per encoder forward pass.
525        batch_size: Option<usize>,
526    },
527}
528
529#[derive(Clone, Debug, Deserialize)]
530#[serde(deny_unknown_fields)]
531pub struct VgrRouteConfig {
532    pub efficient_target: String,
533    pub capable_target: String,
534    /// Defaults to `efficient_target`.
535    #[serde(default)]
536    pub judge_target: Option<String>,
537    #[serde(default)]
538    pub capable_judge_target: Option<String>,
539    #[serde(default)]
540    pub mode: VgrModeConfig,
541    #[serde(default)]
542    pub active_approval: Option<String>,
543    #[serde(default = "default_vgr_deadline")]
544    pub deadline_seconds: f64,
545    /// Enforces VGR decision and efficient turn budgets. Defaults to true.
546    #[serde(default = "default_true")]
547    pub bounded_efficient: bool,
548    #[serde(default = "default_true")]
549    pub task_typing: bool,
550    #[serde(default = "default_vgr_breaker_threshold")]
551    pub breaker_threshold: u32,
552    #[serde(default = "default_vgr_breaker_cooldown")]
553    pub breaker_cooldown_seconds: f64,
554    /// Clean trailing tool results that let a long run recover on the capable judge.
555    #[serde(default)]
556    pub confirmed_recovery_min_clean_tail: Option<u32>,
557    /// Tells the capable tier it inherits unverified tool-using work.
558    #[serde(default)]
559    pub agentic_handoff: bool,
560    /// Condenses history from the efficient tier at handoff. Requires `agentic_handoff`.
561    #[serde(default)]
562    pub compact_handoff: bool,
563    /// Wall-clock budget for the efficient tier within one user turn.
564    #[serde(default)]
565    pub efficient_turn_budget_seconds: Option<f64>,
566    /// Holds escalations across later user turns.
567    #[serde(default)]
568    pub latch_escalation: bool,
569    /// Lets the efficient tier attempt requests that contain attachments.
570    #[serde(default)]
571    pub efficient_supports_attachments: bool,
572}
573
574#[derive(Clone, Debug, Default, Deserialize)]
575#[serde(rename_all = "snake_case")]
576pub enum VgrModeConfig {
577    #[default]
578    Off,
579    Evaluate,
580    Shadow,
581    Active,
582}
583
584/// What fires an advisor route's review.
585#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
586#[serde(rename_all = "snake_case")]
587pub enum AdvisorTriggerConfig {
588    /// The executor's first turn without tool calls.
589    #[default]
590    NoToolCall,
591    /// The first turn whose text matches `gate_trigger_pattern`.
592    Pattern,
593}
594
595/// The judge a `stage_router` route falls through to, and how it routes.
596#[derive(Clone, Debug, Deserialize)]
597#[serde(deny_unknown_fields)]
598pub struct StageClassifierConfig {
599    /// Target the judge is called through. Not a routing destination.
600    pub target: String,
601    /// Composite accepts custom-schema judges as well as capability judges.
602    #[serde(default)]
603    pub mode: Option<ClassifierMode>,
604    #[serde(default)]
605    pub response_schema: Option<String>,
606    #[serde(default)]
607    pub policy: Option<ClassifierPolicyConfig>,
608    #[serde(default)]
609    pub decision: Option<DecisionJudgeRouteConfig>,
610    #[serde(default)]
611    pub fail_open: Option<bool>,
612    /// Lowest solve probability that still routes to the efficient tier, from 0 to 1.
613    pub base_threshold: Option<f64>,
614    /// How much to raise the threshold when the judge is uncertain. Added once
615    /// for an uncertain verdict and twice for unsupported.
616    #[serde(default)]
617    pub threshold_step: Option<f64>,
618    /// How often the judge runs. Composite honors it. A standalone stage route
619    /// rejects any value other than `every_request`, because its fallback judge
620    /// runs on every ambiguous turn and retains no verdict.
621    #[serde(default)]
622    pub classify_trigger: ClassifyTrigger,
623    /// Reuses the session's target by hashing the first user message when no
624    /// session ID is available.
625    #[serde(default)]
626    pub message_hash_fallback: bool,
627    /// How many trailing turns the judge sees. Unset shows it the opening task
628    /// and the latest user follow-up only.
629    #[serde(default)]
630    pub recent_turn_window: Option<usize>,
631    /// Image cap for the latest user instruction message; zero omits its images from the judge.
632    #[serde(default)]
633    pub judge_max_images: Option<usize>,
634    /// Replaces the packaged judge prompt.
635    #[serde(default)]
636    pub prompt: Option<String>,
637    /// How the judge is asked for structured output. Use `json_object` when the
638    /// provider cannot do JSON Schema.
639    #[serde(default)]
640    pub response_format_type: ClassifierResponseFormat,
641    /// Most completion tokens the judge verdict may use.
642    #[serde(default = "default_classifier_max_output_tokens")]
643    pub max_output_tokens: u64,
644    /// Whole-consultation bound on the judge call in milliseconds; expiry follows the
645    /// route's `fail_open` setting. Unset leaves the consultation unbounded.
646    #[serde(default)]
647    pub judge_deadline_ms: Option<u64>,
648}
649
650const COMPOSITE_PLANNING_PROMPT: &str = "You are in the planning phase. Inspect the task and the relevant code, then form a concrete implementation plan before modifying any files. Use read-only tools as needed. Do not make an edit until the plan is complete. After completing the plan, immediately make the first edit in the same task to hand execution off. Do not finish or return a final response with only the plan.";
651
652/// The shared model pair and defaults for composite stage profiles.
653#[derive(Clone, Debug, Deserialize)]
654#[serde(deny_unknown_fields)]
655pub struct StageTierConfig {
656    pub capable_target: String,
657    pub efficient_target: String,
658    #[serde(default)]
659    pub capable_first_threshold: f64,
660    #[serde(flatten)]
661    pub settings: StageSettingsConfig,
662}
663
664/// Settings shared by standalone stage routes and composite profiles.
665#[derive(Clone, Debug, Default, Deserialize)]
666#[serde(default, deny_unknown_fields)]
667pub struct StageSettingsConfig {
668    pub cache_weight: Option<f64>,
669    #[serde(alias = "efficient_first_threshold")]
670    pub confidence_threshold: Option<f64>,
671    pub recent_turn_window: Option<usize>,
672    pub tool_semantics: Option<ToolSemantics>,
673    pub compaction_override: Option<bool>,
674    pub capable_hold_turns: Option<i64>,
675    pub efficient_hold_turns: Option<i64>,
676    pub handoff_notes: Option<HandoffNoteConfig>,
677    pub capable_system_prompt: Option<String>,
678    pub efficient_system_prompt: Option<String>,
679}
680
681#[derive(Clone, Debug, Default, Deserialize)]
682#[serde(deny_unknown_fields)]
683pub struct StageProfileConfig {
684    pub capable_target: Option<String>,
685    pub efficient_target: Option<String>,
686    pub classifier: Option<StageClassifierConfig>,
687    pub picker: Option<PickerMode>,
688    #[serde(flatten)]
689    pub settings: StageSettingsConfig,
690}
691
692impl StageSettingsConfig {
693    fn stage_config(&self, shared: &Self, mode: PickerMode, threshold: f64) -> StageRouterConfig {
694        let mut config =
695            StageRouterConfig::new(mode, self.confidence_threshold.unwrap_or(threshold));
696        config.cache_weight = self
697            .cache_weight
698            .or(shared.cache_weight)
699            .unwrap_or_default();
700        config.recent_window = self.recent_turn_window.or(shared.recent_turn_window);
701        config.compaction_override = self
702            .compaction_override
703            .or(shared.compaction_override)
704            .unwrap_or(true);
705        config.tool_semantics = self
706            .tool_semantics
707            .as_ref()
708            .or(shared.tool_semantics.as_ref())
709            .cloned()
710            .unwrap_or_default();
711        config.capable_hold_turns = self
712            .capable_hold_turns
713            .or(shared.capable_hold_turns)
714            .unwrap_or(2);
715        config.efficient_hold_turns = self.efficient_hold_turns.or(shared.efficient_hold_turns);
716        config.handoff_notes = self
717            .handoff_notes
718            .as_ref()
719            .or(shared.handoff_notes.as_ref())
720            .cloned();
721        config.capable_system_prompt = self
722            .capable_system_prompt
723            .as_ref()
724            .or(shared.capable_system_prompt.as_ref())
725            .cloned();
726        config.efficient_system_prompt = self
727            .efficient_system_prompt
728            .as_ref()
729            .or(shared.efficient_system_prompt.as_ref())
730            .cloned();
731        config
732    }
733}
734
735impl StageTierConfig {
736    fn profile_config(
737        &self,
738        profile: &StageProfileConfig,
739        picker: PickerMode,
740    ) -> StageRouterConfig {
741        let threshold = match picker {
742            PickerMode::EfficientFirst => self.settings.confidence_threshold.unwrap_or(0.4),
743            PickerMode::CapableFirst => self.capable_first_threshold,
744        };
745        let mode = profile.picker.unwrap_or(picker);
746        let capable_first = mode == PickerMode::CapableFirst;
747        let mut config = profile
748            .settings
749            .stage_config(&self.settings, mode, threshold);
750        config.recent_window.get_or_insert(3);
751        config.capable_hold_turns = profile
752            .settings
753            .capable_hold_turns
754            .or(self.settings.capable_hold_turns)
755            .unwrap_or(if capable_first { 0 } else { 2 });
756        config
757            .efficient_hold_turns
758            .get_or_insert(if capable_first { -1 } else { 0 });
759        if capable_first {
760            config
761                .capable_system_prompt
762                .get_or_insert_with(|| COMPOSITE_PLANNING_PROMPT.into());
763        }
764        config
765    }
766
767    /// Warns when both tiers name one target; see [`warn_identical_tiers`].
768    fn warn_identical_tiers(&self, route_name: &str) {
769        warn_identical_tiers(route_name, &self.capable_target, &self.efficient_target);
770    }
771}
772
773impl StageClassifierConfig {
774    fn composite_judge_config(
775        &self,
776        route_name: &str,
777        capable: &str,
778        efficient: &str,
779    ) -> AlgorithmResult<CompositeJudgeConfig> {
780        if matches!(self.mode, Some(ClassifierMode::Custom)) {
781            return Ok(CompositeJudgeConfig::Custom(
782                self.custom_classifier_config(route_name)?,
783            ));
784        }
785        let mut config = self.task_classifier_config(route_name, capable, efficient)?;
786        if let CapabilityJudgeConfig::Decision(judge) = &mut config.judge {
787            judge.cutoff.get_or_insert(0.92);
788        }
789        Ok(CompositeJudgeConfig::Capability(config))
790    }
791
792    fn task_classifier_config(
793        &self,
794        route_name: &str,
795        capable_target: &str,
796        efficient_target: &str,
797    ) -> AlgorithmResult<TaskClassifierConfig> {
798        if self
799            .mode
800            .is_some_and(|mode| !matches!(mode, ClassifierMode::Capability))
801            || self.response_schema.is_some()
802            || self.policy.is_some()
803        {
804            return Err(AlgorithmConfigError::new(
805                "custom classifier settings require composite with mode = custom",
806            ));
807        }
808        let config = LlmClassifierRouteConfig {
809            classifier_target: self.target.clone(),
810            strong_target: Some(capable_target.to_string()),
811            weak_target: Some(efficient_target.to_string()),
812            base_threshold: self.base_threshold,
813            threshold_step: self.threshold_step,
814            fail_open: self.fail_open,
815            decision: self.decision.clone(),
816            classify_trigger: self.classify_trigger,
817            message_hash_fallback: self.message_hash_fallback,
818            recent_turn_window: self.recent_turn_window,
819            judge_max_images: self.judge_max_images,
820            prompt: self.prompt.clone(),
821            response_format_type: self.response_format_type,
822            max_output_tokens: self.max_output_tokens,
823            judge_deadline_ms: self.judge_deadline_ms,
824            ..Default::default()
825        };
826        match config.validated_classifier_mode(route_name)? {
827            LlmClassifierModeConfig::Capability(config) => Ok(config.into_task_config()),
828            _ => Err(AlgorithmConfigError::new("expected a capability judge")),
829        }
830    }
831
832    fn infer_decision(
833        &mut self,
834        infer: &mut impl FnMut(&str, &mut Option<DecisionJudgeRouteConfig>),
835    ) {
836        if matches!(self.mode, None | Some(ClassifierMode::Capability)) {
837            infer(&self.target, &mut self.decision);
838        }
839    }
840
841    fn stage_fallback(
842        &self,
843        route_name: &str,
844        capable: &str,
845        efficient: &str,
846        targets: &BTreeMap<String, ModelId>,
847    ) -> AlgorithmResult<LlmFallback> {
848        Ok(LlmFallback {
849            target: Some(resolve_target_model_id(route_name, &self.target, targets)?),
850            config: self.task_classifier_config(route_name, capable, efficient)?,
851        })
852    }
853
854    fn custom_classifier_config(
855        &self,
856        route_name: &str,
857    ) -> AlgorithmResult<CustomClassifierConfig> {
858        if self.fail_open == Some(false) {
859            return Err(AlgorithmConfigError::new(
860                "composite custom classifiers always fail open; remove fail_open = false",
861            ));
862        }
863        if self.decision.is_some()
864            || self.base_threshold.is_some()
865            || self.threshold_step.is_some()
866            || self.response_format_type != ClassifierResponseFormat::JsonSchema
867        {
868            return Err(AlgorithmConfigError::new(
869                "composite custom classifier cannot use capability thresholds, decision settings, or response_format_type",
870            ));
871        }
872        let schema =
873            required_classifier_field(route_name, "response_schema", &self.response_schema)?;
874        let schema = serde_json::from_str(&schema).map_err(|error| {
875            AlgorithmConfigError::with_source(
876                format!("composite route {route_name}: response_schema is invalid JSON"),
877                error,
878            )
879        })?;
880        let mut config = CustomClassifierConfig::new(
881            required_classifier_field(route_name, "prompt", &self.prompt)?,
882            schema,
883            required_classifier_field(route_name, "policy", &self.policy)?.into_libsy(),
884        );
885        config.classify_trigger = self.classify_trigger;
886        config.message_hash_fallback = self.message_hash_fallback;
887        config.recent_turn_window = self.recent_turn_window;
888        config.judge_max_images = self.judge_max_images;
889        config.max_output_tokens = self.max_output_tokens;
890        Ok(config)
891    }
892}
893
894impl AlgorithmSpec {
895    /// Filters configured pools without replacing required targets or changing their roles.
896    pub(crate) fn restricted_to(&self, allowed: &BTreeSet<&str>) -> AlgorithmResult<Self> {
897        let mut restricted = self.clone();
898        match &mut restricted {
899            Self::Random {
900                targets, weights, ..
901            } => {
902                if let Some(weights) = weights {
903                    if weights.len() != targets.len() {
904                        return Err(AlgorithmConfigError::new(format!(
905                            "random expected {} weights, got {}",
906                            targets.len(),
907                            weights.len()
908                        )));
909                    }
910                    // Keep weight positions paired with the original target order.
911                    let mut index = 0;
912                    weights.retain(|_| {
913                        let keep = allowed.contains(targets[index].as_str());
914                        index += 1;
915                        keep
916                    });
917                }
918                targets.retain(|target| allowed.contains(target.as_str()));
919                if targets.is_empty() {
920                    return Err(AlgorithmConfigError::new(
921                        "target requirements leave random without an eligible target".to_string(),
922                    ));
923                }
924            }
925            Self::LlmClassifier { config } => {
926                if let Some(models) = &mut config.models {
927                    models.restrict_to(allowed);
928                }
929            }
930            _ => {}
931        }
932        let subagents = match &mut restricted {
933            Self::Passthrough { subagents, .. }
934            | Self::StageRouter { subagents, .. }
935            | Self::Composite { subagents, .. } => subagents.as_mut(),
936            _ => None,
937        };
938        if let Some(SubagentRouteConfig::LlmClassifier(config)) = subagents
939            && let Some(models) = &mut config.models
940        {
941            models.restrict_to(allowed);
942        }
943        if let Some(target) = restricted
944            .callable_target_names()
945            .into_iter()
946            .find(|target| !allowed.contains(target))
947        {
948            return Err(AlgorithmConfigError::new(format!(
949                "required target {target} does not satisfy target requirements"
950            )));
951        }
952        Ok(restricted)
953    }
954
955    pub(crate) const fn supports_target_restrictions(&self) -> bool {
956        !matches!(self, Self::PrefillRouter { .. })
957    }
958
959    /// This iterator yields tier classifier targets and their optional decision settings.
960    /// It includes classifiers in nested Composite profiles.
961    /// Standalone custom and direct modes use model groups and are excluded.
962    pub(crate) fn classifier_targets(
963        &self,
964    ) -> impl Iterator<Item = (&str, Option<&DecisionJudgeRouteConfig>)> {
965        let (primary, profiles) = match self {
966            Self::LlmClassifier { config, .. }
967                if !matches!(
968                    config.classifier_mode(),
969                    ClassifierMode::Custom | ClassifierMode::Direct
970                ) =>
971            {
972                (
973                    Some((config.classifier_target.as_str(), config.decision.as_ref())),
974                    [None, None],
975                )
976            }
977            Self::Composite {
978                classifier,
979                efficient,
980                capable,
981                ..
982            } => (
983                Some((classifier.target.as_str(), classifier.decision.as_ref())),
984                [efficient.as_deref(), capable.as_deref()],
985            ),
986            Self::StageRouter { classifier, .. } => (
987                classifier
988                    .as_ref()
989                    .map(|c| (c.target.as_str(), c.decision.as_ref())),
990                [None, None],
991            ),
992            _ => (None, [None, None]),
993        };
994        primary.into_iter().chain(
995            profiles
996                .into_iter()
997                .flatten()
998                .filter_map(|profile| profile.classifier.as_ref())
999                .map(|c| (c.target.as_str(), c.decision.as_ref())),
1000        )
1001    }
1002
1003    /// Gives capability judges default decision settings when their target is a decision target.
1004    pub(crate) fn infer_decision_judges(&mut self, is_decision_target: impl Fn(&str) -> bool) {
1005        let mut infer = |target: &str, decision: &mut Option<DecisionJudgeRouteConfig>| {
1006            if is_decision_target(target) {
1007                decision.get_or_insert_with(Default::default);
1008            }
1009        };
1010        match self {
1011            Self::LlmClassifier { config }
1012                if matches!(config.classifier_mode(), ClassifierMode::Capability) =>
1013            {
1014                infer(&config.classifier_target, &mut config.decision);
1015            }
1016            Self::StageRouter {
1017                classifier: Some(classifier),
1018                ..
1019            } => classifier.infer_decision(&mut infer),
1020            Self::Composite {
1021                classifier,
1022                efficient,
1023                capable,
1024                ..
1025            } => {
1026                classifier.infer_decision(&mut infer);
1027                for profile in [efficient, capable].into_iter().flatten() {
1028                    if let Some(classifier) = &mut profile.classifier {
1029                        classifier.infer_decision(&mut infer);
1030                    }
1031                }
1032            }
1033            _ => {}
1034        }
1035    }
1036
1037    /// Judge targets that must be decision targets.
1038    pub(crate) fn decision_target_names(&self) -> Vec<&str> {
1039        let mut names: Vec<&str> = self
1040            .classifier_targets()
1041            .filter(|(_, decision)| decision.is_some())
1042            .map(|(target, _)| target)
1043            .collect();
1044        if let Self::LlmClassifier { config, .. } = self
1045            && matches!(config.classifier_mode(), ClassifierMode::Direct)
1046            && let Some(models) = &config.models
1047        {
1048            names.extend(models.get(&Category::Judge).iter().map(String::as_str));
1049        }
1050        names
1051    }
1052
1053    fn profile_targets(&self) -> impl Iterator<Item = &String> {
1054        let profiles = match self {
1055            Self::Composite {
1056                efficient, capable, ..
1057            } => [efficient.as_deref(), capable.as_deref()],
1058            _ => [None, None],
1059        };
1060        profiles
1061            .into_iter()
1062            .flatten()
1063            .flat_map(|p| p.capable_target.iter().chain(&p.efficient_target))
1064    }
1065
1066    /// Completion targets in algorithm order; judge-only targets are excluded.
1067    pub fn routing_target_names(&self) -> Vec<&str> {
1068        match self {
1069            Self::Noop { .. } => Vec::new(),
1070            Self::Random { targets, .. } => targets.iter().map(String::as_str).collect(),
1071            Self::Passthrough {
1072                target, subagents, ..
1073            } => {
1074                let mut names = vec![target.as_str()];
1075                if let Some(subagents) = subagents {
1076                    names.extend(subagents.routing_target_names());
1077                }
1078                names
1079            }
1080            Self::LlmClassifier { config, .. } => match config.classifier_mode() {
1081                ClassifierMode::Capability => config
1082                    .weak_target
1083                    .iter()
1084                    .chain(&config.strong_target)
1085                    .map(String::as_str)
1086                    .collect(),
1087                ClassifierMode::Escalation => config
1088                    .strong_target
1089                    .iter()
1090                    .chain(&config.weak_target)
1091                    .map(String::as_str)
1092                    .collect(),
1093                ClassifierMode::Custom | ClassifierMode::Direct => config
1094                    .models
1095                    .as_ref()
1096                    .map(CategoryModelConfig::routing_names)
1097                    .unwrap_or_default(),
1098            },
1099            Self::StageRouter {
1100                capable_target,
1101                efficient_target,
1102                subagents,
1103                ..
1104            } => {
1105                let mut names = vec![capable_target.as_str(), efficient_target.as_str()];
1106                if let Some(subagents) = subagents {
1107                    names.extend(subagents.routing_target_names());
1108                }
1109                names
1110            }
1111            Self::Auto {
1112                capable_target,
1113                efficient_target,
1114            } => vec![capable_target.as_str(), efficient_target.as_str()],
1115            Self::Composite {
1116                stage, subagents, ..
1117            } => {
1118                let mut names = vec![
1119                    stage.capable_target.as_str(),
1120                    stage.efficient_target.as_str(),
1121                ];
1122                names.extend(self.profile_targets().map(String::as_str));
1123                if let Some(subagents) = subagents {
1124                    names.extend(subagents.routing_target_names());
1125                }
1126                names
1127            }
1128            // The advisor is judge-only: reviews go through its own client,
1129            // so it is not a completion (or count_tokens) destination.
1130            Self::Advisor {
1131                executor_target, ..
1132            } => vec![executor_target],
1133            Self::Vgr { config } => {
1134                vec![
1135                    config.efficient_target.as_str(),
1136                    config.capable_target.as_str(),
1137                ]
1138            }
1139            Self::PrefillRouter { targets, .. } => targets.iter().map(String::as_str).collect(),
1140        }
1141    }
1142
1143    /// Every target the algorithm may call, including judge-only targets.
1144    ///
1145    /// [`routing_target_names`](Self::routing_target_names) covers completion destinations;
1146    /// a classifier also calls its judge, and that call needs a client too.
1147    pub fn callable_target_names(&self) -> Vec<&str> {
1148        let mut names = self.routing_target_names();
1149        names.extend(self.judge_target_names());
1150        names
1151    }
1152
1153    /// Targets the algorithm calls only to decide, such as a judge or an advisor. A target
1154    /// that also answers requests appears in [`routing_target_names`](Self::routing_target_names) too.
1155    pub fn judge_target_names(&self) -> Vec<&str> {
1156        let mut names = Vec::new();
1157        match self {
1158            // Custom and direct modes name their judge in `models.judge`; the other
1159            // two modes use the top-level `classifier_target`.
1160            Self::LlmClassifier { config, .. } => {
1161                if matches!(
1162                    config.classifier_mode(),
1163                    ClassifierMode::Custom | ClassifierMode::Direct
1164                ) {
1165                    names.extend(
1166                        config
1167                            .models
1168                            .as_ref()
1169                            .map(|models| models.get(&Category::Judge))
1170                            .unwrap_or_default()
1171                            .iter()
1172                            .map(String::as_str),
1173                    );
1174                } else {
1175                    names.push(config.classifier_target.as_str());
1176                }
1177            }
1178            Self::StageRouter { .. } | Self::Composite { .. } => {
1179                names.extend(self.classifier_targets().map(|(target, _)| target));
1180            }
1181            Self::Advisor { advisor_target, .. } => names.push(advisor_target),
1182            Self::Vgr { config } => {
1183                names.extend(config.judge_target.as_deref());
1184                names.extend(config.capable_judge_target.as_deref());
1185            }
1186            _ => {}
1187        }
1188        // A sub-agent classifier calls its own judge, which is never a completion target.
1189        if let Self::Passthrough {
1190            subagents: Some(subagents),
1191            ..
1192        }
1193        | Self::StageRouter {
1194            subagents: Some(subagents),
1195            ..
1196        }
1197        | Self::Composite {
1198            subagents: Some(subagents),
1199            ..
1200        } = self
1201        {
1202            names.extend(subagents.judge_target_names());
1203        }
1204        names
1205    }
1206
1207    /// Target names grouped as the runtime [`Driver`](libsy::Driver) expects them.
1208    fn runtime_model_names(&self, route_name: &str) -> AlgorithmResult<RuntimeModelNames> {
1209        let parent = match self {
1210            Self::Noop { .. } => HashMap::new(),
1211            Self::Random { targets, .. } | Self::PrefillRouter { targets, .. } => {
1212                category_models([(Category::Any, targets.clone())])
1213            }
1214            Self::Passthrough { target, .. } => {
1215                category_models([(Category::Any, vec![target.clone()])])
1216            }
1217            Self::LlmClassifier { config } => {
1218                classifier_runtime_model_names(config.validated_classifier_mode(route_name)?)
1219            }
1220            Self::StageRouter {
1221                capable_target,
1222                efficient_target,
1223                classifier,
1224                ..
1225            } => {
1226                let mut models = category_models([
1227                    (Category::Capable, vec![capable_target.clone()]),
1228                    (Category::Efficient, vec![efficient_target.clone()]),
1229                    (
1230                        Category::Any,
1231                        vec![capable_target.clone(), efficient_target.clone()],
1232                    ),
1233                ]);
1234                if let Some(classifier) = classifier {
1235                    models.insert(Category::Judge, vec![classifier.target.clone()]);
1236                }
1237                models
1238            }
1239            Self::Auto {
1240                capable_target,
1241                efficient_target,
1242            } => category_models([
1243                (Category::Capable, vec![capable_target.clone()]),
1244                (Category::Efficient, vec![efficient_target.clone()]),
1245                (
1246                    Category::Any,
1247                    vec![capable_target.clone(), efficient_target.clone()],
1248                ),
1249            ]),
1250            Self::Composite { stage, .. } => category_models([
1251                (
1252                    Category::Judge,
1253                    self.judge_target_names()
1254                        .into_iter()
1255                        .map(str::to_string)
1256                        .collect(),
1257                ),
1258                (Category::Capable, vec![stage.capable_target.clone()]),
1259                (Category::Efficient, vec![stage.efficient_target.clone()]),
1260                (
1261                    Category::Any,
1262                    [stage.capable_target.clone(), stage.efficient_target.clone()]
1263                        .into_iter()
1264                        .chain(self.profile_targets().cloned())
1265                        .collect(),
1266                ),
1267            ]),
1268            Self::Advisor {
1269                executor_target,
1270                advisor_target,
1271                ..
1272            } => category_models([
1273                (Category::Efficient, vec![executor_target.clone()]),
1274                (Category::Any, vec![executor_target.clone()]),
1275                (Category::Judge, vec![advisor_target.clone()]),
1276            ]),
1277            Self::Vgr { config } => {
1278                let judge = config
1279                    .judge_target
1280                    .as_ref()
1281                    .unwrap_or(&config.efficient_target);
1282                let judges = std::iter::once(judge)
1283                    .chain(&config.capable_judge_target)
1284                    .cloned()
1285                    .collect();
1286                category_models([
1287                    (Category::Efficient, vec![config.efficient_target.clone()]),
1288                    (Category::Capable, vec![config.capable_target.clone()]),
1289                    (
1290                        Category::Any,
1291                        vec![
1292                            config.efficient_target.clone(),
1293                            config.capable_target.clone(),
1294                        ],
1295                    ),
1296                    (Category::Judge, judges),
1297                ])
1298            }
1299        };
1300
1301        let subagents = match self {
1302            Self::Passthrough { subagents, .. }
1303            | Self::StageRouter { subagents, .. }
1304            | Self::Composite { subagents, .. } => subagents.as_ref(),
1305            _ => None,
1306        };
1307        // Sub-agent groups stay separate from the parent's. Merging them would let a
1308        // sub-agent's `capable` resolve to the parent's, and would put models only the
1309        // sub-agents were given into the parent's `Any` fallback list.
1310        let subagent = subagents
1311            .map(|subagents| subagent_runtime_model_names(subagents, route_name))
1312            .transpose()?;
1313        Ok(RuntimeModelNames { parent, subagent })
1314    }
1315
1316    /// Response target and routing-only dependency for routers that answer while routing.
1317    #[cfg(not(target_os = "wasi"))]
1318    pub(crate) fn routing_response_and_dependency(&self) -> Option<(&str, &str)> {
1319        match self {
1320            Self::LlmClassifier { config, .. }
1321                if matches!(config.classifier_mode(), ClassifierMode::Escalation) =>
1322            {
1323                Some((
1324                    config.weak_target.as_deref()?,
1325                    config.classifier_target.as_str(),
1326                ))
1327            }
1328            Self::Advisor {
1329                executor_target,
1330                advisor_target,
1331                ..
1332            } => Some((executor_target, advisor_target)),
1333            Self::Vgr { config } => Some((
1334                &config.efficient_target,
1335                config
1336                    .judge_target
1337                    .as_deref()
1338                    .unwrap_or(&config.efficient_target),
1339            )),
1340            Self::Noop { .. }
1341            | Self::Random { .. }
1342            | Self::Passthrough { .. }
1343            | Self::LlmClassifier { .. }
1344            | Self::StageRouter { .. }
1345            | Self::Auto { .. }
1346            | Self::Composite { .. }
1347            | Self::PrefillRouter { .. } => None,
1348        }
1349    }
1350
1351    /// Builds this algorithm after resolving configured target names.
1352    pub fn build(
1353        &self,
1354        route_name: &str,
1355        targets: &BTreeMap<String, ModelId>,
1356    ) -> AlgorithmResult<Arc<dyn Algorithm>> {
1357        build_algorithm(route_name, self, targets)
1358    }
1359
1360    /// Resolves target names to host model IDs and builds the algorithm and runtime groups.
1361    pub fn build_with_runtime_models(
1362        &self,
1363        route_name: &str,
1364        targets: &BTreeMap<String, ModelId>,
1365    ) -> AlgorithmResult<(Arc<dyn Algorithm>, RuntimeModels)> {
1366        let algorithm = self.build(route_name, targets)?;
1367        let names = self.runtime_model_names(route_name)?;
1368        let mut models =
1369            RuntimeModels::new(resolve_runtime_models(route_name, names.parent, targets)?);
1370        if let Some(subagent) = names.subagent {
1371            models = models.with_subagent(resolve_runtime_models(route_name, subagent, targets)?);
1372        }
1373        Ok((algorithm, models))
1374    }
1375}
1376
1377/// One route's target names, grouped by category and by routing scope.
1378struct RuntimeModelNames {
1379    /// Groups the algorithm itself routes over.
1380    parent: HashMap<Category, Vec<String>>,
1381    /// Groups delegated sub-agent work routes over, when the route has a `subagents` table.
1382    subagent: Option<HashMap<Category, Vec<String>>>,
1383}
1384
1385fn category_models(
1386    entries: impl IntoIterator<Item = (Category, Vec<String>)>,
1387) -> HashMap<Category, Vec<String>> {
1388    entries.into_iter().collect()
1389}
1390
1391fn custom_runtime_model_names(config: &CategoryModelConfig) -> HashMap<Category, Vec<String>> {
1392    config.groups().collect()
1393}
1394
1395fn classifier_runtime_model_names(
1396    config: LlmClassifierModeConfig,
1397) -> HashMap<Category, Vec<String>> {
1398    match config {
1399        LlmClassifierModeConfig::Capability(config) => category_models([
1400            (Category::Judge, vec![config.classifier_target]),
1401            (Category::Efficient, vec![config.weak_target.clone()]),
1402            (Category::Capable, vec![config.strong_target.clone()]),
1403            (
1404                Category::Any,
1405                vec![config.weak_target, config.strong_target],
1406            ),
1407        ]),
1408        LlmClassifierModeConfig::Escalation(config) => category_models([
1409            (Category::Judge, vec![config.classifier_target]),
1410            (Category::Efficient, vec![config.weak_target.clone()]),
1411            (Category::Capable, vec![config.strong_target.clone()]),
1412            (
1413                Category::Any,
1414                vec![config.strong_target, config.weak_target],
1415            ),
1416        ]),
1417        LlmClassifierModeConfig::Custom(config) => custom_runtime_model_names(&config.models),
1418        LlmClassifierModeConfig::Direct { models, .. } => custom_runtime_model_names(&models),
1419    }
1420}
1421
1422fn subagent_runtime_model_names(
1423    config: &SubagentRouteConfig,
1424    route_name: &str,
1425) -> AlgorithmResult<HashMap<Category, Vec<String>>> {
1426    match config {
1427        SubagentRouteConfig::Passthrough { target } => {
1428            Ok(category_models([(Category::Any, vec![target.clone()])]))
1429        }
1430        SubagentRouteConfig::LlmClassifier(config) => {
1431            let LlmClassifierModeConfig::Custom(config) =
1432                config.validated_classifier_mode(route_name)?
1433            else {
1434                return Err(AlgorithmConfigError::new(format!(
1435                    "route {route_name}: subagents llm_classifier only supports mode custom"
1436                )));
1437            };
1438            Ok(custom_runtime_model_names(&config.models))
1439        }
1440    }
1441}
1442impl LlmClassifierRouteConfig {
1443    fn classifier_mode(&self) -> ClassifierMode {
1444        let default = if self.escalation.is_some() {
1445            ClassifierMode::Escalation
1446        } else {
1447            ClassifierMode::Capability
1448        };
1449        self.mode.unwrap_or(default)
1450    }
1451
1452    fn validated_classifier_mode(
1453        &self,
1454        route_name: &str,
1455    ) -> AlgorithmResult<LlmClassifierModeConfig> {
1456        let Self {
1457            classifier_target,
1458            mode,
1459            strong_target,
1460            weak_target,
1461            base_threshold,
1462            threshold_step,
1463            unmatched_steps,
1464            fail_open,
1465            classify_trigger,
1466            message_hash_fallback,
1467            recent_turn_window,
1468            judge_max_images,
1469            prompt,
1470            response_format_type,
1471            max_output_tokens,
1472            judge_deadline_ms,
1473            escalation,
1474            decision,
1475            models,
1476            default_target,
1477            response_schema,
1478            policy,
1479        } = self;
1480
1481        let selected_mode = match (mode, escalation.is_some()) {
1482            (Some(mode), _) => *mode,
1483            (None, true) => ClassifierMode::Escalation,
1484            (None, false) => ClassifierMode::Capability,
1485        };
1486
1487        if decision.is_some() && !matches!(selected_mode, ClassifierMode::Capability) {
1488            return Err(AlgorithmConfigError::new(format!(
1489                "llm_classifier route {route_name}: decision requires capability mode"
1490            )));
1491        }
1492
1493        if !matches!(
1494            selected_mode,
1495            ClassifierMode::Capability | ClassifierMode::Direct
1496        ) && *fail_open == Some(true)
1497        {
1498            return Err(AlgorithmConfigError::new(format!(
1499                "llm_classifier route {route_name}: fail_open = true requires capability or direct mode"
1500            )));
1501        }
1502
1503        match selected_mode {
1504            ClassifierMode::Capability => {
1505                if escalation.is_some() {
1506                    return Err(classifier_field_error(
1507                        route_name,
1508                        "escalation",
1509                        "capability",
1510                    ));
1511                }
1512                reject_custom_fields(
1513                    route_name,
1514                    "capability",
1515                    models,
1516                    default_target,
1517                    response_schema,
1518                    policy,
1519                )?;
1520                let judge = if let Some(decision) = decision {
1521                    if base_threshold.is_some()
1522                        || threshold_step.is_some()
1523                        || unmatched_steps.is_some()
1524                        || prompt.is_some()
1525                        || *response_format_type != ClassifierResponseFormat::JsonSchema
1526                        || *max_output_tokens != default_classifier_max_output_tokens()
1527                        || judge_deadline_ms.is_some()
1528                    {
1529                        return Err(AlgorithmConfigError::new(format!(
1530                            "llm_classifier route {route_name}: decision cannot use LLM judge settings; use decision.cutoff and decision.instructions"
1531                        )));
1532                    }
1533                    CapabilityJudgeRouteConfig::Decision(decision.clone())
1534                } else {
1535                    CapabilityJudgeRouteConfig::Llm(LlmCapabilityConfig {
1536                        base_threshold: required_classifier_field(
1537                            route_name,
1538                            "base_threshold",
1539                            base_threshold,
1540                        )?,
1541                        threshold_step: threshold_step.unwrap_or_default(),
1542                        unmatched_steps: unmatched_steps.unwrap_or(DEFAULT_UNMATCHED_STEPS),
1543                        contract: classifier_contract(prompt.as_deref())
1544                            .with_response_format_type(*response_format_type),
1545                        max_output_tokens: *max_output_tokens,
1546                        judge_deadline_ms: *judge_deadline_ms,
1547                    })
1548                };
1549                Ok(LlmClassifierModeConfig::Capability(
1550                    CapabilityClassifierRouteConfig {
1551                        classifier_target: classifier_target.clone(),
1552                        fail_open: fail_open.unwrap_or(true),
1553                        strong_target: required_classifier_field(
1554                            route_name,
1555                            "strong_target",
1556                            strong_target,
1557                        )?,
1558                        weak_target: required_classifier_field(
1559                            route_name,
1560                            "weak_target",
1561                            weak_target,
1562                        )?,
1563                        judge,
1564                        classify_trigger: *classify_trigger,
1565                        message_hash_fallback: *message_hash_fallback,
1566                        recent_turn_window: *recent_turn_window,
1567                        judge_max_images: *judge_max_images,
1568                    },
1569                ))
1570            }
1571            ClassifierMode::Escalation => {
1572                if judge_max_images.is_some() {
1573                    return Err(classifier_field_error(
1574                        route_name,
1575                        "judge_max_images",
1576                        "escalation",
1577                    ));
1578                }
1579                reject_custom_fields(
1580                    route_name,
1581                    "escalation",
1582                    models,
1583                    default_target,
1584                    response_schema,
1585                    policy,
1586                )?;
1587                if *classify_trigger != ClassifyTrigger::EveryRequest {
1588                    return Err(AlgorithmConfigError::new(format!(
1589                        "llm_classifier route {route_name} mode escalation cannot use classify_trigger"
1590                    )));
1591                }
1592                let has_capability_settings = base_threshold.is_some()
1593                    || threshold_step.is_some()
1594                    || fail_open.is_some()
1595                    || *message_hash_fallback
1596                    || recent_turn_window.is_some();
1597                // `unmatched_steps` is new, so no existing escalation configuration carries it:
1598                // reject it even when the mode is implied by `escalation`. The older capability
1599                // keys stay tolerated in that implicit form for compatibility.
1600                if unmatched_steps.is_some() || (mode.is_some() && has_capability_settings) {
1601                    return Err(AlgorithmConfigError::new(format!(
1602                        "llm_classifier route {route_name} mode escalation cannot use capability routing settings"
1603                    )));
1604                }
1605                if has_capability_settings {
1606                    // Existing files that select escalation through the `escalation` table alone
1607                    // keep loading, but their capability keys do nothing in this mode.
1608                    tracing::warn!(
1609                        "llm_classifier route {route_name} runs in escalation mode because it has an escalation table; base_threshold, threshold_step, fail_open, recent_turn_window and message_hash_fallback are ignored in this mode. Set mode = \"escalation\" and remove them."
1610                    );
1611                }
1612                Ok(LlmClassifierModeConfig::Escalation(
1613                    EscalationClassifierRouteConfig {
1614                        classifier_target: classifier_target.clone(),
1615                        strong_target: required_classifier_field(
1616                            route_name,
1617                            "strong_target",
1618                            strong_target,
1619                        )?,
1620                        weak_target: required_classifier_field(
1621                            route_name,
1622                            "weak_target",
1623                            weak_target,
1624                        )?,
1625                        prompt: prompt.clone(),
1626                        response_format_type: *response_format_type,
1627                        max_output_tokens: *max_output_tokens,
1628                        judge_deadline_ms: *judge_deadline_ms,
1629                        judge: required_classifier_field(route_name, "escalation", escalation)?,
1630                    },
1631                ))
1632            }
1633            ClassifierMode::Custom => {
1634                if !classifier_target.is_empty()
1635                    || strong_target.is_some()
1636                    || weak_target.is_some()
1637                    || base_threshold.is_some()
1638                    || threshold_step.is_some()
1639                    || unmatched_steps.is_some()
1640                    || escalation.is_some()
1641                    || *response_format_type != ClassifierResponseFormat::JsonSchema
1642                {
1643                    return Err(AlgorithmConfigError::new(format!(
1644                        "llm_classifier route {route_name} mode custom cannot use capability or escalation fields and response_format_type must be 'json_schema'"
1645                    )));
1646                }
1647                let (models, default_target) =
1648                    validated_models(route_name, models, default_target)?;
1649                Ok(LlmClassifierModeConfig::Custom(
1650                    CustomClassifierRouteConfig {
1651                        models,
1652                        default_target,
1653                        prompt: required_classifier_field(route_name, "prompt", prompt)?,
1654                        response_schema: required_classifier_field(
1655                            route_name,
1656                            "response_schema",
1657                            response_schema,
1658                        )?,
1659                        policy: required_classifier_field(route_name, "policy", policy)?,
1660                        classify_trigger: *classify_trigger,
1661                        message_hash_fallback: *message_hash_fallback,
1662                        recent_turn_window: *recent_turn_window,
1663                        judge_max_images: *judge_max_images,
1664                        max_output_tokens: *max_output_tokens,
1665                        judge_deadline_ms: *judge_deadline_ms,
1666                    },
1667                ))
1668            }
1669            ClassifierMode::Direct => {
1670                if !classifier_target.is_empty()
1671                    || strong_target.is_some()
1672                    || weak_target.is_some()
1673                    || base_threshold.is_some()
1674                    || threshold_step.is_some()
1675                    || unmatched_steps.is_some()
1676                    || escalation.is_some()
1677                    || prompt.is_some()
1678                    || response_schema.is_some()
1679                    || policy.is_some()
1680                    || *response_format_type != ClassifierResponseFormat::JsonSchema
1681                    || *max_output_tokens != default_classifier_max_output_tokens()
1682                    || judge_deadline_ms.is_some()
1683                    || judge_max_images.is_some()
1684                {
1685                    return Err(AlgorithmConfigError::new(format!(
1686                        "llm_classifier route {route_name} mode direct cannot use capability, escalation, or LLM judge fields"
1687                    )));
1688                }
1689                let (models, default_target) =
1690                    validated_models(route_name, models, default_target)?;
1691                let options = models
1692                    .groups()
1693                    .filter(|(category, targets)| {
1694                        !targets.is_empty() && !matches!(category, Category::Judge | Category::Any)
1695                    })
1696                    .map(|(category, _)| category)
1697                    .collect();
1698                Ok(LlmClassifierModeConfig::Direct {
1699                    models,
1700                    default_target,
1701                    config: DirectClassifierConfig {
1702                        options,
1703                        fail_open: fail_open.unwrap_or(true),
1704                        classify_trigger: *classify_trigger,
1705                        message_hash_fallback: *message_hash_fallback,
1706                        recent_turn_window: *recent_turn_window,
1707                    },
1708                })
1709            }
1710        }
1711    }
1712}
1713
1714fn validated_models(
1715    route_name: &str,
1716    models: &Option<CategoryModelConfig>,
1717    default_target: &Option<String>,
1718) -> AlgorithmResult<(CategoryModelConfig, Category)> {
1719    let models = required_classifier_field(route_name, "models", models)?;
1720    let default_target: Category =
1721        required_classifier_field(route_name, "default_target", default_target)?
1722            .parse()
1723            .map_err(|error| {
1724                AlgorithmConfigError::new(format!(
1725                    "llm_classifier route {route_name} has invalid default_target: {error}"
1726                ))
1727            })?;
1728    if default_target == Category::Judge {
1729        return Err(AlgorithmConfigError::new(format!(
1730            "llm_classifier route {route_name} default_target cannot be judge"
1731        )));
1732    }
1733    models.validate(route_name, &default_target)?;
1734    Ok((models, default_target))
1735}
1736
1737fn reject_custom_fields(
1738    route_name: &str,
1739    mode: &str,
1740    models: &Option<CategoryModelConfig>,
1741    default_target: &Option<String>,
1742    response_schema: &Option<String>,
1743    policy: &Option<ClassifierPolicyConfig>,
1744) -> AlgorithmResult<()> {
1745    if models.is_some() || default_target.is_some() || response_schema.is_some() || policy.is_some()
1746    {
1747        return Err(AlgorithmConfigError::new(format!(
1748            "llm_classifier route {route_name} mode {mode} cannot use custom classifier fields"
1749        )));
1750    }
1751    Ok(())
1752}
1753
1754fn classifier_field_error(route_name: &str, field: &str, mode: &str) -> AlgorithmConfigError {
1755    AlgorithmConfigError::new(format!(
1756        "llm_classifier route {route_name} mode {mode} cannot use {field}"
1757    ))
1758}
1759
1760fn required_classifier_field<T: Clone>(
1761    route_name: &str,
1762    field: &str,
1763    value: &Option<T>,
1764) -> AlgorithmResult<T> {
1765    value.clone().ok_or_else(|| {
1766        AlgorithmConfigError::new(format!(
1767            "llm_classifier route {route_name} requires {field}"
1768        ))
1769    })
1770}
1771
1772fn build_subagent_router_config(
1773    route_name: &str,
1774    config: &SubagentRouteConfig,
1775    targets: &BTreeMap<String, ModelId>,
1776) -> AlgorithmResult<SubagentRouterConfig> {
1777    match config {
1778        SubagentRouteConfig::Passthrough { target } => {
1779            resolve_target_model_id(route_name, target, targets)?;
1780            Ok(SubagentRouterConfig::fixed_target())
1781        }
1782        SubagentRouteConfig::LlmClassifier(config) => {
1783            let LlmClassifierModeConfig::Custom(config) =
1784                config.validated_classifier_mode(route_name)?
1785            else {
1786                return Err(AlgorithmConfigError::new(format!(
1787                    "route {route_name}: subagents llm_classifier only supports mode custom"
1788                )));
1789            };
1790            for name in config.models.all_names() {
1791                resolve_target_model_id(route_name, name, targets)?;
1792            }
1793            if config.models.get(&config.default_target).is_empty() {
1794                return Err(AlgorithmConfigError::new(format!(
1795                    "route {route_name}: subagents llm_classifier has no model for default category {}",
1796                    config.default_target.as_str()
1797                )));
1798            }
1799            let response_schema =
1800                serde_json::from_str(&config.response_schema).map_err(|error| {
1801                    AlgorithmConfigError::with_source(
1802                        format!(
1803                            "route {route_name}: subagents llm_classifier response_schema is invalid JSON: {error}"
1804                        ),
1805                        error,
1806                    )
1807                })?;
1808            warn_single_target_classifier(route_name, &config.models);
1809            let mut classifier_config = CustomClassifierConfig::new(
1810                config.prompt,
1811                response_schema,
1812                config.policy.into_libsy(),
1813            );
1814            classifier_config.recent_turn_window = config.recent_turn_window;
1815            classifier_config.judge_max_images = config.judge_max_images;
1816            classifier_config.max_output_tokens = config.max_output_tokens;
1817            classifier_config.judge_deadline_ms = config.judge_deadline_ms;
1818            let classifier = Arc::new(
1819                LlmTaskClassifier::new(LlmClassifierConfig::Custom {
1820                    default_target: config.default_target.clone(),
1821                    config: classifier_config,
1822                })
1823                .map_err(|error| {
1824                    AlgorithmConfigError::with_source(
1825                        format!("route {route_name}: subagents llm_classifier: {error}"),
1826                        error,
1827                    )
1828                })?,
1829            );
1830            Ok(SubagentRouterConfig {
1831                classifier,
1832                default_target: config.default_target,
1833                classify_trigger: config.classify_trigger,
1834                message_hash_fallback: config.message_hash_fallback,
1835            })
1836        }
1837    }
1838}
1839
1840fn attach_subagent_router(
1841    route_name: &str,
1842    parent: Arc<dyn Algorithm>,
1843    config: Option<&SubagentRouteConfig>,
1844    targets: &BTreeMap<String, ModelId>,
1845) -> AlgorithmResult<Arc<dyn Algorithm>> {
1846    let Some(config) = config else {
1847        return Ok(parent);
1848    };
1849    let config = build_subagent_router_config(route_name, config, targets)?;
1850    let algorithm = SubagentRouter::new(parent, config).map_err(|error| {
1851        AlgorithmConfigError::with_source(
1852            format!("route {route_name}: subagent routing: {error}"),
1853            error,
1854        )
1855    })?;
1856    Ok(Arc::new(algorithm))
1857}
1858
1859/// `build_algorithm` builds the configured algorithm and attaches supported subagent routing.
1860/// It returns errors for invalid settings or failed target lookups during construction.
1861/// `AlgorithmSpec::build_with_runtime_models` also resolves the runtime model groups.
1862fn build_algorithm(
1863    route_name: &str,
1864    config: &AlgorithmSpec,
1865    targets: &BTreeMap<String, ModelId>,
1866) -> AlgorithmResult<Arc<dyn Algorithm>> {
1867    match config {
1868        AlgorithmSpec::Noop { .. } => Ok(Arc::new(Noop {})),
1869        AlgorithmSpec::Random {
1870            targets: names,
1871            weights,
1872            seed,
1873        } => {
1874            // The algorithm only sees its targets at request time, so a bad pairing
1875            // would otherwise fail every request instead of failing to start.
1876            if let Some(weights) = weights
1877                && weights.len() != names.len()
1878            {
1879                return Err(AlgorithmConfigError::new(format!(
1880                    "random route {route_name}: expected {} weights, got {}",
1881                    names.len(),
1882                    weights.len()
1883                )));
1884            }
1885            let mut seen = BTreeSet::new();
1886            if let Some(duplicate) = names.iter().find(|name| !seen.insert(*name)) {
1887                return Err(AlgorithmConfigError::new(format!(
1888                    "random route {route_name}: targets must be unique, {duplicate} is repeated"
1889                )));
1890            }
1891            let algorithm = Random::new(weights.clone(), *seed).map_err(|error| {
1892                AlgorithmConfigError::with_source(
1893                    format!("random route {route_name}: {error}"),
1894                    error,
1895                )
1896            })?;
1897            Ok(Arc::new(algorithm))
1898        }
1899        AlgorithmSpec::Passthrough { subagents, .. } => {
1900            let algorithm = Passthrough;
1901            let parent: Arc<dyn Algorithm> = Arc::new(algorithm);
1902            attach_subagent_router(route_name, parent, subagents.as_ref(), targets)
1903        }
1904        AlgorithmSpec::LlmClassifier {
1905            config: classifier_config,
1906            ..
1907        } => {
1908            let mode = classifier_config.validated_classifier_mode(route_name)?;
1909            let algorithm = match mode {
1910                LlmClassifierModeConfig::Capability(config) => {
1911                    let classifier_config = config.into_task_config();
1912                    LlmTaskClassifier::new(LlmClassifierConfig::Capability {
1913                        config: classifier_config,
1914                    })
1915                }
1916                LlmClassifierModeConfig::Escalation(config) => {
1917                    LlmTaskClassifier::new(LlmClassifierConfig::Escalation {
1918                        contract: classifier_contract(config.prompt.as_deref())
1919                            .with_response_format_type(config.response_format_type),
1920                        config: config.judge,
1921                        max_output_tokens: config.max_output_tokens,
1922                        judge_deadline_ms: config.judge_deadline_ms,
1923                    })
1924                }
1925                LlmClassifierModeConfig::Custom(config) => {
1926                    let response_schema = serde_json::from_str(&config.response_schema).map_err(
1927                        |error| {
1928                            AlgorithmConfigError::with_source(
1929                                format!(
1930                                    "llm_classifier route {route_name}: response_schema is invalid JSON: {error}"
1931                                ),
1932                                error,
1933                            )
1934                        },
1935                    )?;
1936                    warn_single_target_classifier(route_name, &config.models);
1937                    let mut classifier_config = CustomClassifierConfig::new(
1938                        config.prompt,
1939                        response_schema,
1940                        config.policy.into_libsy(),
1941                    );
1942                    classifier_config.classify_trigger = config.classify_trigger;
1943                    classifier_config.message_hash_fallback = config.message_hash_fallback;
1944                    classifier_config.recent_turn_window = config.recent_turn_window;
1945                    classifier_config.judge_max_images = config.judge_max_images;
1946                    classifier_config.max_output_tokens = config.max_output_tokens;
1947                    classifier_config.judge_deadline_ms = config.judge_deadline_ms;
1948                    LlmTaskClassifier::new(LlmClassifierConfig::Custom {
1949                        default_target: config.default_target,
1950                        config: classifier_config,
1951                    })
1952                }
1953                LlmClassifierModeConfig::Direct {
1954                    default_target,
1955                    config,
1956                    ..
1957                } => LlmTaskClassifier::new(LlmClassifierConfig::Direct {
1958                    default_target,
1959                    config,
1960                }),
1961            }
1962            .map_err(|error| {
1963                AlgorithmConfigError::with_source(
1964                    format!("llm_classifier route {route_name}: {error}"),
1965                    error,
1966                )
1967            })?;
1968            Ok(Arc::new(algorithm))
1969        }
1970        AlgorithmSpec::StageRouter {
1971            capable_target,
1972            efficient_target,
1973            capable_first_threshold,
1974            settings,
1975            picker,
1976            classifier,
1977            subagents,
1978            ..
1979        } => {
1980            if matches!(picker, PickerMode::CapableFirst) {
1981                tracing::warn!(
1982                    "stage_router route {route_name} uses the experimental \"capable_first\" picker. Use \"efficient_first\" by default or calibrate confidence_threshold for your model pair and workload."
1983                );
1984            }
1985            warn_identical_tiers(route_name, capable_target, efficient_target);
1986            let threshold = settings.confidence_threshold.ok_or_else(|| {
1987                AlgorithmConfigError::new(format!(
1988                    "stage_router route {route_name}: confidence_threshold is required"
1989                ))
1990            })?;
1991            let mut config = settings.stage_config(settings, *picker, threshold);
1992            config.capable_first_threshold = *capable_first_threshold;
1993            // The judge is called through its own target, so it is not a routing
1994            // destination and stays out of the tier pair.
1995            config.llm_fallback = classifier
1996                .as_ref()
1997                .map(|classifier| {
1998                    classifier.stage_fallback(route_name, capable_target, efficient_target, targets)
1999                })
2000                .transpose()?;
2001            let algorithm = StageRouter::new(config).map_err(|error| {
2002                AlgorithmConfigError::with_source(
2003                    format!("stage_router route {route_name}: {error}"),
2004                    error,
2005                )
2006            })?;
2007            let parent: Arc<dyn Algorithm> = Arc::new(algorithm);
2008            attach_subagent_router(route_name, parent, subagents.as_ref(), targets)
2009        }
2010        AlgorithmSpec::Auto {
2011            capable_target,
2012            efficient_target,
2013        } => {
2014            warn_identical_tiers(route_name, capable_target, efficient_target);
2015            let config = StageRouterConfig::new(PickerMode::EfficientFirst, 0.5);
2016            let algorithm = StageRouter::new(config).map_err(|error| {
2017                AlgorithmConfigError::with_source(
2018                    format!("auto route {route_name}: {error}"),
2019                    error,
2020                )
2021            })?;
2022            Ok(Arc::new(algorithm))
2023        }
2024        AlgorithmSpec::Composite {
2025            classifier,
2026            stage,
2027            efficient,
2028            capable,
2029            subagents,
2030        } => {
2031            stage.warn_identical_tiers(route_name);
2032            let judge = classifier.composite_judge_config(
2033                route_name,
2034                &stage.capable_target,
2035                &stage.efficient_target,
2036            )?;
2037            let has_overrides = config.profile_targets().next().is_some();
2038            let defaults = StageProfileConfig::default();
2039            let profiles = [
2040                (efficient, PickerMode::EfficientFirst),
2041                (capable, PickerMode::CapableFirst),
2042            ]
2043            .map(|(profile, picker)| -> AlgorithmResult<_> {
2044                let profile = profile.as_deref().unwrap_or(&defaults);
2045                let mut config = stage.profile_config(profile, picker);
2046                let [capable, efficient] = [
2047                    (&profile.capable_target, &stage.capable_target),
2048                    (&profile.efficient_target, &stage.efficient_target),
2049                ]
2050                .map(|(target, shared)| target.as_ref().unwrap_or(shared));
2051                if has_overrides {
2052                    config.tier_targets = Some([
2053                        resolve_target_model_id(route_name, capable, targets)?,
2054                        resolve_target_model_id(route_name, efficient, targets)?,
2055                    ]);
2056                }
2057                config.llm_fallback = profile
2058                    .classifier
2059                    .as_ref()
2060                    .map(|classifier| {
2061                        classifier.stage_fallback(route_name, capable, efficient, targets)
2062                    })
2063                    .transpose()?;
2064                Ok(config)
2065            });
2066            let [profile_0, profile_1] = profiles;
2067            let algorithm =
2068                CompositeRouter::new(judge, profile_0?, profile_1?).map_err(|error| {
2069                    AlgorithmConfigError::with_source(
2070                        format!("composite route {route_name}: {error}"),
2071                        error,
2072                    )
2073                })?;
2074            let parent: Arc<dyn Algorithm> = Arc::new(algorithm);
2075            attach_subagent_router(route_name, parent, subagents.as_ref(), targets)
2076        }
2077        AlgorithmSpec::Advisor {
2078            reviewer_system_prompt,
2079            redo_feedback_prefix,
2080            gate_trigger,
2081            gate_trigger_pattern,
2082            max_reviews,
2083            gate_stall_turns,
2084            gate_min_tool_results,
2085            advisor_max_tokens,
2086            advisor_temperature,
2087            transcript_max_chars,
2088            fail_open,
2089            ..
2090        } => {
2091            // A pattern set under the default trigger would be silently
2092            // ignored; reject the misconfiguration instead.
2093            if *gate_trigger == AdvisorTriggerConfig::NoToolCall && gate_trigger_pattern.is_some() {
2094                return Err(AlgorithmConfigError::new(format!(
2095                    "advisor route {route_name}: gate_trigger_pattern requires \
2096                     gate_trigger = \"pattern\""
2097                )));
2098            }
2099            let mut config = AdvisorGateConfig::default();
2100            if let Some(prompt) = reviewer_system_prompt {
2101                config.reviewer_system_prompt = prompt.clone();
2102            }
2103            if let Some(prefix) = redo_feedback_prefix {
2104                config.redo_feedback_prefix = prefix.clone();
2105            }
2106            config.gate_trigger = match gate_trigger {
2107                AdvisorTriggerConfig::NoToolCall => GateTrigger::NoToolCall,
2108                AdvisorTriggerConfig::Pattern => {
2109                    GateTrigger::Pattern(gate_trigger_pattern.clone().unwrap_or_default())
2110                }
2111            };
2112            config.max_reviews = *max_reviews;
2113            config.gate_stall_turns = *gate_stall_turns;
2114            config.gate_min_tool_results = *gate_min_tool_results;
2115            config.advisor_max_tokens = *advisor_max_tokens;
2116            config.advisor_temperature = *advisor_temperature;
2117            config.transcript_max_chars = *transcript_max_chars;
2118            config.fail_open = *fail_open;
2119            let algorithm = AdvisorGate::new(config).map_err(|error| {
2120                AlgorithmConfigError::with_source(
2121                    format!("advisor route {route_name}: {error}"),
2122                    error,
2123                )
2124            })?;
2125            Ok(Arc::new(algorithm))
2126        }
2127        AlgorithmSpec::Vgr { config } => build_vgr(route_name, config, targets),
2128        AlgorithmSpec::PrefillRouter {
2129            targets: names,
2130            checkpoint,
2131            device,
2132            cache_dir,
2133            max_length,
2134            batch_size,
2135        } => {
2136            #[cfg(feature = "prefill-router")]
2137            {
2138                let targets = names
2139                    .iter()
2140                    .map(|name| resolve_target_model_id(route_name, name, targets))
2141                    .collect::<AlgorithmResult<Vec<_>>>()?;
2142                let mut config = prefill_router::PrefillRouterConfig::new(targets, checkpoint);
2143                config.device.clone_from(device);
2144                config.cache_dir.clone_from(cache_dir);
2145                if let Some(max_length) = max_length {
2146                    config.max_length = *max_length;
2147                }
2148                if let Some(batch_size) = batch_size {
2149                    config.batch_size = *batch_size;
2150                }
2151                let algorithm = config.build().map_err(|error| {
2152                    AlgorithmConfigError::with_source(
2153                        format!("prefill_router route {route_name}: {error}"),
2154                        error,
2155                    )
2156                })?;
2157                Ok(Arc::new(algorithm))
2158            }
2159
2160            #[cfg(not(feature = "prefill-router"))]
2161            {
2162                let _ = (
2163                    names, checkpoint, device, cache_dir, max_length, batch_size, targets,
2164                );
2165                Err(AlgorithmConfigError::new(format!(
2166                    "prefill_router route {route_name} requires the `prefill-router` Cargo feature"
2167                )))
2168            }
2169        }
2170    }
2171}
2172
2173fn build_vgr(
2174    route_name: &str,
2175    config: &VgrRouteConfig,
2176    targets: &BTreeMap<String, ModelId>,
2177) -> AlgorithmResult<Arc<dyn Algorithm>> {
2178    let efficient = resolve_target_model_id(route_name, &config.efficient_target, targets)?;
2179    let capable = resolve_target_model_id(route_name, &config.capable_target, targets)?;
2180    let optional = |name: &Option<String>| {
2181        name.as_deref()
2182            .map(|name| resolve_target_model_id(route_name, name, targets))
2183            .transpose()
2184    };
2185    let mut runtime = VgrConfig::new(efficient, capable);
2186    runtime.targets.judge = optional(&config.judge_target)?;
2187    runtime.targets.capable_judge = optional(&config.capable_judge_target)?;
2188    runtime.mode = match config.mode {
2189        VgrModeConfig::Off => libsy::ServingMode::Off,
2190        VgrModeConfig::Evaluate => libsy::ServingMode::Evaluate,
2191        VgrModeConfig::Shadow => libsy::ServingMode::Shadow,
2192        VgrModeConfig::Active => libsy::ServingMode::Active {
2193            approval: config.active_approval.clone().unwrap_or_default(),
2194        },
2195    };
2196    runtime.deadline = vgr_duration(route_name, "deadline_seconds", config.deadline_seconds)?;
2197    runtime.bounded_efficient = config.bounded_efficient;
2198    runtime.task_typing = config.task_typing;
2199    runtime.confirmed_recovery_min_clean_tail = config.confirmed_recovery_min_clean_tail;
2200    runtime.agentic_handoff = config.agentic_handoff;
2201    runtime.compact_handoff = config.compact_handoff;
2202    runtime.latch_escalation = config.latch_escalation;
2203    runtime.efficient_supports_attachments = config.efficient_supports_attachments;
2204    runtime.efficient_turn_budget = config
2205        .efficient_turn_budget_seconds
2206        .map(|seconds| vgr_duration(route_name, "efficient_turn_budget_seconds", seconds))
2207        .transpose()?;
2208    runtime.breaker = BreakerConfig {
2209        threshold: config.breaker_threshold,
2210        cooldown: vgr_duration(
2211            route_name,
2212            "breaker_cooldown_seconds",
2213            config.breaker_cooldown_seconds,
2214        )?,
2215    };
2216    Vgr::new(runtime)
2217        .map(|algorithm| Arc::new(algorithm) as Arc<dyn Algorithm>)
2218        .map_err(|error| {
2219            AlgorithmConfigError::with_source(format!("vgr route {route_name}: {error}"), error)
2220        })
2221}
2222
2223fn vgr_duration(route: &str, field: &str, seconds: f64) -> AlgorithmResult<std::time::Duration> {
2224    let message = || format!("vgr route {route}: {field} must be a positive number");
2225    let duration = std::time::Duration::try_from_secs_f64(seconds)
2226        .map_err(|error| AlgorithmConfigError::with_source(message(), error))?;
2227    if duration.is_zero() {
2228        return Err(AlgorithmConfigError::new(message()));
2229    }
2230    Ok(duration)
2231}
2232
2233const fn default_max_reviews() -> u32 {
2234    1
2235}
2236
2237const fn default_advisor_max_tokens() -> u64 {
2238    2048
2239}
2240
2241const fn default_transcript_max_chars() -> usize {
2242    200_000
2243}
2244
2245const fn default_fail_open() -> bool {
2246    true
2247}
2248
2249fn classifier_contract(prompt: Option<&str>) -> ClassifierContractConfig {
2250    prompt.map_or_else(ClassifierContractConfig::default, |prompt| {
2251        ClassifierContractConfig::default().with_prompt(prompt)
2252    })
2253}
2254
2255fn default_classifier_max_output_tokens() -> u64 {
2256    LlmCapabilityConfig::default().max_output_tokens
2257}
2258
2259/// Both tiers on one target leave the route nothing to choose between; every decision
2260/// lands on the same model. The file still loads, since a single-model deployment can
2261/// be a deliberate overhead measurement.
2262fn warn_identical_tiers(route_name: &str, capable_target: &str, efficient_target: &str) {
2263    if capable_target == efficient_target {
2264        tracing::warn!(
2265            route = route_name,
2266            target = capable_target,
2267            "capable_target and efficient_target name the same target, so every request goes to one model; use passthrough for a single model, or point the tiers at two targets"
2268        );
2269    }
2270}
2271
2272fn warn_single_target_classifier(route_name: &str, models: &CategoryModelConfig) {
2273    if models.routing_names().len() < 2 {
2274        tracing::warn!(
2275            route = route_name,
2276            "custom classifier has only one routing target; judge calls add cost without a routing choice. Use passthrough or add another completion target in routes.<name>, or in routes.<name>.subagents for a subagent classifier."
2277        );
2278    }
2279}
2280
2281const fn default_vgr_deadline() -> f64 {
2282    30.0
2283}
2284
2285const fn default_true() -> bool {
2286    true
2287}
2288
2289const fn default_vgr_breaker_threshold() -> u32 {
2290    5
2291}
2292
2293const fn default_vgr_breaker_cooldown() -> f64 {
2294    30.0
2295}
2296
2297fn resolve_target_model_id(
2298    route_name: &str,
2299    name: &str,
2300    targets: &BTreeMap<String, ModelId>,
2301) -> AlgorithmResult<ModelId> {
2302    targets.get(name).cloned().ok_or_else(|| {
2303        AlgorithmConfigError::new(format!(
2304            "route {route_name} references unknown target {name}"
2305        ))
2306    })
2307}
2308
2309fn resolve_runtime_models(
2310    route_name: &str,
2311    names: HashMap<Category, Vec<String>>,
2312    targets: &BTreeMap<String, ModelId>,
2313) -> AlgorithmResult<HashMap<Category, Vec<ModelId>>> {
2314    names
2315        .into_iter()
2316        .map(|(category, names)| {
2317            let models = names
2318                .into_iter()
2319                .map(|name| resolve_target_model_id(route_name, &name, targets))
2320                .collect::<AlgorithmResult<Vec<_>>>()?;
2321            Ok((category, models))
2322        })
2323        .collect()
2324}
2325
2326#[cfg(test)]
2327mod tests {
2328    use super::*;
2329
2330    #[test]
2331    fn composite_profile_defaults() -> AlgorithmResult<()> {
2332        let stage: StageTierConfig =
2333            toml::from_str("capable_target = 'strong'\nefficient_target = 'weak'").unwrap();
2334        for (picker, threshold, capable_hold, efficient_hold, prompt) in [
2335            (PickerMode::EfficientFirst, 0.4, 2, 0, None),
2336            (
2337                PickerMode::CapableFirst,
2338                0.0,
2339                0,
2340                -1,
2341                Some(COMPOSITE_PLANNING_PROMPT),
2342            ),
2343        ] {
2344            let config = stage.profile_config(&StageProfileConfig::default(), picker);
2345            assert_eq!(config.mode, picker);
2346            assert_eq!(config.confidence_threshold, threshold);
2347            assert_eq!(config.recent_window, Some(3));
2348            assert!(config.compaction_override);
2349            assert_eq!(config.capable_hold_turns, capable_hold);
2350            assert_eq!(config.efficient_hold_turns, Some(efficient_hold));
2351            assert_eq!(config.capable_system_prompt.as_deref(), prompt);
2352            assert!(config.llm_fallback.is_none());
2353            assert!(config.handoff_notes.is_none());
2354        }
2355        let standalone = StageSettingsConfig::default().stage_config(
2356            &StageSettingsConfig::default(),
2357            PickerMode::CapableFirst,
2358            0.5,
2359        );
2360        assert_eq!(standalone.capable_hold_turns, 2);
2361        assert!(standalone.compaction_override);
2362        assert!(standalone.capable_system_prompt.is_none());
2363        Ok(())
2364    }
2365
2366    #[test]
2367    fn composite_profile_overrides() {
2368        let stage: StageTierConfig = toml::from_str(
2369            r#"
2370capable_target = "strong"
2371efficient_target = "weak"
2372efficient_first_threshold = 0.7
2373capable_first_threshold = 0.2
2374recent_turn_window = 5
2375compaction_override = false
2376capable_hold_turns = 4
2377efficient_hold_turns = 1
2378capable_system_prompt = "Shared plan"
2379"#,
2380        )
2381        .unwrap();
2382        let shared = stage.profile_config(&StageProfileConfig::default(), PickerMode::CapableFirst);
2383        assert_eq!(shared.confidence_threshold, 0.2);
2384        assert_eq!(shared.recent_window, Some(5));
2385        assert!(!shared.compaction_override);
2386        assert_eq!(shared.capable_hold_turns, 4);
2387        assert_eq!(shared.efficient_hold_turns, Some(1));
2388        assert_eq!(shared.capable_system_prompt.as_deref(), Some("Shared plan"));
2389        assert_eq!(
2390            stage
2391                .profile_config(&StageProfileConfig::default(), PickerMode::EfficientFirst)
2392                .confidence_threshold,
2393            0.7
2394        );
2395        let profile: StageProfileConfig = toml::from_str(
2396            r#"
2397confidence_threshold = 0.0
2398recent_turn_window = 2
2399compaction_override = true
2400capable_hold_turns = 0
2401efficient_hold_turns = 0
2402capable_system_prompt = ""
2403"#,
2404        )
2405        .unwrap();
2406        let config = stage.profile_config(&profile, PickerMode::CapableFirst);
2407        assert_eq!(config.confidence_threshold, 0.0);
2408        assert_eq!(config.recent_window, Some(2));
2409        assert!(config.compaction_override);
2410        assert_eq!(config.capable_hold_turns, 0);
2411        assert_eq!(config.efficient_hold_turns, Some(0));
2412        assert_eq!(config.capable_system_prompt.as_deref(), Some(""));
2413    }
2414
2415    #[test]
2416    fn composite_decision_defaults_and_overrides() -> AlgorithmResult<()> {
2417        for (settings, cutoff, fail_open) in [
2418            ("[decision]", 0.92, true),
2419            ("fail_open = false\n[decision]\ncutoff = 0.7", 0.7, false),
2420        ] {
2421            let classifier: StageClassifierConfig = toml::from_str(&format!(
2422                "target = 'judge'\nclassify_trigger = 'new_session'\n{settings}"
2423            ))
2424            .unwrap();
2425            let CompositeJudgeConfig::Capability(config) =
2426                classifier.composite_judge_config("route", "strong", "weak")?
2427            else {
2428                panic!()
2429            };
2430            assert_eq!(config.classify_trigger, ClassifyTrigger::NewSession);
2431            assert_eq!(config.fail_open, fail_open);
2432            let CapabilityJudgeConfig::Decision(judge) = config.judge else {
2433                panic!()
2434            };
2435            assert_eq!(judge.cutoff, Some(cutoff));
2436        }
2437        Ok(())
2438    }
2439
2440    #[test]
2441    fn restricted_random_preserves_weight_positions() -> AlgorithmResult<()> {
2442        let allowed = BTreeSet::from(["private_a", "private_b"]);
2443        let mut algorithm = AlgorithmSpec::Random {
2444            targets: ["public_a", "private_a", "public_b", "private_b"]
2445                .map(String::from)
2446                .to_vec(),
2447            weights: Some(vec![1.0, 2.0, 3.0, 4.0]),
2448            seed: Some(42),
2449        };
2450        let AlgorithmSpec::Random {
2451            targets,
2452            weights,
2453            seed,
2454        } = algorithm.restricted_to(&allowed)?
2455        else {
2456            unreachable!();
2457        };
2458        assert_eq!(targets, ["private_a", "private_b"]);
2459        assert_eq!(weights, Some(vec![2.0, 4.0]));
2460        assert_eq!(seed, Some(42));
2461        if let AlgorithmSpec::Random { weights, .. } = &mut algorithm {
2462            *weights = Some(vec![1.0]);
2463        }
2464        assert!(algorithm.restricted_to(&allowed).is_err());
2465        Ok(())
2466    }
2467
2468    fn custom_classifier() -> LlmClassifierRouteConfig {
2469        LlmClassifierRouteConfig {
2470            mode: Some(ClassifierMode::Custom),
2471            models: Some(CategoryModelConfig(BTreeMap::from([
2472                ("any".into(), vec!["public".into(), "private".into()]),
2473                ("efficient".into(), vec!["public".into(), "private".into()]),
2474                ("judge".into(), vec!["judge".into()]),
2475                ("research".into(), vec!["public".into()]),
2476            ]))),
2477            default_target: Some("efficient".into()),
2478            prompt: Some("Select an available target.".into()),
2479            response_schema: Some(r#"{"type":"object"}"#.into()),
2480            max_output_tokens: default_classifier_max_output_tokens(),
2481            policy: Some(ClassifierPolicyConfig::TargetSelector {
2482                selector: "/target".into(),
2483            }),
2484            ..LlmClassifierRouteConfig::default()
2485        }
2486    }
2487
2488    #[test]
2489    fn restricted_custom_pools_cover_parent_and_subagents() -> AlgorithmResult<()> {
2490        let allowed = BTreeSet::from(["private", "judge"]);
2491        let targets = BTreeMap::from([
2492            ("private".into(), ModelId::from("private")),
2493            ("judge".into(), ModelId::from("judge")),
2494        ]);
2495        let parent = AlgorithmSpec::LlmClassifier {
2496            config: custom_classifier(),
2497        };
2498        let child = AlgorithmSpec::Passthrough {
2499            target: "private".into(),
2500            subagents: Some(SubagentRouteConfig::LlmClassifier(Box::new(
2501                custom_classifier(),
2502            ))),
2503        };
2504        for algorithm in [parent, child] {
2505            let restricted = algorithm.restricted_to(&allowed)?;
2506            let groups = restricted.runtime_model_names("test")?;
2507            let groups = groups.subagent.unwrap_or(groups.parent);
2508            assert_eq!(groups[&Category::Any], ["private"]);
2509            assert_eq!(groups[&Category::Efficient], ["private"]);
2510            assert_eq!(groups[&Category::Judge], ["judge"]);
2511            restricted.build("test", &targets)?;
2512            let missing_judge = algorithm.restricted_to(&BTreeSet::from(["private"]))?;
2513            assert!(missing_judge.build("test", &targets).is_err());
2514        }
2515        Ok(())
2516    }
2517
2518    #[test]
2519    fn restricted_roles_are_not_replaced() {
2520        let stage = AlgorithmSpec::Auto {
2521            capable_target: "private".into(),
2522            efficient_target: "public".into(),
2523        };
2524        assert!(stage.restricted_to(&BTreeSet::from(["private"])).is_err());
2525    }
2526}