car-inference 0.48.0

Local model inference for CAR — Candle backend with Qwen3 models
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
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
//! Curated OpenRouter model definitions and credential resolution.
//!
//! The built-in table produces exactly eleven reviewed personal models plus
//! the eleven opaque Parslee-managed aliases. Personal availability follows the
//! resolved credential on every registry snapshot; CAR deliberately does not
//! project OpenRouter's full catalog. Managed aliases remain bounded and never
//! disclose upstream provider ids.

use car_secrets::{SecretRef, SecretStore};
#[cfg(test)]
use std::cell::Cell;
#[cfg(test)]
use std::sync::MutexGuard;
use std::sync::{Mutex, OnceLock};

use crate::schema::{
    ApiProtocol, CostModel, GenerateParam, ModelCapability, ModelSchema, ModelSource,
    PerformanceEnvelope, ProprietaryAuth, ProprietaryProtocol, TrustTier,
};

pub const API_KEY_ENV: &str = "OPENROUTER_API_KEY";
pub const OAUTH_KEYCHAIN_KEY: &str = car_secrets::OPENROUTER_OAUTH_KEY;
pub const DEFAULT_API_BASE: &str = "https://openrouter.ai/api";

fn oauth_keychain_service() -> String {
    // Test-double verification can isolate its credential without touching the
    // operator's real OAuth connection. Production never sets this variable.
    std::env::var("CAR_OPENROUTER_OAUTH_KEYCHAIN_SERVICE")
        .unwrap_or_else(|_| car_secrets::DEFAULT_SERVICE.to_string())
}

fn oauth_secret_ref() -> SecretRef {
    SecretRef::new(oauth_keychain_service(), OAUTH_KEYCHAIN_KEY)
}

/// The OAuth credential is daemon-private. Generic secret RPC/FFI surfaces
/// must fail closed for this exact `(service, key)` pair; only this module's
/// request lease and the daemon-owned OAuth manager may access it.
pub fn is_reserved_oauth_secret(service: Option<&str>, key: &str) -> bool {
    service.unwrap_or(car_secrets::DEFAULT_SERVICE) == oauth_keychain_service()
        && key == OAUTH_KEYCHAIN_KEY
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CredentialSource {
    Env,
    Pasted,
    Oauth,
}

impl CredentialSource {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Env => "env",
            Self::Pasted => "pasted",
            Self::Oauth => "oauth",
        }
    }
}

/// Resolve only existence/source metadata. Registry listing and routing use
/// this path so they never fetch the credential value from the OS keychain.
pub fn credential_source() -> Option<CredentialSource> {
    #[cfg(test)]
    CREDENTIAL_SOURCE_CALLS.with(|calls| calls.set(calls.get() + 1));
    #[cfg(test)]
    if let Some(value) = test_credential_override()
        .lock()
        .unwrap_or_else(|p| p.into_inner())
        .clone()
    {
        return value.map(|_| CredentialSource::Env);
    }
    if environment_key_exists() {
        return Some(CredentialSource::Env);
    }
    if pasted_key_exists() {
        return Some(CredentialSource::Pasted);
    }
    oauth_key_exists().then_some(CredentialSource::Oauth)
}

#[cfg(test)]
thread_local! {
    // Per-thread instrumentation keeps the "one credential probe per routing
    // decision" assertion isolated from unrelated router tests running in
    // parallel in the same process.
    static CREDENTIAL_SOURCE_CALLS: Cell<usize> = const { Cell::new(0) };
}

#[cfg(test)]
pub(crate) fn reset_credential_source_call_count() {
    CREDENTIAL_SOURCE_CALLS.with(|calls| calls.set(0));
}

#[cfg(test)]
pub(crate) fn credential_source_call_count() -> usize {
    CREDENTIAL_SOURCE_CALLS.with(Cell::get)
}

pub fn environment_key_exists() -> bool {
    std::env::var(API_KEY_ENV).is_ok_and(|value| !value.trim().is_empty())
}

/// Resolve on every request: environment, separately pasted key, then OAuth.
pub fn resolve_credential() -> Option<(String, CredentialSource)> {
    #[cfg(test)]
    if let Some(value) = test_credential_override()
        .lock()
        .unwrap_or_else(|p| p.into_inner())
        .clone()
    {
        return value.map(|key| (key, CredentialSource::Env));
    }
    if let Ok(value) = std::env::var(API_KEY_ENV) {
        if !value.trim().is_empty() {
            return Some((value, CredentialSource::Env));
        }
    }
    let store = SecretStore::new();
    if store.is_available() {
        if let Ok(value) = store.get(&SecretRef::with_default_service(API_KEY_ENV)) {
            if !value.trim().is_empty() {
                return Some((value, CredentialSource::Pasted));
            }
        }
        if let Ok(value) = store.get(&oauth_secret_ref()) {
            if !value.trim().is_empty() {
                return Some((value, CredentialSource::Oauth));
            }
        }
    }
    None
}

#[cfg(test)]
fn test_credential_override() -> &'static Mutex<Option<Option<String>>> {
    static OVERRIDE: OnceLock<Mutex<Option<Option<String>>>> = OnceLock::new();
    OVERRIDE.get_or_init(|| Mutex::new(None))
}

#[cfg(test)]
fn test_credential_serial_lock() -> &'static Mutex<()> {
    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
    LOCK.get_or_init(|| Mutex::new(()))
}

/// Serializes tests that exercise the process-wide credential resolver. The
/// guard also clears the override on unwind so a failed test cannot poison the
/// availability seen by the rest of the suite.
#[cfg(test)]
pub(crate) struct TestCredentialScope {
    _guard: MutexGuard<'static, ()>,
}

#[cfg(test)]
impl Drop for TestCredentialScope {
    fn drop(&mut self) {
        clear_test_credential();
    }
}

#[cfg(test)]
pub(crate) fn test_credential_scope() -> TestCredentialScope {
    TestCredentialScope {
        _guard: test_credential_serial_lock()
            .lock()
            .unwrap_or_else(|p| p.into_inner()),
    }
}

#[cfg(test)]
pub(crate) fn test_environment_scope() -> tokio::sync::MutexGuard<'static, ()> {
    test_environment_lock().blocking_lock()
}

#[cfg(test)]
pub(crate) async fn test_environment_scope_async() -> tokio::sync::MutexGuard<'static, ()> {
    test_environment_lock().lock().await
}

#[cfg(test)]
fn test_environment_lock() -> &'static tokio::sync::Mutex<()> {
    static LOCK: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new();
    LOCK.get_or_init(|| tokio::sync::Mutex::new(()))
}

/// Deterministic credential seam for provider-wire tests. `Some(key)` forces a
/// key, `None` forces no credential; [`clear_test_credential`] restores normal
/// env/keychain resolution.
#[cfg(test)]
pub(crate) fn set_test_credential(value: Option<&str>) {
    *test_credential_override()
        .lock()
        .unwrap_or_else(|p| p.into_inner()) = Some(value.map(str::to_string));
}

#[cfg(test)]
pub(crate) fn clear_test_credential() {
    *test_credential_override()
        .lock()
        .unwrap_or_else(|p| p.into_inner()) = None;
}

pub fn pasted_key_exists() -> bool {
    SecretStore::new()
        .status(&SecretRef::with_default_service(API_KEY_ENV))
        .map(|status| status.exists)
        .unwrap_or(false)
}

pub fn oauth_key_exists() -> bool {
    SecretStore::new()
        .status(&oauth_secret_ref())
        .map(|status| status.exists)
        .unwrap_or(false)
}

