cpa-exec 0.4.3

Part of cliproxy: upstream provider executors
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
//! Codex live calls (internal/client/codex/live): the WebRTC SDP bootstrap request to the
//! ChatGPT realtime calls endpoint, its sideband and standard Realtime WebSockets, and
//! hangup.
//!
//! Request shaping ports live.go, client_secret.go and websocket.go byte for byte,
//! including Go's error texts; expected values come from
//! tests/fixtures/codex_live/vectors.json, generated by running the Go functions. Routes,
//! client secrets and call state live in cpa-server's `realtime` module.

use std::collections::BTreeMap;
use std::time::Duration;

use bytes::Bytes;
use cpa_common::gostr::{GoStr, quote as go_quote, trim_space};
use cpa_common::json::{self as gj, GoValue, Kind};
use cpa_core::config::Config;
use cpa_core::credential::Credential;
use cpa_core::exec::{CaptureEvent, CaptureSink, ExecError, UpstreamRequest};
use http::HeaderMap;

use crate::codex::CodexExecutor;
use crate::codex_request::{self as request, View};
use crate::meta_wire::{check_valid, fold, kind_name};
use crate::openai_compat_multipart::{MediaType, parse_media_type};
use crate::proxy::{self, GoHeaders, Route, Upstream, canonical_header};

/// `upstreamCallURL`.
pub const CALL_URL: &str = "https://chatgpt.com/backend-api/codex/realtime/calls?intent=quicksilver&architecture=avas";
/// `defaultSidebandAPIBaseURL`: sideband, standard Realtime WebSocket and hangup.
pub const API_BASE: &str = "wss://api.openai.com/v1";
/// `defaultLiveModel`.
pub const DEFAULT_MODEL: &str = "gpt-live-1-codex";
/// `defaultStandardRealtimeModel`.
pub const DEFAULT_STANDARD_MODEL: &str = "gpt-realtime";
/// `maxBodySize`: call requests, upstream responses and rejected handshakes.
pub const MAX_BODY: usize = 16 << 20;
/// Largest relayed WebSocket message.
// ponytail: gorilla streams messages of any size; tungstenite buffers whole messages, so
// 16 MiB (Go's body cap) bounds per-connection memory. Raise it if a client needs more.
pub const MAX_WS_MESSAGE: usize = MAX_BODY;
/// gorilla keeps at most 1 KiB of a rejected handshake's body.
const MAX_HANDSHAKE_BODY: usize = 1024;
// ponytail: Go's sideband dialer has no handshake timeout (request cancellation only);
// a fixed bound keeps a stalled upstream from holding the call claim forever.
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(30);

/// `liveProtocolHeaders`: client headers forwarded to every live upstream request.
pub const PROTOCOL_HEADERS: [&str; 9] = [
    "OpenAI-Alpha",
    "X-Session-Id",
    "Session-Id",
    "Thread-Id",
    "Originator",
    "OpenAI-Safety-Identifier",
    "OpenAI-Organization",
    "OpenAI-Project",
    "X-Oai-Attestation",
];

/// Where live requests go. Tests point both at local mocks.
#[derive(Debug, Clone)]
pub struct Endpoints {
    pub call_url: String,
    /// WebSocket base (`ws`/`wss`); hangup uses its HTTP form.
    pub api_base: String,
}

impl Default for Endpoints {
    fn default() -> Self {
        Self {
            call_url: CALL_URL.into(),
            api_base: API_BASE.into(),
        }
    }
}

/// A call request on its way upstream.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Call {
    pub body: Vec<u8>,
    pub content_type: String,
    pub model: String,
}

/// Why a call request could not be shaped.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ShapeError {
    /// HTTP 400 with Go's message.
    Invalid(String),
    /// Go assigns into a nil map (a `null` request or session); gin's recovery answers
    /// 500 with no body.
    NilMap,
}

fn invalid(message: impl Into<String>) -> ShapeError {
    ShapeError::Invalid(message.into())
}

/// `strings.TrimSpace` on a Go string.
fn trim(s: &str) -> &str {
    std::str::from_utf8(trim_space(s.as_bytes())).unwrap_or(s)
}

/// The media type when `mime.ParseMediaType` succeeds.
fn media(content_type: &str) -> Option<String> {
    match parse_media_type(content_type) {
        MediaType::Ok(media, _) => Some(media),
        _ => None,
    }
}

fn is_sdp(media: Option<&str>) -> bool {
    matches!(media, Some("application/sdp" | "text/plain"))
}

/// `prepareCallRequest`: multipart SDP + session becomes `{"sdp","session"}` JSON; any
/// other body passes through with its model (default `gpt-live-1-codex`).
pub fn prepare(body: &[u8], content_type: &str) -> Result<Call, ShapeError> {
    if let MediaType::Ok(media, params) = parse_media_type(content_type)
        && media == "multipart/form-data"
    {
        let boundary = params.get("boundary").map(|b| trim(b)).unwrap_or_default();
        return multipart_call(body, boundary);
    }
    let mut model = model_from_json(body);
    if model.is_empty() {
        model = DEFAULT_MODEL.into();
    }
    let content_type = if trim(content_type).is_empty() {
        "application/json"
    } else {
        content_type
    };
    Ok(Call {
        body: body.to_vec(),
        content_type: content_type.into(),
        model,
    })
}

/// `applyClientSecretCallSession`: the ephemeral key's session replaces the request's.
pub fn apply_client_secret(call: Call, session: &[u8]) -> Result<Call, ShapeError> {
    if session.is_empty() {
        return Ok(call);
    }
    let media = media(&call.content_type);
    let body = if is_sdp(media.as_deref()) {
        encode_call(&call.body, Some(session))
    } else if media.as_deref() == Some("application/json") {
        let mut payload = unmarshal_raw_map(&call.body)
            .map_err(|e| invalid(format!("failed to decode Realtime call request: {e}")))?
            .ok_or(ShapeError::NilMap)?;
        payload.insert("session".into(), session.to_vec());
        marshal_raw_map(&payload)
    } else {
        return Err(invalid("Realtime client secrets require an SDP or JSON call request"));
    };
    Ok(Call {
        body,
        content_type: "application/json".into(),
        model: model_from_json(session),
    })
}

/// `rewriteCallRequestModel`: the upstream model replaces `session.model`, or a
/// top-level `model` when there is no session. Returns the upstream model.
pub fn rewrite_model(call: Call) -> Result<Call, ShapeError> {
    let upstream = codex_model(&call.model);
    let unchanged = |call: Call| Call {
        model: upstream.clone(),
        ..call
    };
    if media(&call.content_type).as_deref() != Some("application/json") || trim_space(&call.body).is_empty() {
        return Ok(unchanged(call));
    }
    let Some(mut payload) =
        unmarshal_raw_map(&call.body).map_err(|e| invalid(format!("failed to decode Realtime call request: {e}")))?
    else {
        return Ok(unchanged(call));
    };
    let encoded_model = gj::quote(&upstream);
    if let Some(raw) = payload.get("session") {
        let mut session = unmarshal_raw_map(raw)
            .map_err(|e| invalid(format!("failed to decode Realtime session: {e}")))?
            .ok_or(ShapeError::NilMap)?;
        session.insert("model".into(), encoded_model);
        payload.insert("session".into(), marshal_raw_map(&session));
    } else if payload.contains_key("model") {
        payload.insert("model".into(), encoded_model);
    } else {
        return Ok(unchanged(call));
    }
    Ok(Call {
        body: marshal_raw_map(&payload),
        content_type: call.content_type,
        model: upstream,
    })
}

