Skip to content

Switchyard lets LLM applications route traffic across models and providers while preserving native OpenAI and Anthropic API compatibility - enabling flexible model selection, benchmarking, and cost/performance optimization.

Rust
139 KB
Raw Blame
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Tests for translating streaming provider events through the stream IR.

pub mod common;

use std::collections::HashMap;

use pretty_assertions::assert_eq;
use serde_json::{Value, json};
use switchyard_protocol::{LlmResponseStreamEvent, ResponseAccumulator, StopReason};
use switchyard_translation::{
    LlmResponseChunk, StreamTranslationState, TranslationEngine, WireFormat, decode_stream_event,
};

use common::{REASONING_MODEL, text_and_encrypted_reasoning_details};

type TestResult = std::result::Result<(), Box<dyn std::error::Error + Send + Sync>>;

#[test]
fn fragmented_chat_tool_names_are_complete_in_cross_format_streams() -> TestResult {
    let engine = TranslationEngine::default();
    for target in [WireFormat::AnthropicMessages, WireFormat::OpenAiResponses] {
        for (early_arguments, arguments) in [("{", "}"), ("", "{}"), ("", "")] {
            let mut state = StreamTranslationState::new(WireFormat::OpenAiChat, target);
            let mut events = Vec::new();
            for event in [
                json!({"choices": [{"delta": {"tool_calls": [{"index": 0,
                    "id": "call_weather", "function": {"name": "wea", "arguments": ""}}]}}]}),
                json!({"choices": [{"delta": {"tool_calls": [{"index": 0,
                    "function": {"arguments": early_arguments}}]}}]}),
                json!({"choices": [{"delta": {"tool_calls": [{"index": 0,
                    "function": {"name": "ther", "arguments": arguments}}]}}]}),
                json!({"choices": [{"delta": {}, "finish_reason": "tool_calls"}]}),
            ] {
                let translated =
                    engine.translate_event(&mut state, WireFormat::OpenAiChat, target, &event)?;
                if event["choices"][0]["finish_reason"].is_null() {
                    assert!(
                        translated.iter().all(|event| {
                            event["type"] != "content_block_start"
                                && event["type"] != "response.output_item.added"
                        }),
                        "tool name must not be announced before completion"
                    );
                }
                events.extend(translated);
            }
            events.extend(engine.finish_stream(&mut state, target)?);
            let names: Vec<_> = events
                .iter()
                .filter_map(|event| {
                    event
                        .get("content_block")
                        .or_else(|| event.get("item"))?
                        .get("name")?
                        .as_str()
                })
                .collect();
            let expected = if target == WireFormat::AnthropicMessages {
                vec!["weather"]
            } else {
                vec!["weather", "weather"]
            };
            assert_eq!(names, expected, "{target:?}, arguments={arguments:?}");
            let emitted_arguments: String = events
                .iter()
                .filter_map(|event| {
                    if event["type"] == "response.function_call_arguments.delta" {
                        event["delta"].as_str()
                    } else {
                        event["delta"]["partial_json"].as_str()
                    }
                })
                .collect();
            assert_eq!(emitted_arguments, format!("{early_arguments}{arguments}"));
        }
    }
    Ok(())
}

// Reduces Anthropic stream events to ordered labels (`<block>_start`, `<delta>`,
// `<block>_stop`) so ordering assertions stay readable without restating each payload.
fn event_labels(events: &[Value]) -> Vec<String> {
    let mut block_types: HashMap<u64, String> = HashMap::new();
    events
        .iter()
        .map(|event| {
            let index = event
                .get("index")
                .and_then(Value::as_u64)
                .unwrap_or_default();
            match event
                .get("type")
                .and_then(Value::as_str)
                .unwrap_or_default()
            {
                "content_block_start" => {
                    let block_type = event
                        .get("content_block")
                        .and_then(|block| block.get("type"))
                        .and_then(Value::as_str)
                        .unwrap_or_default()
                        .to_string();
                    block_types.insert(index, block_type.clone());
                    format!("{block_type}_start")
                }
                "content_block_delta" => event
                    .get("delta")
                    .and_then(|delta| delta.get("type"))
                    .and_then(Value::as_str)
                    .unwrap_or_default()
                    .to_string(),
                "content_block_stop" => {
                    let block_type = block_types.get(&index).cloned().unwrap_or_default();
                    format!("{block_type}_stop")
                }
                other => other.to_string(),
            }
        })
        .collect()
}

// Same-format replay returns the same parsed JSON value, including provider-specific fields.
#[test]
fn preserved_same_format_events_replay_unknown_fields_exactly() -> TestResult {
    let cases = [
        (
            WireFormat::OpenAiChat,
            json!({
                "id": "chatcmpl-test",
                "object": "chat.completion.chunk",
                "model": "gpt-4o",
                "system_fingerprint": "fp_provider_specific",
                "choices": [{
                    "index": 0,
                    "delta": {"content": "Hi"},
                    "finish_reason": null
                }]
            }),
        ),
        (
            WireFormat::OpenAiResponses,
            json!({
                "type": "response.output_text.delta",
                "item_id": "item-1",
                "output_index": 0,
                "content_index": 0,
                "delta": "Hi",
                "sequence_number": 2,
                "provider_extension": {"exact": true}
            }),
        ),
        (
            WireFormat::OpenAiResponses,
            json!({
                "type": "response.output_item.done",
                "output_index": 0,
                "item": {"type": "compaction", "id": "cmp_1", "encrypted_content": "opaque"}
            }),
        ),
        (
            WireFormat::AnthropicMessages,
            json!({
                "type": "content_block_delta",
                "index": 0,
                "delta": {"type": "text_delta", "text": "Hi"},
                "provider_extension": {"exact": true}
            }),
        ),
    ];

    for (format, event) in cases {
        let engine = TranslationEngine::default();
        let mut state = StreamTranslationState::new(format, format);
        let preserved = engine.decode_stream_event(&mut state, format, event.clone())?;
        let replayed = engine.encode_stream_event(&mut state, format, preserved)?;
        assert_eq!(replayed, vec![event]);
    }
    Ok(())
}

// A same-format error remains the last replayed event even if the source supplies more frames.
#[test]
fn preserved_same_format_replay_stops_after_an_error() -> TestResult {
    let format = WireFormat::OpenAiResponses;
    let events = [
        json!({"type": "response.output_text.delta", "delta": "before"}),
        json!({"type": "error", "message": "boom"}),
        json!({"type": "response.output_text.delta", "delta": "after"}),
        json!({"type": "response.completed", "response": {"id": "resp_1"}}),
    ];
    let engine = TranslationEngine::default();
    let mut decode_state = StreamTranslationState::new(format, format);
    let mut encode_state = StreamTranslationState::new(format, format);
    let mut replayed = Vec::new();

    for event in events {
        let preserved = engine.decode_stream_event(&mut decode_state, format, event)?;
        replayed.extend(engine.encode_stream_event(&mut encode_state, format, preserved)?);
    }

    assert_eq!(
        replayed,
        vec![
            json!({"type": "response.output_text.delta", "delta": "before"}),
            json!({"type": "error", "message": "boom"}),
        ]
    );
    Ok(())
}

// A finished item that contradicts text that was already streamed reaches a same-format client
// as an error event in its place. Before, the contradicting event was replayed and the stream
// ended with no error event.
#[test]
fn preserved_same_format_snapshot_conflict_replays_as_an_error() -> TestResult {
    let format = WireFormat::OpenAiResponses;
    let events = [
        json!({"type": "response.output_text.delta", "output_index": 0, "content_index": 0, "delta": "Hello"}),
        json!({"type": "response.output_item.done", "output_index": 0, "item": {"type": "message",
            "role": "assistant", "content": [{"type": "output_text", "text": "Goodbye"}]}}),
    ];
    let engine = TranslationEngine::default();
    let mut decode_state = StreamTranslationState::new(format, format);
    let mut encode_state = StreamTranslationState::new(format, format);
    let mut replayed = Vec::new();
    for event in events {
        let preserved = engine.decode_stream_event(&mut decode_state, format, event)?;
        replayed.extend(engine.encode_stream_event(&mut encode_state, format, preserved)?);
    }

    let types: Vec<_> = replayed.iter().map(|event| &event["type"]).collect();
    assert_eq!(
        types,
        [&json!("response.output_text.delta"), &json!("error")],
        "{replayed:?}"
    );
    assert_eq!(
        replayed[1]["message"],
        "Responses snapshot conflicts with streamed content"
    );
    Ok(())
}

#[test]
fn anthropic_errors_include_type_and_terminate_stream() -> TestResult {
    let engine = TranslationEngine::default();
    let target = WireFormat::AnthropicMessages;
    let message = "stream failed";
    for chunk in [
        LlmResponseChunk::StreamError {
            message: message.into(),
        },
        LlmResponseChunk::DecodeError {
            message: message.into(),
        },
    ] {
        let mut state = StreamTranslationState::new(WireFormat::OpenAiChat, target);
        let events = engine.encode_stream_event(
            &mut state,
            target,
            LlmResponseStreamEvent::new(vec![chunk]),
        )?;
        assert_eq!(
            events,
            vec![json!({"type": "error", "error": {"type": "api_error", "message": message}})]
        );
        assert!(
            engine
                .encode_stream_event(
                    &mut state,
                    target,
                    LlmResponseStreamEvent::new(vec![LlmResponseChunk::MessageStop {
                        reason: None
                    }]),
                )?
                .is_empty()
        );
        assert!(engine.finish_stream(&mut state, target)?.is_empty());
    }
    Ok(())
}

#[test]
fn same_format_decode_failure_emits_terminal_error() -> TestResult {
    let cases = [
        (
            WireFormat::OpenAiChat,
            json!({"choices": [{"index": 0, "delta": {"content": "partial"}}]}),
        ),
        (
            WireFormat::AnthropicMessages,
            json!({
                "type": "content_block_delta", "index": 0,
                "delta": {"type": "text_delta", "text": "partial"}
            }),
        ),
    ];
    let engine = TranslationEngine::default();
    for (format, text) in cases {
        let mut decode_state = StreamTranslationState::new(format, format);
        let mut encode_state = StreamTranslationState::new(format, format);
        let preserved = engine.decode_stream_event(&mut decode_state, format, text.clone())?;
        assert_eq!(
            engine.encode_stream_event(&mut encode_state, format, preserved)?,
            vec![text.clone()]
        );

        let invalid = engine.decode_stream_event(&mut decode_state, format, Value::Null)?;
        let errors = engine.encode_stream_event(&mut encode_state, format, invalid)?;
        assert_eq!(errors.len(), 1, "{format:?}");
        assert!(
            errors[0]["error"]["message"].is_string(),
            "{format:?}: {errors:?}"
        );
        if format == WireFormat::AnthropicMessages {
            assert_eq!(errors[0]["type"], "error");
        }

        let later = engine.decode_stream_event(&mut decode_state, format, text)?;
        assert!(
            engine
                .encode_stream_event(&mut encode_state, format, later)?
                .is_empty()
        );
        assert!(engine.finish_stream(&mut encode_state, format)?.is_empty());
    }
    Ok(())
}

// Replay emits the preserved event without running the encoder, so the encoder never sees the
// stop it would normally record. Replay must still leave the stream marked finished or
// `finish_stream` synthesizes a terminal the client already received.
#[test]
fn replayed_terminal_event_suppresses_synthesized_finish() -> TestResult {
    let cases = [
        (
            WireFormat::OpenAiChat,
            vec![
                json!({
                    "id": "chatcmpl-test",
                    "object": "chat.completion.chunk",
                    "model": "gpt-4o",
                    "choices": [{"index": 0, "delta": {"content": "Hi"}, "finish_reason": null}]
                }),
                json!({
                    "id": "chatcmpl-test",
                    "object": "chat.completion.chunk",
                    "model": "gpt-4o",
                    "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]
                }),
            ],
        ),
        (
            WireFormat::AnthropicMessages,
            vec![
                json!({"type": "message_start", "message": {"id": "msg_1", "model": "claude"}}),
                json!({"type": "message_stop"}),
            ],
        ),
        (
            WireFormat::OpenAiResponses,
            vec![
                json!({"type": "response.created", "response": {"id": "resp_1", "model": "gpt-4o"}}),
                json!({"type": "response.completed", "response": {"id": "resp_1", "model": "gpt-4o"}}),
            ],
        ),
    ];

    let engine = TranslationEngine::default();
    for (format, events) in cases {
        let mut state = StreamTranslationState::new(format, format);
        let mut replayed = Vec::new();
        for event in &events {
            let preserved = engine.decode_stream_event(&mut state, format, event.clone())?;
            replayed.extend(engine.encode_stream_event(&mut state, format, preserved)?);
        }
        assert_eq!(replayed, events, "{format:?} engine replay");
        assert!(
            engine.finish_stream(&mut state, format)?.is_empty(),
            "{format:?} engine replay already delivered a terminal event",
        );
    }
    Ok(())
}

#[test]
fn replayed_nonterminal_event_advances_encoder_state_before_finish() -> TestResult {
    let engine = TranslationEngine::default();
    let format = WireFormat::OpenAiChat;
    let event = json!({
        "id": "chatcmpl-clean-eof",
        "object": "chat.completion.chunk",
        "model": "gpt-4o",
        "choices": [{
            "index": 0,
            "delta": {"role": "assistant", "content": "Hi"},
            "finish_reason": null
        }]
    });
    let mut decode_state = StreamTranslationState::new(format, format);
    let preserved = engine.decode_stream_event(&mut decode_state, format, event.clone())?;

    // Provider decoding and caller encoding are independent stream boundaries in a host such as
    // NeMo Relay. Replay must therefore advance a fresh encoder state using the normalized view.
    let mut encode_state = StreamTranslationState::new(format, format);
    assert_eq!(
        engine.encode_stream_event(&mut encode_state, format, preserved)?,
        vec![event]
    );
    let finish = engine.finish_stream(&mut encode_state, format)?;

    assert_eq!(finish.len(), 1);
    assert_eq!(finish[0]["id"], "chatcmpl-clean-eof");
    assert_eq!(finish[0]["model"], "gpt-4o");
    assert_eq!(finish[0]["choices"][0]["finish_reason"], "stop");
    Ok(())
}

// Exact replay advances sequencing by the one raw event actually emitted, not discarded
// synthetic events produced while advancing encoder state.
#[test]
fn responses_replay_without_sequence_advances_by_one_emitted_event() -> TestResult {
    let engine = TranslationEngine::default();
    let format = WireFormat::OpenAiResponses;
    let raw = json!({
        "type": "response.output_item.added",
        "output_index": 0,
        "item": {
            "type": "function_call",
            "id": "fc_0",
            "call_id": "call_0",
            "name": "bash",
            "arguments": ""
        }
    });
    let replayed = LlmResponseStreamEvent::preserved(
        format,
        raw.clone(),
        vec![LlmResponseChunk::ToolCallDelta {
            index: 0,
            id: Some("call_0".to_string()),
            name: Some("bash".to_string()),
            arguments_delta: None,
        }],
    );
    let mut state = StreamTranslationState::new(format, format);

    assert_eq!(
        engine.encode_stream_event(&mut state, format, replayed)?,
        vec![raw]
    );
    let generated = engine.encode_stream_event(
        &mut state,
        format,
        LlmResponseStreamEvent::new(vec![LlmResponseChunk::ToolCallDelta {
            index: 0,
            id: None,
            name: None,
            arguments_delta: Some("{}".to_string()),
        }]),
    )?;

    assert_eq!(generated.len(), 1);
    assert_eq!(generated[0]["sequence_number"], 1);
    Ok(())
}

