ante-llm 0.4.2

Streaming LLM client for Anthropic, OpenAI, Gemini and Chat Completions servers, from the Ante coding agent
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
// Copyright 2026 Antigma Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! OpenAI Responses WebSocket transport: persistent `wss://.../responses`
//! connection with `previous_response_id` + incremental input continuation.
//! See <https://developers.openai.com/api/docs/guides/websocket-mode>.
//! Produces the same [`ResponseStreamEvent`] values as the HTTP/SSE path so
//! the existing `ResponseMapper` is reused unchanged.

use anyhow::{Context, Result, bail};
use futures_util::{SinkExt, Stream, StreamExt};
use serde::Serialize;
use serde_json::{Value, json};
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use tokio::net::TcpStream;
use tokio::sync::{Mutex, OwnedMutexGuard};
use tokio_tungstenite::{
    MaybeTlsStream, WebSocketStream,
    tungstenite::{
        Error as WsError, Message,
        client::IntoClientRequest,
        handshake::client::{Request, Response},
        http::header::{HeaderName, HeaderValue},
    },
};
use tracing::{debug, info, trace, warn};

use super::reasoning_encrypted_content;
use super::types::ResponseStreamEvent;
use crate::auth::Rejection;
use crate::client::Client;
use crate::error::{LlmError, error_details};

pub(in crate::openai) type ResponseEventStream =
    Pin<Box<dyn Stream<Item = std::result::Result<ResponseStreamEvent, LlmError>> + Send>>;

/// How the Responses client carries a call. The caller picks one when it
/// builds the client.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OpenAiTransport {
    /// Every call is a POST read as server-sent events.
    HttpSse,
    /// `stream_chat` continues one conversation on a WebSocket, falling back
    /// to HTTP/SSE when the socket is unavailable. `chat` always uses
    /// HTTP/SSE. Build one client per conversation.
    WebsocketAuto,
}

impl std::fmt::Display for OpenAiTransport {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            OpenAiTransport::HttpSse => "http_sse",
            OpenAiTransport::WebsocketAuto => "websocket_auto",
        })
    }
}

/// Maximum time to wait for the initial WebSocket upgrade.
pub(in crate::openai) const WS_CONNECT_TIMEOUT: Duration = Duration::from_secs(15);

/// `OpenAI-Beta` header value sent on the WebSocket upgrade: the opt-in to
/// version 2 of the Responses WebSocket protocol.
pub(in crate::openai) const WS_BETA_HEADER_VALUE: &str = "responses_websockets=2026-02-06";

#[derive(Clone)]
pub(in crate::openai) struct ResponsesWsTransport {
    client: Client,
    session: Arc<Mutex<WebSocketSession>>,
}

impl ResponsesWsTransport {
    pub(in crate::openai) fn new(client: Client) -> Self {
        Self { client, session: Arc::new(Mutex::new(WebSocketSession::default())) }
    }

    /// Try to run this request over the WebSocket transport. `None` means the
    /// ws path is unavailable for it (start failure, or the session has fallen
    /// back for good) and the caller uses HTTP/SSE instead; the reason is
    /// logged here. Start failures never surface as request errors.
    ///
    /// The caller bounds this open together with its HTTP fallback, and may
    /// cut it at any await: the connection and its continuation leave the
    /// session while a frame is in flight, so no torn frame or stale
    /// `previous_response_id` stays behind, and the next call connects afresh.
    pub(in crate::openai) async fn stream_events<Req: Serialize + Sync>(
        &self,
        request: &Req,
    ) -> Result<Option<ResponseEventStream>, LlmError> {
        let mut guard = self.session.clone().lock_owned().await;
        if guard.fallback {
            return Ok(None);
        }
        // HTTP fallback never needs a JSON tree; only materialize it while
        // this session can still use WebSocket continuation.
        let request_body = serde_json::to_value(request)
            .map_err(|error| LlmError::request_conversion(error.into()))?;

        if guard.conn.is_none() {
            match ResponsesWsConnection::connect(&self.client).await {
                Ok(conn) => guard.conn = Some(conn),
                Err(err) => {
                    if err.permanent {
                        guard.fallback = true;
                        warn!(?err, "openai_ws permanent error; switching session to HTTP/SSE");
                    } else {
                        warn!(
                            ?err,
                            "openai_ws transient error before first event; retrying via HTTP/SSE"
                        );
                    }
                    return Ok(None);
                }
            }
        }

        let baseline = RequestBaseline::new(&request_body);
        let input_start = incremental_input_start(&guard, &request_body, &baseline);
        let previous_response_id = input_start.and(guard.last_response_id.as_deref());
        debug!(
            incremental = input_start.is_some(),
            previous_response_id = previous_response_id.unwrap_or(""),
            "openai_ws sending response.create"
        );
        let envelope =
            build_response_create_envelope(request_body, previous_response_id, input_start);

        // The continuation is connection-local (`store: false`), so it goes
        // with the connection; a completed response records the new one.
        let mut conn = guard.conn.take().expect("conn just set");
        guard.reset_baseline();
        match conn.send_json(&envelope).await {
            Ok(()) => guard.conn = Some(conn),
            Err(err) => {
                conn.close().await;
                warn!(?err, "openai_ws send failed; retrying via HTTP/SSE");
                return Ok(None);
            }
        }

        let stream = futures_util::stream::unfold(
            WsStreamState { guard: Some(guard), baseline, observed_server_item_types: Vec::new() },
            ws_stream_next,
        );

        Ok(Some(Box::pin(stream)))
    }
}

