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