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