/// Outcome of a single text-frame recv from the server.
#[derive(Debug)]
enum ResponsesWsRecv {
    Event(ResponseStreamEvent),
    /// Server emitted `{"type":"error",...}`, already classified; the
    /// connection is no longer usable. Kept apart from a transport `Err`
    /// because the server definitively rejected this request, so the
    /// continuation baseline survives (see [`ws_stream_next`]), whereas a
    /// transport failure leaves it unknown whether the server completed.
    Error(LlmError),
    /// Stream ended without a terminal response event.
    Closed,
}

struct ResponsesWsConnection {
    stream: WebSocketStream<MaybeTlsStream<TcpStream>>,
    idle_timeout: Duration,
}

impl ResponsesWsConnection {
    /// Open a new connection. Layers headers: provider static, then auth,
    /// then a mandatory `OpenAI-Beta: responses_websockets=...` override.
    /// An upgrade has no resend path, so a `401`/`403` is answered by asking
    /// the auth layer to recover the credential and connecting again once;
    /// a second rejection is a permanent [`ConnectError`], so the session
    /// falls back for good.
    async fn connect(client: &Client) -> Result<Self, ConnectError> {
        let ws_url = derive_ws_url(client.base_url()).map_err(ConnectError::permanent)?;
        let upgrade = client
            .auth()
            .source()
            .call(
                |token| {
                    let ws_url = ws_url.clone();
                    let headers = client.transport_headers(token.as_ref());
                    async move {
                        let mut request = ws_url
                            .as_str()
                            .into_client_request()
                            .with_context(|| format!("failed to build ws request for {ws_url}"))
                            .map_err(ConnectError::permanent)?;
                        let mut headers = headers
                            .map_err(|error| ConnectError::permanent(anyhow::Error::new(error)))?;
                        // Replace any provider-supplied OpenAI-Beta with the V2 WS value.
                        headers.insert(
                            HeaderName::from_static("openai-beta"),
                            HeaderValue::from_static(WS_BETA_HEADER_VALUE),
                        );
                        request.headers_mut().extend(headers);

                        debug!(url = %ws_url, "openai_ws connecting");
                        tokio::time::timeout(WS_CONNECT_TIMEOUT, dial(request)).await.map_err(
                            |_| {
                                ConnectError::transient(anyhow::anyhow!(
                                    "openai websocket connect timed out"
                                ))
                            },
                        )
                    }
                },
                |outcome| match outcome {
                    Ok(Err(tokio_tungstenite::tungstenite::Error::Http(response))) => {
                        Rejection::from_status(response.status())
                    }
                    _ => None,
                },
            )
            .await
            .map_err(|error| ConnectError::permanent(anyhow::Error::new(error)))??;

        match upgrade {
            Ok((stream, _resp)) => Ok(Self { stream, idle_timeout: client.stream_idle_timeout() }),
            Err(err) => Err(map_handshake_error(err)),
        }
    }

