switchyard-runner 0.3.0

Configured routing execution for Switchyard serving surfaces
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Schema-neutral algorithm configuration and construction.

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::path::PathBuf;
use std::sync::Arc;

use libsy::{
    AdvisorGate, AdvisorGateConfig, Algorithm, ClassifierContractConfig, ClassifierResponseFormat,
    ClassifyTrigger, CompositeRouter, CompositeRouterConfig, CustomClassifierConfig,
    CustomClassifierPolicy, EscalationJudgeConfig, GateTrigger, HandoffNoteConfig,
    LlmClassifierConfig, LlmFallback, LlmTaskClassifier, Noop, Passthrough, PickerMode,
    PlanExecute, PlanExecuteConfig, Random, StageRouter, StageRouterConfig, SubagentRouter,
    SubagentRouterConfig, TaskClassifierConfig, ToolSemantics,
};
use serde::Deserialize;
use switchyard_protocol::{Category, ModelId};

/// Error returned when an algorithm description cannot be constructed.
#[derive(Debug)]
pub struct AlgorithmConfigError {
    message: String,
    source: Option<Box<dyn Error + Send + Sync>>,
}

impl AlgorithmConfigError {
    fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            source: None,
        }
    }

    fn with_source(message: impl Into<String>, source: impl Error + Send + Sync + 'static) -> Self {
        Self {
            message: message.into(),
            source: Some(Box::new(source)),
        }
    }
}

impl Display for AlgorithmConfigError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl Error for AlgorithmConfigError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.source.as_deref().map(|source| source as _)
    }
}

type AlgorithmResult<T> = Result<T, AlgorithmConfigError>;

/// How a custom classifier turns the judge's JSON verdict into a target.
#[derive(Clone, Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum ClassifierPolicyConfig {
    /// Reads the target name straight out of the judge's verdict.
    TargetSelector {
        /// JSON Pointer to the name, such as `/decision/target`.
        selector: String,
    },
}

/// Which of the three `llm_classifier` behaviors a route uses.
#[derive(Clone, Copy, Debug, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ClassifierMode {
    /// Judges the request first, then serves the strong or weak target.
    Capability,
    /// Serves the weak target first and judges the finished turn, moving to the
    /// strong target once the session latches.
    Escalation,
    /// Judges against your own JSON schema and routes to any configured target.
    Custom,
}

impl ClassifierPolicyConfig {
    fn into_libsy(self) -> CustomClassifierPolicy {
        match self {
            Self::TargetSelector { selector } => CustomClassifierPolicy::target_selector(selector),
        }
    }
}

#[derive(Clone, Debug)]
enum LlmClassifierModeConfig {
    Capability(CapabilityClassifierRouteConfig),
    Escalation(EscalationClassifierRouteConfig),
    Custom(CustomClassifierRouteConfig),
}

#[derive(Clone, Debug)]
struct CapabilityClassifierRouteConfig {
    classifier_target: String,
    strong_target: String,
    weak_target: String,
    base_threshold: f64,
    threshold_step: f64,
    classify_trigger: ClassifyTrigger,
    message_hash_fallback: bool,
    recent_turn_window: Option<usize>,
    prompt: Option<String>,
    response_format_type: ClassifierResponseFormat,
    max_output_tokens: u64,
}

#[derive(Clone, Debug)]
struct EscalationClassifierRouteConfig {
    classifier_target: String,
    strong_target: String,
    weak_target: String,
    prompt: Option<String>,
    response_format_type: ClassifierResponseFormat,
    max_output_tokens: u64,
    judge: EscalationJudgeConfig,
}

#[derive(Clone, Debug)]
struct CustomClassifierRouteConfig {
    models: CategoryModelConfig,
    default_target: Category,
    prompt: String,
    response_schema: String,
    policy: ClassifierPolicyConfig,
    classify_trigger: ClassifyTrigger,
    message_hash_fallback: bool,
    recent_turn_window: Option<usize>,
    max_output_tokens: u64,
}

/// Runtime model groups for a custom classifier, keyed by group name.
///
/// `any` and `judge` are required; `capable` and `efficient` carry tier meaning
/// when present. Any other key is a deployment-defined group the policy may
/// select by name, which is what lets one route choose between more than two
/// models. Ordered so error messages and derived target lists do not depend on
/// hash iteration.
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(transparent)]
pub struct CategoryModelConfig(BTreeMap<String, Vec<String>>);

impl CategoryModelConfig {
    fn validate(&self, route_name: &str, default_target: &Category) -> AlgorithmResult<()> {
        for category in [Category::Any, Category::Judge] {
            if self.get(&category).is_empty() {
                return Err(AlgorithmConfigError::new(format!(
                    "llm_classifier route {route_name} models.{} must contain at least one target",
                    category.as_str()
                )));
            }
        }
        if self.get(default_target).is_empty() {
            return Err(AlgorithmConfigError::new(format!(
                "llm_classifier route {route_name} models.{} must contain at least one target because it is the default_target",
                default_target.as_str()
            )));
        }
        // Every group name parses, so a typo would otherwise build fine and then
        // abstain on every request. `any` is the fallback pool the router checks
        // the selected target against, so a group outside it can never be served.
        let any = self.get(&Category::Any);
        for (name, models) in &self.0 {
            if name == Category::Judge.as_str() || name == Category::Any.as_str() {
                continue;
            }
            if let Some(missing) = models.iter().find(|model| !any.contains(model)) {
                return Err(AlgorithmConfigError::new(format!(
                    "llm_classifier route {route_name} models.{name} lists target {missing}, which must also appear in models.any"
                )));
            }
        }
        Ok(())
    }

    fn get(&self, category: &Category) -> &[String] {
        self.0.get(category.as_str()).map_or(&[], Vec::as_slice)
    }

    /// Every configured target name, judge included.
    fn all_names(&self) -> Vec<&str> {
        Self::deduped(self.0.values().flatten())
    }

    /// The completion targets: every group except the judge's own candidates.
    ///
    /// `any` leads because it is the deployment's stated fallback order, and
    /// callers read this order to pick a route's representative target.
    fn routing_names(&self) -> Vec<&str> {
        let others = self
            .0
            .iter()
            .filter(|(name, _)| {
                *name != Category::Judge.as_str() && *name != Category::Any.as_str()
            })
            .flat_map(|(_, models)| models);
        Self::deduped(self.get(&Category::Any).iter().chain(others))
    }

