agent-quota-core 0.4.1

Local-credential quota probes for Codex, Claude Code, and AI coding agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
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
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
#![warn(missing_docs)]
//! Local-credential quota probes for AI coding agents.
//!
//! Agent Quota reads locally configured accounts, performs the smallest
//! provider-specific check available, and returns a versioned, provider-neutral
//! snapshot. A successful probe and usable quota are represented separately so
//! consumers do not need to infer routing decisions from transport health.

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use std::{fs, process::Stdio};

use reqwest::header::HeaderMap;
use reqwest::redirect::Policy;
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::{ChildStdin, Command};
use tokio::sync::Mutex;
use tokio::time::timeout;

const DEFAULT_CODEX_TIMEOUT: Duration = Duration::from_secs(10);
const DEFAULT_CLAUDE_TIMEOUT: Duration = Duration::from_secs(20);
const DEFAULT_CACHE_TTL: Duration = Duration::from_secs(5 * 60);
const CLAUDE_USAGE_MODEL: &str = "claude-haiku-4-5-20251001";
const CLAUDE_API_URL: &str = "https://api.anthropic.com/v1/messages";
const CLAUDE_CREDENTIALS_RELATIVE_PATH: &str = ".claude/.credentials.json";

#[cfg(target_os = "windows")]
const CREATE_NO_WINDOW: u32 = 0x0800_0000;

/// Current serialized snapshot schema.
pub const SNAPSHOT_SCHEMA_VERSION: u32 = 1;

/// Result type used for configuration operations.
pub type AgentQuotaResult<T> = Result<T, AgentQuotaError>;

/// Configuration loading or validation error.
#[derive(Debug)]
pub enum AgentQuotaError {
    /// The configuration file could not be read.
    ConfigRead {
        /// Path that could not be read.
        path: PathBuf,
        /// Underlying filesystem error.
        source: std::io::Error,
    },
    /// The configuration file is not valid TOML or contains unknown fields.
    ConfigParse {
        /// Path containing invalid configuration.
        path: PathBuf,
        /// Parser diagnostic.
        message: String,
    },
    /// The configuration is syntactically valid but semantically unsafe.
    ConfigValidation {
        /// Human-readable validation diagnostic.
        message: String,
    },
}

impl std::fmt::Display for AgentQuotaError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::ConfigRead { path, source } => {
                write!(formatter, "could not read {}: {source}", path.display())
            }
            Self::ConfigParse { path, message } => {
                write!(
                    formatter,
                    "invalid configuration in {}: {message}",
                    path.display()
                )
            }
            Self::ConfigValidation { message } => formatter.write_str(message),
        }
    }
}

impl std::error::Error for AgentQuotaError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::ConfigRead { source, .. } => Some(source),
            Self::ConfigParse { .. } | Self::ConfigValidation { .. } => None,
        }
    }
}

/// Supported quota provider.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProviderId {
    /// OpenAI Codex CLI.
    Codex,
    /// Anthropic Claude Code credentials.
    Claude,
}

impl ProviderId {
    /// Stable provider identifier.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Codex => "codex",
            Self::Claude => "claude",
        }
    }

    /// Human-readable provider name.
    pub fn label(self) -> &'static str {
        match self {
            Self::Codex => "Codex",
            Self::Claude => "Claude Code",
        }
    }

    /// Parse a provider name or common alias.
    pub fn from_name(value: &str) -> Option<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "codex" | "openai-codex" => Some(Self::Codex),
            "claude" | "claude-code" | "anthropic" => Some(Self::Claude),
            _ => None,
        }
    }
}

/// One locally configured provider account.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub struct ProviderProfile {
    /// Stable, non-empty profile identifier.
    pub id: String,
    /// Provider used by this profile.
    pub provider: ProviderId,
    /// Optional human-readable label.
    pub label: Option<String>,
    /// Optional Codex executable path.
    pub command_path: Option<PathBuf>,
    /// Optional Claude Code credentials file.
    pub credentials_path: Option<PathBuf>,
    /// Codex process environment overrides.
    #[serde(default)]
    pub env: BTreeMap<String, String>,
    /// Whether this profile participates in configured collection.
    #[serde(default = "default_enabled")]
    pub enabled: bool,
}

impl ProviderProfile {
    /// Construct the conventional local profile for a provider.
    pub fn default_for_provider(provider: ProviderId) -> Self {
        Self {
            id: provider.as_str().to_owned(),
            provider,
            label: None,
            command_path: None,
            credentials_path: None,
            env: BTreeMap::new(),
            enabled: true,
        }
    }

    /// Human-readable profile name.
    pub fn display_name(&self) -> String {
        self.label
            .as_deref()
            .filter(|value| !value.trim().is_empty())
            .map(ToOwned::to_owned)
            .unwrap_or_else(|| self.provider.label().to_owned())
    }

    /// Validate provider-specific and identity fields.
    pub fn validate(&self) -> AgentQuotaResult<()> {
        if self.id.trim().is_empty() {
            return Err(validation_error("profile id must not be empty"));
        }
        if self.id.trim() != self.id {
            return Err(validation_error(format!(
                "profile id `{}` must not start or end with whitespace",
                self.id
            )));
        }
        if self
            .label
            .as_ref()
            .is_some_and(|label| label.trim().is_empty())
        {
            return Err(validation_error(format!(
                "profile `{}` has an empty label; omit `label` to use the provider name",
                self.id
            )));
        }

        match self.provider {
            ProviderId::Codex if self.credentials_path.is_some() => {
                return Err(validation_error(format!(
                    "profile `{}` is Codex, so `credentials_path` is not supported",
                    self.id
                )));
            }
            ProviderId::Claude if self.command_path.is_some() => {
                return Err(validation_error(format!(
                    "profile `{}` is Claude, so `command_path` is not supported",
                    self.id
                )));
            }
            ProviderId::Claude if !self.env.is_empty() => {
                return Err(validation_error(format!(
                    "profile `{}` is Claude, so process environment overrides are not supported",
                    self.id
                )));
            }
            ProviderId::Codex | ProviderId::Claude => {}
        }
        Ok(())
    }
}

fn default_enabled() -> bool {
    true
}

/// Top-level TOML configuration.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub struct AgentQuotaConfig {
    /// Configured provider accounts.
    #[serde(default)]
    pub profiles: Vec<ProviderProfile>,
}

impl AgentQuotaConfig {
    /// Load and validate a TOML configuration file.
    pub fn load(path: impl AsRef<Path>) -> AgentQuotaResult<Self> {
        let path = path.as_ref();
        let raw = fs::read_to_string(path).map_err(|source| AgentQuotaError::ConfigRead {
            path: path.to_path_buf(),
            source,
        })?;
        let config =
            toml::from_str::<Self>(&raw).map_err(|error| AgentQuotaError::ConfigParse {
                path: path.to_path_buf(),
                message: error.to_string(),
            })?;
        config.validate()?;
        Ok(config)
    }

    /// Validate profile identities and provider-specific fields.
    pub fn validate(&self) -> AgentQuotaResult<()> {
        let mut ids = BTreeSet::new();
        for profile in &self.profiles {
            profile.validate()?;
            if !ids.insert(&profile.id) {
                return Err(validation_error(format!(
                    "profile id `{}` is defined more than once",
                    profile.id
                )));
            }
        }
        Ok(())
    }

    /// Return enabled profiles in configuration order.
    pub fn profiles(&self) -> Vec<ProviderProfile> {
        self.profiles
            .iter()
            .filter(|profile| profile.enabled)
            .cloned()
            .collect()
    }
}

fn validation_error(message: impl Into<String>) -> AgentQuotaError {
    AgentQuotaError::ConfigValidation {
        message: message.into(),
    }
}

/// Explicit set of accounts to collect.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum UsageSelection {
    All,
    Providers(Vec<ProviderId>),
    Profiles(Vec<ProviderProfile>),
}