    async fn send_json<T: Serialize>(&mut self, value: &T) -> Result<()> {
        let payload = serde_json::to_string(value)?;
        trace!(payload_len = payload.len(), "openai_ws send");
        self.stream
            .send(Message::Text(payload.into()))
            .await
            .context("failed to send websocket payload")?;
        Ok(())
    }

    /// Receive one Responses event, skipping ping/pong and surfacing wrapped
    /// `{"type":"error",...}` envelopes. A connection that goes idle or dies
    /// mid-response is `UnexpectedEof`, so the caller may reconnect as on
    /// the SSE path; an undecodable frame on a live connection is
    /// `MalformedResponse`.
    async fn recv_response_event(&mut self) -> std::result::Result<ResponsesWsRecv, LlmError> {
        loop {
            let next = tokio::time::timeout(self.idle_timeout, self.stream.next()).await;
            match next {
                Err(_) => {
                    return Err(LlmError::unexpected_eof(format!(
                        "openai websocket idle for {:?}",
                        self.idle_timeout
                    )));
                }
                Ok(None) => return Ok(ResponsesWsRecv::Closed),
                Ok(Some(Err(err))) => {
                    return Err(LlmError::unexpected_eof(format!(
                        "openai websocket recv error: {err}"
                    )));
                }
                Ok(Some(Ok(Message::Text(t)))) => {
                    trace!(payload_len = t.len(), "openai_ws recv");
                    let text: &str = t.as_ref();
                    let value: Value = serde_json::from_str(text).map_err(|err| {
                        debug!(%text, "openai_ws frame is not valid JSON");
                        LlmError::malformed_response(format!(
                            "failed to parse openai_ws frame as JSON: {err}"
                        ))
                    })?;
                    if let Some(err) = parse_wrapped_error(&value) {
                        return Ok(ResponsesWsRecv::Error(err));
                    }
                    let event: ResponseStreamEvent =
                        serde_json::from_value(value).map_err(|err| {
                            debug!(%text, "openai_ws frame is not a ResponseStreamEvent");
                            LlmError::malformed_response(format!(
                                "failed to parse openai_ws frame as ResponseStreamEvent: {err}"
                            ))
                        })?;
                    return Ok(ResponsesWsRecv::Event(event));
                }
                Ok(Some(Ok(Message::Binary(_)))) => {
                    return Err(LlmError::malformed_response(
                        "unexpected binary frame from openai ws",
                    ));
                }
                Ok(Some(Ok(Message::Close(frame)))) => {
                    debug!(?frame, "openai_ws closed by server");
                    return Ok(ResponsesWsRecv::Closed);
                }
                Ok(Some(Ok(Message::Ping(_) | Message::Pong(_) | Message::Frame(_)))) => continue,
            }
        }
    }

    async fn close(mut self) {
        let _ = self.stream.close(None).await;
    }
}

type Dialed = (WebSocketStream<MaybeTlsStream<TcpStream>>, Response);

/// Open the socket. With the `rustls` feature, `wss://` goes through rustls on
/// aws-lc-rs with the bundled Mozilla roots. The provider is chosen here
/// rather than left to rustls's process default, which panics when the
/// consumer's dependency graph enables no provider, or two.
#[cfg(feature = "rustls")]
async fn dial(request: Request) -> Result<Dialed, WsError> {
    use rustls::{ClientConfig, RootCertStore, crypto::aws_lc_rs};
    use tokio_tungstenite::{Connector, tungstenite::error::TlsError};

    let roots = RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
    let config = ClientConfig::builder_with_provider(Arc::new(aws_lc_rs::default_provider()))
        .with_safe_default_protocol_versions()
        .map_err(|error| TlsError::Rustls(Box::new(error)))?
        .with_root_certificates(roots)
        .with_no_client_auth();
    let connector = Connector::Rustls(Arc::new(config));
    tokio_tungstenite::connect_async_tls_with_config(request, None, false, Some(connector)).await
}

/// Open the socket with whatever TLS tokio-tungstenite was built with
/// (`native-tls`), or none.
#[cfg(not(feature = "rustls"))]
async fn dial(request: Request) -> Result<Dialed, WsError> {
    tokio_tungstenite::connect_async(request).await
}

