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