/// Options identifying exactly which provider accounts to collect.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct CollectUsageOptions {
    selection: UsageSelection,
}

impl Default for CollectUsageOptions {
    fn default() -> Self {
        Self::all()
    }
}

impl CollectUsageOptions {
    /// Collect conventional local profiles for every supported provider.
    pub fn all() -> Self {
        Self {
            selection: UsageSelection::All,
        }
    }

    /// Collect conventional profiles for exactly the supplied providers.
    ///
    /// An empty iterator performs no probes.
    pub fn providers(providers: impl IntoIterator<Item = ProviderId>) -> Self {
        Self {
            selection: UsageSelection::Providers(providers.into_iter().collect()),
        }
    }

    /// Collect exactly the supplied enabled profiles.
    ///
    /// An empty iterator performs no probes.
    pub fn profiles(profiles: impl IntoIterator<Item = ProviderProfile>) -> Self {
        Self {
            selection: UsageSelection::Profiles(profiles.into_iter().collect()),
        }
    }

    fn selected_profiles(&self) -> Vec<ProviderProfile> {
        match &self.selection {
            UsageSelection::All => vec![
                ProviderProfile::default_for_provider(ProviderId::Codex),
                ProviderProfile::default_for_provider(ProviderId::Claude),
            ],
            UsageSelection::Providers(providers) => providers
                .iter()
                .copied()
                .map(ProviderProfile::default_for_provider)
                .collect(),
            UsageSelection::Profiles(profiles) => profiles
                .iter()
                .filter(|profile| profile.enabled)
                .cloned()
                .collect(),
        }
    }
}

/// Health of the provider probe itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProbeStatus {
    /// Provider returned a recognizable quota response.
    Ok,
    /// Local credentials are missing or rejected.
    AuthenticationRequired,
    /// Installed provider version does not expose compatible quota data.
    Unsupported,
    /// A retryable process, network, or provider failure occurred.
    TransientError,
    /// Provider returned a response that could not be interpreted safely.
    InvalidResponse,
    /// The supplied profile is invalid.
    InvalidConfiguration,
}

/// Whether normalized quota permits another agent run.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum QuotaState {
    /// Every reported blocking window has remaining capacity.
    Available,
    /// At least one reported blocking window is exhausted.
    Exhausted,
    /// Capacity cannot be determined.
    Unknown,
}

/// Stable machine-readable failure category.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProviderUsageErrorCode {
    /// Profile fields are invalid.
    InvalidConfiguration,
    /// Required executable is not installed or not discoverable.
    ExecutableNotFound,
    /// Credential file is unavailable.
    CredentialsUnavailable,
    /// Provider rejected or could not find credentials.
    AuthenticationRequired,
    /// Provider did not respond before the configured deadline.
    Timeout,
    /// Network transport failed.
    Network,
    /// Provider returned an unsuccessful response.
    ProviderResponse,
    /// Response shape could not be interpreted.
    InvalidResponse,
    /// Provider version does not expose the expected quota interface.
    Unsupported,
}

/// Structured probe failure for automation and user interfaces.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProviderUsageError {
    /// Stable error code.
    pub code: ProviderUsageErrorCode,
    /// Safe human-readable diagnostic.
    pub message: String,
    /// Whether retrying later may succeed without user action.
    pub retryable: bool,
}

/// Normalized provider quota snapshot.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProviderUsageSnapshot {
    /// Serialized schema version.
    pub schema_version: u32,
    /// Stable provider identifier.
    pub provider_id: ProviderId,
    /// Human-readable provider name.
    pub provider_name: String,
    /// Stable profile identifier.
    pub profile_id: String,
    /// Human-readable profile name.
    pub profile_name: String,
    /// Provider account label, when exposed.
    pub account_label: Option<String>,
    /// Machine-readable origin of quota data.
    pub source: Option<String>,
    /// Health of the quota probe.
    pub probe_status: ProbeStatus,
    /// Whether reported quota permits more work.
    pub quota_state: QuotaState,
    /// Provider subscription plan, when exposed.
    pub plan: Option<String>,
    /// Normalized quota windows.
    pub windows: Vec<ProviderUsageWindow>,
    /// Observation time in Unix epoch milliseconds.
    pub observed_at_ms: i64,
    /// Optional informational note.
    pub message: Option<String>,
    /// Structured error when the probe did not succeed.
    pub error: Option<ProviderUsageError>,
}

impl ProviderUsageSnapshot {
    /// Return whether this snapshot is a safe positive signal for new work.
    ///
    /// A probe must have completed successfully and reported available quota.
    /// Keeping the two checks together prevents callers from treating an
    /// unknown quota state or a failed probe as usable capacity.
    pub fn is_ready(&self) -> bool {
        self.probe_status == ProbeStatus::Ok && self.quota_state == QuotaState::Available
    }
}

/// One provider quota window.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProviderUsageWindow {
    /// Normalized window category.
    pub kind: ProviderUsageWindowKind,
    /// Human-readable label.
    pub label: String,
    /// Consumed capacity from zero to one hundred.
    pub used_percent: Option<f64>,
    /// Remaining capacity from zero to one hundred.
    pub remaining_percent: Option<f64>,
    /// Window duration in minutes.
    pub window_minutes: Option<u64>,
    /// Reset time in Unix epoch seconds.
    pub resets_at_epoch_seconds: Option<i64>,
    /// Optional provider status detail.
    pub detail: Option<String>,
}

/// Normalized quota window category.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProviderUsageWindowKind {
    /// Rolling five-hour window.
    FiveHour,
    /// Rolling or calendar weekly window.
    Weekly,
    /// Provider-specific window.
    Other,
}

#[derive(Debug, Clone)]
struct ProbeFailure {
    error: ProviderUsageError,
}

impl ProbeFailure {
    fn new(code: ProviderUsageErrorCode, message: impl Into<String>, retryable: bool) -> Self {
        Self {
            error: ProviderUsageError {
                code,
                message: message.into(),
                retryable,
            },
        }
    }

    fn status(&self) -> ProbeStatus {
        match self.error.code {
            ProviderUsageErrorCode::InvalidConfiguration => ProbeStatus::InvalidConfiguration,
            ProviderUsageErrorCode::CredentialsUnavailable
            | ProviderUsageErrorCode::AuthenticationRequired => ProbeStatus::AuthenticationRequired,
            ProviderUsageErrorCode::Unsupported => ProbeStatus::Unsupported,
            ProviderUsageErrorCode::InvalidResponse => ProbeStatus::InvalidResponse,
            ProviderUsageErrorCode::ExecutableNotFound
            | ProviderUsageErrorCode::Timeout
            | ProviderUsageErrorCode::Network
            | ProviderUsageErrorCode::ProviderResponse => ProbeStatus::TransientError,
        }
    }
}

/// Reusable collector with injectable transport settings.
#[derive(Debug, Clone)]
pub struct AgentQuotaClient {
    http_client: reqwest::Client,
    claude_api_url: String,
    claude_model: String,
    codex_timeout: Duration,
    claude_timeout: Duration,
}

impl Default for AgentQuotaClient {
    fn default() -> Self {
        let http_client = reqwest::Client::builder()
            .user_agent(concat!("agent-quota/", env!("CARGO_PKG_VERSION")))
            .redirect(Policy::none())
            .build()
            .unwrap_or_else(|_| reqwest::Client::new());
        Self {
            http_client,
            claude_api_url: CLAUDE_API_URL.to_owned(),
            claude_model: CLAUDE_USAGE_MODEL.to_owned(),
            codex_timeout: DEFAULT_CODEX_TIMEOUT,
            claude_timeout: DEFAULT_CLAUDE_TIMEOUT,
        }
    }
}

impl AgentQuotaClient {
    /// Construct a collector with production defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// Override the HTTP client, useful for embedding and tests.
    ///
    /// The default client disables redirects. A custom client is responsible
    /// for protecting authorization headers across redirects and proxies.
    pub fn with_http_client(mut self, http_client: reqwest::Client) -> Self {
        self.http_client = http_client;
        self
    }