/// `callRequestSDP`: the client's offer, for the media relay.
pub fn request_sdp(body: &[u8], content_type: &str) -> Result<String, String> {
    let media = media(content_type);
    if is_sdp(media.as_deref()) {
        if trim_space(body).is_empty() {
            return Err("Codex live call request requires an SDP offer".into());
        }
        return Ok(String::from_utf8_lossy(body).into_owned());
    }
    if media.as_deref() != Some("application/json") {
        return Err("Codex live media relay requires an SDP or JSON call request".into());
    }
    let sdp = unmarshal_sdp(body).map_err(|e| format!("failed to decode Codex live call request: {e}"))?;
    if trim(&sdp).is_empty() {
        return Err("Codex live call request requires an SDP offer".into());
    }
    Ok(sdp)
}

/// `replaceCallRequestSDP`: the relay's own offer replaces the client's.
pub fn replace_sdp(body: &[u8], content_type: &str, sdp: &str) -> Result<(Vec<u8>, String), ShapeError> {
    let media = media(content_type);
    if is_sdp(media.as_deref()) {
        return Ok((encode_call(sdp.as_bytes(), None), "application/json".into()));
    }
    if media.as_deref() != Some("application/json") {
        return Err(invalid("Codex live media relay requires an SDP or JSON call request"));
    }
    let mut payload = unmarshal_raw_map(body)
        .map_err(|e| invalid(format!("failed to decode Codex live call request: {e}")))?
        .ok_or(ShapeError::NilMap)?;
    payload.insert("sdp".into(), gj::quote(sdp));
    Ok((marshal_raw_map(&payload), "application/json".into()))
}

/// `callResponseSDP`: the upstream answer, JSON-wrapped or raw.
pub fn response_sdp(body: &[u8], content_type: &str) -> Result<String, String> {
    if media(content_type).as_deref() == Some("application/json") {
        let sdp = unmarshal_sdp(body).map_err(|e| format!("failed to decode Codex live response: {e}"))?;
        if trim(&sdp).is_empty() {
            return Err("Codex live response requires an SDP answer".into());
        }
        return Ok(sdp);
    }
    if trim_space(body).is_empty() {
        return Err("Codex live response requires an SDP answer".into());
    }
    Ok(String::from_utf8_lossy(body).into_owned())
}

/// A request log copy of a live body without SDP ICE credentials: each `a=ice-ufrag:`
/// and `a=ice-pwd:` value becomes `[REDACTED]`, whether the SDP is raw, a multipart
/// field or a JSON string. Go logs these bodies unchanged.
pub fn redact_sdp(body: &[u8]) -> std::borrow::Cow<'_, [u8]> {
    // In a JSON string the `=` may be escaped as `\u003d`.
    const NEEDLES: [&[u8]; 6] = [
        b"a=ice-ufrag:",
        b"a=ice-pwd:",
        b"a\\u003dice-ufrag:",
        b"a\\u003dice-pwd:",
        b"a\\u003Dice-ufrag:",
        b"a\\u003Dice-pwd:",
    ];
    let mut out: Option<Vec<u8>> = None;
    let (mut copied, mut at) = (0, 0);
    while at < body.len() {
        let Some(needle) = NEEDLES.iter().find(|n| body[at..].starts_with(n)) else {
            at += 1;
            continue;
        };
        let value = at + needle.len();
        let end = credential_end(body, value);
        if end > value {
            let out = out.get_or_insert_with(|| Vec::with_capacity(body.len()));
            out.extend_from_slice(&body[copied..value]);
            out.extend_from_slice(b"[REDACTED]");
            copied = end;
        }
        at = end;
    }
    match out {
        None => body.into(),
        Some(mut out) => {
            out.extend_from_slice(&body[copied..]);
            out.into()
        }
    }
}

/// Where an ICE credential starting at `at` ends: at the line end, or in a JSON string at
/// its closing quote or an escaped line end (`\r`, `\n`, `\u000d`, `\u000a`). Other JSON
/// escapes, such as `\/` or `\u0073`, are part of the value.
fn credential_end(body: &[u8], mut at: usize) -> usize {
    while let Some(&byte) = body.get(at) {
        match byte {
            b'\r' | b'\n' | b'"' => break,
            b'\\' => {
                let escape = &body[at + 1..];
                let line_end = matches!(escape.first(), Some(b'r' | b'n'))
                    || escape
                        .get(..5)
                        .is_some_and(|u| u.eq_ignore_ascii_case(b"u000d") || u.eq_ignore_ascii_case(b"u000a"));
                if line_end {
                    break;
                }
                at += if escape.first() == Some(&b'u') { 6 } else { 2 };
            }
            _ => at += 1,
        }
    }
    at.min(body.len())
}

/// `modelFromJSON`: `session.model`, else `model`, trimmed; empty when Go's decode into
/// `struct{Model; Session struct{Model}}` fails at all.
pub fn model_from_json(body: &[u8]) -> String {
    if check_valid(body).is_err() {
        return String::new();
    }
    let root = gj::parse(body);
    if root.kind == Kind::Null {
        return String::new();
    }
    if !root.is_object() {
        return String::new();
    }
    let (mut model, mut session_model, mut failed) = (String::new(), String::new(), false);
    // A string sets the field, null leaves it, anything else is a type error.
    let store = |slot: &mut String, value: &gj::Res<'_>| match value.kind {
        Kind::String => {
            *slot = gj::go_unquote(&value.raw).unwrap_or_default();
            true
        }
        Kind::Null => true,
        _ => false,
    };
    root.each(|key, value| {
        let key = gj::go_unquote(&key.raw).unwrap_or_default();
        if field_is(&key, "model") {
            failed |= !store(&mut model, &value);
        } else if field_is(&key, "session") {
            match value.kind {
                Kind::Null => {}
                // A repeated session decodes into the same struct: fields merge.
                Kind::Json if value.is_object() => value.each(|key, value| {
                    if field_is(&gj::go_unquote(&key.raw).unwrap_or_default(), "model") {
                        failed |= !store(&mut session_model, &value);
                    }
                    true
                }),
                _ => failed = true,
            }
        }
        true
    });
    if failed {
        return String::new();
    }
    match trim(&session_model) {
        "" => trim(&model).to_owned(),
        session => session.to_owned(),
    }
}

/// encoding/json field matching: exact, else Go's case fold.
fn field_is(key: &str, name: &str) -> bool {
    key == name || fold(key) == fold(name)
}

