Skip to main content

lean_ctx/proxy/
anthropic.rs

1use axum::{
2    body::Body,
3    extract::State,
4    http::{Request, StatusCode},
5    response::Response,
6};
7use serde_json::Value;
8
9use super::ProxyState;
10use super::compress_shared::{self, ToolKind};
11use super::forward;
12use super::tool_kind::{self, ToolResultKind};
13use super::{cache_safety, prefix_cache_stats, prefix_replay, prose, sticky_tools};
14
15std::thread_local! {
16    /// Set by `forward.rs` when the current request has the `X-Headroom-Compressed` header.
17    static HEADROOM_REQUEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
18}
19
20/// Called from `forward.rs` to signal that this request was pre-compressed by Headroom.
21pub(super) fn set_headroom_request(val: bool) {
22    HEADROOM_REQUEST.set(val);
23}
24use crate::core::config::{HistoryMode, ProseRole};
25
26/// GH #1472: Detect whether an Anthropic-wire-format request is actually
27/// GitHub Copilot Claude (same POST /v1/messages shape, but must route to
28/// Copilot hosts, not api.anthropic.com).
29///
30/// Detection signals (any one is sufficient):
31/// - `Editor-Version` header present (Copilot IDE integration)
32/// - `Copilot-Integration-Id` header present
33/// - `Authorization: Bearer` with Copilot session token shape (tid=…;exp=…)
34/// - Configured `openai_upstream` is a githubcopilot.com host
35fn is_copilot_request(req: &Request<Body>, openai_upstream: &str) -> bool {
36    let headers = req.headers();
37
38    // Signal 1: Copilot IDE headers
39    if headers.contains_key("editor-version") || headers.contains_key("copilot-integration-id") {
40        return true;
41    }
42
43    // Signal 2: Authorization bearer looks like a Copilot token
44    if let Some(auth) = headers.get("authorization").and_then(|v| v.to_str().ok()) {
45        let token = auth.strip_prefix("Bearer ").unwrap_or("");
46        if token.starts_with("ghu_")
47            || token.starts_with("gho_")
48            || token.contains("tid=")
49            || token.contains("proxy-ep=")
50        {
51            return true;
52        }
53    }
54
55    // Signal 3: Configured openai_upstream is a Copilot host
56    if is_copilot_host(openai_upstream) {
57        return true;
58    }
59
60    false
61}
62
63fn is_copilot_host(url: &str) -> bool {
64    let lower = url.to_lowercase();
65    lower.contains("githubcopilot.com")
66        || lower.contains("copilot-proxy")
67        || lower.contains("copilot-api")
68}
69
70/// Resolve the upstream for a Copilot-shaped Anthropic request.
71/// Prefers the token's `proxy-ep` field, falls back to the configured
72/// `openai_upstream` (which users set to their Copilot endpoint).
73fn resolve_copilot_upstream(req: &Request<Body>, openai_upstream: &str) -> String {
74    // Try extracting proxy-ep from the Authorization token
75    if let Some(auth) = req
76        .headers()
77        .get("authorization")
78        .and_then(|v| v.to_str().ok())
79    {
80        let token = auth.strip_prefix("Bearer ").unwrap_or("");
81        if let Some(ep) = extract_proxy_ep(token) {
82            return format!("https://{ep}");
83        }
84    }
85    openai_upstream.to_string()
86}
87
88/// Extract `proxy-ep=host` from a Copilot session token.
89fn extract_proxy_ep(token: &str) -> Option<&str> {
90    for part in token.split(';') {
91        let trimmed = part.trim();
92        if let Some(val) = trimmed.strip_prefix("proxy-ep=") {
93            if !val.is_empty() {
94                return Some(val);
95            }
96        }
97    }
98    None
99}
100
101pub async fn handler(
102    State(state): State<ProxyState>,
103    req: Request<Body>,
104) -> Result<Response, StatusCode> {
105    let openai_up = state.openai_upstream();
106
107    let (upstream, provider_label) = if is_copilot_request(&req, &openai_up) {
108        let copilot_upstream = resolve_copilot_upstream(&req, &openai_up);
109        tracing::info!(
110            "Copilot Claude detected (Anthropic wire format), routing to {copilot_upstream}"
111        );
112        (copilot_upstream, "Copilot")
113    } else {
114        (state.anthropic_upstream(), "Anthropic")
115    };
116
117    forward::forward_request(
118        State(state),
119        req,
120        &upstream,
121        "/v1/messages",
122        compress_request_body,
123        provider_label,
124        &[],
125    )
126    .await
127}
128
129pub(super) fn compress_request_body(
130    parsed: Value,
131    original_size: usize,
132) -> (Vec<u8>, usize, usize) {
133    let mut doc = parsed;
134    let mut modified = false;
135
136    // Opt-in per-role prose aggressiveness (#710). Both default to `None`, in
137    // which case nothing below fires and the body is byte-for-byte unchanged.
138    let cfg = crate::core::config::Config::load();
139    let config_headroom = cfg.proxy.is_headroom_compat();
140    if config_headroom {
141        prefix_cache_stats::record_headroom_compat();
142    }
143    // Per-request Headroom detection: if this specific request carries the
144    // X-Headroom-Compressed header, treat it as headroom-compat even without
145    // the global config flag. The header is checked in forward.rs and the
146    // result is threaded through via a thread-local set by the caller.
147    let _headroom_compat = config_headroom || HEADROOM_REQUEST.get();
148    // #1905: input-compression holdout. The forward path decided the arm on the
149    // pristine body; the control arm turns off every input-compression stage so
150    // the meter sees a real uncompressed baseline. Cache-only features stay as
151    // they are in both arms, keeping the comparison about compression alone.
152    let compression_control = super::holdout::in_compression_control();
153    let system_aggr = cfg
154        .proxy
155        .resolved_role_aggressiveness(ProseRole::System)
156        .filter(|_| !compression_control);
157    let user_aggr = cfg
158        .proxy
159        .resolved_role_aggressiveness(ProseRole::User)
160        .filter(|_| !compression_control);
161    let live_compress = cfg.proxy.live_compresses() && !compression_control;
162    let mode = if compression_control {
163        HistoryMode::Off
164    } else {
165        cfg.proxy.resolved_history_mode()
166    };
167    // #939: active prompt-cache breakpoint injection (opt-in, Anthropic-only).
168    // Resolved up front so the meter-only short-circuit below does not skip the
169    // one mutation this mode performs — its whole point is to add a cache anchor
170    // to an otherwise byte-passthrough request.
171    let inject_breakpoint = cfg.proxy.cache_breakpoint_enabled();
172    // #940: cache-aligner volatile-field telemetry (default-on, measurement-only).
173    // Also resolved up front so a meter-only proxy still reaches the scan slot —
174    // it never mutates the body, it only records how much cache the system prompt
175    // leaks, so it ships on for every proxy (#986 premium defaults).
176    let align_volatile = cfg.proxy.cache_aligner_enabled();
177    // #974: active cache-aligner relocate (opt-in, Anthropic-only). Resolved up
178    // front like the telemetry above so a meter-only proxy still reaches the
179    // relocate slot — this is the one mutation that moves volatile fields out of
180    // the cacheable prefix.
181    let relocate_volatile = cfg.proxy.cache_align_relocate_enabled();
182    // #986: cache-economics (default-on). Resolved up front so the meter-only
183    // short-circuit below still reaches the miss-attribution slot — that
184    // telemetry only reads the cacheable prefix, it never mutates the body, and
185    // the paired net-cost gate only makes the cold-prefix repack more
186    // conservative, so both halves ship on for every proxy (#986 premium
187    // defaults).
188    let cache_economics = cfg.proxy.cache_policy_enabled();
189    // #895 Track B: output-savings holdout arm, from the pristine body (before any
190    // mutation below) so it matches the arm the response meter records. Control
191    // conversations skip output-shaping (effort + verbosity steer) but are still
192    // metered. Default holdout=0 → always Treatment (no behaviour change).
193    let arm = super::holdout::assign(
194        &super::holdout::anthropic_key(&doc),
195        cfg.proxy.output_holdout_fraction(),
196    );
197    // #493: in-band CCR expansion (opt-in). Splice any <lc_expand:HASH> the model
198    // echoed back into the verbatim original from the local tee store. A strict
199    // no-op when no marker is present (byte-identical body → cache-safe). Runs
200    // before the meter-only short-circuit so an explicit expand request is
201    // honored even when the proxy is otherwise byte-passthrough.
202    if cfg.proxy.ccr_inband_enabled() {
203        modified |= super::ccr::splice_inband_in_place(&mut doc);
204    }
205    // #834: cache-safe cross-provider effort control. Default off → no-op. The
206    // value is a constant, so it never perturbs the prompt-cache prefix; it only
207    // dials an *existing* adaptive thinking request (never enables thinking the
208    // client didn't ask for).
209    if arm == super::holdout::Arm::Treatment {
210        if let Some(effort) = cfg.proxy.resolved_effort() {
211            modified |= super::effort::apply_anthropic(&mut doc, effort);
212        }
213        // #895: cache-safe wire verbosity steer (constant suffix after the last
214        // cache_control breakpoint). Control arm skips it so the holdout measures
215        // its effect.
216        if cfg.proxy.verbosity_steer_enabled() {
217            modified |= super::verbosity::apply_anthropic(&mut doc);
218        }
219    }
220    // Meter-only (#481): live compression off, no history pruning, no prose
221    // rewriting → forward + usage metering still run, but the body is left
222    // unchanged so the provider prompt-cache prefix stays byte-stable. A pending
223    // in-band splice (`modified`) opts out: the body did change this turn.
224    if !live_compress
225        && mode == HistoryMode::Off
226        && system_aggr.is_none()
227        && user_aggr.is_none()
228        && !modified
229        && !inject_breakpoint
230        && !align_volatile
231        && !relocate_volatile
232        && !cache_economics
233    {
234        let out = serde_json::to_vec(&doc).unwrap_or_default();
235        return (out, original_size, original_size);
236    }
237    let mut prose_segments: u64 = 0;
238
239    // Length of the client's provider-cached message prefix. Needed both for
240    // cache-safe pruning below and to gate top-level system prose: if any
241    // message is client-cached, `system` (which precedes every message) is part
242    // of that cached prefix and must not be rewritten.
243    let cached = doc
244        .get("messages")
245        .and_then(|m| m.as_array())
246        .map_or(0, |m| super::history_prune::cached_prefix_len(m));
247
248    // #480: opt-in big-gap cold-prefix repack. When enabled AND the proxy can
249    // confidently predict (from idle time vs the provider cache TTL) that the
250    // client-cached prefix is already cold, override the normal "never touch the
251    // cached prefix" rule for THIS request and prune/compress the prefix too,
252    // re-seeding a leaner cache. Default-off; never fires without a measured idle
253    // gap past TTL × margin, so warm caches stay byte-stable (#448).
254    // #986: cache-economics miss attribution (opt-in, measurement-only). Classify
255    // why this turn hits or misses the provider prompt-cache (TTL lapse vs prefix
256    // change) and bump the `/status` gauges. Reads the cacheable prefix only — the
257    // body is never touched — so it is strictly cache-safe.
258    if cache_economics
259        && let Some(m) = doc.get("messages").and_then(|m| m.as_array())
260        && let Some(outcome) = super::cache_attribution::record_request(m, cached)
261    {
262        match outcome {
263            super::cache_attribution::CacheOutcome::WarmReuse => {
264                prefix_cache_stats::record_hit();
265            }
266            super::cache_attribution::CacheOutcome::ColdStart => {}
267            _ => {
268                prefix_cache_stats::record_miss();
269            }
270        }
271    }
272    // #480 repack decision, with the #986 net-cost gate folded in: when
273    // cache-economics is on, also require the prefix to be large enough to cache
274    // (`worth_repacking`). The gate is an extra AND-condition, so it can only make
275    // repacking *more* conservative; default-off proxies keep the prior value.
276    let repack = cfg.proxy.repacks_cold_prefix()
277        && !compression_control
278        && doc
279            .get("messages")
280            .and_then(|m| m.as_array())
281            .is_some_and(|m| {
282                super::cold_prefix::repack_decision(m, cached)
283                    && (!cache_economics
284                        || super::cache_policy::worth_repacking(doc.get("system"), m, cached))
285            });
286    // The prefix length the rewrites below must protect: the full cached prefix
287    // normally, or 0 when we are intentionally repacking the cold prefix.
288    let protect = if repack { 0 } else { cached };
289
290    // System prose: compressed freely when nothing is client-cached, or when a
291    // cold-prefix repack deliberately rewrites it to re-seed a leaner cache.
292    // With a warm cached prefix the system block is part of that prefix, so
293    // mutating it busts the cache: only the cache-economics gate may approve
294    // that, priced on the whole prefix, and a per-conversation latch then keeps
295    // every later turn on the compressed prefix (#1912). A `cache_control` on
296    // `system` itself always anchors it (unless repacking).
297    let warm_gate = if system_aggr.is_some()
298        && !repack
299        && cached > 0
300        && cache_economics
301        && doc
302            .get("system")
303            .is_some_and(|s| !prose::value_has_cache_control(s))
304    {
305        let messages = doc
306            .get("messages")
307            .and_then(Value::as_array)
308            .map_or(&[][..], Vec::as_slice);
309        super::cold_prefix::conversation_key(messages).map(|key| {
310            (
311                key,
312                super::cache_policy::prefix_tokens(doc.get("system"), messages, cached),
313                super::cache_policy::observed_prefix_reuse(messages),
314                doc.get("model")
315                    .and_then(Value::as_str)
316                    .unwrap_or("default")
317                    .to_owned(),
318            )
319        })
320    } else {
321        None
322    };
323    if let Some(a) = system_aggr
324        && let Some(system) = doc.get_mut("system")
325        && (repack || !prose::value_has_cache_control(system))
326    {
327        let segments = if repack || cached == 0 {
328            prose::compress_system_value(system, a)
329        } else if let Some((key, prefix_before, reuse, model_name)) = warm_gate {
330            let mut candidate = system.clone();
331            let n = prose::compress_system_value(&mut candidate, a);
332            let latched = super::cold_prefix::system_compression_latched(key);
333            let approve = n > 0
334                && (latched
335                    || matches!(
336                        super::cache_policy::system_mutation_decision(
337                            prefix_before,
338                            system,
339                            &candidate,
340                            reuse,
341                            &super::cache_policy::model_cost_for(&model_name),
342                        ),
343                        super::cache_policy::MutationDecision::Mutate { .. }
344                    ));
345            if approve {
346                if !latched {
347                    super::cold_prefix::latch_system_compression(key);
348                }
349                *system = candidate;
350                n
351            } else {
352                0
353            }
354        } else {
355            0
356        };
357        if segments > 0 {
358            prose_segments += u64::from(segments);
359            modified = true;
360        }
361    }
362
363    if let Some(messages) = doc.get_mut("messages").and_then(|m| m.as_array_mut()) {
364        // Resolve tool-call id → tool name so file/source reads can be protected
365        // from lossy compression that would force the model to re-read mid-task.
366        let tool_names = tool_kind::anthropic_tool_names(messages);
367
368        // Prune at a frozen, cache-aware boundary by default: Anthropic's
369        // prompt cache matches exact prefixes, so the boundary must not move
370        // every turn (see `history_prune::prune_boundary`). `mode` resolved above.
371        let boundary = super::history_prune::prune_boundary(mode, messages.len());
372        // Never rewrite content the client has marked with `cache_control`:
373        // pruning inside the already-cached prefix invalidates Anthropic's
374        // prompt cache from the first changed message (#448). Pruning therefore
375        // starts after the last breakpoint; with no breakpoint this is 0, i.e.
376        // the previous behaviour.
377        modified |=
378            super::history_prune::prune_history_range(messages, protect, boundary, &tool_names);
379
380        for msg in messages.iter_mut() {
381            let role = msg.get("role").and_then(|r| r.as_str()).unwrap_or("");
382            if role != "user" {
383                continue;
384            }
385
386            if let Some(content) = msg.get_mut("content").and_then(|c| c.as_array_mut()) {
387                for block in content.iter_mut() {
388                    if compress_shared::classify_tool_kind(block) != ToolKind::ToolResult {
389                        continue;
390                    }
391
392                    let name = block
393                        .get("tool_use_id")
394                        .and_then(|v| v.as_str())
395                        .and_then(|id| tool_names.get(id))
396                        .map(String::as_str);
397                    let kind = compress_shared::tool_result_kind(name);
398
399                    // #481: skip live compression when globally off or when the
400                    // originating tool is on the exclusion list (Serena default).
401                    let excluded =
402                        name.is_some_and(|n| cfg.proxy.is_tool_live_compress_excluded(n));
403                    if live_compress
404                        && !excluded
405                        && let Some(inner_content) = block.get_mut("content")
406                    {
407                        modified |= compress_content_field(inner_content, name, kind);
408                    }
409                }
410            }
411        }
412
413        // Frozen-region user prose: free-text `text` blocks of user turns in
414        // `[cached, boundary)`. Cache-safe by construction — the cached prefix
415        // and the live tail (`>= boundary`) are both left intact, and the
416        // rewrite is content-deterministic so the prefix stays byte-stable.
417        if let Some(a) = user_aggr {
418            let end = boundary.min(messages.len());
419            let start = protect.min(end);
420            for msg in &mut messages[start..end] {
421                if msg.get("role").and_then(|r| r.as_str()) == Some("user")
422                    && let Some(content) = msg.get_mut("content").and_then(|c| c.as_array_mut())
423                {
424                    prose_segments += u64::from(prose::compress_text_blocks(content, a));
425                }
426            }
427        }
428    }
429
430    if prose_segments > 0 {
431        modified = true;
432    }
433    // #940: cache-aligner telemetry. On an unanchored system prompt (the prefix a
434    // provider would cache), count the volatile fields that would bust that cache
435    // turn-to-turn. Pure measurement — runs before any breakpoint injection and
436    // never mutates the body — so it is strictly cache-safe. Skipped once the
437    // client has anchored the prefix itself.
438    if align_volatile
439        && cached == 0
440        && let Some(system) = doc.get("system")
441        && !prose::value_has_cache_control(system)
442        && let Some(text) = super::cache_aligner::system_text(system)
443    {
444        let scan = super::cache_aligner::scan_volatile(&text);
445        cache_safety::record_volatile_system(scan.fields as u64);
446    }
447    // #974: active cache-aligner relocate (Anthropic-only). After the telemetry
448    // above measured the leak on the pristine prompt, move the volatile values out
449    // of the cacheable prefix into an uncached tail block so the prefix finally
450    // caches. Gated exactly like the breakpoint below — Treatment arm, and only
451    // when the client anchored nothing of its own. The rewrite adds the
452    // `cache_control` itself, so a following #939 injection sees an anchored prefix
453    // and stays a no-op: the two compose to exactly one breakpoint on the stable
454    // block, with the volatile tail left uncached.
455    if relocate_volatile
456        && arm == super::holdout::Arm::Treatment
457        && cached == 0
458        && doc
459            .get("system")
460            .is_some_and(|s| !prose::value_has_cache_control(s))
461    {
462        let relocated = super::cache_aligner::apply_anthropic_relocate(&mut doc);
463        if relocated > 0 {
464            modified = true;
465            cache_safety::record_volatile_relocated(relocated as u64);
466        }
467    }
468    // #939: active prompt-cache breakpoint injection (Anthropic-only). When the
469    // client anchored no prefix of its own — no message `cache_control` (`cached
470    // == 0`) and no breakpoint already on `system` — add one ephemeral breakpoint
471    // to `system` so the large, stable system prompt bills later turns at the
472    // cached rate (the win a raw API client leaves on the table). Runs after every
473    // frozen-region rewrite so the marker anchors the final system bytes and the
474    // prefix it creates stays byte-stable across turns (#498). Counted on its own
475    // gauge — a pure win, never against the cache-safe ratio.
476    if inject_breakpoint
477        && cached == 0
478        && doc
479            .get("system")
480            .is_some_and(|s| !prose::value_has_cache_control(s))
481        && super::cache_breakpoint::inject_anthropic_system(&mut doc)
482    {
483        modified = true;
484        cache_safety::record_breakpoint_injected();
485    }
486    // A deliberate cold-prefix repack (#480) is the one sanctioned exception to
487    // the frozen-window rule; count it on its own gauge so it never dilutes the
488    // cache-safe ratio (which exists to catch *accidental* #448 regressions).
489    // Every other rewrite lands strictly inside the cache-safe frozen window.
490    if repack {
491        cache_safety::record_cold_repack();
492    }
493    cache_safety::record(prose_segments, true);
494
495    // Sticky CCR tool injection: once a conversation has used CCR, keep
496    // ctx_expand in tools[] to avoid prefix-cache-busting tool-list changes.
497    let system_val = doc.get("system");
498    let messages_for_id = doc.get("messages").and_then(Value::as_array);
499    if let Some(msgs) = messages_for_id {
500        let conv_id = prefix_replay::conversation_id(system_val, msgs);
501        if sticky_tools::ensure_tool_present(conv_id, &mut doc) {
502            modified = true;
503            prefix_cache_stats::record_sticky_injection();
504        }
505    }
506
507    prefix_cache_stats::record_frozen_count(cached as u64);
508
509    // Prefix replay: if this is an append-only turn, overlay the cached
510    // forwarded prefix bytes with the fresh delta for byte-identical prefix.
511    let system_val_replay = doc.get("system").cloned();
512    let msgs_replay = doc.get("messages").and_then(Value::as_array);
513    let out = if let Some(msgs) = msgs_replay {
514        let conv_id = prefix_replay::conversation_id(system_val_replay.as_ref(), msgs);
515        if let Some(delta) = prefix_replay::detect_append_only(conv_id, msgs)
516            && delta.delta_start < msgs.len()
517        {
518            let delta_msgs = &msgs[delta.delta_start..];
519            if let Some(replayed) = prefix_replay::overlay_prefix(&delta.prefix_bytes, delta_msgs) {
520                prefix_cache_stats::record_replay_hit();
521                let original_bytes = serde_json::to_vec(&doc).unwrap_or_default();
522                prefix_cache_stats::record_delta(
523                    original_bytes.len() as u64,
524                    replayed.len() as u64,
525                );
526                replayed
527            } else {
528                prefix_cache_stats::record_replay_miss();
529                serde_json::to_vec(&doc).unwrap_or_default()
530            }
531        } else {
532            prefix_cache_stats::record_replay_miss();
533            serde_json::to_vec(&doc).unwrap_or_default()
534        }
535    } else {
536        serde_json::to_vec(&doc).unwrap_or_default()
537    };
538    let compressed_size = if modified { out.len() } else { original_size };
539    (out, original_size, compressed_size)
540}
541
542/// Compresses a tool_result `content` field unless it is a protected file/source
543/// read, which must reach the model intact (it is what gets edited).
544fn compress_content_field(
545    content: &mut Value,
546    tool_name: Option<&str>,
547    kind: ToolResultKind,
548) -> bool {
549    match content {
550        Value::String(s) => super::tool_output::compress_text(s, tool_name, kind),
551        Value::Array(arr) => {
552            let mut modified = false;
553            for item in arr.iter_mut() {
554                if compress_shared::should_compress_content(compress_shared::classify_tool_kind(
555                    item,
556                )) && let Some(Value::String(text)) = item.get_mut("text")
557                {
558                    modified |= super::tool_output::compress_text(text, tool_name, kind);
559                }
560            }
561            modified
562        }
563        _ => false,
564    }
565}
566
567#[cfg(test)]
568#[path = "anthropic_tests.rs"]
569mod tests;