swink-agent 0.12.0

Core scaffolding for running LLM-powered agentic loops
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
1506
1507
1508
1509
1510
1511
1512
use std::sync::OnceLock;

use chrono::NaiveDate;
use serde::Deserialize;

use crate::ModelSpec;
use crate::pricing::CostCalculator;
use crate::types::{AssistantMessage, Cost, ModelCapabilities, ThinkingLevel, Usage};

/// Whether a provider's models run on a remote API or on local hardware.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProviderKind {
    Remote,
    Local,
}

/// How requests to a provider are authenticated.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuthMode {
    Bearer,
    ApiKeyHeader,
    AwsSigv4,
}

/// Provider API version selector used when building request URLs.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ApiVersion {
    V1,
    V1beta,
}

/// A capability a preset's model supports, as declared in the catalog TOML.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PresetCapability {
    Text,
    Tools,
    Thinking,
    ImagesIn,
    Streaming,
    StructuredOutput,
}

/// Release maturity of a preset's model at the provider.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PresetStatus {
    Ga,
    Preview,
    /// The provider has retired (or announced retirement of) this model.
    ///
    /// The preset stays listed so catalog lookups and cost calculation keep
    /// working for historical data, and `replacement_model_id` points
    /// consumers at the successor model when one is known.
    ///
    /// TOML representation (existing string statuses are unaffected):
    ///
    /// ```toml
    /// [providers.presets.status.deprecated]
    /// replacement_model_id = "gpt-5.4"
    /// ```
    Deprecated {
        #[serde(default)]
        replacement_model_id: Option<String>,
    },
}

impl PresetStatus {
    /// Returns `true` for [`PresetStatus::Deprecated`], regardless of whether
    /// a replacement model is recorded.
    #[must_use]
    pub const fn is_deprecated(&self) -> bool {
        matches!(self, Self::Deprecated { .. })
    }
}

/// A single named model preset within a [`ProviderCatalog`], as loaded from the catalog TOML.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct PresetCatalog {
    pub id: String,
    pub display_name: String,
    pub group: Option<String>,
    pub model_id: String,
    pub api_version: Option<ApiVersion>,
    #[serde(default)]
    pub capabilities: Vec<PresetCapability>,
    pub status: Option<PresetStatus>,
    pub context_window_tokens: Option<u64>,
    pub max_output_tokens: Option<u64>,
    #[serde(default)]
    pub include_by_default: bool,
    pub repo_id: Option<String>,
    pub filename: Option<String>,
    #[serde(default)]
    pub cost_per_million_input: Option<f64>,
    #[serde(default)]
    pub cost_per_million_output: Option<f64>,
    #[serde(default)]
    pub cost_per_million_cache_read: Option<f64>,
    #[serde(default)]
    pub cost_per_million_cache_write: Option<f64>,
}

impl PresetCatalog {
    /// Create a preset with the required identifying fields; everything else
    /// starts unset and can be filled in with the `with_*` builders.
    #[must_use]
    pub fn new(
        id: impl Into<String>,
        display_name: impl Into<String>,
        model_id: impl Into<String>,
    ) -> Self {
        Self {
            id: id.into(),
            display_name: display_name.into(),
            group: None,
            model_id: model_id.into(),
            api_version: None,
            capabilities: Vec::new(),
            status: None,
            context_window_tokens: None,
            max_output_tokens: None,
            include_by_default: false,
            repo_id: None,
            filename: None,
            cost_per_million_input: None,
            cost_per_million_output: None,
            cost_per_million_cache_read: None,
            cost_per_million_cache_write: None,
        }
    }

    /// Set the display group this preset is listed under.
    #[must_use]
    pub fn with_group(mut self, group: impl Into<String>) -> Self {
        self.group = Some(group.into());
        self
    }

    /// Set the provider API version used when building request URLs.
    #[must_use]
    pub fn with_api_version(mut self, api_version: ApiVersion) -> Self {
        self.api_version = Some(api_version);
        self
    }

    /// Set the declared capabilities.
    #[must_use]
    pub fn with_capabilities(mut self, capabilities: Vec<PresetCapability>) -> Self {
        self.capabilities = capabilities;
        self
    }

    /// Set the release maturity status.
    #[must_use]
    pub fn with_status(mut self, status: PresetStatus) -> Self {
        self.status = Some(status);
        self
    }

    /// Set the model's context window size, in tokens.
    #[must_use]
    pub const fn with_context_window_tokens(mut self, tokens: u64) -> Self {
        self.context_window_tokens = Some(tokens);
        self
    }

    /// Set the model's maximum output tokens.
    #[must_use]
    pub const fn with_max_output_tokens(mut self, tokens: u64) -> Self {
        self.max_output_tokens = Some(tokens);
        self
    }

    /// Set whether this preset is included by default.
    #[must_use]
    pub const fn with_include_by_default(mut self, include: bool) -> Self {
        self.include_by_default = include;
        self
    }

    /// Set the local model repository identifier.
    #[must_use]
    pub fn with_repo_id(mut self, repo_id: impl Into<String>) -> Self {
        self.repo_id = Some(repo_id.into());
        self
    }

    /// Set the local model file name.
    #[must_use]
    pub fn with_filename(mut self, filename: impl Into<String>) -> Self {
        self.filename = Some(filename.into());
        self
    }

    /// Set the USD-per-million-input-token rate.
    #[must_use]
    pub const fn with_cost_per_million_input(mut self, cost: f64) -> Self {
        self.cost_per_million_input = Some(cost);
        self
    }

    /// Set the USD-per-million-output-token rate.
    #[must_use]
    pub const fn with_cost_per_million_output(mut self, cost: f64) -> Self {
        self.cost_per_million_output = Some(cost);
        self
    }

    /// Set the USD-per-million-cache-read-token rate.
    #[must_use]
    pub const fn with_cost_per_million_cache_read(mut self, cost: f64) -> Self {
        self.cost_per_million_cache_read = Some(cost);
        self
    }

    /// Set the USD-per-million-cache-write-token rate.
    #[must_use]
    pub const fn with_cost_per_million_cache_write(mut self, cost: f64) -> Self {
        self.cost_per_million_cache_write = Some(cost);
        self
    }
}

/// A provider entry in the model catalog, holding its auth/connection settings and presets.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct ProviderCatalog {
    pub key: String,
    pub display_name: String,
    pub kind: ProviderKind,
    pub auth_mode: Option<AuthMode>,
    pub credential_env_var: Option<String>,
    pub base_url_env_var: Option<String>,
    pub default_base_url: Option<String>,
    #[serde(default)]
    pub requires_base_url: bool,
    pub region_env_var: Option<String>,
    #[serde(default)]
    pub presets: Vec<PresetCatalog>,
}