pub fn store_oauth_credential(value: &str) -> Result<(), car_secrets::SecretError> {
    SecretStore::new().put(&oauth_secret_ref(), value)
}

pub fn delete_oauth_credential() -> Result<(), car_secrets::SecretError> {
    match SecretStore::new().delete(&oauth_secret_ref()) {
        Ok(()) | Err(car_secrets::SecretError::NotFound { .. }) => Ok(()),
        Err(error) => Err(error),
    }
}

#[derive(Clone, Copy)]
struct CuratedModel {
    upstream_id: &'static str,
    managed_alias: &'static str,
    family: &'static str,
    /// Date of the `https://openrouter.ai/api/v1/models` snapshot this row's
    /// context window, output ceiling and prices were read from. Per-row
    /// rather than table-wide so a later addition doesn't have to claim the
    /// original snapshot's date. Published as `ModelSchema::version`.
    snapshot: &'static str,
    context_length: usize,
    max_output_tokens: usize,
    input_per_mtok: f64,
    output_per_mtok: f64,
    cache_read_input_per_mtok: Option<f64>,
    cache_write_input_per_mtok: Option<f64>,
    high_context_pricing: Option<CuratedPricingTier>,
    capabilities: &'static [ModelCapability],
    tags: &'static [&'static str],
    supported_params: &'static [GenerateParam],
}

#[derive(Clone, Copy)]
struct CuratedPricingTier {
    min_prompt_tokens: usize,
    input_per_mtok: f64,
    output_per_mtok: f64,
    cache_read_input_per_mtok: Option<f64>,
    cache_write_input_per_mtok: Option<f64>,
}

use ModelCapability as C;
const CODE_REASON_VISION: &[ModelCapability] = &[
    C::Generate,
    C::Code,
    C::Reasoning,
    C::ToolUse,
    C::Summarize,
    C::Vision,
];
const CODE_REASON: &[ModelCapability] =
    &[C::Generate, C::Code, C::Reasoning, C::ToolUse, C::Summarize];
const CODE_REASON_MULTI_TOOL: &[ModelCapability] = &[
    C::Generate,
    C::Code,
    C::Reasoning,
    C::ToolUse,
    C::MultiToolCall,
    C::Summarize,
];
const CODE: &[ModelCapability] = &[C::Generate, C::Code, C::ToolUse, C::Summarize];

use GenerateParam as P;
// Keep these bounded to fields `OpenRouterHandler` actually places on the
// Chat Completions request. The reviewed upstream snapshot may advertise
// additional controls, but CAR must not claim them until `ApiRequest` and the
// adapter carry them end to end.
const PARAMS_OPENAI_REASONING: &[GenerateParam] =
    &[P::MaxTokens, P::ResponseFormat, P::ExtendedThinking];
const PARAMS_ANTHROPIC_REASONING: &[GenerateParam] = &[
    P::Temperature,
    P::MaxTokens,
    P::ResponseFormat,
    P::ExtendedThinking,
];
const PARAMS_GEMINI_REASONING: &[GenerateParam] = &[
    P::Temperature,
    P::MaxTokens,
    P::ResponseFormat,
    P::ExtendedThinking,
];
const PARAMS_STANDARD_REASONING: &[GenerateParam] = &[
    P::Temperature,
    P::MaxTokens,
    P::ResponseFormat,
    P::ExtendedThinking,
];
const PARAMS_QWEN_REASONING: &[GenerateParam] = &[
    P::Temperature,
    P::MaxTokens,
    P::ResponseFormat,
    P::ExtendedThinking,
];
const PARAMS_STANDARD: &[GenerateParam] = &[P::Temperature, P::MaxTokens, P::ResponseFormat];

