agentstat 0.1.2

Read-only AI provider usage, quota, balance, and reset data
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
//! Integration tests for agentstat fetch.

#![expect(
    clippy::disallowed_types,
    reason = "test executor state must be shared with cloned clients"
)]

#[cfg(all(feature = "cursor", feature = "local-files"))]
use agentstat::local::CredentialLocation;
use agentstat::*;
use futures::future::BoxFuture;
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use serde_json::Value;
#[cfg(any(
    feature = "codex",
    feature = "claude",
    feature = "synthetic",
    feature = "openai",
    feature = "opencode",
    feature = "cursor",
    feature = "antigravity",
    feature = "codebuff"
))]
use serde_json::json;
use std::collections::{HashMap, VecDeque};
use std::convert::Infallible;
use std::fmt::Write as _;
#[cfg(all(feature = "cursor", feature = "local-files"))]
use std::fs;
use std::str::FromStr;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::Duration;
use std::{future, result, str};
use tokio::time;
#[derive(Debug)]
struct MemoryHttp {
    replies: Mutex<VecDeque<Reply>>,
    requests: Mutex<Vec<String>>,
}
#[derive(Debug)]
struct Reply {
    status: u16,
    body: String,
    headers: Vec<(String, String)>,
}
impl Reply {
    fn json(body: &Value) -> Self {
        Self {
            status: 200,
            body: body.to_string(),
            headers: vec![],
        }
    }
}
impl HttpExecutor for MemoryHttp {
    fn execute(&self, request: reqwest::Request) -> BoxFuture<'_, Result<HttpResponse>> {
        Box::pin(async move {
            let mut captured = format!(
                "{} {}{} HTTP/1.1\r\n",
                request.method(),
                request.url().path(),
                request
                    .url()
                    .query()
                    .map(|q| format!("?{q}"))
                    .unwrap_or_default()
            );
            for (k, v) in request.headers() {
                write!(
                    &mut captured,
                    "{k}: {}\r\n",
                    v.to_str().expect("test header is text")
                )
                .expect("writing to a String cannot fail");
            }
            captured.push_str("\r\n");
            if let Some(bytes) = request.body().and_then(reqwest::Body::as_bytes) {
                captured.push_str(str::from_utf8(bytes).expect("test fixture is valid"));
            }
            self.requests
                .lock()
                .expect("test fixture is valid")
                .push(captured);
            let reply = self
                .replies
                .lock()
                .expect("test fixture is valid")
                .pop_front()
                .expect("unexpected extra HTTP request");
            let mut headers = HeaderMap::new();
            for (k, v) in reply.headers {
                headers.insert(
                    HeaderName::from_bytes(k.as_bytes()).expect("test fixture is valid"),
                    HeaderValue::from_str(&v).expect("test fixture is valid"),
                );
            }
            Ok(HttpResponse {
                status: reply.status,
                headers,
                body: reply.body.into_bytes(),
            })
        })
    }
}
struct Server(Arc<MemoryHttp>);
impl future::IntoFuture for Server {
    type Output = result::Result<Vec<String>, Infallible>;
    type IntoFuture = future::Ready<Self::Output>;
    fn into_future(self) -> Self::IntoFuture {
        assert!(
            self.0
                .replies
                .lock()
                .expect("test executor state is available")
                .is_empty(),
            "expected HTTP request was not made"
        );
        future::ready(Ok(self
            .0
            .requests
            .lock()
            .expect("test executor state is available")
            .clone()))
    }
}
fn executors() -> &'static Mutex<HashMap<String, Arc<MemoryHttp>>> {
    static MAP: OnceLock<Mutex<HashMap<String, Arc<MemoryHttp>>>> = OnceLock::new();
    MAP.get_or_init(Default::default)
}
async fn server(replies: Vec<Reply>) -> (String, Server) {
    static COUNT: AtomicUsize = AtomicUsize::new(0);
    let url = format!(
        "http://127.0.0.1:{}",
        10000 + COUNT.fetch_add(1, Ordering::SeqCst)
    );
    let executor = Arc::new(MemoryHttp {
        replies: Mutex::new(replies.into()),
        requests: Mutex::new(vec![]),
    });
    executors()
        .lock()
        .expect("test executor state is available")
        .insert(url.clone(), executor.clone());
    (url, Server(executor))
}
fn builder(base: &str, provider: ProviderId) -> ClientBuilder {
    Client::builder()
        .endpoint_override(provider, base)
        .http_executor(
            executors()
                .lock()
                .expect("test executor state is available")
                .get(base)
                .expect("test executor state is available")
                .clone(),
        )
}
fn config(v: &Value) -> ProviderConfig {
    if let Some(id) = v["cosmic"].as_str() {
        ProviderConfig::Cosmic {
            project_id: id.into(),
        }
    } else if let Some(id) = v["xai"].as_str() {
        ProviderConfig::Xai { team_id: id.into() }
    } else if let Some(id) = v["flora"].as_str() {
        ProviderConfig::Flora {
            workspace_id: id.into(),
        }
    } else if let Some(id) = v["exa"].as_str() {
        ProviderConfig::Exa {
            api_key_id: id.into(),
        }
    } else {
        ProviderConfig::Default
    }
}

#[cfg(feature = "cursor")]
#[tokio::test]
async fn cursor_cli_preserves_vendor_percentages_and_exact_money_separately() {
    let (base, server) = server(vec![Reply::json(&json!({
        "billingCycleStart": "1790812800000", "billingCycleEnd": "1793491200000",
        "planUsage": {"totalPercentUsed": 10, "apiPercentUsed": 120,
            "totalSpend": "1500.125", "limit": "2000", "remaining": "499.875"},
        "spendLimitUsage": {"totalSpend": "12.345", "limitType": "user",
            "individualLimit": 0, "individualUsed": "12.345", "individualRemaining": 0,
            "pooledLimit": 100000}
    }))])
    .await;
    let snapshot = builder(&base, ProviderId::Cursor)
        .build()
        .unwrap()
        .fetch(FetchRequest::new(
            ProviderId::Cursor,
            Credentials::bearer("private"),
        ))
        .await
        .unwrap();
    assert_eq!(snapshot.source, Source::OAuth);
    let total = &snapshot.windows[0];
    assert_eq!(total.utilization_percent, Some(10.0));
    assert_eq!(total.limit, QuotaLimit::Unknown);
    assert_eq!(total.duration_seconds, None); // Billing periods are not assumed weekly/monthly.
    assert_eq!(total.resets_at.unwrap().timestamp_millis(), 1793491200000);
    assert_eq!(snapshot.windows[1].utilization_percent, Some(120.0));
    let allowance = snapshot
        .windows
        .iter()
        .find(|w| w.id == "plan-allowance")
        .unwrap();
    assert_eq!(allowance.used.as_ref().unwrap().as_str(), "15.00125");
    assert_eq!(allowance.remaining.as_ref().unwrap().as_str(), "4.99875");
    let spend = snapshot
        .windows
        .iter()
        .find(|w| w.id == "on-demand-individual")
        .unwrap();
    assert_eq!(spend.limit, QuotaLimit::Known(Decimal::from(0)));
    assert_eq!(spend.utilization_percent, None);
    assert_eq!(snapshot.spend[0].amount.as_str(), "0.12345");
    let requests = server.await.unwrap();
    assert_eq!(requests.len(), 1);
    assert!(requests[0].contains("connect-protocol-version: 1"));
    assert!(requests[0].ends_with("{}"));
}