    /// Override the Claude Messages endpoint, useful for deterministic tests.
    ///
    /// The local OAuth token is sent to this URL. Never accept the URL from
    /// untrusted input.
    pub fn with_claude_api_url(mut self, url: impl Into<String>) -> Self {
        self.claude_api_url = url.into();
        self
    }

    /// Override the minimal Claude model used to obtain quota headers.
    pub fn with_claude_model(mut self, model: impl Into<String>) -> Self {
        self.claude_model = model.into();
        self
    }

    /// Override provider deadlines.
    pub fn with_timeouts(mut self, codex: Duration, claude: Duration) -> Self {
        self.codex_timeout = codex;
        self.claude_timeout = claude;
        self
    }

    /// Collect normalized snapshots for an explicit selection.
    pub async fn collect_usage(&self, options: CollectUsageOptions) -> Vec<ProviderUsageSnapshot> {
        let probes = options
            .selected_profiles()
            .into_iter()
            .map(|profile| self.collect_profile_usage(profile));
        futures::future::join_all(probes).await
    }

    /// Collect one configured profile.
    pub async fn collect_profile_usage(&self, profile: ProviderProfile) -> ProviderUsageSnapshot {
        if let Err(error) = profile.validate() {
            return failed_snapshot(
                &profile,
                ProbeFailure::new(
                    ProviderUsageErrorCode::InvalidConfiguration,
                    error.to_string(),
                    false,
                ),
            );
        }

        let result = match profile.provider {
            ProviderId::Codex => self.query_codex_usage(&profile).await,
            ProviderId::Claude => self.query_claude_usage(&profile).await,
        };
        result.unwrap_or_else(|error| failed_snapshot(&profile, error))
    }

    async fn query_codex_usage(
        &self,
        profile: &ProviderProfile,
    ) -> Result<ProviderUsageSnapshot, ProbeFailure> {
        let executable = profile
            .command_path
            .as_deref()
            .unwrap_or_else(|| Path::new("codex"));
        let mut command = Command::new(executable);
        command.args(["app-server", "--listen", "stdio://"]);
        command.envs(&profile.env);
        command
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .kill_on_drop(true);
        #[cfg(target_os = "windows")]
        command.creation_flags(CREATE_NO_WINDOW);

        let mut child = command.spawn().map_err(|error| {
            let code = if error.kind() == std::io::ErrorKind::NotFound {
                ProviderUsageErrorCode::ExecutableNotFound
            } else {
                ProviderUsageErrorCode::ProviderResponse
            };
            ProbeFailure::new(
                code,
                format!("could not start `{}`: {error}", executable.display()),
                true,
            )
        })?;
        let mut stdin = child.stdin.take().ok_or_else(|| {
            ProbeFailure::new(
                ProviderUsageErrorCode::InvalidResponse,
                "Codex app-server stdin was unavailable",
                true,
            )
        })?;
        let stdout = child.stdout.take().ok_or_else(|| {
            ProbeFailure::new(
                ProviderUsageErrorCode::InvalidResponse,
                "Codex app-server stdout was unavailable",
                true,
            )
        })?;

        write_rpc(
            &mut stdin,
            json!({
                "method": "initialize",
                "id": 1,
                "params": {
                    "clientInfo": {
                        "name": "agent_quota",
                        "title": "Agent Quota",
                        "version": env!("CARGO_PKG_VERSION"),
                    }
                }
            }),
        )
        .await
        .map_err(codex_io_failure)?;
        write_rpc(&mut stdin, json!({ "method": "initialized", "params": {} }))
            .await
            .map_err(codex_io_failure)?;
        write_rpc(
            &mut stdin,
            json!({
                "method": "account/read",
                "id": 2,
                "params": { "refreshToken": false }
            }),
        )
        .await
        .map_err(codex_io_failure)?;
        write_rpc(
            &mut stdin,
            json!({ "method": "account/rateLimits/read", "id": 3 }),
        )
        .await
        .map_err(codex_io_failure)?;

        let mut lines = BufReader::new(stdout).lines();
        let read = async {
            let mut account_response = None;
            let mut rate_limits_response = None;
            while account_response.is_none() || rate_limits_response.is_none() {
                let Some(line) = lines.next_line().await.map_err(codex_io_failure)? else {
                    break;
                };
                let Ok(value) = serde_json::from_str::<Value>(&line) else {
                    continue;
                };
                match value.get("id").and_then(Value::as_i64) {
                    Some(2) => account_response = Some(value),
                    Some(3) => rate_limits_response = Some(value),
                    _ => {}
                }
            }
            let account_response = account_response.ok_or_else(|| {
                ProbeFailure::new(
                    ProviderUsageErrorCode::InvalidResponse,
                    "Codex account response was missing",
                    true,
                )
            })?;
            let rate_limits_response = rate_limits_response.ok_or_else(|| {
                ProbeFailure::new(
                    ProviderUsageErrorCode::InvalidResponse,
                    "Codex rate-limit response was missing",
                    true,
                )
            })?;
            Ok::<_, ProbeFailure>((account_response, rate_limits_response))
        };

        let responses = timeout(self.codex_timeout, read).await.map_err(|_| {
            ProbeFailure::new(
                ProviderUsageErrorCode::Timeout,
                "timed out waiting for Codex quota data",
                true,
            )
        })??;
        let _ = child.kill().await;
        codex_snapshot_from_responses(profile, &responses.0, &responses.1)
    }

    async fn query_claude_usage(
        &self,
        profile: &ProviderProfile,
    ) -> Result<ProviderUsageSnapshot, ProbeFailure> {
        let token = read_claude_oauth_token(profile.credentials_path.as_deref())?;
        let request = self
            .http_client
            .post(&self.claude_api_url)
            .bearer_auth(token)
            .header("anthropic-version", "2023-06-01")
            .header("anthropic-beta", "oauth-2025-04-20")
            .json(&json!({
                "model": self.claude_model,
                "max_tokens": 1,
                "messages": [{ "role": "user", "content": "hi" }],
            }));
        let response = timeout(self.claude_timeout, request.send())
            .await
            .map_err(|_| {
                ProbeFailure::new(
                    ProviderUsageErrorCode::Timeout,
                    "timed out waiting for Claude quota headers",
                    true,
                )
            })?
            .map_err(|error| {
                ProbeFailure::new(
                    ProviderUsageErrorCode::Network,
                    format!("Claude quota request failed: {error}"),
                    true,
                )
            })?;

        let status = response.status();
        let snapshot = claude_snapshot_from_headers(profile, response.headers(), status)?;
        if status.is_success() || status == StatusCode::TOO_MANY_REQUESTS {
            Ok(snapshot)
        } else {
            Err(http_status_failure("Claude", status))
        }
    }
}

fn codex_io_failure(error: std::io::Error) -> ProbeFailure {
    ProbeFailure::new(
        ProviderUsageErrorCode::ProviderResponse,
        format!("Codex app-server communication failed: {error}"),
        true,
    )
}

fn http_status_failure(provider: &str, status: StatusCode) -> ProbeFailure {
    if matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN) {
        ProbeFailure::new(
            ProviderUsageErrorCode::AuthenticationRequired,
            format!("{provider} rejected the local credentials ({status})"),
            false,
        )
    } else {
        ProbeFailure::new(
            ProviderUsageErrorCode::ProviderResponse,
            format!("{provider} returned HTTP {status}"),
            status.is_server_error() || status == StatusCode::TOO_MANY_REQUESTS,
        )
    }
}

async fn write_rpc(stdin: &mut ChildStdin, value: Value) -> std::io::Result<()> {
    stdin.write_all(value.to_string().as_bytes()).await?;
    stdin.write_all(b"\n").await?;
    stdin.flush().await
}

