loopctl 0.3.0

A trait-based framework for building agent loops with pluggable LLM clients, tools, and memory
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
//! LLM provider clients.
//!
//! This module provides ready-to-use [`ApiClient`](crate::api::ApiClient)
//! implementations for common LLM providers. Each provider is behind a
//! feature flag so you only compile what you need.
//!
//! # Feature Flags
//!
//! | Provider     | Feature    | API Format              |
//! |--------------|------------|-------------------------|
//! | OpenAI       | `openai`   | OpenAI Chat Completions |
//! | Anthropic    | `anthropic`| Anthropic Messages      |
//! | Gemini       | `gemini`   | Google Gemini           |
//! | Ollama       | `ollama`   | OpenAI-compatible       |
//! | `DeepSeek`   | `deepseek` | OpenAI-compatible       |
//! | `Grok` (xAI) | `grok`     | OpenAI-compatible       |
//! | `Z.ai`       | `zai`      | Anthropic Messages      |
//! | Azure OpenAI | `azure`    | OpenAI-compatible       |
//! | Moonshot AI  | `moonshot` | OpenAI-compatible       |
//! | AWS Bedrock  | `bedrock`  | Bedrock Converse/native |
//! | Self-hosted  | any        | OpenAI-compatible       |
//!
//! Any provider that exposes an OpenAI-compatible Chat Completions API
//! can use [`OpenAiClient`] with a custom base URL. The convenience
//! constructors below pre-configure the correct endpoints.
//!
//! # Quick Start
//!
//! ```rust,ignore
//! use loopctl::provider;
//! use loopctl::engine::BareLoop;
//! use loopctl::engine::RunConfig;
//! use loopctl::engine::core::Loop;
//!
//! // OpenAI:
//! let client = provider::OpenAiClient::from_env()?;
//!
//! // DeepSeek:
//! let client = provider::deepseek()?;
//!
//! // Anthropic:
//! let client = provider::AnthropicClient::from_env()?;
//!
//! // Gemini:
//! let client = provider::GeminiClient::from_env()?;
//!
//! // Ollama (local):
//! let client = provider::ollama("llama3")?;
//!
//! // Self-hosted (vLLM, LM Studio, etc.):
//! let client = provider::self_hosted("http://localhost:8080/v1", "my-model")?;
//!
//! let agent = BareLoop::new(
//!     std::sync::Arc::new(client),
//!     tool_registry,
//!     config,
//! );
//! let result = agent.run("Hello!", &RunConfig::default()).await?;
//! ```

#[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
use crate::api::error::ApiError;
#[cfg(any(feature = "anthropic", feature = "gemini"))]
use crate::message::{MessagePart, Role};
#[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
use futures::StreamExt;
#[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
use std::time::Duration;

// SSE line-framing shared by every streaming provider. Each provider keeps
// its own event-extraction logic (`next_data` / `next_event`); the struct,
// `from_response`, `take_line`, and the buffer-overflow guard live here.
#[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
mod sse;

/// Extract the payload of an SSE `data:` field line, or `None` for any other
/// line.
///
/// The SSE specification allows zero or one space after the field colon, so
/// both the spaced form (`data: {...}`) that first-party endpoints send and
/// the compact form (`data:{...}`) that some OpenAI/Anthropic-compatible
/// servers emit are accepted. Exactly one leading space is removed — a second
/// space is payload, not framing. Shared by every provider's event reader so
/// the rule cannot drift between them.
#[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
fn sse_data_payload(line: &str) -> Option<&str> {
    let payload = line.strip_prefix("data:")?;
    Some(payload.strip_prefix(' ').unwrap_or(payload))
}

/// Extract the event name of an SSE `event:` field line, or `None` for any
/// other line.
///
/// Applies the same one-optional-space rule as [`sse_data_payload`]: the
/// spec allows zero or one space after the field colon, and a second space
/// is part of the name. Used by the Anthropic event reader, which pairs an
/// `event:` line with its `data:` payload before dispatching — a compact
/// `event:` line there previously dispatched under an empty type, dropping
/// the whole event.
#[cfg(feature = "anthropic")]
fn sse_event_type(line: &str) -> Option<&str> {
    let event = line.strip_prefix("event:")?;
    Some(event.strip_prefix(' ').unwrap_or(event))
}

/// Maximum accepted response body size (10 MB).
///
/// Guards against unbounded memory growth from a misbehaving or hostile
/// provider that returns a very large non-streaming response. Enforced
/// *before* the body is fully materialized — see
/// [`read_bounded_body`](crate::provider::read_bounded_body).
#[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
pub(super) const MAX_RESPONSE_BODY: usize = 10 * 1024 * 1024;

/// Read a response body, rejecting it before peak memory is exceeded.
///
/// Shared guard used by every provider's non-streaming path. Two checks
/// bound memory:
///
/// 1. **Pre-read (`Content-Length`)** — when the header is present and
///    exceeds [`MAX_RESPONSE_BODY`], the body is rejected without reading a
///    single byte. A hostile provider advertising a huge body never allocates
///    it.
/// 2. **Streaming cap** — for responses without `Content-Length` (chunked
///    transfer), the body is read chunk by chunk and the read aborts the
///    moment the running total crosses [`MAX_RESPONSE_BODY`], so peak memory
///    never exceeds the cap by more than one chunk.
///
/// Replaces the old `resp.bytes().await` + post-hoc length check, which
/// materialized the full body before the guard could fire.
///
/// # Errors
///
/// Returns [`ApiError`] when the body exceeds [`MAX_RESPONSE_BODY`] (either
/// via the header pre-check or the streaming cap), or on a transport error
/// reading the body.
#[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
pub(super) async fn read_bounded_body(resp: reqwest::Response) -> Result<bytes::Bytes, ApiError> {
    if let Some(len) = resp.content_length()
        && usize::try_from(len).map_or(true, |n| n > MAX_RESPONSE_BODY)
    {
        return Err(ApiError::http(format!(
            "response body too large: declared {len} bytes (max {MAX_RESPONSE_BODY})"
        )));
    }
    let mut stream = resp.bytes_stream();
    let mut buf: Vec<u8> = Vec::new();
    while let Some(chunk) = stream.next().await {
        let chunk =
            chunk.map_err(|e| ApiError::http(format!("error reading response body: {e}")))?;
        buf.extend_from_slice(&chunk);
        if buf.len() > MAX_RESPONSE_BODY {
            return Err(ApiError::http(format!(
                "response body too large: streamed {} bytes (max {MAX_RESPONSE_BODY})",
                buf.len()
            )));
        }
    }
    Ok(buf.into())
}

/// Maximum error-diagnostic body retained from a non-success response (8 `KiB`).
///
/// Bounds both memory and network traffic when a provider answers a failed
/// request with a large body: the read stops as soon as this many bytes are
/// available, so a misbehaving endpoint cannot make the client materialize a
/// multi-gigabyte error page. The retained prefix is what error messages and
/// logs carry.
#[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
pub(super) const MAX_ERROR_BODY: usize = 8 * 1024;