/// Connect-time failure with a hint whether the WS path is unusable for the
/// rest of the session (auth / setup errors) vs transient (timeout / one-off
/// handshake glitch).
#[derive(Debug, thiserror::Error)]
#[error("openai websocket connect failed: {error:#}")]
pub(in crate::openai) struct ConnectError {
    pub permanent: bool,
    pub error: anyhow::Error,
}

impl ConnectError {
    fn transient(err: impl Into<anyhow::Error>) -> Self {
        Self { permanent: false, error: err.into() }
    }
    fn permanent(err: impl Into<anyhow::Error>) -> Self {
        Self { permanent: true, error: err.into() }
    }
}

fn map_handshake_error(err: tokio_tungstenite::tungstenite::Error) -> ConnectError {
    use tokio_tungstenite::tungstenite::Error as WsErr;
    match err {
        WsErr::Http(response) => {
            let status = response.status().as_u16();
            let body = response
                .body()
                .as_ref()
                .and_then(|b| std::str::from_utf8(b).ok())
                .unwrap_or("<no body>")
                .to_string();
            let err = anyhow::anyhow!("openai ws handshake HTTP {status}: {body}");
            if status == 401 || status == 403 {
                ConnectError::permanent(err)
            } else {
                ConnectError::transient(err)
            }
        }
        other => ConnectError::transient(anyhow::anyhow!("openai ws handshake: {other}")),
    }
}

/// `https://host/v1` → `wss://host/v1/responses` (and `http` → `ws` for tests).
fn derive_ws_url(base_url: &str) -> Result<url::Url> {
    let mut ws = url::Url::parse(base_url).context("invalid provider base_url")?;
    let scheme = match ws.scheme() {
        "https" => Some("wss"),
        "http" => Some("ws"),
        "ws" | "wss" => None,
        other => bail!("unsupported scheme for websocket transport: {other}"),
    };
    if let Some(scheme) = scheme {
        ws.set_scheme(scheme).map_err(|()| anyhow::anyhow!("failed to set scheme to {scheme}"))?;
    }
    let trimmed = ws.path().trim_end_matches('/');
    let path = if trimmed.ends_with("/responses") {
        trimmed.to_string()
    } else if trimmed.is_empty() {
        "/responses".to_string()
    } else {
        format!("{trimmed}/responses")
    };
    ws.set_path(&path);
    Ok(ws)
}

/// Classify a `{"type":"error",...}` server frame like a `response.failed`
/// event, so the provider code (e.g. context overflow) survives exactly as
/// on the HTTP/SSE path; `None` for normal events.
fn parse_wrapped_error(value: &Value) -> Option<LlmError> {
    if value.get("type").and_then(|v| v.as_str()) != Some("error") {
        return None;
    }
    // `code` for OpenAI's own frames, `type` for OpenAI-compatible gateways
    // (e.g. OpenCode zen) — same fallback order as `classify_http_response`.
    let (code, message) = error_details(value, &["code", "type"]);
    let message = message.unwrap_or_else(|| "openai websocket error".to_string());
    Some(super::failed_error(code, message))
}

/// The state of one WebSocket session. One per [`super::OpenAi`] instance,
/// which the caller builds per conversation. `fallback=true` routes every
/// later call over HTTP/SSE.
#[derive(Default)]
pub(in crate::openai) struct WebSocketSession {
    conn: Option<ResponsesWsConnection>,
    pub(in crate::openai) fallback: bool,
    pub(in crate::openai) last_response_id: Option<String>,
    baseline: Option<RequestBaseline>,
    /// `type` of each server-added output item counted into the baseline, in
    /// order. The next request re-emits them as input items of the same type.
    baseline_server_item_types: Vec<String>,
}

impl WebSocketSession {
    pub(in crate::openai) fn reset_baseline(&mut self) {
        self.last_response_id = None;
        self.baseline = None;
        self.baseline_server_item_types = Vec::new();
    }

    pub(in crate::openai) fn drop_connection(&mut self) {
        self.conn = None;
    }
}

/// Enough of a sent request to validate continuation without retaining its
/// text or attachment payloads. Calculated before the body becomes a delta.
#[derive(Default)]
struct RequestBaseline {
    fingerprint: Value,
    input_hashes: Vec<u64>,
}

