Skip to main content

cpa_exec/
codex_live.rs

1//! Codex live calls (internal/client/codex/live): the WebRTC SDP bootstrap request to the
2//! ChatGPT realtime calls endpoint, its sideband and standard Realtime WebSockets, and
3//! hangup.
4//!
5//! Request shaping ports live.go, client_secret.go and websocket.go byte for byte,
6//! including Go's error texts; expected values come from
7//! tests/fixtures/codex_live/vectors.json, generated by running the Go functions. Routes,
8//! client secrets and call state live in cpa-server's `realtime` module.
9
10use std::collections::BTreeMap;
11use std::time::Duration;
12
13use bytes::Bytes;
14use cpa_common::gostr::{GoStr, quote as go_quote, trim_space};
15use cpa_common::json::{self as gj, GoValue, Kind};
16use cpa_core::config::Config;
17use cpa_core::credential::Credential;
18use cpa_core::exec::{CaptureEvent, CaptureSink, ExecError, UpstreamRequest};
19use http::HeaderMap;
20
21use crate::codex::CodexExecutor;
22use crate::codex_request::{self as request, View};
23use crate::meta_wire::{check_valid, fold, kind_name};
24use crate::openai_compat_multipart::{MediaType, parse_media_type};
25use crate::proxy::{self, GoHeaders, Route, Upstream, canonical_header};
26
27/// `upstreamCallURL`.
28pub const CALL_URL: &str = "https://chatgpt.com/backend-api/codex/realtime/calls?intent=quicksilver&architecture=avas";
29/// `defaultSidebandAPIBaseURL`: sideband, standard Realtime WebSocket and hangup.
30pub const API_BASE: &str = "wss://api.openai.com/v1";
31/// `defaultLiveModel`.
32pub const DEFAULT_MODEL: &str = "gpt-live-1-codex";
33/// `defaultStandardRealtimeModel`.
34pub const DEFAULT_STANDARD_MODEL: &str = "gpt-realtime";
35/// `maxBodySize`: call requests, upstream responses and rejected handshakes.
36pub const MAX_BODY: usize = 16 << 20;
37/// Largest relayed WebSocket message.
38// ponytail: gorilla streams messages of any size; tungstenite buffers whole messages, so
39// 16 MiB (Go's body cap) bounds per-connection memory. Raise it if a client needs more.
40pub const MAX_WS_MESSAGE: usize = MAX_BODY;
41/// gorilla keeps at most 1 KiB of a rejected handshake's body.
42const MAX_HANDSHAKE_BODY: usize = 1024;
43// ponytail: Go's sideband dialer has no handshake timeout (request cancellation only);
44// a fixed bound keeps a stalled upstream from holding the call claim forever.
45const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(30);
46
47/// `liveProtocolHeaders`: client headers forwarded to every live upstream request.
48pub const PROTOCOL_HEADERS: [&str; 9] = [
49    "OpenAI-Alpha",
50    "X-Session-Id",
51    "Session-Id",
52    "Thread-Id",
53    "Originator",
54    "OpenAI-Safety-Identifier",
55    "OpenAI-Organization",
56    "OpenAI-Project",
57    "X-Oai-Attestation",
58];
59
60/// Where live requests go. Tests point both at local mocks.
61#[derive(Debug, Clone)]
62pub struct Endpoints {
63    pub call_url: String,
64    /// WebSocket base (`ws`/`wss`); hangup uses its HTTP form.
65    pub api_base: String,
66}
67
68impl Default for Endpoints {
69    fn default() -> Self {
70        Self {
71            call_url: CALL_URL.into(),
72            api_base: API_BASE.into(),
73        }
74    }
75}
76
77/// A call request on its way upstream.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct Call {
80    pub body: Vec<u8>,
81    pub content_type: String,
82    pub model: String,
83}
84
85/// Why a call request could not be shaped.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub enum ShapeError {
88    /// HTTP 400 with Go's message.
89    Invalid(String),
90    /// Go assigns into a nil map (a `null` request or session); gin's recovery answers
91    /// 500 with no body.
92    NilMap,
93}
94
95fn invalid(message: impl Into<String>) -> ShapeError {
96    ShapeError::Invalid(message.into())
97}
98
99/// `strings.TrimSpace` on a Go string.
100fn trim(s: &str) -> &str {
101    std::str::from_utf8(trim_space(s.as_bytes())).unwrap_or(s)
102}
103
104/// The media type when `mime.ParseMediaType` succeeds.
105fn media(content_type: &str) -> Option<String> {
106    match parse_media_type(content_type) {
107        MediaType::Ok(media, _) => Some(media),
108        _ => None,
109    }
110}
111
112fn is_sdp(media: Option<&str>) -> bool {
113    matches!(media, Some("application/sdp" | "text/plain"))
114}
115
116/// `prepareCallRequest`: multipart SDP + session becomes `{"sdp","session"}` JSON; any
117/// other body passes through with its model (default `gpt-live-1-codex`).
118pub fn prepare(body: &[u8], content_type: &str) -> Result<Call, ShapeError> {
119    if let MediaType::Ok(media, params) = parse_media_type(content_type)
120        && media == "multipart/form-data"
121    {
122        let boundary = params.get("boundary").map(|b| trim(b)).unwrap_or_default();
123        return multipart_call(body, boundary);
124    }
125    let mut model = model_from_json(body);
126    if model.is_empty() {
127        model = DEFAULT_MODEL.into();
128    }
129    let content_type = if trim(content_type).is_empty() {
130        "application/json"
131    } else {
132        content_type
133    };
134    Ok(Call {
135        body: body.to_vec(),
136        content_type: content_type.into(),
137        model,
138    })
139}
140
141/// `applyClientSecretCallSession`: the ephemeral key's session replaces the request's.
142pub fn apply_client_secret(call: Call, session: &[u8]) -> Result<Call, ShapeError> {
143    if session.is_empty() {
144        return Ok(call);
145    }
146    let media = media(&call.content_type);
147    let body = if is_sdp(media.as_deref()) {
148        encode_call(&call.body, Some(session))
149    } else if media.as_deref() == Some("application/json") {
150        let mut payload = unmarshal_raw_map(&call.body)
151            .map_err(|e| invalid(format!("failed to decode Realtime call request: {e}")))?
152            .ok_or(ShapeError::NilMap)?;
153        payload.insert("session".into(), session.to_vec());
154        marshal_raw_map(&payload)
155    } else {
156        return Err(invalid("Realtime client secrets require an SDP or JSON call request"));
157    };
158    Ok(Call {
159        body,
160        content_type: "application/json".into(),
161        model: model_from_json(session),
162    })
163}
164
165/// `rewriteCallRequestModel`: the upstream model replaces `session.model`, or a
166/// top-level `model` when there is no session. Returns the upstream model.
167pub fn rewrite_model(call: Call) -> Result<Call, ShapeError> {
168    let upstream = codex_model(&call.model);
169    let unchanged = |call: Call| Call {
170        model: upstream.clone(),
171        ..call
172    };
173    if media(&call.content_type).as_deref() != Some("application/json") || trim_space(&call.body).is_empty() {
174        return Ok(unchanged(call));
175    }
176    let Some(mut payload) =
177        unmarshal_raw_map(&call.body).map_err(|e| invalid(format!("failed to decode Realtime call request: {e}")))?
178    else {
179        return Ok(unchanged(call));
180    };
181    let encoded_model = gj::quote(&upstream);
182    if let Some(raw) = payload.get("session") {
183        let mut session = unmarshal_raw_map(raw)
184            .map_err(|e| invalid(format!("failed to decode Realtime session: {e}")))?
185            .ok_or(ShapeError::NilMap)?;
186        session.insert("model".into(), encoded_model);
187        payload.insert("session".into(), marshal_raw_map(&session));
188    } else if payload.contains_key("model") {
189        payload.insert("model".into(), encoded_model);
190    } else {
191        return Ok(unchanged(call));
192    }
193    Ok(Call {
194        body: marshal_raw_map(&payload),
195        content_type: call.content_type,
196        model: upstream,
197    })
198}
199
200/// `callRequestSDP`: the client's offer, for the media relay.
201pub fn request_sdp(body: &[u8], content_type: &str) -> Result<String, String> {
202    let media = media(content_type);
203    if is_sdp(media.as_deref()) {
204        if trim_space(body).is_empty() {
205            return Err("Codex live call request requires an SDP offer".into());
206        }
207        return Ok(String::from_utf8_lossy(body).into_owned());
208    }
209    if media.as_deref() != Some("application/json") {
210        return Err("Codex live media relay requires an SDP or JSON call request".into());
211    }
212    let sdp = unmarshal_sdp(body).map_err(|e| format!("failed to decode Codex live call request: {e}"))?;
213    if trim(&sdp).is_empty() {
214        return Err("Codex live call request requires an SDP offer".into());
215    }
216    Ok(sdp)
217}
218
219/// `replaceCallRequestSDP`: the relay's own offer replaces the client's.
220pub fn replace_sdp(body: &[u8], content_type: &str, sdp: &str) -> Result<(Vec<u8>, String), ShapeError> {
221    let media = media(content_type);
222    if is_sdp(media.as_deref()) {
223        return Ok((encode_call(sdp.as_bytes(), None), "application/json".into()));
224    }
225    if media.as_deref() != Some("application/json") {
226        return Err(invalid("Codex live media relay requires an SDP or JSON call request"));
227    }
228    let mut payload = unmarshal_raw_map(body)
229        .map_err(|e| invalid(format!("failed to decode Codex live call request: {e}")))?
230        .ok_or(ShapeError::NilMap)?;
231    payload.insert("sdp".into(), gj::quote(sdp));
232    Ok((marshal_raw_map(&payload), "application/json".into()))
233}
234
235/// `callResponseSDP`: the upstream answer, JSON-wrapped or raw.
236pub fn response_sdp(body: &[u8], content_type: &str) -> Result<String, String> {
237    if media(content_type).as_deref() == Some("application/json") {
238        let sdp = unmarshal_sdp(body).map_err(|e| format!("failed to decode Codex live response: {e}"))?;
239        if trim(&sdp).is_empty() {
240            return Err("Codex live response requires an SDP answer".into());
241        }
242        return Ok(sdp);
243    }
244    if trim_space(body).is_empty() {
245        return Err("Codex live response requires an SDP answer".into());
246    }
247    Ok(String::from_utf8_lossy(body).into_owned())
248}
249
250/// A request log copy of a live body without SDP ICE credentials: each `a=ice-ufrag:`
251/// and `a=ice-pwd:` value becomes `[REDACTED]`, whether the SDP is raw, a multipart
252/// field or a JSON string. Go logs these bodies unchanged.
253pub fn redact_sdp(body: &[u8]) -> std::borrow::Cow<'_, [u8]> {
254    // In a JSON string the `=` may be escaped as `\u003d`.
255    const NEEDLES: [&[u8]; 6] = [
256        b"a=ice-ufrag:",
257        b"a=ice-pwd:",
258        b"a\\u003dice-ufrag:",
259        b"a\\u003dice-pwd:",
260        b"a\\u003Dice-ufrag:",
261        b"a\\u003Dice-pwd:",
262    ];
263    let mut out: Option<Vec<u8>> = None;
264    let (mut copied, mut at) = (0, 0);
265    while at < body.len() {
266        let Some(needle) = NEEDLES.iter().find(|n| body[at..].starts_with(n)) else {
267            at += 1;
268            continue;
269        };
270        let value = at + needle.len();
271        let end = credential_end(body, value);
272        if end > value {
273            let out = out.get_or_insert_with(|| Vec::with_capacity(body.len()));
274            out.extend_from_slice(&body[copied..value]);
275            out.extend_from_slice(b"[REDACTED]");
276            copied = end;
277        }
278        at = end;
279    }
280    match out {
281        None => body.into(),
282        Some(mut out) => {
283            out.extend_from_slice(&body[copied..]);
284            out.into()
285        }
286    }
287}
288
289/// Where an ICE credential starting at `at` ends: at the line end, or in a JSON string at
290/// its closing quote or an escaped line end (`\r`, `\n`, `\u000d`, `\u000a`). Other JSON
291/// escapes, such as `\/` or `\u0073`, are part of the value.
292fn credential_end(body: &[u8], mut at: usize) -> usize {
293    while let Some(&byte) = body.get(at) {
294        match byte {
295            b'\r' | b'\n' | b'"' => break,
296            b'\\' => {
297                let escape = &body[at + 1..];
298                let line_end = matches!(escape.first(), Some(b'r' | b'n'))
299                    || escape
300                        .get(..5)
301                        .is_some_and(|u| u.eq_ignore_ascii_case(b"u000d") || u.eq_ignore_ascii_case(b"u000a"));
302                if line_end {
303                    break;
304                }
305                at += if escape.first() == Some(&b'u') { 6 } else { 2 };
306            }
307            _ => at += 1,
308        }
309    }
310    at.min(body.len())
311}
312
313/// `modelFromJSON`: `session.model`, else `model`, trimmed; empty when Go's decode into
314/// `struct{Model; Session struct{Model}}` fails at all.
315pub fn model_from_json(body: &[u8]) -> String {
316    if check_valid(body).is_err() {
317        return String::new();
318    }
319    let root = gj::parse(body);
320    if root.kind == Kind::Null {
321        return String::new();
322    }
323    if !root.is_object() {
324        return String::new();
325    }
326    let (mut model, mut session_model, mut failed) = (String::new(), String::new(), false);
327    // A string sets the field, null leaves it, anything else is a type error.
328    let store = |slot: &mut String, value: &gj::Res<'_>| match value.kind {
329        Kind::String => {
330            *slot = gj::go_unquote(&value.raw).unwrap_or_default();
331            true
332        }
333        Kind::Null => true,
334        _ => false,
335    };
336    root.each(|key, value| {
337        let key = gj::go_unquote(&key.raw).unwrap_or_default();
338        if field_is(&key, "model") {
339            failed |= !store(&mut model, &value);
340        } else if field_is(&key, "session") {
341            match value.kind {
342                Kind::Null => {}
343                // A repeated session decodes into the same struct: fields merge.
344                Kind::Json if value.is_object() => value.each(|key, value| {
345                    if field_is(&gj::go_unquote(&key.raw).unwrap_or_default(), "model") {
346                        failed |= !store(&mut session_model, &value);
347                    }
348                    true
349                }),
350                _ => failed = true,
351            }
352        }
353        true
354    });
355    if failed {
356        return String::new();
357    }
358    match trim(&session_model) {
359        "" => trim(&model).to_owned(),
360        session => session.to_owned(),
361    }
362}
363
364/// encoding/json field matching: exact, else Go's case fold.
365fn field_is(key: &str, name: &str) -> bool {
366    key == name || fold(key) == fold(name)
367}
368
369/// `json.Unmarshal(body, &struct{ SDP string `json:"sdp"` })`.
370fn unmarshal_sdp(body: &[u8]) -> Result<String, String> {
371    check_valid(body)?;
372    let root = gj::parse(body);
373    if root.kind == Kind::Null {
374        return Ok(String::new());
375    }
376    if !root.is_object() {
377        return Err(format!(
378            r#"json: cannot unmarshal {} into Go value of type struct {{ SDP string "json:\"sdp\"" }}"#,
379            kind_name(&root)
380        ));
381    }
382    let (mut sdp, mut error) = (String::new(), None);
383    root.each(|key, value| {
384        if !field_is(&gj::go_unquote(&key.raw).unwrap_or_default(), "sdp") {
385            return true;
386        }
387        match value.kind {
388            Kind::String => sdp = gj::go_unquote(&value.raw).unwrap_or_default(),
389            Kind::Null => {}
390            _ => {
391                error.get_or_insert_with(|| {
392                    format!(
393                        "json: cannot unmarshal {} into Go struct field .sdp of type string",
394                        kind_name(&value)
395                    )
396                });
397            }
398        }
399        true
400    });
401    error.map_or(Ok(sdp), Err)
402}
403
404/// `json.Unmarshal` into `map[string]json.RawMessage`: `None` is Go's nil map (`null`).
405fn unmarshal_raw_map(body: &[u8]) -> Result<Option<BTreeMap<String, Vec<u8>>>, String> {
406    check_valid(body)?;
407    let root = gj::parse(body);
408    if root.kind == Kind::Null {
409        return Ok(None);
410    }
411    if !root.is_object() {
412        return Err(format!(
413            "json: cannot unmarshal {} into Go value of type map[string]json.RawMessage",
414            kind_name(&root)
415        ));
416    }
417    let mut map = BTreeMap::new();
418    root.each(|key, value| {
419        map.insert(gj::go_unquote(&key.raw).unwrap_or_default(), value.raw.to_vec());
420        true
421    });
422    Ok(Some(map))
423}
424
425/// `json.Marshal(map[string]json.RawMessage)`: sorted keys, compacted HTML-escaped values.
426fn marshal_raw_map(map: &BTreeMap<String, Vec<u8>>) -> Vec<u8> {
427    let mut out = vec![b'{'];
428    for (i, (key, value)) in map.iter().enumerate() {
429        if i > 0 {
430            out.push(b',');
431        }
432        gj::marshal_str(&mut out, key.as_bytes(), true);
433        out.push(b':');
434        out.extend_from_slice(&gj::compact(value, true));
435    }
436    out.push(b'}');
437    out
438}
439
440/// `encodeCallRequest`: `{"sdp":...,"session":...}`, session omitted when empty.
441fn encode_call(sdp: &[u8], session: Option<&[u8]>) -> Vec<u8> {
442    let mut out = b"{\"sdp\":".to_vec();
443    gj::marshal_str(&mut out, sdp, true);
444    if let Some(session) = session.filter(|s| !s.is_empty()) {
445        out.extend_from_slice(b",\"session\":");
446        out.extend_from_slice(&gj::compact(session, true));
447    }
448    out.push(b'}');
449    out
450}
451
452/// `multipartCallRequest`.
453fn multipart_call(body: &[u8], boundary: &str) -> Result<Call, ShapeError> {
454    if boundary.is_empty() {
455        return Err(invalid("Codex live multipart boundary is missing"));
456    }
457    let mut reader = form::Reader::new(body, boundary);
458    let (mut sdp, mut session, mut model) = (None, None, String::new());
459    loop {
460        let part = match reader.next_part() {
461            Ok(Some(part)) => part,
462            Ok(None) => break,
463            Err(e) => return Err(invalid(format!("failed to parse Codex live multipart body: {e}"))),
464        };
465        // `io.ReadAll(part)`: Go's `NextPart` decodes quoted-printable parts on read.
466        let (raw, read_error) = reader.body();
467        let data = if part.quoted_printable {
468            form::quoted_printable(&raw, read_error)
469        } else {
470            read_error.map_or(Ok(raw), Err)
471        }
472        .map_err(|e| invalid(format!("failed to read Codex live multipart field: {e}")))?;
473        match part.name.as_str() {
474            "sdp" => sdp = Some(data),
475            "session" => {
476                if !gj::std_valid(&data) {
477                    return Err(invalid("Codex live session field must contain valid JSON"));
478                }
479                model = model_from_json(&data);
480                session = Some(data);
481            }
482            _ => {}
483        }
484    }
485    let sdp = sdp.ok_or_else(|| invalid("Codex live multipart body requires an sdp field"))?;
486    if model.is_empty() {
487        model = DEFAULT_MODEL.into();
488    }
489    Ok(Call {
490        body: encode_call(&sdp, session.as_deref()),
491        content_type: "application/json".into(),
492        model,
493    })
494}
495
496/// `codexRealtimeModel`: OpenAI Realtime model names map to the Codex live model.
497pub fn codex_model(model: &str) -> String {
498    let trimmed = trim(model);
499    let lower = trimmed.go_lower();
500    if lower.is_empty()
501        || lower == "gpt-realtime"
502        || lower.starts_with("gpt-realtime-")
503        || lower.contains("realtime-preview")
504    {
505        return DEFAULT_MODEL.into();
506    }
507    trimmed.into()
508}
509
510/// `callIDPattern`: `^[A-Za-z0-9_-]{1,128}$`.
511pub fn valid_call_id(id: &str) -> bool {
512    (1..=128).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
513}
514
515/// `callIDFromLocation`: a bare ID, `?call_id=`, or the last segment after `live` or
516/// `calls`.
517pub fn call_id_from_location(location: &str) -> String {
518    let location = trim(location);
519    if valid_call_id(location) {
520        return location.into();
521    }
522    let Some((path, query)) = go_url_path_query(location) else {
523        return String::new();
524    };
525    if let Some(id) = query_first(&query, "call_id").map(|id| trim(&id).to_owned())
526        && valid_call_id(&id)
527    {
528        return id;
529    }
530    let parts: Vec<&str> = path.trim_matches('/').split('/').collect();
531    match parts.as_slice() {
532        [.., previous, id] if valid_call_id(id) && matches!(*previous, "live" | "calls") => (*id).to_owned(),
533        _ => String::new(),
534    }
535}
536
537/// The unescaped path and raw query of `url.Parse(raw)`, `None` where Go errors.
538// ponytail: covers what an upstream `Location` can carry (scheme, authority, escapes,
539// query, fragment); Go's host and port validation is not ported.
540fn go_url_path_query(raw: &str) -> Option<(String, String)> {
541    if raw.bytes().any(|b| b < 0x20 || b == 0x7f) {
542        return None;
543    }
544    let (rest, fragment) = raw.split_once('#').unwrap_or((raw, ""));
545    unescape(fragment, false)?;
546    let scheme_end = rest.find(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')));
547    let (scheme, mut rest) = match scheme_end {
548        Some(0) if rest.starts_with(':') => return None,
549        Some(i) if rest[i..].starts_with(':') && rest.as_bytes()[0].is_ascii_alphabetic() => {
550            (&rest[..i], &rest[i + 1..])
551        }
552        _ => ("", rest),
553    };
554    let query;
555    if rest.ends_with('?') && rest.matches('?').count() == 1 {
556        query = "";
557        rest = &rest[..rest.len() - 1];
558    } else {
559        let (path, q) = rest.split_once('?').unwrap_or((rest, ""));
560        rest = path;
561        query = q;
562    }
563    if !rest.starts_with('/') {
564        if !scheme.is_empty() {
565            return Some((String::new(), query.into()));
566        }
567        if rest.split('/').next().is_some_and(|segment| segment.contains(':')) {
568            return None;
569        }
570    }
571    if (!scheme.is_empty() || !rest.starts_with("///")) && rest.starts_with("//") {
572        let after = &rest[2..];
573        let end = after.find('/').unwrap_or(after.len());
574        rest = &after[end..];
575    }
576    let path = unescape(rest, false)?;
577    Some((String::from_utf8_lossy(&path).into_owned(), query.into()))
578}
579
580/// Go `url.unescape`: `%XX` must be hex; `+` is a space only in query components.
581fn unescape(s: &str, query: bool) -> Option<Vec<u8>> {
582    let b = s.as_bytes();
583    let mut out = Vec::with_capacity(b.len());
584    let mut i = 0;
585    while i < b.len() {
586        match b[i] {
587            b'%' => {
588                let hex = b.get(i + 1..i + 3).filter(|h| h.iter().all(u8::is_ascii_hexdigit))?;
589                out.push(u8::from_str_radix(std::str::from_utf8(hex).ok()?, 16).ok()?);
590                i += 3;
591            }
592            b'+' if query => {
593                out.push(b' ');
594                i += 1;
595            }
596            c => {
597                out.push(c);
598                i += 1;
599            }
600        }
601    }
602    Some(out)
603}
604
605/// `url.ParseQuery(query).Get(name)`.
606fn query_first(query: &str, name: &str) -> Option<String> {
607    query
608        .split('&')
609        .filter(|p| !p.is_empty() && !p.contains(';'))
610        .find_map(|pair| {
611            let (k, v) = pair.split_once('=').unwrap_or((pair, ""));
612            let (k, v) = (unescape(k, true)?, unescape(v, true)?);
613            (k == name.as_bytes()).then(|| String::from_utf8_lossy(&v).into_owned())
614        })
615}
616
617/// `url.QueryEscape`.
618fn query_escape(s: &str) -> String {
619    let mut out = String::with_capacity(s.len());
620    for b in s.bytes() {
621        match b {
622            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),
623            b' ' => out.push('+'),
624            _ => out.push_str(&format!("%{b:02X}")),
625        }
626    }
627    out
628}
629
630/// The three sideband URL shapes (`sidebandStyle`).
631#[derive(Debug, Clone, Copy, PartialEq, Eq)]
632pub enum Sideband {
633    /// `/v1/live/{id}`.
634    Frameless,
635    /// `/v1/realtime/calls/{id}`.
636    Calls,
637    /// `/v1/realtime?call_id={id}`.
638    Query,
639}
640
641/// `buildSidebandURL`.
642pub fn sideband_url(base: &str, style: Sideband, call_id: &str) -> String {
643    let root = base.trim_end_matches('/');
644    match style {
645        Sideband::Calls => format!("{root}/realtime/calls/{call_id}"),
646        Sideband::Query => format!("{root}/realtime?intent=quicksilver&call_id={}", query_escape(call_id)),
647        Sideband::Frameless => format!("{root}/live/{call_id}"),
648    }
649}
650
651/// `directRealtimeURL`.
652pub fn direct_url(base: &str, model: &str) -> String {
653    format!(
654        "{}/realtime?model={}",
655        base.trim_end_matches('/'),
656        query_escape(trim(model))
657    )
658}
659
660/// `websocketHTTPURL`: `ws`→`http`, `wss`→`https`.
661pub fn http_url(url: &str) -> String {
662    let Some((scheme, rest)) = url.split_once("://") else {
663        return url.into();
664    };
665    match scheme.to_ascii_lowercase().as_str() {
666        "ws" => format!("http://{rest}"),
667        "wss" => format!("https://{rest}"),
668        other => format!("{other}://{rest}"),
669    }
670}
671
672/// `realtimeHTTPBaseURL`: where hangup goes.
673pub fn http_base(api_base: &str) -> String {
674    http_url(api_base).trim_end_matches('/').to_owned()
675}
676
677/// `bearerToken`: the trimmed token after a case-insensitive `Bearer `.
678pub fn bearer_token(authorization: &str) -> &str {
679    let value = trim(authorization);
680    match value.get(..7) {
681        Some(prefix) if prefix.eq_ignore_ascii_case("bearer ") => trim(&value[7..]),
682        _ => "",
683    }
684}
685
686/// Why a client-secret session was refused.
687#[derive(Debug, Clone, PartialEq, Eq)]
688pub enum SessionError {
689    /// HTTP 501 `not_supported_error`.
690    Unsupported(String),
691    /// HTTP 400 `invalid_session`.
692    Invalid(String),
693}
694
695/// `normalizeClientSecretSession`: the session shown to the client and the one sent
696/// upstream (Codex model), both as Go's `map[string]any` marshals them.
697pub fn normalize_client_secret_session(session: &[u8]) -> Result<(Vec<u8>, Vec<u8>), SessionError> {
698    let trimmed = trim_space(session);
699    let session = if trimmed.is_empty() || trimmed == b"null" {
700        br#"{"type":"realtime","model":"gpt-realtime"}"#.as_slice()
701    } else {
702        session
703    };
704    let Some(Ok(mut map)) = GoValue::parse_f64(session).map(GoValue::into_object) else {
705        return Err(SessionError::Invalid("session must be a valid JSON object".into()));
706    };
707    let string = |map: &BTreeMap<String, GoValue>, key: &str| match map.get(key) {
708        Some(GoValue::String(s)) => s.clone(),
709        _ => String::new(),
710    };
711    let mut kind = string(&map, "type");
712    if trim(&kind).is_empty() {
713        kind = "realtime".into();
714        map.insert("type".into(), GoValue::String(kind.clone()));
715    }
716    if kind != "realtime" {
717        return Err(SessionError::Unsupported(format!(
718            "Realtime session type is not supported by the Codex OAuth upstream: {}",
719            go_quote(&kind)
720        )));
721    }
722    let mut model = string(&map, "model");
723    if trim(&model).is_empty() {
724        model = DEFAULT_STANDARD_MODEL.into();
725        map.insert("model".into(), GoValue::String(model.clone()));
726    }
727    let client = GoValue::Object(map.clone()).marshal();
728    map.insert("model".into(), GoValue::String(codex_model(&model)));
729    Ok((client, GoValue::Object(map).marshal()))
730}
731
732/// `clientSecretCreateRequest` as `json.Unmarshal` decodes it: the raw `session` (empty
733/// when absent) and `expires_after` (`None` when absent or null). `None` is any decode
734/// error; Go answers every one with the same message.
735#[derive(Debug, Clone, PartialEq, Eq, Default)]
736pub struct SecretRequest {
737    pub session: Vec<u8>,
738    pub expires_after: Option<(String, i64)>,
739}
740
741pub fn decode_secret_request(body: &[u8]) -> Option<SecretRequest> {
742    let mut request = SecretRequest::default();
743    if trim_space(body).is_empty() {
744        return Some(request);
745    }
746    check_valid(body).ok()?;
747    let root = gj::parse(body);
748    if root.kind == Kind::Null {
749        return Some(request);
750    }
751    if !root.is_object() {
752        return None;
753    }
754    let mut ok = true;
755    root.each(|key, value| {
756        let key = gj::go_unquote(&key.raw).unwrap_or_default();
757        if field_is(&key, "session") {
758            request.session = value.raw.to_vec();
759        } else if field_is(&key, "expires_after") {
760            match value.kind {
761                Kind::Null => request.expires_after = None,
762                Kind::Json if value.is_object() => {
763                    // A repeated object decodes into the same struct: fields merge.
764                    let (anchor, seconds) = request.expires_after.get_or_insert_with(Default::default);
765                    value.each(|key, value| {
766                        let key = gj::go_unquote(&key.raw).unwrap_or_default();
767                        match value.kind {
768                            Kind::Null => {}
769                            Kind::String if field_is(&key, "anchor") => {
770                                *anchor = gj::go_unquote(&value.raw).unwrap_or_default();
771                            }
772                            Kind::Number if field_is(&key, "seconds") => {
773                                match std::str::from_utf8(&value.raw).ok().and_then(|n| n.parse::<i64>().ok()) {
774                                    Some(n) => *seconds = n,
775                                    None => ok = false,
776                                }
777                            }
778                            _ if field_is(&key, "anchor") || field_is(&key, "seconds") => ok = false,
779                            _ => {}
780                        }
781                        true
782                    });
783                }
784                _ => ok = false,
785            }
786        }
787        true
788    });
789    ok.then_some(request)
790}
791
792/// `clientSecretLifetime`: ten minutes by default, else 10 s to 2 h from `created_at`.
793pub fn client_secret_lifetime(expires_after: Option<&(String, i64)>) -> Result<Duration, String> {
794    let Some((anchor, seconds)) = expires_after else {
795        return Ok(Duration::from_secs(600));
796    };
797    if !anchor.is_empty() && anchor != "created_at" {
798        return Err("expires_after.anchor must be created_at".into());
799    }
800    if !(10..=7200).contains(seconds) {
801        return Err("expires_after.seconds must be between 10 and 7200".into());
802    }
803    Ok(Duration::from_secs(*seconds as u64))
804}
805
806/// `realtimeSessionResponse`: the client session with `id`, `object` and `expires_at`.
807pub fn session_response(session: &[u8], id: &str, expires_at: i64) -> Option<GoValue> {
808    let Some(Ok(mut map)) = GoValue::parse_f64(session).map(GoValue::into_object) else {
809        return None;
810    };
811    map.insert("id".into(), GoValue::String(id.into()));
812    map.insert("object".into(), GoValue::String("realtime.session".into()));
813    map.insert("expires_at".into(), GoValue::Number(expires_at.to_string()));
814    Some(GoValue::Object(map))
815}
816
817/// `realtimeSessionUpdate`: the key's session minus the fields a `session.update` may
818/// not carry.
819pub fn session_update(session: &[u8]) -> Result<Vec<u8>, String> {
820    let Some(mut map) = unmarshal_raw_map(session)? else {
821        return Ok(b"null".to_vec());
822    };
823    for field in ["model", "id", "object", "expires_at", "client_secret"] {
824        map.remove(field);
825    }
826    Ok(marshal_raw_map(&map))
827}
828
829/// `protocolHeaders`: the forwarded client headers, canonical names, every value.
830pub fn protocol_headers(client: &HeaderMap) -> Vec<(String, String)> {
831    let mut out = Vec::new();
832    for name in PROTOCOL_HEADERS {
833        for value in client.get_all(name) {
834            out.push((
835                canonical_header(name),
836                String::from_utf8_lossy(value.as_bytes()).into_owned(),
837            ));
838        }
839    }
840    out
841}
842
843/// `directRealtimeHeaders`: no `OpenAI-Alpha`, and `Originator` defaults to Codex Desktop.
844pub fn direct_headers(client: &HeaderMap) -> Vec<(String, String)> {
845    let mut out = protocol_headers(client);
846    out.retain(|(name, _)| name != "Openai-Alpha");
847    if out
848        .iter()
849        .find(|(name, _)| name == "Originator")
850        .is_none_or(|(_, v)| v.is_empty())
851    {
852        out.retain(|(name, _)| name != "Originator");
853        out.push(("Originator".into(), "Codex Desktop".into()));
854    }
855    out
856}
857
858/// `readLimitedBody` outcome.
859#[derive(Debug, Clone, PartialEq, Eq)]
860pub enum BodyError {
861    /// More than [`MAX_BODY`] bytes.
862    TooLarge,
863    /// The read failed after the returned bytes; the transport's error.
864    Read(String),
865}
866
867impl std::fmt::Display for BodyError {
868    /// Go's error text (`errBodyTooLarge`, or the read error).
869    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
870        match self {
871            BodyError::TooLarge => f.write_str("Codex live request body too large"),
872            BodyError::Read(text) => f.write_str(text),
873        }
874    }
875}
876
877/// `readLimitedBody`: at most `MAX_BODY` bytes, keeping what arrived on error.
878pub async fn read_limited(upstream: Upstream) -> (Vec<u8>, Option<BodyError>) {
879    use futures_util::StreamExt;
880    let mut body = upstream.body;
881    let mut out = Vec::new();
882    while let Some(chunk) = body.next().await {
883        match chunk {
884            Ok(chunk) => {
885                out.extend_from_slice(&chunk[..chunk.len().min(MAX_BODY + 1 - out.len())]);
886                if out.len() > MAX_BODY {
887                    out.truncate(MAX_BODY);
888                    return (out, Some(BodyError::TooLarge));
889                }
890            }
891            // The shared client's text: it withholds transport causes, which can name
892            // credential-bearing URLs.
893            Err(e) => {
894                return (
895                    out,
896                    Some(BodyError::Read(String::from_utf8_lossy(&e.body).into_owned())),
897                );
898            }
899        }
900    }
901    (out, None)
902}
903
904/// A connected upstream WebSocket.
905pub struct LiveSocket {
906    pub socket: wreq::ws::WebSocket,
907    /// The subprotocol the upstream selected.
908    pub protocol: Option<String>,
909    pub status: u16,
910    pub headers: HeaderMap,
911}
912
913/// A failed upstream WebSocket dial.
914#[derive(Debug)]
915pub struct DialError {
916    /// The handshake response when the upstream answered.
917    pub response: Option<Box<HandshakeResponse>>,
918    /// The status of a refusal before dialling (Go's status error from
919    /// `PrepareHttpRequest`); never an upstream answer.
920    pub status: Option<u16>,
921    pub message: String,
922}
923
924/// A non-101 handshake answer, its body capped like gorilla's.
925#[derive(Debug)]
926pub struct HandshakeResponse {
927    pub status: u16,
928    pub headers: HeaderMap,
929    pub body: Vec<u8>,
930}
931
932/// The credential and client context of one live upstream exchange.
933pub struct LiveTarget<'a> {
934    pub credential: &'a Credential,
935    pub cfg: &'a Config,
936    /// The downstream request headers (custom-header `$` variables read them).
937    pub client: &'a HeaderMap,
938    /// The request's session, for `$CPA-SESSION-ID`.
939    pub session: Option<String>,
940    /// The request log's upstream capture (Go's `helps.Record*` calls). The live
941    /// sockets pass none: Go writes no request log for GET requests.
942    pub capture: CaptureSink,
943}
944
945impl LiveTarget<'_> {
946    fn view(&self) -> View<'_> {
947        View::for_request(self.credential, self.cfg).with_session(self.session.clone())
948    }
949
950    /// `RecordAPIRequest` as live.go and capabilities.go call it: provider `codex`, the
951    /// selected credential and `headersForLogging`.
952    fn record_post(&self, url: &str, headers: &[(String, String)], body: &[u8]) {
953        if !self.capture.enabled() {
954            return;
955        }
956        let (auth_type, auth_value) = cpa_core::registry::dynamic::account_info(self.credential);
957        let headers = logged_headers(headers);
958        self.capture.record(CaptureEvent::Request(UpstreamRequest {
959            url,
960            method: "POST",
961            headers: &headers,
962            body,
963            provider: "codex",
964            auth_id: &self.credential.id,
965            auth_label: &self.credential.label,
966            auth_type,
967            auth_value: &auth_value,
968        }));
969    }
970}
971
972/// `headersForLogging`: an attestation token is logged as `[REDACTED]`.
973fn logged_headers(headers: &[(String, String)]) -> Vec<(String, String)> {
974    let attestation = |name: &str| canonical_header(name) == "X-Oai-Attestation";
975    if !headers
976        .iter()
977        .find(|(n, _)| attestation(n))
978        .is_some_and(|(_, v)| !v.is_empty())
979    {
980        return headers.to_vec();
981    }
982    let mut out: Vec<(String, String)> = headers.iter().filter(|(n, _)| !attestation(n)).cloned().collect();
983    out.push(("X-Oai-Attestation".into(), "[REDACTED]".into()));
984    out
985}
986
987/// `callResponseHeaders`: what request logs keep of a live upstream response.
988pub fn call_response_headers(headers: &HeaderMap) -> Vec<(String, String)> {
989    [
990        "Content-Type",
991        "Location",
992        "Retry-After",
993        "X-Request-Id",
994        "OpenAI-Request-Id",
995    ]
996    .iter()
997    .flat_map(|name| {
998        headers.get_all(*name).iter().map(move |v| {
999            (
1000                canonical_header(name),
1001                String::from_utf8_lossy(v.as_bytes()).into_owned(),
1002            )
1003        })
1004    })
1005    .collect()
1006}
1007
1008impl CodexExecutor {
1009    /// Test hook: where live calls, sidebands and hangups go.
1010    pub fn with_live_endpoints(mut self, call_url: impl Into<String>, api_base: impl Into<String>) -> Self {
1011        self.live = Endpoints {
1012            call_url: call_url.into(),
1013            api_base: api_base.into(),
1014        };
1015        self
1016    }
1017
1018    pub fn live_endpoints(&self) -> &Endpoints {
1019        &self.live
1020    }
1021
1022    /// `setAccountHeader` then the Codex `PrepareRequest`: bearer from the API key or
1023    /// access token, then operator `header:` attributes.
1024    fn live_credential_headers(
1025        view: &View<'_>,
1026        client: &HeaderMap,
1027        mut headers: Vec<(String, String)>,
1028    ) -> Vec<(String, String)> {
1029        fn set(headers: &mut Vec<(String, String)>, name: &str, value: String) {
1030            let name = canonical_header(name);
1031            headers.retain(|(n, _)| *n != name);
1032            headers.push((name, value));
1033        }
1034        if let Some(account) = view.credential.str("account_id").filter(|a| !trim(a).is_empty()) {
1035            set(&mut headers, "Chatgpt-Account-Id", account.to_owned());
1036        }
1037        if trim(view.token).is_empty() {
1038            headers.retain(|(n, _)| n != "Authorization");
1039        } else {
1040            set(&mut headers, "Authorization", format!("Bearer {}", view.token));
1041        }
1042        for (name, value) in request::custom_headers(view, client) {
1043            set(&mut headers, &name, value);
1044        }
1045        headers
1046    }
1047
1048    /// One live HTTP request (`authManager.HttpRequest` with the Codex executor): Go's
1049    /// client for the URL (Chrome TLS for chatgpt.com) through the credential's proxy,
1050    /// redirects followed like `http.Client.Do`.
1051    pub async fn live_post(
1052        &self,
1053        target: &LiveTarget<'_>,
1054        url: &str,
1055        headers: Vec<(String, String)>,
1056        body: Bytes,
1057    ) -> Result<Upstream, ExecError> {
1058        // `PrepareRequest`: Sign in with ChatGPT needs its token.
1059        crate::codex_siwc::require_token(target.credential)?;
1060        let view = target.view();
1061        let headers = Self::live_credential_headers(&view, target.client, headers);
1062        target.record_post(url, &headers, &body);
1063        let mut go = GoHeaders::new();
1064        for (name, value) in headers {
1065            go.add_raw(&name, value);
1066        }
1067        let route = |next: &url::Url| {
1068            Ok(Route {
1069                client: self
1070                    .transport
1071                    .for_url(next.as_str(), &view.proxy, view.chatgpt_keep_alive, view.handshake),
1072                order: None,
1073            })
1074        };
1075        let sent = proxy::send_routed(&route, url, go, body, None, None).await;
1076        if let Err(e) = &sent {
1077            // `RecordAPIResponseError` on a transport failure.
1078            target
1079                .capture
1080                .record(CaptureEvent::ResponseError(&String::from_utf8_lossy(&e.body)));
1081        }
1082        sent
1083    }
1084
1085    /// Dials a live WebSocket with Go's standard dialer rules (credential or global
1086    /// proxy, else the environment's) and the client's subprotocols.
1087    pub async fn live_websocket(
1088        &self,
1089        target: &LiveTarget<'_>,
1090        url: &str,
1091        headers: Vec<(String, String)>,
1092        protocols: Vec<String>,
1093    ) -> Result<LiveSocket, DialError> {
1094        // `PrepareHttpRequest`: Sign in with ChatGPT needs its token (Go's 401).
1095        if let Err(error) = crate::codex_siwc::require_token(target.credential) {
1096            return Err(DialError {
1097                response: None,
1098                status: Some(error.status),
1099                message: String::from_utf8_lossy(&error.body).into_owned(),
1100            });
1101        }
1102        let view = target.view();
1103        let mut map = HeaderMap::new();
1104        for (name, value) in Self::live_credential_headers(&view, target.client, headers) {
1105            if let (Ok(name), Ok(value)) = (
1106                http::HeaderName::try_from(name.as_str()),
1107                http::HeaderValue::from_bytes(value.as_bytes()),
1108            ) {
1109                map.append(name, value);
1110            }
1111        }
1112        let fail = |message: &str| DialError {
1113            response: None,
1114            status: None,
1115            message: message.into(),
1116        };
1117        // gorilla's dialer offers the client's subprotocols as one header and accepts
1118        // whatever the upstream selects, or none; wreq's own negotiation rejects both
1119        // cases, so the offer goes out as a plain header and the answer is read here.
1120        if !protocols.is_empty()
1121            && let Ok(value) = http::HeaderValue::from_str(&protocols.join(", "))
1122        {
1123            map.insert(http::header::SEC_WEBSOCKET_PROTOCOL, value);
1124        }
1125        let builder = self
1126            .transport
1127            .standard(&view.proxy)
1128            .websocket(url)
1129            .headers(map)
1130            .max_frame_size(MAX_WS_MESSAGE)
1131            .max_message_size(MAX_WS_MESSAGE);
1132        let attempt = async {
1133            let mut res = builder.send().await.map_err(|e| fail(&dial_text(&e)))?;
1134            let status = res.status().as_u16();
1135            let headers = res.headers().clone();
1136            if status != 101 {
1137                use futures_util::StreamExt;
1138                let inner = std::mem::replace(&mut *res, wreq::Response::from(http::Response::new(Vec::<u8>::new())));
1139                let mut stream = inner.bytes_stream();
1140                let mut body = Vec::new();
1141                while body.len() < MAX_HANDSHAKE_BODY {
1142                    match stream.next().await {
1143                        Some(Ok(chunk)) => {
1144                            body.extend_from_slice(&chunk[..chunk.len().min(MAX_HANDSHAKE_BODY - body.len())])
1145                        }
1146                        _ => break,
1147                    }
1148                }
1149                return Err(DialError {
1150                    response: Some(Box::new(HandshakeResponse { status, headers, body })),
1151                    status: None,
1152                    message: "websocket: bad handshake".into(),
1153                });
1154            }
1155            let protocol = res
1156                .headers_mut()
1157                .remove(http::header::SEC_WEBSOCKET_PROTOCOL)
1158                .and_then(|p| p.to_str().ok().map(str::to_owned))
1159                .filter(|p| !p.is_empty());
1160            let socket = res
1161                .into_websocket()
1162                .await
1163                .map_err(|_| fail("websocket: bad handshake"))?;
1164            Ok(LiveSocket {
1165                socket,
1166                protocol,
1167                status,
1168                headers,
1169            })
1170        };
1171        tokio::time::timeout(HANDSHAKE_TIMEOUT, attempt)
1172            .await
1173            .unwrap_or_else(|_| Err(fail("websocket: handshake timed out")))
1174    }
1175}
1176
1177fn dial_text(error: &wreq::Error) -> String {
1178    let mut text = error.to_string();
1179    let mut source = std::error::Error::source(error);
1180    while let Some(inner) = source {
1181        text = format!("{text}: {inner}");
1182        source = inner.source();
1183    }
1184    text
1185}
1186
1187/// Go `mime/multipart.Reader` and `textproto.readMIMEHeader` over a body already in
1188/// memory, as `multipartCallRequest` walks it: `NextPart` then `io.ReadAll(part)`.
1189// ponytail: based on cpa-server's management multipart reader (the most Go-accurate of
1190// the three in the tree) plus `NextPart`'s quoted-printable decoding and header limits.
1191// Consolidate the copies into cpa-common when an owner is free.
1192mod form {
1193    use super::MediaType;
1194
1195    pub struct Reader<'a> {
1196        buf: &'a [u8],
1197        pos: usize,
1198        nl: &'static [u8],
1199        dash_boundary: Vec<u8>,
1200        parts_read: usize,
1201    }
1202
1203    enum Scan {
1204        Data,
1205        End,
1206        UnexpectedEof,
1207    }
1208
1209    impl<'a> Reader<'a> {
1210        pub fn new(buf: &'a [u8], boundary: &str) -> Self {
1211            Self {
1212                buf,
1213                pos: 0,
1214                nl: b"\r\n",
1215                dash_boundary: format!("--{boundary}").into_bytes(),
1216                parts_read: 0,
1217            }
1218        }
1219
1220        fn read_slice(&mut self) -> (&'a [u8], bool) {
1221            let rest = &self.buf[self.pos..];
1222            match rest.iter().position(|&b| b == b'\n') {
1223                Some(i) => {
1224                    self.pos += i + 1;
1225                    (&rest[..=i], false)
1226                }
1227                None => {
1228                    self.pos = self.buf.len();
1229                    (rest, true)
1230                }
1231            }
1232        }
1233
1234        fn is_final_boundary(&self, line: &[u8]) -> bool {
1235            let mut dash_dash = self.dash_boundary.clone();
1236            dash_dash.extend_from_slice(b"--");
1237            line.strip_prefix(dash_dash.as_slice())
1238                .map(skip_lwsp)
1239                .is_some_and(|rest| rest.is_empty() || rest == self.nl)
1240        }
1241
1242        fn is_boundary_delimiter_line(&mut self, line: &[u8]) -> bool {
1243            let Some(rest) = line.strip_prefix(self.dash_boundary.as_slice()).map(skip_lwsp) else {
1244                return false;
1245            };
1246            if self.parts_read == 0 && rest == b"\n" {
1247                self.nl = b"\n";
1248            }
1249            rest == self.nl
1250        }
1251
1252        /// `NextPart`; `None` is (a wrapped) `io.EOF`.
1253        pub fn next_part(&mut self) -> Result<Option<Part>, String> {
1254            let mut expect_new_part = false;
1255            loop {
1256                let (line, eof) = self.read_slice();
1257                if eof && self.is_final_boundary(line) {
1258                    return Ok(None);
1259                }
1260                if eof {
1261                    // `multipart: NextPart: EOF` wraps io.EOF, which the caller's
1262                    // `errors.Is(err, io.EOF)` treats as the end of the form.
1263                    return Ok(None);
1264                }
1265                if self.is_boundary_delimiter_line(line) {
1266                    self.parts_read += 1;
1267                    return self.headers();
1268                }
1269                if self.is_final_boundary(line) {
1270                    return Ok(None);
1271                }
1272                if expect_new_part {
1273                    return Err(format!(
1274                        "multipart: expecting a new Part; got line {}",
1275                        cpa_common::gostr::quote(line)
1276                    ));
1277                }
1278                if self.parts_read == 0 {
1279                    continue;
1280                }
1281                if line == self.nl {
1282                    expect_new_part = true;
1283                    continue;
1284                }
1285                return Err(format!(
1286                    "multipart: unexpected line in Next(): {}",
1287                    cpa_common::gostr::quote(line)
1288                ));
1289            }
1290        }
1291
1292        fn read_line(&mut self) -> Option<&'a [u8]> {
1293            if self.pos >= self.buf.len() {
1294                return None;
1295            }
1296            let (line, _) = self.read_slice();
1297            Some(match line.strip_suffix(b"\n") {
1298                Some(line) => line.strip_suffix(b"\r").unwrap_or(line),
1299                None => line,
1300            })
1301        }
1302
1303        /// `readMIMEHeader` with `NextPart`'s limits (10000 headers, 10 MiB), then
1304        /// `FormName()` and the transfer encoding. EOF inside the headers is `io.EOF`.
1305        fn headers(&mut self) -> Result<Option<Part>, String> {
1306            const TOO_LARGE: &str = "multipart: message too large";
1307            let mut disposition: Option<String> = None;
1308            let mut encoding: Option<String> = None;
1309            if matches!(self.buf.get(self.pos), Some(b' ' | b'\t')) {
1310                let Some(line) = self.read_line() else {
1311                    return Ok(None);
1312                };
1313                if line.len() > 80 {
1314                    return Err(TOO_LARGE.into());
1315                }
1316                return Err(format!(
1317                    "malformed MIME header initial line: {}",
1318                    cpa_common::gostr::quote(line)
1319                ));
1320            }
1321            // `maxMIMEHeaders` and `maxMIMEHeaderSize` less the map overhead.
1322            let mut headers_left: i64 = 10_000;
1323            let mut memory_left: i64 = (10 << 20) - 400;
1324            let mut keys = std::collections::HashSet::new();
1325            loop {
1326                let Some(first) = self.read_line() else {
1327                    return Ok(None);
1328                };
1329                if first.is_empty() {
1330                    break;
1331                }
1332                if !first.contains(&b':') {
1333                    return Err(format!(
1334                        "malformed MIME header: missing colon: {}",
1335                        cpa_common::gostr::quote(first)
1336                    ));
1337                }
1338                let mut kv = trim_ascii_space(first).to_vec();
1339                loop {
1340                    let spaces = self.buf[self.pos..]
1341                        .iter()
1342                        .take_while(|&&b| b == b' ' || b == b'\t')
1343                        .count();
1344                    if spaces == 0 {
1345                        break;
1346                    }
1347                    self.pos += spaces;
1348                    kv.push(b' ');
1349                    match self.read_line() {
1350                        Some(line) => kv.extend_from_slice(trim_ascii_space(line)),
1351                        None => break,
1352                    }
1353                }
1354                let malformed = || format!("malformed MIME header line: {}", cpa_common::gostr::quote(&kv));
1355                let colon = kv.iter().position(|&b| b == b':').unwrap_or(kv.len());
1356                let (key, value) = (&kv[..colon], &kv[(colon + 1).min(kv.len())..]);
1357                if !key.iter().all(|&b| is_header_field_byte(b) || b == b' ') {
1358                    return Err(malformed());
1359                }
1360                if value.iter().any(|&b| (b < 0x20 && b != b'\t') || b == 0x7f) {
1361                    return Err(malformed());
1362                }
1363                headers_left -= 1;
1364                if headers_left < 0 {
1365                    return Err(TOO_LARGE.into());
1366                }
1367                let value: Vec<u8> = value
1368                    .iter()
1369                    .skip_while(|&&b| b == b' ' || b == b'\t')
1370                    .copied()
1371                    .collect();
1372                // Keys with a space are kept verbatim, so `Header.Get` never finds them.
1373                let canonical = if key.contains(&b' ') {
1374                    String::from_utf8_lossy(key).into_owned()
1375                } else {
1376                    String::from_utf8_lossy(key).to_ascii_lowercase()
1377                };
1378                if keys.insert(canonical.clone()) {
1379                    memory_left -= key.len() as i64 + 200;
1380                }
1381                memory_left -= value.len() as i64;
1382                if memory_left < 0 {
1383                    return Err(TOO_LARGE.into());
1384                }
1385                let slot = match canonical.as_str() {
1386                    "content-disposition" => &mut disposition,
1387                    "content-transfer-encoding" => &mut encoding,
1388                    _ => continue,
1389                };
1390                slot.get_or_insert_with(|| String::from_utf8_lossy(&value).into_owned());
1391            }
1392            let name = match disposition.map(|d| crate::openai_compat_multipart::parse_media_type(&d)) {
1393                Some(MediaType::Ok(kind, params)) if kind == "form-data" => {
1394                    params.get("name").cloned().unwrap_or_default()
1395                }
1396                _ => String::new(),
1397            };
1398            Ok(Some(Part {
1399                name,
1400                quoted_printable: encoding.is_some_and(|e| e.eq_ignore_ascii_case("quoted-printable")),
1401            }))
1402        }
1403
1404        /// The current part's body up to its closing boundary (`partReader`), and the
1405        /// read error that ended it early.
1406        pub fn body(&mut self) -> (Vec<u8>, Option<String>) {
1407            let mut nl_dash = self.nl.to_vec();
1408            nl_dash.extend_from_slice(&self.dash_boundary);
1409            let mut data = Vec::new();
1410            let mut total = 0;
1411            loop {
1412                let rest = &self.buf[self.pos..];
1413                let (n, scan) = scan_until_boundary(rest, &self.dash_boundary, &nl_dash, total);
1414                data.extend_from_slice(&rest[..n]);
1415                self.pos += n;
1416                total += n;
1417                match scan {
1418                    Scan::Data => {}
1419                    Scan::End => return (data, None),
1420                    Scan::UnexpectedEof => return (data, Some("unexpected EOF".into())),
1421                }
1422            }
1423        }
1424    }
1425
1426    /// What `NextPart` tells the caller about a part.
1427    pub struct Part {
1428        /// `FormName()`.
1429        pub name: String,
1430        /// `Content-Transfer-Encoding: quoted-printable` (case-insensitive).
1431        pub quoted_printable: bool,
1432    }
1433
1434    /// `io.ReadAll(quotedprintable.NewReader(part))` (mime/quotedprintable/reader.go):
1435    /// `=XX` escapes (lower-case hex too), `=` soft breaks before LF or CRLF, a lone
1436    /// `=` that is not followed by two hex digits kept literally, trailing white space
1437    /// dropped. `read_error` is the part reader's own failure after `data`.
1438    pub fn quoted_printable(data: &[u8], read_error: Option<String>) -> Result<Vec<u8>, String> {
1439        let hex = |b: u8| match b {
1440            b'0'..=b'9' => Ok(b - b'0'),
1441            b'A'..=b'F' => Ok(b - b'A' + 10),
1442            b'a'..=b'f' => Ok(b - b'a' + 10),
1443            _ => Err(format!("quotedprintable: invalid hex byte 0x{b:02x}")),
1444        };
1445        let mut out = Vec::with_capacity(data.len());
1446        let mut rest = data;
1447        while !rest.is_empty() {
1448            // `ReadSlice('\n')`: the last line ends with the reader's error instead.
1449            let end = rest.iter().position(|&b| b == b'\n').map_or(rest.len(), |i| i + 1);
1450            let whole = &rest[..end];
1451            rest = &rest[end..];
1452            let at_eof = rest.is_empty() && !whole.ends_with(b"\n") && read_error.is_none();
1453            let kept = whole.len()
1454                - whole
1455                    .iter()
1456                    .rev()
1457                    .take_while(|b| matches!(b, b'\n' | b'\r' | b' ' | b'\t'))
1458                    .count();
1459            let mut line = whole[..kept].to_vec();
1460            let mut line_error = None;
1461            if line.ends_with(b"=") {
1462                let tail = &whole[kept..];
1463                let right = &tail[tail.iter().take_while(|b| matches!(b, b' ' | b'\t')).count()..];
1464                line.pop();
1465                if !right.starts_with(b"\n")
1466                    && !right.starts_with(b"\r\n")
1467                    && !(right.is_empty() && !line.is_empty() && at_eof)
1468                {
1469                    line_error = Some(format!(
1470                        "quotedprintable: invalid bytes after =: {}",
1471                        cpa_common::gostr::quote(right)
1472                    ));
1473                }
1474            } else if whole.ends_with(b"\r\n") {
1475                line.extend_from_slice(b"\r\n");
1476            } else if whole.ends_with(b"\n") {
1477                line.push(b'\n');
1478            }
1479            let mut i = 0;
1480            while i < line.len() {
1481                let b = line[i];
1482                match b {
1483                    b'=' => match line.get(i + 1..i + 3) {
1484                        Some(pair) => match hex(pair[0]).and_then(|hi| Ok(hi << 4 | hex(pair[1])?)) {
1485                            Ok(byte) => {
1486                                out.push(byte);
1487                                i += 3;
1488                                continue;
1489                            }
1490                            Err(_) if !matches!(line[i + 1], b'\r' | b'\n') => out.push(b'='),
1491                            Err(e) => return Err(e),
1492                        },
1493                        None if line.len() - i >= 2 && !matches!(line[i + 1], b'\r' | b'\n') => out.push(b'='),
1494                        None => return Err("unexpected EOF".into()),
1495                    },
1496                    b'\t' | b'\r' | b'\n' | 0x80..=0xff => out.push(b),
1497                    b if !(b' '..=b'~').contains(&b) => {
1498                        return Err(format!("quotedprintable: invalid unescaped byte 0x{b:02x} in body"));
1499                    }
1500                    b => out.push(b),
1501                }
1502                i += 1;
1503            }
1504            if let Some(error) = line_error {
1505                return Err(error);
1506            }
1507        }
1508        read_error.map_or(Ok(out), Err)
1509    }
1510
1511    fn scan_until_boundary(buf: &[u8], dash: &[u8], nl_dash: &[u8], total: usize) -> (usize, Scan) {
1512        if total == 0 {
1513            if buf.starts_with(dash) {
1514                return match match_after_prefix(buf, dash) {
1515                    true => (0, Scan::End),
1516                    false => (dash.len(), Scan::Data),
1517                };
1518            }
1519            if dash.starts_with(buf) {
1520                return (0, Scan::UnexpectedEof);
1521            }
1522        }
1523        if let Some(i) = buf.windows(nl_dash.len()).position(|w| w == nl_dash) {
1524            return match match_after_prefix(&buf[i..], nl_dash) {
1525                true => (i, Scan::End),
1526                false => (i + nl_dash.len(), Scan::Data),
1527            };
1528        }
1529        if nl_dash.starts_with(buf) {
1530            return (0, Scan::UnexpectedEof);
1531        }
1532        if let Some(i) = buf.iter().rposition(|&b| b == nl_dash[0])
1533            && nl_dash.starts_with(&buf[i..])
1534        {
1535            return (i, Scan::Data);
1536        }
1537        (buf.len(), Scan::UnexpectedEof)
1538    }
1539
1540    fn match_after_prefix(buf: &[u8], prefix: &[u8]) -> bool {
1541        match buf.get(prefix.len()) {
1542            None => true,
1543            Some(b' ' | b'\t' | b'\r' | b'\n') => true,
1544            Some(b'-') => buf.get(prefix.len() + 1) == Some(&b'-'),
1545            Some(_) => false,
1546        }
1547    }
1548
1549    fn skip_lwsp(b: &[u8]) -> &[u8] {
1550        let n = b.iter().take_while(|&&c| c == b' ' || c == b'\t').count();
1551        &b[n..]
1552    }
1553
1554    fn trim_ascii_space(b: &[u8]) -> &[u8] {
1555        let is_space = |c: &u8| matches!(c, b' ' | b'\t' | b'\n' | b'\r');
1556        let start = b.iter().position(|c| !is_space(c)).unwrap_or(b.len());
1557        let end = b.iter().rposition(|c| !is_space(c)).map_or(start, |i| i + 1);
1558        &b[start..end]
1559    }
1560
1561    fn is_header_field_byte(b: u8) -> bool {
1562        b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)
1563    }
1564}
1565
1566#[cfg(test)]
1567#[path = "codex_live_tests.rs"]
1568mod tests;