use serde_json::{Map, Value};
use crate::core::tokens::count_tokens;
const MIN_CACHEABLE_TOKENS: usize = 1024;
fn ephemeral() -> Value {
serde_json::json!({ "type": "ephemeral" })
}
pub(crate) fn inject_anthropic_system(doc: &mut Value) -> bool {
let Some(system) = doc.get_mut("system") else {
return false;
};
match system {
Value::String(s) => {
if count_tokens(s) < MIN_CACHEABLE_TOKENS {
return false;
}
let text = std::mem::take(s);
let mut block = Map::new();
block.insert("type".into(), Value::String("text".into()));
block.insert("text".into(), Value::String(text));
block.insert("cache_control".into(), ephemeral());
*system = Value::Array(vec![Value::Object(block)]);
true
}
Value::Array(blocks) => {
if blocks.iter().any(|b| b.get("cache_control").is_some()) {
return false;
}
let total: usize = blocks
.iter()
.filter_map(|b| b.get("text").and_then(Value::as_str))
.map(count_tokens)
.sum();
if total < MIN_CACHEABLE_TOKENS {
return false;
}
let Some(last) = blocks.last_mut().and_then(Value::as_object_mut) else {
return false;
};
last.insert("cache_control".into(), ephemeral());
true
}
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn big_system() -> String {
"You are a meticulous senior engineer. ".repeat(400)
}
#[test]
fn wraps_string_system_into_cache_marked_block() {
let mut doc = serde_json::json!({ "system": big_system(), "messages": [] });
assert!(inject_anthropic_system(&mut doc));
let block = &doc["system"][0];
assert_eq!(block["type"], "text");
assert_eq!(block["cache_control"]["type"], "ephemeral");
assert!(
block["text"].as_str().unwrap().contains("senior engineer"),
"the original system text must be preserved verbatim in the block"
);
}
#[test]
fn marks_last_block_of_array_system() {
let mut doc = serde_json::json!({
"system": [
{ "type": "text", "text": big_system() },
{ "type": "text", "text": big_system() }
],
"messages": []
});
assert!(inject_anthropic_system(&mut doc));
assert!(
doc["system"][0].get("cache_control").is_none(),
"only the last block is marked"
);
assert_eq!(doc["system"][1]["cache_control"]["type"], "ephemeral");
}
#[test]
fn skips_small_system_and_missing_system() {
let mut small = serde_json::json!({ "system": "be terse", "messages": [] });
assert!(
!inject_anthropic_system(&mut small),
"below the cacheable floor → no churn"
);
let mut none = serde_json::json!({ "messages": [] });
assert!(!inject_anthropic_system(&mut none));
}
#[test]
fn never_adds_a_second_breakpoint() {
let mut doc = serde_json::json!({
"system": [
{ "type": "text", "text": big_system(), "cache_control": { "type": "ephemeral" } }
],
"messages": []
});
assert!(
!inject_anthropic_system(&mut doc),
"a client breakpoint must be left as the sole anchor"
);
}
#[test]
fn injection_is_deterministic() {
let mk = || serde_json::json!({ "system": big_system(), "messages": [] });
let mut a = mk();
let mut b = mk();
assert!(inject_anthropic_system(&mut a));
assert!(inject_anthropic_system(&mut b));
assert_eq!(
a, b,
"identical input must yield byte-identical output (#498)"
);
}
}