    fn deduped<'a>(names: impl Iterator<Item = &'a String>) -> Vec<&'a str> {
        let mut seen = BTreeSet::new();
        names
            .map(String::as_str)
            .filter(|name| seen.insert(*name))
            .collect()
    }

    fn groups(&self) -> impl Iterator<Item = (Category, Vec<String>)> + '_ {
        self.0
            .iter()
            .filter_map(|(name, models)| Some((name.parse::<Category>().ok()?, models.clone())))
    }
}

/// Settings for an `llm_classifier` route. Which fields are required depends on
/// the [`ClassifierMode`]; using a field from the wrong mode is an error.
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct LlmClassifierRouteConfig {
    /// Target the judge is called through. Never a routing destination itself.
    pub classifier_target: String,
    /// Mode to run. Defaults to escalation when `escalation` is set, otherwise capability.
    pub mode: Option<ClassifierMode>,
    /// Capability and escalation modes: the capable tier.
    pub strong_target: Option<String>,
    /// Capability and escalation modes: the efficient tier.
    pub weak_target: Option<String>,
    /// Capability mode: lowest solve probability that still routes to the weak
    /// target, from 0 to 1.
    pub base_threshold: Option<f64>,
    /// Capability mode: how much to raise the threshold when the judge is
    /// uncertain. Added once for an uncertain verdict and twice for unsupported.
    pub threshold_step: Option<f64>,
    /// How often the judge runs: every request, once per user turn, or once per session.
    pub classify_trigger: ClassifyTrigger,
    /// Reuses the session's target by hashing the first user message when no
    /// session ID is available. Needs `classify_trigger = "new_session"`.
    pub message_hash_fallback: bool,
    /// How many trailing turns the judge sees. Unset shows it the opening task
    /// and the latest user follow-up only.
    pub recent_turn_window: Option<usize>,
    /// Replaces the packaged judge prompt. Required in custom mode.
    pub prompt: Option<String>,
    /// How the judge is asked for structured output. Use `json_object` when the
    /// provider cannot do JSON Schema.
    pub response_format_type: ClassifierResponseFormat,
    /// Most completion tokens the judge verdict may use.
    #[serde(default = "default_classifier_max_output_tokens")]
    pub max_output_tokens: u64,
    /// Escalation mode: how many escalate verdicts latch the session, and how
    /// much of the transcript the judge sees.
    pub escalation: Option<EscalationJudgeConfig>,
    /// Custom mode: runtime model groups.
    pub models: Option<CategoryModelConfig>,
    /// Custom mode: category used when the judge fails or its verdict cannot be routed.
    pub default_target: Option<String>,
    /// Custom mode: JSON Schema the verdict must match, written as a string.
    pub response_schema: Option<String>,
    /// Custom mode: how to read the chosen target out of the verdict.
    pub policy: Option<ClassifierPolicyConfig>,
}

/// Routing policy applied only to delegated sub-agent work, nested inside a
/// `passthrough` or `stage_router` route.
#[derive(Clone, Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum SubagentRouteConfig {
    /// Sends all sub-agent work to one target.
    Passthrough {
        /// Target that serves sub-agent requests.
        target: String,
    },
    /// Judges each sub-agent request. Only [`ClassifierMode::Custom`] is supported here.
    LlmClassifier(Box<LlmClassifierRouteConfig>),
}

impl SubagentRouteConfig {
    fn routing_target_names(&self) -> Vec<&str> {
        match self {
            Self::Passthrough { target } => vec![target],
            Self::LlmClassifier(classifier) => classifier
                .models
                .as_ref()
                .map(CategoryModelConfig::routing_names)
                .unwrap_or_default(),
        }
    }

    fn judge_target_names(&self) -> Vec<&str> {
        match self {
            Self::Passthrough { .. } => Vec::new(),
            Self::LlmClassifier(classifier) => classifier
                .models
                .as_ref()
                .map(|models| models.get(&Category::Judge))
                .unwrap_or_default()
                .iter()
                .map(String::as_str)
                .collect(),
        }
    }
}