#[cfg(feature = "cursor")]
#[tokio::test]
async fn cursor_cookie_uses_dashboard_and_keeps_missing_limits_unknown() {
    let (base, server) = server(vec![Reply::json(&json!({
        "membershipType": "pro", "billingCycleEnd": "2026-11-01T00:00:00Z",
        "individualUsage": {"plan": {"enabled":true, "autoPercentUsed":0,
            "used": 100, "limit": null},
            "onDemand": {"enabled":true,"used":75,"limit":null,"remaining":null}},
        "teamUsage": {"onDemand": {"used":999999,"limit":999999}}
    }))])
    .await;
    let snapshot = builder(&base, ProviderId::Cursor)
        .build()
        .unwrap()
        .fetch(FetchRequest::new(
            ProviderId::Cursor,
            Credentials::cookie("WorkosCursorSessionToken=private"),
        ))
        .await
        .unwrap();
    assert_eq!(snapshot.source, Source::Web);
    assert_eq!(snapshot.plan.as_deref(), Some("pro"));
    assert_eq!(snapshot.windows[0].utilization_percent, Some(0.0));
    assert!(
        snapshot
            .windows
            .iter()
            .all(|w| w.limit == QuotaLimit::Unknown)
    );
    assert_eq!(snapshot.spend[0].amount.as_str(), "0.75");
    let requests = server.await.unwrap();
    assert!(requests[0].starts_with("GET /api/usage-summary "));
    assert!(requests[0].contains("cookie: WorkosCursorSessionToken=private"));
    assert!(!requests[0].contains("authorization:"));
}

#[cfg(feature = "cursor")]
#[tokio::test]
async fn cursor_rejects_empty_usage_and_warns_on_malformed_optional_amounts() {
    for body in [
        json!({}),
        json!({"individualUsage":{"plan":{"totalPercentUsed":null}}}),
    ] {
        let (base, server) = server(vec![Reply::json(&body)]).await;
        assert!(matches!(
            builder(&base, ProviderId::Cursor)
                .build()
                .unwrap()
                .fetch(FetchRequest::new(
                    ProviderId::Cursor,
                    Credentials::cookie("session=private")
                ))
                .await,
            Err(AgentStatError::InvalidResponse(_))
        ));
        server.await.unwrap();
    }
    let (base, server) = server(vec![Reply::json(&json!({
        "planUsage":{"totalPercentUsed":0,"totalSpend":-1,"limit":100},
        "billingCycleEnd":"invalid"
    }))])
    .await;
    let snapshot = builder(&base, ProviderId::Cursor)
        .build()
        .unwrap()
        .fetch(FetchRequest::new(
            ProviderId::Cursor,
            Credentials::bearer("private"),
        ))
        .await
        .unwrap();
    assert_eq!(snapshot.windows.len(), 1);
    assert_eq!(snapshot.windows[0].resets_at, None);
    assert!(snapshot.warnings.contains(&Warning::MalformedOptionalData));
    server.await.unwrap();
}

#[cfg(feature = "cursor")]
#[tokio::test]
async fn cursor_keeps_overages_and_negative_remaining_allowance() {
    let (base, server) = server(vec![Reply::json(&json!({"planUsage": {
        "totalSpend":2500, "limit":2000, "remaining":-500
    }}))])
    .await;
    let snapshot = builder(&base, ProviderId::Cursor)
        .build()
        .unwrap()
        .fetch(FetchRequest::new(
            ProviderId::Cursor,
            Credentials::bearer("private"),
        ))
        .await
        .unwrap();
    assert_eq!(
        snapshot.windows[0].remaining.as_ref().unwrap().as_str(),
        "-5"
    );
    assert_eq!(snapshot.windows[0].utilization_percent, Some(125.0));
    server.await.unwrap();
}

#[cfg(all(feature = "cursor", feature = "local-files"))]
#[tokio::test]
async fn cursor_local_cli_token_is_used_by_the_public_fetch_api() {
    let dir = tempfile::tempdir().unwrap();
    fs::write(
        dir.path().join("auth.json"),
        r#"{"accessToken":"local-secret"}"#,
    )
    .unwrap();
    let (base, server) = server(vec![Reply::json(
        &json!({"planUsage":{"totalPercentUsed":15}}),
    )])
    .await;
    let client = builder(&base, ProviderId::Cursor)
        .allow_local_files(true)
        .build()
        .unwrap();
    let request = client
        .load_local_credentials(
            ProviderId::Cursor,
            CredentialLocation::Directory(dir.path().into()),
        )
        .await
        .unwrap();
    let snapshot = client.fetch(request).await.unwrap();
    assert_eq!(snapshot.credential_source, CredentialSource::LocalFile);
    assert_eq!(snapshot.windows[0].utilization_percent, Some(15.0));
    assert!(
        !serde_json::to_string(&snapshot)
            .unwrap()
            .contains("local-secret")
    );
    assert!(server.await.unwrap()[0].contains("authorization: Bearer local-secret"));
}

#[cfg(feature = "antigravity")]
#[tokio::test]
async fn antigravity_reports_group_windows_without_inventing_token_allowances() {
    let (base, server) = server(vec![Reply::json(&json!({"groups":[
        {"displayName":"Gemini Models", "buckets":[
            {"bucketId":"gemini-5h","remainingFraction":0.75,"resetTime":"2026-10-23T01:00:00Z"},
            {"bucketId":"gemini-weekly","remainingFraction":0,"remainingAmount":"0"},
            {"bucketId":"disabled-5h"},
            {"bucketId":"malformed-weekly","remainingFraction":1.5}
        ]}
    ]}))])
    .await;
    let snapshot = builder(&base, ProviderId::Antigravity)
        .build()
        .unwrap()
        .fetch(
            FetchRequest::new(ProviderId::Antigravity, Credentials::bearer("private")).config(
                ProviderConfig::Antigravity {
                    project_id: "project-a".into(),
                },
            ),
        )
        .await
        .unwrap();
    assert_eq!(snapshot.windows.len(), 2);
    assert_eq!(snapshot.windows[0].model.as_deref(), Some("Gemini Models"));
    assert_eq!(snapshot.windows[0].duration_seconds, Some(18000));
    assert_eq!(snapshot.windows[1].duration_seconds, Some(604800));
    assert_eq!(snapshot.windows[0].utilization_percent, Some(25.0));
    assert_eq!(snapshot.windows[1].utilization_percent, Some(100.0));
    assert!(
        snapshot
            .windows
            .iter()
            .all(|w| w.used.is_none() && w.limit == QuotaLimit::Unknown)
    );
    assert!(snapshot.warnings.contains(&Warning::IncompleteData));
    assert!(snapshot.warnings.contains(&Warning::MalformedOptionalData));
    let requests = server.await.unwrap();
    assert!(requests[0].contains("user-agent: antigravity"));
    assert!(requests[0].ends_with("{\"project\":\"project-a\"}"));
}