/// Read the diagnostic body of an error response, capped at
/// [`MAX_ERROR_BODY`] bytes.
///
/// Two guards bound the transfer. When `Content-Length` is present and
/// exceeds the cap, the body is refused outright — the response is dropped
/// without reading a single body byte, closing the connection before the
/// server can send the bulk (kernel socket buffers would otherwise let a
/// misbehaving server write far past the cap even after the client stops
/// reading). Otherwise the body is streamed and the read stops as soon as
/// the cap is available, which also bounds chunked responses. Decode errors
/// are replaced lossily so a binary body still yields printable text for
/// logs; an oversized body yields an empty string — its status alone
/// classifies the error.
#[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
pub(super) async fn read_error_body(resp: reqwest::Response) -> String {
    if let Some(len) = resp.content_length()
        && usize::try_from(len).map_or(true, |n| n > MAX_ERROR_BODY)
    {
        return String::new();
    }
    let mut stream = resp.bytes_stream();
    let mut buf: Vec<u8> = Vec::new();
    while buf.len() < MAX_ERROR_BODY
        && let Some(chunk) = stream.next().await
    {
        match chunk {
            Ok(bytes) => {
                let remaining = MAX_ERROR_BODY.saturating_sub(buf.len());
                buf.extend_from_slice(bytes.get(..remaining).unwrap_or(&bytes));
            }
            Err(_) => break,
        }
    }
    String::from_utf8_lossy(&buf).into_owned()
}

/// Classify a non-success HTTP response into the matching [`ApiError`]
/// variant.
///
/// The status alone picks the variant so the classification survives without
/// re-parsing message strings: 401 and 403 are authentication failures
/// ([`ApiError::Auth`], permanent), 429/503/529 are rate limits
/// ([`ApiError::RateLimit`], carrying the parsed `Retry-After` when the
/// server sent one), and everything else stays a status-tagged
/// [`ApiError::Http`]. The body text is preserved in the message for
/// diagnostics, prefixed with the status.
#[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
fn classify_error_response(status: u16, body: String, retry_after: Option<Duration>) -> ApiError {
    match status {
        401 => ApiError::auth_invalid_key(format!("HTTP {status}: {body}")),
        403 => ApiError::auth(format!("HTTP {status}: {body}")),
        429 | 503 | 529 => ApiError::rate_limited(format!("HTTP {status}: {body}"), retry_after),
        _ => ApiError::http_with_status(status, body),
    }
}

/// Send a JSON POST and classify non-success responses into structured
/// [`ApiError`] variants.
///
/// The single HTTP-error construction site shared by the provider clients:
/// it sends the request with `headers` applied, and on a non-success status
/// it reads the `Retry-After` header while the response is still in hand,
/// reads the diagnostic body capped at [`MAX_ERROR_BODY`] bytes, and maps the
/// status via [`classify_error_response`]. Callers therefore get the right
/// variant — auth rejections as [`ApiError::Auth`], rate limits with the
/// server-advised delay as [`ApiError::RateLimit`] — without each provider
/// re-implementing (and drifting on) the same branches. Header values are
/// applied verbatim: callers mark credential headers sensitive
/// ([`HeaderValue::set_sensitive`](reqwest::header::HeaderValue::set_sensitive))
/// so they are redacted in debug output and never indexed into HTTP/2's
/// header-compression table.
///
/// # Errors
///
/// Returns [`ApiError::http`] when the request fails at the transport level,
/// or the classified variant for any non-success status.
#[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
pub(super) async fn post_json_checked(
    client: &reqwest::Client,
    url: &str,
    headers: &[(reqwest::header::HeaderName, reqwest::header::HeaderValue)],
    body: &serde_json::Value,
) -> Result<reqwest::Response, ApiError> {
    let request = headers.iter().fold(client.post(url), |req, (name, value)| {
        req.header(name.clone(), value.clone())
    });
    let resp = request
        .json(body)
        .send()
        .await
        .map_err(|e| ApiError::http(e.to_string()))?;
    let status = resp.status();
    if status.is_success() {
        return Ok(resp);
    }
    let retry_after = resp
        .headers()
        .get(reqwest::header::RETRY_AFTER)
        .and_then(|value| value.to_str().ok())
        .and_then(crate::api::error::parse_retry_after);
    let body_text = read_error_body(resp).await;
    Err(classify_error_response(
        status.as_u16(),
        body_text,
        retry_after,
    ))
}

/// Shared HTTP-client configuration embedded by every provider builder.
///
/// Holds the timeout, connection-pool, and TCP knobs that are identical
/// across [`OpenAiClient`](crate::provider::OpenAiClient),
/// [`AnthropicClient`](crate::provider::AnthropicClient), and
/// [`GeminiClient`](crate::provider::GeminiClient). Each provider builder
/// embeds this struct and delegates its HTTP-related setters to it, so the
/// pool/TCP documentation and construction logic lives in one place.
#[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
#[derive(Clone)]
pub(super) struct HttpClientConfig {
    /// The HTTP read timeout: the maximum gap between bytes of a response.
    ///
    /// Bounds *idleness*, not total duration — a healthy slow stream (a long
    /// SSE generation that keeps emitting events) runs as long as it keeps
    /// producing bytes, while a server that goes silent is aborted after this
    /// gap. This is deliberately not a total request timeout: a total cap at
    /// the HTTP layer would pre-empt the `StreamHandler`'s per-event and
    /// total-stream deadlines (and the engine's turn timeout), killing any
    /// generation longer than the cap. Defaults to 120 seconds.
    ///
    /// Ignored when an external client is supplied via
    /// [`with_http_client`](Self::with_http_client); configure it on that
    /// client instead.
    timeout: Duration,

    /// The TCP connection establishment timeout (including TLS handshake).
    ///
    /// Separate from the total timeout so a slow-connecting server can be
    /// detected faster than a slow-responding one. Defaults to 10 seconds.
    ///
    /// Ignored when an external client is supplied via
    /// [`with_http_client`](Self::with_http_client).
    connect_timeout: Duration,

    /// A pre-built, shared `reqwest::Client`, if injected via
    /// [`with_http_client`](Self::with_http_client).
    ///
    /// When set, the client's connection pool is shared with every other
    /// provider built from the same handle, and the pool/TCP knobs below
    /// (`pool_*`, `tcp_*`) are ignored — they are only applied when the
    /// builder constructs its own client. Configure timeouts on the injected
    /// client, not here.
    http: Option<reqwest::Client>,

    /// Maximum idle connections kept alive per host.
    ///
    /// `None` defers to reqwest's default (unlimited). Set to a small value
    /// (e.g. 1–4) for memory-constrained runners or workloads that make
    /// mostly serial requests to a single host.
    pool_max_idle_per_host: Option<usize>,

    /// How long an idle connection stays in the pool before being closed.
    ///
    /// `None` defers to reqwest's default (90s). Raise for long-idle
    /// interactive workloads to keep TLS sessions warm; lower for tight
    /// batch jobs to free file descriptors sooner.
    pool_idle_timeout: Option<Duration>,

    /// OS-level TCP keepalive interval.
    ///
    /// `None` disables TCP keepalive (reqwest default). Enable (~60s) if
    /// connections are silently dropped after idle periods (e.g. behind
    /// aggressive NATs or load balancers).
    tcp_keepalive: Option<Duration>,

    /// Whether to disable Nagle's algorithm (`TCP_NODELAY`).
    ///
    /// Defaults to `true` — SSE streaming emits many small packets, and
    /// Nagle's algorithm coalesces them, adding latency per delta.
    tcp_nodelay: bool,
}

#[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
impl Default for HttpClientConfig {
    fn default() -> Self {
        Self {
            timeout: Duration::from_mins(2),
            connect_timeout: Duration::from_secs(10),
            http: None,
            pool_max_idle_per_host: None,
            pool_idle_timeout: None,
            tcp_keepalive: None,
            tcp_nodelay: true,
        }
    }
}

