Skip to main content

agent_framework_openai/
responses.rs

1//! [`OpenAIChatClient`]: a [`ChatClient`] for the OpenAI Responses API
2//! (`POST /v1/responses`).
3//!
4//! The Responses API uses an item-based `input`/`output` shape rather than
5//! the `messages` array used by Chat Completions, and supports a dedicated
6//! `previous_response_id` for service-side conversation state. Wire framing
7//! (SSE parsing style, error handling) mirrors [`crate::OpenAIChatCompletionClient`].
8//!
9//! ```no_run
10//! use agent_framework_openai::responses::OpenAIChatClient;
11//! use agent_framework_core::prelude::*;
12//!
13//! # async fn demo() -> Result<()> {
14//! let client = OpenAIChatClient::new("sk-...", "gpt-4o-mini");
15//! let agent = Agent::builder(client)
16//!     .instructions("You are concise.")
17//!     .build();
18//! let reply = agent.run_once("Say hi").await?;
19//! println!("{}", reply.text());
20//! # Ok(())
21//! # }
22//! ```
23
24use std::collections::{HashMap, VecDeque};
25use std::sync::Arc;
26
27use agent_framework_core::client::{ChatClient, ChatStream};
28use agent_framework_core::error::{Error, Result};
29use agent_framework_core::streaming::Utf8StreamDecoder;
30use agent_framework_core::tools::ToolDefinition;
31use agent_framework_core::types::{
32    Annotation, ChatOptions, ChatResponse, ChatResponseUpdate, Content, DataContent, FinishReason,
33    FunctionApprovalRequestContent, FunctionArguments, FunctionCallContent, FunctionResultContent,
34    McpServerToolCallContent, McpServerToolResultContent, Message, OauthConsentRequestContent,
35    ResponseFormat, Role, TextContent, TextReasoningContent, TextSpanRegion, ToolMode, UriContent,
36    UsageContent, UsageDetails,
37};
38use futures::StreamExt;
39use serde_json::{json, Map, Value};
40
41use crate::convert::{
42    audio_format, data_content_media_type, function_arguments_to_string, result_to_string,
43    top_level_media_type, DEFAULT_FILENAME,
44};
45use crate::{ByteStream, DEFAULT_BASE_URL};
46
47/// An OpenAI Responses API chat client (`POST /v1/responses`).
48#[derive(Clone)]
49pub struct OpenAIChatClient {
50    inner: Arc<Inner>,
51}
52
53#[derive(Clone)]
54struct Inner {
55    http: reqwest::Client,
56    api_key: String,
57    base_url: String,
58    model: String,
59    organization: Option<String>,
60}
61
62impl std::fmt::Debug for OpenAIChatClient {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        f.debug_struct("OpenAIChatClient")
65            .field("base_url", &self.inner.base_url)
66            .field("model", &self.inner.model)
67            .field("organization", &self.inner.organization)
68            .finish_non_exhaustive()
69    }
70}
71
72impl OpenAIChatClient {
73    /// Create a client for the given API key and default model.
74    pub fn new(api_key: impl Into<String>, model: impl Into<String>) -> Self {
75        Self {
76            inner: Arc::new(Inner {
77                http: reqwest::Client::new(),
78                api_key: api_key.into(),
79                base_url: DEFAULT_BASE_URL.to_string(),
80                model: model.into(),
81                organization: None,
82            }),
83        }
84    }
85
86    /// Build a client from the `OPENAI_API_KEY` (and optional
87    /// `OPENAI_BASE_URL`) environment variables.
88    pub fn from_env(model: impl Into<String>) -> Result<Self> {
89        let key = std::env::var("OPENAI_API_KEY")
90            .map_err(|_| Error::Configuration("OPENAI_API_KEY is not set".into()))?;
91        let mut client = Self::new(key, model);
92        if let Ok(base) = std::env::var("OPENAI_BASE_URL") {
93            client = client.with_base_url(base);
94        }
95        Ok(client)
96    }
97
98    /// Override the base URL (for Azure OpenAI or compatible servers).
99    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
100        Arc::make_mut(&mut self.inner).base_url = base_url.into();
101        self
102    }
103
104    /// Set the organization header.
105    pub fn with_organization(mut self, org: impl Into<String>) -> Self {
106        Arc::make_mut(&mut self.inner).organization = Some(org.into());
107        self
108    }
109
110    /// The default model id.
111    pub fn model(&self) -> &str {
112        &self.inner.model
113    }
114
115    fn build_body(&self, messages: &[Message], options: &ChatOptions, stream: bool) -> Value {
116        let mut body = Map::new();
117        let model = options
118            .model
119            .clone()
120            .unwrap_or_else(|| self.inner.model.clone());
121        body.insert("model".into(), json!(model));
122
123        let (instructions, rest) = extract_instructions(messages, options.instructions.as_deref());
124        if let Some(instructions) = instructions {
125            body.insert("instructions".into(), json!(instructions));
126        }
127        let input = if uses_service_side_storage(options) {
128            messages_to_continuation_input(rest)
129        } else {
130            messages_to_input(rest)
131        };
132        body.insert("input".into(), json!(input));
133
134        if let Some(conversation_id) = &options.conversation_id {
135            body.insert("previous_response_id".into(), json!(conversation_id));
136        }
137        if let Some(t) = options.temperature {
138            body.insert("temperature".into(), json!(t));
139        }
140        if let Some(t) = options.top_p {
141            body.insert("top_p".into(), json!(t));
142        }
143        if let Some(mt) = options.max_tokens {
144            body.insert("max_output_tokens".into(), json!(mt));
145        }
146        if let Some(store) = options.store {
147            body.insert("store".into(), json!(store));
148        }
149        if let Some(user) = &options.user {
150            body.insert("user".into(), json!(user));
151        }
152        if let Some(metadata) = &options.metadata {
153            body.insert("metadata".into(), json!(metadata));
154        }
155
156        if !options.tools.is_empty() {
157            let tools: Vec<Value> = options.tools.iter().map(tool_to_responses_spec).collect();
158            body.insert("tools".into(), json!(tools));
159            if let Some(allow_multi) = options.allow_multiple_tool_calls {
160                body.insert("parallel_tool_calls".into(), json!(allow_multi));
161            }
162        }
163        if let Some(tool_choice) = &options.tool_choice {
164            body.insert("tool_choice".into(), tool_choice_to_responses(tool_choice));
165        }
166        if let Some(fmt) = &options.response_format {
167            body.insert(
168                "text".into(),
169                json!({ "format": response_format_to_text(fmt) }),
170            );
171        }
172
173        // Inserted before the `additional_properties` pass below, whose
174        // A caller's own `include` entries are already folded in here.
175        if let Some(include) = responses_include(options, true) {
176            body.insert("include".into(), include);
177        }
178
179        for (k, v) in &options.additional_properties {
180            // `include` belongs to `responses_include` alone. Letting it
181            // through would resurrect a value that function deliberately
182            // dropped — an explicit empty array would land as `include: []`,
183            // the one shape it exists to avoid.
184            if k == "include" {
185                continue;
186            }
187            body.entry(k.clone()).or_insert_with(|| v.clone());
188        }
189
190        if stream {
191            body.insert("stream".into(), json!(true));
192        }
193        Value::Object(body)
194    }
195
196    async fn post(&self, body: &Value) -> Result<reqwest::Response> {
197        let url = format!("{}/responses", self.inner.base_url.trim_end_matches('/'));
198        let mut req = self
199            .inner
200            .http
201            .post(&url)
202            .bearer_auth(&self.inner.api_key)
203            .json(body);
204        if let Some(org) = &self.inner.organization {
205            req = req.header("OpenAI-Organization", org);
206        }
207        let resp = req
208            .send()
209            .await
210            .map_err(|e| Error::service(format!("request failed: {e}")))?;
211        if !resp.status().is_success() {
212            let status = resp.status();
213            let retry_after = crate::parse_retry_after(resp.headers());
214            let text = resp.text().await.unwrap_or_default();
215            return Err(crate::classify_service_error(
216                status.as_u16(),
217                &text,
218                format!("OpenAI API error {status}: {text}"),
219                retry_after,
220            ));
221        }
222        Ok(resp)
223    }
224}
225
226#[async_trait::async_trait]
227impl ChatClient for OpenAIChatClient {
228    async fn get_response(
229        &self,
230        messages: Vec<Message>,
231        options: ChatOptions,
232    ) -> Result<ChatResponse> {
233        let body = self.build_body(&messages, &options, false);
234        let resp = self.post(&body).await?;
235        let value: Value = resp
236            .json()
237            .await
238            .map_err(|e| Error::service(format!("invalid response json: {e}")))?;
239        if let Some(err) = response_failure_error(&value) {
240            return Err(err);
241        }
242        Ok(parse_response(&value, options.store))
243    }
244
245    async fn get_streaming_response(
246        &self,
247        messages: Vec<Message>,
248        options: ChatOptions,
249    ) -> Result<ChatStream> {
250        let body = self.build_body(&messages, &options, true);
251        let resp = self.post(&body).await?;
252        Ok(parse_responses_sse_stream(resp, options.store).boxed())
253    }
254
255    fn model(&self) -> Option<&str> {
256        Some(&self.inner.model)
257    }
258
259    fn service_url(&self) -> Option<&str> {
260        Some(&self.inner.base_url)
261    }
262}
263
264// region: request conversion
265
266/// The `include` entry that asks a reasoning model to return its *encrypted*
267/// reasoning item alongside the summary.
268pub const ENCRYPTED_REASONING_INCLUDE: &str = "reasoning.encrypted_content";
269
270/// Build the Responses request's `include` array.
271///
272/// A reasoning item must be replayed verbatim on the follow-up turn of a tool
273/// loop, and the service only accepts it when it carries its `id` *and*
274/// `encrypted_content`. When the conversation is held service-side the model
275/// already has that item, but on a stateless request nothing is stored — so
276/// unless the request asks for `reasoning.encrypted_content`, the item comes
277/// back without it and the replay in [`messages_to_input`] has nothing valid
278/// to re-send. This adds it implicitly in exactly that case, mirroring
279/// upstream's `_prepare_options`.
280///
281/// A caller's own `include` entries (passed through
282/// `ChatOptions::additional_properties`) are always preserved, and an explicit
283/// `reasoning.encrypted_content` is honored even when `implicit` is `false` —
284/// `implicit` gates only whether it is added on the caller's behalf. Foundry
285/// passes `false` here: it does not want encrypted reasoning unless asked for
286/// it by name (upstream #7536).
287///
288/// Returns `None` when the array would be empty, so a request that needs no
289/// `include` does not carry an empty one.
290///
291/// `pub` for the same reason as [`extract_instructions`]: `agent-framework-azure`'s
292/// Responses client builds its own body and reuses this step rather than
293/// reimplementing it.
294pub fn responses_include(options: &ChatOptions, implicit: bool) -> Option<Value> {
295    let mut include: Vec<Value> = options
296        .additional_properties
297        .get("include")
298        .and_then(Value::as_array)
299        .cloned()
300        .unwrap_or_default();
301
302    // Upstream keys this off the service-side-storage indicators, not `store`:
303    // a request continuing a stored conversation needs nothing echoed back.
304    let uses_service_side_storage = uses_service_side_storage(options);
305
306    let already_present = include
307        .iter()
308        .any(|v| v.as_str() == Some(ENCRYPTED_REASONING_INCLUDE));
309    if implicit && !uses_service_side_storage && !already_present {
310        include.push(json!(ENCRYPTED_REASONING_INCLUDE));
311    }
312
313    (!include.is_empty()).then(|| json!(include))
314}
315
316/// Whether a request continues a service-stored response chain: it carries a
317/// non-empty `conversation_id`, sent as `previous_response_id`
318/// (upstream's `request_uses_service_side_storage`).
319///
320/// `pub` so `agent-framework-azure`'s Responses client makes the same call
321/// when choosing between [`messages_to_input`] and
322/// [`messages_to_continuation_input`].
323pub fn uses_service_side_storage(options: &ChatOptions) -> bool {
324    options
325        .conversation_id
326        .as_deref()
327        .is_some_and(|id| !id.is_empty())
328}
329
330/// Split a leading system message (and/or `ChatOptions::instructions`) out
331/// into the Responses API's top-level `instructions` field, returning the
332/// remaining messages to convert into `input` items.
333///
334/// `pub` (rather than private) so `agent-framework-azure`'s Responses client
335/// can reuse this exact instructions-extraction step ahead of
336/// [`messages_to_input`] when building the Azure OpenAI Responses request
337/// body, instead of reimplementing it.
338pub fn extract_instructions<'a>(
339    messages: &'a [Message],
340    options_instructions: Option<&str>,
341) -> (Option<String>, &'a [Message]) {
342    let mut parts = Vec::new();
343    if let Some(instr) = options_instructions {
344        if !instr.is_empty() {
345            parts.push(instr.to_string());
346        }
347    }
348    let mut rest = messages;
349    if let Some(first) = messages.first() {
350        if first.role == Role::system() {
351            let text = first.text();
352            if !text.is_empty() {
353                parts.push(text);
354            }
355            rest = &messages[1..];
356        }
357    }
358    if parts.is_empty() {
359        (None, rest)
360    } else {
361        (Some(parts.join("\n\n")), rest)
362    }
363}
364
365/// Convert framework messages into the Responses API's `input` item array.
366///
367/// `pub` so `agent-framework-azure`'s Responses client can reuse this
368/// conversion verbatim rather than reimplementing it (Azure OpenAI's
369/// Responses API shares the exact same `input` item wire shape).
370pub fn messages_to_input(messages: &[Message]) -> Vec<Value> {
371    convert_messages(messages, false)
372}
373
374/// Convert framework messages into `input` items for a request that continues
375/// a stored response chain (`previous_response_id`, see
376/// [`uses_service_side_storage`]).
377///
378/// The service already holds every item the earlier responses produced, and
379/// rejects an inline copy of one with a server-issued `id` as a duplicate
380/// ("Duplicate item found with id ..."). So hosted `mcp_call` items (and the
381/// results folded into them), `mcp_approval_request` items and reasoning items
382/// are left out here, as upstream's `_prepare_message_for_openai` does under
383/// `request_uses_service_side_storage` (microsoft/agent-framework#3295).
384/// Approval responses and function results still go out: they are new input
385/// the service pairs to its stored items by id.
386pub fn messages_to_continuation_input(messages: &[Message]) -> Vec<Value> {
387    convert_messages(messages, true)
388}
389
390fn convert_messages(messages: &[Message], continues_stored: bool) -> Vec<Value> {
391    let mut out = Vec::new();
392    for msg in messages {
393        let role = msg.role.as_str();
394        if role == Role::TOOL {
395            for content in &msg.contents {
396                match content {
397                    Content::FunctionResult(fr) => out.push(function_result_to_item(fr)),
398                    Content::McpServerToolResult(r) => attach_mcp_output(&mut out, r),
399                    _ => {}
400                }
401            }
402            continue;
403        }
404
405        let mut buffered: Vec<Value> = Vec::new();
406        for content in &msg.contents {
407            match content {
408                // A refusal is its own output content part — `{"type":
409                // "refusal", "refusal": "..."}` — sitting beside `output_text`
410                // in an output message. Re-emitting it as `output_text` would
411                // replay a decline to the provider as an answer. Only
412                // meaningful on the assistant side: an *input* message's
413                // content list admits only input_text/input_image/input_file,
414                // so a refusal on any other role has no wire form and is
415                // dropped rather than mis-encoded.
416                Content::Text(t) if t.refusal => {
417                    if role == Role::ASSISTANT {
418                        buffered.push(json!({ "type": "refusal", "refusal": t.text }));
419                    }
420                }
421                Content::Text(t) => {
422                    let text_type = if role == Role::ASSISTANT {
423                        "output_text"
424                    } else {
425                        "input_text"
426                    };
427                    buffered.push(json!({ "type": text_type, "text": t.text }));
428                }
429                Content::Uri(u) => {
430                    if let Some(part) = content_to_input_part(&u.uri, Some(&u.media_type)) {
431                        buffered.push(part);
432                    }
433                }
434                Content::Data(d) => {
435                    if let Some(part) =
436                        content_to_input_part(&d.uri, data_content_media_type(d).as_deref())
437                    {
438                        buffered.push(part);
439                    }
440                }
441                Content::HostedFile(h) => {
442                    buffered.push(json!({ "type": "input_file", "file_id": h.file_id }));
443                }
444                Content::FunctionCall(fc) => {
445                    flush_text(&mut out, &mut buffered, role);
446                    out.push(json!({
447                        "type": "function_call",
448                        "call_id": fc.call_id,
449                        "name": fc.name,
450                        "arguments": function_arguments_to_string(&fc.arguments),
451                    }));
452                }
453                Content::FunctionResult(fr) => {
454                    flush_text(&mut out, &mut buffered, role);
455                    out.push(function_result_to_item(fr));
456                }
457                Content::FunctionApprovalResponse(r) => {
458                    flush_text(&mut out, &mut buffered, role);
459                    out.push(json!({
460                        "type": "mcp_approval_response",
461                        "approval_request_id": r.id,
462                        "approve": r.approved,
463                    }));
464                }
465                // Already stored service-side under continuation; re-sending
466                // its `id` would duplicate it.
467                Content::FunctionApprovalRequest(_) if continues_stored => {}
468                Content::FunctionApprovalRequest(r) => {
469                    flush_text(&mut out, &mut buffered, role);
470                    out.push(json!({
471                        "type": "mcp_approval_request",
472                        "id": r.id,
473                        "name": r.function_call.name,
474                        "arguments": function_arguments_to_string(&r.function_call.arguments),
475                    }));
476                }
477                // A hosted MCP call and its result are one `mcp_call` input
478                // item carrying both `arguments` and `output`
479                // (`_prepare_content_for_openai` + `_coalesce_pending_mcp_results`).
480                // Replayed after its approval pair, it tells the service the
481                // approved call already ran, so local history does not ask
482                // for it again. Under continuation the service already has
483                // the item by its `id`, so it is not re-sent (and its result,
484                // finding no call to attach to, is dropped with it).
485                Content::McpServerToolCall(call) => {
486                    if !continues_stored && !call.call_id.is_empty() {
487                        flush_text(&mut out, &mut buffered, role);
488                        out.push(json!({
489                            "type": "mcp_call",
490                            "id": call.call_id,
491                            "server_label": call.server_name.clone().unwrap_or_default(),
492                            "name": call.tool_name,
493                            "arguments": function_arguments_to_string(&call.arguments),
494                        }));
495                        // Links the completed call to its replayed approval
496                        // request/response pair.
497                        if let (Some(id), Some(Value::Object(item))) =
498                            (&call.approval_request_id, out.last_mut())
499                        {
500                            item.insert("approval_request_id".into(), Value::String(id.clone()));
501                        }
502                    }
503                }
504                Content::McpServerToolResult(result) => {
505                    flush_text(&mut out, &mut buffered, role);
506                    attach_mcp_output(&mut out, result);
507                }
508                Content::TextReasoning(tr) => {
509                    // Re-emit the original reasoning item verbatim (store:false
510                    // replay). A summary-only reasoning content with no
511                    // preserved item has no valid input form (it lacks the
512                    // required id/encrypted_content), so it is dropped.
513                    // Under continuation the service already holds the item.
514                    let raw = tr.raw_representation.as_ref().filter(|_| !continues_stored);
515                    if let Some(raw) = raw {
516                        flush_text(&mut out, &mut buffered, role);
517                        out.push(raw.clone());
518                    }
519                }
520                _ => {}
521            }
522        }
523        flush_text(&mut out, &mut buffered, role);
524    }
525    out
526}
527
528/// Set a hosted MCP result's output on the latest `mcp_call` input item with
529/// its id that has none yet. A result with no such call is dropped: the
530/// Responses API has no standalone MCP output item
531/// (`_coalesce_pending_mcp_results`).
532fn attach_mcp_output(out: &mut [Value], result: &McpServerToolResultContent) {
533    if result.call_id.is_empty() {
534        return;
535    }
536    let target = out.iter_mut().rev().find(|item| {
537        item.get("type").and_then(Value::as_str) == Some("mcp_call")
538            && item.get("id").and_then(Value::as_str) == Some(result.call_id.as_str())
539    });
540    if let Some(Value::Object(item)) = target {
541        let unfinished = item.get("output").is_none_or(Value::is_null)
542            && item.get("error").is_none_or(Value::is_null);
543        if !unfinished {
544            return;
545        }
546        // A failed call can carry an error and no output; replaying its
547        // error is what marks it as finished rather than still running.
548        let error = result.error.as_ref().filter(|e| !e.is_null());
549        if result.output.is_some() || error.is_none() {
550            item.insert(
551                "output".into(),
552                Value::String(stringify_mcp_output(result.output.as_ref())),
553            );
554        }
555        if let Some(error) = error {
556            item.insert("error".into(), error.clone());
557        }
558    }
559}
560
561/// Render a hosted MCP result as the string `mcp_call.output` field
562/// (`_stringify_mcp_output`): a string as is, text entries joined, anything
563/// else as JSON.
564fn stringify_mcp_output(output: Option<&Value>) -> String {
565    match output {
566        None | Some(Value::Null) => String::new(),
567        Some(Value::String(s)) => s.clone(),
568        Some(Value::Array(entries)) => entries
569            .iter()
570            .map(|entry| match entry {
571                Value::String(s) => s.clone(),
572                other => match other.get("text").and_then(Value::as_str) {
573                    Some(text) => text.to_string(),
574                    None => other.to_string(),
575                },
576            })
577            .collect(),
578        Some(other) => other.to_string(),
579    }
580}
581
582/// Parse a hosted `mcp_call` output item into its call and, once it has run,
583/// its result (`_create_response_content`'s `mcp_call` arm). The item's `id`
584/// is the call id, falling back to `call_id`. A call that failed carries its
585/// `error` on the result, with or without an `output`.
586fn mcp_call_item_contents(item: &Value) -> Vec<Content> {
587    let call_id = item
588        .get("id")
589        .and_then(Value::as_str)
590        .filter(|s| !s.is_empty())
591        .or_else(|| item.get("call_id").and_then(Value::as_str))
592        .unwrap_or_default()
593        .to_string();
594    let mut contents = vec![Content::McpServerToolCall(McpServerToolCallContent {
595        call_id: call_id.clone(),
596        tool_name: item
597            .get("name")
598            .and_then(Value::as_str)
599            .unwrap_or_default()
600            .to_string(),
601        server_name: item
602            .get("server_label")
603            .and_then(Value::as_str)
604            .map(String::from),
605        arguments: item
606            .get("arguments")
607            .and_then(Value::as_str)
608            .map(|a| FunctionArguments::Raw(a.to_string())),
609        approval_request_id: item
610            .get("approval_request_id")
611            .and_then(Value::as_str)
612            .filter(|s| !s.is_empty())
613            .map(String::from),
614    })];
615    let output = item.get("output").filter(|o| !o.is_null()).cloned();
616    let error = item.get("error").filter(|e| !e.is_null()).cloned();
617    if output.is_some() || error.is_some() {
618        contents.push(Content::McpServerToolResult(McpServerToolResultContent {
619            call_id,
620            output,
621            error,
622        }));
623    }
624    contents
625}
626
627/// Map a URI/data content item to a Responses API input content part, or `None`
628/// when it has no wire mapping (mirrors upstream `_openai_content_parser`).
629/// Handles images (`input_image`), audio (`input_audio`), and `application/*`
630/// data (`input_file`).
631fn content_to_input_part(uri: &str, media_type: Option<&str>) -> Option<Value> {
632    let media_type = media_type?;
633    match top_level_media_type(media_type).as_str() {
634        // `detail` defaults to "auto"; the Rust content types carry no override.
635        "image" => Some(json!({
636            "type": "input_image",
637            "image_url": uri,
638            "detail": "auto",
639        })),
640        "audio" => {
641            let format = audio_format(media_type)?;
642            // `input_audio.data` is the raw base64 payload, not a data URI —
643            // same wire rule as the Chat Completions converter.
644            Some(json!({
645                "type": "input_audio",
646                "input_audio": {
647                    "data": crate::convert::strip_data_uri_prefix(uri),
648                    "format": format,
649                },
650            }))
651        }
652        // Inline bytes go in `file_data`; a remote file goes by `file_url`.
653        // Putting a URL in `file_data` makes the service read the URL
654        // itself as the file's contents.
655        // The service identifies an inline file by its name, so a known
656        // document type gets a matching extension rather than a bare `file`.
657        "application" if uri.starts_with("data:") => Some(json!({
658            "type": "input_file",
659            "file_data": uri,
660            "filename": application_filename(media_type),
661        })),
662        "application" => Some(json!({ "type": "input_file", "file_url": uri })),
663        // Text, Markdown and CSV attachments are files too. There was no arm
664        // for them, so they were dropped without a word. The service infers
665        // a file's type from its name, so inline text gets a matching
666        // extension rather than the bare default.
667        "text" if uri.starts_with("data:") => Some(json!({
668            "type": "input_file",
669            "file_data": uri,
670            "filename": text_filename(media_type),
671        })),
672        "text" => Some(json!({ "type": "input_file", "file_url": uri })),
673        _ => None,
674    }
675}
676
677/// A filename for an inline `application/*` file: the bare default with the
678/// extension its media type implies, or the bare default when it implies
679/// none (`application/octet-stream`).
680fn application_filename(media_type: &str) -> String {
681    let subtype = media_type
682        .split(';')
683        .next()
684        .and_then(|t| t.split_once('/'))
685        .map(|(_, sub)| sub.trim().to_ascii_lowercase());
686    let ext = match subtype.as_deref() {
687        Some("pdf") => "pdf",
688        Some("msword") => "doc",
689        Some("vnd.openxmlformats-officedocument.wordprocessingml.document") => "docx",
690        Some("vnd.ms-excel") => "xls",
691        Some("vnd.openxmlformats-officedocument.spreadsheetml.sheet") => "xlsx",
692        Some("vnd.ms-powerpoint") => "ppt",
693        Some("vnd.openxmlformats-officedocument.presentationml.presentation") => "pptx",
694        Some("json") => "json",
695        Some("rtf") => "rtf",
696        Some("xml") => "xml",
697        Some("zip") => "zip",
698        _ => return DEFAULT_FILENAME.to_string(),
699    };
700    format!("{DEFAULT_FILENAME}.{ext}")
701}
702
703/// A filename for an inline `text/*` file, whose extension tells the
704/// service what it holds.
705fn text_filename(media_type: &str) -> String {
706    let subtype = media_type
707        .split(';')
708        .next()
709        .and_then(|t| t.split_once('/'))
710        .map(|(_, sub)| sub.trim().to_ascii_lowercase());
711    let ext = match subtype.as_deref() {
712        Some("markdown") => "md",
713        Some("csv") => "csv",
714        Some("html") => "html",
715        Some("xml") => "xml",
716        _ => "txt",
717    };
718    format!("{DEFAULT_FILENAME}.{ext}")
719}
720
721fn flush_text(out: &mut Vec<Value>, buffered: &mut Vec<Value>, role: &str) {
722    if !buffered.is_empty() {
723        out.push(json!({ "type": "message", "role": role, "content": std::mem::take(buffered) }));
724    }
725}
726
727fn function_result_to_item(fr: &FunctionResultContent) -> Value {
728    json!({
729        "type": "function_call_output",
730        "call_id": fr.call_id,
731        "output": result_to_string(fr),
732    })
733}
734
735/// The flat Responses-API tool spec: `{"type":"function","name":...}`, unlike
736/// Chat Completions' `{"type":"function","function":{...}}` nesting.
737///
738/// `pub` so `agent-framework-azure`'s Responses client can reuse this
739/// mapping rather than reimplementing it.
740pub fn tool_to_responses_spec(tool: &ToolDefinition) -> Value {
741    use agent_framework_core::tools::ToolKind;
742    match &tool.kind {
743        ToolKind::HostedWebSearch => {
744            let mut spec = Map::new();
745            spec.insert("type".into(), json!("web_search"));
746            if let Some(loc) = tool.parameters.get("user_location") {
747                spec.insert("user_location".into(), user_location_to_responses(loc));
748            }
749            Value::Object(spec)
750        }
751        ToolKind::HostedCodeInterpreter => {
752            let mut spec = Map::new();
753            spec.insert("type".into(), json!("code_interpreter"));
754            // A caller-supplied `container` wins; otherwise default to `auto`
755            // and attach any `file_ids` (`_responses_client.py:264-278`).
756            if let Some(container) = tool.parameters.get("container") {
757                spec.insert("container".into(), container.clone());
758            } else {
759                let mut container = Map::new();
760                container.insert("type".into(), json!("auto"));
761                if let Some(file_ids) = tool.parameters.get("file_ids") {
762                    container.insert("file_ids".into(), file_ids.clone());
763                }
764                spec.insert("container".into(), Value::Object(container));
765            }
766            Value::Object(spec)
767        }
768        ToolKind::HostedFileSearch { max_results } => {
769            let mut spec = Map::new();
770            spec.insert("type".into(), json!("file_search"));
771            // The Responses API requires vector-store ids; the marker itself
772            // carries none, so honor ids supplied via the definition's
773            // parameters object when present.
774            if let Some(ids) = tool.parameters.get("vector_store_ids") {
775                spec.insert("vector_store_ids".into(), ids.clone());
776            }
777            // Prefer the marker's `max_results`; fall back to a parameters key.
778            let max = (*max_results)
779                .map(|n| json!(n))
780                .or_else(|| tool.parameters.get("max_results").cloned());
781            if let Some(n) = max {
782                spec.insert("max_num_results".into(), n);
783            }
784            Value::Object(spec)
785        }
786        ToolKind::HostedMcp { url, allowed_tools } => {
787            let mut spec = Map::new();
788            spec.insert("type".into(), json!("mcp"));
789            spec.insert("server_label".into(), json!(tool.name.replace(' ', "_")));
790            spec.insert("server_url".into(), json!(url));
791            if !tool.description.is_empty() {
792                spec.insert("server_description".into(), json!(tool.description));
793            }
794            if let Some(headers) = tool.parameters.get("headers") {
795                spec.insert("headers".into(), headers.clone());
796            }
797            if let Some(allowed) = allowed_tools {
798                spec.insert("allowed_tools".into(), json!(allowed));
799            }
800            spec.insert("require_approval".into(), mcp_require_approval(tool));
801            Value::Object(spec)
802        }
803        ToolKind::HostedImageGeneration => {
804            let mut spec = Map::new();
805            spec.insert("type".into(), json!("image_generation"));
806            // Pass through any caller-supplied generation options (size,
807            // quality, background, …) carried on the marker's parameters.
808            if let Value::Object(params) = &tool.parameters {
809                for (k, v) in params {
810                    if k != "type" && k != "properties" {
811                        spec.insert(k.clone(), v.clone());
812                    }
813                }
814            }
815            Value::Object(spec)
816        }
817        ToolKind::Function => json!({
818            "type": "function",
819            "name": tool.name,
820            "description": tool.description,
821            "parameters": tool.parameters,
822        }),
823    }
824}
825
826/// Build the Responses `web_search.user_location` object from a hosted-tool
827/// `user_location` parameter (`_responses_client.py:310-329`).
828fn user_location_to_responses(location: &Value) -> Value {
829    let mut loc = Map::new();
830    loc.insert("type".into(), json!("approximate"));
831    for key in ["city", "country", "region", "timezone"] {
832        if let Some(v) = location.get(key) {
833            loc.insert(key.into(), v.clone());
834        }
835    }
836    Value::Object(loc)
837}
838
839/// Build the Responses MCP `require_approval` value. A `parameters.approval_mode`
840/// override — either the string `"always_require"`/`"never_require"` or an
841/// object `{"always": [...], "never": [...]}` — takes precedence over the
842/// definition's [`ApprovalMode`]; mirrors `get_mcp_tool`
843/// (`_responses_client.py:365-386`).
844fn mcp_require_approval(tool: &ToolDefinition) -> Value {
845    use agent_framework_core::tools::ApprovalMode;
846    match tool.parameters.get("approval_mode") {
847        Some(Value::String(s)) => {
848            return json!(if s == "always_require" {
849                "always"
850            } else {
851                "never"
852            });
853        }
854        Some(Value::Object(modes)) => {
855            let mut req = Map::new();
856            if let Some(always) = modes.get("always") {
857                req.insert("always".into(), json!({ "tool_names": always }));
858            }
859            if let Some(never) = modes.get("never") {
860                req.insert("never".into(), json!({ "tool_names": never }));
861            }
862            if !req.is_empty() {
863                return Value::Object(req);
864            }
865        }
866        _ => {}
867    }
868    json!(match tool.approval_mode {
869        ApprovalMode::AlwaysRequire => "always",
870        ApprovalMode::NeverRequire => "never",
871    })
872}
873
874/// `pub` so `agent-framework-azure`'s Responses client can reuse this
875/// mapping rather than reimplementing it.
876pub fn tool_choice_to_responses(mode: &ToolMode) -> Value {
877    match mode {
878        ToolMode::Auto => json!("auto"),
879        ToolMode::None => json!("none"),
880        ToolMode::Required(Some(name)) => json!({ "type": "function", "name": name }),
881        ToolMode::Required(None) => json!("required"),
882    }
883}
884
885/// Convert a `ChatOptions::response_format` into a Responses API
886/// `text.format` object. Unlike Chat Completions (which nests the schema
887/// under `json_schema`), the Responses API uses a flat object.
888///
889/// `pub` so `agent-framework-azure`'s Responses client can reuse this
890/// mapping rather than reimplementing it.
891pub fn response_format_to_text(format: &ResponseFormat) -> Value {
892    match format {
893        ResponseFormat::Text => json!({ "type": "text" }),
894        ResponseFormat::JsonObject => json!({ "type": "json_object" }),
895        ResponseFormat::JsonSchema {
896            name,
897            description,
898            schema,
899            strict,
900        } => {
901            let mut obj = Map::new();
902            obj.insert("type".into(), json!("json_schema"));
903            obj.insert("name".into(), json!(name));
904            if let Some(d) = description {
905                obj.insert("description".into(), json!(d));
906            }
907            obj.insert("schema".into(), schema.clone());
908            if let Some(st) = strict {
909                obj.insert("strict".into(), json!(st));
910            }
911            Value::Object(obj)
912        }
913    }
914}
915
916// endregion
917
918// region: response conversion
919
920/// Parse a full (non-streaming) Responses API response.
921///
922/// Map a Responses body whose `status` is `"failed"` to a classified error,
923/// or `None` for a non-failed response. A failed run reports `status:
924/// "failed"` with a 2xx HTTP status, so the error is pulled from the body:
925/// `error.code == "content_filter"` becomes [`Error::ServiceContentFilter`]
926/// (matching the HTTP-level classification in `classify_service_error`),
927/// anything else a generic service error.
928///
929/// `pub` so `agent-framework-azure`'s Responses client can share the exact
930/// classification.
931pub fn response_failure_error(value: &Value) -> Option<Error> {
932    if value.get("status").and_then(Value::as_str) != Some("failed") {
933        return None;
934    }
935    let error = value.get("error");
936    let msg = error
937        .and_then(|e| e.get("message"))
938        .and_then(Value::as_str)
939        .unwrap_or("response failed")
940        .to_string();
941    let code = error.and_then(|e| e.get("code")).and_then(Value::as_str);
942    Some(match code {
943        Some("content_filter") => Error::service_content_filter(msg),
944        _ => Error::service(msg),
945    })
946}
947
948/// `pub` so `agent-framework-azure`'s Responses client (whose wire format is
949/// otherwise identical) can reuse this parser — including `parse_output_item`,
950/// `parse_annotations`, and usage/finish-reason handling — rather than
951/// reimplementing it.
952pub fn parse_response(value: &Value, store: Option<bool>) -> ChatResponse {
953    let mut response = ChatResponse {
954        response_id: value.get("id").and_then(Value::as_str).map(String::from),
955        model: value.get("model").and_then(Value::as_str).map(String::from),
956        ..Default::default()
957    };
958
959    let mut contents: Vec<Content> = Vec::new();
960    if let Some(items) = value.get("output").and_then(Value::as_array) {
961        for item in items {
962            parse_output_item(item, &mut contents);
963        }
964    }
965
966    let mut message = Message::with_contents(Role::assistant(), contents);
967    message.message_id = response.response_id.clone();
968    response.messages.push(message);
969
970    response.finish_reason = finish_reason_from_response(value);
971
972    if let Some(usage) = value.get("usage") {
973        response.usage_details = Some(parse_responses_usage(usage));
974    }
975    if store != Some(false) {
976        response.conversation_id = response.response_id.clone();
977    }
978    response
979}
980
981/// Build the consent content for an `oauth_consent_request` output item,
982/// or `None` when its link cannot be trusted.
983///
984/// An Azure AI Foundry project's Responses endpoint emits this item when a
985/// hosted tool needs the user to complete an OAuth consent flow; OpenAI's
986/// own Responses API does not. It is handled in this shared parser because
987/// `agent-framework-azure` and `agent-framework-foundry` both reuse it
988/// verbatim rather than re-implementing the Responses wire — a Foundry-only
989/// item type that costs an unreachable match arm on the OpenAI path.
990///
991/// The link is checked before it is handed on. It is a URL the framework is
992/// asking a human to open and authenticate at, arriving from the service as
993/// free-form text, so a `http://` or `javascript:` one is dropped with a
994/// warning rather than surfaced as something to click. Upstream validates
995/// the same two things: an HTTPS scheme and a non-empty host.
996fn oauth_consent_content(item: &Value) -> Option<Content> {
997    let item_id = item.get("id").and_then(Value::as_str);
998    let consent_link = item
999        .get("consent_link")
1000        .and_then(Value::as_str)
1001        .unwrap_or_default();
1002    if !is_https_url(consent_link) {
1003        tracing::warn!(
1004            item_id = item_id.unwrap_or("<unknown>"),
1005            "dropping oauth_consent_request without an https consent_link"
1006        );
1007        return None;
1008    }
1009    let mut content = OauthConsentRequestContent::new(consent_link);
1010    content.id = item_id.filter(|id| !id.is_empty()).map(str::to_string);
1011    Some(Content::OauthConsentRequest(content))
1012}
1013
1014/// Whether `link` is an `https` URL with a real host.
1015///
1016/// Two checks, because each alone has a gap. The literal one — an
1017/// `https://` prefix followed by a non-empty authority — accepts
1018/// `https://user@/consent` and `https://:443/consent`, whose authority names
1019/// no host. The WHATWG parser `reqwest` re-exports (so no new dependency)
1020/// rejects those, but repairs `https:///consent` into `https://consent/`, as
1021/// a browser would. A consent link only usable after such a repair is not
1022/// one to hand a human, so it must pass both.
1023fn is_https_url(link: &str) -> bool {
1024    let literal = link
1025        .get(..8)
1026        .filter(|scheme| scheme.eq_ignore_ascii_case("https://"))
1027        .map(|_| &link[8..])
1028        .is_some_and(|authority| {
1029            let end = authority.find(['/', '?', '#']).unwrap_or(authority.len());
1030            !authority[..end].is_empty()
1031        });
1032    literal
1033        && reqwest::Url::parse(link).is_ok_and(|url| {
1034            url.scheme() == "https" && url.host_str().is_some_and(|host| !host.is_empty())
1035        })
1036}
1037
1038fn parse_output_item(item: &Value, contents: &mut Vec<Content>) {
1039    match item.get("type").and_then(Value::as_str) {
1040        Some("message") => {
1041            if let Some(parts) = item.get("content").and_then(Value::as_array) {
1042                for part in parts {
1043                    match part.get("type").and_then(Value::as_str) {
1044                        Some("output_text") => {
1045                            if let Some(text) = part.get("text").and_then(Value::as_str) {
1046                                let mut tc = TextContent::new(text);
1047                                tc.annotations = parse_annotations(part);
1048                                contents.push(Content::Text(tc));
1049                            }
1050                        }
1051                        Some("refusal") => {
1052                            if let Some(text) = part.get("refusal").and_then(Value::as_str) {
1053                                // Marked, so `Message::text` withholds it
1054                                // rather than presenting it as the answer.
1055                                contents.push(Content::Text(TextContent::refusal(text)));
1056                            }
1057                        }
1058                        _ => {}
1059                    }
1060                }
1061            }
1062        }
1063        // Foundry only — see `oauth_consent_content`. Upstream surfaced it
1064        // on the stream first and from the completed response later
1065        // (#8976); a non-streaming run that needed consent otherwise came
1066        // back as an empty answer with no way to learn why.
1067        Some("oauth_consent_request") => {
1068            contents.extend(oauth_consent_content(item));
1069        }
1070        Some("function_call") => {
1071            let call_id = item
1072                .get("call_id")
1073                .and_then(Value::as_str)
1074                .unwrap_or_default()
1075                .to_string();
1076            let name = item
1077                .get("name")
1078                .and_then(Value::as_str)
1079                .unwrap_or_default()
1080                .to_string();
1081            let args = item
1082                .get("arguments")
1083                .and_then(Value::as_str)
1084                .unwrap_or("{}")
1085                .to_string();
1086            contents.push(Content::FunctionCall(FunctionCallContent::new(
1087                call_id,
1088                name,
1089                Some(FunctionArguments::Raw(args)),
1090            )));
1091        }
1092        Some("reasoning") => {
1093            let summaries: Vec<String> = item
1094                .get("summary")
1095                .and_then(Value::as_array)
1096                .map(|arr| {
1097                    arr.iter()
1098                        .filter_map(|s| s.get("text").and_then(Value::as_str))
1099                        .map(str::to_string)
1100                        .collect()
1101                })
1102                .unwrap_or_default();
1103            // Preserve the raw reasoning item so a store:false tool-loop replay
1104            // can re-send it verbatim — reasoning models require the original
1105            // item (id + encrypted_content), not just the summary, on the
1106            // follow-up turn. `messages_to_input` re-emits it from
1107            // `raw_representation`; it is attached to exactly one content so a
1108            // multi-summary item yields exactly one reasoning input item.
1109            let raw = Some(item.clone());
1110            if summaries.is_empty() {
1111                // No summary (e.g. encrypted reasoning) — still carry the item.
1112                contents.push(Content::TextReasoning(TextReasoningContent {
1113                    text: String::new(),
1114                    annotations: None,
1115                    raw_representation: raw,
1116                    protected_data: None,
1117                }));
1118            } else {
1119                let n = summaries.len();
1120                for (i, text) in summaries.into_iter().enumerate() {
1121                    contents.push(Content::TextReasoning(TextReasoningContent {
1122                        text,
1123                        annotations: None,
1124                        raw_representation: (i == n - 1).then(|| raw.clone()).flatten(),
1125                        protected_data: None,
1126                    }));
1127                }
1128            }
1129        }
1130        // Code-interpreter runs surface `logs` as text and `image` outputs as
1131        // URIs; a bare `code` (no outputs) is a text fallback
1132        // (`_create_response_content:748-764`).
1133        Some("code_interpreter_call") => {
1134            let outputs = item
1135                .get("outputs")
1136                .and_then(Value::as_array)
1137                .filter(|a| !a.is_empty());
1138            if let Some(outputs) = outputs {
1139                for output in outputs {
1140                    match output.get("type").and_then(Value::as_str) {
1141                        Some("logs") => {
1142                            if let Some(logs) = output.get("logs").and_then(Value::as_str) {
1143                                contents.push(Content::Text(TextContent::new(logs)));
1144                            }
1145                        }
1146                        Some("image") => {
1147                            if let Some(url) = output.get("url").and_then(Value::as_str) {
1148                                contents.push(Content::Uri(UriContent {
1149                                    uri: url.to_string(),
1150                                    media_type: "image".to_string(),
1151                                }));
1152                            }
1153                        }
1154                        _ => {}
1155                    }
1156                }
1157            } else if let Some(code) = item.get("code").and_then(Value::as_str) {
1158                contents.push(Content::Text(TextContent::new(code)));
1159            }
1160        }
1161        // A generated image is returned as base64; default to image/png unless
1162        // the result is a data URI that states its own type
1163        // (`_create_response_content:788-811`).
1164        Some("image_generation_call") => {
1165            if let Some(result) = item.get("result").and_then(Value::as_str) {
1166                let (uri, media_type) = if result.starts_with("data:") {
1167                    let media_type = if result.contains(';') {
1168                        result
1169                            .strip_prefix("data:")
1170                            .and_then(|r| r.split(';').next())
1171                            .filter(|s| !s.is_empty())
1172                            .map(String::from)
1173                    } else {
1174                        None
1175                    };
1176                    (result.to_string(), media_type)
1177                } else {
1178                    (
1179                        format!("data:image/png;base64,{result}"),
1180                        Some("image/png".to_string()),
1181                    )
1182                };
1183                contents.push(Content::Data(DataContent { uri, media_type }));
1184            }
1185        }
1186        // An MCP approval request round-trips its `id` as the call id so a
1187        // later `FunctionApprovalResponse` refers back to it
1188        // (`_create_response_content:775-787`).
1189        Some("mcp_call") => contents.extend(mcp_call_item_contents(item)),
1190        Some("mcp_approval_request") => {
1191            let id = item
1192                .get("id")
1193                .and_then(Value::as_str)
1194                .unwrap_or_default()
1195                .to_string();
1196            let name = item
1197                .get("name")
1198                .and_then(Value::as_str)
1199                .unwrap_or_default()
1200                .to_string();
1201            let args = item
1202                .get("arguments")
1203                .and_then(Value::as_str)
1204                .unwrap_or("{}")
1205                .to_string();
1206            contents.push(Content::FunctionApprovalRequest(
1207                FunctionApprovalRequestContent {
1208                    id: id.clone(),
1209                    function_call: FunctionCallContent::new(
1210                        id,
1211                        name,
1212                        Some(FunctionArguments::Raw(args)),
1213                    ),
1214                },
1215            ));
1216        }
1217        _ => {}
1218    }
1219}
1220
1221/// Parse the `annotations` on an `output_text` part into [`Annotation`]s
1222/// (`_create_response_content:667-724`). The core annotation type has no free
1223/// `additional_properties`, so upstream's `index`/`container_id` extras are
1224/// dropped.
1225fn parse_annotations(part: &Value) -> Option<Vec<Annotation>> {
1226    let arr = part.get("annotations").and_then(Value::as_array)?;
1227    let mut out = Vec::new();
1228    for ann in arr {
1229        let str_field = |k: &str| ann.get(k).and_then(Value::as_str).map(String::from);
1230        let regions = || {
1231            Some(vec![TextSpanRegion {
1232                start_index: ann.get("start_index").and_then(Value::as_i64),
1233                end_index: ann.get("end_index").and_then(Value::as_i64),
1234            }])
1235        };
1236        match ann.get("type").and_then(Value::as_str) {
1237            Some("file_path") => out.push(Annotation {
1238                file_id: str_field("file_id"),
1239                ..Default::default()
1240            }),
1241            Some("file_citation") => out.push(Annotation {
1242                url: str_field("filename"),
1243                file_id: str_field("file_id"),
1244                ..Default::default()
1245            }),
1246            Some("url_citation") => out.push(Annotation {
1247                title: str_field("title"),
1248                url: str_field("url"),
1249                annotated_regions: regions(),
1250                ..Default::default()
1251            }),
1252            Some("container_file_citation") => out.push(Annotation {
1253                file_id: str_field("file_id"),
1254                url: str_field("filename"),
1255                annotated_regions: regions(),
1256                ..Default::default()
1257            }),
1258            _ => {}
1259        }
1260    }
1261    if out.is_empty() {
1262        None
1263    } else {
1264        Some(out)
1265    }
1266}
1267
1268fn finish_reason_from_response(value: &Value) -> Option<FinishReason> {
1269    let has_function_call = value
1270        .get("output")
1271        .and_then(Value::as_array)
1272        .map(|items| {
1273            items
1274                .iter()
1275                .any(|i| i.get("type").and_then(Value::as_str) == Some("function_call"))
1276        })
1277        .unwrap_or(false);
1278    if has_function_call {
1279        return Some(FinishReason::tool_calls());
1280    }
1281    let status = value.get("status").and_then(Value::as_str)?;
1282    Some(match status {
1283        "completed" => FinishReason::stop(),
1284        "incomplete" => match value
1285            .get("incomplete_details")
1286            .and_then(|d| d.get("reason"))
1287            .and_then(Value::as_str)
1288        {
1289            Some("max_output_tokens") => FinishReason::new(FinishReason::LENGTH),
1290            Some("content_filter") => FinishReason::new(FinishReason::CONTENT_FILTER),
1291            Some(other) => FinishReason::new(other),
1292            None => FinishReason::new("incomplete"),
1293        },
1294        other => FinishReason::new(other),
1295    })
1296}
1297
1298fn parse_responses_usage(usage: &Value) -> UsageDetails {
1299    let mut details = UsageDetails {
1300        input_token_count: usage.get("input_tokens").and_then(Value::as_u64),
1301        output_token_count: usage.get("output_tokens").and_then(Value::as_u64),
1302        total_token_count: usage.get("total_tokens").and_then(Value::as_u64),
1303        ..Default::default()
1304    };
1305    if let Some(cached) = usage
1306        .get("input_tokens_details")
1307        .and_then(|d| d.get("cached_tokens"))
1308        .and_then(Value::as_u64)
1309    {
1310        details
1311            .additional_counts
1312            .insert("openai.cached_input_tokens".into(), cached);
1313        // Mirror upstream: also surface as the typed, cross-language field.
1314        details.cache_read_input_token_count = Some(cached);
1315    }
1316    // Cache *writes* are reported separately from cache reads. Absent when the
1317    // provider does not report them (older API versions).
1318    if let Some(cache_write) = usage
1319        .get("input_tokens_details")
1320        .and_then(|d| d.get("cache_write_tokens"))
1321        .and_then(Value::as_u64)
1322    {
1323        details
1324            .additional_counts
1325            .insert("openai.cache_write_tokens".into(), cache_write);
1326        details.cache_creation_input_token_count = Some(cache_write);
1327    }
1328    if let Some(reasoning) = usage
1329        .get("output_tokens_details")
1330        .and_then(|d| d.get("reasoning_tokens"))
1331        .and_then(Value::as_u64)
1332    {
1333        details
1334            .additional_counts
1335            .insert("openai.reasoning_tokens".into(), reasoning);
1336        details.reasoning_output_token_count = Some(reasoning);
1337    }
1338    details
1339}
1340
1341// endregion
1342
1343// region: streaming
1344
1345/// Turn a Responses API SSE HTTP response into a stream of updates.
1346///
1347/// `pub` so `agent-framework-azure`'s Responses client can reuse this exact
1348/// SSE event parser (Azure OpenAI's Responses API streams the same event
1349/// shapes) rather than reimplementing it.
1350pub fn parse_responses_sse_stream(
1351    resp: reqwest::Response,
1352    store: Option<bool>,
1353) -> impl futures::Stream<Item = Result<ChatResponseUpdate>> + Send {
1354    let byte_stream: ByteStream = Box::pin(resp.bytes_stream());
1355    futures::stream::unfold(
1356        ResponsesSseState {
1357            byte_stream,
1358            buffer: String::new(),
1359            utf8: Utf8StreamDecoder::new(),
1360            queued: VecDeque::new(),
1361            call_ids: HashMap::new(),
1362            done: false,
1363            store,
1364        },
1365        |mut state| async move {
1366            loop {
1367                if let Some(update) = state.queued.pop_front() {
1368                    return Some((Ok(update), state));
1369                }
1370                if state.done {
1371                    return None;
1372                }
1373                match state.byte_stream.next().await {
1374                    Some(Ok(bytes)) => {
1375                        let decoded = state.utf8.push(&bytes);
1376                        state.buffer.push_str(&decoded);
1377                        while let Some(pos) = state.buffer.find('\n') {
1378                            let line = state.buffer[..pos].trim().to_string();
1379                            state.buffer.drain(..=pos);
1380                            let Some(data) = line.strip_prefix("data:") else {
1381                                continue;
1382                            };
1383                            let data = data.trim();
1384                            if data.is_empty() {
1385                                continue;
1386                            }
1387                            let Ok(value) = serde_json::from_str::<Value>(data) else {
1388                                continue;
1389                            };
1390                            match parse_responses_event(&value, &mut state.call_ids, state.store) {
1391                                EventOutcome::Update(update) => state.queued.push_back(update),
1392                                EventOutcome::Error(e) => {
1393                                    state.done = true;
1394                                    return Some((Err(e), state));
1395                                }
1396                                EventOutcome::None => {}
1397                            }
1398                        }
1399                    }
1400                    Some(Err(e)) => {
1401                        state.done = true;
1402                        return Some((Err(Error::service(format!("stream error: {e}"))), state));
1403                    }
1404                    None => return None,
1405                }
1406            }
1407        },
1408    )
1409}
1410
1411struct ResponsesSseState {
1412    byte_stream: ByteStream,
1413    buffer: String,
1414    utf8: Utf8StreamDecoder,
1415    queued: VecDeque<ChatResponseUpdate>,
1416    /// `output_index` -> `call_id`, resolved when the call is first announced
1417    /// via `response.output_item.added` and used to route later
1418    /// `response.function_call_arguments.delta` fragments.
1419    call_ids: HashMap<i64, String>,
1420    done: bool,
1421    store: Option<bool>,
1422}
1423
1424// A transient control-flow value: produced per SSE event and immediately
1425// destructured in the stream loop, never stored in bulk. Boxing the `Update`
1426// variant to equalize sizes would add a heap allocation on every streamed
1427// token, so the size skew is accepted here.
1428#[allow(clippy::large_enum_variant)]
1429enum EventOutcome {
1430    Update(ChatResponseUpdate),
1431    Error(Error),
1432    None,
1433}
1434
1435/// Wrap streamed reasoning text as a [`TextReasoningContent`] update, or
1436/// [`EventOutcome::None`] when empty.
1437fn reasoning_update(text: &str) -> EventOutcome {
1438    if text.is_empty() {
1439        return EventOutcome::None;
1440    }
1441    EventOutcome::Update(ChatResponseUpdate {
1442        contents: vec![Content::TextReasoning(TextReasoningContent {
1443            text: text.to_string(),
1444            annotations: None,
1445            ..Default::default()
1446        })],
1447        role: Some(Role::assistant()),
1448        ..Default::default()
1449    })
1450}
1451
1452/// Parse one Responses API SSE event (already-decoded JSON `data:` payload).
1453fn parse_responses_event(
1454    value: &Value,
1455    call_ids: &mut HashMap<i64, String>,
1456    store: Option<bool>,
1457) -> EventOutcome {
1458    let event_type = value.get("type").and_then(Value::as_str).unwrap_or("");
1459    match event_type {
1460        "response.created" => {
1461            let resp = value.get("response");
1462            let response_id = resp
1463                .and_then(|r| r.get("id"))
1464                .and_then(Value::as_str)
1465                .map(String::from);
1466            let model = resp
1467                .and_then(|r| r.get("model"))
1468                .and_then(Value::as_str)
1469                .map(String::from);
1470            if response_id.is_none() && model.is_none() {
1471                return EventOutcome::None;
1472            }
1473            EventOutcome::Update(ChatResponseUpdate {
1474                role: Some(Role::assistant()),
1475                response_id,
1476                model,
1477                ..Default::default()
1478            })
1479        }
1480        "response.output_text.delta" => {
1481            let text = value.get("delta").and_then(Value::as_str).unwrap_or("");
1482            if text.is_empty() {
1483                return EventOutcome::None;
1484            }
1485            EventOutcome::Update(ChatResponseUpdate {
1486                contents: vec![Content::Text(TextContent::new(text))],
1487                role: Some(Role::assistant()),
1488                ..Default::default()
1489            })
1490        }
1491        // A refusal streams on its own channel. Only the incremental `.delta`
1492        // is consumed: the terminal `response.refusal.done` repeats the whole
1493        // refusal, which aggregation would append to the fragments already
1494        // collected, doubling it — the same reason the text channel above
1495        // does not consume its `.done`. Dropping these events entirely, as
1496        // this parser used to, let a streamed decline reach the caller as an
1497        // empty response.
1498        "response.refusal.delta" => {
1499            let text = value.get("delta").and_then(Value::as_str).unwrap_or("");
1500            if text.is_empty() {
1501                return EventOutcome::None;
1502            }
1503            EventOutcome::Update(ChatResponseUpdate {
1504                contents: vec![Content::Text(TextContent::refusal(text))],
1505                role: Some(Role::assistant()),
1506                ..Default::default()
1507            })
1508        }
1509        // Reasoning (chain-of-thought / summary) streams as its own text
1510        // channel. Both the incremental `.delta` and the terminal `.done`
1511        // (full text) map to `TextReasoningContent`, mirroring upstream
1512        // `_create_streaming_response_content` (`_responses_client.py:917-928`).
1513        "response.reasoning_text.delta" | "response.reasoning_summary_text.delta" => {
1514            reasoning_update(value.get("delta").and_then(Value::as_str).unwrap_or(""))
1515        }
1516        // `.done` carries the *full* completed text, not another increment —
1517        // the deltas above already streamed it, so emitting it again would
1518        // duplicate the reasoning in the aggregated response (adjacent
1519        // reasoning contents coalesce by appending). Treated as terminal
1520        // metadata, like `response.output_text.done`.
1521        "response.reasoning_text.done" | "response.reasoning_summary_text.done" => {
1522            EventOutcome::None
1523        }
1524        "response.output_item.added" => {
1525            let item = value.get("item");
1526            let item_type = item.and_then(|i| i.get("type")).and_then(Value::as_str);
1527            // A consent request is complete the moment it is added — it
1528            // has no deltas to wait for, and the run is blocked on the
1529            // user until it is answered, so holding it back to `done`
1530            // would be holding back the one thing the caller needs.
1531            if item_type == Some("oauth_consent_request") {
1532                return match item.and_then(oauth_consent_content) {
1533                    Some(content) => EventOutcome::Update(ChatResponseUpdate {
1534                        contents: vec![content],
1535                        role: Some(Role::assistant()),
1536                        ..Default::default()
1537                    }),
1538                    None => EventOutcome::None,
1539                };
1540            }
1541            // A hosted MCP call is emitted whole from `done` (below): on
1542            // `added` its arguments are still empty and only stream in
1543            // through `response.mcp_call_arguments.*`, so a call recorded
1544            // here would replay with `{}` arguments.
1545            if item_type != Some("function_call") {
1546                return EventOutcome::None;
1547            }
1548            let output_index = value
1549                .get("output_index")
1550                .and_then(Value::as_i64)
1551                .unwrap_or(0);
1552            let call_id = item
1553                .and_then(|i| i.get("call_id"))
1554                .and_then(Value::as_str)
1555                .unwrap_or_default()
1556                .to_string();
1557            let name = item
1558                .and_then(|i| i.get("name"))
1559                .and_then(Value::as_str)
1560                .unwrap_or_default()
1561                .to_string();
1562            call_ids.insert(output_index, call_id.clone());
1563            EventOutcome::Update(ChatResponseUpdate {
1564                contents: vec![Content::FunctionCall(FunctionCallContent::new(
1565                    call_id, name, None,
1566                ))],
1567                role: Some(Role::assistant()),
1568                ..Default::default()
1569            })
1570        }
1571        // Foundry also emits the consent request as a top-level event
1572        // rather than an output item, carrying the link on the event
1573        // itself. Same content either way.
1574        "response.oauth_consent_requested" => match oauth_consent_content(value) {
1575            Some(content) => EventOutcome::Update(ChatResponseUpdate {
1576                contents: vec![content],
1577                role: Some(Role::assistant()),
1578                ..Default::default()
1579            }),
1580            None => EventOutcome::None,
1581        },
1582        "response.function_call_arguments.delta" => {
1583            let output_index = value
1584                .get("output_index")
1585                .and_then(Value::as_i64)
1586                .unwrap_or(0);
1587            let delta = value.get("delta").and_then(Value::as_str).unwrap_or("");
1588            match call_ids.get(&output_index) {
1589                Some(call_id) => EventOutcome::Update(ChatResponseUpdate {
1590                    contents: vec![Content::FunctionCall(FunctionCallContent::new(
1591                        call_id.clone(),
1592                        "",
1593                        Some(FunctionArguments::Raw(delta.to_string())),
1594                    ))],
1595                    role: Some(Role::assistant()),
1596                    ..Default::default()
1597                }),
1598                None => EventOutcome::None,
1599            }
1600        }
1601        // `response.incomplete` is the terminal event for a turn cut off by
1602        // the content filter or the token budget — the same payload as
1603        // `response.completed`, under a name that says it did not finish.
1604        // Handled here rather than ignored, or a truncated or filtered
1605        // stream would lose its finish reason, usage and response id
1606        // entirely, which is exactly the information the distinct event
1607        // name exists to deliver.
1608        "response.completed" | "response.incomplete" => {
1609            let resp = value.get("response");
1610            let response_id = resp
1611                .and_then(|r| r.get("id"))
1612                .and_then(Value::as_str)
1613                .map(String::from);
1614            let model = resp
1615                .and_then(|r| r.get("model"))
1616                .and_then(Value::as_str)
1617                .map(String::from);
1618            let mut contents = Vec::new();
1619            if let Some(usage) = resp.and_then(|r| r.get("usage")) {
1620                contents.push(Content::Usage(UsageContent {
1621                    details: parse_responses_usage(usage),
1622                }));
1623            }
1624            let finish_reason = resp.and_then(finish_reason_from_response);
1625            let conversation_id = if store != Some(false) {
1626                response_id.clone()
1627            } else {
1628                None
1629            };
1630            EventOutcome::Update(ChatResponseUpdate {
1631                contents,
1632                role: Some(Role::assistant()),
1633                response_id,
1634                model,
1635                conversation_id,
1636                finish_reason,
1637                ..Default::default()
1638            })
1639        }
1640        "response.failed" | "error" => {
1641            let resp = value.get("response");
1642            let err_obj = resp
1643                .and_then(|r| r.get("error"))
1644                .or_else(|| value.get("error"));
1645            let msg = err_obj
1646                .and_then(|e| e.get("message"))
1647                .and_then(Value::as_str)
1648                .unwrap_or("response failed")
1649                .to_string();
1650            // Same classification as the non-streaming `response_failure_error`
1651            // so callers branching on content filters see one behavior for
1652            // streamed and non-streamed Responses.
1653            let code = err_obj.and_then(|e| e.get("code")).and_then(Value::as_str);
1654            EventOutcome::Error(match code {
1655                Some("content_filter") => Error::service_content_filter(msg),
1656                _ => Error::service(msg),
1657            })
1658        }
1659        "response.output_item.done" => {
1660            let Some(item) = value
1661                .get("item")
1662                .filter(|i| i.get("type").and_then(Value::as_str) == Some("mcp_call"))
1663            else {
1664                return EventOutcome::None;
1665            };
1666            // The completed item carries the final arguments and the
1667            // output or error, so the call and its result come from here.
1668            EventOutcome::Update(ChatResponseUpdate {
1669                contents: mcp_call_item_contents(item),
1670                role: Some(Role::assistant()),
1671                ..Default::default()
1672            })
1673        }
1674        // Recognized but carry no additional content: the arguments are
1675        // already fully accumulated via `.delta` events, and item/part
1676        // lifecycle markers don't themselves map to a `Content`.
1677        "response.function_call_arguments.done"
1678        | "response.mcp_call_arguments.delta"
1679        | "response.mcp_call_arguments.done"
1680        | "response.content_part.added"
1681        | "response.content_part.done"
1682        | "response.in_progress" => EventOutcome::None,
1683        _ => EventOutcome::None,
1684    }
1685}
1686
1687// endregion
1688
1689#[cfg(test)]
1690mod tests {
1691    use super::*;
1692
1693    #[test]
1694    fn service_url_reports_the_configured_base_url() {
1695        // Read by the observability layer as `server.address` (#9225, #9222).
1696        let client =
1697            OpenAIChatClient::new("k", "gpt-4o-mini").with_base_url("http://gateway.example/v1");
1698        assert_eq!(client.service_url(), Some("http://gateway.example/v1"));
1699    }
1700    use agent_framework_core::tools::{ApprovalMode, ToolDefinition, ToolKind};
1701    use agent_framework_core::types::{
1702        FunctionApprovalResponseContent, FunctionResultContent, HostedFileContent,
1703    };
1704
1705    fn user(text: &str) -> Message {
1706        Message::user(text)
1707    }
1708
1709    fn user_with(contents: Vec<Content>) -> Message {
1710        Message::with_contents(Role::user(), contents)
1711    }
1712
1713    /// Parse a single Responses output item into its content list.
1714    fn parse_item(item: Value) -> Vec<Content> {
1715        let mut contents = Vec::new();
1716        parse_output_item(&item, &mut contents);
1717        contents
1718    }
1719
1720    fn client() -> OpenAIChatClient {
1721        OpenAIChatClient::new("test-key", "gpt-4o-mini")
1722    }
1723
1724    // region: request body building
1725
1726    #[test]
1727    fn build_body_simple_text() {
1728        let c = client();
1729        let body = c.build_body(&[user("Hello there")], &ChatOptions::new(), false);
1730        assert_eq!(
1731            body,
1732            json!({
1733                "model": "gpt-4o-mini",
1734                "input": [
1735                    { "type": "message", "role": "user", "content": [
1736                        { "type": "input_text", "text": "Hello there" }
1737                    ]}
1738                ],
1739                // Nothing is stored service-side on this request, so the
1740                // encrypted reasoning item is requested for the replay path.
1741                "include": ["reasoning.encrypted_content"],
1742            })
1743        );
1744    }
1745
1746    #[test]
1747    fn responses_usage_parses_cache_write_tokens() {
1748        // Cache *writes* are reported separately from cache reads (upstream #7369).
1749        let d = parse_responses_usage(&json!({
1750            "input_tokens": 2000,
1751            "output_tokens": 60,
1752            "total_tokens": 2060,
1753            "input_tokens_details": { "cached_tokens": 0, "cache_write_tokens": 1024 },
1754        }));
1755        assert_eq!(d.cache_creation_input_token_count, Some(1024));
1756        assert_eq!(d.cache_read_input_token_count, Some(0));
1757        assert_eq!(
1758            d.additional_counts.get("openai.cache_write_tokens"),
1759            Some(&1024)
1760        );
1761    }
1762
1763    #[test]
1764    fn responses_usage_omits_cache_write_tokens_when_not_reported() {
1765        let d = parse_responses_usage(&json!({
1766            "input_tokens": 100,
1767            "output_tokens": 20,
1768            "input_tokens_details": { "cached_tokens": 40 },
1769        }));
1770        assert_eq!(d.cache_creation_input_token_count, None);
1771        assert!(!d
1772            .additional_counts
1773            .contains_key("openai.cache_write_tokens"));
1774    }
1775
1776    #[test]
1777    fn build_body_extracts_leading_system_message_as_instructions() {
1778        let c = client();
1779        let messages = vec![Message::system("Be terse."), user("Hi")];
1780        let body = c.build_body(&messages, &ChatOptions::new(), false);
1781        assert_eq!(body["instructions"], json!("Be terse."));
1782        assert_eq!(
1783            body["input"],
1784            json!([
1785                { "type": "message", "role": "user", "content": [
1786                    { "type": "input_text", "text": "Hi" }
1787                ]}
1788            ])
1789        );
1790    }
1791
1792    #[test]
1793    fn build_body_combines_options_instructions_and_system_message() {
1794        let c = client();
1795        let messages = vec![Message::system("Also be nice."), user("Hi")];
1796        let options = ChatOptions::new().with_instructions("Be terse.");
1797        let body = c.build_body(&messages, &options, false);
1798        assert_eq!(body["instructions"], json!("Be terse.\n\nAlso be nice."));
1799    }
1800
1801    #[test]
1802    fn build_body_assistant_text_uses_output_text_type() {
1803        let c = client();
1804        let messages = vec![user("Hi"), Message::assistant("Hello!")];
1805        let body = c.build_body(&messages, &ChatOptions::new(), false);
1806        assert_eq!(
1807            body["input"][1],
1808            json!({ "type": "message", "role": "assistant", "content": [
1809                { "type": "output_text", "text": "Hello!" }
1810            ]})
1811        );
1812    }
1813
1814    #[test]
1815    fn build_body_function_call_round_trip() {
1816        let c = client();
1817        let call = FunctionCallContent::new(
1818            "call_1",
1819            "get_weather",
1820            Some(FunctionArguments::Raw(r#"{"city":"Paris"}"#.to_string())),
1821        );
1822        let assistant_msg =
1823            Message::with_contents(Role::assistant(), vec![Content::FunctionCall(call)]);
1824        let tool_msg = Message::with_contents(
1825            Role::tool(),
1826            vec![Content::FunctionResult(FunctionResultContent::new(
1827                "call_1",
1828                Some(json!("18C and sunny")),
1829            ))],
1830        );
1831        let body = c.build_body(
1832            &[user("weather?"), assistant_msg, tool_msg],
1833            &ChatOptions::new(),
1834            false,
1835        );
1836        assert_eq!(
1837            body["input"],
1838            json!([
1839                { "type": "message", "role": "user", "content": [
1840                    { "type": "input_text", "text": "weather?" }
1841                ]},
1842                { "type": "function_call", "call_id": "call_1", "name": "get_weather", "arguments": "{\"city\":\"Paris\"}" },
1843                { "type": "function_call_output", "call_id": "call_1", "output": "18C and sunny" },
1844            ])
1845        );
1846    }
1847
1848    #[test]
1849    fn build_body_tools_are_flat_not_nested() {
1850        let c = client();
1851        let tool = ToolDefinition {
1852            name: "get_weather".into(),
1853            description: "Get the weather".into(),
1854            parameters: json!({ "type": "object", "properties": {} }),
1855            kind: ToolKind::Function,
1856            approval_mode: ApprovalMode::NeverRequire,
1857            executor: None,
1858        };
1859        let options = ChatOptions::new().with_tool(tool);
1860        let body = c.build_body(&[user("hi")], &options, false);
1861        assert_eq!(
1862            body["tools"],
1863            json!([{
1864                "type": "function",
1865                "name": "get_weather",
1866                "description": "Get the weather",
1867                "parameters": { "type": "object", "properties": {} },
1868            }])
1869        );
1870    }
1871
1872    #[test]
1873    fn build_body_tool_choice_required_named() {
1874        let c = client();
1875        let options =
1876            ChatOptions::new().with_tool_choice(ToolMode::Required(Some("get_weather".into())));
1877        let body = c.build_body(&[user("hi")], &options, false);
1878        assert_eq!(
1879            body["tool_choice"],
1880            json!({ "type": "function", "name": "get_weather" })
1881        );
1882    }
1883
1884    #[test]
1885    fn stateless_request_asks_for_the_encrypted_reasoning_item() {
1886        // A reasoning item is only replayable on the next turn if it carries
1887        // `encrypted_content`, and the service only returns that when asked.
1888        let c = client();
1889        let body = c.build_body(&[user("hi")], &ChatOptions::new(), false);
1890        assert_eq!(body["include"], json!(["reasoning.encrypted_content"]));
1891    }
1892
1893    #[test]
1894    fn a_service_side_conversation_needs_no_encrypted_reasoning() {
1895        // The service already holds the reasoning item, so echoing it back is
1896        // pointless — and upstream keys this off the storage indicators, not
1897        // off `store`.
1898        let mut options = ChatOptions::new();
1899        options.conversation_id = Some("resp_abc123".into());
1900        let body = client().build_body(&[user("hi")], &options, false);
1901        assert!(
1902            body.get("include").is_none(),
1903            "no include expected, got: {}",
1904            body
1905        );
1906    }
1907
1908    #[test]
1909    fn an_empty_conversation_id_is_not_service_side_storage() {
1910        // An empty id is no id: it would not continue anything server-side, so
1911        // the request is still stateless and still needs the item echoed back.
1912        let mut options = ChatOptions::new();
1913        options.conversation_id = Some(String::new());
1914        let body = client().build_body(&[user("hi")], &options, false);
1915        assert_eq!(body["include"], json!(["reasoning.encrypted_content"]));
1916    }
1917
1918    #[test]
1919    fn a_callers_own_include_entries_survive_and_are_not_duplicated() {
1920        // The caller's entries are preserved alongside the implicit one...
1921        let mut options = ChatOptions::new();
1922        options
1923            .additional_properties
1924            .insert("include".into(), json!(["file_search_call.results"]));
1925        let body = client().build_body(&[user("hi")], &options, false);
1926        assert_eq!(
1927            body["include"],
1928            json!(["file_search_call.results", "reasoning.encrypted_content"])
1929        );
1930
1931        // ...and asking for the encrypted item by name does not get it twice.
1932        let mut options = ChatOptions::new();
1933        options
1934            .additional_properties
1935            .insert("include".into(), json!(["reasoning.encrypted_content"]));
1936        let body = client().build_body(&[user("hi")], &options, false);
1937        assert_eq!(body["include"], json!(["reasoning.encrypted_content"]));
1938    }
1939
1940    #[test]
1941    fn an_explicit_empty_include_is_omitted_not_sent_as_an_empty_array() {
1942        // `responses_include` drops an empty array, and the
1943        // `additional_properties` pass must not put it back: `include` is
1944        // that function's alone. Reached here via a stored conversation, which
1945        // suppresses the implicit entry that would otherwise fill the array.
1946        let mut options = ChatOptions::new();
1947        options.conversation_id = Some("resp_abc123".into());
1948        options
1949            .additional_properties
1950            .insert("include".into(), json!([]));
1951        let body = client().build_body(&[user("hi")], &options, false);
1952        assert!(
1953            body.get("include").is_none(),
1954            "an empty include should be omitted entirely, got: {}",
1955            body
1956        );
1957    }
1958
1959    #[test]
1960    fn other_additional_properties_still_pass_through() {
1961        // Only `include` is intercepted; everything else the caller sets still
1962        // reaches the body.
1963        let mut options = ChatOptions::new();
1964        options
1965            .additional_properties
1966            .insert("safety_identifier".into(), json!("user-123"));
1967        let body = client().build_body(&[user("hi")], &options, false);
1968        assert_eq!(body["safety_identifier"], json!("user-123"));
1969    }
1970
1971    #[test]
1972    fn build_body_conversation_id_becomes_previous_response_id() {
1973        let c = client();
1974        let mut options = ChatOptions::new();
1975        options.conversation_id = Some("resp_abc123".into());
1976        let body = c.build_body(&[user("hi")], &options, false);
1977        assert_eq!(body["previous_response_id"], json!("resp_abc123"));
1978    }
1979
1980    #[test]
1981    fn build_body_max_tokens_becomes_max_output_tokens() {
1982        let c = client();
1983        let options = ChatOptions::new().with_max_tokens(256);
1984        let body = c.build_body(&[user("hi")], &options, false);
1985        assert_eq!(body["max_output_tokens"], json!(256));
1986        assert!(body.get("max_tokens").is_none());
1987    }
1988
1989    #[test]
1990    fn build_body_response_format_becomes_text_format() {
1991        let c = client();
1992        let mut options = ChatOptions::new();
1993        options.response_format = Some(ResponseFormat::JsonSchema {
1994            name: "answer".into(),
1995            description: None,
1996            schema: json!({"type": "object"}),
1997            strict: Some(true),
1998        });
1999        let body = c.build_body(&[user("hi")], &options, false);
2000        assert_eq!(
2001            body["text"]["format"],
2002            json!({ "type": "json_schema", "name": "answer", "schema": {"type": "object"}, "strict": true })
2003        );
2004    }
2005
2006    #[test]
2007    fn build_body_stream_flag() {
2008        let c = client();
2009        let body = c.build_body(&[user("hi")], &ChatOptions::new(), true);
2010        assert_eq!(body["stream"], json!(true));
2011    }
2012
2013    // endregion
2014
2015    // region: response parsing
2016
2017    #[test]
2018    fn parse_response_text_and_usage() {
2019        let value = json!({
2020            "id": "resp_123",
2021            "model": "gpt-4o-mini",
2022            "status": "completed",
2023            "output": [
2024                { "type": "message", "role": "assistant", "content": [
2025                    { "type": "output_text", "text": "Hello!" }
2026                ]}
2027            ],
2028            "usage": { "input_tokens": 10, "output_tokens": 5, "total_tokens": 15 },
2029        });
2030        let resp = parse_response(&value, None);
2031        assert_eq!(resp.response_id.as_deref(), Some("resp_123"));
2032        assert_eq!(resp.conversation_id.as_deref(), Some("resp_123"));
2033        assert_eq!(resp.text(), "Hello!");
2034        assert_eq!(resp.finish_reason, Some(FinishReason::stop()));
2035        let usage = resp.usage_details.unwrap();
2036        assert_eq!(usage.input_token_count, Some(10));
2037        assert_eq!(usage.output_token_count, Some(5));
2038        assert_eq!(usage.total_token_count, Some(15));
2039    }
2040
2041    #[test]
2042    fn parse_response_store_false_omits_conversation_id() {
2043        let value = json!({
2044            "id": "resp_123",
2045            "status": "completed",
2046            "output": [],
2047        });
2048        let resp = parse_response(&value, Some(false));
2049        assert_eq!(resp.conversation_id, None);
2050    }
2051
2052    #[test]
2053    fn parse_response_function_call_sets_tool_calls_finish_reason() {
2054        let value = json!({
2055            "id": "resp_123",
2056            "status": "completed",
2057            "output": [
2058                { "type": "function_call", "call_id": "call_1", "name": "get_weather", "arguments": "{\"city\":\"Paris\"}" }
2059            ],
2060        });
2061        let resp = parse_response(&value, None);
2062        assert_eq!(resp.finish_reason, Some(FinishReason::tool_calls()));
2063        let calls = resp.function_calls();
2064        assert_eq!(calls.len(), 1);
2065        assert_eq!(calls[0].call_id, "call_1");
2066        assert_eq!(calls[0].name, "get_weather");
2067    }
2068
2069    #[test]
2070    fn parse_response_incomplete_max_output_tokens_is_length() {
2071        let value = json!({
2072            "id": "resp_123",
2073            "status": "incomplete",
2074            "incomplete_details": { "reason": "max_output_tokens" },
2075            "output": [],
2076        });
2077        let resp = parse_response(&value, None);
2078        assert_eq!(
2079            resp.finish_reason,
2080            Some(FinishReason::new(FinishReason::LENGTH))
2081        );
2082    }
2083
2084    /// `response.incomplete` is the terminal event for a stream cut off by
2085    /// the content filter or the token budget. Ignoring it — which this
2086    /// did — dropped the finish reason, usage and response id for exactly
2087    /// the streams whose distinct event name exists to report them, and
2088    /// left a client unable to tell a truncated answer from a complete one.
2089    #[test]
2090    fn a_streamed_response_incomplete_carries_its_terminal_metadata() {
2091        let mut call_ids = HashMap::new();
2092        let event = json!({
2093            "type": "response.incomplete",
2094            "response": {
2095                "id": "resp_123",
2096                "model": "gpt-4o",
2097                "status": "incomplete",
2098                "incomplete_details": { "reason": "content_filter" },
2099                "output": [],
2100                "usage": { "input_tokens": 3, "output_tokens": 5, "total_tokens": 8 },
2101            },
2102        });
2103        let EventOutcome::Update(update) = parse_responses_event(&event, &mut call_ids, None)
2104        else {
2105            panic!("response.incomplete must produce a terminal update");
2106        };
2107        assert_eq!(
2108            update.finish_reason,
2109            Some(FinishReason::new(FinishReason::CONTENT_FILTER))
2110        );
2111        assert_eq!(update.response_id.as_deref(), Some("resp_123"));
2112        assert_eq!(update.model.as_deref(), Some("gpt-4o"));
2113        let usage = update
2114            .contents
2115            .iter()
2116            .find_map(|c| match c {
2117                Content::Usage(u) => Some(&u.details),
2118                _ => None,
2119            })
2120            .expect("usage rides the terminal update");
2121        assert_eq!(usage.input_token_count, Some(3));
2122        assert_eq!(usage.output_token_count, Some(5));
2123    }
2124
2125    /// And a `response.completed` is unchanged by sharing the arm.
2126    #[test]
2127    fn a_streamed_response_completed_still_carries_its_metadata() {
2128        let mut call_ids = HashMap::new();
2129        let event = json!({
2130            "type": "response.completed",
2131            "response": {
2132                "id": "resp_456",
2133                "status": "completed",
2134                "output": [],
2135            },
2136        });
2137        let EventOutcome::Update(update) = parse_responses_event(&event, &mut call_ids, None)
2138        else {
2139            panic!("response.completed produces a terminal update");
2140        };
2141        assert_eq!(update.finish_reason, Some(FinishReason::stop()));
2142        assert_eq!(update.response_id.as_deref(), Some("resp_456"));
2143    }
2144
2145    #[test]
2146    fn parse_response_reasoning_becomes_text_reasoning() {
2147        let value = json!({
2148            "id": "resp_123",
2149            "status": "completed",
2150            "output": [
2151                { "type": "reasoning", "summary": [{ "type": "summary_text", "text": "thinking..." }] },
2152                { "type": "message", "role": "assistant", "content": [{ "type": "output_text", "text": "done" }] },
2153            ],
2154        });
2155        let resp = parse_response(&value, None);
2156        let contents = &resp.messages[0].contents;
2157        assert!(matches!(&contents[0], Content::TextReasoning(t) if t.text == "thinking..."));
2158        assert!(matches!(&contents[1], Content::Text(t) if t.text == "done"));
2159    }
2160
2161    #[test]
2162    fn reasoning_item_round_trips_through_input_for_store_false_replay() {
2163        // A store:false tool-loop replay must re-send the original reasoning
2164        // item (id + encrypted_content), not just its summary text.
2165        let reasoning_item = json!({
2166            "type": "reasoning",
2167            "id": "rs_abc",
2168            "encrypted_content": "ENC",
2169            "summary": [{ "type": "summary_text", "text": "thinking..." }],
2170        });
2171        let value = json!({
2172            "id": "resp_1",
2173            "status": "completed",
2174            "output": [
2175                reasoning_item,
2176                { "type": "function_call", "call_id": "c1", "name": "f", "arguments": "{}" },
2177            ],
2178        });
2179        let resp = parse_response(&value, Some(false));
2180        // The parsed reasoning content preserves the raw item.
2181        let reasoning = resp.messages[0]
2182            .contents
2183            .iter()
2184            .find_map(|c| match c {
2185                Content::TextReasoning(t) => Some(t),
2186                _ => None,
2187            })
2188            .expect("reasoning content");
2189        assert_eq!(
2190            reasoning.raw_representation.as_ref().unwrap()["id"],
2191            "rs_abc"
2192        );
2193
2194        // Replaying that assistant message back through the input mapper
2195        // re-emits the reasoning item verbatim, ahead of the function call.
2196        let input = messages_to_input(&resp.messages);
2197        let reasoning_pos = input
2198            .iter()
2199            .position(|i| i.get("type") == Some(&json!("reasoning")))
2200            .expect("reasoning item re-emitted");
2201        assert_eq!(input[reasoning_pos]["id"], "rs_abc");
2202        assert_eq!(input[reasoning_pos]["encrypted_content"], "ENC");
2203        let call_pos = input
2204            .iter()
2205            .position(|i| i.get("type") == Some(&json!("function_call")))
2206            .expect("function call present");
2207        assert!(reasoning_pos < call_pos, "reasoning must precede the call");
2208    }
2209
2210    #[test]
2211    fn summary_only_reasoning_is_not_re_emitted_as_input() {
2212        // A reasoning content with no preserved raw item (e.g. from streaming
2213        // display) has no valid input form and must be dropped, not sent as a
2214        // bogus reasoning item lacking id/encrypted_content.
2215        let msg = Message::with_contents(
2216            Role::assistant(),
2217            vec![Content::TextReasoning(TextReasoningContent {
2218                text: "just display".into(),
2219                annotations: None,
2220                raw_representation: None,
2221                protected_data: None,
2222            })],
2223        );
2224        let input = messages_to_input(&[msg]);
2225        assert!(input
2226            .iter()
2227            .all(|i| i.get("type") != Some(&json!("reasoning"))));
2228    }
2229
2230    // endregion
2231
2232    // region: streaming
2233
2234    fn sse_body(events: &[(&str, Value)]) -> String {
2235        let mut out = String::new();
2236        for (event, data) in events {
2237            out.push_str(&format!("event: {event}\ndata: {}\n\n", data));
2238        }
2239        out
2240    }
2241
2242    async fn collect_updates(text: String) -> Vec<ChatResponseUpdate> {
2243        // Build a fake reqwest::Response backed by the given SSE text using a
2244        // tiny local HTTP server would be overkill; instead we drive the
2245        // event parser directly through the same state machine by feeding
2246        // the byte stream via `futures::stream::once`.
2247        let stream =
2248            futures::stream::once(async move { Ok::<_, reqwest::Error>(bytes::Bytes::from(text)) });
2249        let byte_stream: ByteStream = Box::pin(stream);
2250        let mut state = ResponsesSseState {
2251            byte_stream,
2252            buffer: String::new(),
2253            utf8: Utf8StreamDecoder::new(),
2254            queued: VecDeque::new(),
2255            call_ids: HashMap::new(),
2256            done: false,
2257            store: None,
2258        };
2259        let mut updates = Vec::new();
2260        // Drain the single chunk manually (mirrors the real unfold body).
2261        if let Some(Ok(bytes)) = state.byte_stream.next().await {
2262            let decoded = state.utf8.push(&bytes);
2263            state.buffer.push_str(&decoded);
2264            while let Some(pos) = state.buffer.find('\n') {
2265                let line = state.buffer[..pos].trim().to_string();
2266                state.buffer.drain(..=pos);
2267                let Some(data) = line.strip_prefix("data:") else {
2268                    continue;
2269                };
2270                let data = data.trim();
2271                if data.is_empty() {
2272                    continue;
2273                }
2274                let value: Value = serde_json::from_str(data).unwrap();
2275                if let EventOutcome::Update(u) =
2276                    parse_responses_event(&value, &mut state.call_ids, state.store)
2277                {
2278                    updates.push(u);
2279                }
2280            }
2281        }
2282        updates
2283    }
2284
2285    #[tokio::test]
2286    async fn stream_text_only_accumulates() {
2287        let text = sse_body(&[
2288            (
2289                "response.created",
2290                json!({ "type": "response.created", "response": { "id": "resp_1", "model": "gpt-4o-mini" } }),
2291            ),
2292            (
2293                "response.output_text.delta",
2294                json!({ "type": "response.output_text.delta", "delta": "Hel" }),
2295            ),
2296            (
2297                "response.output_text.delta",
2298                json!({ "type": "response.output_text.delta", "delta": "lo!" }),
2299            ),
2300            (
2301                "response.completed",
2302                json!({ "type": "response.completed", "response": { "id": "resp_1", "model": "gpt-4o-mini", "status": "completed", "output": [], "usage": { "input_tokens": 3, "output_tokens": 2 } } }),
2303            ),
2304        ]);
2305        let updates = collect_updates(text).await;
2306        let resp = ChatResponse::from_updates(updates);
2307        assert_eq!(resp.text(), "Hello!");
2308        assert_eq!(resp.response_id.as_deref(), Some("resp_1"));
2309        assert_eq!(resp.finish_reason, Some(FinishReason::stop()));
2310        let usage = resp.usage_details.unwrap();
2311        assert_eq!(usage.input_token_count, Some(3));
2312        assert_eq!(usage.output_token_count, Some(2));
2313    }
2314
2315    #[tokio::test]
2316    async fn stream_tool_call_accumulates_arguments() {
2317        let text = sse_body(&[
2318            (
2319                "response.output_item.added",
2320                json!({ "type": "response.output_item.added", "output_index": 0, "item": { "type": "function_call", "call_id": "call_1", "name": "get_weather" } }),
2321            ),
2322            (
2323                "response.function_call_arguments.delta",
2324                json!({ "type": "response.function_call_arguments.delta", "output_index": 0, "delta": "{\"city\":" }),
2325            ),
2326            (
2327                "response.function_call_arguments.delta",
2328                json!({ "type": "response.function_call_arguments.delta", "output_index": 0, "delta": "\"Paris\"}" }),
2329            ),
2330            (
2331                "response.completed",
2332                json!({ "type": "response.completed", "response": { "id": "resp_2", "status": "completed", "output": [{"type":"function_call","call_id":"call_1","name":"get_weather","arguments":"{\"city\":\"Paris\"}"}] } }),
2333            ),
2334        ]);
2335        let updates = collect_updates(text).await;
2336        let resp = ChatResponse::from_updates(updates);
2337        let calls = resp.function_calls();
2338        assert_eq!(calls.len(), 1);
2339        assert_eq!(calls[0].call_id, "call_1");
2340        assert_eq!(calls[0].name, "get_weather");
2341        assert_eq!(
2342            calls[0].parse_arguments().unwrap().get("city").unwrap(),
2343            &json!("Paris")
2344        );
2345        assert_eq!(resp.finish_reason, Some(FinishReason::tool_calls()));
2346    }
2347
2348    #[tokio::test]
2349    async fn stream_failed_event_is_error() {
2350        let text = sse_body(&[(
2351            "response.failed",
2352            json!({ "type": "response.failed", "response": { "error": { "message": "boom" } } }),
2353        )]);
2354        let stream =
2355            futures::stream::once(async move { Ok::<_, reqwest::Error>(bytes::Bytes::from(text)) });
2356        let byte_stream: ByteStream = Box::pin(stream);
2357        let mut state = ResponsesSseState {
2358            byte_stream,
2359            buffer: String::new(),
2360            utf8: Utf8StreamDecoder::new(),
2361            queued: VecDeque::new(),
2362            call_ids: HashMap::new(),
2363            done: false,
2364            store: None,
2365        };
2366        let bytes = state.byte_stream.next().await.unwrap().unwrap();
2367        let decoded = state.utf8.push(&bytes);
2368        state.buffer.push_str(&decoded);
2369        let mut saw_error = false;
2370        while let Some(pos) = state.buffer.find('\n') {
2371            let line = state.buffer[..pos].trim().to_string();
2372            state.buffer.drain(..=pos);
2373            let Some(data) = line.strip_prefix("data:") else {
2374                continue;
2375            };
2376            let data = data.trim();
2377            if data.is_empty() {
2378                continue;
2379            }
2380            let value: Value = serde_json::from_str(data).unwrap();
2381            if let EventOutcome::Error(e) =
2382                parse_responses_event(&value, &mut state.call_ids, state.store)
2383            {
2384                assert!(e.to_string().contains("boom"));
2385                saw_error = true;
2386            }
2387        }
2388        assert!(
2389            saw_error,
2390            "expected a response.failed event to surface an error"
2391        );
2392    }
2393
2394    #[test]
2395    fn stream_failed_event_classifies_content_filter() {
2396        // Streamed and non-streamed Responses failures must classify alike
2397        // (mirrors `response_failure_error`).
2398        let mut call_ids = HashMap::new();
2399        let filtered = parse_responses_event(
2400            &json!({
2401                "type": "response.failed",
2402                "response": { "error": { "code": "content_filter", "message": "blocked" } }
2403            }),
2404            &mut call_ids,
2405            None,
2406        );
2407        let EventOutcome::Error(err) = filtered else {
2408            panic!("expected an error outcome");
2409        };
2410        assert!(matches!(err, Error::ServiceContentFilter { .. }));
2411
2412        let generic = parse_responses_event(
2413            &json!({
2414                "type": "response.failed",
2415                "response": { "error": { "code": "server_error", "message": "boom" } }
2416            }),
2417            &mut call_ids,
2418            None,
2419        );
2420        let EventOutcome::Error(err) = generic else {
2421            panic!("expected an error outcome");
2422        };
2423        assert!(matches!(err, Error::Service(_)));
2424    }
2425
2426    // endregion
2427
2428    // region: env-var constructor
2429
2430    /// Guards `OPENAI_API_KEY` / `OPENAI_BASE_URL` mutation: `cargo test` runs
2431    /// tests in the same process on multiple threads, and env vars are
2432    /// process-global, so concurrent set/remove across tests would be racy
2433    /// without serializing access.
2434    static ENV_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
2435
2436    #[test]
2437    fn from_env_reads_api_key_and_base_url() {
2438        let _guard = ENV_MUTEX.lock().unwrap();
2439        // SAFETY: serialized by ENV_MUTEX against the other env-var test in
2440        // this module; no other test in this crate touches these variables.
2441        unsafe {
2442            std::env::set_var("OPENAI_API_KEY", "sk-test-123");
2443            std::env::set_var("OPENAI_BASE_URL", "https://example.test/v1");
2444        }
2445        let client = OpenAIChatClient::from_env("gpt-4o-mini").unwrap();
2446        assert_eq!(client.inner.api_key, "sk-test-123");
2447        assert_eq!(client.inner.base_url, "https://example.test/v1");
2448        unsafe {
2449            std::env::remove_var("OPENAI_API_KEY");
2450            std::env::remove_var("OPENAI_BASE_URL");
2451        }
2452    }
2453
2454    #[test]
2455    fn from_env_errors_when_api_key_missing() {
2456        let _guard = ENV_MUTEX.lock().unwrap();
2457        // SAFETY: serialized by ENV_MUTEX; see above.
2458        unsafe {
2459            std::env::remove_var("OPENAI_API_KEY");
2460            std::env::remove_var("OPENAI_BASE_URL");
2461        }
2462        let result = OpenAIChatClient::from_env("gpt-4o-mini");
2463        assert!(result.is_err());
2464    }
2465    #[test]
2466    fn build_body_maps_hosted_tools_to_responses_types() {
2467        use agent_framework_core::tools::{
2468            hosted_code_interpreter, hosted_file_search, hosted_mcp, hosted_web_search,
2469        };
2470        let c = client();
2471        let mut options = ChatOptions::new();
2472        options.tools = vec![
2473            hosted_web_search(),
2474            hosted_code_interpreter(),
2475            hosted_file_search(Some(7)),
2476            hosted_mcp(
2477                "docs",
2478                "https://mcp.example/sse",
2479                Some(vec!["search".into()]),
2480            ),
2481        ];
2482        let body = c.build_body(&[user("hi")], &options, false);
2483        let tools = body["tools"].as_array().unwrap();
2484        assert_eq!(tools[0], json!({ "type": "web_search" }));
2485        assert_eq!(
2486            tools[1],
2487            json!({ "type": "code_interpreter", "container": { "type": "auto" } })
2488        );
2489        assert_eq!(tools[2]["type"], "file_search");
2490        assert_eq!(tools[2]["max_num_results"], json!(7));
2491        assert_eq!(tools[3]["type"], "mcp");
2492        assert_eq!(tools[3]["server_url"], "https://mcp.example/sse");
2493        assert_eq!(tools[3]["allowed_tools"], json!(["search"]));
2494        assert_eq!(tools[3]["require_approval"], "never");
2495    }
2496
2497    // endregion
2498
2499    // region: multimodal input (Responses)
2500
2501    #[test]
2502    fn an_inline_document_is_named_for_its_type() {
2503        let docx = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
2504        let uri = format!("data:{docx};base64,UEs=");
2505        assert_eq!(
2506            content_to_input_part(&uri, Some(docx)).unwrap()["filename"],
2507            "file.docx"
2508        );
2509        let bin = "data:application/octet-stream;base64,AA==";
2510        assert_eq!(
2511            content_to_input_part(bin, Some("application/octet-stream")).unwrap()["filename"],
2512            "file"
2513        );
2514    }
2515
2516    #[test]
2517    fn a_text_file_is_sent_as_a_file() {
2518        assert_eq!(
2519            content_to_input_part("data:text/plain;base64,aGk=", Some("text/plain")),
2520            Some(
2521                json!({ "type": "input_file", "file_data": "data:text/plain;base64,aGk=", "filename": "file.txt" })
2522            )
2523        );
2524        assert_eq!(
2525            content_to_input_part("data:text/markdown;base64,Iw==", Some("text/markdown")).unwrap()
2526                ["filename"],
2527            "file.md"
2528        );
2529        assert_eq!(
2530            content_to_input_part("https://example.com/notes.csv", Some("text/csv")),
2531            Some(json!({ "type": "input_file", "file_url": "https://example.com/notes.csv" }))
2532        );
2533    }
2534
2535    #[test]
2536    fn a_consent_link_must_name_a_real_host() {
2537        assert!(is_https_url("https://login.example.com/consent?x=1"));
2538        assert!(is_https_url("HTTPS://login.example.com/consent"));
2539        for bad in [
2540            "https://user@/consent",
2541            "https://:443/consent",
2542            "https:///consent",
2543            "http://login.example.com/consent",
2544            "javascript:alert(1)",
2545            "not a url",
2546        ] {
2547            assert!(!is_https_url(bad), "{bad} accepted");
2548        }
2549    }
2550
2551    #[test]
2552    fn a_remote_file_uri_goes_by_file_url() {
2553        assert_eq!(
2554            content_to_input_part("https://example.com/report.pdf", Some("application/pdf")),
2555            Some(json!({ "type": "input_file", "file_url": "https://example.com/report.pdf" }))
2556        );
2557        assert_eq!(
2558            content_to_input_part("data:application/pdf;base64,JV", Some("application/pdf")),
2559            Some(
2560                json!({ "type": "input_file", "file_data": "data:application/pdf;base64,JV", "filename": "file.pdf" })
2561            )
2562        );
2563    }
2564
2565    #[test]
2566    fn input_image_uri_becomes_input_image_part() {
2567        let msg = user_with(vec![Content::Uri(UriContent {
2568            uri: "https://example.com/cat.png".into(),
2569            media_type: "image/png".into(),
2570        })]);
2571        let input = messages_to_input(&[msg]);
2572        assert_eq!(
2573            input[0],
2574            json!({ "type": "message", "role": "user", "content": [
2575                { "type": "input_image", "image_url": "https://example.com/cat.png", "detail": "auto" }
2576            ]})
2577        );
2578    }
2579
2580    #[test]
2581    fn input_audio_file_and_hosted_file_parts() {
2582        let msg = user_with(vec![
2583            Content::Data(DataContent {
2584                uri: "data:audio/wav;base64,QQ".into(),
2585                media_type: Some("audio/wav".into()),
2586            }),
2587            Content::Data(DataContent {
2588                uri: "data:application/pdf;base64,JV".into(),
2589                media_type: Some("application/pdf".into()),
2590            }),
2591            Content::HostedFile(HostedFileContent {
2592                file_id: "file-123".into(),
2593            }),
2594        ]);
2595        let input = messages_to_input(&[msg]);
2596        // `input_audio.data` is the raw base64 payload (data-URI prefix
2597        // stripped), the same wire rule as Chat Completions; file inputs keep
2598        // the full data URI in `file_data`.
2599        assert_eq!(
2600            input[0]["content"],
2601            json!([
2602                { "type": "input_audio", "input_audio": { "data": "QQ", "format": "wav" } },
2603                { "type": "input_file", "file_data": "data:application/pdf;base64,JV", "filename": "file.pdf" },
2604                { "type": "input_file", "file_id": "file-123" },
2605            ])
2606        );
2607    }
2608
2609    #[test]
2610    fn approval_response_becomes_mcp_approval_response_item() {
2611        let resp = FunctionApprovalResponseContent {
2612            approved: true,
2613            id: "appr_1".into(),
2614            function_call: FunctionCallContent::new("appr_1", "search", None),
2615        };
2616        let msg = user_with(vec![Content::FunctionApprovalResponse(resp)]);
2617        let input = messages_to_input(&[msg]);
2618        assert_eq!(
2619            input[0],
2620            json!({
2621                "type": "mcp_approval_response",
2622                "approval_request_id": "appr_1",
2623                "approve": true,
2624            })
2625        );
2626    }
2627
2628    #[test]
2629    fn approval_request_becomes_mcp_approval_request_item() {
2630        let req = FunctionApprovalRequestContent {
2631            id: "appr_1".into(),
2632            function_call: FunctionCallContent::new(
2633                "appr_1",
2634                "search",
2635                Some(FunctionArguments::Raw(r#"{"q":"x"}"#.into())),
2636            ),
2637        };
2638        let msg = Message::with_contents(
2639            Role::assistant(),
2640            vec![Content::FunctionApprovalRequest(req)],
2641        );
2642        let input = messages_to_input(&[msg]);
2643        assert_eq!(
2644            input[0],
2645            json!({
2646                "type": "mcp_approval_request",
2647                "id": "appr_1",
2648                "name": "search",
2649                "arguments": r#"{"q":"x"}"#,
2650            })
2651        );
2652    }
2653
2654    // endregion
2655
2656    // region: output parsing (annotations, code interpreter, images, approvals)
2657
2658    #[test]
2659    fn output_text_url_citation_annotation() {
2660        let contents = parse_item(json!({
2661            "type": "message", "role": "assistant", "content": [{
2662                "type": "output_text", "text": "See source.",
2663                "annotations": [{
2664                    "type": "url_citation", "title": "Src", "url": "https://ex.com",
2665                    "start_index": 0, "end_index": 3,
2666                }],
2667            }],
2668        }));
2669        let Content::Text(t) = &contents[0] else {
2670            panic!("expected text content");
2671        };
2672        let ann = t.annotations.as_ref().unwrap();
2673        assert_eq!(ann[0].title.as_deref(), Some("Src"));
2674        assert_eq!(ann[0].url.as_deref(), Some("https://ex.com"));
2675        let region = &ann[0].annotated_regions.as_ref().unwrap()[0];
2676        assert_eq!(region.start_index, Some(0));
2677        assert_eq!(region.end_index, Some(3));
2678    }
2679
2680    #[test]
2681    fn output_text_file_and_container_citations() {
2682        let contents = parse_item(json!({
2683            "type": "message", "role": "assistant", "content": [{
2684                "type": "output_text", "text": "x",
2685                "annotations": [
2686                    { "type": "file_citation", "filename": "doc.pdf", "file_id": "file-1", "index": 2 },
2687                    { "type": "file_path", "file_id": "file-2", "index": 0 },
2688                    { "type": "container_file_citation", "filename": "c.txt", "file_id": "file-3",
2689                      "container_id": "cont-1", "start_index": 1, "end_index": 4 },
2690                ],
2691            }],
2692        }));
2693        let Content::Text(t) = &contents[0] else {
2694            panic!("expected text content");
2695        };
2696        let ann = t.annotations.as_ref().unwrap();
2697        assert_eq!(ann[0].url.as_deref(), Some("doc.pdf"));
2698        assert_eq!(ann[0].file_id.as_deref(), Some("file-1"));
2699        assert_eq!(ann[1].file_id.as_deref(), Some("file-2"));
2700        assert_eq!(ann[2].file_id.as_deref(), Some("file-3"));
2701        assert_eq!(ann[2].url.as_deref(), Some("c.txt"));
2702        assert_eq!(
2703            ann[2].annotated_regions.as_ref().unwrap()[0].end_index,
2704            Some(4)
2705        );
2706    }
2707
2708    #[test]
2709    fn code_interpreter_outputs_become_text_and_uri() {
2710        let contents = parse_item(json!({
2711            "type": "code_interpreter_call",
2712            "outputs": [
2713                { "type": "logs", "logs": "hello stdout" },
2714                { "type": "image", "url": "https://ex.com/plot.png" },
2715            ],
2716        }));
2717        assert!(matches!(&contents[0], Content::Text(t) if t.text == "hello stdout"));
2718        assert!(
2719            matches!(&contents[1], Content::Uri(u) if u.uri == "https://ex.com/plot.png" && u.media_type == "image")
2720        );
2721    }
2722
2723    #[test]
2724    fn code_interpreter_without_outputs_falls_back_to_code() {
2725        let contents = parse_item(json!({
2726            "type": "code_interpreter_call", "code": "print(1)",
2727        }));
2728        assert!(matches!(&contents[0], Content::Text(t) if t.text == "print(1)"));
2729    }
2730
2731    #[test]
2732    fn image_generation_raw_base64_becomes_png_data() {
2733        let contents = parse_item(json!({
2734            "type": "image_generation_call", "result": "AAAABBBB",
2735        }));
2736        let Content::Data(d) = &contents[0] else {
2737            panic!("expected data content");
2738        };
2739        assert_eq!(d.uri, "data:image/png;base64,AAAABBBB");
2740        assert_eq!(d.media_type.as_deref(), Some("image/png"));
2741    }
2742
2743    #[test]
2744    fn image_generation_data_uri_keeps_stated_media_type() {
2745        let contents = parse_item(json!({
2746            "type": "image_generation_call", "result": "data:image/webp;base64,ZZZ",
2747        }));
2748        let Content::Data(d) = &contents[0] else {
2749            panic!("expected data content");
2750        };
2751        assert_eq!(d.uri, "data:image/webp;base64,ZZZ");
2752        assert_eq!(d.media_type.as_deref(), Some("image/webp"));
2753    }
2754
2755    #[test]
2756    fn mcp_approval_request_output_round_trips_into_response() {
2757        let contents = parse_item(json!({
2758            "type": "mcp_approval_request",
2759            "id": "appr_9", "name": "search", "arguments": r#"{"q":"rust"}"#,
2760            "server_label": "docs",
2761        }));
2762        let Content::FunctionApprovalRequest(req) = &contents[0] else {
2763            panic!("expected approval request");
2764        };
2765        assert_eq!(req.id, "appr_9");
2766        assert_eq!(req.function_call.call_id, "appr_9");
2767        assert_eq!(req.function_call.name, "search");
2768
2769        // The id round-trips into the request's response item (item 5).
2770        let msg = user_with(vec![Content::FunctionApprovalResponse(
2771            req.create_response(true),
2772        )]);
2773        let input = messages_to_input(&[msg]);
2774        assert_eq!(input[0]["type"], json!("mcp_approval_response"));
2775        assert_eq!(input[0]["approval_request_id"], json!("appr_9"));
2776        assert_eq!(input[0]["approve"], json!(true));
2777    }
2778
2779    #[test]
2780    fn mcp_call_output_item_parses_into_call_and_result() {
2781        let contents = parse_item(json!({
2782            "type": "mcp_call", "id": "mcp_1", "name": "search",
2783            "server_label": "docs", "arguments": r#"{"q":"rust"}"#,
2784            "output": "found it",
2785        }));
2786        let [Content::McpServerToolCall(call), Content::McpServerToolResult(result)] =
2787            contents.as_slice()
2788        else {
2789            panic!("expected hosted call and result, got {contents:?}");
2790        };
2791        assert_eq!(call.call_id, "mcp_1");
2792        assert_eq!(call.tool_name, "search");
2793        assert_eq!(call.server_name.as_deref(), Some("docs"));
2794        assert_eq!(result.call_id, "mcp_1");
2795        assert_eq!(result.output, Some(json!("found it")));
2796    }
2797
2798    /// A hosted approval replayed from local history carries the completed
2799    /// `mcp_call` after its request/response pair, so the service sees the
2800    /// approved call as already run instead of an approval still to act on.
2801    #[test]
2802    fn replayed_hosted_approval_carries_its_completed_mcp_call() {
2803        let request = parse_item(json!({
2804            "type": "mcp_approval_request",
2805            "id": "appr_9", "name": "search", "arguments": r#"{"q":"rust"}"#,
2806            "server_label": "docs",
2807        }));
2808        let Content::FunctionApprovalRequest(req) = &request[0] else {
2809            panic!("expected approval request");
2810        };
2811        let response = req.create_response(true);
2812        let completed = parse_item(json!({
2813            "type": "mcp_call", "id": "mcp_1", "approval_request_id": "appr_9",
2814            "name": "search", "server_label": "docs",
2815            "arguments": r#"{"q":"rust"}"#, "output": "found it",
2816        }));
2817        let history = vec![
2818            Message::with_contents(Role::assistant(), request),
2819            user_with(vec![Content::FunctionApprovalResponse(response)]),
2820            Message::with_contents(Role::assistant(), completed),
2821            user("and now?"),
2822        ];
2823        let input = messages_to_input(&history);
2824        let types: Vec<_> = input.iter().map(|i| i["type"].clone()).collect();
2825        assert_eq!(
2826            types,
2827            vec![
2828                json!("mcp_approval_request"),
2829                json!("mcp_approval_response"),
2830                json!("mcp_call"),
2831                json!("message"),
2832            ]
2833        );
2834        assert_eq!(input[2]["id"], json!("mcp_1"));
2835        assert_eq!(input[2]["server_label"], json!("docs"));
2836        assert_eq!(input[2]["name"], json!("search"));
2837        assert_eq!(input[2]["arguments"], json!(r#"{"q":"rust"}"#));
2838        assert_eq!(input[2]["output"], json!("found it"));
2839        assert_eq!(input[2]["approval_request_id"], json!("appr_9"));
2840    }
2841
2842    #[test]
2843    fn orphan_mcp_result_is_dropped_from_input() {
2844        let input = messages_to_input(&[Message::with_contents(
2845            Role::assistant(),
2846            vec![Content::McpServerToolResult(McpServerToolResultContent {
2847                call_id: "mcp_missing".into(),
2848                output: Some(json!("x")),
2849                error: None,
2850            })],
2851        )]);
2852        assert!(input.is_empty(), "{input:?}");
2853    }
2854
2855    /// A streamed `mcp_call` starts with empty arguments on `added`; the
2856    /// final arguments only arrive on the completed item, so the call is
2857    /// recorded from `done` and replays with them rather than `{}`.
2858    #[test]
2859    fn streamed_mcp_call_records_the_completed_arguments() {
2860        let mut ids = HashMap::new();
2861        let added = parse_responses_event(
2862            &json!({"type": "response.output_item.added", "output_index": 0, "item": {
2863                "type": "mcp_call", "id": "mcp_2", "name": "search",
2864                "server_label": "docs", "arguments": "",
2865            }}),
2866            &mut ids,
2867            None,
2868        );
2869        assert!(matches!(added, EventOutcome::None));
2870        for event in [
2871            json!({"type": "response.mcp_call_arguments.delta", "output_index": 0,
2872                   "item_id": "mcp_2", "delta": "{\"q\":"}),
2873            json!({"type": "response.mcp_call_arguments.done", "output_index": 0,
2874                   "item_id": "mcp_2", "arguments": "{\"q\":\"rust\"}"}),
2875        ] {
2876            assert!(matches!(
2877                parse_responses_event(&event, &mut ids, None),
2878                EventOutcome::None
2879            ));
2880        }
2881        let EventOutcome::Update(done) = parse_responses_event(
2882            &json!({"type": "response.output_item.done", "output_index": 0, "item": {
2883                "type": "mcp_call", "id": "mcp_2", "name": "search",
2884                "server_label": "docs", "arguments": "{\"q\":\"rust\"}", "output": "ok",
2885                "approval_request_id": "appr_2",
2886            }}),
2887            &mut ids,
2888            None,
2889        ) else {
2890            panic!("expected an update on done");
2891        };
2892        let response = ChatResponse::from_updates(vec![done]);
2893        let input = messages_to_input(&response.messages);
2894        assert_eq!(
2895            input,
2896            vec![json!({
2897                "type": "mcp_call", "id": "mcp_2", "server_label": "docs",
2898                "name": "search", "arguments": "{\"q\":\"rust\"}", "output": "ok",
2899                "approval_request_id": "appr_2",
2900            })]
2901        );
2902    }
2903
2904    /// A turn continuing a stored response (`previous_response_id`) with the
2905    /// local history provider still attached must not re-send items the
2906    /// service already holds by their server-issued `id` (hosted `mcp_call`,
2907    /// `mcp_approval_request`, reasoning): OpenAI rejects them as duplicates.
2908    /// The new approval response and the text still go out; a stateless
2909    /// request keeps replaying everything.
2910    #[test]
2911    fn continuation_request_does_not_resend_stored_hosted_items() {
2912        let mut assistant = vec![
2913            Content::TextReasoning(TextReasoningContent {
2914                text: String::new(),
2915                annotations: None,
2916                raw_representation: Some(json!({
2917                    "type": "reasoning", "id": "rs_1", "summary": [],
2918                })),
2919                protected_data: None,
2920            }),
2921            Content::FunctionApprovalRequest(FunctionApprovalRequestContent {
2922                id: "mcpr_1".into(),
2923                function_call: FunctionCallContent::new(
2924                    "mcpr_1",
2925                    "search",
2926                    Some(FunctionArguments::Raw("{}".into())),
2927                ),
2928            }),
2929        ];
2930        assistant.extend(mcp_call_item_contents(&json!({
2931            "type": "mcp_call", "id": "mcp_1", "name": "search",
2932            "server_label": "docs", "arguments": "{}", "output": "ok",
2933        })));
2934        assistant.push(Content::text("done"));
2935        let history = vec![
2936            user("find it"),
2937            Message::with_contents(Role::assistant(), assistant),
2938            user_with(vec![Content::FunctionApprovalResponse(
2939                FunctionApprovalResponseContent {
2940                    approved: true,
2941                    id: "mcpr_2".into(),
2942                    function_call: FunctionCallContent::new("mcpr_2", "search", None),
2943                },
2944            )]),
2945        ];
2946        let types = |body: &Value| -> Vec<String> {
2947            body["input"]
2948                .as_array()
2949                .unwrap()
2950                .iter()
2951                .map(|item| item["type"].as_str().unwrap_or("message").to_string())
2952                .collect()
2953        };
2954
2955        let c = client();
2956        let mut options = ChatOptions::new();
2957        options.conversation_id = Some("resp_1".into());
2958        let body = c.build_body(&history, &options, false);
2959        assert_eq!(body["previous_response_id"], json!("resp_1"));
2960        assert_eq!(
2961            types(&body),
2962            ["message", "message", "mcp_approval_response"],
2963            "{body}"
2964        );
2965
2966        let body = c.build_body(&history, &ChatOptions::new(), false);
2967        assert_eq!(
2968            types(&body),
2969            [
2970                "message",
2971                "reasoning",
2972                "mcp_approval_request",
2973                "mcp_call",
2974                "message",
2975                "mcp_approval_response",
2976            ],
2977            "{body}"
2978        );
2979    }
2980
2981    /// An `mcp_call` that failed carries an `error` and no `output`; the
2982    /// error is kept and replayed, so the call does not look unfinished.
2983    #[test]
2984    fn failed_mcp_call_replays_its_error() {
2985        let item = json!({
2986            "type": "mcp_call", "id": "mcp_3", "name": "search",
2987            "server_label": "docs", "arguments": "{}",
2988            "status": "failed", "error": "server unreachable",
2989        });
2990        let contents = mcp_call_item_contents(&item);
2991        let [Content::McpServerToolCall(_), Content::McpServerToolResult(result)] =
2992            contents.as_slice()
2993        else {
2994            panic!("expected call + result, got {contents:?}");
2995        };
2996        assert_eq!(result.output, None);
2997        assert_eq!(result.error, Some(json!("server unreachable")));
2998        let input = messages_to_input(&[Message::with_contents(Role::assistant(), contents)]);
2999        assert_eq!(
3000            input,
3001            vec![json!({
3002                "type": "mcp_call", "id": "mcp_3", "server_label": "docs",
3003                "name": "search", "arguments": "{}", "error": "server unreachable",
3004            })]
3005        );
3006    }
3007
3008    // endregion
3009
3010    // region: streaming reasoning
3011
3012    fn reasoning_event(value: Value) -> EventOutcome {
3013        let mut ids = HashMap::new();
3014        parse_responses_event(&value, &mut ids, None)
3015    }
3016
3017    #[test]
3018    fn a_replayed_refusal_becomes_a_refusal_content_part() {
3019        // Beside `output_text` in an output message, a refusal has its own
3020        // part type. Re-emitting it as `output_text` replays a decline to the
3021        // provider as an answer.
3022        let input = messages_to_input(&[Message::with_contents(
3023            Role::assistant(),
3024            vec![
3025                Content::Text(TextContent::new("here is half")),
3026                Content::Text(TextContent::refusal("I can't do the rest")),
3027            ],
3028        )]);
3029        let content = &input[0]["content"];
3030        assert_eq!(
3031            content[0],
3032            json!({"type": "output_text", "text": "here is half"})
3033        );
3034        assert_eq!(
3035            content[1],
3036            json!({"type": "refusal", "refusal": "I can't do the rest"})
3037        );
3038    }
3039
3040    #[test]
3041    fn a_refusal_on_a_non_assistant_role_is_dropped_rather_than_mis_encoded() {
3042        // An *input* message's content list admits only
3043        // input_text/input_image/input_file — there is no refusal part — so
3044        // emitting one would be rejected by the API. Dropping it is the only
3045        // correct option, and it cannot arise from a parsed provider response
3046        // anyway (refusals are assistant output).
3047        let input = messages_to_input(&[Message::with_contents(
3048            Role::user(),
3049            vec![
3050                Content::Text(TextContent::new("hello")),
3051                Content::Text(TextContent::refusal("stray")),
3052            ],
3053        )]);
3054        let content = &input[0]["content"];
3055        assert_eq!(content.as_array().map(Vec::len), Some(1));
3056        assert_eq!(content[0], json!({"type": "input_text", "text": "hello"}));
3057    }
3058
3059    #[test]
3060    fn a_streamed_refusal_is_marked_and_its_done_event_is_not_duplicated() {
3061        // Before this, `response.refusal.delta` fell through the catch-all
3062        // and a streamed decline reached the caller as an empty response —
3063        // the non-streaming path marked refusals while the streaming path
3064        // dropped them.
3065        let EventOutcome::Update(delta) =
3066            reasoning_event(json!({ "type": "response.refusal.delta", "delta": "I can't" }))
3067        else {
3068            panic!("expected update");
3069        };
3070        assert!(matches!(&delta.contents[0], Content::Text(t) if t.refusal && t.text == "I can't"));
3071
3072        // `.done` repeats the whole refusal; emitting it would double the
3073        // text already streamed, exactly as for the text channel.
3074        let done =
3075            reasoning_event(json!({ "type": "response.refusal.done", "refusal": "I can't help" }));
3076        assert!(matches!(done, EventOutcome::None));
3077    }
3078
3079    // region: Foundry oauth consent
3080
3081    #[test]
3082    fn a_completed_response_surfaces_its_oauth_consent_request() {
3083        // A Foundry hosted tool that needs consent finishes the turn with
3084        // an `oauth_consent_request` output item and no text. Ignored, the
3085        // run came back as an empty answer and the caller had no way to
3086        // learn what it was waiting for (upstream #8976).
3087        let value = json!({
3088            "id": "resp_1",
3089            "status": "completed",
3090            "output": [
3091                {
3092                    "type": "oauth_consent_request",
3093                    "id": "oauth_7",
3094                    "consent_link": "https://login.example.com/consent?state=abc",
3095                }
3096            ],
3097        });
3098        let resp = parse_response(&value, None);
3099        let Content::OauthConsentRequest(consent) = &resp.messages[0].contents[0] else {
3100            panic!(
3101                "expected a consent request, got {:?}",
3102                resp.messages[0].contents
3103            );
3104        };
3105        assert_eq!(
3106            consent.consent_link,
3107            "https://login.example.com/consent?state=abc"
3108        );
3109        // The id is what a workflow registers the request under, so the
3110        // user's answer has something to correlate against.
3111        assert_eq!(consent.id.as_deref(), Some("oauth_7"));
3112    }
3113
3114    #[test]
3115    fn a_streamed_oauth_consent_request_is_emitted_when_the_item_is_added() {
3116        // It has no deltas to wait for and the run is blocked on the user
3117        // until it is answered, so it is emitted on `added` rather than
3118        // held back to `done` like a hosted MCP call.
3119        let EventOutcome::Update(update) = reasoning_event(json!({
3120            "type": "response.output_item.added",
3121            "output_index": 0,
3122            "item": {
3123                "type": "oauth_consent_request",
3124                "id": "oauth_7",
3125                "consent_link": "https://login.example.com/consent",
3126            },
3127        })) else {
3128            panic!("expected an update");
3129        };
3130        assert!(matches!(
3131            &update.contents[0],
3132            Content::OauthConsentRequest(c)
3133                if c.consent_link == "https://login.example.com/consent"
3134                    && c.id.as_deref() == Some("oauth_7")
3135        ));
3136    }
3137
3138    #[test]
3139    fn a_top_level_oauth_consent_event_carries_the_same_content() {
3140        // Foundry also emits the request as a top-level event with the link
3141        // on the event itself rather than on an output item.
3142        let EventOutcome::Update(update) = reasoning_event(json!({
3143            "type": "response.oauth_consent_requested",
3144            "id": "oauth_9",
3145            "consent_link": "https://login.example.com/consent",
3146        })) else {
3147            panic!("expected an update");
3148        };
3149        assert!(matches!(
3150            &update.contents[0],
3151            Content::OauthConsentRequest(c) if c.id.as_deref() == Some("oauth_9")
3152        ));
3153    }
3154
3155    #[test]
3156    fn an_untrustworthy_consent_link_is_dropped_rather_than_surfaced() {
3157        // The framework is asking a human to open this URL and
3158        // authenticate at it, and it arrives from the service as free-form
3159        // text. Anything that is not https with a host is dropped.
3160        for link in [
3161            json!("http://login.example.com/consent"),
3162            json!("javascript:alert(1)"),
3163            json!("https:///no-host"),
3164            json!(""),
3165            Value::Null,
3166        ] {
3167            let value = json!({
3168                "id": "resp_1",
3169                "status": "completed",
3170                "output": [
3171                    { "type": "oauth_consent_request", "id": "oauth_7", "consent_link": link }
3172                ],
3173            });
3174            let resp = parse_response(&value, None);
3175            let found = resp
3176                .messages
3177                .iter()
3178                .flat_map(|m| &m.contents)
3179                .any(|c| matches!(c, Content::OauthConsentRequest(_)));
3180            assert!(!found, "accepted consent_link {link:?}");
3181        }
3182
3183        // The scheme is case-insensitive, so an upper-case one is accepted.
3184        let value = json!({
3185            "id": "resp_1",
3186            "status": "completed",
3187            "output": [
3188                {
3189                    "type": "oauth_consent_request",
3190                    "consent_link": "HTTPS://login.example.com/consent",
3191                }
3192            ],
3193        });
3194        let resp = parse_response(&value, None);
3195        let Content::OauthConsentRequest(consent) = &resp.messages[0].contents[0] else {
3196            panic!("expected a consent request");
3197        };
3198        // No `id` on the item: the content carries none rather than an
3199        // empty string that would correlate against nothing.
3200        assert_eq!(consent.id, None);
3201    }
3202
3203    // endregion
3204
3205    #[test]
3206    fn reasoning_text_delta_streams_and_done_is_terminal_metadata() {
3207        let EventOutcome::Update(delta) =
3208            reasoning_event(json!({ "type": "response.reasoning_text.delta", "delta": "Th" }))
3209        else {
3210            panic!("expected update");
3211        };
3212        assert!(matches!(&delta.contents[0], Content::TextReasoning(t) if t.text == "Th"));
3213
3214        // `.done` carries the full text the deltas already streamed — emitting
3215        // it again would duplicate the reasoning in the aggregate.
3216        let done =
3217            reasoning_event(json!({ "type": "response.reasoning_text.done", "text": "Think" }));
3218        assert!(matches!(done, EventOutcome::None));
3219    }
3220
3221    #[test]
3222    fn reasoning_summary_text_events_map_to_reasoning_content() {
3223        let EventOutcome::Update(delta) = reasoning_event(
3224            json!({ "type": "response.reasoning_summary_text.delta", "delta": "sum" }),
3225        ) else {
3226            panic!("expected update");
3227        };
3228        assert!(matches!(&delta.contents[0], Content::TextReasoning(t) if t.text == "sum"));
3229
3230        let done = reasoning_event(
3231            json!({ "type": "response.reasoning_summary_text.done", "text": "summary" }),
3232        );
3233        assert!(matches!(done, EventOutcome::None));
3234    }
3235
3236    #[test]
3237    fn response_failure_error_classifies_content_filter() {
3238        let filtered = json!({
3239            "status": "failed",
3240            "error": { "code": "content_filter", "message": "blocked" }
3241        });
3242        assert!(matches!(
3243            response_failure_error(&filtered),
3244            Some(Error::ServiceContentFilter { .. })
3245        ));
3246
3247        let generic = json!({
3248            "status": "failed",
3249            "error": { "code": "server_error", "message": "boom" }
3250        });
3251        assert!(matches!(
3252            response_failure_error(&generic),
3253            Some(Error::Service(_))
3254        ));
3255
3256        assert!(response_failure_error(&json!({ "status": "completed" })).is_none());
3257    }
3258
3259    #[test]
3260    fn input_audio_data_strips_data_uri_prefix() {
3261        let part = content_to_input_part("data:audio/wav;base64,QUJD", Some("audio/wav"))
3262            .expect("audio part");
3263        assert_eq!(part["input_audio"]["data"], "QUJD");
3264        assert_eq!(part["input_audio"]["format"], "wav");
3265    }
3266
3267    // endregion
3268
3269    // region: hosted-tool config passthrough
3270
3271    fn hosted(kind: ToolKind, name: &str, params: Value) -> ToolDefinition {
3272        ToolDefinition {
3273            name: name.into(),
3274            description: String::new(),
3275            parameters: params,
3276            kind,
3277            approval_mode: ApprovalMode::NeverRequire,
3278            executor: None,
3279        }
3280    }
3281
3282    #[test]
3283    fn web_search_passes_through_user_location() {
3284        let tool = hosted(
3285            ToolKind::HostedWebSearch,
3286            "web_search",
3287            json!({ "user_location": { "city": "Paris", "country": "FR" } }),
3288        );
3289        assert_eq!(
3290            tool_to_responses_spec(&tool),
3291            json!({
3292                "type": "web_search",
3293                "user_location": { "type": "approximate", "city": "Paris", "country": "FR" },
3294            })
3295        );
3296    }
3297
3298    #[test]
3299    fn file_search_passes_vector_store_ids_and_max_results_param() {
3300        let tool = hosted(
3301            ToolKind::HostedFileSearch { max_results: None },
3302            "file_search",
3303            json!({ "vector_store_ids": ["vs_1"], "max_results": 12 }),
3304        );
3305        let spec = tool_to_responses_spec(&tool);
3306        assert_eq!(spec["vector_store_ids"], json!(["vs_1"]));
3307        assert_eq!(spec["max_num_results"], json!(12));
3308    }
3309
3310    #[test]
3311    fn image_generation_maps_to_responses_tool_with_passthrough_params() {
3312        let tool = hosted(
3313            ToolKind::HostedImageGeneration,
3314            "image_generation",
3315            json!({ "size": "1024x1024", "quality": "high" }),
3316        );
3317        let spec = tool_to_responses_spec(&tool);
3318        assert_eq!(spec["type"], json!("image_generation"));
3319        assert_eq!(spec["size"], json!("1024x1024"));
3320        assert_eq!(spec["quality"], json!("high"));
3321    }
3322
3323    #[test]
3324    fn code_interpreter_passes_file_ids_and_container_override() {
3325        let with_files = hosted(
3326            ToolKind::HostedCodeInterpreter,
3327            "ci",
3328            json!({ "file_ids": ["file-1", "file-2"] }),
3329        );
3330        assert_eq!(
3331            tool_to_responses_spec(&with_files)["container"],
3332            json!({ "type": "auto", "file_ids": ["file-1", "file-2"] })
3333        );
3334        let with_container = hosted(
3335            ToolKind::HostedCodeInterpreter,
3336            "ci",
3337            json!({ "container": { "type": "secure", "id": "c1" } }),
3338        );
3339        assert_eq!(
3340            tool_to_responses_spec(&with_container)["container"],
3341            json!({ "type": "secure", "id": "c1" })
3342        );
3343    }
3344
3345    #[test]
3346    fn mcp_passes_headers_and_string_approval_mode_override() {
3347        let tool = hosted(
3348            ToolKind::HostedMcp {
3349                url: "https://mcp/sse".into(),
3350                allowed_tools: None,
3351            },
3352            "docs",
3353            json!({ "headers": { "Authorization": "Bearer x" }, "approval_mode": "always_require" }),
3354        );
3355        // The enum default is NeverRequire; the parameter overrides it.
3356        let spec = tool_to_responses_spec(&tool);
3357        assert_eq!(spec["headers"], json!({ "Authorization": "Bearer x" }));
3358        assert_eq!(spec["require_approval"], json!("always"));
3359    }
3360
3361    #[test]
3362    fn mcp_object_approval_mode_maps_to_tool_name_lists() {
3363        let tool = hosted(
3364            ToolKind::HostedMcp {
3365                url: "https://mcp/sse".into(),
3366                allowed_tools: None,
3367            },
3368            "docs",
3369            json!({ "approval_mode": { "always": ["delete"], "never": ["read"] } }),
3370        );
3371        assert_eq!(
3372            tool_to_responses_spec(&tool)["require_approval"],
3373            json!({ "always": { "tool_names": ["delete"] }, "never": { "tool_names": ["read"] } })
3374        );
3375    }
3376
3377    // endregion
3378}