/// Rows read from the official `https://openrouter.ai/api/v1/models` catalog.
/// Each row carries the date of the snapshot it was read from in `snapshot`,
/// so a later addition doesn't restate the whole table's provenance.
/// Prices are USD/MTok; high-context overrides use the endpoint's inclusive
/// `min_prompt_tokens` thresholds.
const CURATED: &[CuratedModel] = &[
    CuratedModel {
        upstream_id: "openai/gpt-5.4",
        managed_alias: "frontier-general",
        family: "gpt-5.4",
        snapshot: "2026-07-22",
        context_length: 1_050_000,
        max_output_tokens: 128_000,
        input_per_mtok: 2.5,
        output_per_mtok: 15.0,
        cache_read_input_per_mtok: Some(0.25),
        cache_write_input_per_mtok: None,
        high_context_pricing: Some(CuratedPricingTier {
            min_prompt_tokens: 272_000,
            input_per_mtok: 5.0,
            output_per_mtok: 22.5,
            cache_read_input_per_mtok: Some(0.5),
            cache_write_input_per_mtok: None,
        }),
        capabilities: CODE_REASON_VISION,
        tags: &["frontier"],
        supported_params: PARAMS_OPENAI_REASONING,
    },
    CuratedModel {
        upstream_id: "anthropic/claude-opus-4.6",
        managed_alias: "frontier-deep",
        family: "claude-4.6",
        snapshot: "2026-07-22",
        context_length: 1_000_000,
        max_output_tokens: 128_000,
        input_per_mtok: 5.0,
        output_per_mtok: 25.0,
        cache_read_input_per_mtok: Some(0.5),
        cache_write_input_per_mtok: Some(6.25),
        high_context_pricing: None,
        capabilities: CODE_REASON_VISION,
        tags: &["frontier"],
        supported_params: PARAMS_ANTHROPIC_REASONING,
    },
    CuratedModel {
        upstream_id: "google/gemini-3.1-pro-preview",
        managed_alias: "frontier-multimodal",
        family: "gemini-3.1",
        snapshot: "2026-07-22",
        context_length: 1_048_576,
        max_output_tokens: 65_536,
        input_per_mtok: 2.0,
        output_per_mtok: 12.0,
        cache_read_input_per_mtok: Some(0.2),
        cache_write_input_per_mtok: Some(0.375),
        high_context_pricing: Some(CuratedPricingTier {
            min_prompt_tokens: 200_000,
            input_per_mtok: 4.0,
            output_per_mtok: 18.0,
            cache_read_input_per_mtok: Some(0.4),
            cache_write_input_per_mtok: Some(0.375),
        }),
        capabilities: CODE_REASON_VISION,
        tags: &["frontier", "preview"],
        supported_params: PARAMS_GEMINI_REASONING,
    },
    CuratedModel {
        upstream_id: "anthropic/claude-sonnet-4.6",
        managed_alias: "balanced-general",
        family: "claude-4.6",
        snapshot: "2026-07-22",
        context_length: 1_000_000,
        max_output_tokens: 128_000,
        input_per_mtok: 3.0,
        output_per_mtok: 15.0,
        cache_read_input_per_mtok: Some(0.3),
        cache_write_input_per_mtok: Some(3.75),
        high_context_pricing: None,
        capabilities: CODE_REASON_VISION,
        tags: &["balanced"],
        supported_params: PARAMS_ANTHROPIC_REASONING,
    },
    CuratedModel {
        upstream_id: "moonshotai/kimi-k2.5",
        managed_alias: "open-multimodal",
        family: "kimi-k2.5",
        snapshot: "2026-07-22",
        context_length: 262_144,
        max_output_tokens: 262_144,
        input_per_mtok: 0.57,
        output_per_mtok: 2.85,
        cache_read_input_per_mtok: Some(0.095),
        cache_write_input_per_mtok: None,
        high_context_pricing: None,
        capabilities: CODE_REASON_VISION,
        tags: &["cheap", "open-weight"],
        supported_params: PARAMS_STANDARD_REASONING,
    },
    CuratedModel {
        upstream_id: "qwen/qwen3.5-plus-02-15",
        managed_alias: "open-long-context",
        family: "qwen3.5",
        snapshot: "2026-07-22",
        context_length: 1_000_000,
        max_output_tokens: 65_536,
        input_per_mtok: 0.26,
        output_per_mtok: 1.56,
        cache_read_input_per_mtok: None,
        cache_write_input_per_mtok: None,
        high_context_pricing: Some(CuratedPricingTier {
            min_prompt_tokens: 256_000,
            input_per_mtok: 0.325,
            output_per_mtok: 1.95,
            cache_read_input_per_mtok: None,
            cache_write_input_per_mtok: None,
        }),
        capabilities: CODE_REASON_VISION,
        tags: &["cheap", "open-weight"],
        supported_params: PARAMS_QWEN_REASONING,
    },
    CuratedModel {
        upstream_id: "deepseek/deepseek-v3.2",
        managed_alias: "open-reasoning",
        family: "deepseek-v3.2",
        snapshot: "2026-07-22",
        context_length: 163_840,
        max_output_tokens: 65_536,
        input_per_mtok: 0.269,
        output_per_mtok: 0.4,
        cache_read_input_per_mtok: Some(0.1345),
        cache_write_input_per_mtok: None,
        high_context_pricing: None,
        capabilities: CODE_REASON,
        tags: &["cheap", "open-weight"],
        supported_params: PARAMS_STANDARD_REASONING,
    },
    CuratedModel {
        upstream_id: "minimax/minimax-m2.5",
        managed_alias: "open-fast",
        family: "minimax-m2.5",
        snapshot: "2026-07-22",
        context_length: 204_800,
        max_output_tokens: 196_608,
        input_per_mtok: 0.15,
        output_per_mtok: 0.9,
        cache_read_input_per_mtok: Some(0.05),
        cache_write_input_per_mtok: None,
        high_context_pricing: None,
        capabilities: CODE_REASON_MULTI_TOOL,
        tags: &["cheap", "open-weight"],
        supported_params: PARAMS_STANDARD_REASONING,
    },
    CuratedModel {
        upstream_id: "openai/gpt-5.3-codex",
        managed_alias: "coding-frontier",
        family: "gpt-5.3-codex",
        snapshot: "2026-07-22",
        context_length: 400_000,
        max_output_tokens: 128_000,
        input_per_mtok: 1.75,
        output_per_mtok: 14.0,
        cache_read_input_per_mtok: Some(0.175),
        cache_write_input_per_mtok: None,
        high_context_pricing: None,
        capabilities: CODE_REASON_VISION,
        tags: &["code"],
        supported_params: PARAMS_OPENAI_REASONING,
    },
    CuratedModel {
        upstream_id: "qwen/qwen3-coder-next",
        managed_alias: "coding-efficient",
        family: "qwen3-coder",
        snapshot: "2026-07-22",
        context_length: 262_144,
        max_output_tokens: 262_144,
        input_per_mtok: 0.11,
        output_per_mtok: 0.8,
        cache_read_input_per_mtok: Some(0.07),
        cache_write_input_per_mtok: None,
        high_context_pricing: None,
        capabilities: CODE,
        tags: &["code", "cheap", "open-weight"],
        supported_params: PARAMS_STANDARD,
    },
    // Appended from the live `https://openrouter.ai/api/v1/models` catalog on
    // 2026-07-31. OpenRouter publishes USD *per token* as strings; these are
    // those numbers × 1e6: prompt `0.000005` → 5.0 USD/MTok, completion
    // `0.000025` → 25.0, `input_cache_read` `0.0000005` → 0.5,
    // `input_cache_write` `0.00000625` → 6.25. `context_length` 1_000_000 and
    // `top_provider.max_completion_tokens` 128_000 come from the same row. The
    // `-fast` variant (2× price) is deliberately not curated.
    //
    // Note this row is a price/capability/context clone of `claude-opus-4.6`,
    // so the two tie exactly on every adaptive-routing score term. The tie
    // resolves deterministically but on an incidental key, and NOT the way an
    // id-ascending catalog order suggests: `UnifiedRegistry::list` sorts ids
    // ascending, `AdaptiveRouter`'s scoring sort is stable-descending so the
    // tied pair keeps that order, and the Quality lane picks with
    // `Iterator::max_by`, which returns the LAST of equal maxima — so the
    // primary is `4.8`, while the fallback chain, built from the same ordering,
    // still leads with `4.6`. Deterministic, but decided by string ordering
    // rather than merit. Preferring one on purpose needs an explicit signal (a
    // benchmark score, a `deprecated` flag, a tag), not a rename.
    CuratedModel {
        upstream_id: "anthropic/claude-opus-4.8",
        managed_alias: "frontier-deep-next",
        family: "claude-4.8",
        snapshot: "2026-07-31",
        context_length: 1_000_000,
        max_output_tokens: 128_000,
        input_per_mtok: 5.0,
        output_per_mtok: 25.0,
        cache_read_input_per_mtok: Some(0.5),
        cache_write_input_per_mtok: Some(6.25),
        high_context_pricing: None,
        capabilities: CODE_REASON_VISION,
        tags: &["frontier"],
        supported_params: PARAMS_ANTHROPIC_REASONING,
    },
];

fn schema(model: CuratedModel, gateway: bool, parslee_api_base: &str) -> ModelSchema {
    let id = if gateway {
        format!("parslee/openrouter/{}", model.managed_alias)
    } else {
        format!("openrouter/{}", model.upstream_id)
    };
    // Personal OpenRouter receives its raw upstream id. The Parslee gateway
    // receives the full allow-listed gateway id.
    let name = if gateway {
        id.clone()
    } else {
        model.upstream_id.to_string()
    };
    let mut tags = vec!["builtin".to_string(), "openrouter".to_string()];
    tags.extend(model.tags.iter().map(|tag| (*tag).to_string()));
    if gateway {
        tags.extend(["parslee".to_string(), "managed".to_string()]);
    } else {
        tags.extend([
            "personal-key".to_string(),
            "openrouter-baseline".to_string(),
        ]);
    }
    let source = if gateway {
        ModelSource::Proprietary {
            provider: "parslee".to_string(),
            endpoint: parslee_api_base.to_string(),
            auth: ProprietaryAuth::OAuth2Pkce {
                authority: parslee_api_base.to_string(),
                client_id: "parslee-car".to_string(),
                scopes: vec!["inference:invoke".to_string(), "models:list".to_string()],
            },
            protocol: ProprietaryProtocol {
                chat_path: "/api/v1/orgs/{orgId}/inference/responses".to_string(),
                content_type: "application/json".to_string(),
                streaming: true,
                extra_headers: Default::default(),
            },
        }
    } else {
        ModelSource::RemoteApi {
            endpoint: DEFAULT_API_BASE.to_string(),
            api_key_env: API_KEY_ENV.to_string(),
            api_key_envs: Vec::new(),
            api_version: None,
            protocol: ApiProtocol::OpenRouter,
        }
    };
    ModelSchema {
        id,
        name,
        provider: if gateway { "parslee" } else { "openrouter" }.to_string(),
        family: model.family.to_string(),
        version: model.snapshot.to_string(),
        capabilities: model.capabilities.to_vec(),
        context_length: model.context_length,
        max_output_tokens: Some(model.max_output_tokens),
        param_count: String::new(),
        quantization: None,
        performance: PerformanceEnvelope::default(),
        cost: CostModel {
            input_per_mtok: Some(model.input_per_mtok),
            output_per_mtok: Some(model.output_per_mtok),
            cache_read_input_per_mtok: model.cache_read_input_per_mtok,
            cache_write_input_per_mtok: model.cache_write_input_per_mtok,
            pricing_tiers: model
                .high_context_pricing
                .into_iter()
                .map(|tier| crate::schema::TokenPricingTier {
                    min_prompt_tokens: tier.min_prompt_tokens,
                    prices: crate::schema::TokenPrices {
                        input_per_mtok: Some(tier.input_per_mtok),
                        output_per_mtok: Some(tier.output_per_mtok),
                        cache_read_input_per_mtok: tier.cache_read_input_per_mtok,
                        cache_write_input_per_mtok: tier.cache_write_input_per_mtok,
                    },
                })
                .collect(),
            size_mb: None,
            ram_mb: None,
        },
        source,
        tags,
        supported_params: if gateway {
            // The managed CAR → Parslee transport currently forwards only the
            // output-token limit. Keep the advertised contract bounded to the
            // request body we actually send.
            vec![P::MaxTokens]
        } else {
            model.supported_params.to_vec()
        },
        public_benchmarks: Vec::new(),
        trust_tier: TrustTier::Curated,
        deprecated: false,
        available: false,
        // Remote OpenRouter/Parslee models never require a local weight
        // download. Live credential availability remains a separate gate.
        weights_ready: true,
    }
}