impl RequestBaseline {
    fn new(request_body: &Value) -> Self {
        Self {
            fingerprint: request_fingerprint(request_body),
            input_hashes: request_body
                .get("input")
                .and_then(Value::as_array)
                .map(|items| items.iter().map(input_item_hash).collect())
                .unwrap_or_default(),
        }
    }
}

/// Build the `response.create` envelope. Mirrors the HTTP POST body but adds
/// a `type` tag, drops `stream` (responses always stream on this transport),
/// and optionally drops the cached input prefix for incremental continuation.
pub(in crate::openai) fn build_response_create_envelope(
    request_body: Value,
    previous_response_id: Option<&str>,
    input_start: Option<usize>,
) -> Value {
    let mut envelope = match request_body {
        Value::Object(fields) => fields,
        _ => serde_json::Map::new(),
    };
    envelope.entry("type").or_insert_with(|| json!("response.create"));
    envelope.remove("stream");
    if let Some(start) = input_start
        && let Some(Value::Array(input)) = envelope.get_mut("input")
    {
        input.drain(..start);
    }
    if let Some(prev) = previous_response_id {
        envelope.insert("previous_response_id".to_string(), json!(prev));
    }
    Value::Object(envelope)
}

/// Request body minus `input` and `stream` — the parts that must match across
/// turns for incremental continuation to be safe.
pub(in crate::openai) fn request_fingerprint(request_body: &Value) -> Value {
    let mut map = serde_json::Map::new();
    if let Some(obj) = request_body.as_object() {
        for (k, v) in obj {
            if k == "input" || k == "stream" {
                continue;
            }
            map.insert(k.clone(), v.clone());
        }
    }
    Value::Object(map)
}

/// Hash of one `input` item, for cheap prefix comparison across turns without
/// retaining a copy of the full input array. Conversion is deterministic, so
/// an unchanged message hashes identically on the next turn.
fn input_item_hash(item: &Value) -> u64 {
    let mut hasher = DefaultHasher::new();
    item.hash(&mut hasher);
    hasher.finish()
}

/// First input item to send if the new request can resume from the cached
/// response, else `None` (caller must send full input without `previous_response_id`).
fn incremental_input_start(
    session: &WebSocketSession,
    new_request_body: &Value,
    new_baseline: &RequestBaseline,
) -> Option<usize> {
    let response_id = session.last_response_id.as_ref()?;
    if response_id.is_empty() {
        return None;
    }
    let baseline = session.baseline.as_ref()?;
    if baseline.fingerprint != new_baseline.fingerprint {
        return None;
    }
    let new_input = new_request_body.get("input")?.as_array()?;
    let prior_len = baseline.input_hashes.len();
    let baseline_len = prior_len + session.baseline_server_item_types.len();
    if new_input.len() < baseline_len {
        return None;
    }
    // A rewritten history invalidates `previous_response_id`: the server's
    // cached context no longer matches what the caller now sends.
    // The new input must start with the previous request's exact items,
    // followed by the server-added items the next turn re-emits.
    if !new_baseline.input_hashes.starts_with(&baseline.input_hashes) {
        return None;
    }
    let server_items_match = new_input[prior_len..baseline_len]
        .iter()
        .map(|item| item.get("type").and_then(|v| v.as_str()).unwrap_or(""))
        .eq(session.baseline_server_item_types.iter().map(String::as_str));
    if !server_items_match {
        return None;
    }
    Some(baseline_len)
}

/// Update session baseline after a successful response.
fn record_successful_response(
    session: &mut WebSocketSession,
    baseline: RequestBaseline,
    response_id: &str,
    server_item_types: Vec<String>,
) {
    session.last_response_id = Some(response_id.to_string());
    session.baseline = Some(baseline);
    session.baseline_server_item_types = server_item_types;
}

/// The server output items the next request replays as input.
fn replayed_server_item_type(item: &Value) -> Option<&str> {
    match item.get("type").and_then(Value::as_str) {
        Some(kind @ ("message" | "function_call")) => Some(kind),
        Some(kind @ "reasoning") if reasoning_encrypted_content(item).is_some() => Some(kind),
        // Any other item stays in the server's connection-local cache and
        // never enters a request's input.
        _ => None,
    }
}