fn rpc_failure(value: &Value, operation: &str) -> Option<ProbeFailure> {
    let error = value.get("error")?;
    let message = error
        .get("message")
        .and_then(Value::as_str)
        .unwrap_or("unknown provider error");
    let lower = message.to_ascii_lowercase();
    let authentication = ["auth", "login", "sign in", "credential"]
        .iter()
        .any(|needle| lower.contains(needle));
    Some(if authentication {
        ProbeFailure::new(
            ProviderUsageErrorCode::AuthenticationRequired,
            format!("Codex {operation} failed: {message}"),
            false,
        )
    } else {
        ProbeFailure::new(
            ProviderUsageErrorCode::ProviderResponse,
            format!("Codex {operation} failed: {message}"),
            true,
        )
    })
}

fn codex_snapshot_from_responses(
    profile: &ProviderProfile,
    account_response: &Value,
    rate_limits_response: &Value,
) -> Result<ProviderUsageSnapshot, ProbeFailure> {
    if let Some(error) = rpc_failure(account_response, "account lookup") {
        return Err(error);
    }
    if let Some(error) = rpc_failure(rate_limits_response, "quota lookup") {
        return Err(error);
    }

    let account = account_response
        .pointer("/result/account")
        .and_then(Value::as_object)
        .ok_or_else(|| {
            ProbeFailure::new(
                ProviderUsageErrorCode::AuthenticationRequired,
                "Codex did not return a signed-in account",
                false,
            )
        })?;
    let rate_limits = rate_limits_response
        .pointer("/result/rateLimits")
        .ok_or_else(|| {
            ProbeFailure::new(
                ProviderUsageErrorCode::InvalidResponse,
                "Codex did not return rate-limit data",
                true,
            )
        })?;

    let plan = account
        .get("planType")
        .and_then(Value::as_str)
        .map(format_plan_name);
    let account_label = account
        .get("email")
        .or_else(|| account.get("username"))
        .or_else(|| account.get("id"))
        .and_then(Value::as_str)
        .map(ToOwned::to_owned);
    let mut windows = Vec::new();
    if let Some(primary) = rate_limits.get("primary") {
        if let Some(window) = window_from_object("Primary window", primary) {
            windows.push(window);
        }
    }
    if let Some(secondary) = rate_limits.get("secondary") {
        if let Some(window) = window_from_object("Secondary window", secondary) {
            windows.push(window);
        }
    }
    sort_usage_windows(&mut windows);
    if windows.is_empty() {
        return Err(ProbeFailure::new(
            ProviderUsageErrorCode::InvalidResponse,
            "Codex rate-limit response contained no recognizable quota windows",
            true,
        ));
    }

    let reached = rate_limits
        .get("rateLimitReachedType")
        .and_then(Value::as_str)
        .filter(|value| !value.is_empty());
    let quota_state = if reached.is_some() {
        QuotaState::Exhausted
    } else {
        quota_state_from_windows(&windows)
    };
    Ok(success_snapshot(
        profile,
        account_label,
        Some("codex_app_server"),
        plan,
        windows,
        reached.map(|value| format!("Limit reached: {}", value.replace('_', " "))),
        quota_state,
    ))
}

fn read_claude_oauth_token(credentials_path: Option<&Path>) -> Result<String, ProbeFailure> {
    let path = credentials_path
        .map(Path::to_path_buf)
        .map(Ok)
        .unwrap_or_else(default_claude_credentials_path)
        .map_err(|error| {
            ProbeFailure::new(
                ProviderUsageErrorCode::CredentialsUnavailable,
                error.to_string(),
                false,
            )
        })?;
    let raw = fs::read_to_string(&path).map_err(|error| {
        ProbeFailure::new(
            ProviderUsageErrorCode::CredentialsUnavailable,
            format!(
                "Claude Code credentials were not readable at {}: {error}",
                path.display()
            ),
            false,
        )
    })?;
    let value = serde_json::from_str::<Value>(&raw).map_err(|error| {
        ProbeFailure::new(
            ProviderUsageErrorCode::CredentialsUnavailable,
            format!(
                "Claude Code credentials at {} are invalid: {error}",
                path.display()
            ),
            false,
        )
    })?;
    find_claude_oauth_token(&value)
        .map(ToOwned::to_owned)
        .ok_or_else(|| {
            ProbeFailure::new(
                ProviderUsageErrorCode::AuthenticationRequired,
                format!(
                    "Claude Code OAuth token was not found in {}",
                    path.display()
                ),
                false,
            )
        })
}

/// Conventional Claude Code credentials path for the current user.
pub fn default_claude_credentials_path() -> AgentQuotaResult<PathBuf> {
    dirs::home_dir()
        .map(|home| home.join(CLAUDE_CREDENTIALS_RELATIVE_PATH))
        .ok_or_else(|| validation_error("home directory was not available"))
}

fn find_claude_oauth_token(value: &Value) -> Option<&str> {
    [
        "/claudeAiOauth/accessToken",
        "/oauth/accessToken",
        "/claudeAiOauth/access_token",
    ]
    .into_iter()
    .find_map(|pointer| value.pointer(pointer).and_then(Value::as_str))
    .filter(|token| !token.trim().is_empty())
}

fn claude_snapshot_from_headers(
    profile: &ProviderProfile,
    headers: &HeaderMap,
    status: StatusCode,
) -> Result<ProviderUsageSnapshot, ProbeFailure> {
    if matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN) {
        return Err(http_status_failure("Claude", status));
    }

    let mut windows = [
        claude_header_window(
            headers,
            ProviderUsageWindowKind::FiveHour,
            "5h window",
            "anthropic-ratelimit-unified-5h-utilization",
            "anthropic-ratelimit-unified-5h-reset",
        ),
        claude_header_window(
            headers,
            ProviderUsageWindowKind::Weekly,
            "Weekly window",
            "anthropic-ratelimit-unified-7d-utilization",
            "anthropic-ratelimit-unified-7d-reset",
        ),
    ]
    .into_iter()
    .flatten()
    .collect::<Vec<_>>();
    sort_usage_windows(&mut windows);

    if windows.is_empty() {
        let code = if status.is_success() {
            ProviderUsageErrorCode::Unsupported
        } else {
            ProviderUsageErrorCode::ProviderResponse
        };
        return Err(ProbeFailure::new(
            code,
            if status.is_success() {
                "Anthropic did not return supported unified quota headers".to_owned()
            } else {
                format!("Claude returned HTTP {status} without quota headers")
            },
            status.is_server_error() || status == StatusCode::TOO_MANY_REQUESTS,
        ));
    }

    let provider_status = header_string(headers, "anthropic-ratelimit-unified-status");
    let quota_state = if status == StatusCode::TOO_MANY_REQUESTS
        || provider_status.as_deref().is_some_and(|value| {
            ["rejected", "exhausted", "blocked", "rate_limited"]
                .iter()
                .any(|candidate| value.eq_ignore_ascii_case(candidate))
        }) {
        QuotaState::Exhausted
    } else {
        quota_state_from_windows(&windows)
    };
    let message = provider_status
        .filter(|value| !value.eq_ignore_ascii_case("active"))
        .map(|value| format!("Claude quota status: {value}"))
        .or_else(|| Some("Live quota from Anthropic rate-limit headers.".to_owned()));

    Ok(success_snapshot(
        profile,
        None,
        Some("anthropic_rate_limit_headers"),
        None,
        windows,
        message,
        quota_state,
    ))
}

