Skip to main content

switchyard_translation/codecs/responses/
buffered.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Buffered codec for OpenAI Responses request and response JSON.
5
6use std::collections::HashMap;
7
8use serde_json::{Map, Value, json};
9use switchyard_protocol::MAX_IR_TEMPERATURE;
10
11use super::MAX_TEMPERATURE;
12use crate::codecs::common::{
13    collect_responses_reasoning_text, encrypted_reasoning_data, encrypted_reasoning_item_id,
14    is_anthropic_request, is_known_role_name, provider_extensions, reasoning_text_from_blocks,
15    scale_temperature, text_from_blocks,
16};
17use crate::codecs::openai_chat::{decode_file_source, decode_image_source};
18use crate::codecs::openai_media::{
19    ImagePayload, file_payload, file_source_text, image_payload, image_source_text,
20};
21use crate::codecs::structured_output::{decode_openai_schema_enforcement, encode_openai_format};
22use crate::codecs::{
23    DecodedRequest, DecodedResponse, EncodedRequest, EncodedResponse, FormatCodec,
24};
25use crate::diagnostic::TranslationDiagnostic;
26use crate::error::{Result, TranslationError};
27use crate::format::{FormatId, WireFormat};
28use crate::llm::{
29    AggLlmResponse, ContentBlock, FileSource, ImageSource, LlmRequest, MediaSource, Message,
30    OutputParams, ProviderExtensions, ReasoningParams, ResponseOutput, Role, SamplingParams,
31    StopReason, Tool, ToolCall, ToolChoice, ToolDefinition, ToolResult, Usage,
32};
33use crate::policy::{DeterministicIdPolicy, TranslationPolicy};
34use crate::util::{
35    capture_request_preservation, capture_response_preservation, embed_preservation,
36    exact_preserved_request, exact_preserved_response, is_responses_native_input_item, json_string,
37    push_lossy, stable_id, string_value, validate_request_capabilities,
38};
39
40/// Format codec for OpenAI Responses payloads.
41pub struct OpenAiResponsesCodec;
42
43impl FormatCodec for OpenAiResponsesCodec {
44    fn format(&self) -> FormatId {
45        WireFormat::OpenAiResponses.into()
46    }
47
48    fn decode_request(&self, body: &Value, policy: &TranslationPolicy) -> Result<DecodedRequest> {
49        let body = crate::util::object(body, "$")?;
50        let mut diagnostics = Vec::new();
51        let response_format = decode_responses_text_format(body.get("text"));
52        let mut request = LlmRequest {
53            model: body
54                .get("model")
55                .and_then(Value::as_str)
56                .filter(|model| !model.is_empty())
57                .map(ToOwned::to_owned),
58            output: OutputParams {
59                max_output_tokens: body.get("max_output_tokens").and_then(Value::as_u64),
60                is_schema_enforced: decode_openai_schema_enforcement(response_format.as_ref()),
61                response_format,
62            },
63            reasoning: ReasoningParams {
64                effort: body
65                    .get("reasoning")
66                    .and_then(Value::as_object)
67                    .and_then(|object| object.get("effort"))
68                    .and_then(Value::as_str)
69                    .map(ToOwned::to_owned),
70                raw: body.get("reasoning").cloned(),
71            },
72            sampling: SamplingParams {
73                temperature: body
74                    .get("temperature")
75                    .and_then(Value::as_f64)
76                    .map(|value| scale_temperature(value, MAX_TEMPERATURE, MAX_IR_TEMPERATURE)),
77                top_p: body.get("top_p").and_then(Value::as_f64),
78                top_k: None,
79            },
80            stream: body.get("stream").and_then(Value::as_bool).unwrap_or(false),
81            preservation: capture_request_preservation(
82                WireFormat::OpenAiResponses,
83                &Value::Object(body.clone()),
84                policy,
85            ),
86            ..LlmRequest::default()
87        };
88        if let Some(instructions) = body.get("instructions").and_then(Value::as_str)
89            && !instructions.is_empty()
90        {
91            request.instructions.push(crate::llm::InstructionBlock {
92                role: Role::System,
93                content: vec![ContentBlock::Text {
94                    text: instructions.to_string(),
95                }],
96            });
97        }
98        // With `previous_response_id`, the provider holds the earlier turns, so a tool output
99        // may answer a call that is not in this body.
100        let stored_state = body
101            .get("previous_response_id")
102            .and_then(Value::as_str)
103            .is_some_and(|id| !id.is_empty());
104        let mut custom_call_outputs = Vec::new();
105        request.messages = decode_responses_input(
106            body.get("input").unwrap_or(&Value::String(String::new())),
107            stored_state,
108            &mut custom_call_outputs,
109            &mut diagnostics,
110            policy,
111        )?;
112        let mut tool_namespaces = Map::new();
113        let mut custom_tools = Map::new();
114        request.tools =
115            decode_responses_tools(body.get("tools"), &mut tool_namespaces, &mut custom_tools)
116                .into_iter()
117                .map(Tool::from)
118                .collect();
119        // Responses-lite clients (Codex with a GPT-5 model) carry the tool definitions inside
120        // `input` as an `additional_tools` developer item instead of top-level `tools`. Those
121        // definitions are the request's tools; the item itself is kept verbatim so the request
122        // can be re-emitted in the shape the client used.
123        let mut additional_tools = Vec::new();
124        if let Some(items) = body.get("input").and_then(Value::as_array) {
125            for item in items {
126                if let Some(item) = item.as_object()
127                    && item.get("type").and_then(Value::as_str) == Some("additional_tools")
128                    && let Some(tools) = item.get("tools").and_then(Value::as_array)
129                {
130                    request.tools.extend(
131                        decode_responses_tools(
132                            Some(&Value::Array(tools.clone())),
133                            &mut tool_namespaces,
134                            &mut custom_tools,
135                        )
136                        .into_iter()
137                        .map(Tool::from),
138                    );
139                    additional_tools.extend(tools.iter().cloned());
140                }
141            }
142        }
143        request.tool_choice = body
144            .get("tool_choice")
145            .and_then(decode_responses_tool_choice);
146        request.extensions.fields = provider_extensions(
147            body,
148            &[
149                "model",
150                "instructions",
151                "input",
152                "tools",
153                "tool_choice",
154                "max_output_tokens",
155                "text",
156                "reasoning",
157                "temperature",
158                "top_p",
159                "stream",
160            ],
161        );
162        crate::codex_namespaces::attach_tool_namespaces(&mut request.extensions, tool_namespaces);
163        crate::codex_custom_tools::attach_custom_tools(&mut request.extensions, custom_tools);
164        crate::codex_custom_tools::attach_custom_call_outputs(
165            &mut request.extensions,
166            custom_call_outputs,
167        );
168        crate::codex_custom_tools::attach_additional_tools(
169            &mut request.extensions,
170            additional_tools,
171        );
172        Ok(DecodedRequest {
173            request,
174            diagnostics,
175        })
176    }
177
178    fn encode_request(
179        &self,
180        request: &LlmRequest,
181        policy: &TranslationPolicy,
182    ) -> Result<EncodedRequest> {
183        if let Some(body) =
184            exact_preserved_request(&request.preservation, WireFormat::OpenAiResponses, policy)
185        {
186            return Ok(EncodedRequest {
187                body,
188                diagnostics: Vec::new(),
189            });
190        }
191        let mut diagnostics = Vec::new();
192        validate_request_capabilities(request, &mut diagnostics, policy)?;
193        let mut body = Map::new();
194        if let Some(model) = &request.model {
195            body.insert("model".to_string(), Value::String(model.clone()));
196        }
197        let instructions = request
198            .instructions
199            .iter()
200            .flat_map(|instruction| instruction.content.iter())
201            .filter_map(|block| match block {
202                ContentBlock::Text { text } | ContentBlock::Refusal { text } => Some(text.as_str()),
203                _ => None,
204            })
205            .collect::<Vec<_>>()
206            .join("\n\n");
207        if !instructions.is_empty() {
208            body.insert("instructions".to_string(), Value::String(instructions));
209        }
210        body.insert(
211            "input".to_string(),
212            encode_responses_input(
213                &request.messages,
214                &mut diagnostics,
215                policy,
216                crate::codex_namespaces::tool_namespaces(&request.extensions),
217                &crate::codex_custom_tools::custom_tool_names(&request.extensions),
218                crate::codex_custom_tools::custom_call_outputs(&request.extensions),
219            )?,
220        );
221        if let Some(additional) = crate::codex_custom_tools::additional_tools(&request.extensions) {
222            // A Responses-lite request carried its tools inside `input`; give them back the same
223            // way, verbatim, and leave top-level `tools` absent as the client did.
224            let item = json!({
225                "type": "additional_tools",
226                "role": "developer",
227                "tools": additional,
228            });
229            match body.get_mut("input") {
230                Some(Value::Array(input)) => input.insert(0, item),
231                _ => body
232                    .insert("input".to_string(), Value::Array(vec![item]))
233                    .map_or((), |_| ()),
234            }
235        } else if !request.tools.is_empty() {
236            body.insert(
237                "tools".to_string(),
238                encode_responses_tools(
239                    &request.tools,
240                    crate::codex_namespaces::tool_namespaces(&request.extensions),
241                    crate::codex_custom_tools::custom_tools(&request.extensions),
242                )?,
243            );
244        }
245        if let Some(choice) = &request.tool_choice
246            && let Some(choice) = encode_responses_tool_choice(
247                choice,
248                crate::codex_namespaces::tool_namespaces(&request.extensions),
249                crate::codex_custom_tools::custom_tools(&request.extensions),
250            )
251        {
252            body.insert("tool_choice".to_string(), choice);
253        }
254        if let Some(max_output_tokens) = request.output.max_output_tokens {
255            body.insert("max_output_tokens".to_string(), json!(max_output_tokens));
256        }
257        if let Some(response_format) =
258            encode_openai_format(&request.output, &mut diagnostics, policy)?
259        {
260            body.insert(
261                "text".to_string(),
262                json!({"format": encode_responses_text_format(&response_format)}),
263            );
264        }
265        // An Anthropic request's raw reasoning is its `thinking` object, which Responses
266        // does not accept. Keep only whether thinking is disabled.
267        let mut reasoning = if is_anthropic_request(request) {
268            let mut reasoning = Map::new();
269            if request
270                .reasoning
271                .raw
272                .as_ref()
273                .and_then(|thinking| thinking.get("type"))
274                .and_then(Value::as_str)
275                == Some("disabled")
276            {
277                reasoning.insert("effort".to_string(), json!("none"));
278            }
279            reasoning
280        } else {
281            request
282                .reasoning
283                .raw
284                .as_ref()
285                .and_then(Value::as_object)
286                .cloned()
287                .unwrap_or_default()
288        };
289        if let Some(effort) = &request.reasoning.effort {
290            reasoning.insert("effort".to_string(), json!(effort));
291        }
292        if !reasoning.is_empty() {
293            body.insert("reasoning".to_string(), Value::Object(reasoning));
294        }
295        if let Some(value) = request.sampling.temperature {
296            let value = scale_temperature(value, MAX_IR_TEMPERATURE, MAX_TEMPERATURE);
297            body.insert("temperature".to_string(), json!(value));
298        }
299        if let Some(value) = request.sampling.top_p {
300            body.insert("top_p".to_string(), json!(value));
301        }
302        if request.stream {
303            body.insert("stream".to_string(), Value::Bool(true));
304        }
305        copy_responses_request_extensions(&mut body, &request.extensions.fields);
306
307        let body = embed_preservation(Value::Object(body), &request.preservation, policy);
308        Ok(EncodedRequest { body, diagnostics })
309    }
310
311    fn decode_response(&self, body: &Value, policy: &TranslationPolicy) -> Result<DecodedResponse> {
312        let body = crate::util::object(body, "$")?;
313        // Providers can return HTTP 200 when generation fails. Check `status`
314        // before treating an empty `output` as a completed turn.
315        if body.get("status").and_then(Value::as_str) == Some("failed") {
316            return Err(TranslationError::UpstreamFailure {
317                error: body
318                    .get("error")
319                    .filter(|error| error.is_object())
320                    .cloned()
321                    .unwrap_or_else(|| {
322                        json!({ "message": "provider reported status \"failed\" without error details" })
323                    }),
324            });
325        }
326        let mut diagnostics = Vec::new();
327        let mut content = Vec::new();
328        let mut role = Role::Assistant;
329        let mut stop_reason = None;
330        let mut has_output = false;
331        let mut url_citations = Vec::new();
332        let mut text_offset = 0;
333        if let Some(items) = body.get("output").and_then(Value::as_array) {
334            for item in items {
335                if let Some(output) = decode_responses_output_item(item, &mut diagnostics, policy)?
336                {
337                    has_output = true;
338                    role = output.role;
339                    for mut citation in output.url_citations {
340                        citation.start_index += text_offset;
341                        citation.end_index += text_offset;
342                        url_citations.push(citation);
343                    }
344                    text_offset += output
345                        .content
346                        .iter()
347                        .map(|block| match block {
348                            ContentBlock::Text { text } | ContentBlock::Refusal { text } => {
349                                text.chars().count()
350                            }
351                            _ => 0,
352                        })
353                        .sum::<usize>();
354                    content.extend(output.content);
355                    if output.stop_reason.is_some() {
356                        stop_reason = output.stop_reason;
357                    }
358                }
359            }
360        }
361        // The truncation signal is on the response, not the output items.
362        if body.get("status").and_then(Value::as_str) == Some("incomplete")
363            && body
364                .get("incomplete_details")
365                .and_then(|details| details.get("reason"))
366                .and_then(Value::as_str)
367                == Some("max_output_tokens")
368        {
369            stop_reason = Some(StopReason::MaxTokens);
370        }
371        let outputs = vec![if has_output {
372            ResponseOutput {
373                url_citations,
374                role,
375                content,
376                stop_reason,
377            }
378        } else {
379            ResponseOutput {
380                url_citations: Vec::new(),
381                role: Role::Assistant,
382                content: vec![ContentBlock::Text {
383                    text: String::new(),
384                }],
385                stop_reason: Some(StopReason::EndTurn),
386            }
387        }];
388        let response = AggLlmResponse {
389            id: body
390                .get("id")
391                .and_then(Value::as_str)
392                .map(ToOwned::to_owned),
393            model: body
394                .get("model")
395                .and_then(Value::as_str)
396                .map(ToOwned::to_owned),
397            outputs,
398            usage: decode_responses_usage(body.get("usage")),
399            extensions: ProviderExtensions {
400                fields: provider_extensions(
401                    body,
402                    &["id", "model", "object", "output", "usage", "status"],
403                ),
404            },
405            preservation: capture_response_preservation(
406                WireFormat::OpenAiResponses,
407                &Value::Object(body.clone()),
408                policy,
409            ),
410        };
411        Ok(DecodedResponse {
412            response,
413            diagnostics,
414        })
415    }
416
417    fn encode_response(
418        &self,
419        response: &AggLlmResponse,
420        _policy: &TranslationPolicy,
421    ) -> Result<EncodedResponse> {
422        if let Some(body) =
423            exact_preserved_response(&response.preservation, WireFormat::OpenAiResponses, _policy)
424        {
425            return Ok(EncodedResponse {
426                body,
427                diagnostics: Vec::new(),
428            });
429        }
430        let is_truncated = matches!(
431            response
432                .first_output()
433                .and_then(|output| output.stop_reason),
434            Some(StopReason::MaxTokens)
435        );
436        let status = if is_truncated {
437            "incomplete"
438        } else {
439            "completed"
440        };
441        let incomplete_details = is_truncated.then(|| json!({ "reason": "max_output_tokens" }));
442        Ok(EncodedResponse {
443            body: embed_preservation(
444                json!({
445                    "id": response.id.clone().unwrap_or_else(|| "resp_switchyard".to_string()),
446                    "object": "response",
447                    "created_at": 0,
448                    "model": response.model.clone().unwrap_or_else(|| "unknown".to_string()),
449                    "status": status,
450                    "incomplete_details": incomplete_details,
451                    "output": encode_responses_output(&response.outputs),
452                    "usage": encode_responses_usage(&response.usage),
453                    "parallel_tool_calls": true,
454                    "tool_choice": "auto",
455                    "tools": [],
456                }),
457                &response.preservation,
458                _policy,
459            ),
460            diagnostics: Vec::new(),
461        })
462    }
463}
464
465/// Decodes Responses `input` into ordered normalized messages.
466fn decode_responses_input(
467    value: &Value,
468    stored_state: bool,
469    custom_call_outputs: &mut Vec<String>,
470    diagnostics: &mut Vec<TranslationDiagnostic>,
471    policy: &TranslationPolicy,
472) -> Result<Vec<Message>> {
473    match value {
474        Value::String(text) => Ok(vec![Message::text(Role::User, text)]),
475        Value::Array(items) => {
476            let mut messages = Vec::new();
477            let mut pending_tool_calls = Vec::new();
478            let mut pending_tool_outputs = Vec::new();
479            let mut deferred_messages = Vec::new();
480            let mut pending_reasoning: Vec<ContentBlock> = Vec::new();
481            for (index, item) in items.iter().enumerate() {
482                let Some(item) = item.as_object() else {
483                    push_lossy(
484                        diagnostics,
485                        policy,
486                        format!("Responses input item {index} is not an object"),
487                    )?;
488                    continue;
489                };
490                let item_type = match item.get("type") {
491                    Some(Value::String(item_type)) => Some(item_type.as_str()),
492                    Some(_) => {
493                        return Err(TranslationError::InvalidType {
494                            path: format!("$.input[{index}].type"),
495                            expected: "a string",
496                        });
497                    }
498                    None => None,
499                };
500                let is_message = item_type == Some("message")
501                    || (item_type.is_none()
502                        && item.contains_key("role")
503                        && item.contains_key("content"));
504                match item_type {
505                    _ if is_message => {
506                        let role = request_role_from_responses(
507                            item.get("role").and_then(Value::as_str),
508                            &format!("$.input[{index}].role"),
509                        )?;
510                        let content_value = item.get("content").unwrap_or(&Value::Null);
511                        if is_responses_native_input_item(content_value) {
512                            return Err(TranslationError::InvalidValue {
513                                path: format!("$.input[{index}].content.type"),
514                                message: "native Responses items must be top-level input items"
515                                    .to_string(),
516                            });
517                        }
518                        if let Some(content_index) = content_value.as_array().and_then(|blocks| {
519                            blocks.iter().position(is_responses_native_input_item)
520                        }) {
521                            return Err(TranslationError::InvalidValue {
522                                path: format!("$.input[{index}].content[{content_index}].type"),
523                                message: "native Responses items must be top-level input items"
524                                    .to_string(),
525                            });
526                        }
527                        let mut content = decode_responses_content(content_value);
528                        // Inline instructions wait behind an open tool block or pending
529                        // reasoning. They never split tool calls from their outputs, and
530                        // reasoning keeps its place before them.
531                        if matches!(role, Role::System | Role::Developer)
532                            && !(pending_tool_calls.is_empty()
533                                && pending_tool_outputs.is_empty()
534                                && pending_reasoning.is_empty())
535                        {
536                            deferred_messages.push(Message::new(role, content));
537                            continue;
538                        }
539                        // Reasoning that precedes an assistant message belongs to
540                        // that turn; fold it in so it never surfaces as its own
541                        // (empty-looking) assistant message downstream.
542                        if role == Role::Assistant
543                            && pending_tool_calls.is_empty()
544                            && !pending_reasoning.is_empty()
545                        {
546                            let mut merged = std::mem::take(&mut pending_reasoning);
547                            merged.append(&mut content);
548                            content = merged;
549                            // Instructions held behind the reasoning came before this turn.
550                            if pending_tool_outputs.is_empty() {
551                                messages.append(&mut deferred_messages);
552                            }
553                        }
554                        if role != Role::Assistant {
555                            flush_unattached_responses_reasoning(
556                                &mut messages,
557                                &mut pending_tool_calls,
558                                &mut pending_tool_outputs,
559                                &mut deferred_messages,
560                                &mut pending_reasoning,
561                            );
562                        }
563                        push_responses_non_tool_message(
564                            &mut messages,
565                            &mut pending_tool_calls,
566                            &mut pending_tool_outputs,
567                            &mut deferred_messages,
568                            &mut pending_reasoning,
569                            Message {
570                                role,
571                                content,
572                                phase: if role == Role::Assistant {
573                                    item.get("phase").and_then(Value::as_str).map(str::to_owned)
574                                } else {
575                                    None
576                                },
577                            },
578                        );
579                    }
580                    Some("reasoning") => {
581                        // A reasoning item after a completed tool block opens the
582                        // next assistant turn: flush the finished block so this
583                        // reasoning attaches to the turn that produced it.
584                        if !pending_tool_outputs.is_empty() {
585                            flush_responses_tool_block(
586                                &mut messages,
587                                &mut pending_tool_calls,
588                                &mut pending_tool_outputs,
589                                &mut deferred_messages,
590                                &mut pending_reasoning,
591                            );
592                        }
593                        pending_reasoning.extend(decode_responses_reasoning_item(item));
594                    }
595                    Some("function_call") => {
596                        if !pending_tool_outputs.is_empty() {
597                            flush_responses_tool_block(
598                                &mut messages,
599                                &mut pending_tool_calls,
600                                &mut pending_tool_outputs,
601                                &mut deferred_messages,
602                                &mut pending_reasoning,
603                            );
604                        }
605                        let id = item
606                            .get("call_id")
607                            .and_then(Value::as_str)
608                            .filter(|id| !id.is_empty())
609                            .map(ToOwned::to_owned)
610                            .unwrap_or_else(|| match &policy.deterministic_ids {
611                                DeterministicIdPolicy::GenerateStable { prefix } => {
612                                    stable_id(prefix, index + 1)
613                                }
614                                DeterministicIdPolicy::Preserve => String::new(),
615                            });
616                        // History has to spell a tool the way its definition
617                        // does, or the transcript teaches the model a name the
618                        // upstream was never offered.
619                        let name = item
620                            .get("name")
621                            .and_then(Value::as_str)
622                            .unwrap_or_default()
623                            .to_string();
624                        let name = match item
625                            .get("namespace")
626                            .and_then(Value::as_str)
627                            .filter(|namespace| !namespace.is_empty())
628                        {
629                            Some(namespace) => {
630                                crate::codex_namespaces::qualified_tool_name(namespace, &name)
631                            }
632                            None => name,
633                        };
634                        pending_tool_calls.push(ToolCall {
635                            id,
636                            name,
637                            arguments: item.get("arguments").cloned().unwrap_or_else(|| json!({})),
638                        });
639                    }
640                    kind @ (Some("function_call_output") | Some("custom_tool_call_output")) => {
641                        let tool_call_id = item
642                            .get("call_id")
643                            .and_then(Value::as_str)
644                            .unwrap_or_default()
645                            .to_string();
646                        // A structured output keeps its typed text, image, and file parts;
647                        // any other shape rides through as one text block.
648                        let content = match item.get("output") {
649                            Some(output @ Value::Array(_)) => decode_responses_content(output),
650                            output => vec![ContentBlock::Text {
651                                text: output.map(json_string).unwrap_or_default(),
652                            }],
653                        };
654                        // An output whose call is not in this body answers a call the provider
655                        // holds behind `previous_response_id`; it stays a tool result so routing
656                        // sees a tool continuation, not a new user turn. Without stored state
657                        // the request is malformed, and the output becomes readable user text.
658                        let answers_pending_call = pending_tool_calls
659                            .iter()
660                            .any(|call| call.id == tool_call_id);
661                        if !answers_pending_call && !stored_state {
662                            let output_text = text_from_blocks(&content, " ");
663                            let message = Message::text(
664                                Role::User,
665                                format!("Tool result {tool_call_id}: {output_text}"),
666                            );
667                            push_responses_non_tool_message(
668                                &mut messages,
669                                &mut pending_tool_calls,
670                                &mut pending_tool_outputs,
671                                &mut deferred_messages,
672                                &mut pending_reasoning,
673                                message,
674                            );
675                            continue;
676                        }
677                        // The encoder types an output by the call it answers; a stored custom
678                        // output has no call in this body, so its type is carried separately.
679                        if !answers_pending_call && kind == Some("custom_tool_call_output") {
680                            custom_call_outputs.push(tool_call_id.clone());
681                        }
682                        pending_tool_outputs.push(ToolResult {
683                            tool_call_id,
684                            content,
685                            is_error: None,
686                        });
687                    }
688                    Some("custom_tool_call") => {
689                        // A freeform call carries a raw `input` string; it rides through the IR
690                        // as the single `input` argument of a function-style call.
691                        if !pending_tool_outputs.is_empty() {
692                            flush_responses_tool_block(
693                                &mut messages,
694                                &mut pending_tool_calls,
695                                &mut pending_tool_outputs,
696                                &mut deferred_messages,
697                                &mut pending_reasoning,
698                            );
699                        }
700                        let id = item
701                            .get("call_id")
702                            .and_then(Value::as_str)
703                            .filter(|id| !id.is_empty())
704                            .map(ToOwned::to_owned)
705                            .unwrap_or_else(|| match &policy.deterministic_ids {
706                                DeterministicIdPolicy::GenerateStable { prefix } => {
707                                    stable_id(prefix, index + 1)
708                                }
709                                DeterministicIdPolicy::Preserve => String::new(),
710                            });
711                        let name = item
712                            .get("name")
713                            .and_then(Value::as_str)
714                            .unwrap_or_default()
715                            .to_string();
716                        let input = item
717                            .get("input")
718                            .and_then(Value::as_str)
719                            .unwrap_or_default()
720                            .to_string();
721                        pending_tool_calls.push(ToolCall {
722                            id,
723                            name,
724                            arguments: json!({crate::codex_custom_tools::INPUT_ARGUMENT: input}),
725                        });
726                    }
727                    None => {
728                        return Err(TranslationError::InvalidValue {
729                            path: format!("$.input[{index}].type"),
730                            message: "missing type discriminator on a non-message input item"
731                                .to_string(),
732                        });
733                    }
734                    // Tool definitions, not conversation; decoded separately by the request
735                    // decoder and re-emitted in place by the request encoder.
736                    Some("additional_tools") => {}
737                    _ => {
738                        let message = Message::new(
739                            match item_type {
740                                Some(
741                                    "shell_call"
742                                    | "apply_patch_call"
743                                    | "computer_call"
744                                    | "image_generation_call",
745                                ) => Role::Assistant,
746                                Some(
747                                    "shell_call_output"
748                                    | "apply_patch_call_output"
749                                    | "computer_call_output",
750                                ) => Role::Tool,
751                                _ => Role::User,
752                            },
753                            vec![ContentBlock::Unknown {
754                                provider: WireFormat::OpenAiResponses.into(),
755                                raw: Value::Object(item.clone()),
756                            }],
757                        );
758                        flush_unattached_responses_reasoning(
759                            &mut messages,
760                            &mut pending_tool_calls,
761                            &mut pending_tool_outputs,
762                            &mut deferred_messages,
763                            &mut pending_reasoning,
764                        );
765                        push_responses_non_tool_message(
766                            &mut messages,
767                            &mut pending_tool_calls,
768                            &mut pending_tool_outputs,
769                            &mut deferred_messages,
770                            &mut pending_reasoning,
771                            message,
772                        );
773                    }
774                }
775            }
776            if !pending_tool_calls.is_empty() || !pending_tool_outputs.is_empty() {
777                flush_responses_tool_block(
778                    &mut messages,
779                    &mut pending_tool_calls,
780                    &mut pending_tool_outputs,
781                    &mut deferred_messages,
782                    &mut pending_reasoning,
783                );
784            }
785            // Trailing reasoning with no assistant turn to join keeps the
786            // historical standalone-message shape.
787            if !pending_reasoning.is_empty() {
788                messages.push(Message::new(Role::Assistant, pending_reasoning));
789            }
790            messages.append(&mut deferred_messages);
791            Ok(messages)
792        }
793        _ => Err(TranslationError::InvalidType {
794            path: "$.input".to_string(),
795            expected: "string or array",
796        }),
797    }
798}
799
800/// Places non-tool input items without breaking Responses tool-call adjacency.
801fn push_responses_non_tool_message(
802    messages: &mut Vec<Message>,
803    pending_tool_calls: &mut Vec<ToolCall>,
804    pending_tool_outputs: &mut Vec<ToolResult>,
805    deferred_messages: &mut Vec<Message>,
806    pending_reasoning: &mut Vec<ContentBlock>,
807    message: Message,
808) {
809    if !pending_tool_calls.is_empty() && pending_tool_outputs.is_empty() {
810        deferred_messages.push(message);
811        return;
812    }
813    if !pending_tool_calls.is_empty() || !pending_tool_outputs.is_empty() {
814        flush_responses_tool_block(
815            messages,
816            pending_tool_calls,
817            pending_tool_outputs,
818            deferred_messages,
819            pending_reasoning,
820        );
821    }
822    messages.push(message);
823}
824
825/// Emits reasoning that cannot join an assistant turn as a standalone assistant
826/// message at its original position. While tool calls are pending, the
827/// reasoning belongs to the in-flight turn and stays pending for the flush.
828fn flush_unattached_responses_reasoning(
829    messages: &mut Vec<Message>,
830    pending_tool_calls: &mut Vec<ToolCall>,
831    pending_tool_outputs: &mut Vec<ToolResult>,
832    deferred_messages: &mut Vec<Message>,
833    pending_reasoning: &mut Vec<ContentBlock>,
834) {
835    if pending_reasoning.is_empty() || !pending_tool_calls.is_empty() {
836        return;
837    }
838    let message = Message::new(Role::Assistant, std::mem::take(pending_reasoning));
839    push_responses_non_tool_message(
840        messages,
841        pending_tool_calls,
842        pending_tool_outputs,
843        deferred_messages,
844        pending_reasoning,
845        message,
846    );
847    // Instructions held behind the reasoning follow it.
848    messages.append(deferred_messages);
849}
850
851/// Flushes pending function calls and matching outputs while preserving adjacency.
852/// Pending reasoning rides in the same assistant message as the tool calls so a
853/// Codex reasoning + function_call turn stays one assistant turn downstream.
854fn flush_responses_tool_block(
855    messages: &mut Vec<Message>,
856    pending_tool_calls: &mut Vec<ToolCall>,
857    pending_tool_outputs: &mut Vec<ToolResult>,
858    deferred_messages: &mut Vec<Message>,
859    pending_reasoning: &mut Vec<ContentBlock>,
860) {
861    if !pending_tool_calls.is_empty() {
862        let mut content = std::mem::take(pending_reasoning);
863        content.extend(
864            std::mem::take(pending_tool_calls)
865                .into_iter()
866                .map(ContentBlock::ToolCall),
867        );
868        messages.push(Message::new(Role::Assistant, content));
869    }
870
871    for output in std::mem::take(pending_tool_outputs) {
872        messages.push(Message::new(
873            Role::User,
874            vec![ContentBlock::ToolResult(output)],
875        ));
876    }
877
878    messages.append(deferred_messages);
879}
880
881// Decodes a Responses reasoning item into private reasoning IR content.
882fn decode_responses_reasoning_item(item: &Map<String, Value>) -> Vec<ContentBlock> {
883    if let Some((text, signature)) = item
884        .get("encrypted_content")
885        .and_then(Value::as_str)
886        .and_then(super::decode_anthropic_thinking)
887    {
888        return vec![ContentBlock::Reasoning {
889            text,
890            signature: Some(signature),
891            details: Vec::new(),
892        }];
893    }
894    let mut parts = Vec::new();
895    collect_responses_reasoning_text(item.get("content"), &mut parts);
896    collect_responses_reasoning_text(item.get("summary"), &mut parts);
897    if let Some(text) = item.get("text").and_then(Value::as_str) {
898        parts.push(text.to_string());
899    }
900    // Encrypted reasoning must be replayed under the provider-issued item id;
901    // retain the original item only when it carries that opaque payload.
902    let details = if item.get("encrypted_content").is_some() {
903        vec![Value::Object(item.clone())]
904    } else {
905        Vec::new()
906    };
907    vec![ContentBlock::Reasoning {
908        text: parts.join("\n"),
909        signature: None,
910        details,
911    }]
912}
913
914// Decodes Responses content arrays or strings into normalized content blocks.
915fn decode_responses_content(value: &Value) -> Vec<ContentBlock> {
916    match value {
917        Value::String(text) => vec![ContentBlock::Text { text: text.clone() }],
918        Value::Array(blocks) => {
919            let mut out = Vec::new();
920            for block in blocks {
921                let Some(block) = block.as_object() else {
922                    continue;
923                };
924                match block.get("type").and_then(Value::as_str) {
925                    Some("input_text") | Some("output_text") | Some("text") => {
926                        out.push(ContentBlock::Text {
927                            text: block
928                                .get("text")
929                                .and_then(Value::as_str)
930                                .unwrap_or_default()
931                                .to_string(),
932                        });
933                    }
934                    Some("refusal") => out.push(ContentBlock::Refusal {
935                        text: block
936                            .get("refusal")
937                            .and_then(Value::as_str)
938                            .unwrap_or_default()
939                            .to_string(),
940                    }),
941                    Some("reasoning_text") | Some("summary_text") => {
942                        out.push(ContentBlock::Reasoning {
943                            text: block
944                                .get("text")
945                                .and_then(Value::as_str)
946                                .unwrap_or_default()
947                                .to_string(),
948                            signature: None,
949                            details: Vec::new(),
950                        });
951                    }
952                    Some("input_image") => {
953                        if let Some(source) = decode_image_source(block) {
954                            out.push(ContentBlock::Image { source });
955                        }
956                    }
957                    Some("input_audio") => out.push(ContentBlock::Audio {
958                        source: MediaSource::Raw(Value::Object(block.clone())),
959                    }),
960                    Some("input_file") => out.push(ContentBlock::File {
961                        source: decode_file_source(block),
962                    }),
963                    _ => out.push(ContentBlock::Unknown {
964                        provider: WireFormat::OpenAiResponses.into(),
965                        raw: Value::Object(block.clone()),
966                    }),
967                }
968            }
969            if out.is_empty() {
970                out.push(ContentBlock::Text {
971                    text: String::new(),
972                });
973            }
974            out
975        }
976        Value::Null => vec![ContentBlock::Text {
977            text: String::new(),
978        }],
979        other => vec![ContentBlock::Text {
980            text: string_value(other).unwrap_or_default(),
981        }],
982    }
983}
984
985// Decodes Responses role strings into normalized roles. Used for decoding
986// provider *responses*, which stay lenient — an unexpected role from upstream
987// is coerced to `user` rather than failing the whole response.
988fn role_from_responses(role: Option<&str>) -> Role {
989    match role {
990        Some("assistant") => Role::Assistant,
991        Some("system") => Role::System,
992        Some("developer") => Role::Developer,
993        _ => Role::User,
994    }
995}
996
997// Decodes a Responses *request* message role, enforcing the provider contract.
998//
999// Unlike `role_from_responses` (used for provider responses), request decoding
1000// rejects an unknown role such as "api" with [`TranslationError::InvalidValue`]
1001// so the router surfaces the same `invalid_value` error the provider would,
1002// instead of silently coercing it to `user`. A missing role and
1003// known-but-unmapped roles keep their historical mapping to `user`.
1004fn request_role_from_responses(role: Option<&str>, path: &str) -> Result<Role> {
1005    match role {
1006        Some("assistant") => Ok(Role::Assistant),
1007        Some("system") => Ok(Role::System),
1008        Some("developer") => Ok(Role::Developer),
1009        None => Ok(Role::User),
1010        Some(other) if is_known_role_name(other) => Ok(Role::User),
1011        Some(other) => Err(TranslationError::unsupported_role(path, other)),
1012    }
1013}
1014
1015// Decodes Responses tool shapes, including Codex-style tool entries.
1016// Decodes Responses tool shapes, including Codex-style tool entries.
1017//
1018// Codex groups tools into non-standard ``namespace`` containers that
1019// OpenAI-compatible upstreams do not accept. Each child is exposed under a
1020// `<namespace>__<tool>` name, and `namespaces` records the mapping so the
1021// response can split it back apart.
1022fn decode_responses_tools(
1023    value: Option<&Value>,
1024    namespaces: &mut Map<String, Value>,
1025    custom_tools: &mut Map<String, Value>,
1026) -> Vec<ToolDefinition> {
1027    let Some(tools) = value.and_then(Value::as_array) else {
1028        return Vec::new();
1029    };
1030    let mut out = Vec::new();
1031    for tool in tools {
1032        let Some(tool) = tool.as_object() else {
1033            continue;
1034        };
1035        if tool.get("type").and_then(Value::as_str) == Some("namespace") {
1036            // An unnamed container carries nothing to dispatch on, so its
1037            // children stay bare rather than gaining an empty prefix.
1038            let container = tool
1039                .get("name")
1040                .and_then(Value::as_str)
1041                .filter(|name| !name.is_empty());
1042            let description = tool.get("description").and_then(Value::as_str);
1043            for mut child in decode_responses_tools(tool.get("tools"), namespaces, custom_tools) {
1044                // A nested container already qualified its own children, and the
1045                // innermost name is the one that identifies the tool.
1046                let already_qualified = namespaces.contains_key(&child.name);
1047                if let Some(container) = container
1048                    && !already_qualified
1049                {
1050                    let qualified =
1051                        crate::codex_namespaces::qualified_tool_name(container, &child.name);
1052                    crate::codex_namespaces::record_tool_namespace(
1053                        namespaces,
1054                        &qualified,
1055                        container,
1056                        description,
1057                    );
1058                    child.name = qualified;
1059                }
1060                out.push(child);
1061            }
1062        } else if tool.get("type").and_then(Value::as_str) == Some("custom") {
1063            // A freeform tool takes a raw string, not JSON arguments. The IR sees it as a
1064            // function with a single `input` argument; the verbatim definition is kept so a
1065            // Responses upstream still receives the freeform tool. The definition is keyed by
1066            // the tool's own name: Codex defines its freeform tools at the top level, so a
1067            // custom tool nested in a namespace container (which would be renamed above) is
1068            // not restored verbatim and goes upstream as the equivalent function tool.
1069            if let Some(name) = tool
1070                .get("name")
1071                .and_then(Value::as_str)
1072                .filter(|name| !name.is_empty())
1073            {
1074                custom_tools.insert(name.to_string(), Value::Object(tool.clone()));
1075                out.push(ToolDefinition {
1076                    name: name.to_string(),
1077                    description: tool
1078                        .get("description")
1079                        .and_then(Value::as_str)
1080                        .map(ToOwned::to_owned),
1081                    parameters: crate::codex_custom_tools::input_schema(),
1082                    strict: None,
1083                });
1084            }
1085        } else if tool.get("type").and_then(Value::as_str) == Some("function") {
1086            if let Some(function) = tool.get("function").and_then(Value::as_object) {
1087                if let Some(name) = function.get("name").and_then(Value::as_str)
1088                    && !name.is_empty()
1089                {
1090                    out.push(ToolDefinition {
1091                        name: name.to_string(),
1092                        description: function
1093                            .get("description")
1094                            .and_then(Value::as_str)
1095                            .map(ToOwned::to_owned),
1096                        parameters: function
1097                            .get("parameters")
1098                            .cloned()
1099                            .unwrap_or_else(|| json!({})),
1100                        strict: function.get("strict").and_then(Value::as_bool),
1101                    });
1102                }
1103            } else {
1104                if !push_responses_function_tool(&mut out, tool) {
1105                    push_responses_id_tool(&mut out, tool);
1106                }
1107            }
1108        } else if tool.get("type").is_none() && tool.contains_key("name") {
1109            push_responses_function_tool(&mut out, tool);
1110        } else {
1111            push_responses_id_tool(&mut out, tool);
1112        }
1113    }
1114    out
1115}
1116
1117// Adds an OpenAI-style function tool to the normalized tool list.
1118fn push_responses_function_tool(
1119    out: &mut Vec<ToolDefinition>,
1120    tool: &serde_json::Map<String, Value>,
1121) -> bool {
1122    let Some(name) = tool.get("name").and_then(Value::as_str) else {
1123        return false;
1124    };
1125    if name.is_empty() {
1126        return false;
1127    }
1128
1129    out.push(ToolDefinition {
1130        name: name.to_string(),
1131        description: tool
1132            .get("description")
1133            .and_then(Value::as_str)
1134            .map(ToOwned::to_owned),
1135        parameters: tool.get("parameters").cloned().unwrap_or_else(|| json!({})),
1136        strict: tool.get("strict").and_then(Value::as_bool),
1137    });
1138    true
1139}
1140
1141// Adds a Codex-style ID tool to the normalized tool list.
1142fn push_responses_id_tool(
1143    out: &mut Vec<ToolDefinition>,
1144    tool: &serde_json::Map<String, Value>,
1145) -> bool {
1146    let Some(id) = tool.get("id").and_then(Value::as_str) else {
1147        return false;
1148    };
1149    if id.is_empty() {
1150        return false;
1151    }
1152
1153    out.push(ToolDefinition {
1154        name: id.to_string(),
1155        description: tool
1156            .get("description")
1157            .and_then(Value::as_str)
1158            .map(ToOwned::to_owned),
1159        parameters: tool
1160            .get("inputSchema")
1161            .and_then(Value::as_object)
1162            .and_then(|schema| schema.get("jsonSchema"))
1163            .cloned()
1164            .unwrap_or_else(|| json!({})),
1165        strict: None,
1166    });
1167    true
1168}
1169
1170// Decodes Responses tool-choice values into normalized policy.
1171fn decode_responses_tool_choice(value: &Value) -> Option<ToolChoice> {
1172    match value {
1173        Value::String(text) if text == "auto" => Some(ToolChoice::Auto),
1174        Value::String(text) if text == "required" => Some(ToolChoice::Required),
1175        Value::String(text) if text == "none" => Some(ToolChoice::None),
1176        Value::Object(object) if object.get("type").and_then(Value::as_str) == Some("custom") => {
1177            object
1178                .get("name")
1179                .and_then(Value::as_str)
1180                .map(|name| ToolChoice::Tool {
1181                    name: name.to_string(),
1182                })
1183        }
1184        Value::Object(object) if object.get("type").and_then(Value::as_str) == Some("function") => {
1185            // A forced tool has to name the same thing its definition does, or
1186            // the upstream rejects a choice naming a tool it was never offered.
1187            object.get("name").and_then(Value::as_str).map(|name| {
1188                match object
1189                    .get("namespace")
1190                    .and_then(Value::as_str)
1191                    .filter(|namespace| !namespace.is_empty())
1192                {
1193                    Some(namespace) => ToolChoice::Tool {
1194                        name: crate::codex_namespaces::qualified_tool_name(namespace, name),
1195                    },
1196                    None => ToolChoice::Tool {
1197                        name: name.to_string(),
1198                    },
1199                }
1200            })
1201        }
1202        Value::Object(object)
1203            if object.get("type").and_then(Value::as_str) == Some("allowed_tools") =>
1204        {
1205            Some(ToolChoice::Raw(value.clone()))
1206        }
1207        Value::Object(_) => None,
1208        _ => Some(ToolChoice::Raw(value.clone())),
1209    }
1210}
1211
1212// Maps Responses text format options into Chat-compatible response_format JSON.
1213fn decode_responses_text_format(value: Option<&Value>) -> Option<Value> {
1214    let format = value
1215        .and_then(Value::as_object)
1216        .and_then(|object| object.get("format"))
1217        .and_then(Value::as_object)?;
1218
1219    match format.get("type").and_then(Value::as_str) {
1220        Some("json_schema") => {
1221            if let Some(json_schema) = format.get("json_schema").and_then(Value::as_object) {
1222                return Some(json!({
1223                    "type": "json_schema",
1224                    "json_schema": Value::Object(json_schema.clone()),
1225                }));
1226            }
1227
1228            let mut json_schema = Map::new();
1229            for field in ["name", "description", "schema", "strict"] {
1230                if let Some(value) = format.get(field) {
1231                    json_schema.insert(field.to_string(), value.clone());
1232                }
1233            }
1234            (!json_schema.is_empty()).then_some(json!({
1235                "type": "json_schema",
1236                "json_schema": Value::Object(json_schema),
1237            }))
1238        }
1239        Some("json_object") => Some(json!({"type": "json_object"})),
1240        Some("text") => Some(json!({"type": "text"})),
1241        _ => None,
1242    }
1243}
1244
1245// Flattens Chat-compatible JSON schema fields into the Responses text format shape.
1246fn encode_responses_text_format(response_format: &Value) -> Value {
1247    let Some(format) = response_format.as_object() else {
1248        return response_format.clone();
1249    };
1250    let Some(response_type) = format
1251        .get("type")
1252        .filter(|value| value.as_str() == Some("json_schema"))
1253    else {
1254        return response_format.clone();
1255    };
1256
1257    let Some(Value::Object(json_schema)) = format.get("json_schema") else {
1258        return response_format.clone();
1259    };
1260    if !matches!(json_schema.get("name"), Some(Value::String(_)))
1261        || !matches!(json_schema.get("schema"), Some(Value::Object(_)))
1262        || json_schema
1263            .get("description")
1264            .is_some_and(|value| !value.is_string())
1265        || json_schema
1266            .get("strict")
1267            .is_some_and(|value| !value.is_boolean())
1268    {
1269        return response_format.clone();
1270    }
1271
1272    let mut output = Map::new();
1273    output.insert("type".to_string(), response_type.clone());
1274    for field in ["name", "description", "schema", "strict"] {
1275        if let Some(value) = json_schema.get(field) {
1276            output.insert(field.to_string(), value.clone());
1277        }
1278    }
1279    Value::Object(output)
1280}
1281
1282// Encodes normalized messages into the Responses `input` shape.
1283fn encode_responses_input(
1284    messages: &[Message],
1285    diagnostics: &mut Vec<TranslationDiagnostic>,
1286    policy: &TranslationPolicy,
1287    namespaces: Option<&Map<String, Value>>,
1288    custom_tools: &std::collections::HashSet<String>,
1289    mut custom_call_ids: std::collections::HashSet<String>,
1290) -> Result<Value> {
1291    // Call ids of freeform tool calls emitted by this pass, seeded with the ids of stored-state
1292    // custom outputs. A tool result is typed by the call it answers, and Responses history
1293    // always lists the call before its output, so recording ids as calls are encoded is enough
1294    // to type the outputs that follow.
1295    //
1296    // A lone user text is still sent as an item list: the Codex backend rejects a string `input`.
1297    let mut encoded = Vec::new();
1298    // Some upstream translators (Kimi K3) resolve a tool output by an explicit
1299    // `name`, so pair every output with the name of the call it answers.
1300    let mut call_names: HashMap<&str, &str> = HashMap::new();
1301    for message in messages {
1302        for block in &message.content {
1303            if let ContentBlock::ToolCall(call) = block {
1304                call_names.insert(call.id.as_str(), call.name.as_str());
1305            }
1306        }
1307    }
1308    for message in messages {
1309        // The decoder carries each native top-level input item as one
1310        // provider-qualified block, so replay that block in place.
1311        if let [ContentBlock::Unknown { provider, raw }] = message.content.as_slice()
1312            && provider.as_str() == WireFormat::OpenAiResponses.as_str()
1313            && is_responses_native_input_item(raw)
1314        {
1315            encoded.push(raw.clone());
1316            continue;
1317        }
1318        // Anthropic-signed thinking cannot be sent as Responses input.
1319        let content = message
1320            .content
1321            .iter()
1322            .filter(|block| {
1323                !matches!(
1324                    block,
1325                    ContentBlock::Reasoning {
1326                        signature: Some(_),
1327                        ..
1328                    }
1329                )
1330            })
1331            .cloned()
1332            .collect::<Vec<_>>();
1333        if content.is_empty() {
1334            continue;
1335        }
1336        if content.iter().any(|block| {
1337            matches!(
1338                block,
1339                ContentBlock::ToolCall(_) | ContentBlock::ToolResult(_)
1340            )
1341        }) {
1342            let mut visible_content = Vec::new();
1343            for block in &content {
1344                if let Some(item) = encode_responses_special_input(
1345                    block,
1346                    namespaces,
1347                    &call_names,
1348                    custom_tools,
1349                    &mut custom_call_ids,
1350                    diagnostics,
1351                    policy,
1352                )? {
1353                    if !visible_content.is_empty() {
1354                        let content =
1355                            encode_responses_content(&visible_content, diagnostics, policy)?;
1356                        encoded.push(encode_responses_message(message, content));
1357                        visible_content.clear();
1358                    }
1359                    encoded.push(item);
1360                } else if !matches!(block, ContentBlock::Reasoning { .. }) {
1361                    visible_content.push(block.clone());
1362                }
1363            }
1364            if !visible_content.is_empty() {
1365                let content = encode_responses_content(&visible_content, diagnostics, policy)?;
1366                encoded.push(encode_responses_message(message, content));
1367            }
1368            continue;
1369        }
1370        let mut visible_content = Vec::new();
1371        let mut emitted_special = false;
1372        let mut omitted_reasoning = false;
1373        for block in &content {
1374            if let Some(item) = encode_responses_special_input(
1375                block,
1376                namespaces,
1377                &call_names,
1378                custom_tools,
1379                &mut custom_call_ids,
1380                diagnostics,
1381                policy,
1382            )? {
1383                encoded.push(item);
1384                emitted_special = true;
1385            } else if !matches!(block, ContentBlock::Reasoning { .. }) {
1386                visible_content.push(block.clone());
1387            } else {
1388                omitted_reasoning = true;
1389            }
1390        }
1391        if !visible_content.is_empty()
1392            || (!emitted_special && !omitted_reasoning)
1393            || (message.role == Role::Assistant && message.phase.is_some())
1394        {
1395            let content = encode_responses_content(&visible_content, diagnostics, policy)?;
1396            encoded.push(encode_responses_message(message, content));
1397        }
1398    }
1399    pair_tool_calls_with_outputs(&mut encoded);
1400    Ok(Value::Array(encoded))
1401}
1402
1403// Responses defines `phase` only on assistant message items, so drop it elsewhere.
1404fn encode_responses_message(message: &Message, content: Value) -> Value {
1405    let mut item = json!({
1406        "type": "message",
1407        "role": role_to_responses(message.role),
1408        "content": content,
1409    });
1410    if let (Role::Assistant, Some(phase)) = (message.role, &message.phase) {
1411        item["phase"] = json!(phase);
1412    }
1413    item
1414}
1415
1416// Moves each tool output directly behind the call it answers. A turn with
1417// parallel tool calls otherwise serializes as call,call,output,output, which
1418// upstreams that pair by adjacency (Kimi K3) resolve to the wrong call.
1419fn pair_tool_calls_with_outputs(items: &mut Vec<Value>) {
1420    let call_id = |item: &Value, kind: &str| {
1421        (item.get("type").and_then(Value::as_str) == Some(kind))
1422            .then(|| {
1423                item.get("call_id")
1424                    .and_then(Value::as_str)
1425                    .map(str::to_owned)
1426            })
1427            .flatten()
1428    };
1429    let mut index = 0;
1430    while index < items.len() {
1431        // Freeform (`custom`) calls pair with `custom_tool_call_output` the same way.
1432        let (id, output_kind) = match call_id(&items[index], "function_call") {
1433            Some(id) => (id, "function_call_output"),
1434            None => match call_id(&items[index], "custom_tool_call") {
1435                Some(id) => (id, "custom_tool_call_output"),
1436                None => {
1437                    index += 1;
1438                    continue;
1439                }
1440            },
1441        };
1442        let output = items
1443            .iter()
1444            .skip(index + 1)
1445            .take_while(|item| item.get("type").and_then(Value::as_str) != Some("message"))
1446            .position(|item| call_id(item, output_kind).as_deref() == Some(&id))
1447            .map(|offset| index + 1 + offset);
1448        if let Some(output) = output
1449            && output != index + 1
1450        {
1451            let item = items.remove(output);
1452            items.insert(index + 1, item);
1453        }
1454        index += 1;
1455    }
1456}
1457
1458// Encodes IR blocks that Responses represents as top-level input items.
1459fn encode_responses_special_input(
1460    block: &ContentBlock,
1461    namespaces: Option<&Map<String, Value>>,
1462    call_names: &HashMap<&str, &str>,
1463    custom_tools: &std::collections::HashSet<String>,
1464    custom_call_ids: &mut std::collections::HashSet<String>,
1465    diagnostics: &mut Vec<TranslationDiagnostic>,
1466    policy: &TranslationPolicy,
1467) -> Result<Option<Value>> {
1468    Ok(match block {
1469        ContentBlock::Reasoning {
1470            text,
1471            signature: None,
1472            details,
1473        } => encode_responses_reasoning_input(text, details),
1474        ContentBlock::ToolCall(call) if custom_tools.contains(&call.name) => {
1475            // A freeform tool call replays as `custom_tool_call` with its raw input.
1476            custom_call_ids.insert(call.id.clone());
1477            Some(json!({
1478                "type": "custom_tool_call",
1479                "call_id": call.id,
1480                "name": call.name,
1481                "input": crate::codex_custom_tools::input_from_arguments(&call.arguments),
1482            }))
1483        }
1484        ContentBlock::ToolCall(call) => {
1485            // A Responses client dispatches on name plus namespace, so undo the
1486            // qualification this request applied for a flat upstream.
1487            let (name, namespace) = namespaces
1488                .and_then(|namespaces| {
1489                    crate::codex_namespaces::split_qualified_name(namespaces, &call.name)
1490                })
1491                .map_or((call.name.as_str(), None), |(name, namespace)| {
1492                    (name, Some(namespace))
1493                });
1494            let mut item = json!({
1495                "type": "function_call",
1496                "call_id": call.id,
1497                "name": name,
1498                "arguments": json_string(&call.arguments),
1499            });
1500            if let Some(namespace) = namespace {
1501                item["namespace"] = Value::String(namespace.to_string());
1502            }
1503            Some(item)
1504        }
1505        ContentBlock::ToolResult(result) => {
1506            // A result answering a freeform call replays as `custom_tool_call_output`; anything
1507            // else is a `function_call_output`.
1508            let mut item = json!({
1509                "type": if custom_call_ids.contains(&result.tool_call_id) {
1510                    "custom_tool_call_output"
1511                } else {
1512                    "function_call_output"
1513                },
1514                "call_id": result.tool_call_id,
1515                "output": encode_responses_tool_output(&result.content, diagnostics, policy)?,
1516            });
1517            // Carry the paired call's name, un-qualified to match the emitted
1518            // function_call, for upstreams that resolve outputs by name.
1519            if let Some(name) = call_names.get(result.tool_call_id.as_str()) {
1520                let name = namespaces
1521                    .and_then(|namespaces| {
1522                        crate::codex_namespaces::split_qualified_name(namespaces, name)
1523                    })
1524                    .map_or(*name, |(name, _)| name);
1525                item["name"] = Value::String(name.to_string());
1526            }
1527            Some(item)
1528        }
1529        _ => None,
1530    })
1531}
1532
1533// Encodes reasoning in the shape accepted for Responses input history. Response
1534// output items may carry `content`, but replayed input items must avoid it.
1535fn encode_responses_reasoning_input(text: &str, details: &[Value]) -> Option<Value> {
1536    for detail in details {
1537        let Some(detail) = detail.as_object() else {
1538            continue;
1539        };
1540        if detail.get("type").and_then(Value::as_str) != Some("reasoning") {
1541            continue;
1542        }
1543        let mut item = Map::new();
1544        item.insert("type".to_string(), Value::String("reasoning".to_string()));
1545        for field in ["id", "summary", "encrypted_content"] {
1546            if let Some(value) = detail.get(field) {
1547                item.insert(field.to_string(), value.clone());
1548            }
1549        }
1550        item.entry("summary".to_string())
1551            .or_insert_with(|| Value::Array(Vec::new()));
1552        return Some(Value::Object(item));
1553    }
1554
1555    if text.is_empty() {
1556        return None;
1557    }
1558    Some(json!({
1559        "type": "reasoning",
1560        "summary": [{"type": "summary_text", "text": text}],
1561    }))
1562}
1563
1564// Maps normalized roles back to Responses role strings.
1565fn role_to_responses(role: Role) -> &'static str {
1566    match role {
1567        Role::Assistant => "assistant",
1568        Role::System => "system",
1569        Role::Developer => "developer",
1570        Role::User | Role::Tool => "user",
1571    }
1572}
1573
1574// Encodes normalized content into Responses message content.
1575fn encode_responses_content(
1576    content: &[ContentBlock],
1577    diagnostics: &mut Vec<TranslationDiagnostic>,
1578    policy: &TranslationPolicy,
1579) -> Result<Value> {
1580    let has_non_text = content.iter().any(|block| {
1581        !matches!(
1582            block,
1583            ContentBlock::Text { .. }
1584                | ContentBlock::Refusal { .. }
1585                | ContentBlock::Reasoning { .. }
1586        )
1587    });
1588    if !has_non_text {
1589        return Ok(Value::String(text_from_blocks(content, "\n")));
1590    }
1591    let mut blocks = Vec::new();
1592    for block in content {
1593        match block {
1594            ContentBlock::Text { text } => blocks.push(json!({"type": "input_text", "text": text})),
1595            ContentBlock::Refusal { text } => {
1596                blocks.push(json!({"type": "refusal", "refusal": text}));
1597            }
1598            ContentBlock::Image { source } => match responses_image_part(source) {
1599                Some(part) => blocks.push(part),
1600                None => {
1601                    push_lossy(
1602                        diagnostics,
1603                        policy,
1604                        "Responses codec could not map image content",
1605                    )?;
1606                    blocks.push(json!({"type": "input_text", "text": image_source_text(source)}));
1607                }
1608            },
1609            ContentBlock::Audio { source } => {
1610                blocks.push(crate::codecs::openai_media::audio_part(source)?);
1611            }
1612            ContentBlock::Video { source } => blocks.push(match source {
1613                MediaSource::Raw(raw) => json!({"type": "input_text", "text": json_string(raw)}),
1614                MediaSource::Url { url, media_type } => json!({
1615                    "type": "input_video",
1616                    "video_url": url,
1617                    "media_type": media_type,
1618                }),
1619                MediaSource::Base64 { media_type, data } => json!({
1620                    "type": "input_video",
1621                    "video": {"media_type": media_type, "data": data},
1622                }),
1623            }),
1624            ContentBlock::File { source } => match responses_file_part(source) {
1625                Some(part) => blocks.push(part),
1626                None => {
1627                    push_lossy(
1628                        diagnostics,
1629                        policy,
1630                        "Responses codec could not map file content",
1631                    )?;
1632                    blocks.push(json!({"type": "input_text", "text": file_source_text(source)}));
1633                }
1634            },
1635            ContentBlock::Mcp(_) => {
1636                return Err(TranslationError::LossyConversion(
1637                    "MCP history encoding is not implemented".into(),
1638                ));
1639            }
1640            ContentBlock::Unknown { raw, .. } => {
1641                push_lossy(
1642                    diagnostics,
1643                    policy,
1644                    "unknown content block encoded as text for Responses",
1645                )?;
1646                blocks.push(json!({"type": "input_text", "text": json_string(raw)}));
1647            }
1648            ContentBlock::Reasoning { .. }
1649            | ContentBlock::ToolCall(_)
1650            | ContentBlock::ToolResult(_) => {}
1651        }
1652    }
1653    Ok(Value::Array(blocks))
1654}
1655
1656// Encodes tool-result content as a `function_call_output.output`: a string when it is
1657// text only, otherwise the typed `input_text` / `input_image` / `input_file` parts.
1658fn encode_responses_tool_output(
1659    content: &[ContentBlock],
1660    diagnostics: &mut Vec<TranslationDiagnostic>,
1661    policy: &TranslationPolicy,
1662) -> Result<Value> {
1663    let text_only = content.iter().all(|block| {
1664        matches!(
1665            block,
1666            ContentBlock::Text { .. } | ContentBlock::Refusal { .. }
1667        )
1668    });
1669    if text_only {
1670        return Ok(Value::String(text_from_blocks(content, " ")));
1671    }
1672    encode_responses_content(content, diagnostics, policy)
1673}
1674
1675fn responses_image_part(source: &ImageSource) -> Option<Value> {
1676    if let ImageSource::Raw(raw) = source
1677        && raw.get("type").and_then(Value::as_str) == Some("input_image")
1678        && raw.get("file_id").and_then(Value::as_str).is_some()
1679    {
1680        return Some(raw.clone());
1681    }
1682    let ImagePayload { url, detail } = image_payload(source)?;
1683    let mut part = json!({"type": "input_image"});
1684    part["image_url"] = Value::String(url);
1685    if let Some(detail) = detail {
1686        part["detail"] = Value::String(detail);
1687    }
1688    Some(part)
1689}
1690
1691fn responses_file_part(source: &FileSource) -> Option<Value> {
1692    let mut part = file_payload(source)?;
1693    part.insert("type".to_string(), Value::String("input_file".to_string()));
1694    Some(Value::Object(part))
1695}
1696
1697// Encodes normalized tool definitions into Responses tool JSON.
1698// Encodes normalized tools as Responses entries.
1699//
1700// A Responses client understands Codex containers, so a tool whose name this
1701// request qualified is regrouped under the container it came from.
1702fn encode_responses_tools(
1703    tools: &[Tool],
1704    namespaces: Option<&Map<String, Value>>,
1705    custom_tools: Option<&Map<String, Value>>,
1706) -> Result<Value> {
1707    let mut out: Vec<Value> = Vec::new();
1708    let mut containers: Vec<(String, Vec<Value>)> = Vec::new();
1709    for tool in tools {
1710        let tool = tool.function().ok_or_else(|| {
1711            TranslationError::LossyConversion(
1712                "MCP and provider tool encoding is not implemented".into(),
1713            )
1714        })?;
1715        // A freeform tool goes back out exactly as the client defined it.
1716        if let Some(custom) = custom_tools.and_then(|custom| custom.get(&tool.name)) {
1717            out.push(custom.clone());
1718            continue;
1719        }
1720        let mut item = json!({
1721            "type": "function",
1722            "name": tool.name,
1723            "description": tool.description.clone().unwrap_or_default(),
1724            "parameters": tool.parameters,
1725        });
1726        if let Some(strict) = tool.strict {
1727            item["strict"] = Value::Bool(strict);
1728        }
1729        let split = namespaces.and_then(|namespaces| {
1730            crate::codex_namespaces::split_qualified_name(namespaces, &tool.name)
1731        });
1732        match split {
1733            None => out.push(item),
1734            Some((name, namespace)) => {
1735                item["name"] = Value::String(name.to_string());
1736                match containers
1737                    .iter_mut()
1738                    .find(|(existing, _)| *existing == namespace)
1739                {
1740                    Some((_, children)) => children.push(item),
1741                    None => containers.push((namespace.to_string(), vec![item])),
1742                }
1743            }
1744        }
1745    }
1746    for (namespace, children) in containers {
1747        let description = namespaces
1748            .and_then(|namespaces| {
1749                crate::codex_namespaces::namespace_description(namespaces, &namespace)
1750            })
1751            .unwrap_or_default();
1752        out.push(json!({
1753            "type": "namespace",
1754            "name": namespace,
1755            "description": description,
1756            "tools": children,
1757        }));
1758    }
1759    Ok(Value::Array(out))
1760}
1761
1762// Encodes normalized tool choice into Responses JSON.
1763fn encode_responses_tool_choice(
1764    choice: &ToolChoice,
1765    namespaces: Option<&Map<String, Value>>,
1766    custom_tools: Option<&Map<String, Value>>,
1767) -> Option<Value> {
1768    match choice {
1769        ToolChoice::Auto => Some(Value::String("auto".to_string())),
1770        ToolChoice::Required => Some(Value::String("required".to_string())),
1771        ToolChoice::None => Some(Value::String("none".to_string())),
1772        ToolChoice::Tool { name } if custom_tools.is_some_and(|tools| tools.contains_key(name)) => {
1773            Some(json!({"type": "custom", "name": name}))
1774        }
1775        ToolChoice::Tool { name } => {
1776            let split = namespaces.and_then(|namespaces| {
1777                crate::codex_namespaces::split_qualified_name(namespaces, name)
1778            });
1779            Some(match split {
1780                Some((tool, namespace)) => {
1781                    json!({"type": "function", "name": tool, "namespace": namespace})
1782                }
1783                None => json!({"type": "function", "name": name}),
1784            })
1785        }
1786        ToolChoice::Raw(value) => Some(value.clone()),
1787    }
1788}
1789
1790// Decodes one Responses output item into a normalized response output.
1791fn decode_responses_output_item(
1792    item: &Value,
1793    diagnostics: &mut Vec<TranslationDiagnostic>,
1794    policy: &TranslationPolicy,
1795) -> Result<Option<ResponseOutput>> {
1796    let Some(item) = item.as_object() else {
1797        push_lossy(
1798            diagnostics,
1799            policy,
1800            "Responses output item is not an object",
1801        )?;
1802        return Ok(None);
1803    };
1804    match item.get("type").and_then(Value::as_str) {
1805        Some("message") => Ok(Some(ResponseOutput {
1806            url_citations: decode_responses_url_citations(item.get("content")),
1807            role: role_from_responses(item.get("role").and_then(Value::as_str)),
1808            content: decode_responses_content(item.get("content").unwrap_or(&Value::Null)),
1809            stop_reason: Some(StopReason::EndTurn),
1810        })),
1811        Some("function_call") => Ok(Some(ResponseOutput {
1812            url_citations: Vec::new(),
1813            role: Role::Assistant,
1814            content: vec![ContentBlock::ToolCall(ToolCall {
1815                id: item
1816                    .get("call_id")
1817                    .and_then(Value::as_str)
1818                    .unwrap_or_default()
1819                    .to_string(),
1820                name: item
1821                    .get("name")
1822                    .and_then(Value::as_str)
1823                    .unwrap_or_default()
1824                    .to_string(),
1825                arguments: item
1826                    .get("arguments")
1827                    .map(|value| {
1828                        value
1829                            .as_str()
1830                            .and_then(|text| serde_json::from_str(text).ok())
1831                            .unwrap_or_else(|| value.clone())
1832                    })
1833                    .unwrap_or_else(|| json!({})),
1834            })],
1835            stop_reason: Some(StopReason::ToolUse),
1836        })),
1837        Some("custom_tool_call") => Ok(Some(ResponseOutput {
1838            url_citations: Vec::new(),
1839            role: Role::Assistant,
1840            content: vec![ContentBlock::ToolCall(ToolCall {
1841                id: item
1842                    .get("call_id")
1843                    .and_then(Value::as_str)
1844                    .unwrap_or_default()
1845                    .to_string(),
1846                name: item
1847                    .get("name")
1848                    .and_then(Value::as_str)
1849                    .unwrap_or_default()
1850                    .to_string(),
1851                arguments: json!({
1852                    crate::codex_custom_tools::INPUT_ARGUMENT:
1853                        item.get("input").and_then(Value::as_str).unwrap_or_default()
1854                }),
1855            })],
1856            stop_reason: Some(StopReason::ToolUse),
1857        })),
1858        Some("reasoning") => Ok(Some(ResponseOutput {
1859            url_citations: Vec::new(),
1860            role: Role::Assistant,
1861            content: decode_responses_reasoning_item(item),
1862            stop_reason: None,
1863        })),
1864        Some(kind) if super::is_native_output(kind) => Ok(Some(ResponseOutput {
1865            url_citations: Vec::new(),
1866            role: Role::Assistant,
1867            content: vec![ContentBlock::Unknown {
1868                provider: WireFormat::OpenAiResponses.into(),
1869                raw: Value::Object(item.clone()),
1870            }],
1871            stop_reason: None,
1872        })),
1873        _ => Ok(None),
1874    }
1875}
1876
1877fn decode_responses_url_citations(content: Option<&Value>) -> Vec<crate::UrlCitation> {
1878    let mut citations = Vec::new();
1879    let mut text_offset = 0;
1880    for part in content.and_then(Value::as_array).into_iter().flatten() {
1881        for annotation in part
1882            .get("annotations")
1883            .and_then(Value::as_array)
1884            .into_iter()
1885            .flatten()
1886        {
1887            if annotation["type"] == "url_citation"
1888                && let Ok(mut citation) =
1889                    serde_json::from_value::<crate::UrlCitation>(annotation.clone())
1890            {
1891                citation.start_index += text_offset;
1892                citation.end_index += text_offset;
1893                citations.push(citation);
1894            }
1895        }
1896        let text = match part.get("type").and_then(Value::as_str) {
1897            Some("input_text" | "output_text" | "text") => part.get("text"),
1898            Some("refusal") => part.get("refusal"),
1899            _ => None,
1900        };
1901        text_offset += text
1902            .and_then(Value::as_str)
1903            .unwrap_or_default()
1904            .chars()
1905            .count();
1906    }
1907    citations
1908}
1909
1910// Encodes normalized response outputs into Responses output items.
1911fn encode_responses_output(outputs: &[ResponseOutput]) -> Value {
1912    Value::Array(
1913        outputs
1914            .iter()
1915            .flat_map(|output| {
1916                let has_output_items = output.content.iter().any(|block| {
1917                    matches!(block, ContentBlock::ToolCall(_))
1918                        || matches!(block, ContentBlock::Unknown { provider, raw }
1919                            if provider.as_str() == WireFormat::OpenAiResponses.as_str()
1920                                && raw["type"].as_str().is_some_and(super::is_native_output))
1921                });
1922                let text = text_from_blocks(&output.content, "");
1923                let reasoning = reasoning_text_from_blocks(&output.content, "\n");
1924                let status = if matches!(output.stop_reason, Some(StopReason::MaxTokens)) {
1925                    "incomplete"
1926                } else {
1927                    "completed"
1928                };
1929                let mut items = Vec::new();
1930
1931                let encrypted_reasoning = output.content.iter().find_map(|block| match block {
1932                    ContentBlock::Reasoning { details, .. } => encrypted_reasoning_data(details),
1933                    _ => None,
1934                });
1935                let encrypted_reasoning_id = output.content.iter().find_map(|block| match block {
1936                    ContentBlock::Reasoning { details, .. } => encrypted_reasoning_item_id(details),
1937                    _ => None,
1938                });
1939                let has_signed_reasoning = output.content.iter().any(|block| {
1940                    matches!(
1941                        block,
1942                        ContentBlock::Reasoning {
1943                            signature: Some(_),
1944                            ..
1945                        }
1946                    )
1947                });
1948                if has_signed_reasoning {
1949                    for (index, block) in output.content.iter().enumerate() {
1950                        if let ContentBlock::Reasoning {
1951                            text,
1952                            signature,
1953                            details,
1954                        } = block
1955                        {
1956                            let encrypted = signature
1957                                .as_deref()
1958                                .map(|signature| super::encode_anthropic_thinking(text, signature))
1959                                .or_else(|| encrypted_reasoning_data(details));
1960                            let id = encrypted_reasoning_item_id(details)
1961                                .unwrap_or_else(|| format!("rs_switchyard_{index}"));
1962                            items.push(encode_responses_reasoning_output(
1963                                text,
1964                                encrypted.as_deref(),
1965                                Some(&id),
1966                            ));
1967                        }
1968                    }
1969                } else if !reasoning.is_empty() || encrypted_reasoning.is_some() {
1970                    items.push(encode_responses_reasoning_output(
1971                        &reasoning,
1972                        encrypted_reasoning.as_deref(),
1973                        encrypted_reasoning_id.as_deref(),
1974                    ));
1975                }
1976
1977                if !text.is_empty() || (!has_output_items && reasoning.is_empty()) {
1978                    items.push(json!({
1979                        "type": "message",
1980                        "id": "msg_switchyard",
1981                        "status": status,
1982                        "role": role_to_responses(output.role),
1983                        "content": [{
1984                            "type": "output_text",
1985                            "text": text,
1986                            "annotations": output.url_citations.iter().map(|citation| json!({
1987                                "type": "url_citation",
1988                                "start_index": citation.start_index,
1989                                "end_index": citation.end_index,
1990                                "url": citation.url,
1991                                "title": citation.title,
1992                            })).collect::<Vec<_>>(),
1993                        }],
1994                    }));
1995                }
1996
1997                items.extend(output.content.iter().filter_map(|block| match block {
1998                    ContentBlock::ToolCall(call) => Some(json!({
1999                        "type": "function_call",
2000                        "call_id": call.id,
2001                        "name": call.name,
2002                        "arguments": json_string_python_style(&call.arguments),
2003                    })),
2004                    ContentBlock::Unknown { provider, raw }
2005                        if provider.as_str() == WireFormat::OpenAiResponses.as_str()
2006                            && raw["type"].as_str().is_some_and(super::is_native_output) =>
2007                    {
2008                        Some(raw.clone())
2009                    }
2010                    _ => None,
2011                }));
2012
2013                items
2014            })
2015            .collect(),
2016    )
2017}
2018
2019// Encodes private reasoning as a separate Responses output item. An encrypted-only item
2020// carries no text part but keeps `encrypted_content` so the client can replay it.
2021fn encode_responses_reasoning_output(
2022    text: &str,
2023    encrypted: Option<&str>,
2024    item_id: Option<&str>,
2025) -> Value {
2026    // Standard Responses shape: text as `summary_text` parts, which is what clients record.
2027    let mut summary = Vec::new();
2028    if !text.is_empty() {
2029        summary.push(json!({"type": "summary_text", "text": text}));
2030    }
2031    // Encrypted reasoning verifies only under the id it was issued with, so reuse it.
2032    let mut item = json!({
2033        "type": "reasoning",
2034        "id": item_id.unwrap_or("rs_switchyard"),
2035        "status": "completed",
2036        "summary": summary,
2037    });
2038    if let Some(encrypted) = encrypted {
2039        item["encrypted_content"] = Value::String(encrypted.to_string());
2040    }
2041    item
2042}
2043
2044// Serializes JSON with Python-like spacing to match legacy converter behavior.
2045fn json_string_python_style(value: &Value) -> String {
2046    match value {
2047        Value::Null => "null".to_string(),
2048        Value::Bool(value) => value.to_string(),
2049        Value::Number(value) => value.to_string(),
2050        Value::String(value) => serde_json::to_string(value).unwrap_or_else(|_| value.clone()),
2051        Value::Array(items) => {
2052            let body = items
2053                .iter()
2054                .map(json_string_python_style)
2055                .collect::<Vec<_>>()
2056                .join(", ");
2057            format!("[{body}]")
2058        }
2059        Value::Object(object) => {
2060            let body = object
2061                .iter()
2062                .map(|(key, value)| {
2063                    let key = serde_json::to_string(key).unwrap_or_else(|_| format!("\"{key}\""));
2064                    format!("{key}: {}", json_string_python_style(value))
2065                })
2066                .collect::<Vec<_>>()
2067                .join(", ");
2068            format!("{{{body}}}")
2069        }
2070    }
2071}
2072
2073// Normalizes Responses usage fields.
2074fn decode_responses_usage(value: Option<&Value>) -> Usage {
2075    let Some(value) = value.and_then(Value::as_object) else {
2076        return Usage::default();
2077    };
2078    let aggregate_input_tokens = value
2079        .get("input_tokens")
2080        .or_else(|| value.get("prompt_tokens"))
2081        .and_then(Value::as_u64);
2082    let cached_input_tokens = value
2083        .get("input_tokens_details")
2084        .or_else(|| value.get("prompt_tokens_details"))
2085        .and_then(|details| details.get("cached_tokens"))
2086        .and_then(Value::as_u64);
2087    let cache_creation_input_tokens = value
2088        .get("input_tokens_details")
2089        .and_then(|details| details.get("cache_write_tokens"))
2090        .and_then(Value::as_u64)
2091        .or_else(|| {
2092            value.get("prompt_tokens_details").and_then(|details| {
2093                details
2094                    .get("cache_write_tokens")
2095                    .and_then(Value::as_u64)
2096                    .or_else(|| details.get("cache_creation_tokens").and_then(Value::as_u64))
2097            })
2098        });
2099    let input_tokens = aggregate_input_tokens.map(|tokens| {
2100        tokens
2101            .saturating_sub(cached_input_tokens.unwrap_or(0))
2102            .saturating_sub(cache_creation_input_tokens.unwrap_or(0))
2103    });
2104    let output_tokens = value
2105        .get("output_tokens")
2106        .or_else(|| value.get("completion_tokens"))
2107        .and_then(Value::as_u64);
2108    Usage {
2109        provider_cost: crate::codecs::common::provider_cost(value),
2110        input_tokens,
2111        cache: crate::codecs::common::cache_usage_details(
2112            value,
2113            cached_input_tokens,
2114            cache_creation_input_tokens,
2115        ),
2116        output_tokens,
2117        total_tokens: value
2118            .get("total_tokens")
2119            .and_then(Value::as_u64)
2120            .or_else(|| {
2121                aggregate_input_tokens
2122                    .zip(output_tokens)
2123                    .map(|(input, output)| input + output)
2124            }),
2125        reasoning_tokens: value
2126            .get("output_tokens_details")
2127            .and_then(|details| details.get("reasoning_tokens"))
2128            .or_else(|| {
2129                value
2130                    .get("completion_tokens_details")
2131                    .and_then(|details| details.get("reasoning_tokens"))
2132            })
2133            .and_then(Value::as_u64),
2134    }
2135}
2136
2137// Encodes normalized usage into Responses usage JSON.
2138pub(super) fn encode_responses_usage(usage: &Usage) -> Value {
2139    let input_tokens = usage.input_tokens.unwrap_or(0)
2140        + usage.cached_input_tokens().unwrap_or(0)
2141        + usage.cache_creation_input_tokens().unwrap_or(0);
2142    // The detail objects are required by the Responses schema, so both are always present. An
2143    // upstream that reports no cache or reasoning breakdown means zero, not "unknown"; omitting
2144    // them instead yields a payload that fails to deserialize into the OpenAI SDK's
2145    // ResponseUsage, which types both as non-optional.
2146    crate::codecs::common::encode_usage_metadata(
2147        json!({
2148            "input_tokens": input_tokens,
2149            "output_tokens": usage.output_tokens.unwrap_or(0),
2150            "total_tokens": usage
2151                .total_tokens
2152                .or_else(|| Some(input_tokens + usage.output_tokens.unwrap_or(0)))
2153                .unwrap_or(0),
2154            "input_tokens_details": {
2155                "cached_tokens": usage.cached_input_tokens().unwrap_or(0),
2156                "cache_write_tokens": usage.cache_creation_input_tokens().unwrap_or(0),
2157            },
2158            "output_tokens_details": {"reasoning_tokens": usage.reasoning_tokens.unwrap_or(0)},
2159        }),
2160        usage,
2161    )
2162}
2163
2164/// Re-emits captured request extensions that the Responses format accepts.
2165///
2166/// The allowlist is Responses-specific: Chat-only fields such as
2167/// `stream_options` and `top_logprobs` are deliberately absent, so they stay
2168/// dropped on a Chat-to-Responses hop. Fields already present in `body` are
2169/// left untouched — anything the encoder generated is authoritative over a
2170/// captured extension of the same name.
2171fn copy_responses_request_extensions(
2172    body: &mut Map<String, Value>,
2173    extensions: &Map<String, Value>,
2174) {
2175    for field in [
2176        "include",
2177        "metadata",
2178        "parallel_tool_calls",
2179        "previous_response_id",
2180        "prompt_cache_key",
2181        "prompt_cache_retention",
2182        "safety_identifier",
2183        "service_tier",
2184        "store",
2185        "user",
2186    ] {
2187        if let Some(value) = extensions.get(field) {
2188            body.entry(field.to_string())
2189                .or_insert_with(|| value.clone());
2190        }
2191    }
2192}