/// Return the canonical selector for an allowlisted model using the exact
/// Parslee-managed OpenRouter transport.
///
/// The selector is the reviewed alias ID, never the mutable display/name
/// field. This helper intentionally excludes tags and trust tier: callers use
/// it both to bind outbound requests safely and as one part of the stricter
/// adaptive-trust predicate below.
pub fn canonical_managed_gateway_selector(model: &ModelSchema) -> Option<&str> {
    let canonical_id = is_curated_managed_gateway_alias(&model.id);

    (canonical_id
        && model.provider == "parslee"
        && matches!(
            &model.source,
            ModelSource::Proprietary {
                provider,
                endpoint,
                auth:
                    ProprietaryAuth::OAuth2Pkce {
                        authority,
                        client_id,
                        scopes,
                    },
                protocol,
            } if provider == "parslee"
                && !endpoint.is_empty()
                && endpoint.trim_end_matches('/') == authority.trim_end_matches('/')
                && client_id == "parslee-car"
                && scopes.as_slice() == ["inference:invoke", "models:list"]
                && protocol.chat_path == "/api/v1/orgs/{orgId}/inference/responses"
                && protocol.content_type == "application/json"
                && protocol.streaming
                && protocol.extra_headers.is_empty()
        ))
    .then_some(model.id.as_str())
}

/// Whether `id` is one of the fixed, reviewed Parslee-managed OpenRouter
/// aliases. This reads only the compiled curated catalog: it deliberately
/// does not build or refresh the runtime model registry.
pub fn is_curated_managed_gateway_alias(id: &str) -> bool {
    id.strip_prefix("parslee/openrouter/")
        .is_some_and(|alias| CURATED.iter().any(|entry| entry.managed_alias == alias))
}

/// How long a "this gateway has no OpenRouter upstream" observation suppresses
/// the managed aliases before CAR optimistically advertises them again.
///
/// Bounded rather than permanent because the condition is a *provisioning*
/// state, not a fact about the models: an operator can configure OpenRouter on
/// the Parslee environment at any moment, and CAR has no signal when that
/// happens (`parslee.capabilities` discovers product entitlements — studio,
/// aie, odi, crm — and nothing that enumerates inference upstreams). Fifteen
/// minutes costs at most one failed request per quarter-hour to rediscover,
/// which is the whole price of being wrong in the recoverable direction.
const GATEWAY_UNCONFIGURED_TTL: std::time::Duration = std::time::Duration::from_secs(15 * 60);

/// Default path for the durable observation: `gateway-state.json` under the CAR
/// state root — `~/.car/gateway-state.json` unless `CAR_HOME` moves the root,
/// in which case the observation moves with it. The verdict is about the
/// gateway *this* daemon is pointed at, so it belongs with the daemon's own
/// state rather than being shared across installs.
///
/// Persisted because the in-process static this used to be could not survive a
/// process boundary, and most callers ARE a new process. `car models list` is
/// daemon-first with an in-process fallback, so a fresh daemon, a restarted one,
/// or a CLI run with no daemon all started optimistic again and re-advertised
/// ten aliases that were certain to 503. The suppression only ever helped the
/// one long-lived process that had already made a failing call — which is not
/// the process the user is usually looking at (Parslee-ai/car#786).
pub fn gateway_state_path() -> std::path::PathBuf {
    car_home::root_or_relative().join("gateway-state.json")
}

/// The durable half of the observation.
///
/// Wall-clock rather than `Instant`: a monotonic clock is meaningless once it
/// crosses a process boundary, so persisting one would be persisting a number
/// with no interpretation in the reader.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct GatewayState {
    /// When the managed gateway last answered "OpenRouter is not configured on
    /// this environment". `None` means no such observation is on record.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub openrouter_unconfigured_at: Option<chrono::DateTime<chrono::Utc>>,
}

/// Load, treating a missing or corrupt file as "nothing observed".
///
/// Failing toward "no observation" means failing toward the pre-existing
/// optimistic behaviour, never toward suppressing a namespace the environment
/// can actually serve. A corrupt state file must not make ten models
/// permanently invisible.
pub fn load_gateway_state(path: &std::path::Path) -> GatewayState {
    match std::fs::read_to_string(path) {
        Ok(raw) => serde_json::from_str(&raw).unwrap_or_default(),
        Err(_) => GatewayState::default(),
    }
}

/// Save atomically (temp + rename), creating parent dirs. Best-effort by
/// contract: an unwritable `~/.car` degrades to the old in-process-only
/// behaviour rather than failing an inference call.
pub fn save_gateway_state(path: &std::path::Path, state: &GatewayState) -> std::io::Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let tmp = path.with_extension("json.tmp");
    std::fs::write(&tmp, serde_json::to_string_pretty(state)?)?;
    std::fs::rename(&tmp, path)
}

/// Is an observation taken at `at` still suppressing, as of `now`?
///
/// A timestamp in the FUTURE is treated as no observation at all. That is
/// clock skew or a hand-edited file, and the alternative — trusting it —
/// suppresses the namespace until the clock catches up, which could be
/// arbitrarily long. Fail toward advertising, which costs one failed request.
fn observation_is_live(
    at: chrono::DateTime<chrono::Utc>,
    now: chrono::DateTime<chrono::Utc>,
) -> bool {
    match (now - at).to_std() {
        Ok(elapsed) => elapsed < GATEWAY_UNCONFIGURED_TTL,
        // Negative duration — `at` is in the future.
        Err(_) => false,
    }
}

#[derive(Default)]
struct GatewayObservation {
    /// Whether the durable state has been read this process. The read happens
    /// once, lazily: `gateway_unconfigured()` is consulted per model during
    /// availability derivation, and a disk hit per model would be a real cost
    /// on a hot path.
    loaded: bool,
    at: Option<chrono::DateTime<chrono::Utc>>,
}