fn claude_header_window(
    headers: &HeaderMap,
    kind: ProviderUsageWindowKind,
    label: &str,
    utilization_header: &str,
    reset_header: &str,
) -> Option<ProviderUsageWindow> {
    let utilization = header_number(headers, utilization_header)?;
    if !utilization.is_finite() {
        return None;
    }
    let used_percent = (utilization * 100.0).clamp(0.0, 100.0);
    Some(ProviderUsageWindow {
        kind,
        label: label.to_owned(),
        used_percent: Some(used_percent),
        remaining_percent: Some((100.0 - used_percent).clamp(0.0, 100.0)),
        window_minutes: match kind {
            ProviderUsageWindowKind::FiveHour => Some(300),
            ProviderUsageWindowKind::Weekly => Some(10_080),
            ProviderUsageWindowKind::Other => None,
        },
        resets_at_epoch_seconds: header_integer(headers, reset_header).map(normalize_epoch_seconds),
        detail: header_string(
            headers,
            match kind {
                ProviderUsageWindowKind::FiveHour => "anthropic-ratelimit-unified-5h-status",
                ProviderUsageWindowKind::Weekly => "anthropic-ratelimit-unified-7d-status",
                ProviderUsageWindowKind::Other => "anthropic-ratelimit-unified-status",
            },
        )
        .map(|value| format!("Status: {value}")),
    })
}

fn header_string(headers: &HeaderMap, name: &str) -> Option<String> {
    headers
        .get(name)
        .and_then(|value| value.to_str().ok())
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(ToOwned::to_owned)
}

fn header_number(headers: &HeaderMap, name: &str) -> Option<f64> {
    header_string(headers, name).and_then(|value| value.parse::<f64>().ok())
}

fn header_integer(headers: &HeaderMap, name: &str) -> Option<i64> {
    header_string(headers, name).and_then(|value| value.parse::<i64>().ok())
}

fn window_from_object(label_hint: &str, value: &Value) -> Option<ProviderUsageWindow> {
    value
        .as_object()
        .and_then(|map| window_from_map(label_hint, map))
}

fn window_from_map(label_hint: &str, map: &Map<String, Value>) -> Option<ProviderUsageWindow> {
    let used_percent = number_field(
        map,
        &[
            "usedPercent",
            "used_percent",
            "percentUsed",
            "percent_used",
            "usagePercent",
            "usage_percent",
        ],
    )
    .filter(|value| value.is_finite())
    .map(|value| value.clamp(0.0, 100.0));
    let remaining_percent = number_field(
        map,
        &[
            "remainingPercent",
            "remaining_percent",
            "percentRemaining",
            "percent_remaining",
        ],
    )
    .filter(|value| value.is_finite())
    .map(|value| value.clamp(0.0, 100.0))
    .or_else(|| used_percent.map(|used| (100.0 - used).clamp(0.0, 100.0)));
    if used_percent.is_none() && remaining_percent.is_none() {
        return None;
    }

    let window_minutes = number_field(
        map,
        &[
            "windowDurationMins",
            "window_duration_mins",
            "windowMinutes",
            "window_minutes",
        ],
    )
    .and_then(f64_to_u64)
    .or_else(|| {
        number_field(map, &["limitWindowSeconds", "limit_window_seconds"])
            .and_then(|seconds| f64_to_u64(seconds / 60.0))
    });
    let resets_at_epoch_seconds = integer_field(
        map,
        &["resetsAt", "resetAt", "reset_at", "resets_at", "resetTime"],
    )
    .map(normalize_epoch_seconds);
    let kind = kind_for_usage_window(label_hint, window_minutes);
    Some(ProviderUsageWindow {
        kind,
        label: label_for_usage_window(label_hint, window_minutes, kind),
        used_percent,
        remaining_percent,
        window_minutes,
        resets_at_epoch_seconds,
        detail: None,
    })
}

fn number_field(map: &Map<String, Value>, keys: &[&str]) -> Option<f64> {
    keys.iter()
        .find_map(|key| map.get(*key).and_then(number_value))
}

fn integer_field(map: &Map<String, Value>, keys: &[&str]) -> Option<i64> {
    keys.iter()
        .find_map(|key| map.get(*key).and_then(integer_value))
}

fn number_value(value: &Value) -> Option<f64> {
    value
        .as_f64()
        .or_else(|| value.as_str().and_then(|raw| raw.parse::<f64>().ok()))
}

fn integer_value(value: &Value) -> Option<i64> {
    value
        .as_i64()
        .or_else(|| value.as_str().and_then(|raw| raw.parse::<i64>().ok()))
}

fn f64_to_u64(value: f64) -> Option<u64> {
    if value.is_finite() && value >= 0.0 {
        u64::try_from(value.round() as i128).ok()
    } else {
        None
    }
}

fn normalize_epoch_seconds(value: i64) -> i64 {
    if value > 10_000_000_000 {
        value / 1000
    } else {
        value
    }
}

fn kind_for_usage_window(label_hint: &str, window_minutes: Option<u64>) -> ProviderUsageWindowKind {
    let label_hint = label_hint.to_lowercase();
    match window_minutes {
        Some(300) => ProviderUsageWindowKind::FiveHour,
        Some(10_080) => ProviderUsageWindowKind::Weekly,
        _ if ["five", "5h", "5 hour", "5-hour"]
            .iter()
            .any(|needle| label_hint.contains(needle)) =>
        {
            ProviderUsageWindowKind::FiveHour
        }
        _ if ["weekly", "week", "7 day", "7-day"]
            .iter()
            .any(|needle| label_hint.contains(needle)) =>
        {
            ProviderUsageWindowKind::Weekly
        }
        _ => ProviderUsageWindowKind::Other,
    }
}

fn label_for_usage_window(
    label_hint: &str,
    window_minutes: Option<u64>,
    kind: ProviderUsageWindowKind,
) -> String {
    match kind {
        ProviderUsageWindowKind::FiveHour => "5h window".to_owned(),
        ProviderUsageWindowKind::Weekly => "Weekly window".to_owned(),
        ProviderUsageWindowKind::Other => match window_minutes {
            Some(minutes) if minutes >= 60 && minutes % 60 == 0 => {
                format!("{}h window", minutes / 60)
            }
            Some(minutes) => format!("{minutes}m window"),
            None => humanize_label(label_hint),
        },
    }
}

fn sort_usage_windows(windows: &mut [ProviderUsageWindow]) {
    windows.sort_by(|left, right| {
        window_order(left)
            .cmp(&window_order(right))
            .then_with(|| left.label.cmp(&right.label))
    });
}

fn window_order(window: &ProviderUsageWindow) -> u8 {
    match window.kind {
        ProviderUsageWindowKind::FiveHour => 0,
        ProviderUsageWindowKind::Weekly => 1,
        ProviderUsageWindowKind::Other => 2,
    }
}

fn humanize_label(value: &str) -> String {
    let mut label = String::new();
    let mut previous_lowercase = false;
    for ch in value.chars() {
        if ch == '_' || ch == '-' {
            label.push(' ');
            previous_lowercase = false;
        } else if ch.is_ascii_uppercase() && previous_lowercase {
            label.push(' ');
            label.push(ch);
            previous_lowercase = false;
        } else {
            label.push(ch);
            previous_lowercase = ch.is_ascii_lowercase();
        }
    }
    let label = label.trim();
    if label.eq_ignore_ascii_case("primary") {
        "Primary window".to_owned()
    } else if label.eq_ignore_ascii_case("secondary") {
        "Secondary window".to_owned()
    } else {
        let mut chars = label.chars();
        match chars.next() {
            Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
            None => "Usage window".to_owned(),
        }
    }
}

fn format_plan_name(value: &str) -> String {
    value
        .replace(['_', '-'], " ")
        .split_whitespace()
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
                None => String::new(),
            }
        })
        .collect::<Vec<_>>()
        .join(" ")
}

fn quota_state_from_windows(windows: &[ProviderUsageWindow]) -> QuotaState {
    if windows.is_empty() {
        return QuotaState::Unknown;
    }
    if windows.iter().any(|window| {
        window
            .remaining_percent
            .is_some_and(|remaining| remaining <= 0.0)
            || window.used_percent.is_some_and(|used| used >= 100.0)
    }) {
        QuotaState::Exhausted
    } else if windows
        .iter()
        .any(|window| window.remaining_percent.is_some() || window.used_percent.is_some())
    {
        QuotaState::Available
    } else {
        QuotaState::Unknown
    }
}