/// `json.Unmarshal(body, &struct{ SDP string `json:"sdp"` })`.
fn unmarshal_sdp(body: &[u8]) -> Result<String, String> {
    check_valid(body)?;
    let root = gj::parse(body);
    if root.kind == Kind::Null {
        return Ok(String::new());
    }
    if !root.is_object() {
        return Err(format!(
            r#"json: cannot unmarshal {} into Go value of type struct {{ SDP string "json:\"sdp\"" }}"#,
            kind_name(&root)
        ));
    }
    let (mut sdp, mut error) = (String::new(), None);
    root.each(|key, value| {
        if !field_is(&gj::go_unquote(&key.raw).unwrap_or_default(), "sdp") {
            return true;
        }
        match value.kind {
            Kind::String => sdp = gj::go_unquote(&value.raw).unwrap_or_default(),
            Kind::Null => {}
            _ => {
                error.get_or_insert_with(|| {
                    format!(
                        "json: cannot unmarshal {} into Go struct field .sdp of type string",
                        kind_name(&value)
                    )
                });
            }
        }
        true
    });
    error.map_or(Ok(sdp), Err)
}

/// `json.Unmarshal` into `map[string]json.RawMessage`: `None` is Go's nil map (`null`).
fn unmarshal_raw_map(body: &[u8]) -> Result<Option<BTreeMap<String, Vec<u8>>>, String> {
    check_valid(body)?;
    let root = gj::parse(body);
    if root.kind == Kind::Null {
        return Ok(None);
    }
    if !root.is_object() {
        return Err(format!(
            "json: cannot unmarshal {} into Go value of type map[string]json.RawMessage",
            kind_name(&root)
        ));
    }
    let mut map = BTreeMap::new();
    root.each(|key, value| {
        map.insert(gj::go_unquote(&key.raw).unwrap_or_default(), value.raw.to_vec());
        true
    });
    Ok(Some(map))
}

/// `json.Marshal(map[string]json.RawMessage)`: sorted keys, compacted HTML-escaped values.
fn marshal_raw_map(map: &BTreeMap<String, Vec<u8>>) -> Vec<u8> {
    let mut out = vec![b'{'];
    for (i, (key, value)) in map.iter().enumerate() {
        if i > 0 {
            out.push(b',');
        }
        gj::marshal_str(&mut out, key.as_bytes(), true);
        out.push(b':');
        out.extend_from_slice(&gj::compact(value, true));
    }
    out.push(b'}');
    out
}

/// `encodeCallRequest`: `{"sdp":...,"session":...}`, session omitted when empty.
fn encode_call(sdp: &[u8], session: Option<&[u8]>) -> Vec<u8> {
    let mut out = b"{\"sdp\":".to_vec();
    gj::marshal_str(&mut out, sdp, true);
    if let Some(session) = session.filter(|s| !s.is_empty()) {
        out.extend_from_slice(b",\"session\":");
        out.extend_from_slice(&gj::compact(session, true));
    }
    out.push(b'}');
    out
}

/// `multipartCallRequest`.
fn multipart_call(body: &[u8], boundary: &str) -> Result<Call, ShapeError> {
    if boundary.is_empty() {
        return Err(invalid("Codex live multipart boundary is missing"));
    }
    let mut reader = form::Reader::new(body, boundary);
    let (mut sdp, mut session, mut model) = (None, None, String::new());
    loop {
        let part = match reader.next_part() {
            Ok(Some(part)) => part,
            Ok(None) => break,
            Err(e) => return Err(invalid(format!("failed to parse Codex live multipart body: {e}"))),
        };
        // `io.ReadAll(part)`: Go's `NextPart` decodes quoted-printable parts on read.
        let (raw, read_error) = reader.body();
        let data = if part.quoted_printable {
            form::quoted_printable(&raw, read_error)
        } else {
            read_error.map_or(Ok(raw), Err)
        }
        .map_err(|e| invalid(format!("failed to read Codex live multipart field: {e}")))?;
        match part.name.as_str() {
            "sdp" => sdp = Some(data),
            "session" => {
                if !gj::std_valid(&data) {
                    return Err(invalid("Codex live session field must contain valid JSON"));
                }
                model = model_from_json(&data);
                session = Some(data);
            }
            _ => {}
        }
    }
    let sdp = sdp.ok_or_else(|| invalid("Codex live multipart body requires an sdp field"))?;
    if model.is_empty() {
        model = DEFAULT_MODEL.into();
    }
    Ok(Call {
        body: encode_call(&sdp, session.as_deref()),
        content_type: "application/json".into(),
        model,
    })
}

/// `codexRealtimeModel`: OpenAI Realtime model names map to the Codex live model.
pub fn codex_model(model: &str) -> String {
    let trimmed = trim(model);
    let lower = trimmed.go_lower();
    if lower.is_empty()
        || lower == "gpt-realtime"
        || lower.starts_with("gpt-realtime-")
        || lower.contains("realtime-preview")
    {
        return DEFAULT_MODEL.into();
    }
    trimmed.into()
}

/// `callIDPattern`: `^[A-Za-z0-9_-]{1,128}$`.
pub fn valid_call_id(id: &str) -> bool {
    (1..=128).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}

/// `callIDFromLocation`: a bare ID, `?call_id=`, or the last segment after `live` or
/// `calls`.
pub fn call_id_from_location(location: &str) -> String {
    let location = trim(location);
    if valid_call_id(location) {
        return location.into();
    }
    let Some((path, query)) = go_url_path_query(location) else {
        return String::new();
    };
    if let Some(id) = query_first(&query, "call_id").map(|id| trim(&id).to_owned())
        && valid_call_id(&id)
    {
        return id;
    }
    let parts: Vec<&str> = path.trim_matches('/').split('/').collect();
    match parts.as_slice() {
        [.., previous, id] if valid_call_id(id) && matches!(*previous, "live" | "calls") => (*id).to_owned(),
        _ => String::new(),
    }
}

