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