#[cfg(feature = "antigravity")]
#[tokio::test]
async fn antigravity_rejects_empty_duplicate_and_availability_only_data() {
    for body in [
        json!({}),
        json!({"groups": []}),
        json!({"models":{"gemini":{}}}),
        json!({"buckets":[{"bucketId":"duplicate","remainingFraction":1},
            {"bucketId":"duplicate","remainingFraction":0.5}]}),
    ] {
        let (base, server) = server(vec![Reply::json(&body)]).await;
        assert!(matches!(
            builder(&base, ProviderId::Antigravity)
                .build()
                .unwrap()
                .fetch(FetchRequest::new(
                    ProviderId::Antigravity,
                    Credentials::bearer("private")
                ))
                .await,
            Err(AgentStatError::InvalidResponse(_))
        ));
        server.await.unwrap();
    }
}

#[cfg(all(feature = "cursor", feature = "antigravity"))]
#[tokio::test]
async fn cursor_and_antigravity_do_not_retry_or_refresh_on_http_errors() {
    for provider in [ProviderId::Cursor, ProviderId::Antigravity] {
        for status in [401, 403, 429, 302, 500] {
            let (base, server) = server(vec![Reply {
                status,
                body: "private".into(),
                headers: vec![],
            }])
            .await;
            let error = builder(&base, provider)
                .build()
                .unwrap()
                .fetch(FetchRequest::new(provider, Credentials::bearer("private")))
                .await
                .unwrap_err();
            assert!(!format!("{error:?}").contains("private"));
            assert!(matches!(
                (status, error),
                (401, AgentStatError::Authentication)
                    | (403, AgentStatError::PermissionDenied)
                    | (429, AgentStatError::RateLimited { .. })
                    | (302 | 500, AgentStatError::Http { .. })
            ));
            assert_eq!(server.await.unwrap().len(), 1);
        }
    }
}
#[tokio::test]
async fn all_implemented_remote_providers_have_request_and_normalization_fixtures() {
    let cases: Vec<Value> = serde_json::from_str(include_str!("fixtures/providers.json")).unwrap();
    for descriptor in provider_catalog()
        .into_iter()
        .filter(|p| p.status == CoverageStatus::Implemented && p.id != ProviderId::CodeRabbit)
    {
        assert!(
            cases
                .iter()
                .any(|c| c["provider"] == descriptor.id.as_str()),
            "missing fixture for {}",
            descriptor.id
        );
    }
    for case in cases {
        let provider = ProviderId::from_str(case["provider"].as_str().unwrap()).unwrap();
        if !provider.descriptor().enabled {
            continue;
        }
        let (base, server) = server(vec![Reply::json(&case["body"].clone())]).await;
        let client = builder(&base, provider)
            .timeout(Duration::from_secs(2))
            .http_client_builder(reqwest::Client::builder().no_proxy())
            .build()
            .unwrap();
        let credentials = match case["credential"].as_str() {
            Some("cookie") => {
                Credentials::cookie(case["cookie"].as_str().unwrap_or("sessionKey=test-secret"))
            }
            Some("api_key") => Credentials::api_key("test-secret"),
            _ => Credentials::bearer("test-secret"),
        };
        let snapshot = client
            .fetch(
                FetchRequest::new(provider, credentials)
                    .config(config(&case["config"]))
                    .scope(if case["scope"].is_null() {
                        AccountScope::default()
                    } else {
                        serde_json::from_value(case["scope"].clone()).unwrap()
                    }),
            )
            .await
            .unwrap_or_else(|e| panic!("{provider}: {e:?}"));
        assert_eq!(
            snapshot.windows.len(),
            case["windows"].as_u64().unwrap() as usize,
            "{provider}"
        );
        if let Some(percent) = case["percent"].as_f64() {
            assert!(
                (snapshot.windows[0].utilization_percent.unwrap() - percent).abs() < 1e-8,
                "{provider}"
            );
        }
        for (i, amount) in case["balances"]
            .as_array()
            .unwrap_or(&vec![])
            .iter()
            .enumerate()
        {
            assert_eq!(
                snapshot.balances[i].amount.to_string(),
                amount.as_str().unwrap(),
                "{provider}"
            )
        }
        for (i, amount) in case["spend"]
            .as_array()
            .unwrap_or(&vec![])
            .iter()
            .enumerate()
        {
            assert_eq!(
                snapshot.spend[i].amount.to_string(),
                amount.as_str().unwrap(),
                "{provider}"
            )
        }
        let output = serde_json::to_string(&snapshot).unwrap();
        assert!(!output.contains("test-secret"), "{provider}");
        let requests = time::timeout(
            Duration::from_secs(2),
            future::IntoFuture::into_future(server),
        )
        .await
        .unwrap()
        .unwrap();
        let request = &requests[0];
        let method = case["method"].as_str().unwrap_or("GET");
        let prefix = format!("{method} {}", case["path"].as_str().unwrap());
        assert!(request.starts_with(&prefix), "{provider}: {request}");
        let lower = request.to_lowercase();
        if provider == ProviderId::Codebuff {
            assert!(!lower.contains("authorization:"));
            let body: Value =
                serde_json::from_str(request.split("\r\n\r\n").nth(1).unwrap()).unwrap();
            assert_eq!(body["authToken"], "test-secret");
            assert_eq!(body["fingerprintId"], "agentstat-usage");
        } else {
            let expected_auth = match provider {
                ProviderId::Copilot => "authorization: token test-secret",
                ProviderId::OpenCode => "cookie: __host-console_session=test-secret",
                ProviderId::ElevenLabs => "xi-api-key: test-secret",
                ProviderId::Exa => "x-api-key: test-secret",
                ProviderId::Fal => "authorization: key test-secret",
                _ if case["credential"] == "cookie" => "cookie: sessionkey=test-secret",
                _ => "authorization: bearer test-secret",
            };
            assert!(
                lower.contains(expected_auth),
                "{provider}: wrong auth header"
            );
        }
        if provider == ProviderId::Claude {
            assert!(lower.contains("anthropic-beta: oauth-2025-04-20"))
        }
        if matches!(
            provider,
            ProviderId::Tavily | ProviderId::GitKraken | ProviderId::Copilot | ProviderId::DevPass
        ) {
            assert!(
                snapshot
                    .windows
                    .iter()
                    .any(|w| w.limit == QuotaLimit::Unlimited)
            )
        }
    }
}

