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