use super::types::EPHEMERAL_MARKER_FIELD;
use serde_json::Value;
use std::collections::HashSet;
pub type BlockPredicate<'a> = dyn Fn(&serde_json::Map<String, Value>) -> bool + 'a;
pub fn drop_blocks(messages: Vec<Value>, pred: &BlockPredicate) -> Vec<Value> {
let dropped_tool_use_ids = collect_dropped_tool_use_ids(&messages, pred);
let mut out: Vec<Value> = Vec::with_capacity(messages.len());
for msg in messages {
let Some(obj) = msg.as_object() else {
out.push(msg);
continue;
};
let Some(content) = obj.get("content").and_then(Value::as_array) else {
out.push(msg);
continue;
};
let (kept, changed) = filter_blocks(content, pred, &dropped_tool_use_ids);
if !changed {
out.push(msg);
continue;
}
if kept.is_empty() {
continue;
}
let mut new_obj = obj.clone();
new_obj.insert("content".to_string(), Value::Array(kept));
out.push(Value::Object(new_obj));
}
out
}
fn collect_dropped_tool_use_ids(messages: &[Value], pred: &BlockPredicate) -> HashSet<String> {
let mut ids: HashSet<String> = HashSet::new();
for msg in messages {
let Some(content) = msg
.as_object()
.and_then(|o| o.get("content"))
.and_then(Value::as_array)
else {
continue;
};
for raw in content {
let Some(block) = raw.as_object() else {
continue;
};
if !pred(block) {
continue;
}
let Some(t) = block.get("type").and_then(Value::as_str) else {
continue;
};
if t == "tool_use" || t == "server_tool_use" || t == "mcp_tool_use" {
if let Some(id) = block.get("id").and_then(Value::as_str) {
if !id.is_empty() {
ids.insert(id.to_string());
}
}
}
}
}
ids
}
fn filter_blocks(
content: &[Value],
pred: &BlockPredicate,
dropped_tool_use_ids: &HashSet<String>,
) -> (Vec<Value>, bool) {
let mut kept: Vec<Value> = Vec::with_capacity(content.len());
let mut changed = false;
for raw in content {
let Some(block) = raw.as_object() else {
kept.push(raw.clone());
continue;
};
if pred(block) {
changed = true;
continue;
}
if !dropped_tool_use_ids.is_empty() {
let t = block.get("type").and_then(Value::as_str);
if t == Some("tool_result") || t == Some("mcp_tool_result") {
if let Some(id) = block.get("tool_use_id").and_then(Value::as_str) {
if !id.is_empty() && dropped_tool_use_ids.contains(id) {
changed = true;
continue;
}
}
}
}
kept.push(raw.clone());
}
(kept, changed)
}
pub fn strip_ephemeral(messages: Vec<Value>) -> Vec<Value> {
drop_blocks(messages, &|block| {
match block.get("type").and_then(Value::as_str) {
Some("thinking") | Some("redacted_thinking") => false,
_ => block.get(EPHEMERAL_MARKER_FIELD) == Some(&Value::Bool(true)),
}
})
}