#[test]
fn replayed_anthropic_terminal_delta_finishes_with_message_stop_only() -> TestResult {
    let engine = TranslationEngine::default();
    let format = WireFormat::AnthropicMessages;
    let events = [
        json!({
            "type": "message_start",
            "message": {
                "id": "msg_clean_eof",
                "model": "claude",
                "usage": {"input_tokens": 3, "output_tokens": 0}
            }
        }),
        json!({
            "type": "message_delta",
            "delta": {"stop_reason": "end_turn", "stop_sequence": null},
            "usage": {"output_tokens": 2}
        }),
    ];
    let mut decode_state = StreamTranslationState::new(format, format);
    let mut encode_state = StreamTranslationState::new(format, format);

    for event in events {
        let preserved = engine.decode_stream_event(&mut decode_state, format, event.clone())?;
        assert_eq!(
            engine.encode_stream_event(&mut encode_state, format, preserved)?,
            vec![event]
        );
    }

    let finish = engine.finish_stream(&mut encode_state, format)?;
    assert_eq!(
        finish
            .iter()
            .filter(|event| event["type"] == "message_stop")
            .count(),
        1
    );
    assert!(
        finish.iter().all(|event| event["type"] != "message_delta"),
        "the replayed terminal delta must not be synthesized a second time"
    );
    Ok(())
}

// Cross-format encoding discards provider-specific fields and uses normalized chunks.
#[test]
fn preserved_cross_format_event_uses_normalized_content() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state =
        StreamTranslationState::new(WireFormat::OpenAiChat, WireFormat::AnthropicMessages);
    let event = json!({
        "id": "chatcmpl-test",
        "object": "chat.completion.chunk",
        "model": "gpt-4o",
        "system_fingerprint": "fp_provider_specific",
        "choices": [{
            "index": 0,
            "delta": {"content": "Hi"},
            "finish_reason": null
        }]
    });

    let preserved = engine.decode_stream_event(&mut state, WireFormat::OpenAiChat, event)?;
    let translated =
        engine.encode_stream_event(&mut state, WireFormat::AnthropicMessages, preserved)?;

    assert_eq!(translated[2]["delta"]["text"], "Hi");
    assert!(
        translated
            .iter()
            .all(|event| event.get("system_fingerprint").is_none())
    );
    Ok(())
}

// Verifies an OpenAI text delta opens the expected Anthropic message and content blocks.
#[test]
fn openai_chat_stream_event_translates_to_anthropic_message_events() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state =
        StreamTranslationState::new(WireFormat::OpenAiChat, WireFormat::AnthropicMessages);
    let chunk = json!({
        "id": "chatcmpl-test",
        "object": "chat.completion.chunk",
        "model": "gpt-4o",
        "choices": [{
            "index": 0,
            "delta": {"content": "Hi"},
            "finish_reason": null
        }]
    });

    let events = engine.translate_event(
        &mut state,
        WireFormat::OpenAiChat,
        WireFormat::AnthropicMessages,
        &chunk,
    )?;

    assert_eq!(events[0]["type"], "message_start");
    assert_eq!(events[0]["message"]["model"], "gpt-4o");
    assert_eq!(
        events[1],
        json!({
            "type": "content_block_start",
            "index": 0,
            "content_block": {"type": "text", "text": ""}
        })
    );
    assert_eq!(
        events[2],
        json!({
            "type": "content_block_delta",
            "index": 0,
            "delta": {"type": "text_delta", "text": "Hi"}
        })
    );
    Ok(())
}

// Refusal text is emitted once, whether supplied as deltas or a completed snapshot.
#[test]
fn refusal_stream_translates_to_anthropic() -> TestResult {
    let engine = TranslationEngine::default();
    let refusal = "I cannot help with that request.";
    let chat_delta = json!({
        "id": "chatcmpl-refusal",
        "object": "chat.completion.chunk",
        "model": "gpt-4o",
        "choices": [{
            "index": 0,
            "delta": {"refusal": refusal},
            "finish_reason": null
        }]
    });
    let chat_terminal = json!({
        "id": "chatcmpl-refusal",
        "object": "chat.completion.chunk",
        "model": "gpt-4o",
        "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]
    });
    let part = json!({"type": "refusal", "refusal": refusal});
    let message = json!({"id": "msg_refusal", "type": "message", "role": "assistant",
        "status": "completed", "content": [part]});
    let response = json!({"id": "resp_refusal", "model": "fixture",
        "status": "completed", "output": [message]});
    let completed = json!({"type": "response.completed", "response": response});
    let refusal_done = json!({"type": "response.refusal.done", "item_id": "msg_refusal",
        "output_index": 0, "content_index": 0, "refusal": refusal});

    for (case, source, input, expected_fragments) in [
        (
            "chat_deltas",
            WireFormat::OpenAiChat,
            vec![chat_delta, chat_terminal],
            vec![refusal],
        ),
        (
            "responses_snapshot_only",
            WireFormat::OpenAiResponses,
            vec![completed.clone()],
            vec![refusal],
        ),
        (
            "responses_refusal_done_only",
            WireFormat::OpenAiResponses,
            vec![
                refusal_done.clone(),
                json!({"type": "response.completed", "response": {}}),
            ],
            vec![refusal],
        ),
        (
            "responses_full_lifecycle",
            WireFormat::OpenAiResponses,
            vec![
                json!({"type": "response.created", "response": {"id": "resp_refusal",
                    "model": "fixture", "status": "in_progress", "output": []}}),
                json!({"type": "response.output_item.added", "output_index": 0,
                    "item": {"id": "msg_refusal", "type": "message", "role": "assistant",
                        "status": "in_progress", "content": []}}),
                json!({"type": "response.content_part.added", "item_id": "msg_refusal",
                    "output_index": 0, "content_index": 0,
                    "part": {"type": "refusal", "refusal": ""}}),
                json!({"type": "response.refusal.delta", "item_id": "msg_refusal",
                    "output_index": 0, "content_index": 0, "delta": "I cannot "}),
                json!({"type": "response.refusal.delta", "item_id": "msg_refusal",
                    "output_index": 0, "content_index": 0, "delta": "help with that request."}),
                refusal_done,
                json!({"type": "response.content_part.done", "item_id": "msg_refusal",
                    "output_index": 0, "content_index": 0, "part": part}),
                json!({"type": "response.output_item.done", "output_index": 0, "item": message}),
                completed,
            ],
            vec!["I cannot ", "help with that request."],
        ),
    ] {
        let target = WireFormat::AnthropicMessages;
        let mut decoder = StreamTranslationState::new(source, target);
        let mut encoder = StreamTranslationState::new(source, target);
        let mut events = Vec::new();
        for event in input {
            let decoded = engine.decode_stream_event(&mut decoder, source, event)?;
            events.extend(engine.encode_stream_event(&mut encoder, target, decoded)?);
        }
        events.extend(engine.finish_stream(&mut encoder, target)?);
        let fragments: Vec<_> = events
            .iter()
            .filter(|event| event["type"] == "content_block_delta")
            .filter_map(|event| event["delta"]["text"].as_str())
            .collect();
        assert_eq!(fragments, expected_fragments, "{case}");
        let terminal_deltas: Vec<_> = events
            .iter()
            .filter(|event| event["type"] == "message_delta")
            .map(|event| event["delta"].clone())
            .collect();
        assert_eq!(
            terminal_deltas,
            vec![json!({
                "stop_reason": "refusal",
                "stop_sequence": null,
                "stop_details": {"type": "refusal", "category": null, "explanation": null}
            })],
            "{case}"
        );
    }
    Ok(())
}

// Restores Anthropic-safe IDs before emitting OpenAI tool-call deltas.
#[test]
fn anthropic_stream_tool_id_is_restored_for_openai_chat() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state =
        StreamTranslationState::new(WireFormat::AnthropicMessages, WireFormat::OpenAiChat);
    let raw_id = "functions.list_skills:0";
    let event = json!({
        "type": "content_block_start",
        "index": 0,
        "content_block": {
            "type": "tool_use",
            "id": "sy64_ZnVuY3Rpb25zLmxpc3Rfc2tpbGxzOjA",
            "name": "list_skills",
            "input": {}
        }
    });

    let chunks = engine.translate_event(
        &mut state,
        WireFormat::AnthropicMessages,
        WireFormat::OpenAiChat,
        &event,
    )?;

    assert_eq!(
        chunks[0]["choices"][0]["delta"]["tool_calls"][0]["id"],
        raw_id
    );
    Ok(())
}

// A mixed chunk must emit reasoning before text, matching the buffered decoder.
#[test]
fn openai_chat_mixed_reasoning_and_content_stream_in_reasoning_first_order() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state =
        StreamTranslationState::new(WireFormat::OpenAiChat, WireFormat::AnthropicMessages);
    let chunk = json!({
        "id": "chatcmpl-test",
        "object": "chat.completion.chunk",
        "model": "nvidia/nvidia/nemotron-3-ultra-nvfp4",
        "choices": [{
            "index": 0,
            "delta": {
                "reasoning_content": ".",
                "content": "Hello"
            },
            "finish_reason": null
        }]
    });

    let events = engine.translate_event(
        &mut state,
        WireFormat::OpenAiChat,
        WireFormat::AnthropicMessages,
        &chunk,
    )?;

    assert_eq!(
        event_labels(&events),
        vec![
            "message_start",
            "thinking_start",
            "thinking_delta",
            "signature_delta",
            "thinking_stop",
            "text_start",
            "text_delta",
        ]
    );
    Ok(())
}

// Verifies Anthropic usage and stop events become terminal OpenAI chunks.
#[test]
fn anthropic_stream_usage_and_stop_translate_to_openai_chunks() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state =
        StreamTranslationState::new(WireFormat::AnthropicMessages, WireFormat::OpenAiChat);
    let start = json!({
        "type": "message_start",
        "message": {"id": "msg_1", "model": "claude", "role": "assistant", "content": []}
    });
    engine.translate_event(
        &mut state,
        WireFormat::AnthropicMessages,
        WireFormat::OpenAiChat,
        &start,
    )?;

    let usage = json!({
        "type": "message_delta",
        "delta": {"stop_reason": "end_turn"},
        "usage": {"output_tokens": 42}
    });
    let events = engine.translate_event(
        &mut state,
        WireFormat::AnthropicMessages,
        WireFormat::OpenAiChat,
        &usage,
    )?;

    assert_eq!(events[0]["usage"]["completion_tokens"], 42);
    assert_eq!(events[0]["choices"][0]["finish_reason"], "stop");
    Ok(())
}

// Verifies streamed moderation stops stay distinguishable from normal turns in both
// directions, and that a named refusal category survives re-encoding.
#[test]
fn content_filter_and_refusal_streams_translate_across_formats() -> TestResult {
    let engine = TranslationEngine::default();

    // An OpenAI moderation stop reaches Anthropic clients as `refusal`, carrying the
    // null form Anthropic documents for a refusal mapping to no named category.
    let mut state =
        StreamTranslationState::new(WireFormat::OpenAiChat, WireFormat::AnthropicMessages);
    let chunk = json!({
        "id": "chatcmpl-test",
        "object": "chat.completion.chunk",
        "model": "gpt-4o",
        "choices": [{"index": 0, "delta": {}, "finish_reason": "content_filter"}]
    });
    let mut events = engine.translate_event(
        &mut state,
        WireFormat::OpenAiChat,
        WireFormat::AnthropicMessages,
        &chunk,
    )?;
    events.extend(engine.finish_stream(&mut state, WireFormat::AnthropicMessages)?);
    let terminal = events
        .iter()
        .find(|event| event["type"] == "message_delta")
        .ok_or("missing Anthropic terminal delta")?;
    assert_eq!(terminal["delta"]["stop_reason"], "refusal");
    assert_eq!(
        terminal["delta"]["stop_details"],
        json!({"type": "refusal", "category": null, "explanation": null})
    );

    // The distinction survives the other direction rather than being flattened.
    let mut state =
        StreamTranslationState::new(WireFormat::AnthropicMessages, WireFormat::OpenAiChat);
    let delta = json!({
        "type": "message_delta",
        "delta": {
            "stop_reason": "refusal",
            "stop_details": {
                "type": "refusal",
                "category": "cyber",
                "explanation": "This request was declined because it could enable cyber harm."
            }
        },
        "usage": {"output_tokens": 1}
    });
    let events = engine.translate_event(
        &mut state,
        WireFormat::AnthropicMessages,
        WireFormat::OpenAiChat,
        &delta,
    )?;
    assert_eq!(events[0]["choices"][0]["finish_reason"], "content_filter");

    // Re-encoding a streamed refusal keeps the category the source named.
    let mut state =
        StreamTranslationState::new(WireFormat::AnthropicMessages, WireFormat::AnthropicMessages);
    let mut events = engine.translate_event(
        &mut state,
        WireFormat::AnthropicMessages,
        WireFormat::AnthropicMessages,
        &delta,
    )?;
    events.extend(engine.finish_stream(&mut state, WireFormat::AnthropicMessages)?);
    let terminal = events
        .iter()
        .find(|event| event["type"] == "message_delta")
        .ok_or("missing Anthropic terminal delta")?;
    assert_eq!(terminal["delta"]["stop_reason"], "refusal");
    assert_eq!(terminal["delta"]["stop_details"]["category"], "cyber");
    Ok(())
}

// Verifies Chat target streams expose the served model while retaining source identity.
#[test]
fn anthropic_to_openai_chat_uses_served_model_without_losing_source_model() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state =
        StreamTranslationState::new(WireFormat::AnthropicMessages, WireFormat::OpenAiChat);
    state.target_model = Some("served-model".to_string());
    let start = json!({
        "type": "message_start",
        "message": {
            "id": "msg_1",
            "model": "claude-upstream",
            "role": "assistant",
            "content": []
        }
    });
    engine.translate_event(
        &mut state,
        WireFormat::AnthropicMessages,
        WireFormat::OpenAiChat,
        &start,
    )?;

    let delta = json!({
        "type": "content_block_delta",
        "index": 0,
        "delta": {"type": "text_delta", "text": "hello"}
    });
    let events = engine.translate_event(
        &mut state,
        WireFormat::AnthropicMessages,
        WireFormat::OpenAiChat,
        &delta,
    )?;

    assert_eq!(state.model.as_deref(), Some("claude-upstream"));
    assert_eq!(state.target_model.as_deref(), Some("served-model"));
    assert_eq!(events[0]["model"], "served-model");
    Ok(())
}

// Verifies Anthropic target streams expose the served model without losing source identity.
#[test]
fn responses_to_anthropic_uses_served_model_without_losing_source_model() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state =
        StreamTranslationState::new(WireFormat::OpenAiResponses, WireFormat::AnthropicMessages);
    state.target_model = Some("served-model".to_string());
    let created = json!({
        "type": "response.created",
        "response": {"id": "resp_1", "model": "responses-upstream"}
    });

    let events = engine.translate_event(
        &mut state,
        WireFormat::OpenAiResponses,
        WireFormat::AnthropicMessages,
        &created,
    )?;

    assert_eq!(state.model.as_deref(), Some("responses-upstream"));
    assert_eq!(state.target_model.as_deref(), Some("served-model"));
    assert_eq!(events[0]["message"]["model"], "served-model");
    Ok(())
}

// Verifies Responses target streams expose the served model while retaining source identity.
#[test]
fn openai_chat_to_responses_uses_served_model_without_losing_source_model() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state =
        StreamTranslationState::new(WireFormat::OpenAiChat, WireFormat::OpenAiResponses);
    state.target_model = Some("served-model".to_string());
    let chunk = json!({
        "id": "chatcmpl-test",
        "object": "chat.completion.chunk",
        "model": "gpt-upstream",
        "choices": [{
            "index": 0,
            "delta": {"content": "hello"},
            "finish_reason": null
        }]
    });

    let events = engine.translate_event(
        &mut state,
        WireFormat::OpenAiChat,
        WireFormat::OpenAiResponses,
        &chunk,
    )?;

    assert_eq!(state.model.as_deref(), Some("gpt-upstream"));
    assert_eq!(state.target_model.as_deref(), Some("served-model"));
    assert_eq!(events[0]["response"]["model"], "served-model");
    Ok(())
}