/// The unescaped path and raw query of `url.Parse(raw)`, `None` where Go errors.
// ponytail: covers what an upstream `Location` can carry (scheme, authority, escapes,
// query, fragment); Go's host and port validation is not ported.
fn go_url_path_query(raw: &str) -> Option<(String, String)> {
    if raw.bytes().any(|b| b < 0x20 || b == 0x7f) {
        return None;
    }
    let (rest, fragment) = raw.split_once('#').unwrap_or((raw, ""));
    unescape(fragment, false)?;
    let scheme_end = rest.find(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')));
    let (scheme, mut rest) = match scheme_end {
        Some(0) if rest.starts_with(':') => return None,
        Some(i) if rest[i..].starts_with(':') && rest.as_bytes()[0].is_ascii_alphabetic() => {
            (&rest[..i], &rest[i + 1..])
        }
        _ => ("", rest),
    };
    let query;
    if rest.ends_with('?') && rest.matches('?').count() == 1 {
        query = "";
        rest = &rest[..rest.len() - 1];
    } else {
        let (path, q) = rest.split_once('?').unwrap_or((rest, ""));
        rest = path;
        query = q;
    }
    if !rest.starts_with('/') {
        if !scheme.is_empty() {
            return Some((String::new(), query.into()));
        }
        if rest.split('/').next().is_some_and(|segment| segment.contains(':')) {
            return None;
        }
    }
    if (!scheme.is_empty() || !rest.starts_with("///")) && rest.starts_with("//") {
        let after = &rest[2..];
        let end = after.find('/').unwrap_or(after.len());
        rest = &after[end..];
    }
    let path = unescape(rest, false)?;
    Some((String::from_utf8_lossy(&path).into_owned(), query.into()))
}

/// Go `url.unescape`: `%XX` must be hex; `+` is a space only in query components.
fn unescape(s: &str, query: bool) -> Option<Vec<u8>> {
    let b = s.as_bytes();
    let mut out = Vec::with_capacity(b.len());
    let mut i = 0;
    while i < b.len() {
        match b[i] {
            b'%' => {
                let hex = b.get(i + 1..i + 3).filter(|h| h.iter().all(u8::is_ascii_hexdigit))?;
                out.push(u8::from_str_radix(std::str::from_utf8(hex).ok()?, 16).ok()?);
                i += 3;
            }
            b'+' if query => {
                out.push(b' ');
                i += 1;
            }
            c => {
                out.push(c);
                i += 1;
            }
        }
    }
    Some(out)
}

/// `url.ParseQuery(query).Get(name)`.
fn query_first(query: &str, name: &str) -> Option<String> {
    query
        .split('&')
        .filter(|p| !p.is_empty() && !p.contains(';'))
        .find_map(|pair| {
            let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
            let (k, v) = (unescape(k, true)?, unescape(v, true)?);
            (k == name.as_bytes()).then(|| String::from_utf8_lossy(&v).into_owned())
        })
}

/// `url.QueryEscape`.
fn query_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),
            b' ' => out.push('+'),
            _ => out.push_str(&format!("%{b:02X}")),
        }
    }
    out
}

/// The three sideband URL shapes (`sidebandStyle`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Sideband {
    /// `/v1/live/{id}`.
    Frameless,
    /// `/v1/realtime/calls/{id}`.
    Calls,
    /// `/v1/realtime?call_id={id}`.
    Query,
}

/// `buildSidebandURL`.
pub fn sideband_url(base: &str, style: Sideband, call_id: &str) -> String {
    let root = base.trim_end_matches('/');
    match style {
        Sideband::Calls => format!("{root}/realtime/calls/{call_id}"),
        Sideband::Query => format!("{root}/realtime?intent=quicksilver&call_id={}", query_escape(call_id)),
        Sideband::Frameless => format!("{root}/live/{call_id}"),
    }
}

/// `directRealtimeURL`.
pub fn direct_url(base: &str, model: &str) -> String {
    format!(
        "{}/realtime?model={}",
        base.trim_end_matches('/'),
        query_escape(trim(model))
    )
}

/// `websocketHTTPURL`: `ws`→`http`, `wss`→`https`.
pub fn http_url(url: &str) -> String {
    let Some((scheme, rest)) = url.split_once("://") else {
        return url.into();
    };
    match scheme.to_ascii_lowercase().as_str() {
        "ws" => format!("http://{rest}"),
        "wss" => format!("https://{rest}"),
        other => format!("{other}://{rest}"),
    }
}

/// `realtimeHTTPBaseURL`: where hangup goes.
pub fn http_base(api_base: &str) -> String {
    http_url(api_base).trim_end_matches('/').to_owned()
}

/// `bearerToken`: the trimmed token after a case-insensitive `Bearer `.
pub fn bearer_token(authorization: &str) -> &str {
    let value = trim(authorization);
    match value.get(..7) {
        Some(prefix) if prefix.eq_ignore_ascii_case("bearer ") => trim(&value[7..]),
        _ => "",
    }
}

/// Why a client-secret session was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SessionError {
    /// HTTP 501 `not_supported_error`.
    Unsupported(String),
    /// HTTP 400 `invalid_session`.
    Invalid(String),
}

/// `normalizeClientSecretSession`: the session shown to the client and the one sent
/// upstream (Codex model), both as Go's `map[string]any` marshals them.
pub fn normalize_client_secret_session(session: &[u8]) -> Result<(Vec<u8>, Vec<u8>), SessionError> {
    let trimmed = trim_space(session);
    let session = if trimmed.is_empty() || trimmed == b"null" {
        br#"{"type":"realtime","model":"gpt-realtime"}"#.as_slice()
    } else {
        session
    };
    let Some(Ok(mut map)) = GoValue::parse_f64(session).map(GoValue::into_object) else {
        return Err(SessionError::Invalid("session must be a valid JSON object".into()));
    };
    let string = |map: &BTreeMap<String, GoValue>, key: &str| match map.get(key) {
        Some(GoValue::String(s)) => s.clone(),
        _ => String::new(),
    };
    let mut kind = string(&map, "type");
    if trim(&kind).is_empty() {
        kind = "realtime".into();
        map.insert("type".into(), GoValue::String(kind.clone()));
    }
    if kind != "realtime" {
        return Err(SessionError::Unsupported(format!(
            "Realtime session type is not supported by the Codex OAuth upstream: {}",
            go_quote(&kind)
        )));
    }
    let mut model = string(&map, "model");
    if trim(&model).is_empty() {
        model = DEFAULT_STANDARD_MODEL.into();
        map.insert("model".into(), GoValue::String(model.clone()));
    }
    let client = GoValue::Object(map.clone()).marshal();
    map.insert("model".into(), GoValue::String(codex_model(&model)));
    Ok((client, GoValue::Object(map).marshal()))
}

/// `clientSecretCreateRequest` as `json.Unmarshal` decodes it: the raw `session` (empty
/// when absent) and `expires_after` (`None` when absent or null). `None` is any decode
/// error; Go answers every one with the same message.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct SecretRequest {
    pub session: Vec<u8>,
    pub expires_after: Option<(String, i64)>,
}

pub fn decode_secret_request(body: &[u8]) -> Option<SecretRequest> {
    let mut request = SecretRequest::default();
    if trim_space(body).is_empty() {
        return Some(request);
    }
    check_valid(body).ok()?;
    let root = gj::parse(body);
    if root.kind == Kind::Null {
        return Some(request);
    }
    if !root.is_object() {
        return None;
    }
    let mut ok = true;
    root.each(|key, value| {
        let key = gj::go_unquote(&key.raw).unwrap_or_default();
        if field_is(&key, "session") {
            request.session = value.raw.to_vec();
        } else if field_is(&key, "expires_after") {
            match value.kind {
                Kind::Null => request.expires_after = None,
                Kind::Json if value.is_object() => {
                    // A repeated object decodes into the same struct: fields merge.
                    let (anchor, seconds) = request.expires_after.get_or_insert_with(Default::default);
                    value.each(|key, value| {
                        let key = gj::go_unquote(&key.raw).unwrap_or_default();
                        match value.kind {
                            Kind::Null => {}
                            Kind::String if field_is(&key, "anchor") => {
                                *anchor = gj::go_unquote(&value.raw).unwrap_or_default();
                            }
                            Kind::Number if field_is(&key, "seconds") => {
                                match std::str::from_utf8(&value.raw).ok().and_then(|n| n.parse::<i64>().ok()) {
                                    Some(n) => *seconds = n,
                                    None => ok = false,
                                }
                            }
                            _ if field_is(&key, "anchor") || field_is(&key, "seconds") => ok = false,
                            _ => {}
                        }
                        true
                    });
                }
                _ => ok = false,
            }
        }
        true
    });
    ok.then_some(request)
}