impl ProviderCatalog {
    /// Create a provider entry with the required identifying fields; everything
    /// else starts unset and can be filled in with the `with_*` builders.
    #[must_use]
    pub fn new(
        key: impl Into<String>,
        display_name: impl Into<String>,
        kind: ProviderKind,
    ) -> Self {
        Self {
            key: key.into(),
            display_name: display_name.into(),
            kind,
            auth_mode: None,
            credential_env_var: None,
            base_url_env_var: None,
            default_base_url: None,
            requires_base_url: false,
            region_env_var: None,
            presets: Vec::new(),
        }
    }

    /// Set the authentication mode.
    #[must_use]
    pub fn with_auth_mode(mut self, auth_mode: AuthMode) -> Self {
        self.auth_mode = Some(auth_mode);
        self
    }

    /// Set the environment variable that holds the credential.
    #[must_use]
    pub fn with_credential_env_var(mut self, var: impl Into<String>) -> Self {
        self.credential_env_var = Some(var.into());
        self
    }

    /// Set the environment variable that holds the base URL override.
    #[must_use]
    pub fn with_base_url_env_var(mut self, var: impl Into<String>) -> Self {
        self.base_url_env_var = Some(var.into());
        self
    }

    /// Set the default base URL.
    #[must_use]
    pub fn with_default_base_url(mut self, url: impl Into<String>) -> Self {
        self.default_base_url = Some(url.into());
        self
    }

    /// Set whether a base URL is required to use this provider.
    #[must_use]
    pub const fn with_requires_base_url(mut self, requires: bool) -> Self {
        self.requires_base_url = requires;
        self
    }

    /// Set the environment variable that holds the region (e.g. for AWS).
    #[must_use]
    pub fn with_region_env_var(mut self, var: impl Into<String>) -> Self {
        self.region_env_var = Some(var.into());
        self
    }

    /// Set the provider's presets.
    #[must_use]
    pub fn with_presets(mut self, presets: Vec<PresetCatalog>) -> Self {
        self.presets = presets;
        self
    }

    #[must_use]
    pub fn preset(&self, preset_id: &str) -> Option<&PresetCatalog> {
        self.presets.iter().find(|preset| preset.id == preset_id)
    }
}

/// The full model catalog: a list of providers, each with its own presets.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct ModelCatalog {
    /// Date (`YYYY-MM-DD`) the compiled-in pricing table was last verified
    /// against provider published prices. Used by the pricing-staleness
    /// warning at agent construction; `None` disables the check.
    #[serde(default)]
    pub pricing_as_of: Option<String>,
    #[serde(default)]
    pub providers: Vec<ProviderCatalog>,
}

impl ModelCatalog {
    /// Create an empty catalog with no `pricing_as_of` date and no providers.
    #[must_use]
    pub fn new() -> Self {
        Self {
            pricing_as_of: None,
            providers: Vec::new(),
        }
    }

    /// Set the `pricing_as_of` date (`YYYY-MM-DD`).
    #[must_use]
    pub fn with_pricing_as_of(mut self, pricing_as_of: impl Into<String>) -> Self {
        self.pricing_as_of = Some(pricing_as_of.into());
        self
    }

    /// Set the catalog's providers.
    #[must_use]
    pub fn with_providers(mut self, providers: Vec<ProviderCatalog>) -> Self {
        self.providers = providers;
        self
    }

    #[must_use]
    pub fn provider(&self, provider_key: &str) -> Option<&ProviderCatalog> {
        self.providers
            .iter()
            .find(|provider| provider.key == provider_key)
    }

    /// Search across all providers for a preset matching the given `model_id`.
    #[must_use]
    pub fn find_preset_by_model_id(&self, model_id: &str) -> Option<CatalogPreset> {
        for provider in &self.providers {
            for preset in &provider.presets {
                if preset.model_id == model_id {
                    return self.preset(&provider.key, &preset.id);
                }
            }
        }
        None
    }

    #[must_use]
    pub fn preset(&self, provider_key: &str, preset_id: &str) -> Option<CatalogPreset> {
        let provider = self.provider(provider_key)?;
        let preset = provider.preset(preset_id)?;
        Some(CatalogPreset {
            provider_key: provider.key.clone(),
            provider_display_name: provider.display_name.clone(),
            provider_kind: provider.kind.clone(),
            preset_id: preset.id.clone(),
            display_name: preset.display_name.clone(),
            group: preset.group.clone(),
            model_id: preset.model_id.clone(),
            api_version: preset.api_version.clone(),
            capabilities: preset.capabilities.clone(),
            status: preset.status.clone(),
            context_window_tokens: preset.context_window_tokens,
            max_output_tokens: preset.max_output_tokens,
            auth_mode: provider.auth_mode.clone(),
            credential_env_var: provider.credential_env_var.clone(),
            base_url_env_var: provider.base_url_env_var.clone(),
            default_base_url: provider.default_base_url.clone(),
            requires_base_url: provider.requires_base_url,
            region_env_var: provider.region_env_var.clone(),
            include_by_default: preset.include_by_default,
            repo_id: preset.repo_id.clone(),
            filename: preset.filename.clone(),
            cost_per_million_input: preset.cost_per_million_input,
            cost_per_million_output: preset.cost_per_million_output,
            cost_per_million_cache_read: preset.cost_per_million_cache_read,
            cost_per_million_cache_write: preset.cost_per_million_cache_write,
        })
    }
}

impl Default for ModelCatalog {
    fn default() -> Self {
        Self::new()
    }
}

/// A preset flattened together with its parent provider's fields, for standalone use
/// once resolved via [`ModelCatalog::preset`].
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub struct CatalogPreset {
    pub provider_key: String,
    pub provider_display_name: String,
    pub provider_kind: ProviderKind,
    pub preset_id: String,
    pub display_name: String,
    pub group: Option<String>,
    pub model_id: String,
    pub api_version: Option<ApiVersion>,
    pub capabilities: Vec<PresetCapability>,
    pub status: Option<PresetStatus>,
    pub context_window_tokens: Option<u64>,
    pub max_output_tokens: Option<u64>,
    pub auth_mode: Option<AuthMode>,
    pub credential_env_var: Option<String>,
    pub base_url_env_var: Option<String>,
    pub default_base_url: Option<String>,
    pub requires_base_url: bool,
    pub region_env_var: Option<String>,
    pub include_by_default: bool,
    pub repo_id: Option<String>,
    pub filename: Option<String>,
    pub cost_per_million_input: Option<f64>,
    pub cost_per_million_output: Option<f64>,
    pub cost_per_million_cache_read: Option<f64>,
    pub cost_per_million_cache_write: Option<f64>,
}

