Skip to main content

lean_ctx/proxy/forward/
mod.rs

1//! Shared upstream forward path for OpenAI-compatible providers.
2
3use axum::{
4    body::Body,
5    extract::State,
6    http::{HeaderValue, Request, StatusCode},
7    response::Response,
8};
9
10use super::ProxyState;
11use super::connector::schedule_provider_connector;
12use super::intent::classify_and_store_proxy_intent;
13
14#[cfg(feature = "shape-xlat")]
15mod xlat;
16
17pub(crate) mod enterprise_headers;
18mod headers;
19mod prepare;
20pub mod trace_id;
21mod transport;
22
23#[cfg(test)]
24mod tests;
25
26#[allow(unused_imports)] // re-exported for proxy::* and tests
27pub(super) use headers::{
28    ALLOWED_REQUEST_HEADERS, FORWARDED_HEADERS, is_allowed_request_header,
29    is_forwarded_response_header,
30};
31pub(super) use transport::xlat_stream_body;
32
33// Unit tests import these via `use super::*`.
34#[cfg(test)]
35#[allow(unused_imports)]
36use super::codec::{
37    RequestBodyEncoding, decode_gzip_bounded, encode_gzip, encode_zstd, is_retryable_status,
38    request_body_encoding,
39};
40#[cfg(test)]
41#[allow(unused_imports)]
42use axum::http::request::Parts;
43#[cfg(test)]
44#[allow(unused_imports)]
45use headers::should_forward_request_header;
46#[cfg(test)]
47#[allow(unused_imports)]
48pub(super) use prepare::{cohort_arm, prepare_request_body, wire_context};
49
50pub(crate) mod pipeline;
51pub use crate::core::config::PipelineConfig;
52pub use pipeline::{CompressionPipeline, PipelineReport, StageReport};
53
54const HEADROOM_COMPRESSED_HEADER: &str = "x-headroom-compressed";
55const OCLA_BUDGET_SCOPE_HEADER: &str = "x-ocla-budget-scope";
56const ESTIMATED_CHARS_PER_TOKEN: u64 = 4;
57
58/// Check whether an incoming request was already compressed by Headroom.
59pub(super) fn is_headroom_compressed(parts: &axum::http::request::Parts) -> bool {
60    parts
61        .headers
62        .get(HEADROOM_COMPRESSED_HEADER)
63        .and_then(|v| v.to_str().ok())
64        .is_some_and(|v| !v.is_empty() && v != "0" && !v.eq_ignore_ascii_case("false"))
65}
66
67/// Default request-body ceiling (MiB). A large-codebase refactor with several
68/// big files in context easily exceeds the old 10 MiB cap, which surfaced to the
69/// agent as a hard `400` mid-task. Raised and made configurable via
70/// `LEAN_CTX_PROXY_MAX_BODY_MB`.
71const DEFAULT_MAX_BODY_MB: usize = 64;
72
73pub(super) fn max_body_bytes() -> usize {
74    std::env::var("LEAN_CTX_PROXY_MAX_BODY_MB")
75        .ok()
76        .and_then(|v| v.trim().parse::<usize>().ok())
77        .filter(|mb| *mb > 0)
78        .unwrap_or(DEFAULT_MAX_BODY_MB)
79        .saturating_mul(1024 * 1024)
80}
81
82/// Appends lean-ctx's diagnosis to an upstream `401 … insufficient permissions`
83/// body (#1774), preserving the original text byte for byte.
84///
85/// Any other 401 — a revoked key, a genuine organization-permission problem —
86/// passes through untouched: guessing at those would be worse than staying quiet.
87async fn annotate_openai_scope_401(response: Response) -> Response {
88    let (mut parts, body) = response.into_parts();
89    let Ok(bytes) = axum::body::to_bytes(body, max_body_bytes()).await else {
90        return Response::from_parts(parts, Body::empty());
91    };
92    let Ok(text) = std::str::from_utf8(&bytes) else {
93        return Response::from_parts(parts, Body::from(bytes));
94    };
95    if !text.contains("api.responses.write") && !text.contains("insufficient permissions") {
96        return Response::from_parts(parts, Body::from(bytes));
97    }
98    let hint = "lean-ctx: this looks like a ChatGPT subscription token sent to the OpenAI \
99                platform API. api.openai.com accepts API keys only, so it reports a missing \
100                scope rather than the real cause. Codex with a ChatGPT login belongs on the \
101                subscription rail: run `lean-ctx proxy codex-chatgpt on` with the proxy \
102                running. If you meant to use an API key, set OPENAI_API_KEY.";
103    let annotated = match serde_json::from_str::<serde_json::Value>(text) {
104        Ok(mut doc) => {
105            if let Some(error) = doc.get_mut("error").and_then(|e| e.as_object_mut()) {
106                let message = error
107                    .get("message")
108                    .and_then(serde_json::Value::as_str)
109                    .map(str::to_owned);
110                if let Some(message) = message {
111                    error.insert(
112                        "message".to_string(),
113                        serde_json::Value::String(format!("{message}\n\n{hint}")),
114                    );
115                }
116                error.insert(
117                    "lean_ctx_hint".to_string(),
118                    serde_json::Value::String(hint.to_string()),
119                );
120            }
121            serde_json::to_vec(&doc).unwrap_or_else(|_| bytes.to_vec())
122        }
123        Err(_) => format!("{text}\n\n{hint}").into_bytes(),
124    };
125    // The body length changed. `build_response` never forwards content-length,
126    // but drop it defensively so no stale value can survive.
127    parts.headers.remove(axum::http::header::CONTENT_LENGTH);
128    Response::from_parts(parts, Body::from(annotated))
129}
130
131fn apply_ocla_budget_admission(
132    parts: &axum::http::request::Parts,
133    estimated_bytes: usize,
134) -> Result<(), StatusCode> {
135    let Some(scope) = parts
136        .headers
137        .get(OCLA_BUDGET_SCOPE_HEADER)
138        .and_then(|value| value.to_str().ok())
139        .map(str::trim)
140        .filter(|value| !value.is_empty())
141    else {
142        return Ok(());
143    };
144    let estimated_tokens = (estimated_bytes as u64).saturating_add(ESTIMATED_CHARS_PER_TOKEN - 1)
145        / ESTIMATED_CHARS_PER_TOKEN;
146    crate::core::ocla::wire_api::admit_budgeted_request(scope, estimated_tokens, 0.0)
147        .map_err(|_| StatusCode::PAYMENT_REQUIRED)
148}
149
150#[allow(clippy::if_not_else)]
151pub async fn forward_request(
152    State(state): State<ProxyState>,
153    req: Request<Body>,
154    upstream_base: &str,
155    default_path: &str,
156    compress_body: impl FnOnce(serde_json::Value, usize) -> (Vec<u8>, usize, usize),
157    provider_label: &str,
158    extra_stream_types: &[&str],
159) -> Result<Response, StatusCode> {
160    let (mut parts, body) = req.into_parts();
161    let trace_id = trace_id::extract_or_generate_trace_id(&parts.headers);
162    let body_limit = super::bedrock::request_body_limit(&parts).unwrap_or_else(max_body_bytes);
163    let raw_body_bytes = axum::body::to_bytes(body, body_limit)
164        .await
165        .map_err(|_| StatusCode::PAYLOAD_TOO_LARGE)?;
166    let original_parsed =
167        super::determinism_guard::parse_request_body(&raw_body_bytes, &parts, body_limit);
168    let original_messages = original_parsed
169        .as_ref()
170        .map(super::determinism_guard::cache_relevant_messages);
171    let (mut body_bytes, mut pre_optimize_result) =
172        serde_json::from_slice::<serde_json::Value>(&raw_body_bytes)
173            .ok()
174            .and_then(|mut parsed_body| {
175                let result = crate::proxy::pre_optimize::pre_optimize(&mut parsed_body)?;
176                #[cfg(feature = "enterprise")]
177                crate::proxy::reasoning_budget::apply_reasoning_budget_with_config(
178                    &mut parsed_body,
179                    &result.task_class,
180                    &result.complexity,
181                    &crate::core::config::Config::load().proxy.reasoning_budget,
182                );
183                let serialized = serde_json::to_vec(&parsed_body).ok()?;
184                Some((serialized.into(), Some(result)))
185            })
186            .unwrap_or((raw_body_bytes.clone(), None));
187    // Determinism telemetry: report a warning score to the caller, but keep the
188    // request byte-for-byte intact. Scanning the raw body also makes this work
189    // consistently for every provider shape handled by the shared forwarder.
190    let cache_alignment_score = crate::proxy::cache_aligner::detect_volatile_content(
191        std::str::from_utf8(&body_bytes).unwrap_or_default(),
192    )
193    .alignment_score;
194    let mut lineage = super::lineage::from_trusted_request(&parts, &body_bytes);
195    if let Some(context) = lineage.as_mut() {
196        context.trace_id.clone_from(&trace_id);
197    }
198
199    // Org-policy gate (enterprise#25): under a signed + trusted + enforced org
200    // policy, refuse models outside the ceiling and requests over a hard
201    // budget — before any routing/compression work. No policy → no-op.
202    #[cfg(feature = "enterprise")]
203    let gate_rules = super::policy_gate::active_rules();
204    #[cfg(feature = "enterprise")]
205    if let Some(rules) = &gate_rules {
206        let tags = parts
207            .extensions
208            .get::<super::gateway_identity::GatewayTags>()
209            .cloned()
210            .unwrap_or_default();
211        let requested_model = prepare::requested_model_of(&parts, &body_bytes);
212        if let Err(refusal) = super::policy_gate::enforce(rules, requested_model.as_deref(), &tags)
213        {
214            tracing::warn!(
215                "lean-ctx gateway: org policy refused request ({refusal:?}) \
216                 person={:?} project={:?}",
217                tags.person,
218                tags.project
219            );
220            let mut response = super::policy_gate::refusal_response(&refusal, provider_label);
221            trace_id::inject_trace_id(&mut response, &trace_id);
222            return Ok(response);
223        }
224    }
225    // Active router (enterprise#13): may rewrite `model` in the parsed body
226    // (before compression, so exactly one serialization) and re-target the
227    // upstream within the same wire shape. Fail-open: any miss routes nothing.
228    // An org policy may exempt specific projects from downgrades (#25).
229    let routing_rules = crate::core::config::Config::load().proxy.routing.clone();
230    #[cfg(feature = "enterprise")]
231    let downgrade_forbidden = gate_rules.as_ref().is_some_and(|rules| {
232        let project = parts
233            .extensions
234            .get::<super::gateway_identity::GatewayTags>()
235            .and_then(|t| t.project.clone());
236        super::policy_gate::downgrade_forbidden(rules, project.as_deref())
237    });
238    #[cfg(not(feature = "enterprise"))]
239    let downgrade_forbidden = false;
240    let route_upstreams =
241        (routing_rules.is_active() && !downgrade_forbidden).then(|| state.upstream_snapshot());
242    // Cross-shape translation (enterprise#16) only exists for the exact
243    // messages-create call — count_tokens/batches subpaths have no OpenAI
244    // equivalent and must stay within-shape.
245    let xlat_ok = cfg!(feature = "shape-xlat")
246        && provider_label == "Anthropic"
247        && parts
248            .uri
249            .path()
250            .trim_end_matches('/')
251            .ends_with("/v1/messages");
252    // Thompson sampling only selects configured model aliases. The existing
253    // rule router still resolves the alias to a provider and preserves all
254    // shape, credential, and enterprise-policy checks below.
255    let _thompson_task_class = pre_optimize_result
256        .as_ref()
257        .map_or_else(|| "unknown".to_owned(), |result| result.task_class.clone());
258    let _thompson_model: Option<String> = if route_upstreams
259        .as_ref()
260        .is_some_and(|upstreams| upstreams.providers.len() > 1)
261    {
262        let available_models: Vec<&str> =
263            routing_rules.aliases.keys().map(String::as_str).collect();
264        #[cfg(feature = "enterprise")]
265        {
266            if available_models.len() > 1 {
267                let selected = {
268                    let router = crate::core::model_router::global_model_router();
269                    let router = router
270                        .lock()
271                        .unwrap_or_else(std::sync::PoisonError::into_inner);
272                    router
273                        .select_model(&_thompson_task_class, &available_models)
274                        .to_owned()
275                };
276                serde_json::from_slice::<serde_json::Value>(&body_bytes)
277                    .ok()
278                    .as_mut()
279                    .and_then(serde_json::Value::as_object_mut)
280                    .map(|body| {
281                        body.insert(
282                            "model".to_owned(),
283                            serde_json::Value::String(selected.clone()),
284                        );
285                        if let Ok(rewritten) = serde_json::to_vec(body) {
286                            body_bytes = rewritten.into();
287                        }
288                        selected
289                    })
290            } else {
291                None
292            }
293        }
294        #[cfg(not(feature = "enterprise"))]
295        {
296            let _ = &available_models;
297            None::<String>
298        }
299    } else {
300        None
301    };
302
303    let route_hook = |parsed: &mut serde_json::Value| {
304        route_upstreams.as_ref().and_then(|up| {
305            super::routing::route_request(parsed, provider_label, up, &routing_rules, xlat_ok)
306        })
307    };
308    if is_headroom_compressed(&parts) {
309        super::anthropic::set_headroom_request(true);
310        super::prefix_cache_stats::record_headroom_compat();
311    }
312    let mut prepared = prepare::prepare_request_body(
313        &parts,
314        &body_bytes,
315        compress_body,
316        route_hook,
317        upstream_base,
318        provider_label == "OpenAI",
319    )?;
320    let guard = super::determinism_guard::DeterminismGuard::new(&trace_id);
321    let mut determinism_proof = original_messages.as_deref().map_or_else(
322        || guard.verify(&[], &[]),
323        |before| {
324            let after = prepared
325                .parsed
326                .as_ref()
327                .map(super::determinism_guard::cache_relevant_messages)
328                .unwrap_or_default();
329            guard.verify(before, &after)
330        },
331    );
332    if !determinism_proof.is_stable {
333        tracing::warn!(
334            request_id = %determinism_proof.request_id,
335            frozen_bytes = determinism_proof.frozen_bytes,
336            modification_start_byte = determinism_proof.modification_start_byte,
337            "lean-ctx determinism violation: reverting request modifications"
338        );
339        super::determinism_guard::record_audit(&determinism_proof, true);
340        // Safe mode is deliberately fail-closed for cache safety: resend exactly
341        // what the caller supplied instead of allowing a cache-busting rewrite.
342        prepared.body = raw_body_bytes.to_vec();
343        prepared.parsed = original_parsed.clone();
344        prepared.original_size = raw_body_bytes.len();
345        prepared.compressed_size = raw_body_bytes.len();
346        prepared.compression_candidate = false;
347        prepared.content_dedup_tokens_saved = 0;
348        prepared.route = None;
349        body_bytes = raw_body_bytes.clone();
350        pre_optimize_result = None;
351        determinism_proof = original_messages.as_deref().map_or_else(
352            || guard.verify(&[], &[]),
353            |before| guard.verify(before, before),
354        );
355    } else {
356        super::determinism_guard::record_audit(&determinism_proof, false);
357    }
358    apply_ocla_budget_admission(&parts, prepared.body.len())?;
359    let original_size = prepared.original_size;
360    let compressed_size = prepared.compressed_size;
361    let compression_candidate = prepared.compression_candidate;
362    let preserve_content_encoding = prepared.preserve_content_encoding;
363
364    let mut pipeline_report = None;
365    if let Some(messages) = prepared
366        .parsed
367        .as_mut()
368        .and_then(|body| body.get_mut("messages"))
369        .and_then(serde_json::Value::as_array_mut)
370    {
371        let messages_before_pipeline = messages.clone();
372        let pipeline_config = crate::core::config::Config::load().proxy.pipeline.clone();
373        // Knowledge routing is advisory: it runs after pre-triage but before
374        // compression, has a hard latency budget, and any miss leaves the
375        // existing pipeline untouched.
376        let context_advice = if pipeline_config.enable_knowledge_routing {
377            let query = messages
378                .iter()
379                .rev()
380                .find(|message| {
381                    message.get("role").and_then(serde_json::Value::as_str) == Some("user")
382                })
383                .and_then(|message| message.get("content"))
384                .and_then(serde_json::Value::as_str)
385                .map(str::to_owned)
386                .unwrap_or_default();
387            let routing_task_id = trace_id.clone();
388
389            if query.is_empty() {
390                None
391            } else {
392                match tokio::time::timeout(
393                    std::time::Duration::from_millis(5),
394                    tokio::task::spawn_blocking(move || {
395                        crate::core::knowledge_router::KnowledgeRouter {
396                            manifests: Vec::new(),
397                            resolvers: vec![std::sync::Arc::new(
398                                crate::core::knowledge_router::PatternReferenceResolver,
399                            )],
400                        }
401                        .context_advice(
402                            &routing_task_id,
403                            &query,
404                            &crate::core::task_spine::TaskProfileLocal::default(),
405                            &crate::core::knowledge_router::builtin_manifests(),
406                            None,
407                        )
408                    }),
409                )
410                .await
411                {
412                    Ok(Ok(advice)) if !advice.is_empty() => Some(advice),
413                    Ok(Ok(_)) => None,
414                    Ok(Err(error)) => {
415                        tracing::debug!(%error, "knowledge routing task failed open");
416                        None
417                    }
418                    Err(_) => {
419                        tracing::debug!(
420                            "knowledge routing exceeded 5ms; continuing without advice"
421                        );
422                        None
423                    }
424                }
425            }
426        } else {
427            None
428        };
429        if let Ok(report) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
430            CompressionPipeline::run_with_context_advice(
431                messages,
432                &pipeline_config,
433                context_advice.as_ref(),
434            )
435        })) {
436            pipeline_report = Some(report);
437        } else {
438            *messages = messages_before_pipeline;
439            tracing::warn!("compression pipeline failed; continuing with prepared request");
440        }
441    }
442
443    if let (Some(report), Some(parsed_body)) = (pipeline_report.as_ref(), prepared.parsed.as_mut())
444    {
445        report.apply_effort_budget(parsed_body);
446        let serialized =
447            serde_json::to_vec(parsed_body).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
448        prepared.body = serialized;
449        prepared.compressed_size = prepared.body.len();
450        prepared.compression_candidate = true;
451    }
452
453    let _ = compression_candidate;
454
455    let compression_candidate = prepared.compression_candidate;
456    let content_dedup_tokens_saved = prepared.content_dedup_tokens_saved;
457    let route = prepared.route;
458    let parsed = prepared.parsed;
459    let intent_classification =
460        classify_and_store_proxy_intent(&mut parts, parsed.as_ref(), lineage.as_ref(), &body_bytes);
461    #[cfg(feature = "enterprise")]
462    if let Some(request) = parsed.as_ref() {
463        let session_id = lineage
464            .as_ref()
465            .map_or(trace_id.as_str(), |context| context.session_id.as_str());
466        let turn_provided = super::value_gate_proxy::session_metrics()
467            .request_count
468            .saturating_add(1);
469        #[cfg(feature = "enterprise")]
470        if let Err(error) = crate::core::causal_attribution::record_proxy_context(
471            session_id,
472            request,
473            turn_provided,
474        ) {
475            tracing::debug!(%error, "causal attribution context recording failed");
476        }
477    }
478    // Apply the routing decision to the wire: re-target the upstream and — for
479    // registry providers holding their own key — swap the credential headers.
480    let upstream_base = route
481        .as_ref()
482        .and_then(|r| r.upstream_base.as_deref())
483        .unwrap_or(upstream_base);
484    if let Some(provider) = route.as_ref().and_then(|r| r.credential.as_ref()) {
485        super::providers::inject_gateway_credential(provider, &mut parts.headers)?;
486    }
487    schedule_provider_connector(&parts, lineage.as_ref(), route.as_ref(), provider_label);
488    if let Some(ref parsed) = parsed {
489        let provider = match provider_label {
490            "Anthropic" | "Bedrock" => super::introspect::Provider::Anthropic,
491            "OpenAI" | "ChatGPT" => super::introspect::Provider::OpenAi,
492            _ => super::introspect::Provider::Gemini,
493        };
494        let breakdown = super::introspect::analyze_request(parsed, provider);
495        state.introspect.record(breakdown);
496    }
497    // #895 Track B: assign output-savings holdout from the same pristine parsed
498    // body that each provider's compressor receives. Only when active.
499    let cohort = parsed
500        .as_ref()
501        .and_then(|p| prepare::cohort_arm(p, provider_label, default_path));
502    if compression_candidate {
503        // Shape label drives compression/routing; stats identity may differ —
504        // Grok registry routes speak OpenAI shape but meter under "Grok".
505        let registry_id = parts
506            .extensions
507            .get::<super::providers::RegistryProviderId>()
508            .map(|r| r.id.as_str());
509        let stats_label = super::providers::stats_label(registry_id, provider_label);
510        state
511            .stats
512            .record_provider_request(stats_label, original_size, compressed_size);
513    }
514
515    let tokens_saved = original_size.saturating_sub(compressed_size) as u64 / 4;
516    super::metrics::record_request(tokens_saved, compressed_size as u64);
517
518    // Context Kernel: record identity, coverage, ETPAO for this request.
519    {
520        let proxy_headers: Vec<(String, String)> = parts
521            .headers
522            .iter()
523            .filter_map(|(k, v)| {
524                v.to_str()
525                    .ok()
526                    .map(|v| (k.as_str().to_owned(), v.to_owned()))
527            })
528            .collect();
529        let kernel_data = crate::core::context_kernel::proxy_bridge::ProxyRequestData {
530            headers: proxy_headers,
531            input_tokens: original_size / 4,
532            output_tokens: 0,
533            tokens_saved: tokens_saved as usize,
534            model: parsed
535                .as_ref()
536                .and_then(|v| v.get("model"))
537                .and_then(|m| m.as_str())
538                .map(String::from),
539            provider: Some(provider_label.to_owned()),
540            request_count: 1,
541            ..Default::default()
542        };
543
544        // Evidence pipeline: proxy data → envelope → normalizer → receipt chain.
545        let kernel_result =
546            crate::core::context_kernel::proxy_bridge::process_proxy_request(&kernel_data);
547        crate::core::context_kernel::envelope_wiring::process_proxy_evidence(
548            &kernel_data,
549            &kernel_result,
550        );
551    }
552
553    let model = parsed
554        .as_ref()
555        .and_then(|v| v.get("model"))
556        .and_then(|m| m.as_str());
557    let cache_prompt_hash = super::ocla_cache_bridge::prompt_hash(&body_bytes);
558    if let (Some(cache), Some(model)) = (&state.ocla_cache, model)
559        && let Some(cached) = cache.try_cache_hit(model, &cache_prompt_hash, 0.0, 0)
560    {
561        if let Some(route_decision) = &route {
562            crate::proxy::routing_feedback::global_feedback().record_outcome_for_decision(
563                &route_decision.decision_id,
564                None,
565                tokens_saved,
566                0,
567            );
568        }
569        let mut response = Response::builder()
570            .status(cached.status)
571            .body(Body::from(cached.body))
572            .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
573        if let Ok(value) = HeaderValue::from_str(&cache_alignment_score.to_string()) {
574            response
575                .headers_mut()
576                .insert("x-leanctx-cache-alignment", value);
577        }
578        super::determinism_guard::apply_response_headers(&mut response, &determinism_proof);
579        trace_id::inject_trace_id(&mut response, &trace_id);
580        return Ok(response);
581    }
582    super::cost::record(
583        model,
584        tokens_saved,
585        original_size as u64,
586        compressed_size as u64,
587    );
588
589    // Cross-shape route (enterprise#16): the body now speaks OpenAI Chat
590    // Completions — address the matching endpoint instead of the caller's
591    // `/v1/messages` path, and scan the response with the OpenAI parser.
592    let xlat = route.as_ref().is_some_and(|r| r.xlat);
593    let upstream_url = if xlat {
594        format!("{upstream_base}/v1/chat/completions")
595    } else {
596        crate::proxy::codec::build_upstream_url(&parts, upstream_base, default_path)
597    };
598
599    let counterfactual = if provider_label == "Anthropic" && !xlat {
600        super::counterfactual::maybe_spawn_probe(
601            &state.client,
602            &parts,
603            upstream_base,
604            parsed.as_ref(),
605            route.as_ref().map(|r| r.routed_from.as_str()),
606            compressed_size < original_size,
607        )
608    } else {
609        None
610    };
611
612    let forwarded_body = super::bedrock::finalize_request(
613        provider_label,
614        &mut parts,
615        &body_bytes,
616        prepared.body,
617        body_limit,
618        &upstream_url,
619    )?;
620
621    if let Some(ref pre) = parsed {
622        let cfg_replay = crate::core::config::Config::load();
623        if matches!(
624            cfg_replay.proxy.resolved_proxy_mode(),
625            crate::core::config::ProxyMode::Cache
626        ) {
627            let system_val = pre.get("system");
628            if let Some(msgs) = pre.get("messages").and_then(|m| m.as_array()) {
629                let conv_id = super::prefix_replay::conversation_id(system_val, msgs);
630                super::prefix_replay::record_forwarded(
631                    conv_id,
632                    forwarded_body.clone(),
633                    msgs,
634                    msgs.len(),
635                );
636            }
637        }
638    }
639
640    // Enterprise Suite: inject x-leanctx-* metadata headers before dispatch.
641    {
642        let enterprise_cfg = crate::core::config::Config::load().enterprise.clone();
643        if enterprise_cfg.should_inject_headers() {
644            let agent_id = lineage.as_ref().map(|l| l.agent_id.clone());
645            let session_id = lineage.as_ref().map(|l| l.session_id.clone());
646            let task_class = intent_classification
647                .as_ref()
648                .map(|ic| ic._decision.intent.clone());
649            let meta = enterprise_headers::RuntimeMetadata {
650                original_tokens: original_size / 4,
651                compressed_tokens: compressed_size / 4,
652                agent_id,
653                session_id,
654                task_class,
655            };
656            enterprise_headers::inject(&mut parts, &enterprise_cfg, &meta);
657        }
658    }
659    let response = transport::send_upstream(
660        &state,
661        &parts,
662        &upstream_url,
663        forwarded_body,
664        provider_label,
665        preserve_content_encoding,
666    )
667    .await?;
668
669    if let Some(route_decision) = &route {
670        crate::proxy::routing_feedback::global_feedback().record_outcome_for_decision(
671            &route_decision.decision_id,
672            None,
673            tokens_saved,
674            0,
675        );
676    }
677
678    // Measured usage: read the real model + billed tokens from the response.
679    // Gemini puts the model in the URL path, not the request/response body.
680    // Translated requests get OpenAI-shape responses regardless of the label.
681    let usage_provider = if xlat {
682        super::usage::Provider::OpenAi
683    } else {
684        super::usage::Provider::from_label(provider_label)
685    };
686    let url_model = if usage_provider == super::usage::Provider::Gemini {
687        super::usage::gemini_model_from_path(parts.uri.path())
688    } else {
689        None
690    };
691
692    // Gateway context (enterprise#11/#17/#18): identity tags from the auth
693    // guard + wire savings + baseline inputs, stamped onto the usage record.
694    // A routed request is attributed to the provider actually serving it, and
695    // carries the originally requested model as routed_from (enterprise#13).
696    let mut wire = prepare::wire_context(
697        &parts,
698        provider_label,
699        upstream_base,
700        tokens_saved,
701        original_size,
702        lineage,
703    );
704    if let Some(route) = &route {
705        wire.routed_from = Some(route.routed_from.clone());
706        if let Some(id) = &route.provider_id {
707            wire.provider = id.clone();
708        }
709        // Registry route targets carry their own local-inference flag
710        // (shadow-rate billing); built-in targets keep the URL heuristic.
711        if let Some(local) = route.local {
712            wire.is_local = local;
713        }
714    }
715    wire.counterfactual = counterfactual;
716    let wire = Some(wire);
717    let mut response = transport::build_response(
718        response,
719        extra_stream_types,
720        usage_provider,
721        url_model,
722        cohort,
723        wire,
724        xlat,
725        state.ocla_cache.as_deref(),
726        model,
727        &cache_prompt_hash,
728    )
729    .await?;
730
731    // #1774: OpenAI answers a ChatGPT-subscription OAuth token on the platform
732    // `/v1` rail with `Missing scopes: api.responses.write` — a message about
733    // organization roles and API-key scopes that sends people hunting through
734    // their OpenAI settings for a permission that was never the problem. The real
735    // cause is the rail: a subscription token only authenticates against
736    // chatgpt.com.
737    //
738    // Re-routing here is not an option — OpenCode's own ChatGPT-OAuth plugin
739    // legitimately uses this same path, and `/v1` was added to OPENAI_BASE_URL
740    // precisely so that plugin matches (#366). So name the cause instead, and
741    // append it: the upstream text is preserved byte for byte.
742    if provider_label == "OpenAI" && response.status() == StatusCode::UNAUTHORIZED {
743        response = annotate_openai_scope_401(response).await;
744    }
745    #[cfg(feature = "enterprise")]
746    if let Some(model) = _thompson_model.as_deref() {
747        let router = crate::core::model_router::global_model_router();
748        let mut router = router
749            .lock()
750            .unwrap_or_else(std::sync::PoisonError::into_inner);
751        router.record_outcome(
752            model,
753            &_thompson_task_class,
754            response.status().is_success(),
755            0.0,
756        );
757    }
758
759    let (tokens_pruned, original_tokens, task_class) = pre_optimize_result.as_ref().map_or_else(
760        || {
761            let task_class = intent_classification
762                .as_ref()
763                .map_or("unknown", |classification| {
764                    classification._decision.intent.as_str()
765                });
766            (tokens_saved as usize, original_size / 4, task_class)
767        },
768        |result| {
769            (
770                result.tokens_pruned,
771                result.original_token_estimate,
772                result.task_class.as_str(),
773            )
774        },
775    );
776    super::value_gate_proxy::record_completion(tokens_pruned, original_tokens, task_class);
777    let value_metrics = super::value_gate_proxy::session_metrics();
778    let compression_ratio = super::value_gate_proxy::compression_ratio();
779    let headers = response.headers_mut();
780    if let Ok(value) = HeaderValue::from_str(&tokens_pruned.to_string()) {
781        headers.insert("x-leanctx-tokens-pruned", value);
782    }
783    if let Ok(value) = HeaderValue::from_str(&content_dedup_tokens_saved.to_string()) {
784        headers.insert("x-leanctx-dedup-savings", value);
785    }
786    if let Ok(value) = HeaderValue::from_str(&format!("{compression_ratio:.4}")) {
787        headers.insert("x-leanctx-compression-ratio", value);
788    }
789    if let Ok(value) = HeaderValue::from_str(task_class) {
790        headers.insert("x-leanctx-task-class", value);
791    }
792    if let Some(rank) = super::leaderboard::rank_header_if_due() {
793        if let Ok(value) = HeaderValue::from_str(&rank) {
794            headers.insert("x-leanctx-rank", value);
795        }
796    }
797    if let Some(session_cpao_micros) = value_metrics.session_cpao_micros
798        && let Ok(value) = HeaderValue::from_str(&session_cpao_micros.to_string())
799    {
800        headers.insert("x-leanctx-cpao-micros", value);
801    }
802    if let Ok(value) = HeaderValue::from_str(&cache_alignment_score.to_string()) {
803        headers.insert("x-leanctx-cache-alignment", value);
804    }
805
806    if let Some(report) = pipeline_report.as_ref() {
807        report.apply_response_headers(headers);
808    }
809    if let Some(prepared_body) = parsed.as_ref() {
810        let messages = prepared_body
811            .get("messages")
812            .or_else(|| prepared_body.get("input"))
813            .and_then(serde_json::Value::as_array);
814        if let Some(messages) = messages {
815            let task = crate::proxy::effort_routing::TaskComplexity::from_score(
816                crate::proxy::effort_routing::score_complexity(messages),
817            );
818            if let Ok(value) = HeaderValue::from_str(&task.score.to_string()) {
819                headers.insert("x-leanctx-complexity", value);
820            }
821            if let Ok(value) = HeaderValue::from_str(&task.budget_tokens.to_string()) {
822                headers.insert("x-leanctx-effort-budget", value);
823            }
824        }
825    }
826    super::determinism_guard::apply_response_headers(&mut response, &determinism_proof);
827    trace_id::inject_trace_id(&mut response, &trace_id);
828    Ok(response)
829}