// Stored conversation history is keyed by the upstream ID, so clients must see it unchanged.
#[test]
fn openai_chat_to_responses_keeps_the_upstream_id() -> TestResult {
    let mut state =
        StreamTranslationState::new(WireFormat::OpenAiChat, WireFormat::OpenAiResponses);
    let events = TranslationEngine::default().translate_event(
        &mut state,
        WireFormat::OpenAiChat,
        WireFormat::OpenAiResponses,
        &json!({"id": "chatcmpl-test", "choices": [{"index": 0, "delta": {"content": "hi"}}]}),
    )?;

    assert_eq!(events[0]["response"]["id"], "chatcmpl-test");
    Ok(())
}

// Verifies OpenAI Chat finish emits a terminal chunk when the source closes without one.
#[test]
fn openai_chat_finish_synthesizes_terminal_chunk_after_incomplete_source() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state = StreamTranslationState::new(WireFormat::OpenAiChat, WireFormat::OpenAiChat);
    let chunk = json!({
        "id": "chatcmpl-test",
        "object": "chat.completion.chunk",
        "model": "gpt-4o",
        "choices": [{
            "index": 0,
            "delta": {"content": "hello"},
            "finish_reason": null
        }]
    });

    let mut events = engine.translate_event(
        &mut state,
        WireFormat::OpenAiChat,
        WireFormat::OpenAiChat,
        &chunk,
    )?;
    events.extend(engine.finish_stream(&mut state, WireFormat::OpenAiChat)?);

    let Some(terminal) = events.last() else {
        return Err("finish should emit a terminal OpenAI Chat chunk".into());
    };
    assert_eq!(terminal["choices"][0]["delta"], json!({}));
    assert_eq!(terminal["choices"][0]["finish_reason"], "stop");
    assert!(terminal.get("usage").is_none());
    Ok(())
}

// Verifies provider usage arriving after finish remains visible to OpenAI clients.
#[test]
fn openai_chat_emits_usage_arriving_after_stop() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state = StreamTranslationState::new(WireFormat::OpenAiChat, WireFormat::OpenAiChat);
    let stop = json!({
        "id": "chatcmpl-test",
        "object": "chat.completion.chunk",
        "model": "gpt-4o",
        "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]
    });
    let events = engine.translate_event(
        &mut state,
        WireFormat::OpenAiChat,
        WireFormat::OpenAiChat,
        &stop,
    )?;
    assert!(events[0].get("usage").is_none());

    let usage = json!({
        "id": "chatcmpl-test",
        "object": "chat.completion.chunk",
        "model": "gpt-4o",
        "choices": [],
        "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}
    });
    let events = engine.translate_event(
        &mut state,
        WireFormat::OpenAiChat,
        WireFormat::OpenAiChat,
        &usage,
    )?;
    assert_eq!(events.len(), 1);
    assert_eq!(events[0]["choices"], json!([]));
    assert_eq!(events[0]["usage"]["total_tokens"], 15);
    Ok(())
}

// Verifies OpenAI Chat streaming usage preserves reasoning details for Responses clients.
#[test]
fn openai_chat_stream_reasoning_usage_translates_to_responses_usage_details() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state =
        StreamTranslationState::new(WireFormat::OpenAiChat, WireFormat::OpenAiResponses);
    let usage = json!({
        "id": "chatcmpl-test",
        "object": "chat.completion.chunk",
        "model": "gpt-reasoning",
        "choices": [{
            "index": 0,
            "delta": {},
            "finish_reason": "stop"
        }],
        "usage": {
            "prompt_tokens": 10,
            "completion_tokens": 5,
            "total_tokens": 15,
            "completion_tokens_details": {"reasoning_tokens": 3}
        }
    });

    let mut events = engine.translate_event(
        &mut state,
        WireFormat::OpenAiChat,
        WireFormat::OpenAiResponses,
        &usage,
    )?;
    events.extend(engine.finish_stream(&mut state, WireFormat::OpenAiResponses)?);

    let Some(completed) = events
        .iter()
        .find(|event| event["type"] == "response.completed")
    else {
        return Err("expected final Responses completion event".into());
    };
    assert_eq!(
        completed["response"]["usage"]["output_tokens_details"],
        json!({"reasoning_tokens": 3})
    );
    Ok(())
}

// Verifies streamed cache usage reaches Responses clients in the standard details object.
#[test]
fn openai_chat_stream_cache_usage_translates_to_responses_usage_details() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state =
        StreamTranslationState::new(WireFormat::OpenAiChat, WireFormat::OpenAiResponses);
    let usage = json!({
        "id": "chatcmpl-test",
        "object": "chat.completion.chunk",
        "model": "gpt-cached",
        "choices": [{
            "index": 0,
            "delta": {},
            "finish_reason": "stop"
        }],
        "usage": {
            "prompt_tokens": 100,
            "completion_tokens": 5,
            "total_tokens": 105,
            "prompt_tokens_details": {"cached_tokens": 80}
        }
    });

    let mut events = engine.translate_event(
        &mut state,
        WireFormat::OpenAiChat,
        WireFormat::OpenAiResponses,
        &usage,
    )?;
    events.extend(engine.finish_stream(&mut state, WireFormat::OpenAiResponses)?);

    let Some(completed) = events
        .iter()
        .find(|event| event["type"] == "response.completed")
    else {
        return Err("expected final Responses completion event".into());
    };
    assert_eq!(completed["response"]["usage"]["input_tokens"], 100);
    assert_eq!(
        completed["response"]["usage"]["input_tokens_details"],
        json!({"cached_tokens": 80, "cache_write_tokens": 0})
    );
    Ok(())
}

// Verifies OpenRouter's cache-write field and the legacy alias normalize identically.
#[test]
fn openai_chat_stream_cache_write_usage_is_normalized() -> TestResult {
    for cache_write_field in ["cache_write_tokens", "cache_creation_tokens"] {
        let mut state = StreamTranslationState::new(WireFormat::OpenAiChat, WireFormat::OpenAiChat);
        let mut event = json!({
            "id": "chatcmpl-test",
            "object": "chat.completion.chunk",
            "model": "gpt-cached",
            "choices": [],
            "usage": {
                "prompt_tokens": 100,
                "completion_tokens": 5,
                "total_tokens": 105,
                "prompt_tokens_details": {"cached_tokens": 70}
            }
        });
        event["usage"]["prompt_tokens_details"][cache_write_field] = json!(10);

        let chunks = decode_stream_event(&mut state, WireFormat::OpenAiChat, &event);
        let Some(usage) = chunks.iter().find_map(|chunk| match chunk {
            LlmResponseChunk::Usage(usage) => Some(usage),
            _ => None,
        }) else {
            return Err(format!("expected usage chunk for {cache_write_field}").into());
        };

        assert_eq!(usage.input_tokens, Some(20));
        assert_eq!(usage.cached_input_tokens(), Some(70));
        assert_eq!(usage.cache_creation_input_tokens(), Some(10));
        assert_eq!(usage.output_tokens, Some(5));
    }
    Ok(())
}

// Verifies the streamed total-token fallback keeps cached tokens when upstream omits total_tokens.
#[test]
fn responses_stream_usage_without_total_keeps_cached_tokens_in_total() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state =
        StreamTranslationState::new(WireFormat::OpenAiResponses, WireFormat::OpenAiChat);
    let created = json!({
        "type": "response.created",
        "response": {"id": "resp_1", "model": "gpt-cached"}
    });
    engine.translate_event(
        &mut state,
        WireFormat::OpenAiResponses,
        WireFormat::OpenAiChat,
        &created,
    )?;

    // No total_tokens field: the codec must recompute it from the aggregate input.
    let completed = json!({
        "type": "response.completed",
        "response": {
            "id": "resp_1",
            "usage": {
                "input_tokens": 100,
                "output_tokens": 5,
                "input_tokens_details": {"cached_tokens": 80}
            }
        }
    });
    let mut events = engine.translate_event(
        &mut state,
        WireFormat::OpenAiResponses,
        WireFormat::OpenAiChat,
        &completed,
    )?;
    events.extend(engine.finish_stream(&mut state, WireFormat::OpenAiChat)?);

    let Some(usage) = events
        .iter()
        .find_map(|event| event.get("usage").filter(|usage| !usage.is_null()))
    else {
        return Err("expected a terminal OpenAI chunk carrying usage".into());
    };
    assert_eq!(usage["prompt_tokens"], 100);
    assert_eq!(usage["total_tokens"], 105);
    assert_eq!(usage["prompt_tokens_details"]["cached_tokens"], 80);
    Ok(())
}

// Verifies Responses text deltas become OpenAI Chat content chunks.
#[test]
fn responses_stream_delta_translates_to_openai_chat_chunk() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state =
        StreamTranslationState::new(WireFormat::OpenAiResponses, WireFormat::OpenAiChat);
    let created = json!({
        "type": "response.created",
        "response": {"id": "resp_1", "model": "gpt-4o"}
    });
    engine.translate_event(
        &mut state,
        WireFormat::OpenAiResponses,
        WireFormat::OpenAiChat,
        &created,
    )?;

    let delta = json!({
        "type": "response.output_text.delta",
        "output_index": 0,
        "delta": "hello"
    });
    let events = engine.translate_event(
        &mut state,
        WireFormat::OpenAiResponses,
        WireFormat::OpenAiChat,
        &delta,
    )?;

    assert_eq!(events[0]["model"], "gpt-4o");
    assert_eq!(events[0]["choices"][0]["delta"]["content"], "hello");
    Ok(())
}

// Verifies OpenAI-compatible reasoning deltas become Anthropic thinking, not text content.
#[test]
fn openai_chat_reasoning_stream_fields_do_not_become_anthropic_text() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state =
        StreamTranslationState::new(WireFormat::OpenAiChat, WireFormat::AnthropicMessages);
    let chunk = json!({
        "id": "chatcmpl-test",
        "object": "chat.completion.chunk",
        "model": "nvidia/nemotron",
        "choices": [{
            "index": 0,
            "delta": {
                "reasoning": "private reasoning",
                "reasoning_content": "private reasoning content"
            },
            "finish_reason": null
        }]
    });

    let mut events = engine.translate_event(
        &mut state,
        WireFormat::OpenAiChat,
        WireFormat::AnthropicMessages,
        &chunk,
    )?;
    events.extend(engine.finish_stream(&mut state, WireFormat::AnthropicMessages)?);

    let serialized = serde_json::to_string(&events)?;
    assert!(serialized.contains("private reasoning"));
    assert!(serialized.contains("private reasoning content"));
    assert!(!serialized.contains("reasoning_content"));
    assert!(events.iter().any(|event| {
        event["type"] == "content_block_start"
            && event["content_block"]["type"] == "thinking"
            && event["content_block"]["signature"] == ""
    }));
    assert!(events.iter().any(|event| {
        event["type"] == "content_block_delta"
            && event["delta"]["type"] == "thinking_delta"
            && event["delta"]["thinking"] == "private reasoning content"
    }));
    assert!(events.iter().any(|event| {
        event["type"] == "content_block_delta"
            && event["delta"]["type"] == "signature_delta"
            && event["delta"]["signature"] == ""
    }));
    assert!(!events.iter().any(|event| {
        event["type"] == "content_block_delta"
            && event["delta"]["type"] == "text_delta"
            && event["delta"]["text"]
                .as_str()
                .is_some_and(|text| text.contains("private reasoning"))
    }));
    Ok(())
}

#[test]
fn openai_chat_stream_round_trips_reasoning_details() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state = StreamTranslationState::new(WireFormat::OpenAiChat, WireFormat::OpenAiChat);
    let details = text_and_encrypted_reasoning_details();
    let chunk = json!({
        "id": "chatcmpl-test",
        "object": "chat.completion.chunk",
        "model": REASONING_MODEL,
        "choices": [{
            "index": 0,
            "delta": {
                "reasoning": "fallback text",
                "reasoning_details": details
            },
            "finish_reason": null
        }]
    });

    let events = engine.translate_event(
        &mut state,
        WireFormat::OpenAiChat,
        WireFormat::OpenAiChat,
        &chunk,
    )?;

    assert_eq!(events.len(), 1);
    assert_eq!(
        events[0]["choices"][0]["delta"]["reasoning_details"],
        details
    );
    assert!(events[0]["choices"][0]["delta"].get("reasoning").is_none());
    Ok(())
}

#[test]
fn openai_chat_stream_retains_encrypted_details_and_fallback() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state = StreamTranslationState::new(WireFormat::OpenAiChat, WireFormat::OpenAiChat);
    let details = json!([{
        "type": "reasoning.encrypted",
        "data": "opaque-encrypted-reasoning"
    }]);
    let chunk = json!({
        "id": "chatcmpl-test",
        "object": "chat.completion.chunk",
        "model": REASONING_MODEL,
        "choices": [{
            "index": 0,
            "delta": {
                "reasoning_content": "",
                "reasoning": "fallback text",
                "reasoning_details": details
            },
            "finish_reason": null
        }]
    });

    let events = engine.translate_event(
        &mut state,
        WireFormat::OpenAiChat,
        WireFormat::OpenAiChat,
        &chunk,
    )?;

    assert_eq!(events.len(), 1);
    assert_eq!(
        events[0]["choices"][0]["delta"]["reasoning_details"],
        details
    );
    assert_eq!(
        events[0]["choices"][0]["delta"]["reasoning"],
        "fallback text"
    );
    Ok(())
}

#[test]
fn openai_chat_stream_uses_summary_when_detail_text_is_empty() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state =
        StreamTranslationState::new(WireFormat::OpenAiChat, WireFormat::AnthropicMessages);
    let chunk = json!({
        "id": "chatcmpl-test",
        "object": "chat.completion.chunk",
        "model": REASONING_MODEL,
        "choices": [{
            "index": 0,
            "delta": {
                "reasoning_details": [{
                    "type": "reasoning.summary",
                    "text": "",
                    "summary": "usable summary"
                }]
            },
            "finish_reason": null
        }]
    });

    let events = engine.translate_event(
        &mut state,
        WireFormat::OpenAiChat,
        WireFormat::AnthropicMessages,
        &chunk,
    )?;

    assert!(events.iter().any(|event| {
        event["type"] == "content_block_delta"
            && event["delta"]["type"] == "thinking_delta"
            && event["delta"]["thinking"] == "usable summary"
    }));
    Ok(())
}

