cpa-exec 0.4.4

Part of cliproxy: upstream provider executors
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
//! OpenAI-compatible upstreams (internal/runtime/executor/openai_compat_executor.go):
//! configured providers reached with a bearer API key at `base_url`, speaking Chat
//! Completions, Responses compact and the Images API.

use std::collections::VecDeque;
use std::time::SystemTime;

use bytes::Bytes;
use cpa_core::config::Config;
use cpa_core::credential::Credential;
use cpa_core::exec::{ExecError, ExecRequest, ExecResponse, ExecStream, FailureScope, Operation, ResponseBody};
use cpa_core::format::Format;
use cpa_translate::{RequestCtx, ResponseCtx, StreamTranslator};
use futures_util::StreamExt;

use cpa_common::gostr::GoStr;
use cpa_common::json as gj;
use cpa_common::thinking::{self, ModelCaps, RequestThinking, parse_suffix};

use crate::gemini_stream::ClaudeInputTokens;
use crate::openai_compat_go as go;
use crate::openai_compat_http::{self as wire, Clients, GoHeaders};
use crate::openai_compat_multipart as multipart;
use crate::openai_compat_payload as payload;

pub const USER_AGENT: &str = "cli-proxy-openai-compat";
const COMPACT_ALT: &str = "responses/compact";
const IMAGES_GENERATIONS: &str = "/images/generations";
const IMAGES_EDITS: &str = "/images/edits";
/// `scanner.Buffer(nil, 52_428_800)`.
const MAX_LINE: usize = 52_428_800;
/// helps.ApplyPatchUpstreamErrorMessage: Go's error for an empty or rejected translation.
const EMPTY_TRANSLATION: &str = cpa_translate::APPLY_PATCH_UPSTREAM_ERROR;

/// Providers this executor serves: `openai-compatibility` and `openai-compatible-<name>`
/// (util.OpenAICompatibleProviderKey).
pub fn handles(provider: &str) -> bool {
    provider == "openai-compatibility" || provider.starts_with("openai-compatible-")
}

#[derive(Default)]
pub struct OpenAICompatExecutor {
    clients: Clients,
}

/// Go's plain `statusErr`: never credential-scoped, so a 429 cools only the model
/// (`IsCredentialScoped` is false); other failures by status.
pub(crate) fn scope_for(status: u16) -> FailureScope {
    match status {
        429 => FailureScope::Model,
        401 | 402 | 403 | 408 | 500.. => FailureScope::Credential,
        _ => FailureScope::Request,
    }
}

/// A plain Go error (no status code): no status, scope or retry semantics, which the
/// server models as a transport fault; Go's handler answers 500 with its text.
pub(crate) fn plain_err(message: impl Into<String>) -> ExecError {
    ExecError::local(500, FailureScope::Transport, message)
}

/// `statusErr{code, msg}`: an empty message reads `status N`.
pub(crate) fn status_err(status: u16, message: impl Into<String>) -> ExecError {
    let message = message.into();
    let message = if message.is_empty() {
        format!("status {status}")
    } else {
        message
    };
    ExecError::local(status, scope_for(status), message)
}

/// A chat non-2xx response: `newOpenAICompatStatusError` over the error body, which is
/// captured like Go's `AppendAPIResponseChunk` (read errors ignored, `b, _ :=
/// io.ReadAll`).
async fn upstream_error(upstream: wire::Upstream, capture: &wire::Capture) -> ExecError {
    let (status, headers, body) = wire::read_error_body(upstream).await;
    capture.chunk(&body);
    status_error(status, headers, &body, true)
}

/// An images non-2xx response: the whole body is read first and a read error is
/// captured and returned instead, then `newOpenAICompatStatusError`, or the plain
/// `statusErr` the image stream path uses.
async fn images_error(upstream: wire::Upstream, with_retry: bool, capture: &wire::Capture) -> ExecError {
    let (status, headers) = (upstream.status, upstream.headers.clone());
    let body = wire::read_all(upstream).await;
    capture.read(&body);
    match body {
        Ok(body) => status_error(status, headers, &body, with_retry),
        Err(error) => error,
    }
}

fn status_error(status: u16, headers: http::HeaderMap, body: &[u8], with_retry: bool) -> ExecError {
    let mut error = status_err(status, String::from_utf8_lossy(body));
    if with_retry {
        error.retry_after = payload::retry_after(status, &headers, body, SystemTime::now());
    }
    error.headers = Box::new(headers);
    error
}

fn credentials(credential: &Credential) -> (String, String) {
    let attr = |k: &str| {
        credential
            .attributes
            .get(k)
            .map(|v| v.trim().to_owned())
            .unwrap_or_default()
    };
    (attr("base_url"), attr("api_key"))
}

fn missing_base_url() -> ExecError {
    ExecError::local(401, FailureScope::Credential, "missing provider baseURL")
}

/// `strings.TrimSuffix(baseURL, "/") + path`: one slash only, like Go.
fn endpoint(base_url: &str, path: &str) -> String {
    format!("{}{path}", base_url.strip_suffix('/').unwrap_or(base_url))
}

fn not_registered(what: &str, from: Format, to: Format) -> ExecError {
    ExecError::local(
        501,
        FailureScope::Request,
        format!(
            "{what} translation {} -> {} is not registered",
            from.as_str(),
            to.as_str()
        ),
    )
}