#[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
impl HttpClientConfig {
    /// Set the read timeout (maximum gap between response bytes).
    ///
    /// Not a total request timeout — long streaming generations are bounded
    /// by the `StreamHandler`'s per-event/total deadlines, not by the HTTP
    /// layer. Ignored when an external client was supplied via
    /// [`with_http_client`](Self::with_http_client).
    #[must_use]
    pub(super) fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Set the TCP connection establishment timeout.
    ///
    /// Ignored when an external client was supplied.
    #[must_use]
    pub(super) fn with_connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = timeout;
        self
    }

    /// Inject a pre-built, shared `reqwest::Client`.
    ///
    /// When set, the client's connection pool is shared with every other
    /// provider built from the same handle, and the pool/TCP knobs are
    /// ignored. Configure timeouts on the injected client, not here.
    #[must_use]
    pub(super) fn with_http_client(mut self, client: reqwest::Client) -> Self {
        self.http = Some(client);
        self
    }

    /// Set the maximum idle connections kept alive per host.
    ///
    /// Defaults to reqwest's built-in default (unlimited). Set to a small
    /// value (e.g. 1–4) for memory-constrained runners or workloads that
    /// make mostly serial requests to a single host.
    ///
    /// Ignored when an external client was supplied.
    #[must_use]
    pub(super) fn with_pool_max_idle_per_host(mut self, n: usize) -> Self {
        self.pool_max_idle_per_host = Some(n);
        self
    }

    /// Set how long an idle connection stays in the pool before being closed.
    ///
    /// Defaults to reqwest's built-in default (90s). Raise for long-idle
    /// interactive workloads to keep TLS sessions warm; lower for tight
    /// batch jobs to free file descriptors sooner.
    ///
    /// Ignored when an external client was supplied.
    #[must_use]
    pub(super) fn with_pool_idle_timeout(mut self, d: Duration) -> Self {
        self.pool_idle_timeout = Some(d);
        self
    }

    /// Set the OS-level TCP keepalive interval.
    ///
    /// Defaults to disabled (reqwest default). Enable (~60s) if connections
    /// are silently dropped after idle periods (e.g. behind aggressive NATs
    /// or load balancers).
    ///
    /// Ignored when an external client was supplied.
    #[must_use]
    pub(super) fn with_tcp_keepalive(mut self, d: Duration) -> Self {
        self.tcp_keepalive = Some(d);
        self
    }

    /// Control whether `TCP_NODELAY` is set on connections.
    ///
    /// Defaults to `true` — SSE streaming emits many small packets, and
    /// Nagle's algorithm coalesces them, adding latency per delta. Pass
    /// `false` to re-enable Nagle's algorithm (rarely needed). Ignored when
    /// an external client was supplied.
    #[must_use]
    pub(super) fn with_tcp_nodelay(mut self, enabled: bool) -> Self {
        self.tcp_nodelay = enabled;
        self
    }

    /// Build a `reqwest::Client` from this configuration.
    ///
    /// If an external client was supplied via
    /// [`with_http_client`](Self::with_http_client), it is returned verbatim. Otherwise
    /// a new client is constructed with a connect timeout, a read (idle-gap)
    /// timeout, pool knobs, and `tcp_nodelay(true)`. No total request
    /// timeout is set at this layer: generation-length budgets belong to the
    /// `StreamHandler` and the engine's turn timeout, and a total HTTP cap
    /// would abort healthy long streams.
    ///
    /// # Errors
    ///
    /// Returns [`ApiError`] if `reqwest::Client::builder().build()` fails.
    pub(super) fn build(self) -> Result<reqwest::Client, ApiError> {
        match self.http {
            Some(shared) => Ok(shared),
            None => reqwest::Client::builder()
                .read_timeout(self.timeout)
                .connect_timeout(self.connect_timeout)
                .tcp_nodelay(self.tcp_nodelay)
                .maybe_pool_max_idle_per_host(self.pool_max_idle_per_host)
                .maybe_pool_idle_timeout(self.pool_idle_timeout)
                .maybe_tcp_keepalive(self.tcp_keepalive)
                .build()
                .map_err(|e| ApiError::http(e.to_string())),
        }
    }
}

/// Extension trait for [`reqwest::ClientBuilder`] that accepts `Option<T>`
/// for pool and TCP knobs, no-opping when `None`.
///
/// Used internally by [`HttpClientConfig::build`].
#[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
trait ClientBuilderExt: Sized {
    fn maybe_pool_max_idle_per_host(self, val: Option<usize>) -> Self;
    fn maybe_pool_idle_timeout(self, val: Option<Duration>) -> Self;
    fn maybe_tcp_keepalive(self, val: Option<Duration>) -> Self;
}

#[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
impl ClientBuilderExt for reqwest::ClientBuilder {
    fn maybe_pool_max_idle_per_host(self, val: Option<usize>) -> Self {
        match val {
            Some(n) => self.pool_max_idle_per_host(n),
            None => self,
        }
    }

    fn maybe_pool_idle_timeout(self, val: Option<Duration>) -> Self {
        match val {
            Some(d) => self.pool_idle_timeout(Some(d)),
            None => self,
        }
    }

    fn maybe_tcp_keepalive(self, val: Option<Duration>) -> Self {
        match val {
            Some(d) => self.tcp_keepalive(d),
            None => self,
        }
    }
}

#[cfg(feature = "openai")]
pub mod openai;

#[cfg(feature = "anthropic")]
pub mod anthropic;

#[cfg(feature = "gemini")]
pub mod gemini;

#[cfg(feature = "grammar")]
pub mod grammar;

#[cfg(feature = "openai")]
pub use openai::OpenAiClient;

#[cfg(feature = "anthropic")]
pub use anthropic::AnthropicClient;

#[cfg(feature = "gemini")]
pub use gemini::GeminiClient;

#[cfg(feature = "grammar")]
pub use grammar::{JsonSchemaGrammar, ToolGrammarProvider};

#[cfg(feature = "ollama")]
const OLLAMA_BASE_URL: &str = "http://localhost:11434/v1";

#[cfg(feature = "deepseek")]
const DEEPSEEK_BASE_URL: &str = "https://api.deepseek.com/v1";

#[cfg(feature = "deepseek")]
const DEEPSEEK_DEFAULT_MODEL: &str = "deepseek-chat";

#[cfg(feature = "grok")]
const GROK_BASE_URL: &str = "https://api.x.ai/v1";

#[cfg(feature = "grok")]
const GROK_DEFAULT_MODEL: &str = "grok-beta";

#[cfg(feature = "bedrock")]
pub mod bedrock;

#[cfg(feature = "bedrock")]
pub use bedrock::BedrockClient;

#[cfg(feature = "zai")]
const ZAI_BASE_URL: &str = "https://api.z.ai/api/anthropic";

#[cfg(feature = "zai")]
const ZAI_DEFAULT_MODEL: &str = "glm-4.7";

#[cfg(feature = "moonshot")]
const MOONSHOT_BASE_URL: &str = "https://api.moonshot.ai/v1";

#[cfg(feature = "moonshot")]
const MOONSHOT_DEFAULT_MODEL: &str = "kimi-k2-0905-preview";

/// Read an environment variable, falling back to a second name, then a
/// default value.
///
/// Reduces boilerplate in the convenience constructors below where a
/// provider supports multiple env-var aliases (e.g. `XAI_API_KEY` /
/// `GROK_API_KEY`).
/// Read an environment variable or return a default.
#[cfg(any(
    feature = "ollama",
    feature = "deepseek",
    feature = "grok",
    feature = "zai",
    feature = "openai",
    feature = "azure",
    feature = "moonshot"
))]
fn env_or_default(name: &str, default: &str) -> String {
    std::env::var(name).unwrap_or_else(|_| default.into())
}

/// Read a primary env var, falling back to a secondary if unset.
///
/// Returns `None` only when neither variable is set; providers use
/// this for key aliases (e.g. `XAI_API_KEY` or `GROK_API_KEY`).
#[cfg(any(
    feature = "deepseek",
    feature = "grok",
    feature = "zai",
    feature = "azure",
    feature = "moonshot"
))]
fn env_or_fallback(primary: &str, fallback: &str) -> Option<String> {
    std::env::var(primary)
        .or_else(|_| std::env::var(fallback))
        .ok()
}