fn gateway_observation() -> &'static Mutex<GatewayObservation> {
    static AT: OnceLock<Mutex<GatewayObservation>> = OnceLock::new();
    AT.get_or_init(|| Mutex::new(GatewayObservation::default()))
}

fn observation_guard() -> std::sync::MutexGuard<'static, GatewayObservation> {
    match gateway_observation().lock() {
        Ok(guard) => guard,
        Err(poisoned) => poisoned.into_inner(),
    }
}

/// Record that the managed gateway answered "OpenRouter is not configured on
/// this environment".
///
/// Called from the dispatch loop when the gateway returns that condition. It is
/// environment-scoped — the gateway has no OpenRouter configuration *at all*,
/// so it is identical for every `parslee/openrouter/*` alias and says nothing
/// about any individual model (Parslee-ai/car#786).
///
/// Writes through to disk so the next process starts already knowing.
pub fn note_gateway_unconfigured() {
    let now = chrono::Utc::now();
    {
        let mut guard = observation_guard();
        guard.at = Some(now);
        guard.loaded = true;
    }
    let _ = save_gateway_state(
        &gateway_state_path(),
        &GatewayState {
            openrouter_unconfigured_at: Some(now),
        },
    );
}

/// Whether a recent observation says the managed OpenRouter namespace cannot be
/// served. Drives `available` for those aliases so the catalog stops advertising
/// models that are certain to fail.
///
/// This is CAR *learning* rather than deriving. Availability for these rows
/// derives from `ProprietaryAuth::OAuth2Pkce`, which resolves to exactly "is a
/// Parslee session signed in" — true regardless of what the gateway can serve.
/// There is no discovery endpoint to ask instead, so the only truthful signal
/// available is the gateway's own answer to a real request.
///
/// The observation is read from disk once per process, so what one process
/// learned the next one already knows. Within a process the cached value wins:
/// a long-lived daemon does not re-read the file, so an observation another
/// process writes reaches it on its own next failure rather than immediately.
/// That is deliberate — the daemon is the process making inference calls, so it
/// learns first-hand — and it keeps the hot path free of disk I/O.
pub fn gateway_unconfigured() -> bool {
    let mut guard = observation_guard();
    if !guard.loaded {
        guard.at = load_gateway_state(&gateway_state_path()).openrouter_unconfigured_at;
        guard.loaded = true;
    }
    guard
        .at
        .is_some_and(|at| observation_is_live(at, chrono::Utc::now()))
}

/// Forget the observation. Called when the Parslee session goes away, because
/// what was learned was learned about *that* environment and the next sign-in
/// may be to one that has OpenRouter configured.
///
/// Clears the durable copy too — otherwise signing out and back in to a
/// different environment would inherit the old environment's verdict from disk,
/// which is the whole failure this function exists to prevent.
///
/// Note this catches sign-out, not an org switch within a live session — CAR
/// observes auth presence here, not identity. An org switch therefore keeps the
/// suppression until the TTL expires, which fails in the safe direction (a
/// usable namespace under-advertised for at most one TTL, rather than an
/// unusable one advertised). Persisting does not widen that window: the TTL is
/// wall-clock, so a restart does not restart the clock.
pub fn clear_gateway_unconfigured() {
    {
        let mut guard = observation_guard();
        guard.at = None;
        guard.loaded = true;
    }
    let _ = std::fs::remove_file(gateway_state_path());
}

/// Whether a schema has the exact built-in Parslee-managed OpenRouter
/// identity, metadata, and transport contract.
///
/// Provider names and free-form tags are caller-controlled, so adaptive
/// bootstrap must not treat those strings alone as project curation. This
/// shape is deliberately tied to the reviewed alias allowlist and Parslee's
/// proprietary OAuth/Responses gateway. User-controlled ingestion boundaries
/// independently demote imported schemas to `Community`.
pub(crate) fn is_managed_gateway_schema(model: &ModelSchema) -> bool {
    let Some(canonical_id) = canonical_managed_gateway_selector(model) else {
        return false;
    };
    let has_tag = |expected: &str| model.tags.iter().any(|tag| tag == expected);

    model.name == canonical_id
        && ["builtin", "openrouter", "parslee", "managed"]
            .into_iter()
            .all(has_tag)
}

/// How many curated OpenRouter models the built-in table declares — one
/// personal row and one managed alias each. Tests assert against this rather
/// than a hardcoded literal so adding a reviewed model is a one-line change
/// instead of a hunt through four unrelated count assertions.
pub fn curated_model_count() -> usize {
    CURATED.len()
}

pub fn curated_schemas() -> Vec<ModelSchema> {
    // Use the same explicit override -> persisted connection -> production
    // default resolution as Parslee sign-in. The registry is descriptive;
    // the remote request seam resolves again so a connection switched after
    // registry construction takes effect without restarting CAR.
    let parslee_api_base = car_auth::api_base(None);
    CURATED
        .iter()
        .flat_map(|model| {
            [
                schema(*model, false, &parslee_api_base),
                schema(*model, true, &parslee_api_base),
            ]
        })
        .collect()
}