/// `helps.TranslateRequestWithAPIKeyModelCompatibilityAndUpdateIntent` for this executor
/// (no target executor): Codex-client rewrites, then the pair or its compat variant.
// ponytail: the configuration-update intent crate::codex_client reports is not read
// here yet, so thinking always sees `updates_changed: false`, and equal original and
// working payloads are translated twice (Go translates once); the OpenAI-compatible
// port reads it.
fn translate_body(
    req: &ExecRequest,
    cfg: &Config,
    target: Format,
    model: &str,
    stream: bool,
    body: &[u8],
    is_compat: bool,
) -> Result<Vec<u8>, ExecError> {
    let client = crate::codex_client::Client::new(&req.headers, cfg, "", is_compat);
    crate::codex_client::translate_request(
        req.source_format,
        target,
        &RequestCtx {
            model,
            stream,
            tool_search: false,
        },
        body,
        &client,
    )
    .map(|t| t.body)
    .map_err(|e| ExecError::local(400, FailureScope::Request, e.to_string()))
}

/// `opts.OriginalRequest`, else the payload.
fn original_payload(req: &ExecRequest) -> &[u8] {
    if req.original_body.is_empty() {
        &req.body
    } else {
        &req.original_body
    }
}

/// `helps.ApplyPayloadConfigWithRequest` (no target executor) on the translated body;
/// `original` is the translated original request.
fn apply_payload_rules(
    cfg: &Config,
    req: &ExecRequest,
    model: &str,
    target: Format,
    original: &[u8],
    body: Vec<u8>,
) -> Vec<u8> {
    let rules = cpa_common::payload::Rules::from_config(cfg);
    cpa_common::payload::apply(
        &rules,
        &cpa_common::payload::Request {
            target_executor: "",
            model,
            requested_model: route_model(req),
            protocol: target.as_str(),
            from_protocol: req.source_format.as_str(),
            root: "",
            original,
            request_path: &req.request_path,
            headers: Some(&req.headers),
        },
        body,
    )
}

/// `helps.ApplyRequestThinking` with the capabilities bound to this attempt.
fn apply_thinking(
    body: Vec<u8>,
    req: &ExecRequest,
    target: Format,
    provider: &str,
    resolved: Option<&ModelCaps>,
) -> Result<Vec<u8>, ExecError> {
    thinking::apply_request_thinking(&RequestThinking {
        body: &body,
        payload: &req.body,
        original: &req.original_body,
        model: &req.model,
        from: req.source_format.as_str(),
        to: target.as_str(),
        provider,
        resolved: resolved.map(Some),
        has_request_transformer: cpa_translate::pair(req.source_format, target).is_some(),
        updates_changed: false,
    })
    .map_err(|e| ExecError::local(400, FailureScope::Request, e.message))
    .map(|body| {
        // Go 0e0cab0d (v8.0.64), a cliproxy-rs addition: `APIKeyModelIsCompat` and
        // Claude to OpenAI only.
        let compat = req.resolved_model.as_ref().is_some_and(|r| r.is_compat());
        if compat && req.source_format == Format::Claude && target == Format::OpenAI && !body.is_empty() {
            payload::reconcile_tool_call_reasoning(body)
        } else {
            body
        }
    })
}

fn base_headers(api_key: &str, content_type: &str) -> GoHeaders {
    let mut headers = GoHeaders::new();
    headers.set("Content-Type", content_type);
    if !api_key.is_empty() {
        headers.set("Authorization", format!("Bearer {api_key}"));
    }
    headers.set("User-Agent", USER_AGENT);
    headers
}

/// `util.ApplyCustomHeadersFromAttrs` with the client headers and the canonical session.
fn apply_custom(headers: &mut GoHeaders, credential: &Credential, req: &ExecRequest) {
    let session = cpa_common::session::cpa_session_id(req.session.as_deref());
    for (name, value) in cpa_common::headers::custom_headers(&credential.attributes, &req.headers, session.as_deref()) {
        headers.set(&name, value);
    }
}

impl OpenAICompatExecutor {
    /// Uses `client` for credentials without a proxy (tests pass a plain client).
    pub fn with_client(client: wreq::Client) -> Self {
        Self {
            clients: Clients::new(client),
        }
    }

    pub async fn execute(
        &self,
        credential: &Credential,
        req: ExecRequest,
        cfg: &Config,
    ) -> Result<ExecResponse, ExecError> {
        match req.operation {
            Operation::CountTokens => count_tokens(credential, &req, cfg),
            Operation::Generate => self.chat(credential, req, cfg).await,
        }
    }

    /// Execute (`stream` false) and ExecuteStream (`stream` true) for chat and compact.
    async fn chat(&self, credential: &Credential, req: ExecRequest, cfg: &Config) -> Result<ExecResponse, ExecError> {
        let (base_url, api_key) = credentials(credential);
        let compat = payload::resolve_compat(credential, cfg);
        let client = self.clients.for_credential(credential, cfg);
        chat_with(&client, credential, req, cfg, &base_url, &api_key, compat.as_ref()).await
    }