/// `clientSecretLifetime`: ten minutes by default, else 10 s to 2 h from `created_at`.
pub fn client_secret_lifetime(expires_after: Option<&(String, i64)>) -> Result<Duration, String> {
    let Some((anchor, seconds)) = expires_after else {
        return Ok(Duration::from_secs(600));
    };
    if !anchor.is_empty() && anchor != "created_at" {
        return Err("expires_after.anchor must be created_at".into());
    }
    if !(10..=7200).contains(seconds) {
        return Err("expires_after.seconds must be between 10 and 7200".into());
    }
    Ok(Duration::from_secs(*seconds as u64))
}

/// `realtimeSessionResponse`: the client session with `id`, `object` and `expires_at`.
pub fn session_response(session: &[u8], id: &str, expires_at: i64) -> Option<GoValue> {
    let Some(Ok(mut map)) = GoValue::parse_f64(session).map(GoValue::into_object) else {
        return None;
    };
    map.insert("id".into(), GoValue::String(id.into()));
    map.insert("object".into(), GoValue::String("realtime.session".into()));
    map.insert("expires_at".into(), GoValue::Number(expires_at.to_string()));
    Some(GoValue::Object(map))
}

/// `realtimeSessionUpdate`: the key's session minus the fields a `session.update` may
/// not carry.
pub fn session_update(session: &[u8]) -> Result<Vec<u8>, String> {
    let Some(mut map) = unmarshal_raw_map(session)? else {
        return Ok(b"null".to_vec());
    };
    for field in ["model", "id", "object", "expires_at", "client_secret"] {
        map.remove(field);
    }
    Ok(marshal_raw_map(&map))
}

/// `protocolHeaders`: the forwarded client headers, canonical names, every value.
pub fn protocol_headers(client: &HeaderMap) -> Vec<(String, String)> {
    let mut out = Vec::new();
    for name in PROTOCOL_HEADERS {
        for value in client.get_all(name) {
            out.push((
                canonical_header(name),
                String::from_utf8_lossy(value.as_bytes()).into_owned(),
            ));
        }
    }
    out
}

/// `directRealtimeHeaders`: no `OpenAI-Alpha`, and `Originator` defaults to Codex Desktop.
pub fn direct_headers(client: &HeaderMap) -> Vec<(String, String)> {
    let mut out = protocol_headers(client);
    out.retain(|(name, _)| name != "Openai-Alpha");
    if out
        .iter()
        .find(|(name, _)| name == "Originator")
        .is_none_or(|(_, v)| v.is_empty())
    {
        out.retain(|(name, _)| name != "Originator");
        out.push(("Originator".into(), "Codex Desktop".into()));
    }
    out
}

/// `readLimitedBody` outcome.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BodyError {
    /// More than [`MAX_BODY`] bytes.
    TooLarge,
    /// The read failed after the returned bytes; the transport's error.
    Read(String),
}

impl std::fmt::Display for BodyError {
    /// Go's error text (`errBodyTooLarge`, or the read error).
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BodyError::TooLarge => f.write_str("Codex live request body too large"),
            BodyError::Read(text) => f.write_str(text),
        }
    }
}

/// `readLimitedBody`: at most `MAX_BODY` bytes, keeping what arrived on error.
pub async fn read_limited(upstream: Upstream) -> (Vec<u8>, Option<BodyError>) {
    use futures_util::StreamExt;
    let mut body = upstream.body;
    let mut out = Vec::new();
    while let Some(chunk) = body.next().await {
        match chunk {
            Ok(chunk) => {
                out.extend_from_slice(&chunk[..chunk.len().min(MAX_BODY + 1 - out.len())]);
                if out.len() > MAX_BODY {
                    out.truncate(MAX_BODY);
                    return (out, Some(BodyError::TooLarge));
                }
            }
            // The shared client's text: it withholds transport causes, which can name
            // credential-bearing URLs.
            Err(e) => {
                return (
                    out,
                    Some(BodyError::Read(String::from_utf8_lossy(&e.body).into_owned())),
                );
            }
        }
    }
    (out, None)
}

/// A connected upstream WebSocket.
pub struct LiveSocket {
    pub socket: wreq::ws::WebSocket,
    /// The subprotocol the upstream selected.
    pub protocol: Option<String>,
    pub status: u16,
    pub headers: HeaderMap,
}

/// A failed upstream WebSocket dial.
#[derive(Debug)]
pub struct DialError {
    /// The handshake response when the upstream answered.
    pub response: Option<Box<HandshakeResponse>>,
    /// The status of a refusal before dialling (Go's status error from
    /// `PrepareHttpRequest`); never an upstream answer.
    pub status: Option<u16>,
    pub message: String,
}

/// A non-101 handshake answer, its body capped like gorilla's.
#[derive(Debug)]
pub struct HandshakeResponse {
    pub status: u16,
    pub headers: HeaderMap,
    pub body: Vec<u8>,
}

/// The credential and client context of one live upstream exchange.
pub struct LiveTarget<'a> {
    pub credential: &'a Credential,
    pub cfg: &'a Config,
    /// The downstream request headers (custom-header `$` variables read them).
    pub client: &'a HeaderMap,
    /// The request's session, for `$CPA-SESSION-ID`.
    pub session: Option<String>,
    /// The request log's upstream capture (Go's `helps.Record*` calls). The live
    /// sockets pass none: Go writes no request log for GET requests.
    pub capture: CaptureSink,
}

impl LiveTarget<'_> {
    fn view(&self) -> View<'_> {
        View::for_request(self.credential, self.cfg).with_session(self.session.clone())
    }

    /// `RecordAPIRequest` as live.go and capabilities.go call it: provider `codex`, the
    /// selected credential and `headersForLogging`.
    fn record_post(&self, url: &str, headers: &[(String, String)], body: &[u8]) {
        if !self.capture.enabled() {
            return;
        }
        let (auth_type, auth_value) = cpa_core::registry::dynamic::account_info(self.credential);
        let headers = logged_headers(headers);
        self.capture.record(CaptureEvent::Request(UpstreamRequest {
            url,
            method: "POST",
            headers: &headers,
            body,
            provider: "codex",
            auth_id: &self.credential.id,
            auth_label: &self.credential.label,
            auth_type,
            auth_value: &auth_value,
        }));
    }
}