fn success_snapshot(
    profile: &ProviderProfile,
    account_label: Option<String>,
    source: Option<&str>,
    plan: Option<String>,
    windows: Vec<ProviderUsageWindow>,
    message: Option<String>,
    quota_state: QuotaState,
) -> ProviderUsageSnapshot {
    ProviderUsageSnapshot {
        schema_version: SNAPSHOT_SCHEMA_VERSION,
        provider_id: profile.provider,
        provider_name: profile.provider.label().to_owned(),
        profile_id: profile.id.clone(),
        profile_name: profile.display_name(),
        account_label,
        source: source.map(ToOwned::to_owned),
        probe_status: ProbeStatus::Ok,
        quota_state,
        plan,
        windows,
        observed_at_ms: now_epoch_ms(),
        message,
        error: None,
    }
}

fn failed_snapshot(profile: &ProviderProfile, failure: ProbeFailure) -> ProviderUsageSnapshot {
    ProviderUsageSnapshot {
        schema_version: SNAPSHOT_SCHEMA_VERSION,
        provider_id: profile.provider,
        provider_name: profile.provider.label().to_owned(),
        profile_id: profile.id.clone(),
        profile_name: profile.display_name(),
        account_label: None,
        source: None,
        probe_status: failure.status(),
        quota_state: QuotaState::Unknown,
        plan: None,
        windows: Vec::new(),
        observed_at_ms: now_epoch_ms(),
        message: None,
        error: Some(failure.error),
    }
}

fn now_epoch_ms() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| i64::try_from(duration.as_millis()).unwrap_or(i64::MAX))
        .unwrap_or_default()
}

#[derive(Debug, Clone)]
struct CachedProviderUsage {
    snapshot: ProviderUsageSnapshot,
    cached_at_ms: i64,
}

/// Profile-keyed provider cache for repeated UI or CLI polling.
#[derive(Debug, Clone)]
pub struct ProviderUsageCache {
    inner: Arc<Mutex<BTreeMap<ProviderProfile, CachedProviderUsage>>>,
    ttl: Duration,
}

impl Default for ProviderUsageCache {
    fn default() -> Self {
        Self {
            inner: Arc::new(Mutex::new(BTreeMap::new())),
            ttl: DEFAULT_CACHE_TTL,
        }
    }
}

impl ProviderUsageCache {
    /// Construct a cache with a custom time-to-live.
    pub fn with_ttl(ttl: Duration) -> Self {
        Self {
            ttl,
            ..Self::default()
        }
    }

    /// Collect through a cache keyed by every complete provider profile.
    ///
    /// Failed profiles are not cached, allowing immediate recovery after sign-in
    /// or transient failures while successful profiles keep their cached values.
    pub async fn collect(
        &self,
        client: &AgentQuotaClient,
        options: CollectUsageOptions,
        force_refresh: bool,
    ) -> Vec<ProviderUsageSnapshot> {
        let profiles = options.selected_profiles();
        let probes = profiles.into_iter().map(|profile| async move {
            let now = now_epoch_ms();
            if !force_refresh {
                let guard = self.inner.lock().await;
                if let Some(cached) = guard.get(&profile) {
                    let ttl_ms = i64::try_from(self.ttl.as_millis()).unwrap_or(i64::MAX);
                    if now.saturating_sub(cached.cached_at_ms) < ttl_ms {
                        return cached.snapshot.clone();
                    }
                }
            }

            let snapshot = client.collect_profile_usage(profile.clone()).await;
            let mut guard = self.inner.lock().await;
            if snapshot.probe_status == ProbeStatus::Ok {
                guard.insert(
                    profile,
                    CachedProviderUsage {
                        snapshot: snapshot.clone(),
                        cached_at_ms: now_epoch_ms(),
                    },
                );
            } else {
                guard.remove(&profile);
            }
            snapshot
        });
        futures::future::join_all(probes).await
    }

    /// Clear every cached selection.
    pub async fn clear(&self) {
        self.inner.lock().await.clear();
    }
}

/// Collect all conventional local provider profiles.
pub async fn collect_provider_usage() -> Vec<ProviderUsageSnapshot> {
    collect_usage(CollectUsageOptions::all()).await
}

/// Collect an explicit selection with production defaults.
pub async fn collect_usage(options: CollectUsageOptions) -> Vec<ProviderUsageSnapshot> {
    AgentQuotaClient::new().collect_usage(options).await
}

/// Collect one conventional provider profile.
pub async fn collect_single_provider_usage(provider: ProviderId) -> ProviderUsageSnapshot {
    AgentQuotaClient::new()
        .collect_profile_usage(ProviderProfile::default_for_provider(provider))
        .await
}

/// Collect one configured provider profile.
pub async fn collect_profile_usage(profile: ProviderProfile) -> ProviderUsageSnapshot {
    AgentQuotaClient::new().collect_profile_usage(profile).await
}

#[cfg(test)]
mod tests {
    use super::*;
    use reqwest::header::{HeaderName, HeaderValue};
    use std::io::{Read, Write};
    use std::net::{TcpListener, TcpStream};
    #[cfg(unix)]
    use std::os::unix::fs::PermissionsExt;
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::thread;
    use std::time::Instant;

    static TEST_FILE_SEQUENCE: AtomicU64 = AtomicU64::new(0);

    fn header_map(entries: &[(&'static str, &'static str)]) -> HeaderMap {
        let mut headers = HeaderMap::new();
        for (name, value) in entries {
            headers.insert(
                HeaderName::from_static(name),
                HeaderValue::from_static(value),
            );
        }
        headers
    }

    fn start_http_server(
        status: &'static str,
        headers: &'static str,
        delay: Duration,
    ) -> (String, thread::JoinHandle<()>) {
        let listener = TcpListener::bind("127.0.0.1:0").expect("test listener should bind");
        let address = listener.local_addr().expect("listener should have address");
        let server = thread::spawn(move || {
            let mut stream = accept_test_connection(&listener);
            let mut request = [0_u8; 8_192];
            let bytes = stream.read(&mut request).expect("request should read");
            assert!(bytes > 0, "request should not be empty");
            thread::sleep(delay);
            let response = format!(
                "HTTP/1.1 {status}\r\ncontent-length: 2\r\nconnection: close\r\n{headers}\r\n{{}}"
            );
            let _ = stream.write_all(response.as_bytes());
        });
        (format!("http://{address}/v1/messages"), server)
    }