#[cfg(feature = "codex")]
#[tokio::test]
async fn http_failures_are_typed_redacted_and_never_retried() {
    for status in [401, 403, 429, 500, 302] {
        let (base, server) = server(vec![Reply {
            status,
            body: "test-secret".into(),
            headers: vec![
                ("Retry-After".into(), "120".into()),
                ("Location".into(), "http://127.0.0.1:1/secret".into()),
            ],
        }])
        .await;
        let client = builder(&base, ProviderId::Codex).build().unwrap();
        let err = client
            .fetch(FetchRequest::new(
                ProviderId::Codex,
                Credentials::bearer("test-secret"),
            ))
            .await
            .unwrap_err();
        assert!(!format!("{err} {err:?}").contains("test-secret"));
        match status {
            401 => assert!(matches!(err, AgentStatError::Authentication)),
            403 => assert!(matches!(err, AgentStatError::PermissionDenied)),
            429 => assert!(matches!(
                err,
                AgentStatError::RateLimited {
                    retry_after: Some(_)
                }
            )),
            _ => assert!(matches!(err,AgentStatError::Http{status:s} if s==status)),
        }
        assert_eq!(server.await.unwrap().len(), 1);
    }
}
#[cfg(feature = "codex")]
#[tokio::test]
async fn codex_optional_failure_preserves_primary_and_scope_header() {
    let body = json!({"rate_limit":{"primary_window":{"used_percent":37,"limit_window_seconds":18000,"reset_at":1800000000}}});
    let (base, server) = server(vec![
        Reply::json(&body),
        Reply {
            status: 500,
            body: "private".into(),
            headers: vec![],
        },
    ])
    .await;
    let client = builder(&base, ProviderId::Codex).build().unwrap();
    let request = FetchRequest::new(ProviderId::Codex, Credentials::bearer("private"))
        .scope(AccountScope {
            account_id: Some("workspace-a".into()),
            ..Default::default()
        })
        .include_optional(true);
    let result = client.fetch(request).await.unwrap();
    assert_eq!(result.windows[0].utilization_percent, Some(37.0));
    assert_eq!(result.warnings, vec![Warning::OptionalFetchFailed]);
    for request in server.await.unwrap() {
        assert!(
            request
                .to_lowercase()
                .contains("chatgpt-account-id: workspace-a")
        )
    }
}
#[cfg(feature = "claude")]
#[tokio::test]
async fn claude_cookie_source_uses_explicit_organization() {
    let (base, server) = server(vec![Reply::json(&json!({"five_hour":{"utilization":7}}))]).await;
    let client = builder(&base, ProviderId::Claude).build().unwrap();
    let result = client
        .fetch(
            FetchRequest::new(
                ProviderId::Claude,
                Credentials::cookie("sessionKey=private"),
            )
            .source(Source::Web)
            .config(ProviderConfig::Claude {
                organization_id: "org-a".into(),
            }),
        )
        .await
        .unwrap();
    assert_eq!(result.source, Source::Web);
    assert_eq!(result.scope.organization_id.as_deref(), Some("org-a"));
    assert!(server.await.unwrap()[0].starts_with("GET /api/organizations/org-a/usage "));
}
#[cfg(feature = "claude")]
#[tokio::test]
async fn claude_admin_costs_use_cents_and_api_key_headers() {
    let (base, server) = server(vec![Reply::json(
        &json!({"data":[{"results":[{"amount":"12.34","currency":"USD"}]}],"has_more":false}),
    )])
    .await;
    let client = builder(&base, ProviderId::Claude).build().unwrap();
    let result = client
        .fetch(FetchRequest::new(
            ProviderId::Claude,
            Credentials::api_key("private"),
        ))
        .await
        .unwrap();
    assert_eq!(result.spend[0].amount.to_string(), "0.1234");
    let request = server.await.unwrap().remove(0).to_lowercase();
    assert!(request.contains("x-api-key: private"));
    assert!(request.contains("anthropic-version: 2023-06-01"));
}
#[cfg(feature = "codex")]
#[tokio::test]
async fn malformed_responses_and_body_size_limit() {
    for (body, max, large) in [
        ("{}", 1024, false),
        ("{\"unexpected\":1234567890}", 4, true),
        ("null", 1024, false),
        ("test-secret", 1024, false),
    ] {
        let (base, server) = server(vec![Reply {
            status: 200,
            body: body.into(),
            headers: vec![],
        }])
        .await;
        let client = builder(&base, ProviderId::Codex)
            .max_response_bytes(max)
            .build()
            .unwrap();
        let err = client
            .fetch(FetchRequest::new(
                ProviderId::Codex,
                Credentials::bearer("test-secret"),
            ))
            .await
            .unwrap_err();
        if large {
            assert!(matches!(err, AgentStatError::ResponseTooLarge))
        } else {
            assert!(matches!(err, AgentStatError::InvalidResponse(_)))
        }
        server.await.unwrap();
    }
}
#[test]
fn catalog_covers_all_providers_and_manifest_matches() {
    let manifest: Value = serde_json::from_str(include_str!("../docs/coverage.json")).unwrap();
    assert_eq!(ProviderId::ALL.len(), 106);
    assert_eq!(manifest["providers"].as_array().unwrap().len(), 106);
    for descriptor in provider_catalog() {
        let m = manifest["providers"]
            .as_array()
            .unwrap()
            .iter()
            .find(|v| v["id"] == descriptor.id.as_str())
            .unwrap();
        assert_eq!(m["name"], descriptor.name);
        assert_eq!(m["reason"], descriptor.reason);
        assert_eq!(
            serde_json::to_value(descriptor.status).unwrap(),
            m["status"]
        );
    }
}
#[test]
fn endpoint_validation_and_secret_debug() {
    for url in [
        "http://example.com",
        "https://user:private@example.com",
        "https://example.com/#private",
        "https://example.com/?private=1",
    ] {
        assert!(
            Client::builder()
                .endpoint_override(ProviderId::Codex, url)
                .build()
                .is_err()
        )
    }
    let request = FetchRequest::new(ProviderId::Codex, Credentials::bearer("private"));
    assert!(!format!("{request:?}").contains("private"));
    assert!(Client::builder().concurrency(0).build().is_err());
    assert!(Client::builder().timeout(Duration::ZERO).build().is_err());
}
#[cfg(feature = "codex")]
#[tokio::test]
async fn explicit_source_is_not_silently_changed() {
    let client = Client::builder().build().unwrap();
    assert!(matches!(
        client
            .fetch(
                FetchRequest::new(ProviderId::Codex, Credentials::bearer("private"))
                    .source(Source::Web)
            )
            .await,
        Err(AgentStatError::UnsupportedSource(_))
    ));
}
#[tokio::test]
async fn disabled_and_unimplemented_providers_fail_explicitly() {
    let client = Client::builder().build().unwrap();
    for descriptor in provider_catalog() {
        if descriptor.status != CoverageStatus::Implemented || !descriptor.enabled {
            let error = client
                .fetch(FetchRequest::new(descriptor.id, Credentials::None))
                .await
                .unwrap_err();
            assert!(
                matches!(
                    error,
                    AgentStatError::FeatureDisabled(_) | AgentStatError::Unsupported { .. }
                ),
                "{}: {error}",
                descriptor.id
            );
        }
    }
}
#[cfg(feature = "codex")]
#[tokio::test]
async fn zero_missing_overages_and_malformed_optional_windows_are_preserved() {
    let body = json!({"plan_type":"future-plan","rate_limit":{"primary_window":{"used_percent":125,"limit_window_seconds":18000,"reset_at":1800000000},"secondary_window":"broken"},"additional_rate_limits":[null,{"rate_limit":{"primary_window":{"used_percent":0}}}],"credits":{"balance":"0"}});
    let (base, server) = server(vec![Reply::json(&body)]).await;
    let s = builder(&base, ProviderId::Codex)
        .build()
        .unwrap()
        .fetch(FetchRequest::new(
            ProviderId::Codex,
            Credentials::bearer("private"),
        ))
        .await
        .unwrap();
    assert_eq!(s.windows[0].utilization_percent, Some(125.0));
    assert_eq!(s.windows[1].utilization_percent, Some(0.0));
    assert_eq!(s.windows[1].resets_at, None);
    assert_eq!(s.windows[1].limit, QuotaLimit::Unknown);
    assert_eq!(s.balances[0].amount.to_string(), "0");
    assert!(!s.warnings.is_empty());
    server.await.unwrap();
}
#[cfg(feature = "codex")]
#[tokio::test]
async fn batch_preserves_order_and_account_failures() {
    let (base, server) = server(vec![
        Reply {
            status: 401,
            body: String::new(),
            headers: vec![],
        },
        Reply::json(&json!({"rate_limit":{"primary_window":{"used_percent":20}},"account_id":"b"})),
    ])
    .await;
    let client = builder(&base, ProviderId::Codex)
        .concurrency(1)
        .build()
        .unwrap();
    let requests = ["a", "b"].into_iter().map(|id| {
        FetchRequest::new(ProviderId::Codex, Credentials::bearer("private")).scope(AccountScope {
            account_id: Some(id.into()),
            ..Default::default()
        })
    });
    let result = client.fetch_many(requests).await;
    assert!(matches!(result[0], Err(AgentStatError::Authentication)));
    assert_eq!(
        result[1].as_ref().unwrap().scope.account_id.as_deref(),
        Some("b")
    );
    server.await.unwrap();
}
#[cfg(feature = "codex")]
#[tokio::test]
async fn account_mismatch_fails_instead_of_relabeling_data() {
    let (base, server) = server(vec![Reply::json(
        &json!({"account_id":"b","rate_limit":{"primary_window":{"used_percent":20}}}),
    )])
    .await;
    let client = builder(&base, ProviderId::Codex).build().unwrap();
    let request =
        FetchRequest::new(ProviderId::Codex, Credentials::bearer("private")).scope(AccountScope {
            account_id: Some("a".into()),
            ..Default::default()
        });
    assert!(matches!(
        client.fetch(request).await,
        Err(AgentStatError::InvalidResponse(_))
    ));
    server.await.unwrap();
}
#[cfg(feature = "codex")]
#[derive(Debug)]
struct Hanging;
#[cfg(feature = "codex")]
impl HttpExecutor for Hanging {
    fn execute(&self, _: reqwest::Request) -> BoxFuture<'_, Result<HttpResponse>> {
        Box::pin(future::pending())
    }
}
#[cfg(feature = "codex")]
#[tokio::test]
async fn request_deadline_cancels_transport() {
    let client = Client::builder()
        .http_executor(Arc::new(Hanging))
        .timeout(Duration::from_millis(5))
        .build()
        .unwrap();
    assert!(matches!(
        client
            .fetch(FetchRequest::new(
                ProviderId::Codex,
                Credentials::bearer("private")
            ))
            .await,
        Err(AgentStatError::Timeout)
    ));
}
#[cfg(feature = "codex")]
#[tokio::test]
async fn batch_concurrency_is_bounded() {
    #[derive(Debug)]
    struct Concurrent {
        active: AtomicUsize,
        peak: AtomicUsize,
    }
    impl HttpExecutor for Concurrent {
        fn execute(&self, _: reqwest::Request) -> BoxFuture<'_, Result<HttpResponse>> {
            Box::pin(async move {
                let active = self.active.fetch_add(1, Ordering::SeqCst) + 1;
                self.peak.fetch_max(active, Ordering::SeqCst);
                time::sleep(Duration::from_millis(5)).await;
                self.active.fetch_sub(1, Ordering::SeqCst);
                Ok(HttpResponse {
                    status: 200,
                    headers: HeaderMap::new(),
                    body: br#"{"rate_limit":{"primary_window":{"used_percent":10}}}"#.to_vec(),
                })
            })
        }
    }
    let executor = Arc::new(Concurrent {
        active: AtomicUsize::new(0),
        peak: AtomicUsize::new(0),
    });
    let client = Client::builder()
        .http_executor(executor.clone())
        .concurrency(2)
        .build()
        .unwrap();
    let results = client
        .fetch_many(
            (0..7).map(|_| FetchRequest::new(ProviderId::Codex, Credentials::bearer("private"))),
        )
        .await;
    assert!(results.iter().all(result::Result::is_ok));
    assert_eq!(executor.peak.load(Ordering::SeqCst), 2);
}
#[cfg(feature = "synthetic")]
#[tokio::test]
async fn synthetic_named_quota_slots_have_real_durations() {
    let (base,server)=server(vec![Reply::json(&json!({"rollingFiveHourLimit":{"requests":25,"limit":100},"weeklyTokenLimit":{"used":40,"limit":100},"search":{"hourly":{"used":2,"limit":10}}}))]).await;
    let result = builder(&base, ProviderId::Synthetic)
        .build()
        .unwrap()
        .fetch(FetchRequest::new(
            ProviderId::Synthetic,
            Credentials::api_key("private"),
        ))
        .await
        .unwrap();
    assert_eq!(
        result
            .windows
            .iter()
            .map(|w| w.duration_seconds)
            .collect::<Vec<_>>(),
        vec![Some(18000), Some(604800), Some(3600)]
    );
    server.await.unwrap();
}
#[cfg(feature = "openai")]
#[tokio::test]
async fn admin_pagination_does_not_merge_currencies_or_replay_cursors() {
    let (base,server)=server(vec![Reply::json(&json!({"data":[{"results":[{"amount":{"value":"0.1","currency":"usd"}}]}],"has_more":true,"next_page":"page-two"})),Reply::json(&json!({"data":[{"results":[{"amount":{"value":"0.2","currency":"usd"}},{"amount":{"value":"1.25","currency":"eur"}}]}],"has_more":false}))]).await;
    let result = builder(&base, ProviderId::OpenAI)
        .build()
        .unwrap()
        .fetch(FetchRequest::new(
            ProviderId::OpenAI,
            Credentials::api_key("private"),
        ))
        .await
        .unwrap();
    assert_eq!(result.spend.len(), 2);
    assert!(
        result
            .spend
            .iter()
            .any(|s| s.currency == "USD" && s.amount.as_str() == "0.3")
    );
    assert!(
        result
            .spend
            .iter()
            .any(|s| s.currency == "EUR" && s.amount.as_str() == "1.25")
    );
    assert!(server.await.unwrap()[1].contains("page=page-two"));
}