    /// `executeImages` / `executeImagesStream`: the body (JSON or multipart) goes to
    /// `/images/edits` or `/images/generations` with the model replaced. `request_path` is
    /// the inbound route; `req.stream` selects raw SSE passthrough.
    pub async fn images(
        &self,
        credential: &Credential,
        req: ExecRequest,
        request_path: &str,
        cfg: &Config,
    ) -> Result<ExecResponse, ExecError> {
        let base_model = parse_suffix(&req.model).model_name.trim().to_owned();
        let (base_url, api_key) = credentials(credential);
        if base_url.is_empty() {
            return Err(missing_base_url());
        }
        let client_content_type = req
            .headers
            .get(http::header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .unwrap_or_default()
            .trim()
            .to_owned();
        let (body, content_type) = prepare_images_payload(&req.body, &base_model, &client_content_type, req.stream)?;
        let content_type = if content_type.is_empty() {
            "application/json".to_owned()
        } else {
            content_type
        };
        let (body, content_type) = media_barrier(
            credential,
            &req,
            cfg,
            &base_model,
            &body,
            &content_type,
            &client_content_type,
        )?;
        let path = if request_path.trim().ends_with(IMAGES_EDITS) {
            IMAGES_EDITS
        } else {
            IMAGES_GENERATIONS
        };
        // SetTranslatedReasoningEffort(payload, "openai").
        if req.usage.enabled() {
            req.usage.request(Format::OpenAI, &body);
        }
        let mut headers = base_headers(&api_key, &content_type);
        if req.stream {
            headers.set("Accept", "text/event-stream");
            headers.set("Cache-Control", "no-cache");
        }
        apply_custom(&mut headers, credential, &req);
        let client = self.clients.for_credential(credential, cfg);
        let url = endpoint(&base_url, path);
        let capture = wire::Capture::request(
            &req,
            credential,
            &credential.provider,
            &url,
            "POST",
            headers.pairs(),
            &body,
        );
        let upstream = wire::send(&client, &url, headers, body).await;
        capture.sent(&upstream);
        let upstream = upstream?;
        if !(200..300).contains(&upstream.status) {
            return Err(images_error(upstream, !req.stream, &capture).await);
        }
        let headers = upstream.headers.clone();
        if req.stream {
            // Each raw read is logged; a read error is logged and published as a failure
            // before the client gets it.
            let usage = req.usage.clone();
            let stream = capture
                .stream(upstream.body)
                .inspect(move |item| {
                    if let Err(error) = item {
                        wire::publish_failure(&usage, error);
                    }
                })
                .boxed();
            return Ok(ExecResponse {
                status: 200,
                headers,
                body: ResponseBody::Stream(stream),
            });
        }
        let data = wire::read_all(upstream).await;
        capture.read(&data);
        let data = data?;
        if req.usage.enabled() {
            req.usage.response_body(Format::OpenAI, &data);
        }
        Ok(ExecResponse {
            status: 200,
            headers,
            body: ResponseBody::Buffered(data),
        })
    }
}

/// `executeWithCredentials` / `executeStreamWithCredentials` (Go d9451cb6): the chat
/// request at `base_url` with `api_key`, for this executor's credentials and for
/// Vertex's endpoints/openapi route (which passes no compatibility config).
pub(crate) async fn chat_with(
    client: &wreq::Client,
    credential: &Credential,
    mut req: ExecRequest,
    cfg: &Config,
    base_url: &str,
    api_key: &str,
    compat: Option<&payload::Compat>,
) -> Result<ExecResponse, ExecError> {
    if base_url.is_empty() {
        return Err(missing_base_url());
    }
    if req.operation == Operation::Generate {
        // Only CPA capsules: a native compaction item is the upstream's own context and
        // reaches `/responses/compact` (or the chat translator) as it is.
        if (crate::antigravity_compaction::has_item(&req.body)
            || crate::antigravity_compaction::has_item(&req.original_body))
            && let Err(e) = crate::antigravity_compaction::expand_capsules(&mut req)
        {
            req.usage.discard();
            return Err(status_err(400, e));
        }
        if req.alt.as_deref() != Some(COMPACT_ALT)
            && (crate::antigravity_compaction::has_trigger(&req.body)
                || crate::antigravity_compaction::has_trigger(&req.original_body))
        {
            return compact_summary(client, credential, req, cfg, base_url, api_key, compat).await;
        }
    }
    chat_request(client, credential, req, cfg, base_url, api_key, compat).await
}

/// The ordinary chat or `/responses/compact` request of [`chat_with`], also used for
/// the summary turn of [`compact_summary`].
async fn chat_request(
    client: &wreq::Client,
    credential: &Credential,
    req: ExecRequest,
    cfg: &Config,
    base_url: &str,
    api_key: &str,
    compat: Option<&payload::Compat>,
) -> Result<ExecResponse, ExecError> {
    let base_model = parse_suffix(&req.model).model_name;
    let compact = req.alt.as_deref() == Some(COMPACT_ALT);
    // ExecuteStream always targets chat completions, even with the compact alt.
    let (target, path) = if compact && !req.stream {
        (Format::OpenAIResponse, "/responses/compact")
    } else {
        (Format::OpenAI, "/chat/completions")
    };
    let response_pair = cpa_translate::pair(req.response_format, target);
    if response_pair.is_none() && req.response_format != target {
        return Err(not_registered("response", req.response_format, target));
    }
    let caps = req.resolved_model.as_ref().map(|r| ModelCaps::from(&r.info));
    let is_compat = req.resolved_model.as_ref().is_some_and(|r| r.is_compat());
    let original = translate_body(
        &req,
        cfg,
        target,
        &base_model,
        req.stream,
        original_payload(&req),
        is_compat,
    );
    let mut body = translate_body(&req, cfg, target, &base_model, req.stream, &req.body, is_compat)?;
    let original = crate::translate::baseline_or_working(original, &body);
    body = apply_thinking(body, &req, target, &credential.provider, caps.as_ref())?;
    let requested = route_model(&req);
    if payload::excludes_images(compat, &base_model, requested) {
        body = payload::normalize_tool_results_text_only(body);
    }
    if !compact {
        let mct = payload::uses_max_completion_tokens(compat, &base_model, requested);
        body = payload::normalize_max_tokens(body, mct);
        body = prompt_cache_key(compat, &credential.provider, &req, &base_model, body);
    }
    if compact && !req.stream {
        gj::delete(&mut body, "stream");
        body = payload::sanitize_reasoning_encrypted_content(body);
    }
    if req.stream {
        payload::set_bool_if_different(&mut body, "stream_options.include_usage", true);
    }
    if req.usage.enabled() {
        req.usage.request(target, &body);
    }
    // The payload rules are the last change to the body (868e137).
    body = apply_payload_rules(cfg, &req, &base_model, target, &original, body);
    let mut headers = base_headers(api_key, "application/json");
    apply_custom(&mut headers, credential, &req);
    if req.stream {
        headers.set("Accept", "text/event-stream");
        headers.set("Cache-Control", "no-cache");
    }
    let url = endpoint(base_url, path);
    // Go's `http.NewRequestWithContext` refuses a URL its parser rejects (an escaped
    // host such as `%61iplatform.googleapis.com`) and its transport one without a host
    // (`https:relay.example`), before anything is sent; the url crate would read a host
    // from both and send the key there.
    crate::xai_url::new_request(&url)?;
    let capture = wire::Capture::request(
        &req,
        credential,
        &credential.provider,
        &url,
        "POST",
        headers.pairs(),
        &body,
    );
    let upstream = match crate::xai_url::transport_refusal(&url) {
        Some(error) => Err(error),
        None => wire::send(client, &url, headers, Bytes::from(body.clone())).await,
    };
    capture.sent(&upstream);
    let upstream = upstream?;
    if !(200..300).contains(&upstream.status) {
        return Err(upstream_error(upstream, &capture).await);
    }
    let response_headers = upstream.headers.clone();
    let original = if req.original_body.is_empty() {
        req.body.clone()
    } else {
        req.original_body.clone()
    };
    if req.stream {
        let translator: Box<dyn StreamTranslator> = match response_pair {
            Some(pair) => crate::translate::stream(
                pair,
                &ResponseCtx {
                    model: &req.model,
                    original_request: &original,
                    translated_request: &body,
                    tool_search: false,
                },
                &req,
            ),
            None => Box::new(Identity),
        };
        let mut lines = wire::lines(upstream, MAX_LINE);
        if req.usage.enabled() {
            // StreamUsageBuffer.ObserveOpenAIStream per line; the served model is observed
            // per accepted frame (Frames::frame).
            let usage = req.usage.clone();
            lines = lines
                .inspect(move |line| {
                    if let Ok(line) = line {
                        usage.response_usage_line(Format::OpenAI, line);
                    }
                })
                .boxed();
        }
        let claude = ClaudeInputTokens::new(req.source_format, Format::OpenAI, req.response_format, original.clone());
        let stream = frames(
            lines,
            translator,
            claude,
            req.response_format,
            capture,
            req.usage.clone(),
        );
        return Ok(ExecResponse {
            status: 200,
            headers: response_headers,
            body: ResponseBody::Stream(stream),
        });
    }
    let raw = wire::read_all(upstream).await;
    capture.read(&raw);
    let raw = raw?;
    // ObserveResponseModel(body) and Publish(ParseOpenAIUsage(body)).
    if req.usage.enabled() {
        req.usage.response_body(target, &raw);
    }
    let ctx = ResponseCtx {
        model: &req.model,
        original_request: &original,
        translated_request: &body,
        tool_search: false,
    };
    let mut out = match response_pair {
        Some(pair) => (pair.non_stream)(&ctx, &raw)
            .map_err(|_| ExecError::local(502, FailureScope::Request, EMPTY_TRANSLATION))?,
        // Go's TranslateNonStream still runs the plugin response hooks.
        None => {
            cpa_translate::hooks::unregistered_non_stream(target.as_str(), req.response_format.as_str(), &ctx, &raw)
                .unwrap_or_else(|| raw.to_vec())
        }
    };
    if out.is_empty() {
        return Err(ExecError::local(502, FailureScope::Request, EMPTY_TRANSLATION));
    }
    if req.response_format == Format::OpenAIResponse {
        out = payload::ensure_responses_usage_details(&out);
    }
    Ok(ExecResponse {
        status: 200,
        headers: response_headers,
        body: ResponseBody::Buffered(Bytes::from(out)),
    })
}

const DEFAULT_SUMMARY_MAX_TOKENS: i64 = 8192;

/// `compaction.summary-max-tokens` and `compaction.summary-reasoning-effort`. These
/// apply only to the internal summary request: normal turns keep the client's budget
/// and effort, and an explicitly larger summary budget is never lowered.
fn summary_budget(cfg: &Config) -> (i64, Option<String>) {
    // ponytail: one global floor for every OpenAI-compatible upstream; lift this to a
    // per-provider override when a second upstream needs a different value.
    let section = cfg.document.get("compaction");
    let max_tokens = section
        .and_then(|c| c.get("summary-max-tokens"))
        .and_then(cpa_core::config::go_int)
        .unwrap_or(DEFAULT_SUMMARY_MAX_TOKENS);
    let effort = section
        .and_then(|c| c.get("summary-reasoning-effort"))
        .and_then(|v| v.as_str())
        .map(str::trim)
        .filter(|v| !v.is_empty())
        .map(str::to_owned);
    (max_tokens, effort)
}

/// Reasoning efforts an OpenAI-compatible upstream accepts in `reasoning_effort`.
const SUMMARY_EFFORTS: [&str; 5] = ["minimal", "low", "medium", "high", "xhigh"];

/// A reasoning upstream can spend the caller's whole output budget on
/// `reasoning_content` and return an empty `content`, which then looks like "no
/// summary text". Give the summary a floor, and keep its thinking short. `body` is
/// the Responses summary payload, before translation: the floor reaches the upstream
/// as `max_tokens` or `max_completion_tokens`, and the effort as `reasoning_effort`
/// after the model's thinking rules, like any client value.
fn apply_summary_budget(body: &mut Vec<u8>, max_tokens: i64, effort: Option<&str>) {
    if max_tokens > 0 && gj::get(body, "max_output_tokens").int() < max_tokens {
        gj::set_int(body, "max_output_tokens", max_tokens);
    }
    match effort {
        Some("keep") => {}
        Some(value) if SUMMARY_EFFORTS.contains(&value) => {
            gj::set_str(body, "reasoning.effort", value);
        }
        // Unset or not an OpenAI effort: lower the effort only when the client sent one.
        _ => {
            if gj::get(body, "reasoning.effort").exists() {
                gj::set_str(body, "reasoning.effort", "low");
            }
        }
    }
}

/// Responses compaction v2 for OpenAI-compatible upstreams: the trigger turn is
/// answered by an ordinary non-stream chat summary, sealed into the CPA compaction
/// capsule, so Codex gets exactly one `compaction` output item. Later requests carry
/// that capsule and are expanded by `antigravity_compaction::expand_capsules`. The
/// summary request goes through [`chat_request`], so it gets the same thinking, compatibility
/// normalization, payload rules, URL checks and capture as any chat request.
async fn compact_summary(
    client: &wreq::Client,
    credential: &Credential,
    mut req: ExecRequest,
    cfg: &Config,
    base_url: &str,
    api_key: &str,
    compat: Option<&payload::Compat>,
) -> Result<ExecResponse, ExecError> {
    let model = parse_suffix(&req.model).model_name.to_owned();
    let stream = req.stream;
    let source = crate::antigravity_compaction::source_payload(&req.body, &req.original_body);
    let mut summary = crate::antigravity_compaction::summary_payload(source);
    let (max_tokens, effort) = summary_budget(cfg);
    apply_summary_budget(&mut summary, max_tokens, effort.as_deref());
    req.body = summary.into();
    req.original_body = Bytes::new();
    req.alt = None;
    req.stream = false;
    req.source_format = Format::OpenAIResponse;
    req.response_format = Format::OpenAI;
    let answer = Box::pin(chat_request(client, credential, req, cfg, base_url, api_key, compat)).await?;
    let ResponseBody::Buffered(raw) = answer.body else {
        return Err(crate::antigravity_compaction::statusless(
            "extract summary: no summary text found in upstream response",
        ));
    };
    let text = crate::antigravity_compaction::summary_text(&raw)
        .map_err(|e| crate::antigravity_compaction::statusless(format!("extract summary: {e}")))?;
    let sealed = crate::antigravity_compaction::seal(&text, &model)
        .map_err(|e| crate::antigravity_compaction::statusless(format!("seal compaction capsule: {e}")))?;
    let usage = crate::antigravity_compaction::chat_usage(&raw);

    let mut headers = http::HeaderMap::new();
    if !stream {
        headers.insert(
            http::header::CONTENT_TYPE,
            http::HeaderValue::from_static("application/json"),
        );
        return Ok(ExecResponse {
            status: 200,
            headers,
            body: ResponseBody::Buffered(crate::antigravity_compaction::response(&model, &sealed, usage).into()),
        });
    }
    headers.insert(
        http::header::CONTENT_TYPE,
        http::HeaderValue::from_static("text/event-stream"),
    );
    let chunks: Vec<Result<Bytes, ExecError>> = crate::antigravity_compaction::stream_chunks(&model, &sealed, usage)
        .into_iter()
        .map(|chunk| Ok(Bytes::from(chunk)))
        .collect();
    Ok(ExecResponse {
        status: 200,
        headers,
        body: ResponseBody::Stream(futures_util::stream::iter(chunks).boxed()),
    })
}

/// `ApplyMediaPayloadConfig` on a prepared images request (868e137): the payload rules
/// run last, on the body's JSON view, against the client's original request.
fn media_barrier(
    credential: &Credential,
    req: &ExecRequest,
    cfg: &Config,
    model: &str,
    body: &[u8],
    content_type: &str,
    client_content_type: &str,
) -> Result<(Bytes, String), ExecError> {
    let original = if req.original_body.is_empty() {
        &req.body
    } else {
        &req.original_body
    };
    let (body, content_type) =
        crate::payload_media::apply(body, content_type, original, client_content_type, |view, original| {
            crate::payload_barrier::Barrier {
                executor: &credential.provider,
                model,
                protocol: Format::OpenAI.as_str(),
                root: "",
                original,
            }
            .apply(cfg, req, view)
        })
        .map_err(plain_err)?;
    Ok((Bytes::from(body), content_type))
}

/// `prepareOpenAICompatImagesPayload`.
pub(crate) fn prepare_images_payload(
    body: &[u8],
    model: &str,
    content_type: &str,
    stream: bool,
) -> Result<(Bytes, String), ExecError> {
    if go::json_valid(body) {
        let mut body = body.to_vec();
        if !model.is_empty() {
            payload::set_str_if_different(&mut body, "model", model);
        }
        if stream {
            payload::set_bool_if_different(&mut body, "stream", true);
        } else {
            gj::delete(&mut body, "stream");
        }
        return Ok((Bytes::from(body), "application/json".into()));
    }
    let Some(boundary) = multipart::boundary(content_type) else {
        return Ok((Bytes::copy_from_slice(body), content_type.to_owned()));
    };
    // Go returns a plain error here; the handler answers 500.
    let boundary = boundary.map_err(plain_err)?;
    let form =
        multipart::read_form(body, &boundary).map_err(|e| plain_err(format!("read multipart form failed: {e}")))?;
    let (out, content_type) = multipart::rewrite_images_form(&form, model, stream, false);
    Ok((Bytes::from(out), content_type))
}

/// `helps.PayloadRequestedModel`: the client's model, else the execution model.
fn route_model(req: &ExecRequest) -> &str {
    if req.requested_model.trim().is_empty() {
        req.model.trim()
    } else {
        req.requested_model.trim()
    }
}

/// `applyPromptCacheKey`.
fn prompt_cache_key(
    compat: Option<&payload::Compat>,
    provider: &str,
    req: &ExecRequest,
    base_model: &str,
    mut body: Vec<u8>,
) -> Vec<u8> {
    if !compat.is_some_and(|c| c.support_prompt_cache_key) {
        return body;
    }
    let explicit = [&req.body[..], &req.original_body[..], &body[..]]
        .into_iter()
        .map(|source| gj::get(source, "prompt_cache_key").str().trim().to_owned())
        .find(|key| !key.is_empty());
    if let Some(key) = explicit {
        payload::set_str_if_different(&mut body, "prompt_cache_key", &key);
        return body;
    }
    let model = gj::get(&body, "model").str().trim().to_owned();
    let model = if model.is_empty() { base_model.to_owned() } else { model };
    if req.source_format == Format::Claude
        && let Some(key) = payload::claude_code_prompt_cache(&model, &req.body, &req.headers)
    {
        payload::set_str_if_different(&mut body, "prompt_cache_key", &key);
        return body;
    }
    let Some(session) = provider_session_uuid(provider, req) else {
        return body;
    };
    let provider = provider.trim().go_lower();
    let identity = format!(
        "cli-proxy-api:openai-compat:prompt-cache\0{provider}\0{}\0{}\0{session}",
        model.go_lower(),
        req.source_format.as_str().trim().go_lower()
    );
    let key = uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, identity.as_bytes()).to_string();
    payload::set_str_if_different(&mut body, "prompt_cache_key", &key);
    body
}