/// A routing algorithm described by configured target names.
#[derive(Clone, Debug, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum AlgorithmSpec {
    /// Replies `OK` without calling any model. Useful for smoke tests.
    Noop {},
    /// Splits traffic across several targets.
    Random {
        /// Target names to choose from.
        targets: Vec<String>,
        /// Relative weights in `targets` order. Equal weights when unset.
        weights: Option<Vec<f64>>,
        /// Makes the sequence of choices repeatable.
        seed: Option<u64>,
    },
    /// Sends every request to one target.
    Passthrough {
        /// Target that serves the request.
        target: String,
        /// Separate policy for delegated sub-agent work.
        #[serde(default)]
        subagents: Option<SubagentRouteConfig>,
    },
    /// Plans on the capable target, then permanently hands off after the first mutation.
    PlanExecute {
        /// Target used before the first edit or write.
        capable_target: String,
        /// Target used from the first edit or write onward.
        efficient_target: String,
        /// Replaces the built-in planning instruction.
        #[serde(default)]
        planning_prompt: Option<String>,
        /// Appends an instruction to the handoff request.
        #[serde(default)]
        handoff_prompt: Option<String>,
        /// Replays visible planner reasoning summaries as assistant text at handoff.
        #[serde(default)]
        planner_reasoning_as_text: bool,
    },
    /// Asks a judge model which target should serve the request.
    LlmClassifier {
        /// Judge and tier settings, written directly in the route table.
        #[serde(flatten)]
        config: LlmClassifierRouteConfig,
    },
    /// Picks a tier per turn by scoring signals from recent tool results.
    StageRouter {
        #[serde(flatten)]
        tiers: StageTierConfig,
        /// Tier to use when the signals are not confident.
        picker: PickerMode,
        /// Judge consulted for turns the tool signals cannot decide.
        #[serde(default)]
        classifier: Option<StageClassifierConfig>,
        /// Separate policy for delegated sub-agent work.
        #[serde(default)]
        subagents: Option<SubagentRouteConfig>,
    },
    /// Picks a routing strategy automatically, preset with recommended knobs.
    /// Currently a `stage_router` with `picker = "efficient_first"` and
    /// `confidence_threshold = 0.5`; change `build_algorithm`'s `Auto` arm to
    /// repoint it at a different algorithm or preset.
    Auto {
        /// The capable tier.
        capable_target: String,
        /// The efficient tier.
        efficient_target: String,
    },
    /// A judge picks the tier at each user turn; a stage router runs the turns within it.
    Composite {
        /// Judge that picks the tier. Called through its own target.
        classifier: StageClassifierConfig,
        /// The stage router the judge hands off to.
        stage: StageTierConfig,
        /// Separate policy for delegated sub-agent work.
        #[serde(default)]
        subagents: Option<SubagentRouteConfig>,
    },
    /// Serves every turn from one target, and has a second model review some of
    /// those turns before the caller sees them.
    Advisor {
        /// Serves every client-visible turn.
        executor_target: String,
        /// Reviews gated turns. Never a routing destination.
        advisor_target: String,
        /// Replaces the built-in APPROVE/REDO reviewer prompt.
        #[serde(default)]
        reviewer_system_prompt: Option<String>,
        /// Replaces the built-in text put in front of a REDO plan.
        #[serde(default)]
        redo_feedback_prefix: Option<String>,
        /// What fires a review.
        #[serde(default)]
        gate_trigger: AdvisorTriggerConfig,
        /// Regular expression for the `pattern` trigger. Required by it, and unused otherwise.
        #[serde(default)]
        gate_trigger_pattern: Option<String>,
        /// How many reviews one session may spend.
        #[serde(default = "default_max_reviews")]
        max_reviews: u32,
        /// Reviews a turn after this many assistant turns, as a mid-task
        /// checkpoint. Zero turns the checkpoint off.
        #[serde(default)]
        gate_stall_turns: u32,
        /// Tool results a turn needs before it can be reviewed. Skips early chatty turns.
        #[serde(default)]
        gate_min_tool_results: u32,
        /// Most output tokens one review may use.
        #[serde(default = "default_advisor_max_tokens")]
        advisor_max_tokens: u64,
        /// Sampling temperature for reviews. Left off the request when unset.
        #[serde(default)]
        advisor_temperature: Option<f64>,
        /// Size cap on the transcript sent to the advisor. Longer transcripts
        /// are trimmed from the middle.
        #[serde(default = "default_transcript_max_chars")]
        transcript_max_chars: usize,
        /// Lets the turn through when the advisor fails, instead of erroring.
        #[serde(default = "default_fail_open")]
        fail_open: bool,
    },
    /// Routes using a checkpoint-backed prefill classifier.
    PrefillRouter {
        /// Target names in checkpoint output order.
        targets: Vec<String>,
        /// Tensor-only router checkpoint path.
        checkpoint: PathBuf,
        /// PyTorch device used for encoder inference, such as `cpu`, `cuda`, or
        /// `cuda:0`. Auto-detected when omitted.
        device: Option<String>,
        /// Directory where Hugging Face caches the downloaded encoder and tokenizer.
        cache_dir: Option<PathBuf>,
        /// Maximum tokenized encoder input length; longer prompts are truncated.
        max_length: Option<usize>,
        /// Maximum prompts per encoder forward pass.
        batch_size: Option<usize>,
    },
}

/// What fires an advisor route's review.
#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum AdvisorTriggerConfig {
    /// The executor's first turn without tool calls.
    #[default]
    NoToolCall,
    /// The first turn whose text matches `gate_trigger_pattern`.
    Pattern,
}

/// The judge a `stage_router` route falls through to, and how it routes.
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StageClassifierConfig {
    /// Target the judge is called through. Not a routing destination.
    pub target: String,
    /// Lowest solve probability that still routes to the efficient tier, from 0 to 1.
    pub base_threshold: f64,
    /// How much to raise the threshold when the judge is uncertain. Added once
    /// for an uncertain verdict and twice for unsupported.
    #[serde(default)]
    pub threshold_step: f64,
    /// How often the judge runs. `new_session` has no effect here.
    #[serde(default)]
    pub classify_trigger: ClassifyTrigger,
    /// Reuses the session's target by hashing the first user message when no
    /// session ID is available.
    #[serde(default)]
    pub message_hash_fallback: bool,
    /// How many trailing turns the judge sees. Unset shows it the opening task
    /// and the latest user follow-up only.
    #[serde(default)]
    pub recent_turn_window: Option<usize>,
    /// Replaces the packaged judge prompt.
    #[serde(default)]
    pub prompt: Option<String>,
    /// How the judge is asked for structured output. Use `json_object` when the
    /// provider cannot do JSON Schema.
    #[serde(default)]
    pub response_format_type: ClassifierResponseFormat,
    /// Most completion tokens the judge verdict may use.
    #[serde(default = "default_classifier_max_output_tokens")]
    pub max_output_tokens: u64,
}

/// The tier pair and scoring settings shared by every stage-router-backed route.
///
/// `deny_unknown_fields` here is what rejects a typo on a flattened `stage_router`
/// route, since the enum's own `deny_unknown_fields` does not apply through a flatten.
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StageTierConfig {
    /// The capable tier.
    pub capable_target: String,
    /// The efficient tier.
    pub efficient_target: String,
    /// How much agreement a decisive pick needs, from 0 to 1.
    pub confidence_threshold: f64,
    /// How many trailing tool results the signals are scored over.
    #[serde(default)]
    pub recent_turn_window: Option<usize>,
    /// Exact tool-name semantics added to the built-in stage vocabulary.
    #[serde(default)]
    pub tool_semantics: ToolSemantics,
    /// Requests to keep on the capable tier after an escalation.
    #[serde(default)]
    pub capable_hold_turns: Option<u32>,
    /// Notes handed to a tier when the router switches to it.
    #[serde(default)]
    pub handoff_notes: Option<HandoffNoteConfig>,
}

impl StageClassifierConfig {
    fn task_classifier_config(&self) -> TaskClassifierConfig {
        TaskClassifierConfig {
            base_threshold: self.base_threshold,
            threshold_step: self.threshold_step,
            classify_trigger: self.classify_trigger,
            message_hash_fallback: self.message_hash_fallback,
            recent_turn_window: self.recent_turn_window,
            contract: classifier_contract(self.prompt.as_deref())
                .with_response_format_type(self.response_format_type),
            max_output_tokens: self.max_output_tokens,
        }
    }
}