// A Chat `reasoning_details` stream may send summary text before the id of the item it
// belongs to. The Responses encoder must not open the item under a synthesized id, because the
// encrypted payload that follows binds only to the provider's id. It holds the summary until
// that id arrives, or until later output shows none is coming, and it takes the id from a
// summary detail that carries one.
#[test]
fn openai_chat_stream_summary_before_id_keeps_reasoning_id_and_payload() -> TestResult {
    let engine = TranslationEngine::default();
    let chunk = |delta: Value, finish_reason: Option<&str>| {
        json!({
            "id": "chatcmpl-reasoning",
            "object": "chat.completion.chunk",
            "model": REASONING_MODEL,
            "choices": [{"index": 0, "delta": delta, "finish_reason": finish_reason}]
        })
    };
    let summary = |id: Option<&str>| {
        let mut detail = json!({"type": "reasoning.summary", "summary": "summary first"});
        if let Some(id) = id {
            detail["id"] = json!(id);
        }
        json!({"reasoning_details": [detail]})
    };
    let encrypted = json!({"reasoning_details": [{
        "type": "reasoning.encrypted", "id": "rs_provider", "data": "opaque-stream"
    }]});
    // Translates each delta as its own chunk and returns the events per chunk, then the
    // events of the stop chunk and of finishing the stream.
    let translate =
        |deltas: Vec<Value>| -> Result<Vec<Vec<Value>>, Box<dyn std::error::Error + Send + Sync>> {
            let mut state =
                StreamTranslationState::new(WireFormat::OpenAiChat, WireFormat::OpenAiResponses);
            let mut batches = Vec::new();
            for (delta, finish_reason) in deltas
                .into_iter()
                .map(|delta| (delta, None))
                .chain([(json!({}), Some("stop"))])
            {
                batches.push(engine.translate_event(
                    &mut state,
                    WireFormat::OpenAiChat,
                    WireFormat::OpenAiResponses,
                    &chunk(delta, finish_reason),
                )?);
            }
            batches.push(engine.finish_stream(&mut state, WireFormat::OpenAiResponses)?);
            Ok(batches)
        };
    let types = |batch: &[Value]| -> Vec<String> {
        batch
            .iter()
            .filter_map(|event| event["type"].as_str().map(ToOwned::to_owned))
            .collect()
    };
    let final_reasoning = |batches: &[Vec<Value>]| -> Result<Value, &'static str> {
        batches
            .iter()
            .flatten()
            .find(|event| event["type"] == "response.completed")
            .and_then(|event| event["response"]["output"].as_array())
            .and_then(|output| output.iter().find(|item| item["type"] == "reasoning"))
            .cloned()
            .ok_or("expected a reasoning item in the completed output")
    };
    let opened = [
        "response.output_item.added",
        "response.reasoning_summary_part.added",
        "response.reasoning_summary_text.delta",
    ];
    let expected = json!({
        "type": "reasoning",
        "id": "rs_provider",
        "status": "completed",
        "summary": [{"type": "summary_text", "text": "summary first"}],
        "encrypted_content": "opaque-stream",
    });

    // Summary before the id: the item waits, then opens under the id the payload names.
    let batches = translate(vec![
        json!({"role": "assistant"}),
        summary(None),
        encrypted.clone(),
    ])?;
    assert_eq!(types(&batches[1]), Vec::<String>::new());
    assert_eq!(types(&batches[2]), opened);
    assert_eq!(final_reasoning(&batches)?, expected);
    for event in batches.iter().flatten().filter(|event| {
        event["type"]
            .as_str()
            .is_some_and(|kind| kind.starts_with("response.reasoning_summary"))
    }) {
        assert_eq!(event["item_id"], "rs_provider", "{event}");
    }

    // Summary carrying the id: the item opens at once under it and the payload still attaches.
    let batches = translate(vec![
        json!({"role": "assistant"}),
        summary(Some("rs_provider")),
        encrypted,
    ])?;
    assert_eq!(types(&batches[1]), opened);
    assert_eq!(batches[1][0]["item"]["id"], "rs_provider");
    assert_eq!(final_reasoning(&batches)?, expected);

    // No id ever comes: the answer opens the held item, under a synthesized id, ahead of itself.
    let batches = translate(vec![
        json!({"role": "assistant"}),
        summary(None),
        json!({"content": "answer"}),
    ])?;
    let opened_items: Vec<&str> = batches
        .iter()
        .flatten()
        .filter(|event| event["type"] == "response.output_item.added")
        .filter_map(|event| event["item"]["type"].as_str())
        .collect();
    assert_eq!(opened_items, ["reasoning", "message"]);
    let reasoning = final_reasoning(&batches)?;
    assert_eq!(
        reasoning["summary"],
        json!([{"type": "summary_text", "text": "summary first"}])
    );
    assert!(
        reasoning["id"]
            .as_str()
            .is_some_and(|id| id.starts_with("rs_")),
        "{reasoning}"
    );
    assert!(reasoning.get("encrypted_content").is_none(), "{reasoning}");
    Ok(())
}

// A held summary opens ahead of any later item. A tool delta that carries only an id emits no
// item yet, so it leaves the summary held; a reasoning item at a later index opens the held one
// first, under a synthesized id, so the output keeps stream order.
#[test]
fn responses_stream_held_reasoning_opens_ahead_of_later_items() -> TestResult {
    let engine = TranslationEngine::default();
    let format = WireFormat::OpenAiResponses;
    let mut state = StreamTranslationState::new(format, format);
    let mut events = engine.encode_stream_event(
        &mut state,
        format,
        LlmResponseStreamEvent::new(vec![
            LlmResponseChunk::MessageStart {
                id: Some("resp_1".into()),
                model: Some(REASONING_MODEL.into()),
            },
            LlmResponseChunk::ReasoningDetailsDelta {
                index: 0,
                details: vec![json!({"type": "reasoning.summary", "summary": "held"})],
                text: "held".into(),
            },
            LlmResponseChunk::ToolCallDelta {
                index: 1,
                id: Some("call_1".into()),
                name: None,
                arguments_delta: None,
            },
        ]),
    )?;
    assert!(
        events
            .iter()
            .all(|event| event["type"] != "response.output_item.added"),
        "{events:?}"
    );
    events.extend(engine.encode_stream_event(
        &mut state,
        format,
        LlmResponseStreamEvent::new(vec![LlmResponseChunk::ReasoningDetailsDelta {
            index: 2,
            details: vec![json!({"type": "reasoning.encrypted", "id": "rs_2", "data": "opaque"})],
            text: String::new(),
        }]),
    )?);
    events.extend(engine.finish_stream(&mut state, format)?);

    let added: Vec<(u64, &str)> = events
        .iter()
        .filter(|event| event["type"] == "response.output_item.added")
        .map(|event| {
            (
                event["output_index"].as_u64().unwrap_or(u64::MAX),
                event["item"]["id"].as_str().unwrap_or_default(),
            )
        })
        .collect();
    assert_eq!(added.len(), 2, "{added:?}");
    assert_eq!(added[0].0, 0);
    assert!(
        added[0].1.starts_with("rs_") && added[0].1 != "rs_2",
        "{added:?}"
    );
    assert_eq!(added[1], (1, "rs_2"));
    let completed = events
        .iter()
        .find(|event| event["type"] == "response.completed")
        .ok_or("expected response.completed")?;
    let output = completed["response"]["output"]
        .as_array()
        .ok_or("output should be an array")?;
    assert_eq!(output.len(), 2, "{output:?}");
    assert_eq!(
        output[0]["summary"],
        json!([{"type": "summary_text", "text": "held"}])
    );
    assert_eq!(output[1]["id"], "rs_2");
    assert_eq!(output[1]["encrypted_content"], "opaque");
    Ok(())
}

// Verifies Anthropic thinking deltas become OpenAI reasoning_content, not content.
#[test]
fn anthropic_thinking_stream_deltas_do_not_become_openai_chat_content() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state =
        StreamTranslationState::new(WireFormat::AnthropicMessages, WireFormat::OpenAiChat);
    let start = json!({
        "type": "message_start",
        "message": {"id": "msg_1", "model": "claude", "role": "assistant", "content": []}
    });
    let thinking_start = json!({
        "type": "content_block_start",
        "index": 0,
        "content_block": {"type": "thinking", "thinking": ""}
    });
    let thinking_delta = json!({
        "type": "content_block_delta",
        "index": 0,
        "delta": {"type": "thinking_delta", "thinking": "private chain of thought"}
    });
    let signature_delta = json!({
        "type": "content_block_delta",
        "index": 0,
        "delta": {"type": "signature_delta", "signature": "opaque-signature"}
    });

    let mut events = Vec::new();
    events.extend(engine.translate_event(
        &mut state,
        WireFormat::AnthropicMessages,
        WireFormat::OpenAiChat,
        &start,
    )?);
    events.extend(engine.translate_event(
        &mut state,
        WireFormat::AnthropicMessages,
        WireFormat::OpenAiChat,
        &thinking_start,
    )?);
    events.extend(engine.translate_event(
        &mut state,
        WireFormat::AnthropicMessages,
        WireFormat::OpenAiChat,
        &thinking_delta,
    )?);
    events.extend(engine.translate_event(
        &mut state,
        WireFormat::AnthropicMessages,
        WireFormat::OpenAiChat,
        &signature_delta,
    )?);

    let serialized = serde_json::to_string(&events)?;
    assert!(serialized.contains("private chain of thought"));
    assert!(!serialized.contains("opaque-signature"));
    assert!(events.iter().any(|event| {
        event["choices"][0]["delta"]["reasoning_content"] == "private chain of thought"
    }));
    assert!(
        !events
            .iter()
            .any(|event| { event["choices"][0]["delta"]["content"] == "private chain of thought" })
    );
    Ok(())
}

// A real Anthropic stream carries its stop reason on `message_delta` and then always
// sends a reasonless `message_stop`. Decoding both and folding the chunks must preserve
// the provider reason (here `max_tokens`) — the terminal `message_stop` must not emit a
// second, reasonless `MessageStop` that the accumulator would fold to `EndTurn`.
#[test]
fn anthropic_message_stop_does_not_overwrite_max_tokens_stop_reason() -> TestResult {
    let mut state =
        StreamTranslationState::new(WireFormat::AnthropicMessages, WireFormat::AnthropicMessages);
    let events = vec![
        json!({"type": "message_start", "message": {"id": "msg_1", "model": "claude", "usage": {"input_tokens": 3}}}),
        json!({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}),
        json!({"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Hi"}}),
        json!({"type": "message_delta", "delta": {"stop_reason": "max_tokens"}, "usage": {"output_tokens": 5}}),
        json!({"type": "message_stop"}),
    ];

    let mut accumulator = ResponseAccumulator::new();
    for event in &events {
        for chunk in decode_stream_event(&mut state, WireFormat::AnthropicMessages, event) {
            accumulator.push(chunk);
        }
    }
    let aggregate = accumulator.finish();

    assert_eq!(
        aggregate.outputs[0].stop_reason,
        Some(StopReason::MaxTokens),
        "the reasonless message_stop must not overwrite the max_tokens stop reason"
    );
    Ok(())
}

// Equivalent buffered and streamed Responses results must normalize to the same output.
#[test]
fn responses_buffered_and_streamed_outputs_match() -> TestResult {
    let engine = TranslationEngine::default();
    let buffered = engine
        .decode_response(
            WireFormat::OpenAiResponses,
            &json!({
                "id": "resp_1",
                "object": "response",
                "model": "gpt-reasoning",
                "status": "completed",
                "output": [
                    {
                        "type": "reasoning",
                        "summary": [{"type": "summary_text", "text": "private reasoning"}]
                    },
                    {
                        "type": "message",
                        "role": "assistant",
                        "content": [{"type": "output_text", "text": "Visible answer"}]
                    }
                ]
            }),
            &Default::default(),
        )?
        .response;

    let events = [
        json!({
            "type": "response.created",
            "response": {"id": "resp_1", "model": "gpt-reasoning"}
        }),
        json!({
            "type": "response.reasoning_summary_text.delta",
            "output_index": 0,
            "delta": "private reasoning"
        }),
        json!({
            "type": "response.output_text.delta",
            "output_index": 1,
            "delta": "Visible answer"
        }),
        json!({"type": "response.completed", "response": {}}),
    ];
    let mut state =
        StreamTranslationState::new(WireFormat::OpenAiResponses, WireFormat::OpenAiResponses);
    let mut accumulator = ResponseAccumulator::new();
    for event in &events {
        for chunk in decode_stream_event(&mut state, WireFormat::OpenAiResponses, event) {
            accumulator.push(chunk);
        }
    }

    assert_eq!(buffered.outputs, accumulator.finish().outputs);
    Ok(())
}

// The Responses events a provider streams for one completed function call, ending with a
// `response.completed` whose output repeats the finished call.
fn responses_function_call_stream() -> Vec<Value> {
    let call = json!({
        "id": "fc_1",
        "type": "function_call",
        "status": "completed",
        "call_id": "call_1",
        "name": "get_weather",
        "arguments": "{\"city\":\"Paris\"}"
    });
    vec![
        json!({
            "type": "response.created",
            "response": {"id": "resp_1", "model": "gpt-5.6", "status": "in_progress", "output": []}
        }),
        json!({
            "type": "response.output_item.added",
            "output_index": 0,
            "item": {
                "id": "fc_1",
                "type": "function_call",
                "status": "in_progress",
                "call_id": "call_1",
                "name": "get_weather",
                "arguments": ""
            }
        }),
        json!({
            "type": "response.function_call_arguments.delta",
            "item_id": "fc_1",
            "output_index": 0,
            "delta": "{\"city\":\"Paris\"}"
        }),
        json!({
            "type": "response.function_call_arguments.done",
            "item_id": "fc_1",
            "output_index": 0,
            "name": "get_weather",
            "arguments": "{\"city\":\"Paris\"}"
        }),
        json!({"type": "response.output_item.done", "output_index": 0, "item": call}),
        json!({
            "type": "response.completed",
            "response": {"id": "resp_1", "model": "gpt-5.6", "status": "completed", "output": [call]}
        }),
    ]
}

#[test]
fn anthropic_thinking_survives_responses_tool_continuation() -> TestResult {
    let engine = TranslationEngine::default();
    let policy = common::normalized_policy();
    let thinking = json!({
        "type": "thinking", "thinking": "Check the weather.\n", "signature": "opaque-signature"
    });
    let empty_thinking =
        json!({"type": "thinking", "thinking": "", "signature": "second-signature"});
    let tool = json!({"type": "tool_use", "id": "toolu_weather", "name": "weather", "input": {}});
    let buffered = engine
        .translate_response(
            WireFormat::AnthropicMessages,
            WireFormat::OpenAiResponses,
            &json!({"id": "msg_test", "type": "message", "role": "assistant", "model": "claude",
            "content": [thinking, empty_thinking, tool], "stop_reason": "tool_use",
            "usage": {"input_tokens": 1, "output_tokens": 1}}),
            &policy,
        )?
        .body;
    let events = vec![
        json!({"type": "message_start", "message": {"id": "msg_test", "model": "claude"}}),
        json!({"type": "content_block_start", "index": 0, "content_block": {
            "type": "thinking", "thinking": "Check ", "signature": "opaque-"}}),
        json!({"type": "content_block_delta", "index": 0, "delta": {
            "type": "thinking_delta", "thinking": "the weather.\n"}}),
        json!({"type": "content_block_delta", "index": 0, "delta": {
            "type": "signature_delta", "signature": "sig"}}),
        json!({"type": "content_block_delta", "index": 0, "delta": {
            "type": "signature_delta", "signature": "nature"}}),
        json!({"type": "content_block_stop", "index": 0}),
        json!({"type": "content_block_start", "index": 1, "content_block": empty_thinking}),
        json!({"type": "content_block_stop", "index": 1}),
        json!({"type": "content_block_start", "index": 2, "content_block": tool}),
        json!({"type": "content_block_delta", "index": 2, "delta": {
            "type": "input_json_delta", "partial_json": "{}"}}),
        json!({"type": "content_block_stop", "index": 2}),
        json!({"type": "message_delta", "delta": {"stop_reason": "tool_use"}}),
        json!({"type": "message_stop"}),
    ];
    let streamed = translate_stream(
        &engine,
        WireFormat::AnthropicMessages,
        WireFormat::OpenAiResponses,
        &events,
    )?;
    let done_items: Vec<Value> = streamed
        .iter()
        .filter(|event| event["type"] == "response.output_item.done")
        .map(|event| event["item"].clone())
        .collect();
    let completed = streamed
        .iter()
        .find(|event| event["type"] == "response.completed")
        .unwrap();
    for output in [
        &buffered["output"],
        &json!(done_items),
        &completed["response"]["output"],
    ] {
        let mut input = output.as_array().unwrap().clone();
        for item in &mut input {
            if item["type"] == "reasoning" {
                assert!(item["encrypted_content"].is_string());
                // Replay must use the signed original, not a client's edited summary.
                item["summary"] = json!([]);
            }
        }
        input.push(
            json!({"type": "function_call_output", "call_id": "toolu_weather", "output": "sunny"}),
        );
        let replay = engine
            .translate_request(
                WireFormat::OpenAiResponses,
                WireFormat::AnthropicMessages,
                &json!({"model": "claude", "input": input}),
                &policy,
            )?
            .body;
        assert_eq!(
            replay["messages"][0]["content"],
            json!([thinking, empty_thinking, tool])
        );
        assert_eq!(replay["messages"][1]["content"][0]["type"], "tool_result");
    }
    Ok(())
}