#[cfg(feature = "openai")]
#[tokio::test]
async fn admin_rejects_missing_or_malformed_pagination_flags() {
    for flag in [None, Some(json!("false")), Some(json!(null))] {
        let mut response = json!({
            "data": [{"results": [{"amount": {"value": "1", "currency": "usd"}}]}]
        });
        if let Some(flag) = flag {
            response["has_more"] = flag;
        }
        let (base, server) = server(vec![Reply::json(&response)]).await;
        let result = builder(&base, ProviderId::OpenAI)
            .build()
            .unwrap()
            .fetch(FetchRequest::new(
                ProviderId::OpenAI,
                Credentials::api_key("private"),
            ))
            .await;
        assert!(matches!(result, Err(AgentStatError::InvalidResponse(_))));
        assert_eq!(server.await.unwrap().len(), 1);
    }
}

#[cfg(feature = "codebuff")]
#[tokio::test]
async fn codebuff_api_key_keeps_bearer_header_request() {
    let (base, server) = server(vec![Reply::json(&json!({"usage": 25, "quota": 100}))]).await;
    let snapshot = builder(&base, ProviderId::Codebuff)
        .build()
        .unwrap()
        .fetch(FetchRequest::new(
            ProviderId::Codebuff,
            Credentials::api_key("paid-key"),
        ))
        .await
        .unwrap();
    assert_eq!(snapshot.windows[0].utilization_percent, Some(25.0));
    let request = server.await.unwrap().remove(0);
    assert!(request.contains("authorization: Bearer paid-key"));
    let body: Value = serde_json::from_str(request.split("\r\n\r\n").nth(1).unwrap()).unwrap();
    assert_eq!(body, json!({"fingerprintId": "agentstat-usage"}));
}