impl AlgorithmSpec {
    /// Completion targets in algorithm order; judge-only targets are excluded.
    pub fn routing_target_names(&self) -> Vec<&str> {
        match self {
            Self::Noop { .. } => Vec::new(),
            Self::Random { targets, .. } => targets.iter().map(String::as_str).collect(),
            Self::Passthrough {
                target, subagents, ..
            } => {
                let mut names = vec![target.as_str()];
                if let Some(subagents) = subagents {
                    names.extend(subagents.routing_target_names());
                }
                names
            }
            Self::PlanExecute {
                capable_target,
                efficient_target,
                ..
            } => vec![capable_target.as_str(), efficient_target.as_str()],
            Self::LlmClassifier { config, .. } => match config.classifier_mode() {
                ClassifierMode::Capability => config
                    .weak_target
                    .iter()
                    .chain(&config.strong_target)
                    .map(String::as_str)
                    .collect(),
                ClassifierMode::Escalation => config
                    .strong_target
                    .iter()
                    .chain(&config.weak_target)
                    .map(String::as_str)
                    .collect(),
                ClassifierMode::Custom => config
                    .models
                    .as_ref()
                    .map(CategoryModelConfig::routing_names)
                    .unwrap_or_default(),
            },
            Self::StageRouter {
                tiers, subagents, ..
            } => {
                let mut names = vec![
                    tiers.capable_target.as_str(),
                    tiers.efficient_target.as_str(),
                ];
                if let Some(subagents) = subagents {
                    names.extend(subagents.routing_target_names());
                }
                names
            }
            Self::Auto {
                capable_target,
                efficient_target,
            } => vec![capable_target.as_str(), efficient_target.as_str()],
            Self::Composite {
                stage, subagents, ..
            } => {
                let mut names = vec![
                    stage.capable_target.as_str(),
                    stage.efficient_target.as_str(),
                ];
                if let Some(subagents) = subagents {
                    names.extend(subagents.routing_target_names());
                }
                names
            }
            // The advisor is judge-only: reviews go through its own client,
            // so it is not a completion (or count_tokens) destination.
            Self::Advisor {
                executor_target, ..
            } => vec![executor_target],
            Self::PrefillRouter { targets, .. } => targets.iter().map(String::as_str).collect(),
        }
    }

    /// Every target the algorithm may call, including judge-only targets.
    ///
    /// [`routing_target_names`](Self::routing_target_names) covers completion destinations;
    /// a classifier also calls its judge, and that call needs a client too.
    pub fn callable_target_names(&self) -> Vec<&str> {
        let mut names = self.routing_target_names();
        match self {
            // Custom mode names its judge in `models.judge`; the other two modes
            // use the top-level `classifier_target`.
            Self::LlmClassifier { config, .. } => {
                if matches!(config.classifier_mode(), ClassifierMode::Custom) {
                    names.extend(
                        config
                            .models
                            .as_ref()
                            .map(|models| models.get(&Category::Judge))
                            .unwrap_or_default()
                            .iter()
                            .map(String::as_str),
                    );
                } else {
                    names.push(&config.classifier_target);
                }
            }
            Self::StageRouter {
                classifier: Some(classifier),
                ..
            } => names.push(&classifier.target),
            Self::Composite { classifier, .. } => {
                names.push(&classifier.target);
            }
            Self::Advisor { advisor_target, .. } => names.push(advisor_target),
            _ => {}
        }
        // A sub-agent classifier calls its own judge, which is never a completion target.
        if let Self::Passthrough {
            subagents: Some(subagents),
            ..
        }
        | Self::StageRouter {
            subagents: Some(subagents),
            ..
        }
        | Self::Composite {
            subagents: Some(subagents),
            ..
        } = self
        {
            names.extend(subagents.judge_target_names());
        }
        names
    }

    /// Target names grouped as the runtime [`Driver`](libsy::Driver) expects them.
    pub(crate) fn runtime_model_names(
        &self,
        route_name: &str,
    ) -> AlgorithmResult<RuntimeModelNames> {
        let parent = match self {
            Self::Noop { .. } => HashMap::new(),
            Self::Random { targets, .. } | Self::PrefillRouter { targets, .. } => {
                category_models([(Category::Any, targets.clone())])
            }
            Self::Passthrough { target, .. } => {
                category_models([(Category::Any, vec![target.clone()])])
            }
            Self::PlanExecute {
                capable_target,
                efficient_target,
                ..
            } => category_models([
                (Category::Capable, vec![capable_target.clone()]),
                (Category::Efficient, vec![efficient_target.clone()]),
                (
                    Category::Any,
                    vec![capable_target.clone(), efficient_target.clone()],
                ),
            ]),
            Self::LlmClassifier { config } => {
                classifier_runtime_model_names(config.validated_classifier_mode(route_name)?)
            }
            Self::StageRouter {
                tiers, classifier, ..
            } => {
                let mut models = category_models([
                    (Category::Capable, vec![tiers.capable_target.clone()]),
                    (Category::Efficient, vec![tiers.efficient_target.clone()]),
                    (
                        Category::Any,
                        vec![tiers.capable_target.clone(), tiers.efficient_target.clone()],
                    ),
                ]);
                if let Some(classifier) = classifier {
                    models.insert(Category::Judge, vec![classifier.target.clone()]);
                }
                models
            }
            Self::Auto {
                capable_target,
                efficient_target,
            } => category_models([
                (Category::Capable, vec![capable_target.clone()]),
                (Category::Efficient, vec![efficient_target.clone()]),
                (
                    Category::Any,
                    vec![capable_target.clone(), efficient_target.clone()],
                ),
            ]),
            Self::Composite {
                classifier, stage, ..
            } => category_models([
                (Category::Judge, vec![classifier.target.clone()]),
                (Category::Capable, vec![stage.capable_target.clone()]),
                (Category::Efficient, vec![stage.efficient_target.clone()]),
                (
                    Category::Any,
                    vec![stage.capable_target.clone(), stage.efficient_target.clone()],
                ),
            ]),
            Self::Advisor {
                executor_target,
                advisor_target,
                ..
            } => category_models([
                (Category::Efficient, vec![executor_target.clone()]),
                (Category::Any, vec![executor_target.clone()]),
                (Category::Judge, vec![advisor_target.clone()]),
            ]),
        };

        let subagents = match self {
            Self::Passthrough { subagents, .. }
            | Self::StageRouter { subagents, .. }
            | Self::Composite { subagents, .. } => subagents.as_ref(),
            _ => None,
        };
        // Sub-agent groups stay separate from the parent's. Merging them would let a
        // sub-agent's `capable` resolve to the parent's, and would put models only the
        // sub-agents were given into the parent's `Any` fallback list.
        let subagent = subagents
            .map(|subagents| subagent_runtime_model_names(subagents, route_name))
            .transpose()?;
        Ok(RuntimeModelNames { parent, subagent })
    }