// Translates a whole source stream into `target` events, including the encoder's finish.
fn translate_stream(
    engine: &TranslationEngine,
    source: WireFormat,
    target: WireFormat,
    events: &[Value],
) -> std::result::Result<Vec<Value>, Box<dyn std::error::Error + Send + Sync>> {
    let mut state = StreamTranslationState::new(source, target);
    let mut out = Vec::new();
    for event in events {
        out.extend(engine.translate_event(&mut state, source, target, event)?);
    }
    out.extend(engine.finish_stream(&mut state, target)?);
    Ok(out)
}

// A streamed Responses function call must end with the tool-use stop reason the buffered decoder
// reports: Anthropic `tool_use`, Chat `tool_calls`. Anthropic's tool runners dispatch on it;
// `end_turn` makes them return the unfinished tool-use turn without running the tool. A bare
// `response.completed` with no output array falls back to the argument deltas already decoded,
// while a text-only stream still reports no reason.
#[test]
fn responses_function_call_stream_ends_with_tool_use_on_every_wire() -> TestResult {
    let engine = TranslationEngine::default();
    let stream = responses_function_call_stream();

    let anthropic = translate_stream(
        &engine,
        WireFormat::OpenAiResponses,
        WireFormat::AnthropicMessages,
        &stream,
    )?;
    let stop_reasons: Vec<&Value> = anthropic
        .iter()
        .filter(|event| event["type"] == "message_delta")
        .map(|event| &event["delta"]["stop_reason"])
        .collect();
    assert_eq!(stop_reasons, vec![&json!("tool_use")]);
    assert!(anthropic.iter().any(|event| {
        event["type"] == "content_block_start"
            && event["content_block"]["type"] == "tool_use"
            && event["content_block"]["name"] == "get_weather"
    }));

    let chat = translate_stream(
        &engine,
        WireFormat::OpenAiResponses,
        WireFormat::OpenAiChat,
        &stream,
    )?;
    let finish_reasons: Vec<&Value> = chat
        .iter()
        .filter_map(|event| event["choices"][0].get("finish_reason"))
        .filter(|reason| !reason.is_null())
        .collect();
    assert_eq!(finish_reasons, vec![&json!("tool_calls")]);
    assert!(chat.iter().any(|event| {
        event["choices"][0]["delta"]["tool_calls"][0]["function"]["name"] == "get_weather"
    }));

    // Delta-only fallback: `response.created`, one argument delta, then a bare completion with
    // no output-item events at all.
    let bare_completed = json!({"type": "response.completed", "response": {}});
    let mut state =
        StreamTranslationState::new(WireFormat::OpenAiResponses, WireFormat::OpenAiResponses);
    let mut last = Vec::new();
    for event in [&stream[0], &stream[2], &bare_completed] {
        last = decode_stream_event(&mut state, WireFormat::OpenAiResponses, event);
    }
    assert_eq!(
        last,
        vec![LlmResponseChunk::MessageStop {
            reason: Some("tool_use".to_string())
        }]
    );

    let mut state =
        StreamTranslationState::new(WireFormat::OpenAiResponses, WireFormat::OpenAiResponses);
    let text = json!({"type": "response.output_text.delta", "output_index": 0, "delta": "hi"});
    decode_stream_event(&mut state, WireFormat::OpenAiResponses, &text);
    assert_eq!(
        decode_stream_event(&mut state, WireFormat::OpenAiResponses, &bare_completed),
        vec![LlmResponseChunk::MessageStop { reason: None }]
    );
    Ok(())
}

// Chat clients subscript `tool_calls` with the streamed index, so tool calls must be numbered
// within that array. Anthropic and Responses index the whole content array, where text ahead
// of the first tool call pushes it to 1; the OpenAI SDK then indexes past a one-element array.
#[test]
fn chat_tool_call_index_counts_tool_calls_not_content_blocks() -> TestResult {
    let engine = TranslationEngine::default();
    let tool_indices = |events: &[Value]| -> Vec<Value> {
        events
            .iter()
            .filter_map(|event| event["choices"][0]["delta"]["tool_calls"].as_array())
            .flat_map(|calls| calls.iter().map(|call| call["index"].clone()))
            .collect()
    };

    // Anthropic: text at content index 0, then two tool calls at 1 and 2.
    let tool_block = |index: usize, id: &str| {
        vec![
            json!({"type": "content_block_start", "index": index, "content_block": {"type": "tool_use", "id": id, "name": "lookup", "input": {}}}),
            json!({"type": "content_block_delta", "index": index, "delta": {"type": "input_json_delta", "partial_json": "{\"q\":\"rust\"}"}}),
            json!({"type": "content_block_stop", "index": index}),
        ]
    };
    let mut anthropic = vec![
        json!({"type": "message_start", "message": {"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-test", "content": [], "usage": {"input_tokens": 1, "output_tokens": 1}}}),
        json!({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}),
        json!({"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Checking now."}}),
        json!({"type": "content_block_stop", "index": 0}),
    ];
    anthropic.extend(tool_block(1, "toolu_01"));
    anthropic.extend(tool_block(2, "toolu_02"));
    anthropic.push(json!({"type": "message_delta", "delta": {"stop_reason": "tool_use"}, "usage": {"output_tokens": 8}}));
    anthropic.push(json!({"type": "message_stop"}));
    let chat = translate_stream(
        &engine,
        WireFormat::AnthropicMessages,
        WireFormat::OpenAiChat,
        &anthropic,
    )?;
    assert_eq!(
        tool_indices(&chat),
        vec![json!(0), json!(0), json!(1), json!(1)]
    );

    // Responses: a message item at output index 0, then a function call at 1.
    let responses = [
        json!({"type": "response.created", "response": {"id": "resp_1", "model": "gpt-5.6"}}),
        json!({"type": "response.output_text.delta", "output_index": 0, "delta": "Checking now."}),
        json!({"type": "response.output_item.added", "output_index": 1, "item": {"id": "fc_1", "type": "function_call", "call_id": "call_1", "name": "lookup", "arguments": ""}}),
        json!({"type": "response.function_call_arguments.delta", "output_index": 1, "delta": "{\"q\":\"rust\"}"}),
        json!({"type": "response.completed", "response": {}}),
    ];
    let chat = translate_stream(
        &engine,
        WireFormat::OpenAiResponses,
        WireFormat::OpenAiChat,
        &responses,
    )?;
    assert_eq!(tool_indices(&chat), vec![json!(0), json!(0)]);
    Ok(())
}

#[test]
fn anthropic_empty_tool_input_survives_stream_translation() -> TestResult {
    let engine = TranslationEngine::default();
    let source = WireFormat::AnthropicMessages;
    for empty_fragments in [vec![""], vec![], vec!["{}"]] {
        let mut upstream = vec![
            json!({"type": "message_start", "message": {"id": "msg_tools", "model": "claude"}}),
            json!({"type": "content_block_start", "index": 1, "content_block": {
                "type": "tool_use", "id": "call_empty", "name": "clock", "input": {}}}),
            json!({"type": "content_block_start", "index": 2, "content_block": {
                "type": "tool_use", "id": "call_lookup", "name": "lookup", "input": {}}}),
        ];
        for fragment in empty_fragments {
            upstream.push(json!({"type": "content_block_delta", "index": 1,
                "delta": {"type": "input_json_delta", "partial_json": fragment}}));
        }
        upstream.extend([
            json!({"type": "content_block_delta", "index": 2,
                "delta": {"type": "input_json_delta", "partial_json": ""}}),
            json!({"type": "content_block_delta", "index": 2,
                "delta": {"type": "input_json_delta", "partial_json": "{\"q\":"}}),
            json!({"type": "content_block_stop", "index": 1}),
            json!({"type": "content_block_delta", "index": 2,
                "delta": {"type": "input_json_delta", "partial_json": "\"rust\"}"}}),
            json!({"type": "content_block_stop", "index": 2}),
            json!({"type": "message_delta", "delta": {"stop_reason": "tool_use"}}),
            json!({"type": "message_stop"}),
        ]);
        let mut observed = Vec::new();
        for separate_states in [false, true] {
            for target in [WireFormat::OpenAiChat, WireFormat::OpenAiResponses, source] {
                let mut decoder = StreamTranslationState::new(source, target);
                let mut encoder = StreamTranslationState::new(source, target);
                let mut events = Vec::new();
                for event in &upstream {
                    let decoded =
                        engine.decode_stream_event(&mut decoder, source, event.clone())?;
                    if event["delta"]["partial_json"] == "{\"q\":" {
                        assert!(
                            decoded.normalized().iter().any(|chunk| matches!(chunk,
                            LlmResponseChunk::ToolCallDelta { arguments_delta: Some(delta), .. }
                                if delta == "{\"q\":")),
                            "nonempty input must stream immediately"
                        );
                    }
                    let state = if separate_states {
                        &mut encoder
                    } else {
                        &mut decoder
                    };
                    events.extend(engine.encode_stream_event(state, target, decoded)?);
                }
                let state = if separate_states {
                    &mut encoder
                } else {
                    &mut decoder
                };
                events.extend(engine.finish_stream(state, target)?);
                assert!(engine.finish_stream(state, target)?.is_empty());
                if target == source {
                    assert_eq!(events, upstream);
                    continue;
                }
                let mut arguments = [String::new(), String::new()];
                for event in &events {
                    if target == WireFormat::OpenAiChat {
                        if let Some(calls) = event["choices"][0]["delta"]["tool_calls"].as_array() {
                            for call in calls {
                                let index =
                                    call["index"].as_u64().ok_or("missing tool index")? as usize;
                                if let Some(delta) = call["function"]["arguments"].as_str() {
                                    arguments[index].push_str(delta);
                                }
                            }
                        }
                    } else if event["type"] == "response.function_call_arguments.delta" {
                        let index = event["output_index"]
                            .as_u64()
                            .ok_or("missing output index")?
                            as usize;
                        arguments[index]
                            .push_str(event["delta"].as_str().ok_or("missing argument delta")?);
                    }
                }
                if target == WireFormat::OpenAiResponses {
                    let completed = events.last().ok_or("missing completion")?;
                    assert_eq!(completed["type"], "response.completed");
                    for (index, argument) in arguments.iter().enumerate() {
                        assert_eq!(
                            completed["response"]["output"][index]["arguments"],
                            *argument
                        );
                        let done = events
                            .iter()
                            .find(|event| {
                                event["type"] == "response.output_item.done"
                                    && event["output_index"] == index
                            })
                            .ok_or("missing completed tool")?;
                        assert_eq!(done["item"]["arguments"], *argument);
                        let done = events
                            .iter()
                            .find(|event| {
                                event["type"] == "response.function_call_arguments.done"
                                    && event["output_index"] == index
                            })
                            .ok_or("missing completed arguments")?;
                        assert_eq!(done["arguments"], *argument);
                    }
                }
                observed.push(arguments);
            }
        }
        assert_eq!(
            observed,
            vec![["{}".to_string(), r#"{"q":"rust"}"#.to_string()]; 4]
        );
        for arguments in observed {
            assert_eq!(serde_json::from_str::<Value>(&arguments[0])?, json!({}));
            assert_eq!(
                serde_json::from_str::<Value>(&arguments[1])?,
                json!({"q": "rust"})
            );
        }
    }
    // Initial values and partial inputs must not be replaced or completed with {}.
    for (input, fragment, closes, expected) in [
        (json!({"q": "rust"}), "", true, r#"{"q":"rust"}"#),
        (json!({}), "{", true, "{"),
        (json!({}), "", false, ""),
    ] {
        let mut state = StreamTranslationState::new(source, WireFormat::OpenAiChat);
        let mut events = vec![
            json!({"type": "content_block_start", "index": 0, "content_block": {
                "type": "tool_use", "id": "call_control", "name": "lookup", "input": input}}),
            json!({"type": "content_block_delta", "index": 0,
                "delta": {"type": "input_json_delta", "partial_json": fragment}}),
        ];
        if closes {
            events.push(json!({"type": "content_block_stop", "index": 0}));
        }
        events.push(json!({"type": "message_delta", "delta": {"stop_reason": "max_tokens"}}));
        events.push(json!({"type": "message_stop"}));
        let mut arguments = String::new();
        for event in events {
            for chunk in decode_stream_event(&mut state, source, &event) {
                if let LlmResponseChunk::ToolCallDelta {
                    arguments_delta: Some(delta),
                    ..
                } = chunk
                {
                    arguments.push_str(&delta);
                }
            }
        }
        assert_eq!(arguments, expected);
    }

    Ok(())
}

// An OpenAI-shaped error frame carries no `choices`, so it must decode to a stream error
// instead of a bare message start that silently drops the upstream message.
#[test]
fn openai_chat_error_frame_decodes_to_stream_error() -> TestResult {
    let mut state = StreamTranslationState::new(WireFormat::OpenAiChat, WireFormat::OpenAiChat);
    let event = json!({"error": {"message": "upstream exploded", "type": "server_error"}});

    let chunks = decode_stream_event(&mut state, WireFormat::OpenAiChat, &event);

    assert_eq!(chunks.len(), 1);
    match &chunks[0] {
        LlmResponseChunk::StreamError { message } => assert_eq!(message, "upstream exploded"),
        other => return Err(format!("expected StreamError, got {other:?}").into()),
    }
    Ok(())
}

// Verifies the streaming encoder matches the buffered one: both Responses usage detail objects
// are present even when the upstream reports no cache or reasoning breakdown.
#[test]
fn openai_chat_stream_usage_without_breakdowns_still_emits_responses_usage_details() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state =
        StreamTranslationState::new(WireFormat::OpenAiChat, WireFormat::OpenAiResponses);
    let usage = json!({
        "id": "chatcmpl-test",
        "object": "chat.completion.chunk",
        "model": "plain-model",
        "choices": [{
            "index": 0,
            "delta": {},
            "finish_reason": "stop"
        }],
        "usage": {"prompt_tokens": 41, "completion_tokens": 3, "total_tokens": 44}
    });

    let mut events = engine.translate_event(
        &mut state,
        WireFormat::OpenAiChat,
        WireFormat::OpenAiResponses,
        &usage,
    )?;
    events.extend(engine.finish_stream(&mut state, WireFormat::OpenAiResponses)?);

    let Some(completed) = events
        .iter()
        .find(|event| event["type"] == "response.completed")
    else {
        return Err("expected final Responses completion event".into());
    };
    assert_eq!(
        completed["response"]["usage"]["input_tokens_details"],
        json!({"cached_tokens": 0, "cache_write_tokens": 0})
    );
    assert_eq!(
        completed["response"]["usage"]["output_tokens_details"],
        json!({"reasoning_tokens": 0})
    );
    Ok(())
}

// Responses terminal snapshots include every field required by strict generated clients.
#[test]
fn responses_completed_event_is_schema_complete_and_retains_message_id() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state =
        StreamTranslationState::new(WireFormat::OpenAiChat, WireFormat::OpenAiResponses);
    let chunk = json!({
        "id": "chatcmpl-test",
        "object": "chat.completion.chunk",
        "model": "gpt-4o",
        "choices": [{
            "index": 0,
            "delta": {"content": "hello"},
            "finish_reason": "stop"
        }]
    });

    let mut events = engine.translate_event(
        &mut state,
        WireFormat::OpenAiChat,
        WireFormat::OpenAiResponses,
        &chunk,
    )?;
    events.extend(engine.finish_stream(&mut state, WireFormat::OpenAiResponses)?);

    for (expected, event) in events.iter().enumerate() {
        assert_eq!(event["sequence_number"], expected as u64);
    }
    let completed = events
        .iter()
        .find(|event| event["type"] == "response.completed")
        .ok_or("expected response.completed")?;
    let response = completed["response"]
        .as_object()
        .ok_or("completed response should be an object")?;
    for field in [
        "id",
        "object",
        "created_at",
        "completed_at",
        "error",
        "incomplete_details",
        "instructions",
        "metadata",
        "model",
        "output",
        "parallel_tool_calls",
        "frequency_penalty",
        "presence_penalty",
        "status",
        "temperature",
        "tool_choice",
        "tools",
        "top_p",
        "usage",
    ] {
        assert!(
            response.contains_key(field),
            "missing response field {field}"
        );
    }
    // Synthesized item ids carry the response id so they stay unique across turns.
    assert_eq!(response["output"][0]["id"], "msg_chatcmpl-test_0");
    let done = events
        .iter()
        .find(|event| event["type"] == "response.output_item.done")
        .ok_or("expected response.output_item.done")?;
    assert_eq!(done["item"]["id"], "msg_chatcmpl-test_0");
    Ok(())
}

// Some upstreams issue response ids several hundred characters long. Synthesized item ids
// embed the response id for uniqueness, but OpenAI rejects item ids over 64 characters, so long
// discriminators must be digested while staying distinct across responses.
#[test]
fn responses_synthesized_item_ids_stay_within_the_openai_length_limit() -> TestResult {
    let engine = TranslationEngine::default();
    let mut ids = Vec::new();
    for suffix in ["a", "b"] {
        let long_id = format!("chatcmpl-{}{suffix}", "x".repeat(360));
        let mut state =
            StreamTranslationState::new(WireFormat::OpenAiChat, WireFormat::OpenAiResponses);
        let chunk = json!({
            "id": long_id,
            "object": "chat.completion.chunk",
            "model": "gpt-4o",
            "choices": [{
                "index": 0,
                "delta": {"content": "hello"},
                "finish_reason": "stop"
            }]
        });
        let mut events = engine.translate_event(
            &mut state,
            WireFormat::OpenAiChat,
            WireFormat::OpenAiResponses,
            &chunk,
        )?;
        events.extend(engine.finish_stream(&mut state, WireFormat::OpenAiResponses)?);
        let done = events
            .iter()
            .find(|event| event["type"] == "response.output_item.done")
            .ok_or("expected response.output_item.done")?;
        let id = done["item"]["id"]
            .as_str()
            .ok_or("item id should be a string")?
            .to_string();
        assert!(id.starts_with("msg_"), "{id}");
        assert!(id.ends_with("_0"), "{id}");
        assert!(
            id.chars().count() <= 64,
            "{id} is {} chars",
            id.chars().count()
        );
        ids.push(id);
    }
    assert_ne!(
        ids[0], ids[1],
        "distinct responses must yield distinct item ids"
    );
    Ok(())
}

// Encrypted reasoning is bound to the item id the provider issued it under. When a buffered
// reply is re-streamed to the client, the emitted reasoning item must reuse that id or the
// client's replay fails verification upstream.
#[test]
fn responses_stream_reuses_provider_id_for_encrypted_reasoning() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state =
        StreamTranslationState::new(WireFormat::OpenAiResponses, WireFormat::OpenAiResponses);
    let chunks = vec![
        LlmResponseChunk::MessageStart {
            id: Some("resp_upstream".to_string()),
            model: Some("gpt-5.6-luna".to_string()),
        },
        LlmResponseChunk::ReasoningDetailsDelta {
            index: 0,
            details: vec![json!({
                "type": "reasoning.encrypted",
                "data": "opaque-encrypted-reasoning",
                "id": "rs_provider_issued"
            })],
            text: String::new(),
        },
        LlmResponseChunk::ReasoningDelta {
            index: 0,
            text: "thinking".to_string(),
        },
        LlmResponseChunk::TextDelta {
            index: 1,
            text: "done".to_string(),
        },
        LlmResponseChunk::MessageStop { reason: None },
    ];
    let mut events = Vec::new();
    for chunk in chunks {
        events.extend(engine.encode_stream_event(
            &mut state,
            WireFormat::OpenAiResponses,
            LlmResponseStreamEvent::new(vec![chunk]),
        )?);
    }
    events.extend(engine.finish_stream(&mut state, WireFormat::OpenAiResponses)?);

    let reasoning_done = events
        .iter()
        .find(|event| {
            event["type"] == "response.output_item.done" && event["item"]["type"] == "reasoning"
        })
        .ok_or("expected a completed reasoning item")?;
    assert_eq!(reasoning_done["item"]["id"], "rs_provider_issued");
    assert_eq!(
        reasoning_done["item"]["encrypted_content"],
        "opaque-encrypted-reasoning"
    );
    // Every reasoning event references the same provider id.
    for event in events.iter().filter(|event| {
        event["type"]
            .as_str()
            .is_some_and(|kind| kind.starts_with("response.reasoning_summary"))
    }) {
        assert_eq!(event["item_id"], "rs_provider_issued", "{event}");
    }
    Ok(())
}