/// `headersForLogging`: an attestation token is logged as `[REDACTED]`.
fn logged_headers(headers: &[(String, String)]) -> Vec<(String, String)> {
    let attestation = |name: &str| canonical_header(name) == "X-Oai-Attestation";
    if !headers
        .iter()
        .find(|(n, _)| attestation(n))
        .is_some_and(|(_, v)| !v.is_empty())
    {
        return headers.to_vec();
    }
    let mut out: Vec<(String, String)> = headers.iter().filter(|(n, _)| !attestation(n)).cloned().collect();
    out.push(("X-Oai-Attestation".into(), "[REDACTED]".into()));
    out
}

/// `callResponseHeaders`: what request logs keep of a live upstream response.
pub fn call_response_headers(headers: &HeaderMap) -> Vec<(String, String)> {
    [
        "Content-Type",
        "Location",
        "Retry-After",
        "X-Request-Id",
        "OpenAI-Request-Id",
    ]
    .iter()
    .flat_map(|name| {
        headers.get_all(*name).iter().map(move |v| {
            (
                canonical_header(name),
                String::from_utf8_lossy(v.as_bytes()).into_owned(),
            )
        })
    })
    .collect()
}

impl CodexExecutor {
    /// Test hook: where live calls, sidebands and hangups go.
    pub fn with_live_endpoints(mut self, call_url: impl Into<String>, api_base: impl Into<String>) -> Self {
        self.live = Endpoints {
            call_url: call_url.into(),
            api_base: api_base.into(),
        };
        self
    }

    pub fn live_endpoints(&self) -> &Endpoints {
        &self.live
    }

    /// `setAccountHeader` then the Codex `PrepareRequest`: bearer from the API key or
    /// access token, then operator `header:` attributes.
    fn live_credential_headers(
        view: &View<'_>,
        client: &HeaderMap,
        mut headers: Vec<(String, String)>,
    ) -> Vec<(String, String)> {
        fn set(headers: &mut Vec<(String, String)>, name: &str, value: String) {
            let name = canonical_header(name);
            headers.retain(|(n, _)| *n != name);
            headers.push((name, value));
        }
        if let Some(account) = view.credential.str("account_id").filter(|a| !trim(a).is_empty()) {
            set(&mut headers, "Chatgpt-Account-Id", account.to_owned());
        }
        if trim(view.token).is_empty() {
            headers.retain(|(n, _)| n != "Authorization");
        } else {
            set(&mut headers, "Authorization", format!("Bearer {}", view.token));
        }
        for (name, value) in request::custom_headers(view, client) {
            set(&mut headers, &name, value);
        }
        headers
    }

    /// One live HTTP request (`authManager.HttpRequest` with the Codex executor): Go's
    /// client for the URL (Chrome TLS for chatgpt.com) through the credential's proxy,
    /// redirects followed like `http.Client.Do`.
    pub async fn live_post(
        &self,
        target: &LiveTarget<'_>,
        url: &str,
        headers: Vec<(String, String)>,
        body: Bytes,
    ) -> Result<Upstream, ExecError> {
        // `PrepareRequest`: Sign in with ChatGPT needs its token.
        crate::codex_siwc::require_token(target.credential)?;
        let view = target.view();
        let headers = Self::live_credential_headers(&view, target.client, headers);
        target.record_post(url, &headers, &body);
        let mut go = GoHeaders::new();
        for (name, value) in headers {
            go.add_raw(&name, value);
        }
        let route = |next: &url::Url| {
            Ok(Route {
                client: self
                    .transport
                    .for_url(next.as_str(), &view.proxy, view.chatgpt_keep_alive, view.handshake),
                order: None,
            })
        };
        let sent = proxy::send_routed(&route, url, go, body, None, None).await;
        if let Err(e) = &sent {
            // `RecordAPIResponseError` on a transport failure.
            target
                .capture
                .record(CaptureEvent::ResponseError(&String::from_utf8_lossy(&e.body)));
        }
        sent
    }

    /// Dials a live WebSocket with Go's standard dialer rules (credential or global
    /// proxy, else the environment's) and the client's subprotocols.
    pub async fn live_websocket(
        &self,
        target: &LiveTarget<'_>,
        url: &str,
        headers: Vec<(String, String)>,
        protocols: Vec<String>,
    ) -> Result<LiveSocket, DialError> {
        // `PrepareHttpRequest`: Sign in with ChatGPT needs its token (Go's 401).
        if let Err(error) = crate::codex_siwc::require_token(target.credential) {
            return Err(DialError {
                response: None,
                status: Some(error.status),
                message: String::from_utf8_lossy(&error.body).into_owned(),
            });
        }
        let view = target.view();
        let mut map = HeaderMap::new();
        for (name, value) in Self::live_credential_headers(&view, target.client, headers) {
            if let (Ok(name), Ok(value)) = (
                http::HeaderName::try_from(name.as_str()),
                http::HeaderValue::from_bytes(value.as_bytes()),
            ) {
                map.append(name, value);
            }
        }
        let fail = |message: &str| DialError {
            response: None,
            status: None,
            message: message.into(),
        };
        // gorilla's dialer offers the client's subprotocols as one header and accepts
        // whatever the upstream selects, or none; wreq's own negotiation rejects both
        // cases, so the offer goes out as a plain header and the answer is read here.
        if !protocols.is_empty()
            && let Ok(value) = http::HeaderValue::from_str(&protocols.join(", "))
        {
            map.insert(http::header::SEC_WEBSOCKET_PROTOCOL, value);
        }
        let builder = self
            .transport
            .standard(&view.proxy)
            .websocket(url)
            .headers(map)
            .max_frame_size(MAX_WS_MESSAGE)
            .max_message_size(MAX_WS_MESSAGE);
        let attempt = async {
            let mut res = builder.send().await.map_err(|e| fail(&dial_text(&e)))?;
            let status = res.status().as_u16();
            let headers = res.headers().clone();
            if status != 101 {
                use futures_util::StreamExt;
                let inner = std::mem::replace(&mut *res, wreq::Response::from(http::Response::new(Vec::<u8>::new())));
                let mut stream = inner.bytes_stream();
                let mut body = Vec::new();
                while body.len() < MAX_HANDSHAKE_BODY {
                    match stream.next().await {
                        Some(Ok(chunk)) => {
                            body.extend_from_slice(&chunk[..chunk.len().min(MAX_HANDSHAKE_BODY - body.len())])
                        }
                        _ => break,
                    }
                }
                return Err(DialError {
                    response: Some(Box::new(HandshakeResponse { status, headers, body })),
                    status: None,
                    message: "websocket: bad handshake".into(),
                });
            }
            let protocol = res
                .headers_mut()
                .remove(http::header::SEC_WEBSOCKET_PROTOCOL)
                .and_then(|p| p.to_str().ok().map(str::to_owned))
                .filter(|p| !p.is_empty());
            let socket = res
                .into_websocket()
                .await
                .map_err(|_| fail("websocket: bad handshake"))?;
            Ok(LiveSocket {
                socket,
                protocol,
                status,
                headers,
            })
        };
        tokio::time::timeout(HANDSHAKE_TIMEOUT, attempt)
            .await
            .unwrap_or_else(|_| Err(fail("websocket: handshake timed out")))
    }
}