    fn accept_test_connection(listener: &TcpListener) -> TcpStream {
        listener
            .set_nonblocking(true)
            .expect("test listener should become nonblocking");
        let deadline = Instant::now() + Duration::from_secs(5);

        loop {
            match listener.accept() {
                Ok((stream, _)) => {
                    stream
                        .set_nonblocking(false)
                        .expect("test stream should become blocking");
                    stream
                        .set_read_timeout(Some(Duration::from_secs(5)))
                        .expect("test stream should have a read timeout");
                    stream
                        .set_write_timeout(Some(Duration::from_secs(5)))
                        .expect("test stream should have a write timeout");
                    return stream;
                }
                Err(error)
                    if error.kind() == std::io::ErrorKind::WouldBlock
                        && Instant::now() < deadline =>
                {
                    thread::sleep(Duration::from_millis(5));
                }
                Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                    panic!("request did not connect before the test deadline");
                }
                Err(error) => panic!("request should connect: {error}"),
            }
        }
    }

    fn temporary_claude_credentials() -> PathBuf {
        let path = std::env::temp_dir().join(format!(
            "agent-quota-test-{}-{}-{}.json",
            std::process::id(),
            now_epoch_ms(),
            TEST_FILE_SEQUENCE.fetch_add(1, Ordering::Relaxed)
        ));
        fs::write(&path, r#"{"claudeAiOauth":{"accessToken":"test-token"}}"#)
            .expect("credentials fixture should write");
        path
    }

    #[test]
    fn parses_and_validates_profile_config() {
        let config = toml::from_str::<AgentQuotaConfig>(
            r#"
                [[profiles]]
                id = "claude-work"
                provider = "claude"
                label = "Claude Work"
                credentials_path = "C:/Users/example/.claude-work/.credentials.json"

                [[profiles]]
                id = "codex-private"
                provider = "codex"
                label = "Codex Private"

                [profiles.env]
                CODEX_HOME = "C:/Users/example/.codex-private"
            "#,
        )
        .expect("profile config should parse");

        config.validate().expect("profile config should validate");
        assert_eq!(config.profiles.len(), 2);
        assert_eq!(config.profiles[0].provider, ProviderId::Claude);
    }

    #[test]
    fn rejects_unknown_and_duplicate_profile_fields() {
        let unknown = toml::from_str::<AgentQuotaConfig>(
            r#"
                [[profiles]]
                id = "codex"
                provider = "codex"
                comand_path = "codex"
            "#,
        );
        assert!(unknown.is_err());

        let duplicate = AgentQuotaConfig {
            profiles: vec![
                ProviderProfile::default_for_provider(ProviderId::Codex),
                ProviderProfile::default_for_provider(ProviderId::Codex),
            ],
        };
        assert!(duplicate.validate().is_err());
    }

    #[test]
    fn empty_explicit_selection_does_not_expand_to_all() {
        assert!(CollectUsageOptions::providers([])
            .selected_profiles()
            .is_empty());
        assert!(CollectUsageOptions::profiles([])
            .selected_profiles()
            .is_empty());
        assert_eq!(CollectUsageOptions::all().selected_profiles().len(), 2);
    }

    #[test]
    fn maps_codex_success_and_exhaustion() {
        let account = json!({
            "id": 2,
            "result": {
                "account": { "type": "chatgpt", "email": "user@example.com", "planType": "plus" }
            }
        });
        let rate_limits = json!({
            "id": 3,
            "result": {
                "rateLimits": {
                    "primary": { "usedPercent": 100, "windowDurationMins": 300, "resetsAt": 1_730_947_200 },
                    "secondary": { "usedPercent": 46, "windowDurationMins": 10080, "resetsAt": 1_731_206_400 },
                    "rateLimitReachedType": "primary"
                }
            }
        });
        let profile = ProviderProfile::default_for_provider(ProviderId::Codex);
        let snapshot = codex_snapshot_from_responses(&profile, &account, &rate_limits)
            .expect("response should map");

        assert_eq!(
            snapshot.probe_status,
            ProbeStatus::Ok,
            "unexpected snapshot: {snapshot:?}"
        );
        assert_eq!(snapshot.quota_state, QuotaState::Exhausted);
        assert!(!snapshot.is_ready());
        assert_eq!(snapshot.account_label.as_deref(), Some("user@example.com"));
        assert_eq!(snapshot.windows.len(), 2);
    }

    #[test]
    fn rejects_codex_rpc_errors_and_missing_windows() {
        let profile = ProviderProfile::default_for_provider(ProviderId::Codex);
        let auth_error = json!({
            "id": 2,
            "error": { "code": -32000, "message": "Please sign in to Codex" }
        });
        let rate_limits = json!({ "id": 3, "result": { "rateLimits": {} } });
        let error = codex_snapshot_from_responses(&profile, &auth_error, &rate_limits)
            .expect_err("RPC error must not become an available snapshot");
        assert_eq!(
            error.error.code,
            ProviderUsageErrorCode::AuthenticationRequired
        );

        let account = json!({ "id": 2, "result": { "account": {} } });
        let error = codex_snapshot_from_responses(&profile, &account, &rate_limits)
            .expect_err("missing windows must be rejected");
        assert_eq!(error.error.code, ProviderUsageErrorCode::InvalidResponse);
    }

    #[tokio::test]
    async fn codex_production_process_path_maps_mock_app_server() {
        let extension = if cfg!(windows) { "cmd" } else { "sh" };
        let path = std::env::temp_dir().join(format!(
            "agent-quota-mock-codex-{}-{}.{}",
            std::process::id(),
            now_epoch_ms(),
            extension
        ));
        #[cfg(windows)]
        let script = concat!(
            "@echo off\r\n",
            "echo {\"id\":2,\"result\":{\"account\":{\"email\":\"test@example.com\",\"planType\":\"plus\"}}}\r\n",
            "echo {\"id\":3,\"result\":{\"rateLimits\":{\"primary\":{\"usedPercent\":25,\"windowDurationMins\":300,\"resetsAt\":1730947200}}}}\r\n",
            "ping -n 3 127.0.0.1 >nul\r\n"
        );
        #[cfg(unix)]
        let script = concat!(
            "#!/bin/sh\n",
            "printf '%s\\n' '{\"id\":2,\"result\":{\"account\":{\"email\":\"test@example.com\",\"planType\":\"plus\"}}}'\n",
            "printf '%s\\n' '{\"id\":3,\"result\":{\"rateLimits\":{\"primary\":{\"usedPercent\":25,\"windowDurationMins\":300,\"resetsAt\":1730947200}}}}'\n",
            "sleep 2\n"
        );
        fs::write(&path, script).expect("mock Codex executable should write");
        #[cfg(unix)]
        {
            let mut permissions = fs::metadata(&path)
                .expect("mock metadata should read")
                .permissions();
            permissions.set_mode(0o755);
            fs::set_permissions(&path, permissions).expect("mock should become executable");
        }

        let profile = ProviderProfile {
            command_path: Some(path.clone()),
            ..ProviderProfile::default_for_provider(ProviderId::Codex)
        };
        let snapshot = AgentQuotaClient::new().collect_profile_usage(profile).await;
        let _ = fs::remove_file(path);

        assert_eq!(
            snapshot.probe_status,
            ProbeStatus::Ok,
            "unexpected snapshot: {snapshot:?}"
        );
        assert_eq!(snapshot.quota_state, QuotaState::Available);
        assert_eq!(snapshot.account_label.as_deref(), Some("test@example.com"));
        assert_eq!(snapshot.windows[0].remaining_percent, Some(75.0));
    }

    #[test]
    fn parses_claude_headers_and_http_failures() {
        let headers = header_map(&[
            ("anthropic-ratelimit-unified-5h-utilization", "0.42"),
            ("anthropic-ratelimit-unified-5h-reset", "1730947200"),
            ("anthropic-ratelimit-unified-7d-utilization", "0.68"),
            ("anthropic-ratelimit-unified-7d-reset", "1731206400000"),
            ("anthropic-ratelimit-unified-status", "active"),
        ]);
        let profile = ProviderProfile::default_for_provider(ProviderId::Claude);
        let snapshot = claude_snapshot_from_headers(&profile, &headers, StatusCode::OK)
            .expect("headers should map");
        assert_eq!(snapshot.probe_status, ProbeStatus::Ok);
        assert_eq!(snapshot.quota_state, QuotaState::Available);
        assert!(snapshot.is_ready());
        assert_eq!(snapshot.windows[0].remaining_percent, Some(58.0));
        assert_eq!(
            snapshot.windows[1].resets_at_epoch_seconds,
            Some(1_731_206_400)
        );

        let error =
            claude_snapshot_from_headers(&profile, &HeaderMap::new(), StatusCode::UNAUTHORIZED)
                .expect_err("401 should be authentication failure");
        assert_eq!(
            error.error.code,
            ProviderUsageErrorCode::AuthenticationRequired
        );
    }

    #[test]
    fn reads_claude_oauth_token_from_supported_shapes() {
        let credentials = json!({
            "claudeAiOauth": {
                "accessToken": "oauth-token"
            }
        });
        assert_eq!(find_claude_oauth_token(&credentials), Some("oauth-token"));
    }

    #[tokio::test]
    async fn cache_is_profile_keyed_and_does_not_cache_failures() {
        let cache = ProviderUsageCache::default();
        let client = AgentQuotaClient::new();
        let codex_profile = ProviderProfile::default_for_provider(ProviderId::Codex);
        cache.inner.lock().await.insert(
            codex_profile.clone(),
            CachedProviderUsage {
                snapshot: success_snapshot(
                    &codex_profile,
                    None,
                    Some("fixture"),
                    None,
                    vec![ProviderUsageWindow {
                        kind: ProviderUsageWindowKind::FiveHour,
                        label: "5h window".to_owned(),
                        used_percent: Some(25.0),
                        remaining_percent: Some(75.0),
                        window_minutes: Some(300),
                        resets_at_epoch_seconds: None,
                        detail: None,
                    }],
                    None,
                    QuotaState::Available,
                ),
                cached_at_ms: now_epoch_ms(),
            },
        );
        let empty = CollectUsageOptions::profiles([]);
        assert!(cache
            .collect(&client, empty.clone(), false)
            .await
            .is_empty());

        let invalid_profile = ProviderProfile {
            id: String::new(),
            ..ProviderProfile::default_for_provider(ProviderId::Codex)
        };
        let invalid = CollectUsageOptions::profiles([invalid_profile]);
        let first = cache.collect(&client, invalid.clone(), false).await;
        let second = cache.collect(&client, invalid, false).await;
        assert_eq!(first[0].probe_status, ProbeStatus::InvalidConfiguration);
        assert_eq!(second[0].probe_status, ProbeStatus::InvalidConfiguration);
        let guard = cache.inner.lock().await;
        assert_eq!(guard.len(), 1);
        assert!(guard.contains_key(&codex_profile));
    }

    #[test]
    fn serializes_versioned_snapshot_contract() {
        let profile = ProviderProfile::default_for_provider(ProviderId::Codex);
        let snapshot = success_snapshot(
            &profile,
            Some("user@example.com".to_owned()),
            Some("fixture"),
            Some("Plus".to_owned()),
            vec![ProviderUsageWindow {
                kind: ProviderUsageWindowKind::FiveHour,
                label: "5h window".to_owned(),
                used_percent: Some(42.0),
                remaining_percent: Some(58.0),
                window_minutes: Some(300),
                resets_at_epoch_seconds: Some(1_730_947_200),
                detail: None,
            }],
            None,
            QuotaState::Available,
        );
        let value = serde_json::to_value(snapshot).expect("snapshot should serialize");
        assert_eq!(value["schemaVersion"], SNAPSHOT_SCHEMA_VERSION);
        assert_eq!(value["providerId"], "codex");
        assert_eq!(value["probeStatus"], "ok");
        assert_eq!(value["quotaState"], "available");
        assert!(value["observedAtMs"].as_i64().is_some());
        assert_eq!(value["windows"][0]["resetsAtEpochSeconds"], 1_730_947_200);
    }

    #[test]
    fn shared_v1_fixture_matches_the_public_model() {
        let raw = include_str!("../fixtures/provider-usage-v1.json");
        let snapshots =
            serde_json::from_str::<Vec<ProviderUsageSnapshot>>(raw).expect("fixture should parse");
        assert_eq!(snapshots.len(), 2);
        assert_eq!(snapshots[0].schema_version, SNAPSHOT_SCHEMA_VERSION);
        assert_eq!(snapshots[0].probe_status, ProbeStatus::Ok);
        assert_eq!(
            snapshots[1].error.as_ref().map(|error| error.code),
            Some(ProviderUsageErrorCode::CredentialsUnavailable)
        );
    }

    #[tokio::test]
    async fn claude_production_path_uses_injected_endpoint_and_checks_headers() {
        let listener = TcpListener::bind("127.0.0.1:0").expect("test listener should bind");
        let address = listener.local_addr().expect("listener should have address");
        let server = thread::spawn(move || {
            let mut stream = accept_test_connection(&listener);
            let mut request = [0_u8; 8_192];
            let bytes = stream.read(&mut request).expect("request should read");
            let request = String::from_utf8_lossy(&request[..bytes]);
            assert!(request.starts_with("POST /v1/messages "));
            assert!(request
                .to_ascii_lowercase()
                .contains("user-agent: agent-quota/"));
            let response = concat!(
                "HTTP/1.1 200 OK\r\n",
                "content-length: 2\r\n",
                "connection: close\r\n",
                "anthropic-ratelimit-unified-5h-utilization: 0.25\r\n",
                "anthropic-ratelimit-unified-5h-reset: 1730947200\r\n",
                "anthropic-ratelimit-unified-status: active\r\n",
                "\r\n{}"
            );
            stream
                .write_all(response.as_bytes())
                .expect("response should write");
        });

        let credentials_path = temporary_claude_credentials();
        let profile = ProviderProfile {
            credentials_path: Some(credentials_path.clone()),
            ..ProviderProfile::default_for_provider(ProviderId::Claude)
        };
        let client =
            AgentQuotaClient::new().with_claude_api_url(format!("http://{address}/v1/messages"));
        let snapshot = client.collect_profile_usage(profile).await;
        let _ = fs::remove_file(credentials_path);
        server.join().expect("server should finish");

        assert_eq!(snapshot.probe_status, ProbeStatus::Ok);
        assert_eq!(snapshot.quota_state, QuotaState::Available);
        assert_eq!(snapshot.windows[0].remaining_percent, Some(75.0));
    }

    #[tokio::test]
    async fn claude_production_path_classifies_http_and_timeout_failures() {
        let credentials_path = temporary_claude_credentials();
        let profile = ProviderProfile {
            credentials_path: Some(credentials_path.clone()),
            ..ProviderProfile::default_for_provider(ProviderId::Claude)
        };

        let (url, server) = start_http_server("401 Unauthorized", "", Duration::from_millis(0));
        let snapshot = AgentQuotaClient::new()
            .with_claude_api_url(url)
            .collect_profile_usage(profile.clone())
            .await;
        server.join().expect("401 server should finish");
        assert_eq!(snapshot.probe_status, ProbeStatus::AuthenticationRequired);
        assert_eq!(
            snapshot.error.as_ref().map(|error| error.code),
            Some(ProviderUsageErrorCode::AuthenticationRequired)
        );

        let headers = concat!(
            "anthropic-ratelimit-unified-5h-utilization: 1.0\r\n",
            "anthropic-ratelimit-unified-5h-reset: 1730947200\r\n",
            "anthropic-ratelimit-unified-status: exhausted\r\n"
        );
        let (url, server) =
            start_http_server("429 Too Many Requests", headers, Duration::from_millis(0));
        let snapshot = AgentQuotaClient::new()
            .with_claude_api_url(url)
            .collect_profile_usage(profile.clone())
            .await;
        server.join().expect("429 server should finish");
        assert_eq!(snapshot.probe_status, ProbeStatus::Ok);
        assert_eq!(snapshot.quota_state, QuotaState::Exhausted);

        let (url, server) = start_http_server("200 OK", "", Duration::from_millis(0));
        let snapshot = AgentQuotaClient::new()
            .with_claude_api_url(url)
            .collect_profile_usage(profile.clone())
            .await;
        server.join().expect("no-header server should finish");
        assert_eq!(snapshot.probe_status, ProbeStatus::Unsupported);

        let (url, server) = start_http_server("200 OK", "", Duration::from_millis(500));
        let snapshot = AgentQuotaClient::new()
            .with_claude_api_url(url)
            .with_timeouts(DEFAULT_CODEX_TIMEOUT, Duration::from_millis(250))
            .collect_profile_usage(profile)
            .await;
        server.join().expect("timeout server should finish");
        let _ = fs::remove_file(credentials_path);
        assert_eq!(snapshot.probe_status, ProbeStatus::TransientError);
        assert_eq!(
            snapshot.error.as_ref().map(|error| error.code),
            Some(ProviderUsageErrorCode::Timeout)
        );
    }
}