/// Built-in registry rows: eleven reviewed personal models plus eleven managed
/// aliases. The personal rows are always discoverable; registry availability
/// follows the current credential without adding unreviewed model IDs.
pub fn builtin_schemas() -> Vec<ModelSchema> {
    curated_schemas()
}

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

    #[test]
    fn managed_aliases_follow_the_configured_parslee_api_base() {
        let _environment = test_environment_scope();
        unsafe {
            std::env::set_var(
                car_auth::PARSLEE_API_BASE_KEY,
                "https://staging-api.parslee.ai/",
            );
        }

        let managed: Vec<_> = curated_schemas()
            .into_iter()
            .filter(|schema| schema.provider == "parslee")
            .collect();
        assert_eq!(managed.len(), CURATED.len());
        for schema in managed {
            let ModelSource::Proprietary { endpoint, auth, .. } = schema.source else {
                panic!("managed alias must use the Parslee proprietary transport");
            };
            assert_eq!(endpoint, "https://staging-api.parslee.ai");
            let ProprietaryAuth::OAuth2Pkce { authority, .. } = auth else {
                panic!("managed alias must use the Parslee OAuth connection");
            };
            assert_eq!(authority, "https://staging-api.parslee.ai");
        }

        unsafe {
            std::env::remove_var(car_auth::PARSLEE_API_BASE_KEY);
        }
    }

    #[test]
    fn managed_alias_schema_keeps_the_production_default() {
        let schema = schema(CURATED[0], true, car_auth::DEFAULT_API_BASE);
        let ModelSource::Proprietary { endpoint, auth, .. } = schema.source else {
            panic!("managed alias must use the Parslee proprietary transport");
        };
        assert_eq!(endpoint, car_auth::DEFAULT_API_BASE);
        let ProprietaryAuth::OAuth2Pkce { authority, .. } = auth else {
            panic!("managed alias must use the Parslee OAuth connection");
        };
        assert_eq!(authority, car_auth::DEFAULT_API_BASE);
    }

    #[test]
    fn managed_aliases_match_the_gateway_contract() {
        let managed: Vec<_> = curated_schemas()
            .into_iter()
            .filter(|schema| schema.provider == "parslee")
            .collect();
        assert!(
            managed.iter().all(is_managed_gateway_schema),
            "every reviewed alias must satisfy the managed gateway predicate"
        );
        let ids: Vec<_> = managed.into_iter().map(|schema| schema.id).collect();
        assert_eq!(
            ids,
            [
                "parslee/openrouter/frontier-general",
                "parslee/openrouter/frontier-deep",
                "parslee/openrouter/frontier-multimodal",
                "parslee/openrouter/balanced-general",
                "parslee/openrouter/open-multimodal",
                "parslee/openrouter/open-long-context",
                "parslee/openrouter/open-reasoning",
                "parslee/openrouter/open-fast",
                "parslee/openrouter/coding-frontier",
                "parslee/openrouter/coding-efficient",
                "parslee/openrouter/frontier-deep-next",
            ]
        );
    }

    #[test]
    fn managed_gateway_predicate_rejects_allowlisted_id_with_wrong_selector_name() {
        let mut schema = curated_schemas()
            .into_iter()
            .find(|schema| schema.id == "parslee/openrouter/frontier-general")
            .expect("managed frontier alias");
        schema.name = "attacker-controlled-upstream-selector".into();

        assert!(
            !is_managed_gateway_schema(&schema),
            "an allowlisted id cannot make a different outbound selector trusted"
        );
    }

    #[test]
    fn managed_aliases_deserialize_the_gateway_models_fixture_without_upstream_ids() {
        let fixture: serde_json::Value = serde_json::from_str(include_str!(
            "../tests/fixtures/parslee-openrouter-models.json"
        ))
        .expect("gateway fixture must be valid JSON");
        assert_eq!(fixture["object"], "list");
        let rows = fixture["data"].as_array().expect("data array");
        let ids: Vec<_> = rows
            .iter()
            .map(|row| row["id"].as_str().expect("opaque id"))
            .collect();
        let projected: Vec<_> = curated_schemas()
            .into_iter()
            .filter(|schema| schema.provider == "parslee")
            .map(|schema| schema.id)
            .collect();
        assert_eq!(ids, projected);
        for row in rows {
            assert_eq!(row["object"], "model");
            assert_eq!(row["owned_by"], "parslee");
            assert_eq!(row["provider"], "openrouter");
            assert!(row.get("upstream_model").is_none());
            assert!(!row.to_string().contains("openai/"));
            assert!(!row.to_string().contains("anthropic/"));
            assert!(row["capabilities"].is_array());
            assert!(row["tags"].is_array());
        }
    }

    #[test]
    fn managed_aliases_advertise_only_parameters_the_parslee_transport_forwards() {
        let managed: Vec<_> = builtin_schemas()
            .into_iter()
            .filter(|schema| schema.provider == "parslee")
            .collect();
        assert_eq!(managed.len(), CURATED.len());
        for schema in managed {
            assert_eq!(
                schema.supported_params,
                vec![P::MaxTokens],
                "{} advertises a request control the CAR-to-Parslee transport drops",
                schema.id
            );
        }
    }

    #[test]
    fn projections_are_bounded_distinct_and_price_identical() {
        let schemas = curated_schemas();
        assert_eq!(schemas.len(), CURATED.len() * 2);
        for model in CURATED {
            let personal = schemas
                .iter()
                .find(|s| s.id == format!("openrouter/{}", model.upstream_id))
                .unwrap();
            let gateway = schemas
                .iter()
                .find(|s| s.id == format!("parslee/openrouter/{}", model.managed_alias))
                .unwrap();
            assert_eq!(personal.cost.input_per_mtok, gateway.cost.input_per_mtok);
            assert_eq!(personal.cost.output_per_mtok, gateway.cost.output_per_mtok);
            assert_eq!(
                personal.cost.cache_read_input_per_mtok,
                gateway.cost.cache_read_input_per_mtok
            );
            assert_eq!(
                personal.cost.cache_write_input_per_mtok,
                gateway.cost.cache_write_input_per_mtok
            );
            assert_eq!(personal.cost.pricing_tiers, gateway.cost.pricing_tiers);
            assert_eq!(personal.capabilities, gateway.capabilities);
        }
    }
    #[test]
    fn only_calibrated_models_are_frontier() {
        let frontier: Vec<_> = curated_schemas()
            .into_iter()
            .filter(|s| s.provider == "openrouter" && s.tags.iter().any(|t| t == "frontier"))
            .collect();
        assert_eq!(frontier.len(), 4);
        assert!(frontier
            .iter()
            .all(|s| !s.tags.iter().any(|t| t == "cheap")));
    }

    #[test]
    fn personal_registry_is_exactly_the_reviewed_rows() {
        let personal: Vec<_> = curated_schemas()
            .into_iter()
            .filter(|schema| schema.provider == "openrouter")
            .collect();
        let ids: Vec<_> = personal.iter().map(|schema| schema.id.as_str()).collect();
        assert_eq!(
            ids,
            [
                "openrouter/openai/gpt-5.4",
                "openrouter/anthropic/claude-opus-4.6",
                "openrouter/google/gemini-3.1-pro-preview",
                "openrouter/anthropic/claude-sonnet-4.6",
                "openrouter/moonshotai/kimi-k2.5",
                "openrouter/qwen/qwen3.5-plus-02-15",
                "openrouter/deepseek/deepseek-v3.2",
                "openrouter/minimax/minimax-m2.5",
                "openrouter/openai/gpt-5.3-codex",
                "openrouter/qwen/qwen3-coder-next",
                "openrouter/anthropic/claude-opus-4.8",
            ]
        );
        assert!(personal.iter().all(|schema| {
            schema.trust_tier == TrustTier::Curated
                && schema.tags.iter().any(|tag| tag == "openrouter")
                && schema.tags.iter().any(|tag| tag == "personal-key")
                && !schema.tags.iter().any(|tag| tag == "dynamic")
        }));
    }

    #[test]
    fn personal_capabilities_and_params_match_reviewed_chat_transport_contract() {
        let handler = crate::protocol::handler_for(ApiProtocol::OpenRouter);
        assert!(!handler.supports_audio());
        assert!(!handler.supports_video());
        let expected = [
            ("openrouter/openai/gpt-5.4", CODE_REASON_VISION),
            ("openrouter/anthropic/claude-opus-4.6", CODE_REASON_VISION),
            (
                "openrouter/google/gemini-3.1-pro-preview",
                CODE_REASON_VISION,
            ),
            ("openrouter/anthropic/claude-sonnet-4.6", CODE_REASON_VISION),
            ("openrouter/moonshotai/kimi-k2.5", CODE_REASON_VISION),
            ("openrouter/qwen/qwen3.5-plus-02-15", CODE_REASON_VISION),
            ("openrouter/deepseek/deepseek-v3.2", CODE_REASON),
            ("openrouter/minimax/minimax-m2.5", CODE_REASON_MULTI_TOOL),
            ("openrouter/openai/gpt-5.3-codex", CODE_REASON_VISION),
            ("openrouter/qwen/qwen3-coder-next", CODE),
            ("openrouter/anthropic/claude-opus-4.8", CODE_REASON_VISION),
        ];
        let personal: Vec<_> = curated_schemas()
            .into_iter()
            .filter(|schema| schema.provider == "openrouter")
            .collect();
        for (id, capabilities) in expected {
            let schema = personal.iter().find(|schema| schema.id == id).unwrap();
            assert_eq!(
                schema.capabilities, capabilities,
                "{id} capability metadata drifted from the reviewed model contract"
            );
            assert!(!schema.has_capability(C::VideoUnderstanding));
            assert!(!schema.has_capability(C::AudioUnderstanding));
            assert!(!schema.has_capability(C::ImageGeneration));
            assert!(!schema.has_capability(C::VideoGeneration));
        }

        let transport_params = [
            P::Temperature,
            P::MaxTokens,
            P::ResponseFormat,
            P::ExtendedThinking,
        ];
        for schema in personal {
            assert!(
                schema
                    .supported_params
                    .iter()
                    .all(|parameter| transport_params.contains(parameter)),
                "{} advertises a request parameter CAR's OpenRouter Chat adapter does not send",
                schema.id
            );
        }
    }

    #[test]
    fn current_catalog_prices_include_tiers_and_per_model_cache_rates() {
        let schemas = curated_schemas();
        let gpt = schemas
            .iter()
            .find(|schema| schema.id == "openrouter/openai/gpt-5.4")
            .unwrap();
        assert_eq!(gpt.cost.prices_for(271_999).input_per_mtok, Some(2.5));
        assert_eq!(gpt.cost.prices_for(272_000).input_per_mtok, Some(5.0));
        assert_eq!(gpt.cost.prices_for(272_000).output_per_mtok, Some(22.5));
        assert_eq!(
            gpt.cost.prices_for(272_000).cache_read_input_per_mtok,
            Some(0.5)
        );

        let gemini = schemas
            .iter()
            .find(|schema| schema.id == "openrouter/google/gemini-3.1-pro-preview")
            .unwrap();
        assert_eq!(
            gemini.cost.prices_for(199_999).cache_write_input_per_mtok,
            Some(0.375)
        );
        assert_eq!(gemini.cost.prices_for(200_000).input_per_mtok, Some(4.0));
        assert_eq!(gemini.cost.prices_for(200_000).output_per_mtok, Some(18.0));
        assert_eq!(
            gemini.cost.prices_for(200_000).cache_read_input_per_mtok,
            Some(0.4)
        );

        let kimi = schemas
            .iter()
            .find(|schema| schema.id == "openrouter/moonshotai/kimi-k2.5")
            .unwrap();
        assert_eq!(kimi.cost.cache_read_input_per_mtok, Some(0.095));
        assert_eq!(kimi.cost.cache_write_input_per_mtok, None);
    }

    /// The one place `estimated_usd_bounded`'s substitution ranges are
    /// load-bearing rather than merely descriptive.
    ///
    /// A missing cache-WRITE rate is flagged in both directions, so it stays
    /// honest at any ratio; a missing OUTPUT rate refuses, so refusing is never
    /// wrong. But a missing cache-READ rate claims a real `≤` ceiling, and that
    /// ceiling rests on cache reads being cheaper than uncached input. The
    /// argument is sound — a cache read is a substitute good for sending the
    /// tokens fresh, so a provider pricing it above input would be selling
    /// something whose rational use is "don't use it" — but an argument in a
    /// docstring is not a guard. This makes the assumption fail loudly the day
    /// a provider violates it, instead of silently issuing a ceiling that is
    /// not one.
    #[test]
    fn no_curated_cache_read_rate_exceeds_its_input_rate() {
        for schema in curated_schemas() {
            // Check the base sheet and every declared tier: a tier can
            // override either component independently.
            let thresholds = std::iter::once(0).chain(
                schema
                    .cost
                    .pricing_tiers
                    .iter()
                    .map(|tier| tier.min_prompt_tokens),
            );
            for threshold in thresholds {
                let prices = schema.cost.prices_for(threshold);
                let (Some(input), Some(cache_read)) =
                    (prices.input_per_mtok, prices.cache_read_input_per_mtok)
                else {
                    continue;
                };
                assert!(
                    cache_read <= input,
                    "{} prices a cache read at {cache_read}/MTok above its {input}/MTok input \
                     rate at prompt threshold {threshold}. The `≤` ceiling that \
                     `estimated_usd_bounded` puts on a MISSING cache-read rate assumes this \
                     never happens — if a provider now surcharges cached reads, that \
                     substitution needs both direction flags the way cache write does.",
                    schema.id
                );
            }
        }
    }

    /// Live `https://openrouter.ai/api/v1/models` row for
    /// `anthropic/claude-opus-4.8`, read 2026-07-31: `context_length`
    /// 1000000, `top_provider.max_completion_tokens` 128000, and USD/token
    /// pricing strings `prompt: "0.000005"`, `completion: "0.000025"`,
    /// `input_cache_read: "0.0000005"`, `input_cache_write: "0.00000625"` —
    /// each × 1e6 for this catalog's USD/MTok unit.
    #[test]
    fn claude_opus_4_8_matches_the_live_openrouter_catalog_row() {
        let schemas = curated_schemas();
        let personal = schemas
            .iter()
            .find(|schema| schema.id == "openrouter/anthropic/claude-opus-4.8")
            .expect("built-in curated row, no runtime registration");
        assert_eq!(personal.provider, "openrouter");
        assert_eq!(personal.context_length, 1_000_000);
        assert_eq!(personal.max_output_tokens, Some(128_000));
        assert_eq!(personal.cost.input_per_mtok, Some(5.0));
        assert_eq!(personal.cost.output_per_mtok, Some(25.0));
        assert_eq!(personal.cost.cache_read_input_per_mtok, Some(0.5));
        assert_eq!(personal.cost.cache_write_input_per_mtok, Some(6.25));
        assert!(personal.cost.pricing_tiers.is_empty());
        assert_eq!(personal.version, "2026-07-31");

        // The alias fronts it without naming it.
        let alias = schemas
            .iter()
            .find(|schema| schema.id == "parslee/openrouter/frontier-deep-next")
            .expect("matching managed alias row");
        assert!(is_managed_gateway_schema(alias));
        assert!(!serde_json::to_string(alias).unwrap().contains("opus-4.8"));
    }

    /// Frozen expectations for the ten rows that predate `claude-opus-4.8`,
    /// so a future catalog edit that silently reprices or resizes one fails
    /// here rather than in a customer's invoice.
    ///
    /// This cements the **2026-07-22 snapshot**, deliberately. Live OpenRouter
    /// has already drifted from it in at least one place (`qwen3-coder-next`
    /// publishes 0.12 input today against the 0.11 frozen here). That is not a
    /// bug to fix in passing: each row declares the date it was read on, and
    /// re-snapshotting prices is a separate, deliberate act that updates the
    /// numbers and the `snapshot` date together. If you are here because this
    /// test failed after a re-snapshot, update both.
    ///
    /// Capabilities are asserted by
    /// `personal_capabilities_and_params_match_reviewed_chat_transport_contract`,
    /// which is why this one does not claim them in its name.
    #[test]
    fn the_ten_preexisting_rows_keep_their_ids_prices_and_sizes() {
        // id, input, output, cache read, cache write, context, max output.
        let expected: &[(&str, f64, f64, Option<f64>, Option<f64>, usize, usize)] = &[
            (
                "openrouter/openai/gpt-5.4",
                2.5,
                15.0,
                Some(0.25),
                None,
                1_050_000,
                128_000,
            ),
            (
                "openrouter/anthropic/claude-opus-4.6",
                5.0,
                25.0,
                Some(0.5),
                Some(6.25),
                1_000_000,
                128_000,
            ),
            (
                "openrouter/google/gemini-3.1-pro-preview",
                2.0,
                12.0,
                Some(0.2),
                Some(0.375),
                1_048_576,
                65_536,
            ),
            (
                "openrouter/anthropic/claude-sonnet-4.6",
                3.0,
                15.0,
                Some(0.3),
                Some(3.75),
                1_000_000,
                128_000,
            ),
            (
                "openrouter/moonshotai/kimi-k2.5",
                0.57,
                2.85,
                Some(0.095),
                None,
                262_144,
                262_144,
            ),
            (
                "openrouter/qwen/qwen3.5-plus-02-15",
                0.26,
                1.56,
                None,
                None,
                1_000_000,
                65_536,
            ),
            (
                "openrouter/deepseek/deepseek-v3.2",
                0.269,
                0.4,
                Some(0.1345),
                None,
                163_840,
                65_536,
            ),
            (
                "openrouter/minimax/minimax-m2.5",
                0.15,
                0.9,
                Some(0.05),
                None,
                204_800,
                196_608,
            ),
            (
                "openrouter/openai/gpt-5.3-codex",
                1.75,
                14.0,
                Some(0.175),
                None,
                400_000,
                128_000,
            ),
            (
                "openrouter/qwen/qwen3-coder-next",
                0.11,
                0.8,
                Some(0.07),
                None,
                262_144,
                262_144,
            ),
        ];
        let schemas = curated_schemas();
        assert_eq!(
            expected.len() + 1,
            curated_model_count(),
            "this list must cover every curated row except the one added after it"
        );
        for (id, input, output, cache_read, cache_write, context, max_output) in expected {
            let schema = schemas
                .iter()
                .find(|schema| &schema.id == id)
                .unwrap_or_else(|| panic!("{id} must not be removed or renamed"));
            assert_eq!(schema.context_length, *context, "{id} context window");
            assert_eq!(
                schema.max_output_tokens,
                Some(*max_output),
                "{id} max output tokens"
            );
            assert_eq!(schema.cost.input_per_mtok, Some(*input), "{id} input price");
            assert_eq!(
                schema.cost.output_per_mtok,
                Some(*output),
                "{id} output price"
            );
            assert_eq!(
                schema.cost.cache_read_input_per_mtok, *cache_read,
                "{id} cache-read price"
            );
            assert_eq!(
                schema.cost.cache_write_input_per_mtok, *cache_write,
                "{id} cache-write price"
            );
            assert_eq!(schema.version, "2026-07-22", "{id} snapshot date");
        }

        // The one high-context tier nothing else pinned. gpt-5.4's and
        // gemini's tiers are asserted by
        // `current_catalog_prices_include_tiers_and_per_model_cache_rates`;
        // qwen3.5-plus's was unguarded until now.
        let qwen = schemas
            .iter()
            .find(|schema| schema.id == "openrouter/qwen/qwen3.5-plus-02-15")
            .unwrap();
        assert_eq!(qwen.cost.prices_for(255_999).input_per_mtok, Some(0.26));
        assert_eq!(qwen.cost.prices_for(255_999).output_per_mtok, Some(1.56));
        assert_eq!(qwen.cost.prices_for(256_000).input_per_mtok, Some(0.325));
        assert_eq!(qwen.cost.prices_for(256_000).output_per_mtok, Some(1.95));
        // It publishes no cache rates at either tier — the case that makes the
        // stats column report a bounded estimate rather than a fabricated $0.
        assert_eq!(
            qwen.cost.prices_for(256_000).cache_read_input_per_mtok,
            None
        );
        assert_eq!(
            qwen.cost.prices_for(256_000).cache_write_input_per_mtok,
            None
        );
    }
}