// Verifies a streamed token-limit stop terminates with response.incomplete.
#[test]
fn openai_chat_length_finish_translates_to_responses_incomplete_event() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state =
        StreamTranslationState::new(WireFormat::OpenAiChat, WireFormat::OpenAiResponses);
    let chunk = json!({
        "id": "chatcmpl-test",
        "object": "chat.completion.chunk",
        "model": "gpt-4o",
        "choices": [{
            "index": 0,
            "delta": {"content": "Half an ans"},
            "finish_reason": "length"
        }]
    });

    let mut events = engine.translate_event(
        &mut state,
        WireFormat::OpenAiChat,
        WireFormat::OpenAiResponses,
        &chunk,
    )?;
    events.extend(engine.finish_stream(&mut state, WireFormat::OpenAiResponses)?);

    let Some(terminal) = events.last() else {
        return Err("finish should emit a terminal Responses event".into());
    };
    assert_eq!(terminal["type"], "response.incomplete");
    assert_eq!(terminal["response"]["status"], "incomplete");
    assert_eq!(
        terminal["response"]["incomplete_details"],
        json!({"reason": "max_output_tokens"})
    );
    assert_eq!(terminal["response"]["output"][0]["status"], "incomplete");
    Ok(())
}

// Verifies an Anthropic-vocabulary token-limit stop also terminates with response.incomplete.
#[test]
fn anthropic_max_tokens_stop_translates_to_responses_incomplete_event() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state =
        StreamTranslationState::new(WireFormat::AnthropicMessages, WireFormat::OpenAiResponses);
    let delta = json!({
        "type": "message_delta",
        "delta": {"stop_reason": "max_tokens"},
        "usage": {"output_tokens": 1}
    });

    let mut events = engine.translate_event(
        &mut state,
        WireFormat::AnthropicMessages,
        WireFormat::OpenAiResponses,
        &delta,
    )?;
    events.extend(engine.finish_stream(&mut state, WireFormat::OpenAiResponses)?);

    let Some(terminal) = events.last() else {
        return Err("finish should emit a terminal Responses event".into());
    };
    assert_eq!(terminal["type"], "response.incomplete");
    assert_eq!(
        terminal["response"]["incomplete_details"],
        json!({"reason": "max_output_tokens"})
    );
    Ok(())
}

// Verifies a streamed response.incomplete from a Responses upstream reaches a Chat client.
#[test]
fn responses_incomplete_event_translates_to_chat_length_finish() -> TestResult {
    // A token-limited response must retain final accounting as well as the length stop reason.
    let engine = TranslationEngine::default();
    let mut state =
        StreamTranslationState::new(WireFormat::OpenAiResponses, WireFormat::OpenAiChat);
    let incomplete = json!({
        "type": "response.incomplete",
        "response": {"status": "incomplete", "incomplete_details": {"reason": "max_output_tokens"},
            "usage":{"input_tokens":12000,"input_tokens_details":{"cached_tokens":4000,"cache_write_tokens":7000},"output_tokens":16,"total_tokens":12016,"cost":0.01515}}
    });

    let mut events = engine.translate_event(
        &mut state,
        WireFormat::OpenAiResponses,
        WireFormat::OpenAiChat,
        &incomplete,
    )?;
    events.extend(engine.finish_stream(&mut state, WireFormat::OpenAiChat)?);

    let Some(terminal) = events
        .iter()
        .find(|event| event["choices"][0]["finish_reason"] == "length")
    else {
        return Err("finish should emit a terminal Chat chunk".into());
    };
    assert_eq!(terminal["choices"][0]["finish_reason"], "length");
    let usage = events
        .iter()
        .find_map(|event| event.get("usage"))
        .ok_or("missing terminal usage")?;
    assert_eq!(usage["prompt_tokens"], 12000);
    assert_eq!(usage["prompt_tokens_details"]["cached_tokens"], 4000);
    assert_eq!(usage["prompt_tokens_details"]["cache_write_tokens"], 7000);
    assert_eq!(usage["cost"], 0.01515);
    Ok(())
}