#[cfg(feature = "ollama")]
#[tokio::test]
async fn ollama_legacy_limits_preserve_remaining_percent_and_reset_times() {
    let (base, server) = server(vec![Reply::json(&json!({
        "included": {
            "session": {"remaining_percent": 75, "resets_at": "2026-10-23T07:00:00Z"},
            "weekly": {"remaining_percent": 40, "resets_at": "2026-10-29T00:00:00Z"}
        },
        "purchased": {"balance_usd": "12.345"}
    }))])
    .await;
    let snapshot = builder(&base, ProviderId::Ollama)
        .build()
        .unwrap()
        .fetch(FetchRequest::new(
            ProviderId::Ollama,
            Credentials::api_key("private"),
        ))
        .await
        .unwrap();
    assert_eq!(snapshot.windows.len(), 2);
    assert_eq!(snapshot.windows[0].id, "session");
    assert_eq!(snapshot.windows[0].utilization_percent, Some(25.0));
    assert_eq!(snapshot.windows[0].duration_seconds, Some(18_000));
    assert_eq!(snapshot.windows[1].utilization_percent, Some(60.0));
    assert_eq!(snapshot.windows[1].duration_seconds, Some(604_800));
    assert!(
        snapshot
            .windows
            .iter()
            .all(|window| window.resets_at.is_some())
    );
    assert_eq!(snapshot.balances[0].amount.as_str(), "12.345");
    let requests = server.await.unwrap();
    assert_eq!(requests.len(), 1);
    assert!(requests[0].starts_with("GET /api/balance "));
    assert!(requests[0].contains("authorization: Bearer private"));
}

#[cfg(feature = "ollama")]
#[tokio::test]
async fn ollama_rejects_malformed_legacy_meter() {
    let (base, server) = server(vec![Reply::json(&json!({
        "included": {
            "session": {"remaining_percent": 110, "resets_at": "2026-10-23T07:00:00Z"},
            "weekly": {"remaining_percent": 40, "resets_at": "2026-10-29T00:00:00Z"}
        }
    }))])
    .await;
    assert!(matches!(
        builder(&base, ProviderId::Ollama)
            .build()
            .unwrap()
            .fetch(FetchRequest::new(
                ProviderId::Ollama,
                Credentials::bearer("private")
            ))
            .await,
        Err(AgentStatError::InvalidResponse(_))
    ));
    server.await.unwrap();
}

#[cfg(feature = "ollama")]
#[tokio::test]
async fn mismatched_typed_provider_configuration_is_rejected_before_fetch() {
    let result = Client::builder()
        .build()
        .unwrap()
        .fetch(
            FetchRequest::new(ProviderId::Ollama, Credentials::bearer("private")).config(
                ProviderConfig::Exa {
                    api_key_id: "another-account".into(),
                },
            ),
        )
        .await;
    assert!(matches!(result, Err(AgentStatError::Configuration(_))));
}

#[cfg(feature = "opencodego")]
#[tokio::test]
async fn opencode_go_reads_key_authenticated_quota_windows() {
    let (base, server) = server(vec![Reply::json(&json!({"usage": {
        "rolling": {"status": "ok", "percent": 12, "resetsAt": "2026-10-23T03:00:00Z"},
        "weekly": {"status": "rate-limited", "percent": 100, "resetsAt": "2026-10-29T00:00:00Z"},
        "monthly": {"status": "ok", "percent": 8, "resetsAt": "2026-11-01T00:00:00Z"}
    }}))])
    .await;
    let snapshot = builder(&base, ProviderId::OpenCodeGo)
        .build()
        .unwrap()
        .fetch(FetchRequest::new(
            ProviderId::OpenCodeGo,
            Credentials::api_key("private"),
        ))
        .await
        .unwrap();
    assert_eq!(snapshot.source, Source::Api);
    assert_eq!(snapshot.windows.len(), 3);
    assert_eq!(snapshot.windows[0].id, "five-hour");
    assert_eq!(snapshot.windows[0].duration_seconds, Some(18_000));
    assert_eq!(snapshot.windows[1].utilization_percent, Some(100.0));
    assert_eq!(snapshot.windows[2].id, "monthly");
    assert_eq!(snapshot.windows[2].kind, WindowKind::Calendar);
    assert!(snapshot.balances.is_empty());
    let requests = server.await.unwrap();
    assert_eq!(requests.len(), 1);
    assert!(requests[0].starts_with("GET /zen/go/v1/usage "));
    assert!(requests[0].contains("authorization: Bearer private"));
}