    /// Response target and routing-only dependency for routers that answer while routing.
    pub(crate) fn routing_response_and_dependency(&self) -> Option<(&str, &str)> {
        match self {
            Self::LlmClassifier { config, .. }
                if matches!(config.classifier_mode(), ClassifierMode::Escalation) =>
            {
                Some((
                    config.weak_target.as_deref()?,
                    config.classifier_target.as_str(),
                ))
            }
            Self::Advisor {
                executor_target,
                advisor_target,
                ..
            } => Some((executor_target, advisor_target)),
            Self::Noop { .. }
            | Self::Random { .. }
            | Self::Passthrough { .. }
            | Self::PlanExecute { .. }
            | Self::LlmClassifier { .. }
            | Self::StageRouter { .. }
            | Self::Auto { .. }
            | Self::Composite { .. }
            | Self::PrefillRouter { .. } => None,
        }
    }

    /// Builds this algorithm after resolving configured target names.
    pub fn build(
        &self,
        context: &str,
        targets: &BTreeMap<String, ModelId>,
    ) -> AlgorithmResult<Arc<dyn Algorithm>> {
        build_algorithm(context, self, targets)
    }
}

/// One route's target names, grouped by category and by routing scope.
pub(crate) struct RuntimeModelNames {
    /// Groups the algorithm itself routes over.
    pub(crate) parent: HashMap<Category, Vec<String>>,
    /// Groups delegated sub-agent work routes over, when the route has a `subagents` table.
    pub(crate) subagent: Option<HashMap<Category, Vec<String>>>,
}

fn category_models(
    entries: impl IntoIterator<Item = (Category, Vec<String>)>,
) -> HashMap<Category, Vec<String>> {
    entries.into_iter().collect()
}

fn custom_runtime_model_names(config: &CategoryModelConfig) -> HashMap<Category, Vec<String>> {
    config.groups().collect()
}

fn classifier_runtime_model_names(
    config: LlmClassifierModeConfig,
) -> HashMap<Category, Vec<String>> {
    match config {
        LlmClassifierModeConfig::Capability(config) => category_models([
            (Category::Judge, vec![config.classifier_target]),
            (Category::Efficient, vec![config.weak_target.clone()]),
            (Category::Capable, vec![config.strong_target.clone()]),
            (
                Category::Any,
                vec![config.weak_target, config.strong_target],
            ),
        ]),
        LlmClassifierModeConfig::Escalation(config) => category_models([
            (Category::Judge, vec![config.classifier_target]),
            (Category::Efficient, vec![config.weak_target.clone()]),
            (Category::Capable, vec![config.strong_target.clone()]),
            (
                Category::Any,
                vec![config.strong_target, config.weak_target],
            ),
        ]),
        LlmClassifierModeConfig::Custom(config) => custom_runtime_model_names(&config.models),
    }
}

fn subagent_runtime_model_names(
    config: &SubagentRouteConfig,
    route_name: &str,
) -> AlgorithmResult<HashMap<Category, Vec<String>>> {
    match config {
        SubagentRouteConfig::Passthrough { target } => {
            Ok(category_models([(Category::Any, vec![target.clone()])]))
        }
        SubagentRouteConfig::LlmClassifier(config) => {
            let LlmClassifierModeConfig::Custom(config) =
                config.validated_classifier_mode(route_name)?
            else {
                return Err(AlgorithmConfigError::new(format!(
                    "route {route_name}: subagents llm_classifier only supports mode custom"
                )));
            };
            Ok(custom_runtime_model_names(&config.models))
        }
    }
}
impl LlmClassifierRouteConfig {
    fn classifier_mode(&self) -> ClassifierMode {
        let default = if self.escalation.is_some() {
            ClassifierMode::Escalation
        } else {
            ClassifierMode::Capability
        };
        self.mode.unwrap_or(default)
    }