impl CatalogPreset {
    /// Create a flattened preset with the required identifying fields;
    /// everything else starts unset and can be filled in with the `with_*`
    /// builders.
    #[must_use]
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        provider_key: impl Into<String>,
        provider_display_name: impl Into<String>,
        provider_kind: ProviderKind,
        preset_id: impl Into<String>,
        display_name: impl Into<String>,
        model_id: impl Into<String>,
    ) -> Self {
        Self {
            provider_key: provider_key.into(),
            provider_display_name: provider_display_name.into(),
            provider_kind,
            preset_id: preset_id.into(),
            display_name: display_name.into(),
            group: None,
            model_id: model_id.into(),
            api_version: None,
            capabilities: Vec::new(),
            status: None,
            context_window_tokens: None,
            max_output_tokens: None,
            auth_mode: None,
            credential_env_var: None,
            base_url_env_var: None,
            default_base_url: None,
            requires_base_url: false,
            region_env_var: None,
            include_by_default: false,
            repo_id: None,
            filename: None,
            cost_per_million_input: None,
            cost_per_million_output: None,
            cost_per_million_cache_read: None,
            cost_per_million_cache_write: None,
        }
    }

    /// Set the display group this preset is listed under.
    #[must_use]
    pub fn with_group(mut self, group: impl Into<String>) -> Self {
        self.group = Some(group.into());
        self
    }

    /// Set the provider API version used when building request URLs.
    #[must_use]
    pub fn with_api_version(mut self, api_version: ApiVersion) -> Self {
        self.api_version = Some(api_version);
        self
    }

    /// Set the declared capabilities.
    #[must_use]
    pub fn with_capabilities(mut self, capabilities: Vec<PresetCapability>) -> Self {
        self.capabilities = capabilities;
        self
    }

    /// Set the release maturity status.
    #[must_use]
    pub fn with_status(mut self, status: PresetStatus) -> Self {
        self.status = Some(status);
        self
    }

    /// Set the model's context window size, in tokens.
    #[must_use]
    pub const fn with_context_window_tokens(mut self, tokens: u64) -> Self {
        self.context_window_tokens = Some(tokens);
        self
    }

    /// Set the model's maximum output tokens.
    #[must_use]
    pub const fn with_max_output_tokens(mut self, tokens: u64) -> Self {
        self.max_output_tokens = Some(tokens);
        self
    }

    /// Set the provider's authentication mode.
    #[must_use]
    pub fn with_auth_mode(mut self, auth_mode: AuthMode) -> Self {
        self.auth_mode = Some(auth_mode);
        self
    }

    /// Set the environment variable that holds the credential.
    #[must_use]
    pub fn with_credential_env_var(mut self, var: impl Into<String>) -> Self {
        self.credential_env_var = Some(var.into());
        self
    }

    /// Set the environment variable that holds the base URL override.
    #[must_use]
    pub fn with_base_url_env_var(mut self, var: impl Into<String>) -> Self {
        self.base_url_env_var = Some(var.into());
        self
    }

    /// Set the default base URL.
    #[must_use]
    pub fn with_default_base_url(mut self, url: impl Into<String>) -> Self {
        self.default_base_url = Some(url.into());
        self
    }

    /// Set whether a base URL is required to use this provider.
    #[must_use]
    pub const fn with_requires_base_url(mut self, requires: bool) -> Self {
        self.requires_base_url = requires;
        self
    }

    /// Set the environment variable that holds the region (e.g. for AWS).
    #[must_use]
    pub fn with_region_env_var(mut self, var: impl Into<String>) -> Self {
        self.region_env_var = Some(var.into());
        self
    }

    /// Set whether this preset is included by default.
    #[must_use]
    pub const fn with_include_by_default(mut self, include: bool) -> Self {
        self.include_by_default = include;
        self
    }

    /// Set the local model repository identifier.
    #[must_use]
    pub fn with_repo_id(mut self, repo_id: impl Into<String>) -> Self {
        self.repo_id = Some(repo_id.into());
        self
    }

    /// Set the local model file name.
    #[must_use]
    pub fn with_filename(mut self, filename: impl Into<String>) -> Self {
        self.filename = Some(filename.into());
        self
    }

    /// Set the USD-per-million-input-token rate.
    #[must_use]
    pub const fn with_cost_per_million_input(mut self, cost: f64) -> Self {
        self.cost_per_million_input = Some(cost);
        self
    }

    /// Set the USD-per-million-output-token rate.
    #[must_use]
    pub const fn with_cost_per_million_output(mut self, cost: f64) -> Self {
        self.cost_per_million_output = Some(cost);
        self
    }

    /// Set the USD-per-million-cache-read-token rate.
    #[must_use]
    pub const fn with_cost_per_million_cache_read(mut self, cost: f64) -> Self {
        self.cost_per_million_cache_read = Some(cost);
        self
    }

    /// Set the USD-per-million-cache-write-token rate.
    #[must_use]
    pub const fn with_cost_per_million_cache_write(mut self, cost: f64) -> Self {
        self.cost_per_million_cache_write = Some(cost);
        self
    }

    /// Build a [`ModelCapabilities`] from the catalog's capability list and
    /// token limits.
    #[must_use]
    pub fn model_capabilities(&self) -> ModelCapabilities {
        let has = |cap: &PresetCapability| self.capabilities.contains(cap);
        ModelCapabilities {
            supports_thinking: has(&PresetCapability::Thinking),
            supports_vision: has(&PresetCapability::ImagesIn),
            supports_tool_use: has(&PresetCapability::Tools),
            supports_streaming: has(&PresetCapability::Streaming),
            supports_structured_output: has(&PresetCapability::StructuredOutput),
            max_context_window: self.context_window_tokens,
            max_output_tokens: self.max_output_tokens,
        }
    }

    /// Create a [`ModelSpec`] pre-populated with capabilities from the catalog.
    ///
    /// Local thinking-capable models default to [`ThinkingLevel::Medium`] so
    /// thinking is active out of the box (local inference treats any non-`Off`
    /// level as a binary "on" toggle). Remote presets keep the opt-in
    /// [`ThinkingLevel::Off`] default because remote thinking consumes billable
    /// token budget. Callers can still disable thinking explicitly via
    /// [`ModelSpec::with_thinking_level`] with [`ThinkingLevel::Off`].
    #[must_use]
    pub fn model_spec(&self) -> ModelSpec {
        let capabilities = self.model_capabilities();
        let mut spec = ModelSpec::new(&self.provider_key, &self.model_id);
        if self.provider_kind == ProviderKind::Local && capabilities.supports_thinking {
            spec = spec.with_thinking_level(ThinkingLevel::Medium);
        }
        spec.with_capabilities(capabilities)
    }

    /// Returns `true` when the preset's status is [`PresetStatus::Deprecated`].
    #[must_use]
    pub fn is_deprecated(&self) -> bool {
        self.status
            .as_ref()
            .is_some_and(PresetStatus::is_deprecated)
    }

    /// The catalog-recorded replacement for a deprecated preset, if any.
    ///
    /// Returns `None` for non-deprecated presets and for deprecated presets
    /// without a known successor.
    #[must_use]
    pub fn replacement_model_id(&self) -> Option<&str> {
        match self.status.as_ref()? {
            PresetStatus::Deprecated {
                replacement_model_id,
            } => replacement_model_id.as_deref(),
            _ => None,
        }
    }
}