/// Look up a required API key from the environment.
///
/// # Errors
///
/// Returns [`ApiError::auth_invalid_key`] if neither environment variable is set.
#[cfg(any(
    feature = "deepseek",
    feature = "grok",
    feature = "zai",
    feature = "azure",
    feature = "moonshot"
))]
fn require_api_key(primary: &str, fallback: Option<&str>) -> Result<String, ApiError> {
    if let Some(fb) = fallback {
        if let Some(val) = env_or_fallback(primary, fb) {
            return Ok(val);
        }
    } else if let Ok(val) = std::env::var(primary) {
        return Ok(val);
    }
    Err(ApiError::auth_invalid_key(format!("{primary} not set")))
}

/// Separate inline `Role::System` messages from the rest of the history and
/// fold their text into a single system string.
///
/// Providers that reject an inline system role accept system content only as a
/// top-level request field. This helper pulls every system message out of
/// `messages`, concatenates their text parts (newline-separated), and merges
/// the result with an optional caller-supplied system prompt.
#[cfg(any(feature = "anthropic", feature = "gemini"))]
fn fold_system_messages<'a>(
    messages: &'a [crate::message::Message],
    system: Option<&str>,
) -> (Vec<&'a crate::message::Message>, Option<String>) {
    let mut folded = String::new();
    let non_system: Vec<&crate::message::Message> = messages
        .iter()
        .filter(|m| {
            if matches!(m.role, Role::System) {
                for part in &m.parts {
                    if let MessagePart::Text { text } = part {
                        if !folded.is_empty() {
                            folded.push('\n');
                        }
                        folded.push_str(text);
                    }
                }
                false
            } else {
                true
            }
        })
        .collect();
    let effective = match (system, folded.is_empty()) {
        (Some(s), false) => Some(format!("{s}\n{folded}")),
        (Some(s), true) => Some(s.to_string()),
        (None, false) => Some(folded),
        (None, true) => None,
    };
    (non_system, effective)
}

/// Ollama client — an [`OpenAiClient`] pointed at an Ollama server.
///
/// Works with both local Ollama (`http://localhost:11434/v1`, no API key
/// needed) and Ollama Cloud (`https://api.ollama.com/v1`, requires
/// `OLLAMA_API_KEY`).
///
/// Reads:
/// - `OLLAMA_API_KEY` — optional for local, required for cloud.
/// - `OLLAMA_BASE_URL` — optional, defaults to `http://localhost:11434/v1`.
///   Set to `https://api.ollama.com/v1` for Ollama Cloud.
///
/// # Example
///
/// ```rust,ignore
/// use loopctl::provider;
///
/// // Local:
/// let client = provider::ollama("llama3")?;
///
/// // Cloud (set OLLAMA_API_KEY and OLLAMA_BASE_URL):
/// let client = provider::ollama("llama3")?;
/// ```
///
/// # Errors
///
/// Returns [`ApiError`] if the HTTP client cannot be built.
#[cfg(feature = "ollama")]
pub fn ollama(model: &str) -> Result<OpenAiClient, ApiError> {
    let base = env_or_default("OLLAMA_BASE_URL", OLLAMA_BASE_URL);
    let api_key = env_or_default("OLLAMA_API_KEY", "ollama");

    OpenAiClient::builder()
        .with_api_key(api_key)
        .with_base_url(base)
        .with_model(model)
        .with_stream_usage(false)
        .build()
}

/// `DeepSeek` client — an [`OpenAiClient`] pointed at the `DeepSeek` API.
///
/// Reads `DEEPSEEK_API_KEY` (required) and optionally `DEEPSEEK_MODEL`
/// (defaults to `deepseek-chat`).
///
/// # Example
///
/// ```rust,ignore
/// use loopctl::provider;
///
/// let client = provider::deepseek()?;
/// ```
///
/// # Errors
///
/// Returns [`ApiError`] if no API key is found.
#[cfg(feature = "deepseek")]
pub fn deepseek() -> Result<OpenAiClient, ApiError> {
    let api_key = require_api_key("DEEPSEEK_API_KEY", None)?;
    let model = env_or_default("DEEPSEEK_MODEL", DEEPSEEK_DEFAULT_MODEL);

    OpenAiClient::builder()
        .with_api_key(api_key)
        .with_base_url(DEEPSEEK_BASE_URL)
        .with_model(model)
        .build()
}

/// Azure OpenAI client — an [`OpenAiClient`] pointed at the resource's
/// v1 API.
///
/// The v1 surface (`https://{resource}.openai.azure.com/openai/v1`)
/// speaks the OpenAI wire format with standard Bearer auth. The
/// resource name must be 2–64 characters of alphanumerics and hyphens,
/// starting and ending with an alphanumeric (Azure's account-name
/// rule). Reads `AZURE_OPENAI_API_KEY` (required) and
/// `AZURE_OPENAI_MODEL` (required — set it to the deployment name
/// configured in the Azure OpenAI resource; on the v1 surface the
/// model name identifies the deployment). The legacy deployment-URL
/// scheme is not supported.
///
/// # Example
///
/// ```rust,ignore
/// use loopctl::provider;
///
/// let client = provider::azure("my-resource")?;
/// ```
///
/// # Errors
///
/// Returns [`ApiError`] if no API key is found, the resource name is
/// invalid, or `AZURE_OPENAI_MODEL` is not set.
#[cfg(feature = "azure")]
pub fn azure(resource: impl AsRef<str>) -> Result<OpenAiClient, ApiError> {
    let resource = resource.as_ref();
    let chars_ok = resource
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '-');
    let edges_ok = resource
        .chars()
        .next()
        .is_some_and(|c| c.is_ascii_alphanumeric())
        && resource
            .chars()
            .next_back()
            .is_some_and(|c| c.is_ascii_alphanumeric());
    if !(2..=64).contains(&resource.chars().count()) || !chars_ok || !edges_ok {
        return Err(ApiError::config_validation(format!(
            "azure: resource name {resource:?} must be 2–64 characters of \
             alphanumerics and hyphens, starting and ending with an alphanumeric"
        )));
    }
    let api_key = require_api_key("AZURE_OPENAI_API_KEY", None)?;
    let deployment = std::env::var("AZURE_OPENAI_MODEL").map_err(|_| {
        ApiError::config(
            "azure: AZURE_OPENAI_MODEL is missing — set it to the deployment \
             name configured in your Azure OpenAI resource",
        )
    })?;
    let base = format!("https://{resource}.openai.azure.com/openai/v1");

    OpenAiClient::builder()
        .with_api_key(api_key)
        .with_base_url(base)
        .with_model(deployment)
        .build()
}

/// Moonshot AI (Kimi) client — an [`OpenAiClient`] pointed at the
/// Moonshot API.
///
/// Reads `MOONSHOT_API_KEY` (required) and optionally `MOONSHOT_MODEL`
/// (defaults to `kimi-k2-0905-preview`).
///
/// # Example
///
/// ```rust,ignore
/// use loopctl::provider;
///
/// let client = provider::moonshot()?;
/// ```
///
/// # Errors
///
/// Returns [`ApiError`] if no API key is found.
#[cfg(feature = "moonshot")]
pub fn moonshot() -> Result<OpenAiClient, ApiError> {
    let api_key = require_api_key("MOONSHOT_API_KEY", None)?;
    let model = env_or_default("MOONSHOT_MODEL", MOONSHOT_DEFAULT_MODEL);

    OpenAiClient::builder()
        .with_api_key(api_key)
        .with_base_url(MOONSHOT_BASE_URL)
        .with_model(model)
        .build()
}