fn dial_text(error: &wreq::Error) -> String {
    let mut text = error.to_string();
    let mut source = std::error::Error::source(error);
    while let Some(inner) = source {
        text = format!("{text}: {inner}");
        source = inner.source();
    }
    text
}

/// Go `mime/multipart.Reader` and `textproto.readMIMEHeader` over a body already in
/// memory, as `multipartCallRequest` walks it: `NextPart` then `io.ReadAll(part)`.
// ponytail: based on cpa-server's management multipart reader (the most Go-accurate of
// the three in the tree) plus `NextPart`'s quoted-printable decoding and header limits.
// Consolidate the copies into cpa-common when an owner is free.
mod form {
    use super::MediaType;

    pub struct Reader<'a> {
        buf: &'a [u8],
        pos: usize,
        nl: &'static [u8],
        dash_boundary: Vec<u8>,
        parts_read: usize,
    }

    enum Scan {
        Data,
        End,
        UnexpectedEof,
    }

    impl<'a> Reader<'a> {
        pub fn new(buf: &'a [u8], boundary: &str) -> Self {
            Self {
                buf,
                pos: 0,
                nl: b"\r\n",
                dash_boundary: format!("--{boundary}").into_bytes(),
                parts_read: 0,
            }
        }

        fn read_slice(&mut self) -> (&'a [u8], bool) {
            let rest = &self.buf[self.pos..];
            match rest.iter().position(|&b| b == b'\n') {
                Some(i) => {
                    self.pos += i + 1;
                    (&rest[..=i], false)
                }
                None => {
                    self.pos = self.buf.len();
                    (rest, true)
                }
            }
        }

        fn is_final_boundary(&self, line: &[u8]) -> bool {
            let mut dash_dash = self.dash_boundary.clone();
            dash_dash.extend_from_slice(b"--");
            line.strip_prefix(dash_dash.as_slice())
                .map(skip_lwsp)
                .is_some_and(|rest| rest.is_empty() || rest == self.nl)
        }

        fn is_boundary_delimiter_line(&mut self, line: &[u8]) -> bool {
            let Some(rest) = line.strip_prefix(self.dash_boundary.as_slice()).map(skip_lwsp) else {
                return false;
            };
            if self.parts_read == 0 && rest == b"\n" {
                self.nl = b"\n";
            }
            rest == self.nl
        }

        /// `NextPart`; `None` is (a wrapped) `io.EOF`.
        pub fn next_part(&mut self) -> Result<Option<Part>, String> {
            let mut expect_new_part = false;
            loop {
                let (line, eof) = self.read_slice();
                if eof && self.is_final_boundary(line) {
                    return Ok(None);
                }
                if eof {
                    // `multipart: NextPart: EOF` wraps io.EOF, which the caller's
                    // `errors.Is(err, io.EOF)` treats as the end of the form.
                    return Ok(None);
                }
                if self.is_boundary_delimiter_line(line) {
                    self.parts_read += 1;
                    return self.headers();
                }
                if self.is_final_boundary(line) {
                    return Ok(None);
                }
                if expect_new_part {
                    return Err(format!(
                        "multipart: expecting a new Part; got line {}",
                        cpa_common::gostr::quote(line)
                    ));
                }
                if self.parts_read == 0 {
                    continue;
                }
                if line == self.nl {
                    expect_new_part = true;
                    continue;
                }
                return Err(format!(
                    "multipart: unexpected line in Next(): {}",
                    cpa_common::gostr::quote(line)
                ));
            }
        }

        fn read_line(&mut self) -> Option<&'a [u8]> {
            if self.pos >= self.buf.len() {
                return None;
            }
            let (line, _) = self.read_slice();
            Some(match line.strip_suffix(b"\n") {
                Some(line) => line.strip_suffix(b"\r").unwrap_or(line),
                None => line,
            })
        }

        /// `readMIMEHeader` with `NextPart`'s limits (10000 headers, 10 MiB), then
        /// `FormName()` and the transfer encoding. EOF inside the headers is `io.EOF`.
        fn headers(&mut self) -> Result<Option<Part>, String> {
            const TOO_LARGE: &str = "multipart: message too large";
            let mut disposition: Option<String> = None;
            let mut encoding: Option<String> = None;
            if matches!(self.buf.get(self.pos), Some(b' ' | b'\t')) {
                let Some(line) = self.read_line() else {
                    return Ok(None);
                };
                if line.len() > 80 {
                    return Err(TOO_LARGE.into());
                }
                return Err(format!(
                    "malformed MIME header initial line: {}",
                    cpa_common::gostr::quote(line)
                ));
            }
            // `maxMIMEHeaders` and `maxMIMEHeaderSize` less the map overhead.
            let mut headers_left: i64 = 10_000;
            let mut memory_left: i64 = (10 << 20) - 400;
            let mut keys = std::collections::HashSet::new();
            loop {
                let Some(first) = self.read_line() else {
                    return Ok(None);
                };
                if first.is_empty() {
                    break;
                }
                if !first.contains(&b':') {
                    return Err(format!(
                        "malformed MIME header: missing colon: {}",
                        cpa_common::gostr::quote(first)
                    ));
                }
                let mut kv = trim_ascii_space(first).to_vec();
                loop {
                    let spaces = self.buf[self.pos..]
                        .iter()
                        .take_while(|&&b| b == b' ' || b == b'\t')
                        .count();
                    if spaces == 0 {
                        break;
                    }
                    self.pos += spaces;
                    kv.push(b' ');
                    match self.read_line() {
                        Some(line) => kv.extend_from_slice(trim_ascii_space(line)),
                        None => break,
                    }
                }
                let malformed = || format!("malformed MIME header line: {}", cpa_common::gostr::quote(&kv));
                let colon = kv.iter().position(|&b| b == b':').unwrap_or(kv.len());
                let (key, value) = (&kv[..colon], &kv[(colon + 1).min(kv.len())..]);
                if !key.iter().all(|&b| is_header_field_byte(b) || b == b' ') {
                    return Err(malformed());
                }
                if value.iter().any(|&b| (b < 0x20 && b != b'\t') || b == 0x7f) {
                    return Err(malformed());
                }
                headers_left -= 1;
                if headers_left < 0 {
                    return Err(TOO_LARGE.into());
                }
                let value: Vec<u8> = value
                    .iter()
                    .skip_while(|&&b| b == b' ' || b == b'\t')
                    .copied()
                    .collect();
                // Keys with a space are kept verbatim, so `Header.Get` never finds them.
                let canonical = if key.contains(&b' ') {
                    String::from_utf8_lossy(key).into_owned()
                } else {
                    String::from_utf8_lossy(key).to_ascii_lowercase()
                };
                if keys.insert(canonical.clone()) {
                    memory_left -= key.len() as i64 + 200;
                }
                memory_left -= value.len() as i64;
                if memory_left < 0 {
                    return Err(TOO_LARGE.into());
                }
                let slot = match canonical.as_str() {
                    "content-disposition" => &mut disposition,
                    "content-transfer-encoding" => &mut encoding,
                    _ => continue,
                };
                slot.get_or_insert_with(|| String::from_utf8_lossy(&value).into_owned());
            }
            let name = match disposition.map(|d| crate::openai_compat_multipart::parse_media_type(&d)) {
                Some(MediaType::Ok(kind, params)) if kind == "form-data" => {
                    params.get("name").cloned().unwrap_or_default()
                }
                _ => String::new(),
            };
            Ok(Some(Part {
                name,
                quoted_printable: encoding.is_some_and(|e| e.eq_ignore_ascii_case("quoted-printable")),
            }))
        }

        /// The current part's body up to its closing boundary (`partReader`), and the
        /// read error that ended it early.
        pub fn body(&mut self) -> (Vec<u8>, Option<String>) {
            let mut nl_dash = self.nl.to_vec();
            nl_dash.extend_from_slice(&self.dash_boundary);
            let mut data = Vec::new();
            let mut total = 0;
            loop {
                let rest = &self.buf[self.pos..];
                let (n, scan) = scan_until_boundary(rest, &self.dash_boundary, &nl_dash, total);
                data.extend_from_slice(&rest[..n]);
                self.pos += n;
                total += n;
                match scan {
                    Scan::Data => {}
                    Scan::End => return (data, None),
                    Scan::UnexpectedEof => return (data, Some("unexpected EOF".into())),
                }
            }
        }
    }

    /// What `NextPart` tells the caller about a part.
    pub struct Part {
        /// `FormName()`.
        pub name: String,
        /// `Content-Transfer-Encoding: quoted-printable` (case-insensitive).
        pub quoted_printable: bool,
    }

    /// `io.ReadAll(quotedprintable.NewReader(part))` (mime/quotedprintable/reader.go):
    /// `=XX` escapes (lower-case hex too), `=` soft breaks before LF or CRLF, a lone
    /// `=` that is not followed by two hex digits kept literally, trailing white space
    /// dropped. `read_error` is the part reader's own failure after `data`.
    pub fn quoted_printable(data: &[u8], read_error: Option<String>) -> Result<Vec<u8>, String> {
        let hex = |b: u8| match b {
            b'0'..=b'9' => Ok(b - b'0'),
            b'A'..=b'F' => Ok(b - b'A' + 10),
            b'a'..=b'f' => Ok(b - b'a' + 10),
            _ => Err(format!("quotedprintable: invalid hex byte 0x{b:02x}")),
        };
        let mut out = Vec::with_capacity(data.len());
        let mut rest = data;
        while !rest.is_empty() {
            // `ReadSlice('\n')`: the last line ends with the reader's error instead.
            let end = rest.iter().position(|&b| b == b'\n').map_or(rest.len(), |i| i + 1);
            let whole = &rest[..end];
            rest = &rest[end..];
            let at_eof = rest.is_empty() && !whole.ends_with(b"\n") && read_error.is_none();
            let kept = whole.len()
                - whole
                    .iter()
                    .rev()
                    .take_while(|b| matches!(b, b'\n' | b'\r' | b' ' | b'\t'))
                    .count();
            let mut line = whole[..kept].to_vec();
            let mut line_error = None;
            if line.ends_with(b"=") {
                let tail = &whole[kept..];
                let right = &tail[tail.iter().take_while(|b| matches!(b, b' ' | b'\t')).count()..];
                line.pop();
                if !right.starts_with(b"\n")
                    && !right.starts_with(b"\r\n")
                    && !(right.is_empty() && !line.is_empty() && at_eof)
                {
                    line_error = Some(format!(
                        "quotedprintable: invalid bytes after =: {}",
                        cpa_common::gostr::quote(right)
                    ));
                }
            } else if whole.ends_with(b"\r\n") {
                line.extend_from_slice(b"\r\n");
            } else if whole.ends_with(b"\n") {
                line.push(b'\n');
            }
            let mut i = 0;
            while i < line.len() {
                let b = line[i];
                match b {
                    b'=' => match line.get(i + 1..i + 3) {
                        Some(pair) => match hex(pair[0]).and_then(|hi| Ok(hi << 4 | hex(pair[1])?)) {
                            Ok(byte) => {
                                out.push(byte);
                                i += 3;
                                continue;
                            }
                            Err(_) if !matches!(line[i + 1], b'\r' | b'\n') => out.push(b'='),
                            Err(e) => return Err(e),
                        },
                        None if line.len() - i >= 2 && !matches!(line[i + 1], b'\r' | b'\n') => out.push(b'='),
                        None => return Err("unexpected EOF".into()),
                    },
                    b'\t' | b'\r' | b'\n' | 0x80..=0xff => out.push(b),
                    b if !(b' '..=b'~').contains(&b) => {
                        return Err(format!("quotedprintable: invalid unescaped byte 0x{b:02x} in body"));
                    }
                    b => out.push(b),
                }
                i += 1;
            }
            if let Some(error) = line_error {
                return Err(error);
            }
        }
        read_error.map_or(Ok(out), Err)
    }

    fn scan_until_boundary(buf: &[u8], dash: &[u8], nl_dash: &[u8], total: usize) -> (usize, Scan) {
        if total == 0 {
            if buf.starts_with(dash) {
                return match match_after_prefix(buf, dash) {
                    true => (0, Scan::End),
                    false => (dash.len(), Scan::Data),
                };
            }
            if dash.starts_with(buf) {
                return (0, Scan::UnexpectedEof);
            }
        }
        if let Some(i) = buf.windows(nl_dash.len()).position(|w| w == nl_dash) {
            return match match_after_prefix(&buf[i..], nl_dash) {
                true => (i, Scan::End),
                false => (i + nl_dash.len(), Scan::Data),
            };
        }
        if nl_dash.starts_with(buf) {
            return (0, Scan::UnexpectedEof);
        }
        if let Some(i) = buf.iter().rposition(|&b| b == nl_dash[0])
            && nl_dash.starts_with(&buf[i..])
        {
            return (i, Scan::Data);
        }
        (buf.len(), Scan::UnexpectedEof)
    }

    fn match_after_prefix(buf: &[u8], prefix: &[u8]) -> bool {
        match buf.get(prefix.len()) {
            None => true,
            Some(b' ' | b'\t' | b'\r' | b'\n') => true,
            Some(b'-') => buf.get(prefix.len() + 1) == Some(&b'-'),
            Some(_) => false,
        }
    }

    fn skip_lwsp(b: &[u8]) -> &[u8] {
        let n = b.iter().take_while(|&&c| c == b' ' || c == b'\t').count();
        &b[n..]
    }

    fn trim_ascii_space(b: &[u8]) -> &[u8] {
        let is_space = |c: &u8| matches!(c, b' ' | b'\t' | b'\n' | b'\r');
        let start = b.iter().position(|c| !is_space(c)).unwrap_or(b.len());
        let end = b.iter().rposition(|c| !is_space(c)).map_or(start, |i| i + 1);
        &b[start..end]
    }

    fn is_header_field_byte(b: u8) -> bool {
        b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)
    }
}

#[cfg(test)]
#[path = "codex_live_tests.rs"]
mod tests;