impl ModelCatalog {
    /// The parsed `pricing_as_of` date, or `None` if absent or malformed.
    #[must_use]
    pub fn pricing_as_of_date(&self) -> Option<NaiveDate> {
        NaiveDate::parse_from_str(self.pricing_as_of.as_deref()?, "%Y-%m-%d").ok()
    }

    /// Check whether the catalog's pricing data is stale as of `today`.
    ///
    /// Returns `Some(PricingStaleness)` when the pricing table is older than
    /// `threshold_days`, and `None` when it is fresh or when the catalog
    /// carries no (parseable) `pricing_as_of` date.
    #[must_use]
    pub fn pricing_staleness_at(
        &self,
        today: NaiveDate,
        threshold_days: u32,
    ) -> Option<PricingStaleness> {
        let as_of = self.pricing_as_of_date()?;
        let age_days = (today - as_of).num_days();
        (age_days > i64::from(threshold_days)).then_some(PricingStaleness {
            as_of,
            age_days,
            threshold_days,
        })
    }
}

/// Default staleness threshold (in days) for the compiled-in pricing table.
pub const DEFAULT_PRICING_STALENESS_DAYS: u32 = 180;

/// Environment variable that overrides [`DEFAULT_PRICING_STALENESS_DAYS`]
/// for the warning logged at agent construction. Value is a day count.
pub const PRICING_STALENESS_ENV_VAR: &str = "SWINK_PRICING_STALENESS_DAYS";

/// Details of a stale compiled-in pricing table.
///
/// Produced by [`pricing_staleness`] / [`ModelCatalog::pricing_staleness_at`]
/// when the catalog's `pricing_as_of` date is older than the threshold.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PricingStaleness {
    /// Date the pricing table was last verified.
    pub as_of: NaiveDate,
    /// Age of the pricing table in days, relative to the evaluation date.
    pub age_days: i64,
    /// The threshold that was exceeded.
    pub threshold_days: u32,
}

impl PricingStaleness {
    /// Create a staleness record from its three fields.
    #[must_use]
    pub const fn new(as_of: NaiveDate, age_days: i64, threshold_days: u32) -> Self {
        Self {
            as_of,
            age_days,
            threshold_days,
        }
    }
}

/// Check the compiled-in catalog's pricing staleness against today's date.
///
/// Returns `Some` when the pricing table is older than `threshold_days`.
/// See [`DEFAULT_PRICING_STALENESS_DAYS`] for the default threshold used at
/// agent construction.
#[must_use]
pub fn pricing_staleness(threshold_days: u32) -> Option<PricingStaleness> {
    model_catalog().pricing_staleness_at(chrono::Utc::now().date_naive(), threshold_days)
}

/// Log a once-per-process warning when the compiled-in pricing table is
/// older than the configured threshold.
///
/// The threshold defaults to [`DEFAULT_PRICING_STALENESS_DAYS`] and can be
/// overridden via the [`PRICING_STALENESS_ENV_VAR`] environment variable.
/// Called at agent construction.
pub(crate) fn warn_if_pricing_stale() {
    static ONCE: std::sync::Once = std::sync::Once::new();
    ONCE.call_once(|| {
        let threshold_days = std::env::var(PRICING_STALENESS_ENV_VAR)
            .ok()
            .and_then(|value| value.trim().parse::<u32>().ok())
            .unwrap_or(DEFAULT_PRICING_STALENESS_DAYS);
        if let Some(staleness) = pricing_staleness(threshold_days) {
            tracing::warn!(
                pricing_as_of = %staleness.as_of,
                age_days = staleness.age_days,
                threshold_days = staleness.threshold_days,
                "compiled-in model pricing table may be stale; costs from \
                 calculate_cost() may not match current provider prices"
            );
        }
    });
}

#[must_use]
pub fn model_catalog() -> &'static ModelCatalog {
    static MODEL_CATALOG: OnceLock<ModelCatalog> = OnceLock::new();
    MODEL_CATALOG.get_or_init(|| {
        toml::from_str(include_str!("model_catalog.toml"))
            .expect("src/model_catalog.toml must be valid TOML")
    })
}

/// Compute monetary cost from token usage using catalog pricing data.
///
/// Looks up the model by `model_id` across all providers. Returns
/// `Cost::default()` if the model is not found or has no pricing data.
#[must_use]
pub fn calculate_cost(model_id: &str, usage: &Usage) -> Cost {
    let Some(preset) = model_catalog().find_preset_by_model_id(model_id) else {
        tracing::debug!(
            model_id,
            "model not found in catalog; cost reported as zero"
        );
        return Cost::default();
    };

    #[allow(clippy::cast_precision_loss)] // token counts fit comfortably in f64
    let per_m = |tokens: u64, rate: Option<f64>| -> f64 {
        rate.map_or(0.0, |r| tokens as f64 * r / 1_000_000.0)
    };

    let input = per_m(usage.input, preset.cost_per_million_input);
    let output = per_m(usage.output, preset.cost_per_million_output);
    let cache_read = per_m(usage.cache_read, preset.cost_per_million_cache_read);
    let cache_write = per_m(usage.cache_write, preset.cost_per_million_cache_write);

    Cost {
        input,
        output,
        cache_read,
        cache_write,
        total: input + output + cache_read + cache_write,
        ..Cost::default()
    }
}

