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, request::Parts},
7    response::Response,
8};
9
10use super::ProxyState;
11use super::connector::schedule_provider_connector;
12use super::intent::classify_and_store_proxy_intent;
13use crate::core::context_admission::egress::{self, EgressBody, EgressOutcome, EgressTarget};
14
15#[cfg(feature = "shape-xlat")]
16mod xlat;
17
18mod driver;
19pub(crate) mod enterprise_headers;
20mod headers;
21mod prepare;
22pub mod trace_id;
23mod transport;
24
25#[cfg(test)]
26mod tests;
27
28#[allow(unused_imports)] // re-exported for proxy::* and tests
29pub(super) use headers::{
30    ALLOWED_REQUEST_HEADERS, FORWARDED_HEADERS, is_allowed_request_header,
31    is_forwarded_response_header,
32};
33pub(super) use transport::xlat_stream_body;
34
35// Unit tests import these via `use super::*`.
36#[cfg(test)]
37#[allow(unused_imports)]
38use super::codec::{
39    RequestBodyEncoding, decode_gzip_bounded, encode_gzip, encode_zstd, is_retryable_status,
40    request_body_encoding,
41};
42#[cfg(test)]
43#[allow(unused_imports)]
44use headers::should_forward_request_header;
45#[cfg(test)]
46#[allow(unused_imports)]
47pub(super) use prepare::{cohort_arm, prepare_request_body, wire_context};
48
49pub(crate) mod pipeline;
50pub use crate::core::config::PipelineConfig;
51pub use pipeline::{CompressionPipeline, PipelineReport, StageReport};
52
53const HEADROOM_COMPRESSED_HEADER: &str = "x-headroom-compressed";
54const OCLA_BUDGET_SCOPE_HEADER: &str = "x-ocla-budget-scope";
55const ESTIMATED_CHARS_PER_TOKEN: u64 = 4;
56
57/// Final egress control (G6): admit the body that is about to leave. A
58/// parsed body is admitted string by string and re-encoded only when the
59/// gateway changed something, so an unchanged request keeps its exact bytes
60/// (#1912); a body the proxy cannot parse is handled as an opaque payload.
61fn admit_egress(
62    parts: &Parts,
63    body: Vec<u8>,
64    parsed: Option<&serde_json::Value>,
65    provider: &str,
66    upstream_base: &str,
67) -> Result<(Vec<u8>, EgressOutcome), StatusCode> {
68    let target = EgressTarget {
69        provider,
70        model: parsed
71            .and_then(|doc| doc.get("model"))
72            .and_then(serde_json::Value::as_str),
73        upstream_base,
74    };
75    let outcome = match parsed {
76        Some(doc) => egress::admit_request(doc, &target),
77        None => egress::admit_opaque(body.len(), &target),
78    };
79    let body = match &outcome.body {
80        EgressBody::Rewritten(doc) => {
81            let logical = serde_json::to_vec(doc).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
82            prepare::encode_request_body(parts, logical)?
83        }
84        EgressBody::Unchanged | EgressBody::Refused(_) => body,
85    };
86    Ok((body, outcome))
87}
88
89/// Check whether an incoming request was already compressed by Headroom.
90pub(super) fn is_headroom_compressed(parts: &axum::http::request::Parts) -> bool {
91    parts
92        .headers
93        .get(HEADROOM_COMPRESSED_HEADER)
94        .and_then(|v| v.to_str().ok())
95        .is_some_and(|v| !v.is_empty() && v != "0" && !v.eq_ignore_ascii_case("false"))
96}
97
98/// Default request-body ceiling (MiB). A large-codebase refactor with several
99/// big files in context easily exceeds the old 10 MiB cap, which surfaced to the
100/// agent as a hard `400` mid-task. Raised and made configurable via
101/// `LEAN_CTX_PROXY_MAX_BODY_MB`.
102const DEFAULT_MAX_BODY_MB: usize = 64;
103
104#[derive(Clone)]
105struct ProxyDispatchResult {
106    error: Option<StatusCode>,
107    response: std::sync::Arc<std::sync::Mutex<Option<Response>>>,
108    economics: crate::core::execution_lifecycle::ProxyEconomicsObservation,
109}
110
111struct ProxyContextIntent {
112    kernel_data: crate::core::context_kernel::proxy_bridge::ProxyRequestData,
113    #[cfg(feature = "enterprise")]
114    causal_session_id: String,
115    #[cfg(feature = "enterprise")]
116    causal_request: Option<serde_json::Value>,
117    #[cfg(feature = "enterprise")]
118    causal_turn_provided: u64,
119}
120
121#[derive(Clone, Copy)]
122enum ProxyTerminalKind {
123    CacheHit,
124}
125
126struct ProxyPrepared {
127    state: ProxyState,
128    extra_stream_types: Vec<String>,
129    usage_provider: crate::proxy::usage::Provider,
130    url_model: Option<String>,
131    cohort: crate::proxy::holdout::Cohorts,
132    wire: Option<Box<crate::proxy::usage::WireContext>>,
133    xlat: bool,
134    model: Option<String>,
135    cache_prompt_hash: String,
136    cache_alignment_score: u8,
137    headroom_compatible: bool,
138    determinism_audit: super::determinism_guard::DeterminismProof,
139    determinism_proof: super::determinism_guard::DeterminismProof,
140    pipeline_report: Option<PipelineReport>,
141    tokens_pruned: usize,
142    original_tokens: usize,
143    task_class: String,
144    content_dedup_tokens_saved: usize,
145    original_size: usize,
146    compressed_size: usize,
147    compression_candidate: bool,
148    tokens_saved: u64,
149    route: Option<crate::proxy::routing::RouteDecision>,
150    stats_label: String,
151    introspect: Option<(serde_json::Value, super::introspect::Provider)>,
152    prefix_replay: Option<(u64, Vec<u8>, Vec<serde_json::Value>, usize)>,
153    // A response confirms the send, independently of later response decoding.
154    upstream_send_succeeded: bool,
155    upstream_started: Option<std::time::Instant>,
156    context_ir: Option<ProxyContextIntent>,
157    terminal: Option<ProxyTerminalKind>,
158}
159
160struct AdmittedProxyRequest {
161    parts: Parts,
162    raw_body_bytes: axum::body::Bytes,
163    body_limit: usize,
164    #[cfg(feature = "enterprise")]
165    gate_rules: Option<super::policy_gate::GateRules>,
166}
167
168struct ProxyOutbound {
169    parts: Parts,
170    upstream_url: String,
171    upstream_base: String,
172    forwarded_body: Vec<u8>,
173    preserve_content_encoding: bool,
174    prepared: ProxyPrepared,
175}
176
177enum PreparedProxyRequest {
178    Upstream(Box<ProxyOutbound>),
179    Terminal(Box<ProxyPrimitive>),
180}
181
182enum ProxyPrimitive {
183    Upstream {
184        response: Result<reqwest::Response, StatusCode>,
185        prepared: ProxyPrepared,
186    },
187    Cache {
188        response: Response,
189        prepared: ProxyPrepared,
190    },
191    Policy {
192        response: Response,
193        original_tokens: usize,
194        trace_id: String,
195    },
196}
197
198struct ProxyProcessed {
199    result: ProxyDispatchResult,
200    prepared: Option<ProxyPrepared>,
201    skip_reason: Option<&'static str>,
202}
203
204struct ProxyDriver<'a, F> {
205    state: Option<ProxyState>,
206    request: Option<Request<Body>>,
207    admitted: Option<AdmittedProxyRequest>,
208    prepared_request: Option<PreparedProxyRequest>,
209    upstream_base: &'a str,
210    default_path: &'a str,
211    compress_body: Option<F>,
212    provider_label: &'a str,
213    extra_stream_types: Vec<String>,
214    trace_id: String,
215}
216
217fn proxy_dispatch_result(
218    response: Response,
219    tokens_pruned: usize,
220    original_tokens: usize,
221    task_class: &str,
222) -> ProxyDispatchResult {
223    ProxyDispatchResult {
224        error: None,
225        response: std::sync::Arc::new(std::sync::Mutex::new(Some(response))),
226        economics: crate::core::execution_lifecycle::ProxyEconomicsObservation {
227            tokens_pruned,
228            original_tokens,
229            task_class: task_class.to_owned(),
230        },
231    }
232}
233
234pub(super) fn max_body_bytes() -> usize {
235    std::env::var("LEAN_CTX_PROXY_MAX_BODY_MB")
236        .ok()
237        .and_then(|v| v.trim().parse::<usize>().ok())
238        .filter(|mb| *mb > 0)
239        .unwrap_or(DEFAULT_MAX_BODY_MB)
240        .saturating_mul(1024 * 1024)
241}
242
243/// Appends lean-ctx's diagnosis to an upstream `401 … insufficient permissions`
244/// body (#1774), preserving the original text byte for byte.
245///
246/// Any other 401 — a revoked key, a genuine organization-permission problem —
247/// passes through untouched: guessing at those would be worse than staying quiet.
248async fn annotate_openai_scope_401(response: Response) -> Response {
249    let (mut parts, body) = response.into_parts();
250    let Ok(bytes) = axum::body::to_bytes(body, max_body_bytes()).await else {
251        return Response::from_parts(parts, Body::empty());
252    };
253    let Ok(text) = std::str::from_utf8(&bytes) else {
254        return Response::from_parts(parts, Body::from(bytes));
255    };
256    if !text.contains("api.responses.write") && !text.contains("insufficient permissions") {
257        return Response::from_parts(parts, Body::from(bytes));
258    }
259    let hint = "lean-ctx: this looks like a ChatGPT subscription token sent to the OpenAI \
260                platform API. api.openai.com accepts API keys only, so it reports a missing \
261                scope rather than the real cause. Codex with a ChatGPT login belongs on the \
262                subscription rail: run `lean-ctx proxy codex-chatgpt on` with the proxy \
263                running. If you meant to use an API key, set OPENAI_API_KEY.";
264    let annotated = match serde_json::from_str::<serde_json::Value>(text) {
265        Ok(mut doc) => {
266            if let Some(error) = doc.get_mut("error").and_then(|e| e.as_object_mut()) {
267                let message = error
268                    .get("message")
269                    .and_then(serde_json::Value::as_str)
270                    .map(str::to_owned);
271                if let Some(message) = message {
272                    error.insert(
273                        "message".to_string(),
274                        serde_json::Value::String(format!("{message}\n\n{hint}")),
275                    );
276                }
277                error.insert(
278                    "lean_ctx_hint".to_string(),
279                    serde_json::Value::String(hint.to_string()),
280                );
281            }
282            serde_json::to_vec(&doc).unwrap_or_else(|_| bytes.to_vec())
283        }
284        Err(_) => format!("{text}\n\n{hint}").into_bytes(),
285    };
286    // The body length changed. `build_response` never forwards content-length,
287    // but drop it defensively so no stale value can survive.
288    parts.headers.remove(axum::http::header::CONTENT_LENGTH);
289    Response::from_parts(parts, Body::from(annotated))
290}
291
292fn apply_ocla_budget_admission(
293    parts: &axum::http::request::Parts,
294    estimated_bytes: usize,
295) -> Result<(), StatusCode> {
296    let Some(scope) = parts
297        .headers
298        .get(OCLA_BUDGET_SCOPE_HEADER)
299        .and_then(|value| value.to_str().ok())
300        .map(str::trim)
301        .filter(|value| !value.is_empty())
302    else {
303        return Ok(());
304    };
305    let estimated_tokens = (estimated_bytes as u64).saturating_add(ESTIMATED_CHARS_PER_TOKEN - 1)
306        / ESTIMATED_CHARS_PER_TOKEN;
307    crate::core::ocla::wire_api::admit_budgeted_request(scope, estimated_tokens, 0.0)
308        .map_err(|_| StatusCode::PAYMENT_REQUIRED)
309}
310
311#[allow(clippy::if_not_else)]
312pub async fn forward_request(
313    State(state): State<ProxyState>,
314    req: Request<Body>,
315    upstream_base: &str,
316    default_path: &str,
317    compress_body: impl FnOnce(serde_json::Value, usize) -> (Vec<u8>, usize, usize) + Send,
318    provider_label: &str,
319    extra_stream_types: &[&str],
320) -> Result<Response, StatusCode> {
321    let trace_id = trace_id::extract_or_generate_trace_id(req.headers());
322    let (parts, body) = req.into_parts();
323    let body_limit = super::bedrock::request_body_limit(&parts).unwrap_or_else(max_body_bytes);
324    let body_bytes = axum::body::to_bytes(body, body_limit)
325        .await
326        .map_err(|_| StatusCode::PAYLOAD_TOO_LARGE)?;
327    let request_scope = format!(
328        "proxy:{provider_label}:{}:{}:{}:{trace_id}",
329        parts.method,
330        parts.uri,
331        blake3::hash(&body_bytes).to_hex()
332    );
333    let req = Request::from_parts(parts, Body::from(body_bytes));
334    let lifecycle = crate::core::execution_lifecycle::ExecutionLifecycle::global();
335    let result = lifecycle
336        .run(
337            crate::core::execution_lifecycle::ToolRequest {
338                tool_name: "proxy_forward".to_owned(),
339                query: None,
340                session_id: trace_id.clone(),
341                agent_id: provider_label.to_owned(),
342                surface: crate::core::execution_lifecycle::ToolSurface::Proxy,
343                idempotency_key: Some(request_scope),
344            },
345            crate::core::execution_lifecycle::RuntimeContext {
346                client_name: Some(provider_label.to_owned()),
347                project_root: None,
348            },
349            crate::core::execution_lifecycle::ProductEntitlements::default(),
350            ProxyDriver {
351                state: Some(state),
352                request: Some(req),
353                admitted: None,
354                prepared_request: None,
355                upstream_base,
356                default_path,
357                compress_body: Some(compress_body),
358                provider_label,
359                extra_stream_types: extra_stream_types
360                    .iter()
361                    .map(|value| (*value).to_owned())
362                    .collect(),
363                trace_id,
364            },
365        )
366        .await;
367
368    let completed = match result {
369        Ok(completed) => completed,
370        Err(crate::core::execution_lifecycle::LifecycleRunError::Dispatch(status)) => {
371            return Err(status);
372        }
373        Err(
374            crate::core::execution_lifecycle::LifecycleRunError::Aborted(_)
375            | crate::core::execution_lifecycle::LifecycleRunError::ReplayTypeMismatch,
376        ) => {
377            return Err(StatusCode::CONFLICT);
378        }
379    };
380    if let Some(status) = completed.error {
381        return Err(status);
382    }
383    let mut response = completed
384        .response
385        .lock()
386        .unwrap_or_else(std::sync::PoisonError::into_inner)
387        .take()
388        .ok_or(StatusCode::CONFLICT)?;
389    let value_metrics = super::value_gate_proxy::session_metrics();
390    let compression_ratio = super::value_gate_proxy::compression_ratio();
391    if let Ok(value) = HeaderValue::from_str(&format!("{compression_ratio:.4}")) {
392        response
393            .headers_mut()
394            .insert("x-leanctx-compression-ratio", value);
395    }
396    if let Some(session_cpao_micros) = value_metrics.session_cpao_micros
397        && let Ok(value) = HeaderValue::from_str(&session_cpao_micros.to_string())
398    {
399        response
400            .headers_mut()
401            .insert("x-leanctx-cpao-micros", value);
402    }
403    Ok(response)
404}
405
406#[allow(clippy::if_not_else)]
407async fn prepare_upstream_request(
408    State(state): State<ProxyState>,
409    admitted: AdmittedProxyRequest,
410    upstream_base: &str,
411    default_path: &str,
412    compress_body: impl FnOnce(serde_json::Value, usize) -> (Vec<u8>, usize, usize),
413    provider_label: &str,
414    extra_stream_types: &[&str],
415    trace_id: String,
416) -> Result<PreparedProxyRequest, StatusCode> {
417    let AdmittedProxyRequest {
418        mut parts,
419        raw_body_bytes,
420        body_limit,
421        #[cfg(feature = "enterprise")]
422        gate_rules,
423    } = admitted;
424    let original_parsed =
425        super::determinism_guard::parse_request_body(&raw_body_bytes, &parts, body_limit);
426    let original_messages = original_parsed
427        .as_ref()
428        .map(super::determinism_guard::cache_relevant_messages);
429    // #1905: decide the input-compression holdout arm once, on the caller's
430    // pristine body. The control arm skips pre-optimization here and every
431    // compression stage in `prepare_request_body` and the pipeline below.
432    let compression_arm = original_parsed
433        .as_ref()
434        .and_then(super::holdout::compression_holdout_arm);
435    let compression_control = compression_arm == Some(super::holdout::Arm::Control);
436    let (mut body_bytes, mut pre_optimize_result) =
437        serde_json::from_slice::<serde_json::Value>(&raw_body_bytes)
438            .ok()
439            .filter(|_| !compression_control)
440            .and_then(|mut parsed_body| {
441                let result = crate::proxy::pre_optimize::pre_optimize(&mut parsed_body)?;
442                #[cfg(feature = "enterprise")]
443                crate::proxy::reasoning_budget::apply_reasoning_budget_with_config(
444                    &mut parsed_body,
445                    &result.task_class,
446                    &result.complexity,
447                    &crate::core::config::Config::load().proxy.reasoning_budget,
448                );
449                let serialized = serde_json::to_vec(&parsed_body).ok()?;
450                Some((serialized.into(), Some(result)))
451            })
452            .unwrap_or((raw_body_bytes.clone(), None));
453    // Determinism telemetry: report a warning score to the caller, but keep the
454    // request byte-for-byte intact. Scanning the raw body also makes this work
455    // consistently for every provider shape handled by the shared forwarder.
456    let cache_alignment_score = crate::proxy::cache_aligner::detect_volatile_content(
457        std::str::from_utf8(&body_bytes).unwrap_or_default(),
458    )
459    .alignment_score;
460    let mut lineage = super::lineage::from_trusted_request(&parts, &raw_body_bytes);
461    if let Some(context) = lineage.as_mut() {
462        context.trace_id.clone_from(&trace_id);
463    }
464
465    // Operator aliases: may rewrite `model` in the parsed body (before
466    // compression, so exactly one serialization) and re-target the upstream.
467    // Fail-open: any miss routes nothing. An org policy may exempt specific
468    // projects from alias rewrites that change the model (#25).
469    let routing_rules = crate::core::config::Config::load().proxy.routing.clone();
470    #[cfg(feature = "enterprise")]
471    let downgrade_forbidden = gate_rules.as_ref().is_some_and(|rules| {
472        let project = parts
473            .extensions
474            .get::<super::gateway_identity::GatewayTags>()
475            .and_then(|t| t.project.clone());
476        super::policy_gate::downgrade_forbidden(rules, project.as_deref())
477    });
478    #[cfg(not(feature = "enterprise"))]
479    let downgrade_forbidden = false;
480    let route_upstreams =
481        (routing_rules.is_active() && !downgrade_forbidden).then(|| state.upstream_snapshot());
482    // Cross-shape translation (enterprise#16) only exists for the exact
483    // messages-create call — count_tokens/batches subpaths have no OpenAI
484    // equivalent and must stay within-shape.
485    let xlat_ok = cfg!(feature = "shape-xlat")
486        && provider_label == "Anthropic"
487        && parts
488            .uri
489            .path()
490            .trim_end_matches('/')
491            .ends_with("/v1/messages");
492    let route_hook = |parsed: &mut serde_json::Value| {
493        route_upstreams.as_ref().and_then(|up| {
494            super::routing::route_request(parsed, provider_label, up, &routing_rules, xlat_ok)
495        })
496    };
497    let headroom_compatible = is_headroom_compressed(&parts);
498    if headroom_compatible {
499        super::anthropic::set_headroom_request(true);
500    }
501    let mut prepared = prepare::prepare_request_body(
502        &parts,
503        &body_bytes,
504        compress_body,
505        route_hook,
506        upstream_base,
507        provider_label == "OpenAI",
508        compression_arm,
509    )?;
510    let guard = super::determinism_guard::DeterminismGuard::new(&trace_id);
511    let mut determinism_proof = original_messages.as_deref().map_or_else(
512        || guard.verify(&[], &[]),
513        |before| {
514            let after = prepared
515                .parsed
516                .as_ref()
517                .map(super::determinism_guard::cache_relevant_messages)
518                .unwrap_or_default();
519            guard.verify(before, &after)
520        },
521    );
522    let determinism_audit = determinism_proof.clone();
523    let guard_reverted = !determinism_proof.is_stable;
524    if guard_reverted {
525        tracing::warn!(
526            request_id = %determinism_proof.request_id,
527            frozen_bytes = determinism_proof.frozen_bytes,
528            modification_start_byte = determinism_proof.modification_start_byte,
529            "lean-ctx determinism violation: reverting request modifications"
530        );
531        // Safe mode is deliberately fail-closed for cache safety: resend exactly
532        // what the caller supplied instead of allowing a cache-busting rewrite.
533        prepared.body = raw_body_bytes.to_vec();
534        prepared.parsed = original_parsed.clone();
535        prepared.original_size = raw_body_bytes.len();
536        prepared.compressed_size = raw_body_bytes.len();
537        prepared.compression_candidate = false;
538        prepared.content_dedup_tokens_saved = 0;
539        prepared.route = None;
540        body_bytes = raw_body_bytes.clone();
541        pre_optimize_result = None;
542        determinism_proof = original_messages.as_deref().map_or_else(
543            || guard.verify(&[], &[]),
544            |before| guard.verify(before, before),
545        );
546    }
547    if !super::outbound_model_policy::allows_outbound(prepared.parsed.as_ref()) {
548        return Err(StatusCode::FORBIDDEN);
549    }
550    apply_ocla_budget_admission(&parts, prepared.body.len())?;
551    let original_size = prepared.original_size;
552    let mut compressed_size = prepared.compressed_size;
553    let preserve_content_encoding = prepared.preserve_content_encoding;
554
555    let mut pipeline_report = None;
556    let mut pipeline_changed = false;
557    // #1912: a guard revert promised the caller's exact bytes — no pipeline
558    // stage and no effort injection may run on top of it. #1905: neither may
559    // the input-compression control arm, which is forwarded uncompressed.
560    if !guard_reverted
561        && !compression_control
562        && let Some(messages) = prepared
563            .parsed
564            .as_mut()
565            .and_then(|body| body.get_mut("messages"))
566            .and_then(serde_json::Value::as_array_mut)
567    {
568        let messages_before_pipeline = messages.clone();
569        let active_user_before_pipeline = messages
570            .iter()
571            .rposition(|message| {
572                message.get("role").and_then(serde_json::Value::as_str) == Some("user")
573            })
574            .map(|index| (index, messages[index].clone()));
575        let pipeline_config = crate::core::config::Config::load().proxy.pipeline.clone();
576        // Knowledge routing is advisory: it runs after pre-triage but before
577        // compression, has a hard latency budget, and any miss leaves the
578        // existing pipeline untouched.
579        let context_advice = if pipeline_config.enable_knowledge_routing {
580            let query = messages
581                .iter()
582                .rev()
583                .find(|message| {
584                    message.get("role").and_then(serde_json::Value::as_str) == Some("user")
585                })
586                .and_then(|message| message.get("content"))
587                .and_then(serde_json::Value::as_str)
588                .map(str::to_owned)
589                .unwrap_or_default();
590            let routing_task_id = trace_id.clone();
591
592            if query.is_empty() {
593                None
594            } else {
595                match tokio::time::timeout(
596                    std::time::Duration::from_millis(5),
597                    tokio::task::spawn_blocking(move || {
598                        crate::core::knowledge_router::KnowledgeRouter {
599                            manifests: Vec::new(),
600                            resolvers: vec![std::sync::Arc::new(
601                                crate::core::knowledge_router::PatternReferenceResolver,
602                            )],
603                        }
604                        .context_advice(
605                            &routing_task_id,
606                            &query,
607                            &crate::core::task_spine::TaskProfileLocal::default(),
608                            &crate::core::knowledge_router::builtin_manifests(),
609                            None,
610                        )
611                    }),
612                )
613                .await
614                {
615                    Ok(Ok(advice)) if !advice.is_empty() => Some(advice),
616                    Ok(Ok(_)) => None,
617                    Ok(Err(error)) => {
618                        tracing::debug!(%error, "knowledge routing task failed open");
619                        None
620                    }
621                    Err(_) => {
622                        tracing::debug!(
623                            "knowledge routing exceeded 5ms; continuing without advice"
624                        );
625                        None
626                    }
627                }
628            }
629        } else {
630            None
631        };
632        if let Ok(report) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
633            CompressionPipeline::run_with_context_advice(
634                messages,
635                &pipeline_config,
636                context_advice.as_ref(),
637            )
638        })) {
639            pipeline_changed = *messages != messages_before_pipeline;
640            pipeline_report = Some(report);
641        } else {
642            *messages = messages_before_pipeline;
643            tracing::warn!("compression pipeline failed; continuing with prepared request");
644        }
645        if let Some((index, active_user)) = active_user_before_pipeline {
646            if let Some(current) = messages.get_mut(index) {
647                *current = active_user;
648            }
649        }
650    }
651
652    if let (Some(report), Some(parsed_body)) = (pipeline_report.as_ref(), prepared.parsed.as_mut())
653    {
654        let effort_changed = report.apply_effort_budget(parsed_body);
655        if pipeline_changed || effort_changed {
656            let serialized =
657                serde_json::to_vec(parsed_body).map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
658            // The upstream still receives the caller's Content-Encoding, so a
659            // rewritten gzip/zstd body must be re-encoded, not sent as plain JSON.
660            prepared.body = prepare::encode_request_body(&parts, serialized)?;
661            prepared.compression_candidate = true;
662        }
663    }
664
665    // #1912: when nothing changed the request's meaning — every rewrite was a
666    // no-op or reverted — forward the caller's bytes untouched. A re-serialized
667    // body reorders keys and reformats numbers, which busts provider prompt
668    // caches keyed on the exact prefix bytes.
669    if prepared.parsed.is_some() && prepared.parsed == original_parsed {
670        prepared.body = raw_body_bytes.to_vec();
671        compressed_size = original_size;
672    }
673
674    let compression_candidate = prepared.compression_candidate;
675    // Agent compaction (prepare) plus the pipeline's in-request tool-output
676    // dedup (#1980); a reverted pipeline reports zero for its stage.
677    let content_dedup_tokens_saved = prepared.content_dedup_tokens_saved
678        + pipeline_report
679            .as_ref()
680            .map_or(0, PipelineReport::dedup_tokens_saved);
681    let route = prepared.route;
682    let parsed = prepared.parsed;
683    let intent_classification =
684        classify_and_store_proxy_intent(&mut parts, parsed.as_ref(), lineage.as_ref(), &body_bytes);
685    // Apply the routing decision to the wire: re-target the upstream and — for
686    // registry providers holding their own key — swap the credential headers.
687    let upstream_base = route
688        .as_ref()
689        .and_then(|r| r.upstream_base.as_deref())
690        .unwrap_or(upstream_base);
691    if let Some(provider) = route.as_ref().and_then(|r| r.credential.as_ref()) {
692        super::providers::inject_gateway_credential(provider, &mut parts.headers)?;
693    }
694    schedule_provider_connector(&parts, lineage.as_ref(), route.as_ref(), provider_label);
695    // #895 Track B: assign output savings from the pristine parsed body; #1905
696    // assigns input compression before rewrites so both arms survive the pipeline.
697    let cohort = super::holdout::Cohorts {
698        output: parsed
699            .as_ref()
700            .and_then(|p| prepare::cohort_arm(p, provider_label, default_path)),
701        compression: compression_arm,
702    };
703    // Shape label drives compression/routing; stats identity may differ —
704    // Grok registry routes speak OpenAI shape but meter under "Grok".
705    let registry_id = parts
706        .extensions
707        .get::<super::providers::RegistryProviderId>()
708        .map(|r| r.id.as_str());
709    let stats_label = super::providers::stats_label(registry_id, provider_label).to_owned();
710
711    let tokens_saved = original_size.saturating_sub(compressed_size) as u64 / 4;
712    #[cfg(feature = "enterprise")]
713    let causal_session_id = lineage
714        .as_ref()
715        .map_or_else(|| trace_id.clone(), |context| context.session_id.clone());
716    #[cfg(feature = "enterprise")]
717    let causal_turn_provided = super::value_gate_proxy::session_metrics()
718        .request_count
719        .saturating_add(1);
720    let context_ir = {
721        let proxy_headers: Vec<(String, String)> = parts
722            .headers
723            .iter()
724            .filter_map(|(k, v)| {
725                v.to_str()
726                    .ok()
727                    .map(|v| (k.as_str().to_owned(), v.to_owned()))
728            })
729            .collect();
730        let kernel_data = crate::core::context_kernel::proxy_bridge::ProxyRequestData {
731            headers: proxy_headers,
732            input_tokens: original_size / 4,
733            output_tokens: 0,
734            tokens_saved: tokens_saved as usize,
735            model: parsed
736                .as_ref()
737                .and_then(|v| v.get("model"))
738                .and_then(|m| m.as_str())
739                .map(String::from),
740            provider: Some(provider_label.to_owned()),
741            request_count: 1,
742            ..Default::default()
743        };
744        Some(ProxyContextIntent {
745            kernel_data,
746            #[cfg(feature = "enterprise")]
747            causal_session_id,
748            #[cfg(feature = "enterprise")]
749            causal_request: parsed.clone(),
750            #[cfg(feature = "enterprise")]
751            causal_turn_provided,
752        })
753    };
754
755    let model = parsed
756        .as_ref()
757        .and_then(|v| v.get("model"))
758        .and_then(|m| m.as_str())
759        .map(str::to_owned);
760    let cache_prompt_hash = super::ocla_cache_bridge::prompt_hash(&body_bytes);
761    if let (Some(cache), Some(model)) = (&state.ocla_cache, model.clone())
762        && let Some(cached) = cache.try_cache_hit(&model, &cache_prompt_hash, 0.0, 0)
763    {
764        let response = Response::builder()
765            .status(cached.status)
766            .body(Body::from(cached.body))
767            .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
768        let introspect = parsed.as_ref().map(|parsed| {
769            let provider = match provider_label {
770                "Anthropic" | "Bedrock" => super::introspect::Provider::Anthropic,
771                "OpenAI" | "ChatGPT" => super::introspect::Provider::OpenAi,
772                _ => super::introspect::Provider::Gemini,
773            };
774            (parsed.clone(), provider)
775        });
776        let prepared = ProxyPrepared {
777            state,
778            extra_stream_types: extra_stream_types
779                .iter()
780                .map(|value| (*value).to_owned())
781                .collect(),
782            usage_provider: super::usage::Provider::from_label(provider_label),
783            url_model: None,
784            cohort,
785            wire: None,
786            xlat: route.as_ref().is_some_and(|decision| decision.xlat),
787            model: Some(model),
788            cache_prompt_hash,
789            cache_alignment_score,
790            headroom_compatible,
791            determinism_audit,
792            determinism_proof,
793            pipeline_report,
794            tokens_pruned: tokens_saved as usize,
795            original_tokens: original_size / 4,
796            task_class: pre_optimize_result.as_ref().map_or_else(
797                || {
798                    intent_classification.as_ref().map_or_else(
799                        || "unknown".to_owned(),
800                        |classification| classification._decision.intent.clone(),
801                    )
802                },
803                |result| result.task_class.clone(),
804            ),
805            content_dedup_tokens_saved,
806            original_size,
807            compressed_size,
808            compression_candidate,
809            tokens_saved,
810            route,
811            stats_label,
812            introspect,
813            prefix_replay: None,
814            upstream_send_succeeded: false,
815            upstream_started: None,
816            context_ir,
817            terminal: Some(ProxyTerminalKind::CacheHit),
818        };
819        return Ok(PreparedProxyRequest::Terminal(Box::new(
820            ProxyPrimitive::Cache { response, prepared },
821        )));
822    }
823
824    // Cross-shape route (enterprise#16): the body now speaks OpenAI Chat
825    // Completions — address the matching endpoint instead of the caller's
826    // `/v1/messages` path, and scan the response with the OpenAI parser.
827    let xlat = route.as_ref().is_some_and(|r| r.xlat);
828    let upstream_url = if xlat {
829        format!("{upstream_base}/v1/chat/completions")
830    } else {
831        crate::proxy::codec::build_upstream_url(&parts, upstream_base, default_path)
832    };
833
834    // G6: final egress control, on exactly the body that leaves — after
835    // compression, routing, translation and every cache-safety revert.
836    let (request_body, egress) = admit_egress(
837        &parts,
838        prepared.body,
839        parsed.as_ref(),
840        provider_label,
841        upstream_base,
842    )?;
843    let egress_agent = lineage.as_ref().map(|context| context.agent_id.clone());
844    if let EgressBody::Refused(refusal) = &egress.body {
845        tracing::warn!("lean-ctx proxy: {refusal} (see `lean-ctx inspect --proxy`)");
846        egress::finish_off_runtime(egress, None, original_size, egress_agent).await;
847        return Err(StatusCode::FORBIDDEN);
848    }
849
850    let forwarded_body = super::bedrock::finalize_request(
851        provider_label,
852        &mut parts,
853        &body_bytes,
854        request_body,
855        body_limit,
856        &upstream_url,
857    )?;
858    egress::finish_off_runtime(
859        egress,
860        Some(forwarded_body.clone()),
861        original_size,
862        egress_agent,
863    )
864    .await;
865
866    let prefix_replay = if let Some(ref pre) = parsed {
867        let cfg_replay = crate::core::config::Config::load();
868        if matches!(
869            cfg_replay.proxy.resolved_proxy_mode(),
870            crate::core::config::ProxyMode::Cache
871        ) {
872            let system_val = pre.get("system");
873            if let Some(msgs) = pre.get("messages").and_then(|m| m.as_array()) {
874                let conv_id = super::prefix_replay::conversation_id(system_val, msgs);
875                Some((conv_id, forwarded_body.clone(), msgs.clone(), msgs.len()))
876            } else {
877                None
878            }
879        } else {
880            None
881        }
882    } else {
883        None
884    };
885
886    // Enterprise Suite: inject x-leanctx-* metadata headers before dispatch.
887    {
888        let enterprise_cfg = crate::core::config::Config::load().enterprise.clone();
889        if enterprise_cfg.should_inject_headers() {
890            let agent_id = lineage.as_ref().map(|l| l.agent_id.clone());
891            let session_id = lineage.as_ref().map(|l| l.session_id.clone());
892            let task_class = intent_classification
893                .as_ref()
894                .map(|ic| ic._decision.intent.clone());
895            let meta = enterprise_headers::RuntimeMetadata {
896                original_tokens: original_size / 4,
897                compressed_tokens: compressed_size / 4,
898                agent_id,
899                session_id,
900                task_class,
901            };
902            enterprise_headers::inject(&mut parts, &enterprise_cfg, &meta);
903        }
904    }
905    // Measured usage: read the real model + billed tokens from the response.
906    // Gemini puts the model in the URL path, not the request/response body.
907    // Translated requests get OpenAI-shape responses regardless of the label.
908    let usage_provider = if xlat {
909        super::usage::Provider::OpenAi
910    } else {
911        super::usage::Provider::from_label(provider_label)
912    };
913    let url_model = if usage_provider == super::usage::Provider::Gemini {
914        super::usage::gemini_model_from_path(parts.uri.path())
915    } else {
916        None
917    };
918
919    // Gateway context (enterprise#11/#17/#18): identity tags from the auth
920    // guard + wire savings + baseline inputs, stamped onto the usage record.
921    // A routed request is attributed to the provider actually serving it, and
922    // carries the originally requested model as routed_from (enterprise#13).
923    let mut wire = prepare::wire_context(
924        &parts,
925        provider_label,
926        upstream_base,
927        tokens_saved,
928        original_size,
929        lineage,
930    );
931    if let Some(route) = &route {
932        wire.routed_from = Some(route.routed_from.clone());
933        if let Some(id) = &route.provider_id {
934            wire.provider.clone_from(id);
935        }
936        // Registry route targets carry their own local-inference flag
937        // (shadow-rate billing); built-in targets keep the URL heuristic.
938        if let Some(local) = route.local {
939            wire.is_local = local;
940        }
941    }
942    let wire = Some(wire);
943    let introspect = parsed.as_ref().map(|parsed| {
944        let provider = match provider_label {
945            "Anthropic" | "Bedrock" => super::introspect::Provider::Anthropic,
946            "OpenAI" | "ChatGPT" => super::introspect::Provider::OpenAi,
947            _ => super::introspect::Provider::Gemini,
948        };
949        (parsed.clone(), provider)
950    });
951    let (tokens_pruned, original_tokens, task_class) = pre_optimize_result.as_ref().map_or_else(
952        || {
953            let task_class = intent_classification
954                .as_ref()
955                .map_or("unknown", |classification| {
956                    classification._decision.intent.as_str()
957                });
958            (
959                tokens_saved as usize,
960                original_size / 4,
961                task_class.to_owned(),
962            )
963        },
964        |result| {
965            (
966                result.tokens_pruned,
967                result.original_token_estimate,
968                result.task_class.clone(),
969            )
970        },
971    );
972    let upstream_base = upstream_base.to_owned();
973    let prepared = ProxyPrepared {
974        state,
975        extra_stream_types: extra_stream_types
976            .iter()
977            .map(|value| (*value).to_owned())
978            .collect(),
979        usage_provider,
980        url_model,
981        cohort,
982        wire,
983        xlat,
984        model,
985        cache_prompt_hash,
986        cache_alignment_score,
987        headroom_compatible,
988        determinism_audit,
989        determinism_proof,
990        pipeline_report,
991        tokens_pruned,
992        original_tokens,
993        task_class,
994        content_dedup_tokens_saved,
995        original_size,
996        compressed_size,
997        compression_candidate,
998        tokens_saved,
999        route,
1000        stats_label,
1001        introspect,
1002        prefix_replay,
1003        upstream_send_succeeded: false,
1004        upstream_started: None,
1005        context_ir,
1006        terminal: None,
1007    };
1008    Ok(PreparedProxyRequest::Upstream(Box::new(ProxyOutbound {
1009        parts,
1010        upstream_url,
1011        upstream_base,
1012        forwarded_body,
1013        preserve_content_encoding,
1014        prepared,
1015    })))
1016}
1017
1018fn apply_response_headers(response: &mut Response, prepared: &ProxyPrepared) {
1019    let headers = response.headers_mut();
1020    if let Ok(value) = HeaderValue::from_str(&prepared.tokens_pruned.to_string()) {
1021        headers.insert("x-leanctx-tokens-pruned", value);
1022    }
1023    if let Ok(value) = HeaderValue::from_str(&prepared.content_dedup_tokens_saved.to_string()) {
1024        headers.insert("x-leanctx-dedup-savings", value);
1025    }
1026    if let Ok(value) = HeaderValue::from_str(&prepared.task_class) {
1027        headers.insert("x-leanctx-task-class", value);
1028    }
1029    if let Some(rank) = super::leaderboard::rank_header_if_due()
1030        && let Ok(value) = HeaderValue::from_str(&rank)
1031    {
1032        headers.insert("x-leanctx-rank", value);
1033    }
1034    if let Ok(value) = HeaderValue::from_str(&prepared.cache_alignment_score.to_string()) {
1035        headers.insert("x-leanctx-cache-alignment", value);
1036    }
1037    if let Some(report) = prepared.pipeline_report.as_ref() {
1038        report.apply_response_headers(headers);
1039    }
1040    if let Some((prepared_body, _)) = prepared.introspect.as_ref() {
1041        let messages = prepared_body
1042            .get("messages")
1043            .or_else(|| prepared_body.get("input"))
1044            .and_then(serde_json::Value::as_array);
1045        if let Some(messages) = messages {
1046            // Same session-stable score the effort stage injects (#1912).
1047            let task = crate::proxy::effort_routing::TaskComplexity::from_score(
1048                crate::proxy::effort_routing::score_session_complexity(messages),
1049            );
1050            if let Ok(value) = HeaderValue::from_str(&task.score.to_string()) {
1051                headers.insert("x-leanctx-complexity", value);
1052            }
1053            if let Ok(value) = HeaderValue::from_str(&task.budget_tokens.to_string()) {
1054                headers.insert("x-leanctx-effort-budget", value);
1055            }
1056        }
1057    }
1058    super::determinism_guard::apply_response_headers(response, &prepared.determinism_proof);
1059    trace_id::inject_trace_id(response, &prepared.determinism_proof.request_id);
1060}