#[cfg(test)]
fn replayed_server_item_types(items: &[Value]) -> Vec<String> {
    items.iter().filter_map(replayed_server_item_type).map(str::to_string).collect()
}

struct WsStreamState {
    guard: Option<OwnedMutexGuard<WebSocketSession>>,
    baseline: RequestBaseline,
    observed_server_item_types: Vec<String>,
}

impl Drop for WsStreamState {
    /// A stream dropped before its terminal event, as a cancelled call drops
    /// it, abandons its response mid-flight. The connection still holds that
    /// response's unread frames, and the next request would read them as its
    /// own answer. Discard it, as the in-band error exits do.
    fn drop(&mut self) {
        if let Some(guard) = self.guard.as_mut() {
            guard.drop_connection();
            guard.reset_baseline();
        }
    }
}

async fn ws_stream_next(
    mut state: WsStreamState,
) -> Option<(std::result::Result<ResponseStreamEvent, LlmError>, WsStreamState)> {
    let guard = state.guard.as_mut()?;
    let conn = guard.conn.as_mut()?;

    let recv = match conn.recv_response_event().await {
        Ok(recv) => recv,
        Err(err) => {
            guard.drop_connection();
            guard.reset_baseline();
            state.guard = None;
            return Some((Err(err), state));
        }
    };

    match recv {
        ResponsesWsRecv::Event(event) => {
            if event.kind == "response.output_item.done"
                && let Some(kind) = event.item.as_ref().and_then(replayed_server_item_type)
            {
                state.observed_server_item_types.push(kind.to_string());
            }
            let terminal = matches!(
                event.kind.as_str(),
                "response.completed" | "response.done" | "response.failed" | "response.incomplete"
            );
            if terminal {
                if matches!(event.kind.as_str(), "response.completed" | "response.done") {
                    let response_id = event
                        .response
                        .as_ref()
                        .and_then(|response| response.get("id"))
                        .and_then(Value::as_str)
                        .unwrap_or_default();
                    update_session_after_complete(&mut state, response_id);
                } else if let Some(guard) = state.guard.as_mut() {
                    guard.reset_baseline();
                }
                state.guard = None;
            }
            Some((Ok(event), state))
        }
        ResponsesWsRecv::Error(err) => {
            let code = err.detail.provider_code.as_deref();
            warn!(?code, message = %err.detail.message, "openai_ws wrapped error");
            guard.drop_connection();
            if code == Some("previous_response_not_found") {
                guard.reset_baseline();
            }
            state.guard = None;
            // The driver hands a raw-stream `Err` to the consumer unchanged.
            Some((Err(err), state))
        }
        ResponsesWsRecv::Closed => {
            guard.drop_connection();
            state.guard = None;
            None
        }
    }
}