#[cfg(feature = "opencodego")]
#[tokio::test]
async fn opencode_go_rejects_missing_or_invalid_windows() {
    for body in [
        json!({"usage": {}}),
        json!({"usage": {
            "rolling": {"status": "ok", "percent": 120, "resetsAt": "2026-10-23T03:00:00Z"},
            "weekly": {"status": "ok", "percent": 20, "resetsAt": "2026-10-29T00:00:00Z"},
            "monthly": {"status": "ok", "percent": 10, "resetsAt": "2026-11-01T00:00:00Z"}
        }}),
    ] {
        let (base, server) = server(vec![Reply::json(&body)]).await;
        assert!(matches!(
            builder(&base, ProviderId::OpenCodeGo)
                .build()
                .unwrap()
                .fetch(FetchRequest::new(
                    ProviderId::OpenCodeGo,
                    Credentials::api_key("private")
                ))
                .await,
            Err(AgentStatError::InvalidResponse(_))
        ));
        server.await.unwrap();
    }
}

#[cfg(feature = "opencode")]
mod opencode {
    use super::*;

    fn request(workspace: Option<&str>) -> FetchRequest {
        FetchRequest::new(
            ProviderId::OpenCode,
            Credentials::cookie("__Host-console_session=test-secret"),
        )
        .source(Source::Web)
        .scope(AccountScope {
            workspace_id: workspace.map(str::to_owned),
            ..Default::default()
        })
    }
    fn quota() -> Value {
        json!({"access":{"endsAt":"2026-11-01T00:00:00Z","meters":{
            "fiveHour":{"usedMicroCents":"300000000","limitMicroCents":"1200000000","resetsAt":"2026-10-23T03:00:00Z"},
            "week":{"usedMicroCents":"1200000000","limitMicroCents":"3000000000"},
            "month":{"usedMicroCents":"600000000","limitMicroCents":"6000000000"}
        }}})
    }
    fn payg_replies(balance: &Value, total: &Value) -> Vec<Reply> {
        vec![
            Reply::json(&Value::Null),
            Reply::json(&json!({"id":"wrk_A","hasGoSubscription":false})),
            Reply::json(
                &json!({"mode":"pay-as-you-go","billingMode":"prepaid","balanceMicroCents":balance}),
            ),
            Reply::json(&json!({"totalCostMicroCents":total})),
        ]
    }

    #[tokio::test]
    async fn discovers_unique_workspace_and_scopes_all_usage_requests() {
        let (base, server) = server(vec![
            Reply::json(&json!([{"id":"wrk_A"}])),
            Reply::json(&quota()),
        ])
        .await;
        let snapshot = builder(&base, ProviderId::OpenCode)
            .build()
            .unwrap()
            .fetch(request(None))
            .await
            .unwrap();
        assert_eq!(snapshot.scope.workspace_id.as_deref(), Some("wrk_A"));
        assert_eq!(snapshot.source, Source::Web);
        assert_eq!(
            snapshot
                .windows
                .iter()
                .map(|w| w.utilization_percent)
                .collect::<Vec<_>>(),
            vec![Some(25.0), Some(40.0), Some(10.0)]
        );
        assert_eq!(snapshot.windows[0].used.as_ref().unwrap().as_str(), "3");
        assert_eq!(
            snapshot.windows[0].limit,
            QuotaLimit::Known("12".parse().unwrap())
        );
        assert_eq!(
            snapshot.windows[0].remaining.as_ref().unwrap().as_str(),
            "9"
        );
        assert_eq!(snapshot.windows[0].duration_seconds, Some(18000));
        assert_eq!(snapshot.windows[1].duration_seconds, Some(604800));
        assert_eq!(snapshot.windows[1].resets_at, None);
        assert_eq!(snapshot.windows[2].kind, WindowKind::Calendar);
        assert_eq!(
            snapshot.windows[2].resets_at.unwrap().to_rfc3339(),
            "2026-11-01T00:00:00+00:00"
        );
        let requests = server.await.unwrap();
        assert!(requests[0].starts_with("GET /console/api/orgs "));
        assert!(!requests[0].contains("x-org-id:"));
        assert!(requests[1].contains("x-org-id: wrk_A"));
        for request in requests {
            assert!(request.contains("cookie: __Host-console_session=test-secret"));
            assert!(!request.contains("authorization:"));
        }
    }

    #[tokio::test]
    async fn go_subscription_can_include_zen_prepaid_balance() {
        let (base, server) = server(vec![
            Reply::json(&quota()),
            Reply::json(&json!({
                "mode": "pay-as-you-go",
                "billingMode": "prepaid",
                "balanceMicroCents": "1250000000"
            })),
        ])
        .await;
        let snapshot = builder(&base, ProviderId::OpenCode)
            .build()
            .unwrap()
            .fetch(request(Some("wrk_A")).include_optional(true))
            .await
            .unwrap();
        assert_eq!(snapshot.windows.len(), 3);
        assert_eq!(snapshot.balances[0].id, "prepaid");
        assert_eq!(snapshot.balances[0].amount.as_str(), "12.5");
        let requests = server.await.unwrap();
        assert_eq!(requests.len(), 2);
        assert!(requests[1].starts_with("GET /console/api/billing/status "));
        assert!(requests[1].contains("x-org-id: wrk_A"));
    }

    #[tokio::test]
    async fn optional_zen_balance_failure_keeps_go_quota() {
        let (base, server) = server(vec![
            Reply::json(&quota()),
            Reply {
                status: 503,
                body: "unavailable".into(),
                headers: vec![],
            },
        ])
        .await;
        let snapshot = builder(&base, ProviderId::OpenCode)
            .build()
            .unwrap()
            .fetch(request(Some("wrk_A")).include_optional(true))
            .await
            .unwrap();
        assert_eq!(snapshot.windows.len(), 3);
        assert!(snapshot.balances.is_empty());
        assert_eq!(snapshot.warnings, vec![Warning::OptionalFetchFailed]);
        server.await.unwrap();
    }

    #[tokio::test]
    async fn discovery_never_selects_arbitrary_workspace() {
        for body in [
            json!([]),
            json!([{"id":"not-a-workspace"}]),
            json!([{"id":"wrk_A"},{"id":"org_B"}]),
            json!({"error":"unexpected"}),
        ] {
            let (base, server) = server(vec![Reply::json(&body)]).await;
            let result = builder(&base, ProviderId::OpenCode)
                .build()
                .unwrap()
                .fetch(request(None))
                .await;
            assert!(matches!(
                result,
                Err(AgentStatError::Configuration(_) | AgentStatError::InvalidResponse(_))
            ));
            assert_eq!(server.await.unwrap().len(), 1);
        }
    }

    #[tokio::test]
    async fn explicit_workspace_skips_discovery_and_invalid_selection_fails_locally() {
        let (base, server) = server(vec![Reply::json(&quota())]).await;
        builder(&base, ProviderId::OpenCode)
            .build()
            .unwrap()
            .fetch(request(Some("org_SELECTED")))
            .await
            .unwrap();
        let requests = server.await.unwrap();
        assert_eq!(requests.len(), 1);
        assert!(requests[0].starts_with("GET /console/api/go/status "));
        assert!(requests[0].contains("x-org-id: org_SELECTED"));
        let client = Client::builder().build().unwrap();
        for id in [
            "",
            "wrk_",
            "../wrk_A",
            "https://opencode.ai/console/wrk_A",
            "wrk_A\n",
        ] {
            assert!(matches!(
                client.fetch(request(Some(id))).await,
                Err(AgentStatError::Configuration(_))
            ));
        }
        assert!(matches!(
            client
                .fetch(FetchRequest::new(
                    ProviderId::OpenCode,
                    Credentials::api_key("private")
                ))
                .await,
            Err(AgentStatError::InvalidCredentials(_))
        ));
        assert!(matches!(
            client
                .fetch(request(Some("wrk_A")).source(Source::Api))
                .await,
            Err(AgentStatError::UnsupportedSource(_))
        ));
    }