/// `Grok` (xAI) client — an [`OpenAiClient`] pointed at the xAI API.
///
/// Reads `XAI_API_KEY` (or `GROK_API_KEY`) (required) and optionally
/// `GROK_MODEL` (defaults to `grok-beta`).
///
/// # Example
///
/// ```rust,ignore
/// use loopctl::provider;
///
/// let client = provider::grok()?;
/// ```
///
/// # Errors
///
/// Returns [`ApiError`] if no API key is found.
#[cfg(feature = "grok")]
pub fn grok() -> Result<OpenAiClient, ApiError> {
    let api_key = require_api_key("XAI_API_KEY", Some("GROK_API_KEY"))?;
    let model = std::env::var("XAI_MODEL")
        .or_else(|_| std::env::var("GROK_MODEL"))
        .unwrap_or_else(|_| GROK_DEFAULT_MODEL.into());

    OpenAiClient::builder()
        .with_api_key(api_key)
        .with_base_url(GROK_BASE_URL)
        .with_model(model)
        .build()
}

/// `Z.ai` (`ZhipuAI` / `BigModel`) client — an [`AnthropicClient`] pointed
/// at the `Z.ai` Anthropic-compatible API.
///
/// `Z.ai` exposes an Anthropic Messages-compatible API at
/// `https://api.z.ai/api/anthropic`.
///
/// Reads `ZAI_API_KEY` (or `ZHIPUAI_API_KEY`) (required) and optionally
/// `ZAI_MODEL` (defaults to `glm-4.7`).
///
/// # Example
///
/// ```rust,ignore
/// use loopctl::provider;
///
/// let client = provider::zai()?;
/// ```
///
/// # Errors
///
/// Returns [`ApiError`] if no API key is found.
#[cfg(feature = "zai")]
pub fn zai() -> Result<AnthropicClient, ApiError> {
    let api_key = require_api_key("ZAI_API_KEY", Some("ZHIPUAI_API_KEY"))?;
    let model = env_or_default("ZAI_MODEL", ZAI_DEFAULT_MODEL);

    AnthropicClient::builder()
        .with_api_key(api_key)
        .with_base_url(ZAI_BASE_URL)
        .with_model(model)
        .build()
}

