use causa_kernel::{
BlockContent, BlockId, BlockMeta, Context, ContextBlock, ContextFrame, EditFailure,
GenerationOptions, MediaRef, ModelItem, ModelRef, ModelResponse, ModelStopReason, Role,
TextPayload, ToolCallDraft, ToolOutput, ToolResultPayload, ToolResultStatus,
validate_tool_result_append,
};
use causa_protocol::translation::anthropic::render_anthropic_messages;
use causa_protocol::translation::openai_chat::render_openai_chat_messages;
use causa_protocol::translation::openai_responses::render_openai_responses_input;
use causa_protocol::translation::render_options::{
AnthropicRenderOptions, ChatRenderOptions, ResponsesRenderOptions,
};
use serde_json::{Value, json};
use std::sync::atomic::{AtomicUsize, Ordering};
static NEXT_BLOCK_ID: AtomicUsize = AtomicUsize::new(1);
fn block_id() -> BlockId {
BlockId::new(uuid::Uuid::from_u128(
NEXT_BLOCK_ID.fetch_add(1, Ordering::Relaxed) as u128,
))
}
trait FixtureAppend {
fn push_text(
&mut self,
id: BlockId,
text: TextPayload,
source: &str,
) -> Result<(), EditFailure>;
fn push_response(
&mut self,
response: &ModelResponse,
stop: ModelStopReason,
ids: Vec<BlockId>,
) -> Result<Vec<BlockId>, Box<dyn std::error::Error>>;
fn push_results(
&mut self,
results: Vec<(BlockId, ToolResultPayload)>,
) -> Result<(), Box<dyn std::error::Error>>;
}
impl FixtureAppend for Context {
fn push_text(
&mut self,
id: BlockId,
text: TextPayload,
source: &str,
) -> Result<(), EditFailure> {
let role = match source {
"system" => Role::System,
"assistant" => Role::Assistant,
_ => Role::User,
};
self.edit()
.append([ContextBlock::new(
id,
BlockContent::text(role, text.0),
BlockMeta::from_source(source),
)])
.commit()
}
fn push_response(
&mut self,
response: &ModelResponse,
stop: ModelStopReason,
ids: Vec<BlockId>,
) -> Result<Vec<BlockId>, Box<dyn std::error::Error>> {
let blocks = response.to_blocks(stop, &ids)?;
let calls = blocks
.iter()
.filter_map(|block| {
matches!(block.content(), BlockContent::ToolCall(_)).then_some(block.id())
})
.collect();
self.edit().append(blocks).commit()?;
Ok(calls)
}
fn push_results(
&mut self,
results: Vec<(BlockId, ToolResultPayload)>,
) -> Result<(), Box<dyn std::error::Error>> {
validate_tool_result_append(self.blocks(), &results)?;
self.edit()
.append(results.into_iter().map(|(id, result)| {
ContextBlock::new(id, BlockContent::ToolResult(result), BlockMeta::default())
}))
.commit()?;
Ok(())
}
}
fn material(build: impl FnOnce(&mut Context)) -> Context {
let mut context = Context::new();
build(&mut context);
context
}
fn joined_frame(retained: Vec<Context>, current: Context) -> ContextFrame {
ContextFrame {
blocks: retained
.into_iter()
.chain([current])
.flat_map(Context::into_blocks)
.collect(),
}
}
fn scenario_frame() -> ContextFrame {
let history = vec![material(|active| {
active
.push_text(block_id(), TextPayload::new("be terse"), "system")
.unwrap();
active
.push_text(block_id(), TextPayload::new("find the file"), "user")
.unwrap();
let applied = active
.push_response(
&ModelResponse {
items: vec![
ModelItem::text("reading"),
ModelItem::tool_call(
ToolCallDraft::new("read", json!({"path": "a"}))
.with_provider_call_id("toolu_1"),
),
],
},
ModelStopReason::ToolUse,
vec![block_id(), block_id()],
)
.unwrap();
let call_block_id = applied[0];
active
.push_results(vec![(
block_id(),
ToolResultPayload::new(
call_block_id,
ToolResultStatus::Succeeded,
ToolOutput::new(json!("file-a")),
),
)])
.unwrap();
})];
let mut active = Context::new();
active
.push_text(block_id(), TextPayload::new("and now?"), "user")
.unwrap();
active
.push_response(
&ModelResponse {
items: vec![ModelItem::text("done")],
},
ModelStopReason::EndTurn,
vec![block_id()],
)
.unwrap();
joined_frame(history, active)
}
fn render(frame: &ContextFrame) -> (Value, Value, Value) {
let model = ModelRef::new("test-model");
let generation = GenerationOptions::default().with_max_tokens(1024);
let media = causa_protocol::translation::media::MediaSet::new();
(
render_anthropic_messages(
frame,
&media,
&generation,
&model,
causa_kernel::CacheDirective::None,
&AnthropicRenderOptions::default(),
)
.unwrap(),
render_openai_chat_messages(
frame,
&media,
&generation,
&model,
causa_kernel::CacheDirective::None,
&ChatRenderOptions::default(),
)
.unwrap(),
render_openai_responses_input(
frame,
&media,
&generation,
&model,
causa_kernel::CacheDirective::None,
&ResponsesRenderOptions::default(),
)
.unwrap(),
)
}
#[test]
fn tool_result_notes_and_media_render_with_their_own_result() {
use causa_protocol::translation::media::{MediaPayload, MediaSet};
let mut turn = Context::new();
turn.push_text(block_id(), TextPayload::new("search"), "user")
.unwrap();
let applied = turn
.push_response(
&ModelResponse {
items: vec![ModelItem::tool_call(
ToolCallDraft::new("search", json!({"limit": 20}))
.with_provider_call_id("external-call-7"),
)],
},
ModelStopReason::ToolUse,
vec![block_id()],
)
.unwrap();
let media_ref = MediaRef::new("image/png", "search-image");
turn.push_results(vec![(
block_id(),
ToolResultPayload::new(
applied[0],
ToolResultStatus::Succeeded,
ToolOutput::new(json!({"found": 1})),
)
.with_media(vec![media_ref.clone()])
.with_notes(vec![
TextPayload::new("The limit was reduced to 5."),
TextPayload::new("The result includes one image."),
]),
)])
.unwrap();
let frame = joined_frame(vec![], turn);
let mut media = MediaSet::new();
media.insert("search-image", MediaPayload::new("image/png", "aGVsbG8="));
let model = ModelRef::new("test-model");
let generation = GenerationOptions::default().with_max_tokens(1024);
let anthropic = render_anthropic_messages(
&frame,
&media,
&generation,
&model,
causa_kernel::CacheDirective::None,
&AnthropicRenderOptions::default(),
)
.unwrap();
let chat = render_openai_chat_messages(
&frame,
&media,
&generation,
&model,
causa_kernel::CacheDirective::None,
&ChatRenderOptions::default(),
)
.unwrap();
let responses = render_openai_responses_input(
&frame,
&media,
&generation,
&model,
causa_kernel::CacheDirective::None,
&ResponsesRenderOptions::default(),
)
.unwrap();
let expected_notes =
"{\"found\":1}\n\nNotes:\n- The limit was reduced to 5.\n- The result includes one image.";
let anthropic_result = &anthropic["messages"][2]["content"][0];
assert_eq!(anthropic_result["type"], "tool_result");
let anthropic_parts = anthropic_result["content"].as_array().unwrap();
assert_eq!(anthropic_parts[0]["text"], "{\"found\":1}");
assert_eq!(anthropic_parts[1]["text"], "Notes:");
assert_eq!(anthropic_parts[2]["text"], "- The limit was reduced to 5.");
assert_eq!(
anthropic_parts[3]["text"],
"- The result includes one image."
);
assert_eq!(anthropic_parts[4]["type"], "image");
let chat_result = &chat["messages"][2];
assert_eq!(chat_result["role"], "tool");
assert_eq!(chat_result["tool_call_id"], "external-call-7");
assert_eq!(chat_result["content"], expected_notes);
assert_eq!(chat["messages"][3]["content"][1]["type"], "image_url");
let response_result = &responses["input"][2];
assert_eq!(response_result["type"], "function_call_output");
assert_eq!(response_result["call_id"], "external-call-7");
assert_eq!(response_result["output"], expected_notes);
assert_eq!(responses["input"][3]["content"][1]["type"], "input_image");
let stored_result = frame
.blocks
.iter()
.find_map(|block| match block.content() {
causa_kernel::BlockContent::ToolResult(result) => Some(result),
_ => None,
})
.unwrap();
assert_eq!(stored_result.output.content, json!({"found": 1}));
}
#[derive(Debug, Clone, PartialEq)]
enum Step {
System(String),
UserText(String),
AssistantText(String),
Assistant {
text: String,
calls: Vec<(String, String, Value)>,
},
AssistantCall {
wire_id: String,
name: String,
arguments: Value,
},
ToolResult {
wire_id: String,
content: String,
},
}
fn merge_steps(steps: Vec<Step>) -> Vec<Step> {
let mut merged: Vec<Step> = Vec::new();
for step in steps {
match (&step, merged.last_mut()) {
(Step::UserText(t), Some(Step::UserText(last))) => {
last.push('\n');
last.push_str(t);
}
(Step::AssistantText(t), Some(Step::Assistant { text, .. })) => {
text.push('\n');
text.push_str(t);
}
(
Step::AssistantCall {
wire_id,
name,
arguments,
},
Some(Step::Assistant { calls, .. }),
) => {
calls.push((wire_id.clone(), name.clone(), arguments.clone()));
}
(Step::AssistantText(t), _) => merged.push(Step::Assistant {
text: t.clone(),
calls: vec![],
}),
(Step::AssistantCall { .. }, _) => merged.push(Step::Assistant {
text: String::new(),
calls: vec![],
}),
_ => merged.push(step),
}
}
merged
}
fn expected_timeline() -> Vec<Step> {
vec![
Step::System("be terse".into()),
Step::UserText("find the file".into()),
Step::Assistant {
text: "reading".into(),
calls: vec![("toolu_1".into(), "read".into(), json!({"path": "a"}))],
},
Step::ToolResult {
wire_id: "toolu_1".into(),
content: "file-a".into(),
},
Step::UserText("and now?".into()),
Step::Assistant {
text: "done".into(),
calls: vec![],
},
]
}
fn anthropic_steps(body: &Value) -> Vec<Step> {
let mut steps = Vec::new();
if let Some(system) = body.get("system").and_then(Value::as_array) {
for block in system {
if let Some(text) = block.get("text").and_then(Value::as_str) {
steps.push(Step::System(text.to_string()));
}
}
}
for message in body["messages"].as_array().unwrap() {
let role = message["role"].as_str().unwrap();
for block in message["content"].as_array().unwrap() {
match (role, block["type"].as_str().unwrap()) {
(_, "text") => {
let text = block["text"].as_str().unwrap().to_string();
if role == "assistant" {
steps.push(Step::AssistantText(text));
} else {
steps.push(Step::UserText(text));
}
}
("assistant", "tool_use") => steps.push(Step::AssistantCall {
wire_id: block["id"].as_str().unwrap().into(),
name: block["name"].as_str().unwrap().into(),
arguments: block["input"].clone(),
}),
(_, "tool_result") => steps.push(Step::ToolResult {
wire_id: block["tool_use_id"].as_str().unwrap().into(),
content: block["content"].as_str().unwrap().into(),
}),
other => panic!("unexpected anthropic block: {other:?}"),
}
}
}
merge_steps(steps)
}
fn chat_steps(body: &Value) -> Vec<Step> {
let mut steps = Vec::new();
for message in body["messages"].as_array().unwrap() {
match message["role"].as_str().unwrap() {
"system" => steps.push(Step::System(message["content"].as_str().unwrap().into())),
"user" => steps.push(Step::UserText(message["content"].as_str().unwrap().into())),
"assistant" => {
if let Some(text) = message.get("content").and_then(Value::as_str) {
steps.push(Step::AssistantText(text.into()));
}
for call in message
.get("tool_calls")
.and_then(Value::as_array)
.map_or(&[] as &[Value], |v| v)
{
let arguments: Value =
serde_json::from_str(call["function"]["arguments"].as_str().unwrap())
.unwrap();
steps.push(Step::AssistantCall {
wire_id: call["id"].as_str().unwrap().into(),
name: call["function"]["name"].as_str().unwrap().into(),
arguments,
});
}
}
"tool" => steps.push(Step::ToolResult {
wire_id: message["tool_call_id"].as_str().unwrap().into(),
content: message["content"].as_str().unwrap().into(),
}),
other => panic!("unexpected chat role: {other:?}"),
}
}
merge_steps(steps)
}
fn responses_steps(body: &Value) -> Vec<Step> {
let mut steps = Vec::new();
if let Some(instructions) = body.get("instructions").and_then(Value::as_str) {
steps.push(Step::System(instructions.to_string()));
}
for item in body["input"].as_array().unwrap() {
match item["type"].as_str().unwrap_or("message") {
"message" => {
let role = item["role"].as_str().unwrap();
for part in item["content"].as_array().unwrap() {
let text = part["text"].as_str().unwrap().to_string();
if role == "assistant" {
steps.push(Step::AssistantText(text));
} else {
steps.push(Step::UserText(text));
}
}
}
"function_call" => {
let arguments: Value =
serde_json::from_str(item["arguments"].as_str().unwrap()).unwrap();
steps.push(Step::AssistantCall {
wire_id: item["call_id"].as_str().unwrap().into(),
name: item["name"].as_str().unwrap().into(),
arguments,
});
}
"function_call_output" => steps.push(Step::ToolResult {
wire_id: item["call_id"].as_str().unwrap().into(),
content: item["output"].as_str().unwrap().into(),
}),
other => panic!("unexpected responses item: {other:?}"),
}
}
merge_steps(steps)
}
#[test]
fn all_three_protocols_produce_the_same_semantic_timeline() {
let (anthropic, chat, responses) = render(&scenario_frame());
let expected = expected_timeline();
assert_eq!(anthropic_steps(&anthropic), expected, "anthropic");
assert_eq!(chat_steps(&chat), expected, "openai chat");
assert_eq!(responses_steps(&responses), expected, "openai responses");
}
#[test]
fn system_instruction_leads_every_protocol_body() {
let (anthropic, chat, responses) = render(&scenario_frame());
assert_eq!(
anthropic["system"],
json!([{"type": "text", "text": "be terse"}])
);
assert_eq!(chat["messages"][0]["role"], json!("system"));
assert_eq!(chat["messages"][0]["content"], json!("be terse"));
assert_eq!(responses["instructions"], json!("be terse"));
}
#[test]
fn tool_pairing_round_trips_through_every_protocol() {
let (anthropic, chat, responses) = render(&scenario_frame());
let messages = anthropic["messages"].as_array().unwrap();
let use_id = messages[1]["content"]
.as_array()
.unwrap()
.iter()
.find(|b| b["type"] == "tool_use")
.map(|b| b["id"].as_str().unwrap())
.unwrap();
let result_id = messages[2]["content"]
.as_array()
.unwrap()
.iter()
.find(|b| b["type"] == "tool_result")
.map(|b| b["tool_use_id"].as_str().unwrap())
.unwrap();
assert_eq!(use_id, result_id);
let chat_messages = chat["messages"].as_array().unwrap();
let call_id = chat_messages
.iter()
.find(|m| m["role"] == "assistant" && m.get("tool_calls").is_some())
.map(|m| m["tool_calls"][0]["id"].as_str().unwrap())
.unwrap();
let result_id = chat_messages
.iter()
.find(|m| m["role"] == "tool")
.map(|m| m["tool_call_id"].as_str().unwrap())
.unwrap();
assert_eq!(call_id, result_id);
let responses_call_id = responses["input"][2]["call_id"].as_str().unwrap();
let responses_result_id = responses["input"][3]["call_id"].as_str().unwrap();
assert_eq!(responses_call_id, responses_result_id);
}
#[test]
fn content_shapes_survive_all_three_renderers() {
let history = vec![];
let mut active = Context::new();
active
.push_text(block_id(), TextPayload::new("go"), "user")
.unwrap();
let applied = active
.push_response(
&ModelResponse {
items: vec![
ModelItem::text("listing"),
ModelItem::tool_call(ToolCallDraft::new("list", json!({"dir": "/"}))),
],
},
ModelStopReason::ToolUse,
vec![block_id(), block_id()],
)
.unwrap();
active
.push_results(vec![(
block_id(),
ToolResultPayload::new(
applied[0],
ToolResultStatus::Failed,
ToolOutput::new(json!({"error": "denied"})),
),
)])
.unwrap();
let frame = joined_frame(history, active);
let (anthropic, chat, responses) = render(&frame);
let expected_payload = json!({"error": "denied"}).to_string();
assert_eq!(
anthropic["messages"][2]["content"][0]["content"],
json!(expected_payload)
);
assert_eq!(
anthropic["messages"][2]["content"][0]["is_error"],
json!(true)
);
assert_eq!(chat["messages"][2]["content"], json!(expected_payload));
assert_eq!(responses["input"][3]["output"], json!(expected_payload));
}
#[test]
fn tool_results_keep_their_declaration_identity_across_selected_materials() {
let mut history = Vec::new();
for (turn_name, wire_id) in [("t1", "provider_first"), ("t2", "provider_second")] {
history.push(material(|turn| {
turn.push_text(block_id(), TextPayload::new("read again"), "user")
.unwrap();
let applied = turn
.push_response(
&ModelResponse {
items: vec![ModelItem::tool_call(
ToolCallDraft::new("read", json!({"path": "same"}))
.with_provider_call_id(wire_id),
)],
},
ModelStopReason::ToolUse,
vec![block_id()],
)
.unwrap();
turn.push_results(vec![(
block_id(),
ToolResultPayload::new(
applied[0],
ToolResultStatus::Succeeded,
ToolOutput::new(json!(turn_name)),
),
)])
.unwrap();
}));
}
let mut active = Context::new();
active
.push_text(block_id(), TextPayload::new("next"), "user")
.unwrap();
let frame = joined_frame(history, active);
let (anthropic, chat, responses) = render(&frame);
let anthropic_call_ids: Vec<&str> = anthropic["messages"]
.as_array()
.unwrap()
.iter()
.flat_map(|m| m["content"].as_array().unwrap())
.filter(|b| b["type"] == "tool_use")
.map(|b| b["id"].as_str().unwrap())
.collect();
let chat_call_ids: Vec<&str> = chat["messages"]
.as_array()
.unwrap()
.iter()
.flat_map(|m| m["tool_calls"].as_array().into_iter().flatten())
.map(|call| call["id"].as_str().unwrap())
.collect();
let responses_call_ids: Vec<&str> = responses["input"]
.as_array()
.unwrap()
.iter()
.filter(|item| item["type"] == "function_call")
.map(|item| item["call_id"].as_str().unwrap())
.collect();
let anthropic_ids: Vec<&str> = anthropic["messages"]
.as_array()
.unwrap()
.iter()
.flat_map(|m| m["content"].as_array().unwrap())
.filter(|b| b["type"] == "tool_result")
.map(|b| b["tool_use_id"].as_str().unwrap())
.collect();
let chat_ids: Vec<&str> = chat["messages"]
.as_array()
.unwrap()
.iter()
.filter(|m| m["role"] == "tool")
.map(|m| m["tool_call_id"].as_str().unwrap())
.collect();
let responses_ids: Vec<&str> = responses["input"]
.as_array()
.unwrap()
.iter()
.filter(|b| b["type"] == "function_call_output")
.map(|b| b["call_id"].as_str().unwrap())
.collect();
let expected_ids = vec!["provider_first", "provider_second"];
assert_eq!(anthropic_call_ids, expected_ids);
assert_eq!(chat_call_ids, expected_ids);
assert_eq!(responses_call_ids, expected_ids);
assert_eq!(anthropic_ids, expected_ids);
assert_eq!(chat_ids, expected_ids);
assert_eq!(responses_ids, expected_ids);
let anthropic_results: Vec<String> = anthropic["messages"]
.as_array()
.unwrap()
.iter()
.flat_map(|m| m["content"].as_array().unwrap())
.filter(|b| b["type"] == "tool_result")
.map(|b| {
b["content"]
.as_str()
.or_else(|| b["content"][0]["text"].as_str())
.unwrap()
.to_owned()
})
.collect();
let chat_results: Vec<&str> = chat["messages"]
.as_array()
.unwrap()
.iter()
.filter(|m| m["role"] == "tool")
.map(|m| m["content"].as_str().unwrap())
.collect();
let responses_results: Vec<&str> = responses["input"]
.as_array()
.unwrap()
.iter()
.filter(|item| item["type"] == "function_call_output")
.map(|item| item["output"].as_str().unwrap())
.collect();
assert_eq!(anthropic_results, vec!["t1", "t2"]);
assert_eq!(chat_results, vec!["t1", "t2"]);
assert_eq!(responses_results, vec!["t1", "t2"]);
}