    #[tokio::test]
    async fn missing_optional_meters_stay_missing_and_overages_survive() {
        let body = json!({"access":{"meters":{"fiveHour":{"usedMicroCents":"1500000000","limitMicroCents":"1200000000"},"week":{"usedMicroCents":"invalid","limitMicroCents":"100"}}}});
        let (base, server) = server(vec![Reply::json(&body)]).await;
        let snapshot = builder(&base, ProviderId::OpenCode)
            .build()
            .unwrap()
            .fetch(request(Some("wrk_A")))
            .await
            .unwrap();
        assert_eq!(snapshot.windows.len(), 1);
        assert_eq!(snapshot.windows[0].utilization_percent, Some(125.0));
        assert_eq!(
            snapshot.windows[0].remaining.as_ref().unwrap().as_str(),
            "-3"
        );
        assert_eq!(snapshot.windows[0].resets_at, None);
        assert_eq!(snapshot.warnings, vec![Warning::MalformedOptionalData]);
        server.await.unwrap();
    }

    #[tokio::test]
    async fn zero_limits_do_not_become_unlimited() {
        let (base, server) = server(vec![Reply::json(
            &json!({"access":{"meters":{"fiveHour":{"usedMicroCents":0,"limitMicroCents":"0"}}}}),
        )])
        .await;
        let snapshot = builder(&base, ProviderId::OpenCode)
            .build()
            .unwrap()
            .fetch(request(Some("wrk_A")))
            .await
            .unwrap();
        assert_eq!(
            snapshot.windows[0].limit,
            QuotaLimit::Known(Decimal::from(0))
        );
        assert_eq!(snapshot.windows[0].utilization_percent, None);
        server.await.unwrap();
    }

    #[tokio::test]
    async fn confirmed_payg_preserves_exact_spend_balance_and_workspace() {
        let (base, server) = server(payg_replies(&json!("1250000000"), &json!("325000000"))).await;
        let snapshot = builder(&base, ProviderId::OpenCode)
            .build()
            .unwrap()
            .fetch(request(Some("wrk_A")))
            .await
            .unwrap();
        assert!(snapshot.windows.is_empty());
        assert_eq!(snapshot.spend[0].id, "last-30-days");
        assert_eq!(snapshot.spend[0].amount.as_str(), "3.25");
        assert_eq!(snapshot.balances[0].amount.as_str(), "12.5");
        let requests = server.await.unwrap();
        assert_eq!(requests.len(), 4);
        assert!(requests[3].starts_with("GET /console/api/usage/summary?range=30d "));
        for request in requests {
            assert!(request.starts_with("GET "));
            assert!(request.contains("x-org-id: wrk_A"));
        }
    }

    #[tokio::test]
    async fn optional_balance_failure_preserves_spend_and_negative_balance_is_valid() {
        for balance in [Value::Null, json!("invalid"), json!("-1250000000")] {
            let (base, server) =
                server(payg_replies(&balance, &json!("900719925474099312345678"))).await;
            let snapshot = builder(&base, ProviderId::OpenCode)
                .build()
                .unwrap()
                .fetch(request(Some("wrk_A")))
                .await
                .unwrap();
            assert_eq!(
                snapshot.spend[0].amount.as_str(),
                "9007199254740993.12345678"
            );
            if balance == "-1250000000" {
                assert_eq!(snapshot.balances[0].amount.as_str(), "-12.5")
            } else {
                assert!(snapshot.balances.is_empty());
                assert!(!snapshot.warnings.is_empty());
            }
            server.await.unwrap();
        }
    }

    #[tokio::test]
    async fn broken_subscription_never_falls_back_to_spend() {
        for body in [
            json!({}),
            json!({"access":{"meters":{}}}),
            json!({"access":false}),
            json!({"access":{"meters":{"fiveHour":{"usedMicroCents":true,"limitMicroCents":100}}}}),
        ] {
            let (base, server) = server(vec![Reply::json(&body)]).await;
            assert!(matches!(
                builder(&base, ProviderId::OpenCode)
                    .build()
                    .unwrap()
                    .fetch(request(Some("wrk_A")))
                    .await,
                Err(AgentStatError::InvalidResponse(_))
            ));
            assert_eq!(server.await.unwrap().len(), 1);
        }
        for organization in [
            json!({"hasGoSubscription":true}),
            json!({"hasGoSubscription":false,"id":"wrk_B"}),
            json!({}),
        ] {
            let (base, server) = server(vec![
                Reply::json(&json!({"access":null})),
                Reply::json(&organization),
            ])
            .await;
            assert!(matches!(
                builder(&base, ProviderId::OpenCode)
                    .build()
                    .unwrap()
                    .fetch(request(Some("wrk_A")))
                    .await,
                Err(AgentStatError::InvalidResponse(_))
            ));
            server.await.unwrap();
        }
    }

    #[tokio::test]
    async fn invalid_microcent_totals_fail_instead_of_becoming_zero() {
        for total in [
            json!(true),
            json!(-1),
            json!(1.5),
            json!("NaN"),
            Value::Null,
            json!("-1"),
            json!("1.5"),
        ] {
            let (base, server) = server(payg_replies(&json!("0"), &total)).await;
            assert!(matches!(
                builder(&base, ProviderId::OpenCode)
                    .build()
                    .unwrap()
                    .fetch(request(Some("wrk_A")))
                    .await,
                Err(AgentStatError::InvalidResponse(_))
            ));
            server.await.unwrap();
        }
    }

    #[tokio::test]
    async fn provider_errors_stop_without_retry_or_legacy_fallback() {
        for status in [401, 403, 429, 500] {
            let (base, server) = server(vec![Reply {
                status,
                body: "private-token".into(),
                headers: vec![],
            }])
            .await;
            let error = builder(&base, ProviderId::OpenCode)
                .build()
                .unwrap()
                .fetch(request(Some("wrk_A")))
                .await
                .unwrap_err();
            match status {
                401 => assert!(matches!(error, AgentStatError::Authentication)),
                403 => assert!(matches!(error, AgentStatError::PermissionDenied)),
                429 => assert!(matches!(error, AgentStatError::RateLimited { .. })),
                _ => assert!(matches!(error, AgentStatError::Http { status: 500 })),
            }
            assert!(!format!("{error:?}").contains("private-token"));
            assert_eq!(server.await.unwrap().len(), 1);
        }
    }
}