// Interleave text and two tool calls to check that deltas keep the right item IDs.
// Completion events must include the full text and tool arguments, and the final
// response must preserve each item's ID.
#[test]
fn translated_responses_text_and_tool_events_keep_item_identity_until_done() -> TestResult {
    let cases = [
        (
            WireFormat::OpenAiChat,
            vec![
                json!({"id":"chat_1","model":"model/local","choices":[{"index":0,"delta":{"role":"assistant","content":"Hel"}}]}),
                json!({"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_a","type":"function","function":{"name":"lookup","arguments":"{"}}]}}]}),
                json!({"choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"id":"call_b","type":"function","function":{"name":"weather","arguments":"{"}}]}}]}),
                json!({"choices":[{"index":0,"delta":{"content":"lo"}}]}),
                json!({"choices":[{"index":0,"delta":{"tool_calls":[{"index":1,"function":{"arguments":"\"city\":\"Paris\"}"}}]}}]}),
                json!({"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"id\":1}"}}]}}]}),
                json!({"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}),
            ],
        ),
        (
            WireFormat::AnthropicMessages,
            vec![
                json!({"type":"message_start","message":{"id":"msg_1","model":"model/local","role":"assistant","content":[],"usage":{"input_tokens":1,"output_tokens":0}}}),
                json!({"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}),
                json!({"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hel"}}),
                json!({"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"lo"}}),
                json!({"type":"content_block_stop","index":0}),
                json!({"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"call_a","name":"lookup","input":{}}}),
                json!({"type":"content_block_start","index":2,"content_block":{"type":"tool_use","id":"call_b","name":"weather","input":{}}}),
                json!({"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{"}}),
                json!({"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"{"}}),
                json!({"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"\"city\":\"Paris\"}"}}),
                json!({"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"\"id\":1}"}}),
                json!({"type":"content_block_stop","index":1}),
                json!({"type":"content_block_stop","index":2}),
                json!({"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":1}}),
                json!({"type":"message_stop"}),
            ],
        ),
    ];
    for (source, upstream) in cases {
        let engine = TranslationEngine::default();
        let target = WireFormat::OpenAiResponses;
        let mut state = StreamTranslationState::new(source, target);
        let mut events = Vec::new();
        for event in upstream {
            events.extend(engine.translate_event(&mut state, source, target, &event)?);
        }
        events.extend(engine.finish_stream(&mut state, target)?);
        assert!(engine.finish_stream(&mut state, target)?.is_empty());
        let items = events
            .iter()
            .filter(|event| event["type"] == "response.output_item.added")
            .map(|event| {
                (
                    event["output_index"].as_u64().unwrap_or_default(),
                    &event["item"],
                )
            })
            .collect::<HashMap<_, _>>();
        assert_eq!(items.len(), 3);
        for (sequence, event) in events.iter().enumerate() {
            assert_eq!(event["sequence_number"], sequence);
            let kind = event["type"].as_str().unwrap_or_default();
            if kind.starts_with("response.output_text.")
                || kind.starts_with("response.content_part.")
                || kind.starts_with("response.function_call_arguments.")
            {
                let index = event["output_index"]
                    .as_u64()
                    .ok_or("missing output index")?;
                assert_eq!(event["item_id"], items[&index]["id"], "{source:?}: {kind}");
            }
            if kind.starts_with("response.output_text.") {
                assert_eq!(event["content_index"], 0);
                assert_eq!(event["logprobs"], json!([]));
            }
            if kind.starts_with("response.content_part.") {
                assert_eq!(event["part"]["annotations"], json!([]));
                assert_eq!(event["part"]["logprobs"], json!([]));
            }
        }
        let text_events = events
            .iter()
            .filter(|event| event["output_index"] == 0)
            .map(|event| event["type"].as_str().unwrap_or_default())
            .collect::<Vec<_>>();
        assert_eq!(
            text_events,
            [
                "response.output_item.added",
                "response.content_part.added",
                "response.output_text.delta",
                "response.output_text.delta",
                "response.output_text.done",
                "response.content_part.done",
                "response.output_item.done"
            ]
        );
        let text_done = events
            .iter()
            .find(|event| event["type"] == "response.output_text.done")
            .ok_or("missing text completion")?;
        assert_eq!(text_done["text"], "Hello");
        for (index, name, call_id, arguments) in [
            (1, "lookup", "call_a", r#"{"id":1}"#),
            (2, "weather", "call_b", r#"{"city":"Paris"}"#),
        ] {
            let tool_events = events
                .iter()
                .filter(|event| event["output_index"] == index)
                .collect::<Vec<_>>();
            let mut expected_types = vec![
                "response.output_item.added",
                "response.function_call_arguments.delta",
                "response.function_call_arguments.done",
                "response.output_item.done",
            ];
            if source == WireFormat::AnthropicMessages {
                expected_types.insert(2, "response.function_call_arguments.delta");
            }
            assert_eq!(
                tool_events
                    .iter()
                    .map(|event| event["type"].as_str().unwrap_or_default())
                    .collect::<Vec<_>>(),
                expected_types
            );
            let done = tool_events[tool_events.len() - 2];
            assert_eq!(done["name"], name);
            assert_eq!(done["arguments"], arguments);
            let item_done = tool_events[tool_events.len() - 1];
            assert_eq!(item_done["item"]["id"], items[&index]["id"]);
            assert_eq!(item_done["item"]["call_id"], call_id);
        }
        let completed = events.last().ok_or("missing response completion")?;
        assert_eq!(completed["type"], "response.completed");
        let output = completed["response"]["output"]
            .as_array()
            .ok_or("missing final output")?;
        assert_eq!(output.len(), 3);
        assert_eq!(
            output[0]["content"][0],
            json!({"type":"output_text","text":"Hello","annotations":[],"logprobs":[]})
        );
        for (index, item) in output.iter().enumerate() {
            assert_eq!(item["id"], items[&(index as u64)]["id"]);
        }
    }
    Ok(())
}

// A completion event must not repeat function-call arguments from delta events.
#[test]
fn responses_decode_emits_tool_arguments_once() -> TestResult {
    let engine = TranslationEngine::default();
    let mut state = StreamTranslationState::default();
    let arguments = r#"{"skill":"demo:thing","args":{}}"#;

    let upstream = [
        json!({"type": "response.output_item.added", "output_index": 0,
               "item": {"type": "function_call", "call_id": "call_1",
                        "name": "Skill", "arguments": ""}}),
        json!({"type": "response.function_call_arguments.delta",
               "output_index": 0, "delta": arguments}),
        json!({"type": "response.output_item.done", "output_index": 0,
               "item": {"type": "function_call", "call_id": "call_1",
                        "name": "Skill", "arguments": arguments}}),
    ];

    let mut seen = String::new();
    for event in upstream {
        let decoded = engine.decode_stream_event(&mut state, WireFormat::OpenAiResponses, event)?;
        for chunk in decoded.normalized() {
            if let LlmResponseChunk::ToolCallDelta {
                arguments_delta: Some(delta),
                ..
            } = chunk
            {
                seen.push_str(delta);
            }
        }
    }

    assert_eq!(seen, arguments);
    Ok(())
}

// A Responses `reasoning` output item may carry only `encrypted_content`, with no
// plaintext. The stream decoder must surface it as a `reasoning.encrypted` detail so a
// caller that buffers the stream (the escalation router) still holds something the
// client can replay; otherwise the reasoning is dropped before it reaches the IR.
#[test]
fn responses_stream_decodes_encrypted_reasoning_item_into_details() -> TestResult {
    let engine = TranslationEngine::default();
    let format = WireFormat::OpenAiResponses;
    let mut state = StreamTranslationState::new(format, format);
    let event = json!({
        "type": "response.output_item.done",
        "output_index": 0,
        "item": {
            "type": "reasoning",
            "id": "rs_upstream",
            "status": "completed",
            "summary": [],
            "encrypted_content": "opaque-encrypted-reasoning"
        }
    });

    let decoded = engine.decode_stream_event(&mut state, format, event)?;

    assert_eq!(
        decoded.normalized(),
        &[LlmResponseChunk::ReasoningDetailsDelta {
            index: 0,
            details: vec![json!({
                "type": "reasoning.encrypted",
                "data": "opaque-encrypted-reasoning",
                "id": "rs_upstream"
            })],
            text: String::new(),
        }]
    );
    Ok(())
}

// The synthesized encode path (no preserved provider JSON, as produced by
// `AggLlmResponse::into_stream`) must emit an encrypted-only reasoning detail as a
// Responses `reasoning` item carrying `encrypted_content`, not drop it.
#[test]
fn responses_stream_encodes_encrypted_reasoning_details_as_reasoning_item() -> TestResult {
    let engine = TranslationEngine::default();
    let format = WireFormat::OpenAiResponses;
    let mut state = StreamTranslationState::new(format, format);
    let chunks = vec![
        LlmResponseChunk::MessageStart {
            id: Some("resp_1".to_string()),
            model: Some(REASONING_MODEL.to_string()),
        },
        LlmResponseChunk::ReasoningDetailsDelta {
            index: 0,
            details: vec![json!({
                "type": "reasoning.encrypted",
                "data": "opaque-encrypted-reasoning"
            })],
            text: String::new(),
        },
        LlmResponseChunk::MessageStop { reason: None },
    ];

    let mut events = Vec::new();
    for chunk in chunks {
        events.extend(engine.encode_stream_event(
            &mut state,
            format,
            LlmResponseStreamEvent::new(vec![chunk]),
        )?);
    }
    events.extend(engine.finish_stream(&mut state, format)?);

    let done_item = events
        .iter()
        .filter(|event| event["type"] == "response.output_item.done")
        .map(|event| &event["item"])
        .find(|item| item["type"] == "reasoning")
        .ok_or("expected a completed reasoning output item")?;
    assert_eq!(done_item["encrypted_content"], "opaque-encrypted-reasoning");

    let completed = events
        .iter()
        .find(|event| event["type"] == "response.completed")
        .ok_or("expected response.completed")?;
    let final_reasoning = completed["response"]["output"]
        .as_array()
        .ok_or("output should be an array")?
        .iter()
        .find(|item| item["type"] == "reasoning")
        .ok_or("final output should include the reasoning item")?;
    assert_eq!(
        final_reasoning["encrypted_content"],
        "opaque-encrypted-reasoning"
    );
    Ok(())
}

// Some providers deliver a reasoning item only in `response.output_item.done`, as
// plaintext in a top-level `text` field, with no streamed `reasoning_text.delta` events.
// The decoder must surface that text so a buffering caller can re-emit the item.
#[test]
fn responses_stream_decodes_text_only_reasoning_item_from_done() -> TestResult {
    let engine = TranslationEngine::default();
    let format = WireFormat::OpenAiResponses;
    let mut state = StreamTranslationState::new(format, format);
    let event = json!({
        "type": "response.output_item.done",
        "output_index": 0,
        "item": {"type": "reasoning", "id": "rs_upstream", "text": "Let me explore the repo first."}
    });

    let decoded = engine.decode_stream_event(&mut state, format, event)?;

    assert_eq!(
        decoded.normalized(),
        &[
            LlmResponseChunk::ReasoningDetailsDelta {
                index: 0,
                details: vec![json!({"type": "reasoning.encrypted", "id": "rs_upstream"})],
                text: String::new(),
            },
            LlmResponseChunk::ReasoningDelta {
                index: 0,
                text: "Let me explore the repo first.".to_string(),
            }
        ]
    );
    Ok(())
}

// When reasoning text already streamed through `reasoning_text.delta`, the completed item
// that repeats it must not be decoded a second time.
#[test]
fn responses_stream_does_not_duplicate_streamed_reasoning_on_done() -> TestResult {
    let engine = TranslationEngine::default();
    let format = WireFormat::OpenAiResponses;
    let mut state = StreamTranslationState::new(format, format);
    let delta = json!({
        "type": "response.reasoning_text.delta",
        "output_index": 0,
        "content_index": 0,
        "delta": "Let me explore"
    });
    let done = json!({
        "type": "response.output_item.done",
        "output_index": 0,
        "item": {
            "type": "reasoning",
            "id": "rs_upstream",
            "content": [{"type": "reasoning_text", "text": "Let me explore"}]
        }
    });

    let first = engine.decode_stream_event(&mut state, format, delta)?;
    let second = engine.decode_stream_event(&mut state, format, done)?;

    assert_eq!(first.normalized().len(), 1);
    // The done item contributes only its provider id, never the text again.
    assert_eq!(
        second.normalized(),
        &[LlmResponseChunk::ReasoningDetailsDelta {
            index: 0,
            details: vec![json!({"type": "reasoning.encrypted", "id": "rs_upstream"})],
            text: String::new(),
        }]
    );
    Ok(())
}

// Providers differ in which event carries a reasoning item's text. Each carrier must decode
// exactly once: `output_item.added` with text, a `reasoning_text.done` with no prior deltas,
// and a reasoning item that appears only inside `response.completed`'s output array.
#[test]
fn responses_stream_decodes_reasoning_text_from_added_done_and_completed_once() -> TestResult {
    let engine = TranslationEngine::default();
    let format = WireFormat::OpenAiResponses;

    // (a) only in output_item.added
    let mut state = StreamTranslationState::new(format, format);
    let added = json!({"type": "response.output_item.added", "output_index": 0,
        "item": {"type": "reasoning", "id": "rs_a", "text": "from added"}});
    let decoded = engine.decode_stream_event(&mut state, format, added)?;
    assert_eq!(
        decoded.normalized(),
        &[
            LlmResponseChunk::ReasoningDetailsDelta {
                index: 0,
                details: vec![json!({"type": "reasoning.encrypted", "id": "rs_a"})],
                text: String::new(),
            },
            LlmResponseChunk::ReasoningDelta {
                index: 0,
                text: "from added".into()
            }
        ]
    );
    // the matching done repeats it and must be skipped
    let done = json!({"type": "response.output_item.done", "output_index": 0,
        "item": {"type": "reasoning", "id": "rs_a", "text": "from added"}});
    assert_eq!(
        engine
            .decode_stream_event(&mut state, format, done)?
            .normalized(),
        &[]
    );

    // (b) only in reasoning_text.done
    let mut state = StreamTranslationState::new(format, format);
    let text_done = json!({"type": "response.reasoning_text.done", "output_index": 1,
        "content_index": 0, "text": "from text done"});
    let decoded = engine.decode_stream_event(&mut state, format, text_done)?;
    assert_eq!(
        decoded.normalized(),
        &[LlmResponseChunk::ReasoningDelta {
            index: 1,
            text: "from text done".into()
        }]
    );

    // (c) only inside response.completed output; emitted before the stop
    let mut state = StreamTranslationState::new(format, format);
    let completed = json!({"type": "response.completed", "response": {"id": "resp_1",
        "output": [{"type": "reasoning", "id": "rs_c", "text": "from completed"}],
        "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2}}});
    let decoded = engine.decode_stream_event(&mut state, format, completed)?;
    let kinds: Vec<&str> = decoded
        .normalized()
        .iter()
        .map(|c| match c {
            LlmResponseChunk::ReasoningDelta { text, .. } => {
                assert_eq!(text, "from completed");
                "reasoning"
            }
            LlmResponseChunk::ReasoningDetailsDelta { .. } => "id",
            LlmResponseChunk::Usage(_) => "usage",
            LlmResponseChunk::MessageStop { .. } => "stop",
            _ => "other",
        })
        .collect();
    assert_eq!(kinds, vec!["id", "reasoning", "usage", "stop"]);

    // (d) completed output repeating already-streamed reasoning adds nothing
    let mut state = StreamTranslationState::new(format, format);
    let delta =
        json!({"type": "response.reasoning_text.delta", "output_index": 0, "delta": "streamed"});
    engine.decode_stream_event(&mut state, format, delta)?;
    let completed = json!({"type": "response.completed", "response": {"id": "resp_2",
        "output": [{"type": "reasoning", "id": "rs_d", "text": "streamed"}]}});
    let decoded = engine.decode_stream_event(&mut state, format, completed)?;
    assert!(
        decoded
            .normalized()
            .iter()
            .all(|c| !matches!(c, LlmResponseChunk::ReasoningDelta { .. }))
    );
    Ok(())
}

// Codex records a reasoning item only in the standard Responses shape: text lives in
// `summary: [{"type": "summary_text", ...}]` and streams as `reasoning_summary_part.added`,
// `reasoning_summary_text.delta`, `reasoning_summary_text.done`, `reasoning_summary_part.done`.
// The encoder must emit that shape, not a `content: [reasoning_text]` item, or the client
// silently drops the reasoning.
#[test]
fn responses_stream_encodes_reasoning_as_summary_text() -> TestResult {
    let engine = TranslationEngine::default();
    let format = WireFormat::OpenAiResponses;
    let mut state = StreamTranslationState::new(format, format);
    let chunks = vec![
        LlmResponseChunk::MessageStart {
            id: Some("resp_1".into()),
            model: Some(REASONING_MODEL.into()),
        },
        LlmResponseChunk::ReasoningDelta {
            index: 0,
            text: "Let me ".into(),
        },
        LlmResponseChunk::ReasoningDelta {
            index: 0,
            text: "think.".into(),
        },
        LlmResponseChunk::TextDelta {
            index: 1,
            text: "done".into(),
        },
        LlmResponseChunk::MessageStop { reason: None },
    ];
    let mut events = Vec::new();
    for chunk in chunks {
        events.extend(engine.encode_stream_event(
            &mut state,
            format,
            LlmResponseStreamEvent::new(vec![chunk]),
        )?);
    }
    events.extend(engine.finish_stream(&mut state, format)?);
    let types: Vec<&str> = events.iter().filter_map(|e| e["type"].as_str()).collect();

    assert!(
        types.contains(&"response.reasoning_summary_part.added"),
        "{types:?}"
    );
    assert_eq!(
        types
            .iter()
            .filter(|t| **t == "response.reasoning_summary_text.delta")
            .count(),
        2,
        "{types:?}"
    );
    assert!(
        types.contains(&"response.reasoning_summary_text.done"),
        "{types:?}"
    );
    assert!(
        types.contains(&"response.reasoning_summary_part.done"),
        "{types:?}"
    );
    assert!(
        !types
            .iter()
            .any(|t| t.starts_with("response.reasoning_text.")),
        "legacy reasoning_text events must not be emitted: {types:?}"
    );

    let done = events
        .iter()
        .filter(|e| e["type"] == "response.output_item.done")
        .map(|e| &e["item"])
        .find(|i| i["type"] == "reasoning")
        .ok_or("reasoning output_item.done")?;
    assert_eq!(
        done["summary"],
        json!([{"type": "summary_text", "text": "Let me think."}])
    );
    assert!(
        done.get("content")
            .is_none_or(|c| c.as_array().is_some_and(Vec::is_empty)),
        "no content part: {done}"
    );

    let completed = events
        .iter()
        .find(|e| e["type"] == "response.completed")
        .ok_or("completed")?;
    let final_reasoning = completed["response"]["output"]
        .as_array()
        .ok_or("output")?
        .iter()
        .find(|i| i["type"] == "reasoning")
        .ok_or("final reasoning item")?;
    assert_eq!(final_reasoning["summary"][0]["text"], "Let me think.");
    Ok(())
}

// Item ids the encoder synthesizes must be unique across responses. A client replays the
// whole conversation, so two turns whose reasoning items are both `rs_0` (and whose tool
// calls are both `fc_1`) hand the upstream a history with colliding ids. Passthrough carries
// the provider's unique ids; the synthesized path must not be worse.
#[test]
fn responses_stream_synthesized_item_ids_are_unique_across_responses() -> TestResult {
    let engine = TranslationEngine::default();
    let format = WireFormat::OpenAiResponses;
    let mut ids = Vec::new();
    for resp in ["resp_first", "resp_second"] {
        let mut state = StreamTranslationState::new(format, format);
        let chunks = vec![
            LlmResponseChunk::MessageStart {
                id: Some(resp.into()),
                model: Some(REASONING_MODEL.into()),
            },
            LlmResponseChunk::ReasoningDelta {
                index: 0,
                text: "think".into(),
            },
            LlmResponseChunk::ToolCallDelta {
                index: 1,
                id: Some("call_x".into()),
                name: Some("exec_command".into()),
                arguments_delta: Some("{}".into()),
            },
            LlmResponseChunk::TextDelta {
                index: 2,
                text: "done".into(),
            },
            LlmResponseChunk::MessageStop { reason: None },
        ];
        let mut events = Vec::new();
        for chunk in chunks {
            events.extend(engine.encode_stream_event(
                &mut state,
                format,
                LlmResponseStreamEvent::new(vec![chunk]),
            )?);
        }
        events.extend(engine.finish_stream(&mut state, format)?);
        for e in events
            .iter()
            .filter(|e| e["type"] == "response.output_item.done")
        {
            ids.push((
                e["item"]["type"].as_str().unwrap_or("").to_string(),
                e["item"]["id"].as_str().unwrap_or("").to_string(),
            ));
        }
    }
    let mut seen = std::collections::HashSet::new();
    for (kind, id) in &ids {
        assert!(!id.is_empty(), "{kind} item without id");
        assert!(
            seen.insert(id.clone()),
            "item id {id} ({kind}) repeated across responses: {ids:?}"
        );
    }
    Ok(())
}

// Decodes a provider Responses stream and re-encodes it the way the buffered/escalation path
// does: from normalized chunks, with no preserved provider JSON.
fn reencode_responses_events(
    events: Vec<Value>,
) -> Result<Vec<Value>, Box<dyn std::error::Error + Send + Sync>> {
    let engine = TranslationEngine::default();
    let format = WireFormat::OpenAiResponses;
    let mut decode_state = StreamTranslationState::new(format, format);
    let mut encode_state = StreamTranslationState::new(format, format);
    let mut out = Vec::new();
    for event in events {
        let decoded = engine.decode_stream_event(&mut decode_state, format, event)?;
        for chunk in decoded.normalized() {
            out.extend(engine.encode_stream_event(
                &mut encode_state,
                format,
                LlmResponseStreamEvent::new(vec![chunk.clone()]),
            )?);
        }
    }
    out.extend(engine.finish_stream(&mut encode_state, format)?);
    Ok(out)
}

// GPT-5 emits a reasoning item ahead of each tool call. Every one of them must reach the
// client under its provider id with its encrypted payload, in the provider's order.
#[test]
fn responses_stream_keeps_every_reasoning_item_of_a_response() -> TestResult {
    let events = vec![
        json!({"type": "response.created", "response": {"id": "resp_up", "model": "gpt-5.6-luna"}}),
        json!({"type": "response.output_item.added", "output_index": 0,
               "item": {"type": "reasoning", "id": "rs_a", "summary": []}}),
        json!({"type": "response.output_item.done", "output_index": 0,
               "item": {"type": "reasoning", "id": "rs_a", "summary": [], "encrypted_content": "enc-a"}}),
        json!({"type": "response.output_item.added", "output_index": 1,
               "item": {"type": "function_call", "id": "fc_1", "call_id": "call_1", "name": "exec", "arguments": ""}}),
        json!({"type": "response.output_item.done", "output_index": 1,
               "item": {"type": "function_call", "id": "fc_1", "call_id": "call_1", "name": "exec", "arguments": "{\"cmd\":\"ls\"}"}}),
        json!({"type": "response.output_item.added", "output_index": 2,
               "item": {"type": "reasoning", "id": "rs_b", "summary": []}}),
        json!({"type": "response.output_item.done", "output_index": 2,
               "item": {"type": "reasoning", "id": "rs_b", "summary": [], "encrypted_content": "enc-b"}}),
        json!({"type": "response.output_item.added", "output_index": 3,
               "item": {"type": "function_call", "id": "fc_3", "call_id": "call_3", "name": "exec", "arguments": ""}}),
        json!({"type": "response.output_item.done", "output_index": 3,
               "item": {"type": "function_call", "id": "fc_3", "call_id": "call_3", "name": "exec", "arguments": "{\"cmd\":\"pwd\"}"}}),
    ];
    let events = reencode_responses_events(events)?;

    let reasoning_done: Vec<&Value> = events
        .iter()
        .filter(|event| {
            event["type"] == "response.output_item.done" && event["item"]["type"] == "reasoning"
        })
        .collect();
    assert_eq!(reasoning_done.len(), 2, "both reasoning items must close");
    assert_eq!(reasoning_done[0]["item"]["id"], "rs_a");
    assert_eq!(reasoning_done[0]["item"]["encrypted_content"], "enc-a");
    assert_eq!(reasoning_done[1]["item"]["id"], "rs_b");
    assert_eq!(reasoning_done[1]["item"]["encrypted_content"], "enc-b");

    let completed = events
        .iter()
        .find(|event| event["type"] == "response.completed")
        .ok_or("expected response.completed")?;
    let kinds: Vec<&str> = completed["response"]["output"]
        .as_array()
        .ok_or("output array")?
        .iter()
        .filter_map(|item| item["type"].as_str())
        .collect();
    assert_eq!(
        kinds,
        ["reasoning", "function_call", "reasoning", "function_call"]
    );
    Ok(())
}

// Summary text streams before the encrypted payload arrives on `done`. The item must open
// under the provider id announced by `added`, not a synthesized one, so the payload is kept.
#[test]
fn responses_stream_opens_reasoning_under_provider_id_before_payload_arrives() -> TestResult {
    let events = vec![
        json!({"type": "response.created", "response": {"id": "resp_up", "model": "gpt-5.6-luna"}}),
        json!({"type": "response.output_item.added", "output_index": 0,
               "item": {"type": "reasoning", "id": "rs_a", "summary": []}}),
        json!({"type": "response.reasoning_summary_text.delta", "output_index": 0, "item_id": "rs_a",
               "summary_index": 0, "delta": "plan"}),
        json!({"type": "response.output_item.done", "output_index": 0,
               "item": {"type": "reasoning", "id": "rs_a", "summary": [{"type": "summary_text", "text": "plan"}],
                        "encrypted_content": "enc-a"}}),
    ];
    let events = reencode_responses_events(events)?;

    let added: Vec<&Value> = events
        .iter()
        .filter(|event| {
            event["type"] == "response.output_item.added" && event["item"]["type"] == "reasoning"
        })
        .collect();
    assert_eq!(added.len(), 1, "one reasoning item opens");
    assert_eq!(added[0]["item"]["id"], "rs_a");
    let done = events
        .iter()
        .find(|event| {
            event["type"] == "response.output_item.done" && event["item"]["type"] == "reasoning"
        })
        .ok_or("expected a completed reasoning item")?;
    assert_eq!(done["item"]["id"], "rs_a");
    assert_eq!(done["item"]["encrypted_content"], "enc-a");
    assert_eq!(done["item"]["summary"][0]["text"], "plan");
    Ok(())
}

// An encrypted-only reasoning item streams no text, so it must not open a summary part it can
// never close; the client should see the item open, then close with an empty `summary` and the
// encrypted payload attached.
#[test]
fn responses_stream_encrypted_only_reasoning_opens_no_summary_part() -> TestResult {
    let engine = TranslationEngine::default();
    let format = WireFormat::OpenAiResponses;
    let mut state = StreamTranslationState::new(format, format);
    let chunks = vec![
        LlmResponseChunk::MessageStart {
            id: Some("resp_1".into()),
            model: Some(REASONING_MODEL.into()),
        },
        LlmResponseChunk::ReasoningDetailsDelta {
            index: 0,
            details: vec![json!({"type": "reasoning.encrypted", "data": "opaque", "id": "rs_1"})],
            text: String::new(),
        },
        LlmResponseChunk::TextDelta {
            index: 1,
            text: "done".into(),
        },
        LlmResponseChunk::MessageStop { reason: None },
    ];
    let mut events = Vec::new();
    for chunk in chunks {
        events.extend(engine.encode_stream_event(
            &mut state,
            format,
            LlmResponseStreamEvent::new(vec![chunk]),
        )?);
    }
    events.extend(engine.finish_stream(&mut state, format)?);
    let types: Vec<&str> = events.iter().filter_map(|e| e["type"].as_str()).collect();

    assert!(
        !types
            .iter()
            .any(|t| t.starts_with("response.reasoning_summary")),
        "{types:?}"
    );
    let done = events
        .iter()
        .find(|e| e["type"] == "response.output_item.done" && e["item"]["type"] == "reasoning")
        .ok_or("expected the reasoning item to close")?;
    assert_eq!(done["item"]["id"], "rs_1");
    assert_eq!(done["item"]["encrypted_content"], "opaque");
    assert_eq!(done["item"]["summary"], json!([]));
    Ok(())
}

// An empty reasoning delta opens the item but not a summary part, so a provider that sends a
// blank first delta does not leave the client with an unclosed part.
#[test]
fn responses_stream_empty_reasoning_delta_opens_no_summary_part() -> TestResult {
    let engine = TranslationEngine::default();
    let format = WireFormat::OpenAiResponses;
    let mut state = StreamTranslationState::new(format, format);
    let chunks = vec![
        LlmResponseChunk::MessageStart {
            id: Some("resp_1".into()),
            model: Some(REASONING_MODEL.into()),
        },
        LlmResponseChunk::ReasoningDelta {
            index: 0,
            text: String::new(),
        },
        LlmResponseChunk::TextDelta {
            index: 1,
            text: "done".into(),
        },
        LlmResponseChunk::MessageStop { reason: None },
    ];
    let mut events = Vec::new();
    for chunk in chunks {
        events.extend(engine.encode_stream_event(
            &mut state,
            format,
            LlmResponseStreamEvent::new(vec![chunk]),
        )?);
    }
    events.extend(engine.finish_stream(&mut state, format)?);
    let types: Vec<&str> = events.iter().filter_map(|e| e["type"].as_str()).collect();
    assert!(
        !types
            .iter()
            .any(|t| t.starts_with("response.reasoning_summary")),
        "{types:?}"
    );
    assert!(types.contains(&"response.output_item.added"), "{types:?}");
    Ok(())
}

#[test]
fn responses_terminal_snapshots_recover_missing_output_once() -> TestResult {
    let engine = TranslationEngine::default();
    let source = WireFormat::OpenAiResponses;
    let output = json!([
        {"type": "message", "role": "assistant", "content": [
            {"type": "output_text", "text": "Visible answer"}
        ]},
        {"type": "function_call", "id": "fc_1", "call_id": "call_1",
         "name": "get_weather", "arguments": "{\"city\":\"Paris\"}"}
    ]);
    let response =
        json!({"id": "resp_1", "model": "fixture", "status": "completed", "output": output});
    let mut expected = engine
        .decode_response(source, &response, &Default::default())?
        .response;
    if let switchyard_protocol::ContentBlock::ToolCall(call) = &mut expected.outputs[0].content[1] {
        call.arguments = json!({"city": "Paris"});
    }
    for target in [WireFormat::OpenAiChat, WireFormat::AnthropicMessages] {
        for mode in [
            "terminal",
            "done",
            "partial",
            "full",
            "name_only",
            "id_only",
        ] {
            let mut events = vec![
                json!({"type": "response.created", "response": {"id": "resp_1", "model": "fixture"}}),
            ];
            if matches!(mode, "partial" | "full") {
                events.push(
                    json!({"type": "response.output_text.delta", "output_index": 0,
                    "delta": if mode == "full" { "Visible answer" } else { "Visible " }}),
                );
                events.push(json!({"type": "response.output_item.added", "output_index": 1,
                    "item": {"type": "function_call", "call_id": "call_1", "name": "get_weather", "arguments": ""}}));
                events.push(
                    json!({"type": "response.function_call_arguments.delta", "output_index": 1,
                    "delta": if mode == "full" { "{\"city\":\"Paris\"}" } else { "{\"city\":" }}),
                );
            }
            if matches!(mode, "name_only" | "id_only") {
                let mut item =
                    json!({"type": "function_call", "arguments": "{\"city\":\"Paris\"}"});
                if mode == "name_only" {
                    item["name"] = json!("get_weather");
                } else {
                    item["call_id"] = json!("call_1");
                }
                for event_type in ["response.output_item.added", "response.output_item.done"] {
                    events.push(json!({"type": event_type, "output_index": 1, "item": item}));
                }
            } else if mode != "terminal" {
                for (index, item) in output.as_array().unwrap().iter().enumerate() {
                    events.push(json!({"type": "response.output_item.done", "output_index": index, "item": item}));
                }
            }
            events.push(json!({"type": "response.completed", "response": response}));
            let mut decoder = StreamTranslationState::new(source, target);
            let mut encoder = StreamTranslationState::new(source, target);
            let mut reader = StreamTranslationState::new(target, target);
            let mut accumulator = ResponseAccumulator::new();
            for event in events {
                let is_incomplete_identity = matches!(mode, "name_only" | "id_only")
                    && event["type"] != "response.completed";
                let decoded = engine.decode_stream_event(&mut decoder, source, event)?;
                for encoded in engine.encode_stream_event(&mut encoder, target, decoded)? {
                    if target == WireFormat::AnthropicMessages && is_incomplete_identity {
                        assert_ne!(encoded["content_block"]["type"], "tool_use");
                    }
                    for chunk in decode_stream_event(&mut reader, target, &encoded) {
                        accumulator.push(chunk);
                    }
                }
            }
            for encoded in engine.finish_stream(&mut encoder, target)? {
                for chunk in decode_stream_event(&mut reader, target, &encoded) {
                    accumulator.push(chunk);
                }
            }
            assert_eq!(
                expected.outputs,
                accumulator.finish().outputs,
                "{target:?}: {mode}"
            );
        }
    }
    for event_type in ["response.output_item.added", "response.output_item.done"] {
        for identity in [
            json!({}),
            json!({"call_id": "", "name": "get_weather"}),
            json!({"id": "fc_1", "name": ""}),
        ] {
            let mut state = StreamTranslationState::new(source, WireFormat::OpenAiChat);
            let mut item = identity;
            item["type"] = json!("function_call");
            let incomplete = engine.decode_stream_event(
                &mut state,
                source,
                json!({"type": event_type, "output_index": 1, "item": item}),
            )?;
            let target = WireFormat::AnthropicMessages;
            let mut encoder = StreamTranslationState::new(source, target);
            let early = engine.encode_stream_event(&mut encoder, target, incomplete)?;
            assert!(
                early
                    .iter()
                    .all(|event| event["content_block"]["type"] != "tool_use")
            );
            let terminal = engine.finish_stream(&mut encoder, target)?;
            assert_eq!(terminal.len(), 1);
            assert_eq!(terminal[0]["type"], "error");
            assert!(engine.finish_stream(&mut encoder, target)?.is_empty());
            let decoded = engine.decode_stream_event(
                &mut state,
                source,
                json!({"type": "response.completed", "response": response}),
            )?;
            assert!(
                decoded.normalized().iter().any(|chunk| matches!(chunk,
                    LlmResponseChunk::ToolCallDelta { id: Some(id), name: Some(name), .. }
                    if id == "call_1" && name == "get_weather"
                )),
                "{event_type}: {item}"
            );
            engine.decode_stream_event(
                &mut state,
                source,
                json!({"type": event_type, "output_index": 1, "item": item}),
            )?;
            let repeated = engine.decode_stream_event(
                &mut state,
                source,
                json!({"type": "response.completed", "response": response}),
            )?;
            assert!(
                !repeated
                    .normalized()
                    .iter()
                    .any(|chunk| matches!(chunk, LlmResponseChunk::ToolCallDelta { .. }))
            );
        }
    }
    for delta in [
        json!({"type": "response.output_text.delta", "output_index": 0, "delta": "Different"}),
        json!({"type": "response.function_call_arguments.delta", "output_index": 1, "delta": "["}),
    ] {
        let mut state = StreamTranslationState::new(source, WireFormat::OpenAiChat);
        engine.decode_stream_event(&mut state, source, delta)?;
        let decoded = engine.decode_stream_event(
            &mut state,
            source,
            json!({"type": "response.completed", "response": response}),
        )?;
        assert!(matches!(
            decoded.normalized().last(),
            Some(LlmResponseChunk::DecodeError { .. })
        ));
        assert!(
            !decoded
                .normalized()
                .iter()
                .any(|chunk| matches!(chunk, LlmResponseChunk::MessageStop { .. }))
        );
    }
    Ok(())
}

// LiteLLM in front of Bedrock streams a freeform call as function-style argument deltas that
// spell `{"content": ...}`. OpenAI streams it with custom input deltas. Both must decode,
// without a conflict, to one call whose only arguments are the finished input.
#[test]
fn responses_custom_tool_calls_decode_from_the_finished_item() -> TestResult {
    let engine = TranslationEngine::default();
    let source = WireFormat::OpenAiResponses;
    let done = json!({"type": "custom_tool_call", "id": "ctc_1", "call_id": "call_1", "name": "exec", "input": "ls"});
    let added = json!({"type": "response.output_item.added", "output_index": 1,
        "item": {"type": "custom_tool_call", "id": "ctc_1", "call_id": "call_1", "name": "exec", "input": ""}});
    let item_done =
        json!({"type": "response.output_item.done", "output_index": 1, "item": done.clone()});
    let completed = json!({"type": "response.completed", "response": {"id": "resp_1", "status": "completed",
        "output": [{"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": ""}]}, done]}});
    let litellm = vec![
        added.clone(),
        json!({"type": "response.function_call_arguments.delta", "output_index": 1, "delta": "{\"content\": "}),
        json!({"type": "response.function_call_arguments.delta", "output_index": 1, "delta": "\"ls\"}"}),
        json!({"type": "response.function_call_arguments.done", "output_index": 1, "arguments": "{\"content\": \"ls\"}"}),
        item_done.clone(),
        completed.clone(),
    ];
    let openai = vec![
        added,
        json!({"type": "response.custom_tool_call_input.delta", "output_index": 1, "delta": "ls"}),
        json!({"type": "response.custom_tool_call_input.done", "output_index": 1, "input": "ls"}),
        item_done,
        completed,
    ];
    for (shape, events) in [("litellm", litellm), ("openai", openai)] {
        let mut state = StreamTranslationState::new(source, WireFormat::OpenAiChat);
        let mut chunks = Vec::new();
        for event in events {
            chunks.extend(
                engine
                    .decode_stream_event(&mut state, source, event)?
                    .normalized()
                    .to_vec(),
            );
        }
        assert!(
            !chunks.iter().any(|chunk| matches!(
                chunk,
                LlmResponseChunk::DecodeError { .. } | LlmResponseChunk::StreamError { .. }
            )),
            "{shape}: {chunks:?}"
        );
        let arguments: String = chunks
            .iter()
            .filter_map(|chunk| match chunk {
                LlmResponseChunk::ToolCallDelta {
                    arguments_delta: Some(arguments),
                    ..
                } => Some(arguments.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(arguments, r#"{"input":"ls"}"#, "{shape}");
    }
    Ok(())
}