/// `helps.ProviderSessionUUID`: the execution session, else the derived session identity,
/// as a provider-scoped stable UUID.
fn provider_session_uuid(provider: &str, req: &ExecRequest) -> Option<String> {
    let nonempty = |s: &Option<String>| s.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned);
    let (kind, value) = match nonempty(&req.execution_session) {
        Some(execution) => ("execution-session", execution),
        None => ("derived-session", nonempty(&req.derived_session)?),
    };
    let provider = provider.trim().go_lower();
    if provider.is_empty() {
        return None;
    }
    let identity = format!("cli-proxy-api\0{provider}\0{kind}\0{value}");
    Some(uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, identity.as_bytes()).to_string())
}

/// `CountTokens`: a local tiktoken estimate of the translated chat request.
pub(crate) fn count_tokens(
    credential: &Credential,
    req: &ExecRequest,
    cfg: &Config,
) -> Result<ExecResponse, ExecError> {
    let base_model = parse_suffix(&req.model).model_name;
    let caps = req.resolved_model.as_ref().map(|r| ModelCaps::from(&r.info));
    let is_compat = req.resolved_model.as_ref().is_some_and(|r| r.is_compat());
    let body = translate_body(req, cfg, Format::OpenAI, &base_model, false, &req.body, is_compat)?;
    // The rule baseline: the translated original, else the translated body before
    // thinking. Go counts with a failed translation's partial body; this refuses.
    let original = if req.original_body.is_empty() {
        body.clone()
    } else {
        translate_body(
            req,
            cfg,
            Format::OpenAI,
            &base_model,
            false,
            &req.original_body,
            is_compat,
        )?
    };
    let body = apply_thinking(body, req, Format::OpenAI, &credential.provider, caps.as_ref())?;
    let body = crate::payload_barrier::Barrier {
        executor: &credential.provider,
        model: &base_model,
        protocol: Format::OpenAI.as_str(),
        root: "",
        original: &original,
    }
    .apply(cfg, req, body);
    let count = payload::count_chat_tokens(&base_model, &body).map_err(|e| {
        ExecError::local(
            500,
            FailureScope::Request,
            format!("openai compat executor: token counting failed: {e}"),
        )
    })?;
    let usage = format!(r#"{{"usage":{{"prompt_tokens":{count},"completion_tokens":0,"total_tokens":{count}}}}}"#);
    let out = cpa_translate::translate_token_count(req.response_format, Format::OpenAI, count, usage.as_bytes());
    Ok(ExecResponse {
        status: 200,
        headers: Default::default(),
        body: ResponseBody::Buffered(Bytes::from(out)),
    })
}

/// Same-format passthrough when no pair is registered: one `data:` event per frame.
struct Identity;

impl StreamTranslator for Identity {
    fn event(&mut self, event: &[u8]) -> Result<Vec<Bytes>, cpa_translate::Error> {
        Ok(if event.starts_with(b"data: [DONE]") {
            Vec::new()
        } else {
            vec![Bytes::from([event, b"\n\n"].concat())]
        })
    }

    fn finish(&mut self) -> Result<Vec<Bytes>, cpa_translate::Error> {
        Ok(Vec::new())
    }
}

fn trim(bytes: &[u8]) -> &[u8] {
    go::trim_space(bytes)
}

/// The ExecuteStream scan loop: SSE lines grouped into frames, Go's error detection on
/// every frame, and the terminal rules for `[DONE]` and EOF.
struct Frames {
    translator: Box<dyn StreamTranslator>,
    /// `TranslateStreamWithClaudeInputTokens` (Go f3e36f19): a Claude client's
    /// `message_start` gets the estimate of its request when the upstream reports none.
    claude: ClaudeInputTokens,
    responses: bool,
    claude_client: bool,
    event: String,
    data: Vec<Vec<u8>>,
    ready: VecDeque<Result<Bytes, ExecError>>,
    seen_done: bool,
    /// A data frame carried a finish_reason (Go 4f2e5270 `openAICompatChunkHasFinishReason`).
    saw_finish_reason: bool,
    failed: bool,
    capture: wire::Capture,
    usage: cpa_core::exec::UsageSink,
}

impl Frames {
    /// `publishStreamError(err, false)`: the error is logged and published as a failure
    /// before the client gets it.
    fn fail(&mut self, status: u16, message: impl Into<String>) -> bool {
        let error = status_err(status, message);
        self.capture.error(&error);
        wire::publish_failure(&self.usage, &error);
        self.terminal(error);
        true
    }

    /// `publishStreamError(err, true)`: the upstream's error payload is neither logged nor
    /// published; a fixed text stands in for it.
    fn fail_payload(&mut self, status: u16, message: impl Into<String>) -> bool {
        let logged = status_err(status, "upstream stream returned an error payload");
        self.capture.error(&logged);
        wire::publish_failure(&self.usage, &logged);
        self.terminal(status_err(status, message));
        true
    }

    /// A terminal error: a Responses client first gets the frame its Go framer would
    /// flush (`responsesSSEFramer.Flush`), then the error.
    fn terminal(&mut self, error: ExecError) {
        let mut flushed = self.translator.flush_frames();
        self.usage_details(&mut flushed);
        self.ready.extend(flushed.into_iter().map(Ok));
        self.ready.push_back(Err(error));
        self.failed = true;
    }

    /// TranslateStreamWithClaudeInputTokens: Responses usage gets its detail fields
    /// unless the apply_patch bridge failed. Go patches before the SSE framer, so frames
    /// the framer flushes later get them too.
    fn usage_details(&self, out: &mut [Bytes]) {
        if self.responses && !self.translator.tool_input_failed() {
            for chunk in out {
                *chunk = Bytes::from(payload::ensure_responses_usage_details(chunk));
            }
        }
    }

    /// One Go `TranslateStream` call per frame's joined `data:` line: no blank line
    /// follows it, so plugin stream hooks run once per line, as in Go.
    fn translate(&mut self, line: &[u8]) -> bool {
        match self.translator.event(line) {
            Ok(mut out) => {
                self.usage_details(&mut out);
                self.claude.apply(&mut out);
                self.ready.extend(out.into_iter().map(Ok));
                false
            }
            Err(e) => self.fail(502, e.to_string()),
        }
    }

    /// `processFrame`; true ends the scan.
    fn frame(&mut self) -> bool {
        let event = std::mem::take(&mut self.event);
        let data = std::mem::take(&mut self.data);
        if data.is_empty() {
            return payload::error_event(&event) && self.fail(502, "upstream error event ended without data");
        }
        if data.len() > 1 && data.iter().any(|d| trim(d) == b"[DONE]") {
            return self.fail(502, "upstream stream ended with incomplete data before [DONE]");
        }
        let joined = data.join(&b"\n"[..]);
        let payload_bytes = trim(&joined);
        let done = payload_bytes == b"[DONE]";
        if done && payload::error_event(&event) {
            return self.fail(502, "upstream error event ended before [DONE]");
        }
        if !done && !go::json_valid(payload_bytes) {
            return self.fail(502, "upstream stream ended with incomplete SSE data frame");
        }
        if !done && let Some(status) = payload::stream_data_error(payload_bytes, &event) {
            return self.fail_payload(status, String::from_utf8_lossy(payload_bytes));
        }
        if !done && !self.saw_finish_reason {
            self.saw_finish_reason = has_finish_reason(payload_bytes);
        }
        // ObserveChatTokenEvent (Go f8e4a840): the served model comes from frames that
        // passed these checks, not from every line.
        self.usage.response_model_line(payload_bytes);
        let mut line = b"data: ".to_vec();
        line.extend_from_slice(payload_bytes);
        if self.translate(&line) {
            return true;
        }
        // helps.ApplyPatchTranslationError: the frame's chunks go out, then the 502.
        if self.translator.tool_input_failed() {
            return self.fail(502, EMPTY_TRANSLATION);
        }
        if done {
            self.seen_done = true;
        }
        done
    }

    /// One scanned line; true ends the scan.
    fn line(&mut self, line: &[u8]) -> bool {
        let line = trim(line);
        if line.is_empty() {
            return self.frame();
        }
        if let Some(rest) = line.strip_prefix(b"data:") {
            self.data.push(trim(rest).to_vec());
        } else if let Some(rest) = line.strip_prefix(b"event:") {
            self.event = String::from_utf8_lossy(trim(rest)).into_owned();
        } else if line.starts_with(b":") || line.starts_with(b"id:") || line.starts_with(b"retry:") {
        } else if line.starts_with(b"{") || line.starts_with(b"[") {
            return self.fail_payload(502, String::from_utf8_lossy(line));
        }
        false
    }

    /// `helps.EndApplyPatchStream` when the transport ends: the translator's closing
    /// apply_patch frames, then the 502 when its tool input failed. True ends the stream.
    fn end_tool_input(&mut self) -> bool {
        let out = self.translator.finalize_tool_input();
        self.ready.extend(out.into_iter().map(Ok));
        if self.translator.tool_input_failed() {
            // RecordApplyPatchStreamFailure publishes; nothing is logged.
            let error = status_err(502, EMPTY_TRANSLATION);
            wire::publish_failure(&self.usage, &error);
            self.terminal(error);
            return true;
        }
        false
    }

    /// Clean EOF: flush a pending frame, then Go's terminal rule per client format.
    fn eof(&mut self) {
        if !self.seen_done && !self.failed && !self.data.is_empty() {
            self.frame();
        }
        if self.failed || self.end_tool_input() {
            return;
        }
        if !self.seen_done {
            // 0ea4e1dc: a finish reason that left every item done completes the stream.
            if self.responses && self.translator.can_finalize_response_stream() {
                if self.translate(b"data: [DONE]") {
                    return;
                }
                self.seen_done = !self.translator.can_finalize_response_stream();
            }
        }
        if !self.seen_done {
            // 4f2e5270: a Claude client's EOF fails too unless a chunk carried a finish
            // reason; both failures publish the usage seen so far.
            if self.responses || (self.claude_client && !self.saw_finish_reason) {
                let error = status_err(502, "upstream stream closed before [DONE]");
                self.capture.error(&error);
                self.usage
                    .publish_failure_with_usage(error.status, &String::from_utf8_lossy(&error.body));
                self.terminal(error);
                return;
            }
            if self.translate(b"data: [DONE]") {
                return;
            }
        }
        self.finish();
    }

    fn finish(&mut self) {
        match self.translator.finish() {
            Ok(mut out) => {
                self.usage_details(&mut out);
                self.ready.extend(out.into_iter().map(Ok));
            }
            Err(e) => {
                self.fail(502, e.to_string());
            }
        }
    }
}

/// Go `openAICompatChunkHasFinishReason`: a choice whose `finish_reason` is not null and
/// not blank after `strings.TrimSpace`.
fn has_finish_reason(payload: &[u8]) -> bool {
    gj::get(payload, "choices").array().iter().any(|choice| {
        let reason = choice.get("finish_reason");
        reason.kind != gj::Kind::Null && !go::trim_space(&reason.bytes()).is_empty()
    })
}

fn frames(
    lines: ExecStream,
    translator: Box<dyn StreamTranslator>,
    claude: ClaudeInputTokens,
    client: Format,
    capture: wire::Capture,
    usage: cpa_core::exec::UsageSink,
) -> ExecStream {
    let state = Frames {
        translator,
        claude,
        responses: client == Format::OpenAIResponse,
        claude_client: client == Format::Claude,
        event: String::new(),
        data: Vec::new(),
        ready: VecDeque::new(),
        seen_done: false,
        saw_finish_reason: false,
        failed: false,
        capture,
        usage,
    };
    futures_util::stream::unfold((lines, state, false), |(mut lines, mut state, mut ended)| async move {
        loop {
            if let Some(item) = state.ready.pop_front() {
                if item.is_err() {
                    state.ready.clear();
                    ended = true;
                }
                return Some((item, (lines, state, ended)));
            }
            if ended {
                return None;
            }
            match lines.next().await {
                Some(Ok(line)) => {
                    // AppendAPIResponseChunk per scanned line.
                    state.capture.chunk(&line);
                    if state.line(&line) {
                        if !state.failed && !state.end_tool_input() {
                            state.finish();
                        }
                        ended = true;
                    }
                }
                Some(Err(error)) => {
                    // Go ends apply_patch input before reporting the scan error.
                    if !state.end_tool_input() {
                        state.capture.error(&error);
                        wire::publish_failure(&state.usage, &error);
                        state.terminal(error);
                    }
                    ended = true;
                }
                None => {
                    state.eof();
                    ended = true;
                }
            }
        }
    })
    .boxed()
}

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