/// Fill in an assistant message's [`Cost`] from catalog pricing when the
/// adapter did not price the response itself.
///
/// Most built-in remote adapters emit `Cost::default()` on every assistant
/// message — they report token [`Usage`] but leave pricing to the caller. The
/// agent loop calls this helper on each assistant message before accumulating
/// cost, so that [`PolicyContext::accumulated_cost`](crate::PolicyContext) —
/// and therefore any cost ceiling built on it — sees real money.
///
/// Adapters that *do* supply their own cost (the proxy adapter, which passes
/// through provider-billed amounts) keep precedence: a non-zero [`Cost`] is
/// left untouched.
///
/// Returns `true` if the message was repriced, `false` if it was left as-is
/// (adapter already priced it, or the model has no catalog pricing).
///
/// # Example
/// ```rust
/// use swink_agent::{AssistantMessage, StopReason, Usage, price_assistant_message};
///
/// let mut message = AssistantMessage::new(vec![], "anthropic", "claude-sonnet-4-6")
///     .with_usage(Usage::default().with_input(1_000_000))
///     .with_stop_reason(StopReason::Stop)
///     .with_timestamp(0);
///
/// assert!(price_assistant_message(&mut message));
/// assert!((message.cost.total - 3.0).abs() < 1e-9);
/// ```
pub fn price_assistant_message(message: &mut AssistantMessage) -> bool {
    price_assistant_message_with(message, None)
}