fn update_session_after_complete(state: &mut WsStreamState, response_id: &str) {
    let Some(guard) = state.guard.as_mut() else { return };
    if response_id.is_empty() {
        warn!("openai_ws response.completed missing id; resetting baseline");
        guard.reset_baseline();
        return;
    }
    info!(
        response_id = %response_id,
        baseline = state.baseline.input_hashes.len() + state.observed_server_item_types.len(),
        "openai_ws response complete, baseline updated"
    );
    record_successful_response(
        guard,
        std::mem::take(&mut state.baseline),
        response_id,
        std::mem::take(&mut state.observed_server_item_types),
    );
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::LlmErrorKind;
    use serde_json::json;
    use std::collections::BTreeMap;

    /// Nothing else in this crate's graph installs a rustls provider, so a
    /// handshake left to the process default would panic here.
    #[cfg(feature = "rustls")]
    #[tokio::test]
    async fn wss_handshake_needs_no_process_crypto_provider() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let port = listener.local_addr().unwrap().port();
        tokio::spawn(async move { drop(listener.accept().await) });
        let request = format!("wss://127.0.0.1:{port}/").into_client_request().unwrap();
        assert!(dial(request).await.is_err());
    }

    #[tokio::test]
    async fn permanent_fallback_skips_json_conversion() {
        let transport = ResponsesWsTransport::new(crate::test_support::unauthenticated(
            "http://localhost:1".to_string(),
        ));
        // Tuple keys cannot be JSON object keys. Conversion errors remain
        // request errors while WS is active, but fallback must not serialize.
        let request = BTreeMap::from([((1, 2), "not a JSON key")]);
        assert!(matches!(
            transport.stream_events(&request).await,
            Err(error) if error.kind == LlmErrorKind::InvalidRequest
        ));

        transport.session.lock().await.fallback = true;
        assert!(transport.stream_events(&request).await.unwrap().is_none());
    }

    #[test]
    fn derive_ws_url_replaces_scheme_and_appends_responses() {
        let url = derive_ws_url("https://api.openai.com/v1").unwrap();
        assert_eq!(url.as_str(), "wss://api.openai.com/v1/responses");

        let url = derive_ws_url("http://localhost:1234/").unwrap();
        assert_eq!(url.as_str(), "ws://localhost:1234/responses");

        let url = derive_ws_url("http://127.0.0.1:8080/v9").unwrap();
        assert_eq!(url.as_str(), "ws://127.0.0.1:8080/v9/responses");

        let url = derive_ws_url("ws://127.0.0.1:8080/v1/responses").unwrap();
        assert_eq!(url.as_str(), "ws://127.0.0.1:8080/v1/responses");

        assert!(derive_ws_url("ftp://nope").is_err());
    }

    #[test]
    fn parse_wrapped_error_classifies_the_frame() {
        use crate::error::LlmErrorKind;

        let v = json!({
            "type": "error",
            "status": 429,
            "error": { "code": "rate_limit_exceeded", "message": "slow down" }
        });
        let err = parse_wrapped_error(&v).expect("expected wrapped error");
        assert_eq!(err.kind, LlmErrorKind::RateLimited);
        assert_eq!(err.detail.provider_code.as_deref(), Some("rate_limit_exceeded"));
        assert_eq!(err.detail.message, "slow down");

        // Gateways relaying class-named errors carry the code in `error.type`
        // (no `code` field), e.g. OpenCode zen's usage-limit errors.
        let typed = json!({
            "type": "error",
            "error": { "type": "FreeUsageLimitError", "message": "Rate limit exceeded." }
        });
        let err = parse_wrapped_error(&typed).expect("expected wrapped error");
        assert_eq!(err.kind, LlmErrorKind::Quota);
        assert_eq!(err.detail.provider_code.as_deref(), Some("FreeUsageLimitError"));

        // Non-error frames pass through.
        let regular = json!({ "type": "response.output_text.delta", "delta": "hi" });
        assert!(parse_wrapped_error(&regular).is_none());
    }

    #[test]
    fn response_create_preserves_decorated_fields() {
        let body = json!({
            "model": "gpt-5",
            "input": [
                {"type": "message", "content": "full history"},
                {"type": "message", "content": "new turn"}
            ],
            "stream": true,
            "service_tier": "priority"
        });
        let envelope = build_response_create_envelope(body, Some("resp_1"), Some(1));

        assert_eq!(envelope["type"], "response.create");
        assert_eq!(envelope["service_tier"], "priority");
        assert_eq!(envelope["previous_response_id"], "resp_1");
        assert_eq!(envelope["input"], json!([{"type": "message", "content": "new turn"}]));
        assert!(envelope.get("stream").is_none());
    }

    #[test]
    fn incremental_delta_basic_flow() {
        let mut session = WebSocketSession::default();

        let request1 = json!({
            "model": "gpt-5",
            "instructions": "be helpful",
            "tools": [],
            "input": [
                {"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}
            ]
        });
        // First turn: nothing cached -> no delta possible.
        assert!(
            incremental_input_start(&session, &request1, &RequestBaseline::new(&request1))
                .is_none()
        );

        // Simulate completion: server emitted one assistant message.
        let output = vec![json!({
            "type": "message",
            "role": "assistant",
            "content": [{"type":"output_text","text":"hello"}]
        })];
        record_successful_response(
            &mut session,
            RequestBaseline::new(&request1),
            "resp_1",
            replayed_server_item_types(&output),
        );

        // Second turn: same fingerprint, input strictly extends.
        let request2 = json!({
            "model": "gpt-5",
            "instructions": "be helpful",
            "tools": [],
            "input": [
                {"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]},
                {"type":"message","role":"assistant","content":[{"type":"output_text","text":"hello"}]},
                {"type":"message","role":"user","content":[{"type":"input_text","text":"again"}]}
            ]
        });
        let start = incremental_input_start(&session, &request2, &RequestBaseline::new(&request2))
            .expect("expected delta");
        let envelope = build_response_create_envelope(request2, Some("resp_1"), Some(start));
        assert_eq!(envelope["input"].as_array().unwrap().len(), 1);
        assert_eq!(envelope["input"][0]["content"][0]["text"], "again");
    }

    #[test]
    fn incremental_rejected_when_prefix_rewritten() {
        let mut session = WebSocketSession::default();
        let request1 = json!({
            "model": "gpt-5",
            "instructions": "be helpful",
            "tools": [],
            "input": [
                {"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}
            ]
        });
        let output = vec![json!({
            "type": "message",
            "role": "assistant",
            "content": [{"type":"output_text","text":"hello"}]
        })];
        record_successful_response(
            &mut session,
            RequestBaseline::new(&request1),
            "resp_1",
            replayed_server_item_types(&output),
        );

        // The caller rewrote history: same fingerprint and a long-enough
        // input, but the first item no longer matches the cached baseline.
        let request2 = json!({
            "model": "gpt-5",
            "instructions": "be helpful",
            "tools": [],
            "input": [
                {"type":"message","role":"user","content":[{"type":"input_text","text":"<summary of earlier conversation>"}]},
                {"type":"message","role":"assistant","content":[{"type":"output_text","text":"hello"}]},
                {"type":"message","role":"user","content":[{"type":"input_text","text":"again"}]}
            ]
        });
        assert!(
            incremental_input_start(&session, &request2, &RequestBaseline::new(&request2))
                .is_none(),
            "rewritten prefix must disable incremental continuation"
        );
    }

    #[test]
    fn incremental_rejected_when_server_item_type_differs() {
        let mut session = WebSocketSession::default();
        let request1 = json!({
            "model": "gpt-5",
            "instructions": "be helpful",
            "tools": [],
            "input": [
                {"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}
            ]
        });
        // Server emitted a function_call, but the next request carries a
        // message in that position — history no longer lines up.
        let output = vec![json!({
            "type": "function_call",
            "call_id": "call_1",
            "name": "do_it",
            "arguments": "{}"
        })];
        record_successful_response(
            &mut session,
            RequestBaseline::new(&request1),
            "resp_1",
            replayed_server_item_types(&output),
        );

        let request2 = json!({
            "model": "gpt-5",
            "instructions": "be helpful",
            "tools": [],
            "input": [
                {"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]},
                {"type":"message","role":"assistant","content":[{"type":"output_text","text":"hello"}]},
                {"type":"message","role":"user","content":[{"type":"input_text","text":"again"}]}
            ]
        });
        assert!(
            incremental_input_start(&session, &request2, &RequestBaseline::new(&request2))
                .is_none()
        );
    }

    #[test]
    fn incremental_counts_reasoning_only_when_it_is_replayed() {
        // A reasoning item comes back as input when it carries its encrypted
        // content, so it counts toward the prefix; one without stays in the
        // server's connection-local cache and must not disable incremental.
        let user = |text: &str| json!({"type":"message","role":"user","content":[{"type":"input_text","text":text}]});
        let message = json!({"type":"message","role":"assistant","content":[]});
        let replayed = json!({"type":"reasoning","summary":[],"encrypted_content":"enc..."});
        for (reasoning, replay, expected) in [
            (json!({"type":"reasoning","id":"r1","encrypted_content":"enc..."}), Some(replayed), 3),
            (json!({"type":"reasoning","id":"r1"}), None, 2),
        ] {
            let mut session = WebSocketSession::default();
            let request1 = json!({"model": "o4-mini", "tools": [], "input": [user("hi")]});
            record_successful_response(
                &mut session,
                RequestBaseline::new(&request1),
                "resp_1",
                replayed_server_item_types(&[reasoning, message.clone()]),
            );

            let mut input = vec![user("hi")];
            input.extend(replay);
            input.extend([message.clone(), user("more")]);
            let request2 = json!({"model": "o4-mini", "tools": [], "input": input});
            let start =
                incremental_input_start(&session, &request2, &RequestBaseline::new(&request2))
                    .expect("incremental should be possible with reasoning output");
            assert_eq!(start, expected);
        }
    }
}