    fn validated_classifier_mode(
        &self,
        route_name: &str,
    ) -> AlgorithmResult<LlmClassifierModeConfig> {
        let Self {
            classifier_target,
            mode,
            strong_target,
            weak_target,
            base_threshold,
            threshold_step,
            classify_trigger,
            message_hash_fallback,
            recent_turn_window,
            prompt,
            response_format_type,
            max_output_tokens,
            escalation,
            models,
            default_target,
            response_schema,
            policy,
        } = self;

        let selected_mode = match (mode, escalation.is_some()) {
            (Some(mode), _) => *mode,
            (None, true) => ClassifierMode::Escalation,
            (None, false) => ClassifierMode::Capability,
        };

        match selected_mode {
            ClassifierMode::Capability => {
                if escalation.is_some() {
                    return Err(classifier_field_error(
                        route_name,
                        "escalation",
                        "capability",
                    ));
                }
                reject_custom_fields(
                    route_name,
                    "capability",
                    models,
                    default_target,
                    response_schema,
                    policy,
                )?;
                Ok(LlmClassifierModeConfig::Capability(
                    CapabilityClassifierRouteConfig {
                        classifier_target: classifier_target.clone(),
                        strong_target: required_classifier_field(
                            route_name,
                            "strong_target",
                            strong_target,
                        )?,
                        weak_target: required_classifier_field(
                            route_name,
                            "weak_target",
                            weak_target,
                        )?,
                        base_threshold: required_classifier_field(
                            route_name,
                            "base_threshold",
                            base_threshold,
                        )?,
                        threshold_step: threshold_step.unwrap_or_default(),
                        classify_trigger: *classify_trigger,
                        message_hash_fallback: *message_hash_fallback,
                        recent_turn_window: *recent_turn_window,
                        prompt: prompt.clone(),
                        response_format_type: *response_format_type,
                        max_output_tokens: *max_output_tokens,
                    },
                ))
            }
            ClassifierMode::Escalation => {
                reject_custom_fields(
                    route_name,
                    "escalation",
                    models,
                    default_target,
                    response_schema,
                    policy,
                )?;
                if *classify_trigger != ClassifyTrigger::EveryRequest {
                    return Err(AlgorithmConfigError::new(format!(
                        "llm_classifier route {route_name} mode escalation cannot use classify_trigger"
                    )));
                }
                if mode.is_some()
                    && (base_threshold.is_some()
                        || threshold_step.is_some()
                        || *message_hash_fallback
                        || recent_turn_window.is_some())
                {
                    return Err(AlgorithmConfigError::new(format!(
                        "llm_classifier route {route_name} mode escalation cannot use capability routing settings"
                    )));
                }
                Ok(LlmClassifierModeConfig::Escalation(
                    EscalationClassifierRouteConfig {
                        classifier_target: classifier_target.clone(),
                        strong_target: required_classifier_field(
                            route_name,
                            "strong_target",
                            strong_target,
                        )?,
                        weak_target: required_classifier_field(
                            route_name,
                            "weak_target",
                            weak_target,
                        )?,
                        prompt: prompt.clone(),
                        response_format_type: *response_format_type,
                        max_output_tokens: *max_output_tokens,
                        judge: required_classifier_field(route_name, "escalation", escalation)?,
                    },
                ))
            }
            ClassifierMode::Custom => {
                if !classifier_target.is_empty()
                    || strong_target.is_some()
                    || weak_target.is_some()
                    || base_threshold.is_some()
                    || threshold_step.is_some()
                    || escalation.is_some()
                    || *response_format_type != ClassifierResponseFormat::JsonSchema
                {
                    return Err(AlgorithmConfigError::new(format!(
                        "llm_classifier route {route_name} mode custom cannot use capability or escalation fields and response_format_type must be 'json_schema'"
                    )));
                }
                let models = required_classifier_field(route_name, "models", models)?;
                let default_target: Category = required_classifier_field(
                    route_name,
                    "default_target",
                    default_target,
                )?
                .parse()
                .map_err(|error| {
                    AlgorithmConfigError::new(format!(
                        "llm_classifier route {route_name} has invalid default_target: {error}"
                    ))
                })?;
                if default_target == Category::Judge {
                    return Err(AlgorithmConfigError::new(format!(
                        "llm_classifier route {route_name} default_target cannot be judge"
                    )));
                }
                models.validate(route_name, &default_target)?;
                Ok(LlmClassifierModeConfig::Custom(
                    CustomClassifierRouteConfig {
                        models,
                        default_target,
                        prompt: required_classifier_field(route_name, "prompt", prompt)?,
                        response_schema: required_classifier_field(
                            route_name,
                            "response_schema",
                            response_schema,
                        )?,
                        policy: required_classifier_field(route_name, "policy", policy)?,
                        classify_trigger: *classify_trigger,
                        message_hash_fallback: *message_hash_fallback,
                        recent_turn_window: *recent_turn_window,
                        max_output_tokens: *max_output_tokens,
                    },
                ))
            }
        }
    }
}

fn reject_custom_fields(
    route_name: &str,
    mode: &str,
    models: &Option<CategoryModelConfig>,
    default_target: &Option<String>,
    response_schema: &Option<String>,
    policy: &Option<ClassifierPolicyConfig>,
) -> AlgorithmResult<()> {
    if models.is_some() || default_target.is_some() || response_schema.is_some() || policy.is_some()
    {
        return Err(AlgorithmConfigError::new(format!(
            "llm_classifier route {route_name} mode {mode} cannot use custom classifier fields"
        )));
    }
    Ok(())
}

fn classifier_field_error(route_name: &str, field: &str, mode: &str) -> AlgorithmConfigError {
    AlgorithmConfigError::new(format!(
        "llm_classifier route {route_name} mode {mode} cannot use {field}"
    ))
}

fn required_classifier_field<T: Clone>(
    route_name: &str,
    field: &str,
    value: &Option<T>,
) -> AlgorithmResult<T> {
    value.clone().ok_or_else(|| {
        AlgorithmConfigError::new(format!(
            "llm_classifier route {route_name} requires {field}"
        ))
    })
}

fn build_subagent_router_config(
    route_name: &str,
    config: &SubagentRouteConfig,
    targets: &BTreeMap<String, ModelId>,
) -> AlgorithmResult<SubagentRouterConfig> {
    match config {
        SubagentRouteConfig::Passthrough { target } => {
            resolve_target_model_id(route_name, target, targets)?;
            Ok(SubagentRouterConfig::fixed_target())
        }
        SubagentRouteConfig::LlmClassifier(config) => {
            let LlmClassifierModeConfig::Custom(config) =
                config.validated_classifier_mode(route_name)?
            else {
                return Err(AlgorithmConfigError::new(format!(
                    "route {route_name}: subagents llm_classifier only supports mode custom"
                )));
            };
            for name in config.models.all_names() {
                resolve_target_model_id(route_name, name, targets)?;
            }
            if config.models.get(&config.default_target).is_empty() {
                return Err(AlgorithmConfigError::new(format!(
                    "route {route_name}: subagents llm_classifier has no model for default category {}",
                    config.default_target.as_str()
                )));
            }
            let response_schema =
                serde_json::from_str(&config.response_schema).map_err(|error| {
                    AlgorithmConfigError::with_source(
                        format!(
                            "route {route_name}: subagents llm_classifier response_schema is invalid JSON: {error}"
                        ),
                        error,
                    )
                })?;
            warn_single_target_classifier(route_name, &config.models);
            let mut classifier_config = CustomClassifierConfig::new(
                config.prompt,
                response_schema,
                config.policy.into_libsy(),
            );
            classifier_config.recent_turn_window = config.recent_turn_window;
            classifier_config.max_output_tokens = config.max_output_tokens;
            let classifier = Arc::new(
                LlmTaskClassifier::new(LlmClassifierConfig::Custom {
                    default_target: config.default_target.clone(),
                    config: classifier_config,
                })
                .map_err(|error| {
                    AlgorithmConfigError::with_source(
                        format!("route {route_name}: subagents llm_classifier: {error}"),
                        error,
                    )
                })?,
            );
            Ok(SubagentRouterConfig {
                classifier,
                default_target: config.default_target,
                classify_trigger: config.classify_trigger,
                message_hash_fallback: config.message_hash_fallback,
            })
        }
    }
}