/// Like [`price_assistant_message`], but consults an operator-declared
/// [`CostCalculator`] before falling back to the compiled model catalog.
///
/// This is what the agent loop actually calls, threading through the calculator
/// configured via
/// [`AgentOptions::with_cost_calculator`](crate::AgentOptions::with_cost_calculator).
/// It exists because the catalog only knows about models shipped with the
/// crate — local endpoints, private deployments, and negotiated per-tier rates
/// all price at zero without an override.
///
/// Precedence, highest first:
///
/// 1. The adapter's own non-zero [`Cost`] — never overwritten.
/// 2. `calculator`, when it returns a non-zero [`Cost`] for this model.
/// 3. The compiled model catalog.
///
/// Returns `true` if the message was repriced.
///
/// # Example
/// ```rust
/// use swink_agent::{
///     AssistantMessage, ModelRates, PricingTable, StopReason, Usage,
///     price_assistant_message_with,
/// };
///
/// // `claude-sonnet-4-6` is in the catalog at $3.00/M input, but the operator
/// // negotiated $1.00/M and says so.
/// let table = PricingTable::new().with_model(
///     "claude-sonnet-4-6",
///     ModelRates::default().with_input_per_million(1.0),
/// );
///
/// let mut message = AssistantMessage::new(vec![], "anthropic", "claude-sonnet-4-6")
///     .with_usage(Usage::default().with_input(1_000_000))
///     .with_stop_reason(StopReason::Stop)
///     .with_timestamp(0);
///
/// assert!(price_assistant_message_with(&mut message, Some(&table)));
/// assert!((message.cost.total - 1.0).abs() < 1e-9);
/// ```
pub fn price_assistant_message_with(
    message: &mut AssistantMessage,
    calculator: Option<&dyn CostCalculator>,
) -> bool {
    if !message.cost.is_zero() {
        return false;
    }
    let priced = calculator
        .and_then(|calculator| calculator.calculate(&message.model_id, &message.usage))
        .filter(|cost| !cost.is_zero())
        .unwrap_or_else(|| calculate_cost(&message.model_id, &message.usage));
    if priced.is_zero() {
        return false;
    }
    message.cost = priced;
    true
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn catalog_loads_grouped_presets() {
        let catalog = model_catalog();
        let anthropic = catalog.provider("anthropic").unwrap();
        assert_eq!(anthropic.kind, ProviderKind::Remote);
        assert!(anthropic.preset("sonnet_46").is_some());

        let local = catalog.provider("local").unwrap();
        assert_eq!(local.kind, ProviderKind::Local);
        assert!(!local.preset("smollm3_3b").unwrap().include_by_default);
        assert!(local.preset("gemma4_e2b").unwrap().include_by_default);
        assert_eq!(
            local.preset("gemma4_e2b").unwrap().context_window_tokens,
            Some(128_000)
        );

        let google = catalog.provider("google").unwrap();
        assert_eq!(google.kind, ProviderKind::Remote);
        assert_eq!(google.presets.len(), 4);

        let bedrock = catalog.provider("bedrock").unwrap();
        assert_eq!(bedrock.auth_mode, Some(AuthMode::AwsSigv4));
        assert_eq!(bedrock.region_env_var.as_deref(), Some("AWS_REGION"));
    }

    #[test]
    fn preset_lookup_returns_provider_metadata() {
        let preset = model_catalog().preset("openai", "gpt_5_4").unwrap();
        assert_eq!(preset.display_name, "OpenAI GPT-5.4");
        assert_eq!(preset.model_id, "gpt-5.4");
        assert_eq!(preset.credential_env_var.as_deref(), Some("OPENAI_API_KEY"));
        assert_eq!(preset.base_url_env_var.as_deref(), Some("OPENAI_BASE_URL"));
        assert_eq!(preset.auth_mode, Some(AuthMode::Bearer));
    }

    #[test]
    fn google_preset_lookup_returns_extended_metadata() {
        let preset = model_catalog().preset("google", "gemini_3_flash").unwrap();
        assert_eq!(preset.display_name, "Google Gemini 3 Flash");
        assert_eq!(preset.model_id, "gemini-3-flash-preview");
        assert_eq!(preset.api_version, Some(ApiVersion::V1beta));
        assert_eq!(preset.status, Some(PresetStatus::Preview));
        assert_eq!(
            preset.capabilities,
            vec![
                PresetCapability::Text,
                PresetCapability::Tools,
                PresetCapability::Thinking,
                PresetCapability::ImagesIn,
                PresetCapability::Streaming,
                PresetCapability::StructuredOutput,
            ]
        );
        assert_eq!(preset.context_window_tokens, Some(1_000_000));
        assert_eq!(preset.max_output_tokens, Some(65536));
        assert_eq!(preset.credential_env_var.as_deref(), Some("GEMINI_API_KEY"));
        assert_eq!(preset.base_url_env_var.as_deref(), Some("GEMINI_BASE_URL"));
    }

    #[test]
    fn azure_and_bedrock_presets_expose_provider_specific_metadata() {
        let azure = model_catalog().preset("azure", "gpt_4o").unwrap();
        assert_eq!(azure.auth_mode, Some(AuthMode::ApiKeyHeader));
        assert!(azure.requires_base_url);
        assert_eq!(azure.base_url_env_var.as_deref(), Some("AZURE_BASE_URL"));

        let bedrock = model_catalog()
            .preset("bedrock", "anthropic_claude_sonnet_45")
            .unwrap();
        assert_eq!(bedrock.auth_mode, Some(AuthMode::AwsSigv4));
        assert_eq!(bedrock.region_env_var.as_deref(), Some("AWS_REGION"));
        assert_eq!(bedrock.group.as_deref(), Some("anthropic"));
    }

    #[test]
    fn anthropic_preset_model_capabilities() {
        let preset = model_catalog().preset("anthropic", "sonnet_46").unwrap();
        let caps = preset.model_capabilities();
        assert!(caps.supports_thinking);
        assert!(caps.supports_vision);
        assert!(caps.supports_tool_use);
        assert!(caps.supports_streaming);
        assert!(caps.supports_structured_output);
        assert_eq!(caps.max_context_window, Some(200_000));
        assert_eq!(caps.max_output_tokens, Some(16384));
    }

    #[test]
    fn model_spec_carries_capabilities_from_preset() {
        let preset = model_catalog().preset("anthropic", "opus_46").unwrap();
        let spec = preset.model_spec();
        let caps = spec.capabilities();
        assert!(caps.supports_thinking);
        assert!(caps.supports_vision);
        assert!(caps.supports_tool_use);
        assert_eq!(caps.max_context_window, Some(200_000));
        assert_eq!(caps.max_output_tokens, Some(32768));
    }

    #[test]
    fn openai_preset_no_thinking() {
        let preset = model_catalog().preset("openai", "gpt_5_4_mini").unwrap();
        let caps = preset.model_capabilities();
        assert!(!caps.supports_thinking);
        assert!(caps.supports_tool_use);
        assert!(caps.supports_vision);
        assert!(caps.supports_streaming);
        assert!(caps.supports_structured_output);
        assert_eq!(caps.max_context_window, Some(400_000));
    }

    #[test]
    fn local_preset_minimal_capabilities() {
        let preset = model_catalog().preset("local", "smollm3_3b").unwrap();
        let caps = preset.model_capabilities();
        assert!(!caps.supports_thinking);
        assert!(!caps.supports_vision);
        assert!(!caps.supports_tool_use);
        assert!(caps.supports_streaming);
        assert!(!caps.supports_structured_output);
        assert_eq!(caps.max_context_window, Some(8192));
        assert_eq!(caps.max_output_tokens, Some(2048));
    }

    #[test]
    fn bedrock_preset_capabilities() {
        let preset = model_catalog()
            .preset("bedrock", "anthropic_claude_sonnet_45")
            .unwrap();
        let caps = preset.model_capabilities();
        assert!(caps.supports_thinking);
        assert!(caps.supports_vision);
        assert!(caps.supports_tool_use);
        assert!(caps.supports_streaming);
        assert!(!caps.supports_structured_output);
    }

    #[test]
    fn local_thinking_preset_model_spec_defaults_to_thinking_on() {
        let preset = model_catalog().preset("local", "gemma4_e2b").unwrap();
        let spec = preset.model_spec();
        assert!(spec.capabilities().supports_thinking);
        assert_ne!(spec.thinking_level, ThinkingLevel::Off);
    }

    #[test]
    fn local_non_thinking_preset_model_spec_stays_off() {
        let preset = model_catalog().preset("local", "smollm3_3b").unwrap();
        let spec = preset.model_spec();
        assert!(!spec.capabilities().supports_thinking);
        assert_eq!(spec.thinking_level, ThinkingLevel::Off);
    }

    #[test]
    fn remote_thinking_preset_model_spec_stays_opt_in() {
        let preset = model_catalog().preset("anthropic", "sonnet_46").unwrap();
        let spec = preset.model_spec();
        assert!(spec.capabilities().supports_thinking);
        assert_eq!(spec.thinking_level, ThinkingLevel::Off);
    }

    #[test]
    fn local_thinking_default_can_be_explicitly_disabled() {
        let preset = model_catalog().preset("local", "gemma4_e2b").unwrap();
        let spec = preset.model_spec().with_thinking_level(ThinkingLevel::Off);
        assert_eq!(spec.thinking_level, ThinkingLevel::Off);
    }

    #[test]
    fn manual_model_spec_defaults_to_no_capabilities() {
        let spec = crate::ModelSpec::new("custom", "my-model");
        let caps = spec.capabilities();
        assert!(!caps.supports_thinking);
        assert!(!caps.supports_vision);
        assert!(!caps.supports_tool_use);
        assert!(!caps.supports_streaming);
        assert!(!caps.supports_structured_output);
        assert_eq!(caps.max_context_window, None);
        assert_eq!(caps.max_output_tokens, None);
    }

    // --- US4: Cost calculation tests ---

    fn usage(input: u64, output: u64, cache_read: u64, cache_write: u64) -> crate::types::Usage {
        crate::types::Usage {
            input,
            output,
            cache_read,
            cache_write,
            total: input + output + cache_read + cache_write,
            ..Default::default()
        }
    }

    #[test]
    fn calculate_cost_known_model() {
        // Sonnet 4.6: input=$3/M, output=$15/M
        let cost = calculate_cost("claude-sonnet-4-6", &usage(1_000_000, 500_000, 0, 0));
        assert!((cost.input - 3.0).abs() < 0.001);
        assert!((cost.output - 7.5).abs() < 0.001);
        assert!((cost.total - 10.5).abs() < 0.001);
    }

    #[test]
    fn calculate_cost_unknown_model() {
        let cost = calculate_cost("nonexistent-model-xyz", &usage(1_000_000, 1_000_000, 0, 0));
        assert!((cost.input).abs() < 0.001);
        assert!((cost.output).abs() < 0.001);
        assert!((cost.total).abs() < 0.001);
    }

    #[test]
    fn calculate_cost_zero_usage() {
        let cost = calculate_cost("claude-sonnet-4-6", &usage(0, 0, 0, 0));
        assert!((cost.total).abs() < 0.001);
    }

    fn message(model_id: &str, usage: Usage, cost: Cost) -> AssistantMessage {
        AssistantMessage {
            content: vec![],
            provider: "anthropic".to_string(),
            model_id: model_id.to_string(),
            usage,
            cost,
            stop_reason: crate::types::StopReason::Stop,
            error_message: None,
            error_kind: None,
            timestamp: 0,
            cache_hint: None,
        }
    }

    #[test]
    fn price_assistant_message_fills_in_unpriced_message() {
        let mut msg = message(
            "claude-sonnet-4-6",
            usage(1_000_000, 1_000_000, 0, 0),
            Cost::default(),
        );
        assert!(price_assistant_message(&mut msg));
        assert!((msg.cost.input - 3.0).abs() < 0.001);
        assert!((msg.cost.total - msg.cost.input - msg.cost.output).abs() < 0.001);
        assert!(msg.cost.total > 0.0);
    }

    #[test]
    fn price_assistant_message_preserves_adapter_supplied_cost() {
        let adapter_cost = Cost {
            input: 0.5,
            total: 0.5,
            ..Cost::default()
        };
        let mut msg = message(
            "claude-sonnet-4-6",
            usage(1_000_000, 1_000_000, 0, 0),
            adapter_cost,
        );
        assert!(!price_assistant_message(&mut msg));
        assert!((msg.cost.total - 0.5).abs() < 0.001);
    }

    #[test]
    fn price_assistant_message_leaves_unknown_model_at_zero() {
        let mut msg = message(
            "nonexistent-model-xyz",
            usage(1_000_000, 1_000_000, 0, 0),
            Cost::default(),
        );
        assert!(!price_assistant_message(&mut msg));
        assert!(msg.cost.is_zero());
    }

    #[test]
    fn price_assistant_message_leaves_zero_usage_at_zero() {
        let mut msg = message("claude-sonnet-4-6", usage(0, 0, 0, 0), Cost::default());
        assert!(!price_assistant_message(&mut msg));
        assert!(msg.cost.is_zero());
    }

    /// Issue #1084: operator-declared rates must beat the compiled catalog.
    ///
    /// `claude-sonnet-4-6` is in the catalog at $3.00/M input. An operator who
    /// declares $1.00/M must see $1.00 — otherwise a `[pricing]` config section
    /// silently does nothing for any model the catalog happens to know.
    #[test]
    fn operator_declared_rates_take_precedence_over_catalog() {
        let table = crate::pricing::PricingTable::new().with_model(
            "claude-sonnet-4-6",
            crate::pricing::ModelRates {
                input_per_million: 1.0,
                ..crate::pricing::ModelRates::default()
            },
        );
        let mut msg = message(
            "claude-sonnet-4-6",
            usage(1_000_000, 0, 0, 0),
            Cost::default(),
        );

        assert!(price_assistant_message_with(&mut msg, Some(&table)));
        assert!(
            (msg.cost.total - 1.0).abs() < 0.001,
            "expected the operator's $1.00/M rate, got ${:.4} (catalog rate is $3.00/M)",
            msg.cost.total
        );
    }

    /// A calculator that declines a model must not suppress catalog pricing.
    #[test]
    fn calculator_declining_a_model_falls_back_to_catalog() {
        let table = crate::pricing::PricingTable::new().with_model(
            "some-other-model",
            crate::pricing::ModelRates {
                input_per_million: 1.0,
                ..crate::pricing::ModelRates::default()
            },
        );
        let mut msg = message(
            "claude-sonnet-4-6",
            usage(1_000_000, 0, 0, 0),
            Cost::default(),
        );

        assert!(price_assistant_message_with(&mut msg, Some(&table)));
        assert!(
            (msg.cost.total - 3.0).abs() < 0.001,
            "expected catalog pricing"
        );
    }

    /// Operator rates are the only way to price a model the catalog has never
    /// heard of — local endpoints and private deployments.
    #[test]
    fn operator_declared_rates_price_a_model_absent_from_the_catalog() {
        let table = crate::pricing::PricingTable::new().with_model(
            "my-local-llama",
            crate::pricing::ModelRates {
                input_per_million: 0.10,
                output_per_million: 0.40,
                ..crate::pricing::ModelRates::default()
            },
        );
        let mut msg = message(
            "my-local-llama",
            usage(1_000_000, 1_000_000, 0, 0),
            Cost::default(),
        );

        assert!(price_assistant_message_with(&mut msg, Some(&table)));
        assert!((msg.cost.total - 0.50).abs() < 0.001);
    }

    /// The adapter's own billed cost outranks even an operator override.
    #[test]
    fn adapter_supplied_cost_outranks_operator_declared_rates() {
        let table = crate::pricing::PricingTable::new().with_model(
            "claude-sonnet-4-6",
            crate::pricing::ModelRates {
                input_per_million: 1.0,
                ..crate::pricing::ModelRates::default()
            },
        );
        let adapter_cost = Cost {
            input: 0.25,
            total: 0.25,
            ..Cost::default()
        };
        let mut msg = message("claude-sonnet-4-6", usage(1_000_000, 0, 0, 0), adapter_cost);

        assert!(!price_assistant_message_with(&mut msg, Some(&table)));
        assert!((msg.cost.total - 0.25).abs() < 0.001);
    }

    /// A calculator returning an explicit zero declines rather than pinning the
    /// message to zero, so the catalog still gets a turn.
    #[test]
    fn calculator_returning_zero_cost_falls_back_to_catalog() {
        let zeroing = |_model_id: &str, _usage: &Usage| Some(Cost::default());
        let mut msg = message(
            "claude-sonnet-4-6",
            usage(1_000_000, 0, 0, 0),
            Cost::default(),
        );

        assert!(price_assistant_message_with(&mut msg, Some(&zeroing)));
        assert!((msg.cost.total - 3.0).abs() < 0.001);
    }

    #[test]
    fn calculate_cost_cache_tokens() {
        // Sonnet 4.6: cache_read=$0.30/M, cache_write=$3.75/M
        let cost = calculate_cost("claude-sonnet-4-6", &usage(0, 0, 2_000_000, 1_000_000));
        assert!((cost.cache_read - 0.60).abs() < 0.001);
        assert!((cost.cache_write - 3.75).abs() < 0.001);
        assert!((cost.total - 4.35).abs() < 0.001);
    }

    #[test]
    fn calculate_cost_no_pricing_data() {
        // Local model has no pricing fields
        let cost = calculate_cost("SmolLM3-3B-Q4_K_M", &usage(1_000_000, 500_000, 0, 0));
        assert!((cost.total).abs() < 0.001);
    }

    // --- US5: Capability introspection tests ---

    #[test]
    fn capabilities_from_catalog_preset() {
        let preset = model_catalog().preset("anthropic", "sonnet_46").unwrap();
        let caps = preset.model_capabilities();
        assert!(caps.supports_thinking);
        assert!(caps.supports_vision);
        assert!(caps.supports_tool_use);
        assert!(caps.supports_streaming);
        assert!(caps.supports_structured_output);
    }

    #[test]
    fn capabilities_context_window_and_output() {
        let preset = model_catalog().preset("openai", "gpt_5_4").unwrap();
        let caps = preset.model_capabilities();
        assert_eq!(caps.max_context_window, Some(1_050_000));
        assert_eq!(caps.max_output_tokens, Some(128_000));
    }

    #[test]
    fn model_spec_carries_capabilities() {
        let preset = model_catalog().preset("google", "gemini_3_flash").unwrap();
        let spec = preset.model_spec();
        let caps = spec.capabilities();
        assert!(caps.supports_thinking);
        assert!(caps.supports_vision);
        assert!(caps.supports_tool_use);
        assert_eq!(caps.max_context_window, Some(1_000_000));
    }

    #[test]
    fn find_preset_by_model_id_works() {
        let preset = model_catalog()
            .find_preset_by_model_id("claude-sonnet-4-6")
            .unwrap();
        assert_eq!(preset.preset_id, "sonnet_46");
        assert_eq!(preset.provider_key, "anthropic");
    }

    #[test]
    fn find_preset_by_model_id_unknown_returns_none() {
        assert!(
            model_catalog()
                .find_preset_by_model_id("nonexistent")
                .is_none()
        );
    }

    // --- Deprecation status ---

    const DEPRECATED_CATALOG: &str = r#"
        pricing_as_of = "2026-01-01"

        [[providers]]
        key = "test"
        display_name = "Test Provider"
        kind = "remote"

        [[providers.presets]]
        id = "old_model"
        display_name = "Old Model"
        model_id = "old-model-1"
        status = { deprecated = { replacement_model_id = "new-model-2" } }

        [[providers.presets]]
        id = "sunset_model"
        display_name = "Sunset Model"
        model_id = "sunset-model-1"
        status = { deprecated = {} }

        [[providers.presets]]
        id = "current_model"
        display_name = "Current Model"
        model_id = "new-model-2"
        status = "ga"
    "#;

    #[test]
    fn deprecated_catalog_entry_parses_with_replacement_id() {
        let catalog: ModelCatalog = toml::from_str(DEPRECATED_CATALOG).unwrap();
        let preset = catalog.preset("test", "old_model").unwrap();
        assert_eq!(
            preset.status,
            Some(PresetStatus::Deprecated {
                replacement_model_id: Some("new-model-2".to_string()),
            })
        );
        assert!(preset.is_deprecated());
        assert_eq!(preset.replacement_model_id(), Some("new-model-2"));
    }

    #[test]
    fn deprecated_catalog_entry_parses_without_replacement_id() {
        let catalog: ModelCatalog = toml::from_str(DEPRECATED_CATALOG).unwrap();
        let preset = catalog.preset("test", "sunset_model").unwrap();
        assert_eq!(
            preset.status,
            Some(PresetStatus::Deprecated {
                replacement_model_id: None,
            })
        );
        assert!(preset.is_deprecated());
        assert_eq!(preset.replacement_model_id(), None);
    }

    #[test]
    fn string_statuses_remain_backward_compatible() {
        let catalog: ModelCatalog = toml::from_str(DEPRECATED_CATALOG).unwrap();
        let preset = catalog.preset("test", "current_model").unwrap();
        assert_eq!(preset.status, Some(PresetStatus::Ga));
        assert!(!preset.is_deprecated());
        assert_eq!(preset.replacement_model_id(), None);

        // The compiled catalog (string statuses only) must still parse and
        // contain no deprecated entries today.
        let compiled = model_catalog();
        for provider in &compiled.providers {
            for preset in &provider.presets {
                assert!(
                    !preset
                        .status
                        .as_ref()
                        .is_some_and(PresetStatus::is_deprecated),
                    "unexpected deprecated preset {}.{}",
                    provider.key,
                    preset.id
                );
            }
        }
    }

    // --- Pricing staleness ---

    #[test]
    fn pricing_staleness_triggers_past_threshold() {
        let catalog: ModelCatalog = toml::from_str(DEPRECATED_CATALOG).unwrap();
        let today = NaiveDate::from_ymd_opt(2026, 8, 1).unwrap();
        let staleness = catalog.pricing_staleness_at(today, 180).unwrap();
        assert_eq!(
            staleness.as_of,
            NaiveDate::from_ymd_opt(2026, 1, 1).unwrap()
        );
        assert_eq!(staleness.age_days, 212);
        assert_eq!(staleness.threshold_days, 180);
    }

    #[test]
    fn pricing_staleness_not_triggered_before_threshold() {
        let catalog: ModelCatalog = toml::from_str(DEPRECATED_CATALOG).unwrap();
        // 31 days old — under a 180-day threshold.
        let today = NaiveDate::from_ymd_opt(2026, 2, 1).unwrap();
        assert!(catalog.pricing_staleness_at(today, 180).is_none());
        // Exactly at the threshold is still fresh (strictly greater triggers).
        let today = NaiveDate::from_ymd_opt(2026, 6, 30).unwrap();
        assert!(catalog.pricing_staleness_at(today, 180).is_none());
        // One day past the threshold triggers.
        let today = NaiveDate::from_ymd_opt(2026, 7, 1).unwrap();
        assert!(catalog.pricing_staleness_at(today, 181).is_none());
        assert!(catalog.pricing_staleness_at(today, 180).is_some());
    }

    #[test]
    fn pricing_staleness_none_when_date_absent_or_malformed() {
        let today = NaiveDate::from_ymd_opt(2030, 1, 1).unwrap();
        let absent: ModelCatalog = toml::from_str("").unwrap();
        assert!(absent.pricing_as_of_date().is_none());
        assert!(absent.pricing_staleness_at(today, 0).is_none());

        let malformed: ModelCatalog = toml::from_str("pricing_as_of = \"soonish\"").unwrap();
        assert!(malformed.pricing_as_of_date().is_none());
        assert!(malformed.pricing_staleness_at(today, 0).is_none());
    }

    #[test]
    fn compiled_catalog_carries_parseable_pricing_as_of() {
        assert!(
            model_catalog().pricing_as_of_date().is_some(),
            "src/model_catalog.toml must set a valid pricing_as_of date"
        );
    }
}