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