#[cfg(test)]
mod gateway_state_tests {
    use super::*;
    use chrono::{Duration, Utc};

    fn tmp(name: &str) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!("car-gw-{}-{}", name, std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        dir.join("gateway-state.json")
    }

    /// The bug this fix exists for. Before persisting, the observation lived in
    /// a process-global static, so a SECOND process — a fresh daemon, a
    /// restarted one, or a CLI run with no daemon — knew nothing and
    /// re-advertised ten aliases certain to 503.
    #[test]
    fn an_observation_survives_the_process_that_made_it() {
        let path = tmp("survives");
        let _ = std::fs::remove_file(&path);

        // Process A learns.
        save_gateway_state(
            &path,
            &GatewayState {
                openrouter_unconfigured_at: Some(Utc::now()),
            },
        )
        .unwrap();

        // Process B reads it back and is still suppressing.
        let reloaded = load_gateway_state(&path);
        let at = reloaded
            .openrouter_unconfigured_at
            .expect("process B must inherit the observation");
        assert!(observation_is_live(at, Utc::now()));
    }

    #[test]
    fn a_missing_file_means_nothing_observed() {
        let path = tmp("missing").with_file_name("definitely-absent.json");
        assert!(load_gateway_state(&path)
            .openrouter_unconfigured_at
            .is_none());
    }

