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 let system_aggr = cfg.proxy.resolved_role_aggressiveness(ProseRole::System);
149 let user_aggr = cfg.proxy.resolved_role_aggressiveness(ProseRole::User);
150 let live_compress = cfg.proxy.live_compresses();
151 let mode = cfg.proxy.resolved_history_mode();
152 // #939: active prompt-cache breakpoint injection (opt-in, Anthropic-only).
153 // Resolved up front so the meter-only short-circuit below does not skip the
154 // one mutation this mode performs — its whole point is to add a cache anchor
155 // to an otherwise byte-passthrough request.
156 let inject_breakpoint = cfg.proxy.cache_breakpoint_enabled();
157 // #940: cache-aligner volatile-field telemetry (default-on, measurement-only).
158 // Also resolved up front so a meter-only proxy still reaches the scan slot —
159 // it never mutates the body, it only records how much cache the system prompt
160 // leaks, so it ships on for every proxy (#986 premium defaults).
161 let align_volatile = cfg.proxy.cache_aligner_enabled();
162 // #974: active cache-aligner relocate (opt-in, Anthropic-only). Resolved up
163 // front like the telemetry above so a meter-only proxy still reaches the
164 // relocate slot — this is the one mutation that moves volatile fields out of
165 // the cacheable prefix.
166 let relocate_volatile = cfg.proxy.cache_align_relocate_enabled();
167 // #986: cache-economics (default-on). Resolved up front so the meter-only
168 // short-circuit below still reaches the miss-attribution slot — that
169 // telemetry only reads the cacheable prefix, it never mutates the body, and
170 // the paired net-cost gate only makes the cold-prefix repack more
171 // conservative, so both halves ship on for every proxy (#986 premium
172 // defaults).
173 let cache_economics = cfg.proxy.cache_policy_enabled();
174 // #895 Track B: output-savings holdout arm, from the pristine body (before any
175 // mutation below) so it matches the arm the response meter records. Control
176 // conversations skip output-shaping (effort + verbosity steer) but are still
177 // metered. Default holdout=0 → always Treatment (no behaviour change).
178 let arm = super::holdout::assign(
179 &super::holdout::anthropic_key(&doc),
180 cfg.proxy.output_holdout_fraction(),
181 );
182 // #493: in-band CCR expansion (opt-in). Splice any <lc_expand:HASH> the model
183 // echoed back into the verbatim original from the local tee store. A strict
184 // no-op when no marker is present (byte-identical body → cache-safe). Runs
185 // before the meter-only short-circuit so an explicit expand request is
186 // honored even when the proxy is otherwise byte-passthrough.
187 if cfg.proxy.ccr_inband_enabled() {
188 modified |= super::ccr::splice_inband_in_place(&mut doc);
189 }
190 // #834: cache-safe cross-provider effort control. Default off → no-op. The
191 // value is a constant, so it never perturbs the prompt-cache prefix; it only
192 // dials an *existing* adaptive thinking request (never enables thinking the
193 // client didn't ask for).
194 if arm == super::holdout::Arm::Treatment {
195 if let Some(effort) = cfg.proxy.resolved_effort() {
196 modified |= super::effort::apply_anthropic(&mut doc, effort);
197 }
198 // #895: cache-safe wire verbosity steer (constant suffix after the last
199 // cache_control breakpoint). Control arm skips it so the holdout measures
200 // its effect.
201 if cfg.proxy.verbosity_steer_enabled() {
202 modified |= super::verbosity::apply_anthropic(&mut doc);
203 }
204 }
205 // Meter-only (#481): live compression off, no history pruning, no prose
206 // rewriting → forward + usage metering still run, but the body is left
207 // unchanged so the provider prompt-cache prefix stays byte-stable. A pending
208 // in-band splice (`modified`) opts out: the body did change this turn.
209 if !live_compress
210 && mode == HistoryMode::Off
211 && system_aggr.is_none()
212 && user_aggr.is_none()
213 && !modified
214 && !inject_breakpoint
215 && !align_volatile
216 && !relocate_volatile
217 && !cache_economics
218 {
219 let out = serde_json::to_vec(&doc).unwrap_or_default();
220 return (out, original_size, original_size);
221 }
222 let mut prose_segments: u64 = 0;
223
224 // Length of the client's provider-cached message prefix. Needed both for
225 // cache-safe pruning below and to gate top-level system prose: if any
226 // message is client-cached, `system` (which precedes every message) is part
227 // of that cached prefix and must not be rewritten.
228 let cached = doc
229 .get("messages")
230 .and_then(|m| m.as_array())
231 .map_or(0, |m| super::history_prune::cached_prefix_len(m));
232
233 // #480: opt-in big-gap cold-prefix repack. When enabled AND the proxy can
234 // confidently predict (from idle time vs the provider cache TTL) that the
235 // client-cached prefix is already cold, override the normal "never touch the
236 // cached prefix" rule for THIS request and prune/compress the prefix too,
237 // re-seeding a leaner cache. Default-off; never fires without a measured idle
238 // gap past TTL × margin, so warm caches stay byte-stable (#448).
239 // #986: cache-economics miss attribution (opt-in, measurement-only). Classify
240 // why this turn hits or misses the provider prompt-cache (TTL lapse vs prefix
241 // change) and bump the `/status` gauges. Reads the cacheable prefix only — the
242 // body is never touched — so it is strictly cache-safe.
243 if cache_economics
244 && let Some(m) = doc.get("messages").and_then(|m| m.as_array())
245 && let Some(outcome) = super::cache_attribution::record_request(m, cached)
246 {
247 match outcome {
248 super::cache_attribution::CacheOutcome::WarmReuse => {
249 prefix_cache_stats::record_hit();
250 }
251 super::cache_attribution::CacheOutcome::ColdStart => {}
252 _ => {
253 prefix_cache_stats::record_miss();
254 }
255 }
256 }
257 // #480 repack decision, with the #986 net-cost gate folded in: when
258 // cache-economics is on, also require the prefix to be large enough to cache
259 // (`worth_repacking`). The gate is an extra AND-condition, so it can only make
260 // repacking *more* conservative; default-off proxies keep the prior value.
261 let repack = cfg.proxy.repacks_cold_prefix()
262 && doc
263 .get("messages")
264 .and_then(|m| m.as_array())
265 .is_some_and(|m| {
266 super::cold_prefix::repack_decision(m, cached)
267 && (!cache_economics
268 || super::cache_policy::worth_repacking(doc.get("system"), m, cached))
269 });
270 // The prefix length the rewrites below must protect: the full cached prefix
271 // normally, or 0 when we are intentionally repacking the cold prefix.
272 let protect = if repack { 0 } else { cached };
273
274 // System prose: only when nothing is client-cached and the `system` field
275 // carries no `cache_control` of its own — otherwise it anchors the cache.
276 // A cold-prefix repack (`protect == 0` with `repack`) deliberately rewrites
277 // it to re-seed a leaner cache.
278 let model_name = doc
279 .get("model")
280 .and_then(Value::as_str)
281 .unwrap_or("default")
282 .to_owned();
283 if let Some(a) = system_aggr
284 && protect == 0
285 && let Some(system) = doc.get_mut("system")
286 && (repack || !prose::value_has_cache_control(system))
287 {
288 let should_compress = if repack || cached == 0 {
289 true
290 } else {
291 let sys_tokens = prose::estimate_tokens(system) as u64;
292 let estimated_after = (sys_tokens as f64 * (1.0 - a)).max(0.0) as u64;
293 let reuse_rate = super::cache_attribution::estimated_reuse_rate();
294 let model_cost = super::cache_policy::model_cost_for(&model_name);
295 let gate = super::cache_policy::should_mutate_frozen(
296 sys_tokens,
297 estimated_after,
298 reuse_rate,
299 &model_cost,
300 );
301 matches!(gate, super::cache_policy::MutationDecision::Mutate { .. })
302 };
303 if should_compress {
304 let n = prose::compress_system_value(system, a);
305 if n > 0 {
306 prose_segments += u64::from(n);
307 modified = true;
308 }
309 }
310 }
311
312 if let Some(messages) = doc.get_mut("messages").and_then(|m| m.as_array_mut()) {
313 // Resolve tool-call id → tool name so file/source reads can be protected
314 // from lossy compression that would force the model to re-read mid-task.
315 let tool_names = tool_kind::anthropic_tool_names(messages);
316
317 // Prune at a frozen, cache-aware boundary by default: Anthropic's
318 // prompt cache matches exact prefixes, so the boundary must not move
319 // every turn (see `history_prune::prune_boundary`). `mode` resolved above.
320 let boundary = super::history_prune::prune_boundary(mode, messages.len());
321 // Never rewrite content the client has marked with `cache_control`:
322 // pruning inside the already-cached prefix invalidates Anthropic's
323 // prompt cache from the first changed message (#448). Pruning therefore
324 // starts after the last breakpoint; with no breakpoint this is 0, i.e.
325 // the previous behaviour.
326 modified |=
327 super::history_prune::prune_history_range(messages, protect, boundary, &tool_names);
328
329 for msg in messages.iter_mut() {
330 let role = msg.get("role").and_then(|r| r.as_str()).unwrap_or("");
331 if role != "user" {
332 continue;
333 }
334
335 if let Some(content) = msg.get_mut("content").and_then(|c| c.as_array_mut()) {
336 for block in content.iter_mut() {
337 if compress_shared::classify_tool_kind(block) != ToolKind::ToolResult {
338 continue;
339 }
340
341 let name = block
342 .get("tool_use_id")
343 .and_then(|v| v.as_str())
344 .and_then(|id| tool_names.get(id))
345 .map(String::as_str);
346 let kind = compress_shared::tool_result_kind(name);
347
348 // #481: skip live compression when globally off or when the
349 // originating tool is on the exclusion list (Serena default).
350 let excluded =
351 name.is_some_and(|n| cfg.proxy.is_tool_live_compress_excluded(n));
352 if live_compress
353 && !excluded
354 && let Some(inner_content) = block.get_mut("content")
355 {
356 modified |= compress_content_field(inner_content, name, kind);
357 }
358 }
359 }
360 }
361
362 // Frozen-region user prose: free-text `text` blocks of user turns in
363 // `[cached, boundary)`. Cache-safe by construction — the cached prefix
364 // and the live tail (`>= boundary`) are both left intact, and the
365 // rewrite is content-deterministic so the prefix stays byte-stable.
366 if let Some(a) = user_aggr {
367 let end = boundary.min(messages.len());
368 let start = protect.min(end);
369 for msg in &mut messages[start..end] {
370 if msg.get("role").and_then(|r| r.as_str()) == Some("user")
371 && let Some(content) = msg.get_mut("content").and_then(|c| c.as_array_mut())
372 {
373 prose_segments += u64::from(prose::compress_text_blocks(content, a));
374 }
375 }
376 }
377 }
378
379 if prose_segments > 0 {
380 modified = true;
381 }
382 // #940: cache-aligner telemetry. On an unanchored system prompt (the prefix a
383 // provider would cache), count the volatile fields that would bust that cache
384 // turn-to-turn. Pure measurement — runs before any breakpoint injection and
385 // never mutates the body — so it is strictly cache-safe. Skipped once the
386 // client has anchored the prefix itself.
387 if align_volatile
388 && cached == 0
389 && let Some(system) = doc.get("system")
390 && !prose::value_has_cache_control(system)
391 && let Some(text) = super::cache_aligner::system_text(system)
392 {
393 let scan = super::cache_aligner::scan_volatile(&text);
394 cache_safety::record_volatile_system(scan.fields as u64);
395 }
396 // #974: active cache-aligner relocate (Anthropic-only). After the telemetry
397 // above measured the leak on the pristine prompt, move the volatile values out
398 // of the cacheable prefix into an uncached tail block so the prefix finally
399 // caches. Gated exactly like the breakpoint below — Treatment arm, and only
400 // when the client anchored nothing of its own. The rewrite adds the
401 // `cache_control` itself, so a following #939 injection sees an anchored prefix
402 // and stays a no-op: the two compose to exactly one breakpoint on the stable
403 // block, with the volatile tail left uncached.
404 if relocate_volatile
405 && arm == super::holdout::Arm::Treatment
406 && cached == 0
407 && doc
408 .get("system")
409 .is_some_and(|s| !prose::value_has_cache_control(s))
410 {
411 let relocated = super::cache_aligner::apply_anthropic_relocate(&mut doc);
412 if relocated > 0 {
413 modified = true;
414 cache_safety::record_volatile_relocated(relocated as u64);
415 }
416 }
417 // #939: active prompt-cache breakpoint injection (Anthropic-only). When the
418 // client anchored no prefix of its own — no message `cache_control` (`cached
419 // == 0`) and no breakpoint already on `system` — add one ephemeral breakpoint
420 // to `system` so the large, stable system prompt bills later turns at the
421 // cached rate (the win a raw API client leaves on the table). Runs after every
422 // frozen-region rewrite so the marker anchors the final system bytes and the
423 // prefix it creates stays byte-stable across turns (#498). Counted on its own
424 // gauge — a pure win, never against the cache-safe ratio.
425 if inject_breakpoint
426 && cached == 0
427 && doc
428 .get("system")
429 .is_some_and(|s| !prose::value_has_cache_control(s))
430 && super::cache_breakpoint::inject_anthropic_system(&mut doc)
431 {
432 modified = true;
433 cache_safety::record_breakpoint_injected();
434 }
435 // A deliberate cold-prefix repack (#480) is the one sanctioned exception to
436 // the frozen-window rule; count it on its own gauge so it never dilutes the
437 // cache-safe ratio (which exists to catch *accidental* #448 regressions).
438 // Every other rewrite lands strictly inside the cache-safe frozen window.
439 if repack {
440 cache_safety::record_cold_repack();
441 }
442 cache_safety::record(prose_segments, true);
443
444 // Sticky CCR tool injection: once a conversation has used CCR, keep
445 // ctx_expand in tools[] to avoid prefix-cache-busting tool-list changes.
446 let system_val = doc.get("system");
447 let messages_for_id = doc.get("messages").and_then(Value::as_array);
448 if let Some(msgs) = messages_for_id {
449 let conv_id = prefix_replay::conversation_id(system_val, msgs);
450 if sticky_tools::ensure_tool_present(conv_id, &mut doc) {
451 modified = true;
452 prefix_cache_stats::record_sticky_injection();
453 }
454 }
455
456 prefix_cache_stats::record_frozen_count(cached as u64);
457
458 // Prefix replay: if this is an append-only turn, overlay the cached
459 // forwarded prefix bytes with the fresh delta for byte-identical prefix.
460 let system_val_replay = doc.get("system");
461 let msgs_replay = doc.get("messages").and_then(Value::as_array);
462 let out = if let Some(msgs) = msgs_replay {
463 let conv_id = prefix_replay::conversation_id(system_val_replay, msgs);
464 if let Some(delta) = prefix_replay::detect_append_only(conv_id, msgs) {
465 let delta_msgs = &msgs[delta.delta_start..];
466 if let Some(replayed) = prefix_replay::overlay_prefix(&delta.prefix_bytes, delta_msgs) {
467 prefix_cache_stats::record_replay_hit();
468 let original_bytes = serde_json::to_vec(&doc).unwrap_or_default();
469 prefix_cache_stats::record_delta(
470 original_bytes.len() as u64,
471 replayed.len() as u64,
472 );
473 replayed
474 } else {
475 prefix_cache_stats::record_replay_miss();
476 serde_json::to_vec(&doc).unwrap_or_default()
477 }
478 } else {
479 prefix_cache_stats::record_replay_miss();
480 serde_json::to_vec(&doc).unwrap_or_default()
481 }
482 } else {
483 serde_json::to_vec(&doc).unwrap_or_default()
484 };
485 let compressed_size = if modified { out.len() } else { original_size };
486 (out, original_size, compressed_size)
487}
488
489/// Compresses a tool_result `content` field unless it is a protected file/source
490/// read, which must reach the model intact (it is what gets edited).
491fn compress_content_field(
492 content: &mut Value,
493 tool_name: Option<&str>,
494 kind: ToolResultKind,
495) -> bool {
496 match content {
497 Value::String(s) => super::tool_output::compress_text(s, tool_name, kind),
498 Value::Array(arr) => {
499 let mut modified = false;
500 for item in arr.iter_mut() {
501 if compress_shared::should_compress_content(compress_shared::classify_tool_kind(
502 item,
503 )) && let Some(Value::String(text)) = item.get_mut("text")
504 {
505 modified |= super::tool_output::compress_text(text, tool_name, kind);
506 }
507 }
508 modified
509 }
510 _ => false,
511 }
512}
513
514#[cfg(test)]
515#[path = "anthropic_tests.rs"]
516mod tests;