fn attach_subagent_router(
    route_name: &str,
    parent: Arc<dyn Algorithm>,
    config: Option<&SubagentRouteConfig>,
    targets: &BTreeMap<String, ModelId>,
) -> AlgorithmResult<Arc<dyn Algorithm>> {
    let Some(config) = config else {
        return Ok(parent);
    };
    let config = build_subagent_router_config(route_name, config, targets)?;
    let algorithm = SubagentRouter::new(parent, config).map_err(|error| {
        AlgorithmConfigError::with_source(
            format!("route {route_name}: subagent routing: {error}"),
            error,
        )
    })?;
    Ok(Arc::new(algorithm))
}

fn build_algorithm(
    route_name: &str,
    config: &AlgorithmSpec,
    targets: &BTreeMap<String, ModelId>,
) -> AlgorithmResult<Arc<dyn Algorithm>> {
    match config {
        AlgorithmSpec::Noop { .. } => Ok(Arc::new(Noop {})),
        AlgorithmSpec::Random {
            targets: names,
            weights,
            seed,
        } => {
            // The algorithm only sees its targets at request time, so a bad pairing
            // would otherwise fail every request instead of failing to start.
            if let Some(weights) = weights
                && weights.len() != names.len()
            {
                return Err(AlgorithmConfigError::new(format!(
                    "random route {route_name}: expected {} weights, got {}",
                    names.len(),
                    weights.len()
                )));
            }
            let mut seen = BTreeSet::new();
            if let Some(duplicate) = names.iter().find(|name| !seen.insert(*name)) {
                return Err(AlgorithmConfigError::new(format!(
                    "random route {route_name}: targets must be unique, {duplicate} is repeated"
                )));
            }
            let algorithm = Random::new(weights.clone(), *seed).map_err(|error| {
                AlgorithmConfigError::with_source(
                    format!("random route {route_name}: {error}"),
                    error,
                )
            })?;
            Ok(Arc::new(algorithm))
        }
        AlgorithmSpec::Passthrough { subagents, .. } => {
            let algorithm = Passthrough;
            let parent: Arc<dyn Algorithm> = Arc::new(algorithm);
            attach_subagent_router(route_name, parent, subagents.as_ref(), targets)
        }
        AlgorithmSpec::PlanExecute {
            planning_prompt,
            handoff_prompt,
            planner_reasoning_as_text,
            ..
        } => {
            let mut config = PlanExecuteConfig::default();
            if let Some(prompt) = planning_prompt {
                config.planning_prompt = prompt.clone();
            }
            config.handoff_prompt.clone_from(handoff_prompt);
            config.planner_reasoning_as_text = *planner_reasoning_as_text;
            let algorithm = PlanExecute::new(config).map_err(|error| {
                AlgorithmConfigError::with_source(
                    format!("plan_execute route {route_name}: {error}"),
                    error,
                )
            })?;
            Ok(Arc::new(algorithm))
        }
        AlgorithmSpec::LlmClassifier {
            config: classifier_config,
            ..
        } => {
            let mode = classifier_config.validated_classifier_mode(route_name)?;
            let algorithm = match mode {
                LlmClassifierModeConfig::Capability(config) => {
                    let classifier_config = TaskClassifierConfig {
                        base_threshold: config.base_threshold,
                        threshold_step: config.threshold_step,
                        classify_trigger: config.classify_trigger,
                        message_hash_fallback: config.message_hash_fallback,
                        recent_turn_window: config.recent_turn_window,
                        contract: classifier_contract(config.prompt.as_deref())
                            .with_response_format_type(config.response_format_type),
                        max_output_tokens: config.max_output_tokens,
                    };
                    LlmTaskClassifier::new(LlmClassifierConfig::Capability {
                        config: classifier_config,
                    })
                }
                LlmClassifierModeConfig::Escalation(config) => {
                    LlmTaskClassifier::new(LlmClassifierConfig::Escalation {
                        contract: classifier_contract(config.prompt.as_deref())
                            .with_response_format_type(config.response_format_type),
                        config: config.judge,
                        max_output_tokens: config.max_output_tokens,
                    })
                }
                LlmClassifierModeConfig::Custom(config) => {
                    let response_schema = serde_json::from_str(&config.response_schema).map_err(
                        |error| {
                            AlgorithmConfigError::with_source(
                                format!(
                                    "llm_classifier route {route_name}: response_schema is invalid JSON: {error}"
                                ),
                                error,
                            )
                        },
                    )?;
                    warn_single_target_classifier(route_name, &config.models);
                    let mut classifier_config = CustomClassifierConfig::new(
                        config.prompt,
                        response_schema,
                        config.policy.into_libsy(),
                    );
                    classifier_config.classify_trigger = config.classify_trigger;
                    classifier_config.message_hash_fallback = config.message_hash_fallback;
                    classifier_config.recent_turn_window = config.recent_turn_window;
                    classifier_config.max_output_tokens = config.max_output_tokens;
                    LlmTaskClassifier::new(LlmClassifierConfig::Custom {
                        default_target: config.default_target,
                        config: classifier_config,
                    })
                }
            }
            .map_err(|error| {
                AlgorithmConfigError::with_source(
                    format!("llm_classifier route {route_name}: {error}"),
                    error,
                )
            })?;
            Ok(Arc::new(algorithm))
        }
        AlgorithmSpec::StageRouter {
            tiers,
            picker,
            classifier,
            subagents,
            ..
        } => {
            let StageTierConfig {
                confidence_threshold,
                recent_turn_window,
                tool_semantics,
                capable_hold_turns,
                handoff_notes,
                ..
            } = tiers;
            if matches!(picker, PickerMode::CapableFirst) {
                tracing::warn!(
                    "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."
                );
            }
            let mut config = StageRouterConfig::new(*picker, *confidence_threshold);
            config.recent_window = *recent_turn_window;
            if let Some(turns) = capable_hold_turns {
                config.capable_hold_turns = *turns;
            }
            config.tool_semantics = tool_semantics.clone();
            config.handoff_notes = handoff_notes.clone();
            // The judge is called through its own target, so it is not a routing
            // destination and stays out of the tier pair.
            config.llm_fallback = classifier.as_ref().map(|classifier| LlmFallback {
                config: classifier.task_classifier_config(),
            });
            let algorithm = StageRouter::new(config).map_err(|error| {
                AlgorithmConfigError::with_source(
                    format!("stage_router route {route_name}: {error}"),
                    error,
                )
            })?;
            let parent: Arc<dyn Algorithm> = Arc::new(algorithm);
            attach_subagent_router(route_name, parent, subagents.as_ref(), targets)
        }
        AlgorithmSpec::Auto { .. } => {
            let config = StageRouterConfig::new(PickerMode::EfficientFirst, 0.5);
            let algorithm = StageRouter::new(config).map_err(|error| {
                AlgorithmConfigError::with_source(
                    format!("auto route {route_name}: {error}"),
                    error,
                )
            })?;
            Ok(Arc::new(algorithm))
        }
        AlgorithmSpec::Composite {
            classifier,
            stage,
            subagents,
        } => {
            let mut stage_config =
                StageRouterConfig::new(PickerMode::EfficientFirst, stage.confidence_threshold);
            stage_config.recent_window = stage.recent_turn_window;
            if let Some(turns) = stage.capable_hold_turns {
                stage_config.capable_hold_turns = turns;
            }
            stage_config.tool_semantics = stage.tool_semantics.clone();
            stage_config.handoff_notes = stage.handoff_notes.clone();
            let config = CompositeRouterConfig {
                judge: classifier.task_classifier_config(),
                stage: stage_config,
            };
            let algorithm = CompositeRouter::new(config).map_err(|error| {
                AlgorithmConfigError::with_source(
                    format!("composite route {route_name}: {error}"),
                    error,
                )
            })?;
            let parent: Arc<dyn Algorithm> = Arc::new(algorithm);
            attach_subagent_router(route_name, parent, subagents.as_ref(), targets)
        }
        AlgorithmSpec::Advisor {
            reviewer_system_prompt,
            redo_feedback_prefix,
            gate_trigger,
            gate_trigger_pattern,
            max_reviews,
            gate_stall_turns,
            gate_min_tool_results,
            advisor_max_tokens,
            advisor_temperature,
            transcript_max_chars,
            fail_open,
            ..
        } => {
            // A pattern set under the default trigger would be silently
            // ignored; reject the misconfiguration instead.
            if *gate_trigger == AdvisorTriggerConfig::NoToolCall && gate_trigger_pattern.is_some() {
                return Err(AlgorithmConfigError::new(format!(
                    "advisor route {route_name}: gate_trigger_pattern requires \
                     gate_trigger = \"pattern\""
                )));
            }
            let mut config = AdvisorGateConfig::default();
            if let Some(prompt) = reviewer_system_prompt {
                config.reviewer_system_prompt = prompt.clone();
            }
            if let Some(prefix) = redo_feedback_prefix {
                config.redo_feedback_prefix = prefix.clone();
            }
            config.gate_trigger = match gate_trigger {
                AdvisorTriggerConfig::NoToolCall => GateTrigger::NoToolCall,
                AdvisorTriggerConfig::Pattern => {
                    GateTrigger::Pattern(gate_trigger_pattern.clone().unwrap_or_default())
                }
            };
            config.max_reviews = *max_reviews;
            config.gate_stall_turns = *gate_stall_turns;
            config.gate_min_tool_results = *gate_min_tool_results;
            config.advisor_max_tokens = *advisor_max_tokens;
            config.advisor_temperature = *advisor_temperature;
            config.transcript_max_chars = *transcript_max_chars;
            config.fail_open = *fail_open;
            let algorithm = AdvisorGate::new(config).map_err(|error| {
                AlgorithmConfigError::with_source(
                    format!("advisor route {route_name}: {error}"),
                    error,
                )
            })?;
            Ok(Arc::new(algorithm))
        }
        AlgorithmSpec::PrefillRouter {
            targets: names,
            checkpoint,
            device,
            cache_dir,
            max_length,
            batch_size,
        } => {
            #[cfg(feature = "prefill-router")]
            {
                let targets = names
                    .iter()
                    .map(|name| resolve_target_model_id(route_name, name, targets))
                    .collect::<AlgorithmResult<Vec<_>>>()?;
                let mut config = prefill_router::PrefillRouterConfig::new(targets, checkpoint);
                config.device.clone_from(device);
                config.cache_dir.clone_from(cache_dir);
                if let Some(max_length) = max_length {
                    config.max_length = *max_length;
                }
                if let Some(batch_size) = batch_size {
                    config.batch_size = *batch_size;
                }
                let algorithm = config.build().map_err(|error| {
                    AlgorithmConfigError::with_source(
                        format!("prefill_router route {route_name}: {error}"),
                        error,
                    )
                })?;
                Ok(Arc::new(algorithm))
            }

            #[cfg(not(feature = "prefill-router"))]
            {
                let _ = (
                    names, checkpoint, device, cache_dir, max_length, batch_size, targets,
                );
                Err(AlgorithmConfigError::new(format!(
                    "prefill_router route {route_name} requires the `prefill-router` Cargo feature"
                )))
            }
        }
    }
}

const fn default_max_reviews() -> u32 {
    1
}

const fn default_advisor_max_tokens() -> u64 {
    2048
}

const fn default_transcript_max_chars() -> usize {
    200_000
}

const fn default_fail_open() -> bool {
    true
}

fn classifier_contract(prompt: Option<&str>) -> ClassifierContractConfig {
    prompt.map_or_else(ClassifierContractConfig::default, |prompt| {
        ClassifierContractConfig::default().with_prompt(prompt)
    })
}

fn default_classifier_max_output_tokens() -> u64 {
    TaskClassifierConfig::default().max_output_tokens
}

fn warn_single_target_classifier(route_name: &str, models: &CategoryModelConfig) {
    if models.routing_names().len() < 2 {
        tracing::warn!(
            route = route_name,
            "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."
        );
    }
}

fn resolve_target_model_id(
    route_name: &str,
    name: &str,
    targets: &BTreeMap<String, ModelId>,
) -> AlgorithmResult<ModelId> {
    targets.get(name).cloned().ok_or_else(|| {
        AlgorithmConfigError::new(format!(
            "route {route_name} references unknown target {name}"
        ))
    })
}