    /// A corrupt state file must not make ten models permanently invisible —
    /// fail toward the optimistic pre-existing behaviour.
    #[test]
    fn a_corrupt_file_means_nothing_observed_rather_than_suppressed() {
        let path = tmp("corrupt");
        std::fs::write(&path, "{ this is not json").unwrap();
        assert!(load_gateway_state(&path)
            .openrouter_unconfigured_at
            .is_none());
    }

    #[test]
    fn the_ttl_still_expires_across_a_restart() {
        let now = Utc::now();
        let fresh = now - Duration::minutes(1);
        let stale = now - Duration::minutes(16);
        assert!(
            observation_is_live(fresh, now),
            "1 min old is inside the 15 min TTL"
        );
        assert!(
            !observation_is_live(stale, now),
            "16 min old must have expired"
        );
    }

    /// Persisting must not restart the clock on a restart, or a daemon bounce
    /// every 14 minutes would suppress the namespace forever.
    #[test]
    fn a_restart_does_not_refresh_an_aging_observation() {
        let path = tmp("aging");
        let old = Utc::now() - Duration::minutes(16);
        save_gateway_state(
            &path,
            &GatewayState {
                openrouter_unconfigured_at: Some(old),
            },
        )
        .unwrap();
        let at = load_gateway_state(&path)
            .openrouter_unconfigured_at
            .unwrap();
        assert!(!observation_is_live(at, Utc::now()));
    }

    /// Clock skew, or a hand-edited file. Trusting a future timestamp would
    /// suppress until the clock caught up, which is unbounded.
    #[test]
    fn a_future_timestamp_is_treated_as_no_observation() {
        let now = Utc::now();
        assert!(!observation_is_live(now + Duration::hours(1), now));
    }

    #[test]
    fn the_state_file_round_trips_and_omits_an_absent_observation() {
        let path = tmp("roundtrip");
        save_gateway_state(&path, &GatewayState::default()).unwrap();
        let raw = std::fs::read_to_string(&path).unwrap();
        assert!(
            !raw.contains("openrouter_unconfigured_at"),
            "an absent observation should not be written: {raw}"
        );
        assert!(load_gateway_state(&path)
            .openrouter_unconfigured_at
            .is_none());
    }

    /// Atomic write: the reader must never observe a half-written file, and a
    /// second save must replace rather than append.
    #[test]
    fn saving_twice_replaces_rather_than_appends() {
        let path = tmp("twice");
        let first = Utc::now() - Duration::minutes(5);
        let second = Utc::now();
        save_gateway_state(
            &path,
            &GatewayState {
                openrouter_unconfigured_at: Some(first),
            },
        )
        .unwrap();
        save_gateway_state(
            &path,
            &GatewayState {
                openrouter_unconfigured_at: Some(second),
            },
        )
        .unwrap();
        let at = load_gateway_state(&path)
            .openrouter_unconfigured_at
            .unwrap();
        assert!(
            (at - second).num_seconds().abs() < 2,
            "second save must win"
        );
        assert!(
            !path.with_extension("json.tmp").exists(),
            "temp file left behind"
        );
    }
}