/// Self-hosted client — an [`OpenAiClient`] pointed at any custom endpoint.
///
/// Use this for `vLLM`, `LM Studio`, `text-generation-inference`, or any
/// other server that exposes an OpenAI-compatible API.
///
/// For servers that require an API key, set it via the `OPENAI_API_KEY`
/// environment variable or use [`OpenAiClient::builder`] directly.
///
/// # Example
///
/// ```rust,ignore
/// use loopctl::provider;
///
/// let client = provider::self_hosted("http://localhost:8080/v1", "my-model")?;
/// ```
///
/// # Errors
///
/// Returns [`ApiError`] if the HTTP client cannot be built.
#[cfg(feature = "openai")]
pub fn self_hosted(base_url: &str, model: &str) -> Result<OpenAiClient, ApiError> {
    let api_key = env_or_default("OPENAI_API_KEY", "self-hosted");

    OpenAiClient::builder()
        .with_api_key(api_key)
        .with_base_url(base_url)
        .with_model(model)
        .build()
}

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

    #[cfg(feature = "testing")]
    use crate::testing::EnvGuard;

    #[cfg(all(feature = "azure", feature = "testing"))]
    #[test]
    fn azure_rejects_invalid_resource_names() {
        let too_long = "r".repeat(65);
        let bads = [
            "",
            "a",
            "under_score",
            "sp ace",
            "res.name",
            "-lead",
            "trail-",
            too_long.as_str(),
        ];
        for bad in bads {
            let Err(err) = azure(bad) else {
                panic!("validation runs before any env access: {bad:?} accepted");
            };
            assert!(err.to_string().contains("resource name"), "{bad:?}: {err}");
            assert_eq!(
                err.code(),
                crate::api::error::ErrorCode::ConfigValidationError,
                "{bad:?}: {err}"
            );
        }

        let env = EnvGuard::acquire(&["AZURE_OPENAI_API_KEY", "AZURE_OPENAI_MODEL"]);
        env.remove("AZURE_OPENAI_API_KEY");
        env.remove("AZURE_OPENAI_MODEL");
        for good in ["ab", "my-resource", &"r".repeat(64)] {
            let Err(err) = azure(good) else {
                panic!("valid name rejected: {good:?}")
            };
            assert!(
                !err.to_string().contains("resource name"),
                "{good:?} is valid; the failure must be env-related: {err}"
            );
        }
    }

    #[cfg(all(feature = "azure", feature = "testing"))]
    #[test]
    fn azure_builds_the_v1_client_from_env() {
        use crate::api::ApiClient as _;

        let env = EnvGuard::acquire(&["AZURE_OPENAI_API_KEY", "AZURE_OPENAI_MODEL"]);
        env.set("AZURE_OPENAI_API_KEY", "key");
        env.set("AZURE_OPENAI_MODEL", "my-deployment");
        let client = azure("my-resource").unwrap();
        assert_eq!(
            client.base_url(),
            "https://my-resource.openai.azure.com/openai/v1"
        );
        assert_eq!(client.model(), "my-deployment");
    }

    #[cfg(all(feature = "azure", feature = "testing"))]
    #[test]
    fn azure_requires_key_and_model() {
        let env = EnvGuard::acquire(&["AZURE_OPENAI_API_KEY", "AZURE_OPENAI_MODEL"]);
        env.set("AZURE_OPENAI_API_KEY", "key");
        env.remove("AZURE_OPENAI_MODEL");
        let Err(err) = azure("res") else {
            panic!("missing AZURE_OPENAI_MODEL must fail the build");
        };
        assert!(err.to_string().contains("AZURE_OPENAI_MODEL"), "{err}");
        assert_eq!(
            err.code(),
            crate::api::error::ErrorCode::ConfigMissing,
            "{err}"
        );

        env.remove("AZURE_OPENAI_API_KEY");
        let Err(err) = azure("res") else {
            panic!("missing AZURE_OPENAI_API_KEY must fail the build");
        };
        assert!(err.to_string().contains("AZURE_OPENAI_API_KEY"), "{err}");
    }

    #[cfg(all(feature = "moonshot", feature = "testing"))]
    #[test]
    fn moonshot_builds_client_and_defaults_model() {
        use crate::api::ApiClient as _;

        let env = EnvGuard::acquire(&["MOONSHOT_API_KEY", "MOONSHOT_MODEL"]);
        env.set("MOONSHOT_API_KEY", "key");
        env.remove("MOONSHOT_MODEL");
        let client = moonshot().unwrap();
        assert_eq!(client.base_url(), "https://api.moonshot.ai/v1");
        assert_eq!(client.model(), MOONSHOT_DEFAULT_MODEL);

        env.set("MOONSHOT_MODEL", "custom");
        assert_eq!(moonshot().unwrap().model(), "custom");
    }

    #[cfg(all(feature = "moonshot", feature = "testing"))]
    #[test]
    fn moonshot_requires_key() {
        let env = EnvGuard::acquire(&["MOONSHOT_API_KEY"]);
        env.remove("MOONSHOT_API_KEY");
        assert!(moonshot().is_err());
    }

    #[cfg(any(
        feature = "ollama",
        feature = "deepseek",
        feature = "grok",
        feature = "zai",
        feature = "openai"
    ))]
    #[cfg(all(
        any(feature = "deepseek", feature = "grok", feature = "zai"),
        feature = "testing"
    ))]
    #[test]
    fn env_or_fallback_primary_set() {
        let env = EnvGuard::acquire(&["LOOPCTL_TEST_PRIMARY", "LOOPCTL_TEST_FALLBACK"]);
        env.set("LOOPCTL_TEST_PRIMARY", "primary-val");
        env.remove("LOOPCTL_TEST_FALLBACK");
        assert_eq!(
            env_or_fallback("LOOPCTL_TEST_PRIMARY", "LOOPCTL_TEST_FALLBACK"),
            Some("primary-val".into())
        );
    }

    #[cfg(all(
        any(feature = "deepseek", feature = "grok", feature = "zai"),
        feature = "testing"
    ))]
    #[test]
    fn env_or_fallback_fallback_used_when_primary_missing() {
        let env = EnvGuard::acquire(&["LOOPCTL_TEST_PRIMARY2", "LOOPCTL_TEST_FALLBACK2"]);
        env.remove("LOOPCTL_TEST_PRIMARY2");
        env.set("LOOPCTL_TEST_FALLBACK2", "fallback-val");
        assert_eq!(
            env_or_fallback("LOOPCTL_TEST_PRIMARY2", "LOOPCTL_TEST_FALLBACK2"),
            Some("fallback-val".into())
        );
    }

    #[cfg(all(
        any(feature = "deepseek", feature = "grok", feature = "zai"),
        feature = "testing"
    ))]
    #[test]
    fn env_or_fallback_none_when_both_missing() {
        let env = EnvGuard::acquire(&["LOOPCTL_TEST_NEITHER_A", "LOOPCTL_TEST_NEITHER_B"]);
        env.remove("LOOPCTL_TEST_NEITHER_A");
        env.remove("LOOPCTL_TEST_NEITHER_B");
        assert_eq!(
            env_or_fallback("LOOPCTL_TEST_NEITHER_A", "LOOPCTL_TEST_NEITHER_B"),
            None
        );
    }

    #[cfg(all(
        any(
            feature = "ollama",
            feature = "deepseek",
            feature = "grok",
            feature = "zai",
            feature = "openai"
        ),
        feature = "testing"
    ))]
    #[test]
    fn env_or_default_uses_env_when_set() {
        let env = EnvGuard::acquire(&["LOOPCTL_TEST_DEFAULT"]);
        env.set("LOOPCTL_TEST_DEFAULT", "from-env");
        assert_eq!(
            env_or_default("LOOPCTL_TEST_DEFAULT", "fallback"),
            "from-env"
        );
    }

    #[cfg(all(
        any(
            feature = "ollama",
            feature = "deepseek",
            feature = "grok",
            feature = "zai",
            feature = "openai"
        ),
        feature = "testing"
    ))]
    #[test]
    fn env_or_default_uses_default_when_unset() {
        let env = EnvGuard::acquire(&["LOOPCTL_TEST_DEFAULT2"]);
        env.remove("LOOPCTL_TEST_DEFAULT2");
        assert_eq!(
            env_or_default("LOOPCTL_TEST_DEFAULT2", "fallback"),
            "fallback"
        );
    }

    #[cfg(all(
        any(feature = "deepseek", feature = "grok", feature = "zai"),
        feature = "testing"
    ))]
    #[test]
    fn require_api_key_primary_set() {
        let env = EnvGuard::acquire(&["LOOPCTL_TEST_KEY_PRIMARY", "LOOPCTL_TEST_KEY_FALLBACK"]);
        env.set("LOOPCTL_TEST_KEY_PRIMARY", "secret");
        env.remove("LOOPCTL_TEST_KEY_FALLBACK");
        let key = require_api_key(
            "LOOPCTL_TEST_KEY_PRIMARY",
            Some("LOOPCTL_TEST_KEY_FALLBACK"),
        )
        .unwrap();
        assert_eq!(key, "secret");
    }

    #[cfg(all(
        any(feature = "deepseek", feature = "grok", feature = "zai"),
        feature = "testing"
    ))]
    #[test]
    fn require_api_key_fallback_used() {
        let env = EnvGuard::acquire(&["LOOPCTL_TEST_KEY_PRIMARY2", "LOOPCTL_TEST_KEY_FALLBACK2"]);
        env.remove("LOOPCTL_TEST_KEY_PRIMARY2");
        env.set("LOOPCTL_TEST_KEY_FALLBACK2", "fallback-secret");
        let key = require_api_key(
            "LOOPCTL_TEST_KEY_PRIMARY2",
            Some("LOOPCTL_TEST_KEY_FALLBACK2"),
        )
        .unwrap();
        assert_eq!(key, "fallback-secret");
    }

    #[cfg(all(
        any(feature = "deepseek", feature = "grok", feature = "zai"),
        feature = "testing"
    ))]
    #[test]
    fn require_api_key_no_fallback_set() {
        let env = EnvGuard::acquire(&["LOOPCTL_TEST_KEY_ONLY"]);
        env.set("LOOPCTL_TEST_KEY_ONLY", "only-val");
        let key = require_api_key("LOOPCTL_TEST_KEY_ONLY", None).unwrap();
        assert_eq!(key, "only-val");
    }

    #[cfg(all(
        any(feature = "deepseek", feature = "grok", feature = "zai"),
        feature = "testing"
    ))]
    #[test]
    fn require_api_key_errors_when_missing() {
        let env = EnvGuard::acquire(&["LOOPCTL_TEST_MISSING_KEY"]);
        env.remove("LOOPCTL_TEST_MISSING_KEY");
        let err = require_api_key("LOOPCTL_TEST_MISSING_KEY", None).unwrap_err();
        assert!(err.to_string().contains("LOOPCTL_TEST_MISSING_KEY"));
    }

    #[cfg(all(
        any(feature = "deepseek", feature = "grok", feature = "zai"),
        feature = "testing"
    ))]
    #[test]
    fn require_api_key_errors_when_both_missing() {
        let env = EnvGuard::acquire(&["LOOPCTL_TEST_MISSING_A", "LOOPCTL_TEST_MISSING_B"]);
        env.remove("LOOPCTL_TEST_MISSING_A");
        env.remove("LOOPCTL_TEST_MISSING_B");
        let err =
            require_api_key("LOOPCTL_TEST_MISSING_A", Some("LOOPCTL_TEST_MISSING_B")).unwrap_err();
        assert!(err.to_string().contains("LOOPCTL_TEST_MISSING_A"));
    }

    #[cfg(all(feature = "ollama", feature = "testing"))]
    #[test]
    fn ollama_client_builds_with_defaults() {
        use crate::api::ApiClient;
        let env = EnvGuard::acquire(&["OLLAMA_BASE_URL"]);
        env.remove("OLLAMA_BASE_URL");
        let client = ollama("llama3").unwrap();
        assert_eq!(client.model(), "llama3");
    }

    #[cfg(all(feature = "ollama", feature = "testing"))]
    #[test]
    fn ollama_client_respects_base_url_env() {
        use crate::api::ApiClient;
        let env = EnvGuard::acquire(&["OLLAMA_BASE_URL"]);
        env.set("OLLAMA_BASE_URL", "http://my-host:1234/v1");
        let client = ollama("test-model").unwrap();
        assert_eq!(client.model(), "test-model");
    }

    #[cfg(all(feature = "ollama", feature = "testing"))]
    #[test]
    fn ollama_client_uses_api_key_when_set() {
        use crate::api::ApiClient;
        let env = EnvGuard::acquire(&["OLLAMA_BASE_URL", "OLLAMA_API_KEY"]);
        env.remove("OLLAMA_BASE_URL");
        env.set("OLLAMA_API_KEY", "my-cloud-key");
        // Should build successfully with the cloud key — no network call.
        let client = ollama("llama3").unwrap();
        assert_eq!(client.model(), "llama3");
    }

    #[cfg(all(feature = "ollama", feature = "testing"))]
    #[test]
    fn ollama_client_defaults_to_local_without_key() {
        use crate::api::ApiClient;
        let env = EnvGuard::acquire(&["OLLAMA_BASE_URL", "OLLAMA_API_KEY"]);
        env.remove("OLLAMA_BASE_URL");
        env.remove("OLLAMA_API_KEY");
        // Should still build — local Ollama doesn't need a real key.
        let client = ollama("llama3").unwrap();
        assert_eq!(client.model(), "llama3");
    }

    #[cfg(feature = "openai")]
    #[test]
    fn self_hosted_client_builds() {
        use crate::api::ApiClient;
        let client = self_hosted("http://localhost:8080/v1", "my-model").unwrap();
        assert_eq!(client.model(), "my-model");
    }

    /// Build a `Role::System` message carrying the given text parts.
    #[cfg(any(feature = "anthropic", feature = "gemini"))]
    fn sys_msg(texts: &[&str]) -> crate::message::Message {
        use crate::message::{MessagePart, Role};
        let parts: Vec<MessagePart> = texts.iter().map(|t| MessagePart::text(*t)).collect();
        crate::message::Message::new(Role::System, parts)
    }

    #[cfg(any(feature = "anthropic", feature = "gemini"))]
    #[test]
    fn fold_system_no_system_messages_no_caller_returns_none() {
        let msgs = [crate::message::Message::user("hi")];
        let (non_system, system) = fold_system_messages(&msgs, None);
        assert_eq!(non_system.len(), 1);
        assert!(system.is_none(), "no system content → None");
    }

    #[cfg(any(feature = "anthropic", feature = "gemini"))]
    #[test]
    fn fold_system_caller_only_passes_through() {
        let msgs = [crate::message::Message::user("hi")];
        let (non_system, system) = fold_system_messages(&msgs, Some("be brief"));
        assert_eq!(non_system.len(), 1);
        assert_eq!(system.as_deref(), Some("be brief"));
    }

    #[cfg(any(feature = "anthropic", feature = "gemini"))]
    #[test]
    fn fold_system_single_system_message_removed_and_folded() {
        let msgs = [
            crate::message::Message::user("hello"),
            sys_msg(&["stay on task"]),
            crate::message::Message::assistant("working"),
        ];
        let (non_system, system) = fold_system_messages(&msgs, None);
        assert_eq!(non_system.len(), 2, "system message filtered out");
        assert_eq!(system.as_deref(), Some("stay on task"));
    }

    #[cfg(any(feature = "anthropic", feature = "gemini"))]
    #[test]
    fn fold_system_caller_prompt_prepended_to_folded() {
        let msgs = [crate::message::Message::user("hi"), sys_msg(&["reminder"])];
        let (_non_system, system) = fold_system_messages(&msgs, Some("be brief"));
        let system = system.expect("merged system is Some");
        assert!(
            system.starts_with("be brief"),
            "caller prompt first: got {system:?}"
        );
        assert!(
            system.contains("reminder"),
            "folded text appended: got {system:?}"
        );
        assert!(
            system.contains('\n'),
            "caller and folded are newline-separated: got {system:?}"
        );
    }

    #[cfg(any(feature = "anthropic", feature = "gemini"))]
    #[test]
    fn fold_system_multiple_system_messages_joined_with_newlines() {
        let msgs = [
            sys_msg(&["first reminder"]),
            crate::message::Message::user("hi"),
            sys_msg(&["second reminder"]),
        ];
        let (non_system, system) = fold_system_messages(&msgs, None);
        assert_eq!(non_system.len(), 1, "both system messages filtered");
        let system = system.expect("folded text is Some");
        assert_eq!(system, "first reminder\nsecond reminder");
    }

    #[cfg(any(feature = "anthropic", feature = "gemini"))]
    #[test]
    fn fold_system_only_text_parts_are_folded() {
        // A System message carrying a tool-call part (unusual, but defensive):
        // only the text parts contribute to the fold.
        use crate::message::{MessagePart, Role};
        let system_msg = crate::message::Message::new(
            Role::System,
            vec![
                MessagePart::text("keep this"),
                MessagePart::tool_call("id", "some_tool", serde_json::json!({})),
            ],
        );
        let msgs = [crate::message::Message::user("hi"), system_msg];
        let (_non_system, system) = fold_system_messages(&msgs, None);
        assert_eq!(system.as_deref(), Some("keep this"));
    }

    #[cfg(any(feature = "anthropic", feature = "gemini"))]
    #[test]
    fn fold_system_preserves_relative_order_of_non_system_messages() {
        let msgs = [
            crate::message::Message::user("first"),
            sys_msg(&["mid reminder"]),
            crate::message::Message::assistant("second"),
            crate::message::Message::user("third"),
        ];
        let (non_system, _system) = fold_system_messages(&msgs, None);
        let texts: Vec<&str> = non_system
            .iter()
            .flat_map(|m| {
                m.parts.iter().filter_map(|p| match p {
                    crate::message::MessagePart::Text { text } => Some(text.as_str()),
                    _ => None,
                })
            })
            .collect();
        assert_eq!(texts, vec!["first", "second", "third"]);
    }

    #[cfg(any(feature = "anthropic", feature = "gemini"))]
    #[test]
    fn fold_system_empty_text_part_contributes_nothing() {
        // A System message whose text is empty: folded string stays empty, so
        // with no caller prompt the result is None.
        let msgs = [sys_msg(&[""])];
        let (non_system, system) = fold_system_messages(&msgs, None);
        assert!(non_system.is_empty(), "system message still filtered");
        assert!(
            system.is_none(),
            "empty folded text and no caller → None (got {system:?})"
        );
    }

    #[cfg(any(feature = "anthropic", feature = "gemini"))]
    #[test]
    fn fold_system_multiple_text_parts_in_one_message_joined() {
        let msgs = [sys_msg(&["part one", "part two"])];
        let (_non_system, system) = fold_system_messages(&msgs, None);
        assert_eq!(system.as_deref(), Some("part one\npart two"));
    }

    #[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
    #[test]
    fn default_builds_clean() {
        assert!(HttpClientConfig::default().build().is_ok());
    }

    #[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
    #[test]
    fn accepts_injected_http_client() {
        let shared = reqwest::Client::new();
        let config = HttpClientConfig::default().with_http_client(shared);
        assert!(config.build().is_ok());
    }

    #[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
    #[test]
    fn injected_client_supersedes_timeouts() {
        let shared = reqwest::Client::builder()
            .timeout(Duration::from_secs(1))
            .build()
            .unwrap();
        let config = HttpClientConfig::default()
            .with_http_client(shared)
            .with_timeout(Duration::from_secs(99));
        assert!(config.build().is_ok());
    }

    #[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
    #[test]
    fn pool_knobs_build_clean() {
        let config = HttpClientConfig::default()
            .with_pool_max_idle_per_host(4)
            .with_pool_idle_timeout(Duration::from_secs(30))
            .with_tcp_keepalive(Duration::from_secs(90));
        assert!(config.build().is_ok());
    }

    #[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
    #[test]
    fn tcp_nodelay_default_is_true() {
        assert!(HttpClientConfig::default().tcp_nodelay);
    }

    #[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
    #[test]
    fn with_tcp_nodelay_can_disable() {
        let config = HttpClientConfig::default().with_tcp_nodelay(false);
        assert!(!config.tcp_nodelay);
    }

    #[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
    #[test]
    fn injected_client_ignores_pool_knobs() {
        let shared = reqwest::Client::new();
        let config = HttpClientConfig::default()
            .with_http_client(shared)
            .with_pool_max_idle_per_host(4)
            .with_pool_idle_timeout(Duration::from_secs(30));
        assert!(config.build().is_ok());
    }

    #[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
    async fn serve_once(
        status: u16,
        headers: String,
        body: Vec<u8>,
    ) -> (String, tokio::task::JoinHandle<()>) {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let handle = tokio::spawn(async move {
            let (mut sock, _) = listener.accept().await.unwrap();
            let mut buf = [0u8; 1024];
            drop(sock.read(&mut buf).await);
            let extra = if headers.is_empty() {
                String::new()
            } else {
                format!("{headers}\r\n")
            };
            let head = format!(
                "HTTP/1.1 {status} OK\r\nContent-Length: {clen}\r\n{extra}\r\n",
                clen = body.len(),
            );
            drop(sock.write_all(head.as_bytes()).await);
            drop(sock.write_all(&body).await);
            drop(sock.flush().await);
        });
        (format!("http://{addr}"), handle)
    }

    #[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
    async fn get_response(url: &str) -> reqwest::Response {
        reqwest::Client::new()
            .get(url)
            .send()
            .await
            .expect("request to test server must succeed")
    }

    #[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
    #[tokio::test]
    async fn read_bounded_body_accepts_under_limit() {
        let body = b"{\"ok\":true}".to_vec();
        let (url, handle) = serve_once(200, String::new(), body.clone()).await;
        let resp = get_response(&url).await;
        let bytes = read_bounded_body(resp).await.expect("small body must pass");
        assert_eq!(bytes.as_ref(), body.as_slice());
        handle.await.unwrap();
    }

    #[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
    #[tokio::test]
    async fn read_error_body_caps_chunked_oversized_response() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let written = std::sync::Arc::new(AtomicUsize::new(0));
        let counter = written.clone();
        let server = tokio::spawn(async move {
            let (mut sock, _) = listener.accept().await.unwrap();
            let mut buf = [0u8; 1024];
            drop(sock.read(&mut buf).await);
            let head = "HTTP/1.1 500 Internal Server Error\r\nConnection: close\r\n\r\n";
            drop(sock.write_all(head.as_bytes()).await);
            let chunk = vec![b'x'; 16384];
            for _ in 0..16 {
                // Yield between chunks so the client task gets scheduled and
                // its early abort can interrupt the transfer (see the
                // Content-Length variant above for the buffering rationale).
                tokio::task::yield_now().await;
                if sock.write_all(&chunk).await.is_err() {
                    break;
                }
                counter.fetch_add(chunk.len(), Ordering::SeqCst);
                drop(sock.flush().await);
            }
        });

        let resp = get_response(&format!("http://{addr}")).await;
        let text = read_error_body(resp).await;
        server.await.unwrap();
        assert_eq!(
            text.len(),
            MAX_ERROR_BODY,
            "a chunked oversized error body must retain exactly the capped prefix"
        );
        assert!(
            text.chars().all(|c| c == 'x'),
            "the retained prefix must be the body's leading bytes"
        );
        let total = written.load(Ordering::SeqCst);
        assert!(
            total < 16 * 16384,
            "the read must abort the transfer short of the full 256 KiB body; the server wrote {total} bytes"
        );
    }

    #[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
    #[tokio::test]
    async fn read_bounded_body_rejects_oversized_content_length() {
        let body = vec![b'x'; MAX_RESPONSE_BODY + 1];
        let (url, handle) = serve_once(200, String::new(), body).await;
        let resp = get_response(&url).await;
        let err = read_bounded_body(resp)
            .await
            .expect_err("oversized body must reject");
        assert!(
            err.to_string().contains("too large"),
            "expected a too-large error, got: {err}"
        );
        handle.await.unwrap();
    }

    #[cfg(feature = "openai")]
    #[tokio::test]
    async fn error_body_read_is_bounded_by_the_cap() {
        use crate::api::ApiClient as _;
        use std::sync::atomic::{AtomicUsize, Ordering};
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let written = std::sync::Arc::new(AtomicUsize::new(0));
        let counter = written.clone();
        let server = tokio::spawn(async move {
            let (mut sock, _) = listener.accept().await.unwrap();
            let mut buf = [0u8; 1024];
            drop(sock.read(&mut buf).await);
            let head = "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 2097152\r\nConnection: close\r\n\r\n";
            drop(sock.write_all(head.as_bytes()).await);
            let chunk = vec![b'x'; 8192];
            for _ in 0..256 {
                // Yield between chunks: on kernels with multi-MiB socket
                // buffers the burst of non-blocking writes below never
                // returns Pending, so without this the server would finish
                // buffering the whole body before the client task ever runs
                // and its early abort could not interrupt the transfer.
                tokio::task::yield_now().await;
                if sock.write_all(&chunk).await.is_err() {
                    break;
                }
                counter.fetch_add(chunk.len(), Ordering::SeqCst);
                drop(sock.flush().await);
            }
        });

        let client = crate::provider::OpenAiClient::builder()
            .with_api_key("k")
            .with_base_url(format!("http://{addr}"))
            .build()
            .expect("client builds");
        let result = client
            .create_message(&crate::api::StreamRequest::new(vec![]))
            .await;
        assert!(result.is_err(), "a 500 response must surface an error");
        server.await.unwrap();
        let total = written.load(Ordering::SeqCst);
        assert!(
            total < 2 * 1024 * 1024,
            "the error-body cap (8 KiB) must stop the read short of the declared 2 MiB body; the server wrote {total} bytes"
        );
    }

    #[cfg(any(feature = "openai", feature = "anthropic", feature = "gemini"))]
    #[test]
    fn sse_data_payload_accepts_spaced_and_compact_forms() {
        assert_eq!(sse_data_payload("data: {\"a\":1}"), Some("{\"a\":1}"));
        assert_eq!(sse_data_payload("data:{\"a\":1}"), Some("{\"a\":1}"));
        assert_eq!(
            sse_data_payload("data:  two spaces"),
            Some(" two spaces"),
            "only the first space after the colon is framing; a second space is payload"
        );
        assert_eq!(
            sse_data_payload("data:"),
            Some(""),
            "a bare data field carries an empty payload, not a skipped line"
        );
        assert_eq!(sse_data_payload("event: message_start"), None);
        assert_eq!(sse_data_payload(": keep-alive comment"), None);
        assert_eq!(
            sse_data_payload("DATA: {\"a\":1}"),
            None,
            "SSE field names are case-sensitive; only lowercase data fields carry payloads"
        );
    }

    #[cfg(feature = "anthropic")]
    #[test]
    fn sse_event_type_accepts_spaced_and_compact_forms() {
        assert_eq!(
            sse_event_type("event: message_start"),
            Some("message_start")
        );
        assert_eq!(sse_event_type("event:message_start"), Some("message_start"));
        assert_eq!(
            sse_event_type("event:  two spaces"),
            Some(" two spaces"),
            "only the first space after the colon is framing; a second space is part of the name"
        );
        assert_eq!(
            sse_event_type("event:"),
            Some(""),
            "a bare event field carries an empty name, not a skipped line"
        );
        assert_eq!(sse_event_type("data: {}"), None);
        assert_eq!(
            sse_event_type("EVENT: message_start"),
            None,
            "SSE field names are case-sensitive; only lowercase event fields name events"
        );
    }

    #[cfg(all(feature = "zai", feature = "testing"))]
    #[test]
    fn zai_default_model_matches_the_documented_default() {
        use crate::api::ApiClient;

        let env = EnvGuard::acquire(&["ZAI_API_KEY", "ZAI_MODEL"]);
        env.set("ZAI_API_KEY", "test-key");
        env.remove("ZAI_MODEL");
        let client = zai().expect("client builds with the test key");
        assert_eq!(
            client.model(),
            "glm-4.7",
            "the deliberate default is glm-4.7; the doc was corrected to match"
        );
    }
}