Skip to main content

switchyard_llm_client/
client.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! [`TranslatingLlmClient`]: encode a neutral
5//! request, call the configured backend over HTTP, decode the neutral response.
6
7use std::borrow::Cow;
8use std::collections::{BTreeMap, BTreeSet, HashMap};
9use std::future::ready;
10use std::sync::atomic::{AtomicU64, Ordering};
11use std::time::{Duration, SystemTime};
12
13use async_trait::async_trait;
14use futures_util::{StreamExt, stream};
15use http::StatusCode;
16use reqwest::RequestBuilder;
17use reqwest::header::{HeaderMap, HeaderName, HeaderValue, RETRY_AFTER};
18use serde_json::{Map, Value, json};
19use switchyard_protocol::{
20    LlmRequest, LlmResponse, LlmResponseChunk, LlmResponseStream, LlmResponseStreamEvent, Metadata,
21    ModelId, Request, Response, RoutedLlmClient,
22};
23use switchyard_translation::{TranslationError, WireFormat, decode_stream};
24use tokio::time::Instant;
25use tracing::Instrument;
26
27use crate::backend::{Backend, openai_url};
28use crate::error::{LlmClientError, Result};
29use crate::metrics;
30use crate::observed_translation;
31
32// Caller headers safe to send when caller auth forwarding is disabled.
33const ALLOWED_METADATA_HEADERS: &[&str] = &["x-request-id"];
34
35// Headers tied to the inbound connection, destination, or body. The HTTP client
36// must rebuild these for the upstream request, even when forwarding auth.
37const NON_FORWARDABLE_HEADERS: &[&str] = &[
38    "host",
39    "content-length",
40    "connection",
41    "proxy-connection",
42    "keep-alive",
43    "proxy-authenticate",
44    "proxy-authorization",
45    "te",
46    "trailer",
47    "transfer-encoding",
48    "upgrade",
49    "content-type",
50    "content-encoding",
51    "accept-encoding",
52    "expect",
53];
54
55const INITIAL_RETRY_DELAY: Duration = Duration::from_millis(250);
56const MAX_RETRY_BACKOFF: Duration = Duration::from_secs(2);
57const MAX_RETRY_AFTER: Duration = Duration::from_secs(60);
58
59/// A named target's provider model and backends.
60#[derive(Clone, Debug)]
61pub struct ModelConfig {
62    target_name: ModelId,
63    provider_model: Option<ModelId>,
64    default_backend: Backend,
65    other_backends: Option<Vec<Backend>>,
66    responses_reasoning: crate::ResponsesReasoningPolicy,
67}
68
69impl ModelConfig {
70    /// Configures a target. Its name is also the provider model ID unless overridden.
71    pub fn new(
72        target_name: impl Into<ModelId>,
73        default_backend: Backend,
74        other_backends: Option<Vec<Backend>>,
75    ) -> Self {
76        Self {
77            target_name: target_name.into(),
78            provider_model: None,
79            default_backend,
80            other_backends,
81            responses_reasoning: crate::ResponsesReasoningPolicy::default(),
82        }
83    }
84
85    /// Sets how Responses reasoning items are replayed to this target.
86    #[must_use]
87    pub fn with_responses_reasoning(mut self, policy: crate::ResponsesReasoningPolicy) -> Self {
88        self.responses_reasoning = policy;
89        self
90    }
91
92    /// Sends `provider_model` upstream in place of `target_name`. The client is still
93    /// called with `target_name`, so several entries can serve one provider model with
94    /// different backend settings.
95    pub fn with_provider_model(mut self, provider_model: impl Into<ModelId>) -> Self {
96        self.provider_model = Some(provider_model.into());
97        self
98    }
99}
100
101/// A model-bearing provider operation outside the normal completion endpoint.
102#[derive(Clone, Copy, Debug, Eq, PartialEq)]
103pub enum AuxiliaryOperation {
104    /// Anthropic Messages input-token counting.
105    AnthropicCountTokens,
106    /// OpenAI Responses input-token counting.
107    ResponsesInputTokens,
108    /// OpenAI Responses compaction.
109    ResponsesCompact,
110}
111
112impl AuxiliaryOperation {
113    const fn wire_format(self) -> WireFormat {
114        match self {
115            Self::AnthropicCountTokens => WireFormat::AnthropicMessages,
116            Self::ResponsesInputTokens | Self::ResponsesCompact => WireFormat::OpenAiResponses,
117        }
118    }
119
120    fn url(self, backend: &Backend) -> String {
121        let suffix = match self {
122            Self::AnthropicCountTokens => return backend.count_tokens_url(),
123            Self::ResponsesInputTokens => "/responses/input_tokens",
124            Self::ResponsesCompact => "/responses/compact",
125        };
126        let base_url = backend.url();
127        openai_url(&base_url, suffix).unwrap_or_else(|error| {
128            tracing::error!(%error, "Unable to build OpenAI auxiliary endpoint URL");
129            base_url
130        })
131    }
132}
133
134/// A client that dispatches neutral-IR requests to named targets.
135///
136/// Each [`ModelConfig`] defines a target's provider model and backends.
137/// Each call resolves the target and wire format, encodes the request,
138/// applies auth and forwarded headers, sends the HTTP request with a shared
139/// [`reqwest::Client`], and decodes the response back to the neutral IR (buffered
140/// or streamed).
141pub struct TranslatingLlmClient {
142    configs_by_target: HashMap<ModelId, ModelConfig>,
143    client: reqwest::Client,
144    forward_auth_client: reqwest::Client,
145    is_rate_limit_cooldown_enabled: bool,
146    cooldown_epoch: Instant,
147    // Milliseconds since cooldown_epoch. Each atomic is independent, so relaxed ordering suffices.
148    unavailable_until: HashMap<ModelId, AtomicU64>,
149}
150
151impl TranslatingLlmClient {
152    /// Builds a client over the given [`ModelConfig`]s, with a fresh shared HTTP
153    /// client and the built-in translation codecs.
154    pub fn new(model_configs: &[ModelConfig]) -> Result<Self> {
155        // Pre-populate so concurrent calls update only atomics and keep map access lock-free.
156        let mut unavailable_until = HashMap::new();
157        for config in model_configs {
158            for backend in std::iter::once(&config.default_backend)
159                .chain(config.other_backends.iter().flatten())
160            {
161                backend.validate_configured_headers(&config.target_name)?;
162            }
163            unavailable_until.insert(config.target_name.clone(), AtomicU64::new(0));
164        }
165        let build_client = |builder: reqwest::ClientBuilder| {
166            builder.build().map_err(|error| LlmClientError::Transport {
167                source: Box::new(error),
168            })
169        };
170        let client = build_client(reqwest::Client::builder())?;
171        // A redirect could move provider-specific headers to another origin.
172        // Forwarded credentials are sent only to the configured URL.
173        let forward_auth_client =
174            build_client(reqwest::Client::builder().redirect(reqwest::redirect::Policy::none()))?;
175        let configs_by_target = model_configs
176            .iter()
177            .map(|config| (config.target_name.clone(), config.clone()))
178            .collect();
179
180        Ok(Self {
181            configs_by_target,
182            client,
183            forward_auth_client,
184            is_rate_limit_cooldown_enabled: true,
185            cooldown_epoch: Instant::now(),
186            unavailable_until,
187        })
188    }
189
190    /// Disable HTTP 429 cooldown so subsequent calls can receive the upstream error.
191    pub fn without_rate_limit_cooldown(mut self) -> Self {
192        self.is_rate_limit_cooldown_enabled = false;
193        self
194    }
195
196    /// The target's backend for `format`, or `None` if no matching backend exists.
197    pub fn backend_for(&self, target_name: &ModelId, format: WireFormat) -> Option<&Backend> {
198        self.configs_by_target.get(target_name).and_then(|config| {
199            if config.default_backend.wire_format() == format {
200                Some(&config.default_backend)
201            } else {
202                config
203                    .other_backends
204                    .as_ref()
205                    .and_then(|backends| backends.iter().find(|b| b.wire_format() == format))
206            }
207        })
208    }
209
210    /// The target's provider model ID, falling back to its name when none is configured.
211    pub fn provider_model<'a>(&'a self, target_name: &'a ModelId) -> &'a ModelId {
212        self.configs_by_target
213            .get(target_name)
214            .and_then(|config| config.provider_model.as_ref())
215            .unwrap_or(target_name)
216    }
217
218    /// Whether the target has a backend for `operation`.
219    pub fn supports_auxiliary(&self, target_name: &ModelId, operation: AuxiliaryOperation) -> bool {
220        self.backend_for(target_name, operation.wire_format())
221            .is_some()
222    }
223
224    /// Reads llama.cpp model properties through the backend's configured auth and headers.
225    ///
226    /// Redirects are disabled so credentials cannot move to another origin.
227    pub async fn get_model_properties(
228        &self,
229        target_name: &ModelId,
230        format: WireFormat,
231        timeout: Duration,
232    ) -> Result<Value> {
233        let backend =
234            self.backend_for(target_name, format)
235                .ok_or_else(|| LlmClientError::Configuration {
236                    message: format!("model {target_name} has no backend for {format:?}"),
237                })?;
238        let mut url = reqwest::Url::parse(backend.base_url()).map_err(|error| {
239            LlmClientError::Configuration {
240                message: format!("model {target_name} has an invalid backend URL: {error}"),
241            }
242        })?;
243        let root = url.path().trim_end_matches('/');
244        let root = root
245            .strip_suffix("/chat/completions")
246            .or_else(|| root.strip_suffix("/responses"))
247            .unwrap_or(root);
248        let path = format!(
249            "{}/props",
250            root.strip_suffix("/v1")
251                .unwrap_or(root)
252                .trim_end_matches('/')
253        );
254        url.set_path(&path);
255        url.set_query(None);
256
257        let builder = self.forward_auth_client.get(url).timeout(timeout);
258        let builder = apply_extra_headers(builder, backend);
259        let response = backend
260            .apply_auth(builder)
261            .send()
262            .await
263            .map_err(convert_reqwest_error)?
264            .error_for_status()
265            .map_err(convert_reqwest_error)?;
266        response
267            .json()
268            .await
269            .map_err(|source| LlmClientError::InvalidResponse {
270                source: Box::new(source),
271            })
272    }
273
274    /// Calls a model-bearing auxiliary provider operation.
275    ///
276    /// Returns an error when the model has no compatible backend or the upstream
277    /// request fails or returns invalid JSON.
278    pub async fn call_auxiliary(
279        &self,
280        target_name: &ModelId,
281        request: Request,
282        operation: AuxiliaryOperation,
283    ) -> Result<Value> {
284        let wire_format = operation.wire_format();
285        let backend = self.backend_for(target_name, wire_format).ok_or_else(|| {
286            LlmClientError::Configuration {
287                message: format!("model {target_name} has no backend for {operation:?}"),
288            }
289        })?;
290        let Request {
291            mut llm_request,
292            metadata,
293            ..
294        } = request;
295        llm_request.model = Some(self.provider_model(target_name).to_string());
296        let http_response = self
297            .send_encoded(
298                backend,
299                wire_format,
300                llm_request,
301                metadata.as_ref(),
302                target_name,
303                UpstreamEndpoint::Auxiliary(operation),
304            )
305            .await?;
306        let EncodedResponse::Buffered { body, .. } = http_response else {
307            return Err(LlmClientError::InvalidRequest {
308                message: "auxiliary endpoints do not support streaming".to_string(),
309            });
310        };
311        serde_json::from_slice(&body).map_err(|error| LlmClientError::InvalidResponse {
312            source: Box::new(error),
313        })
314    }
315
316    /// Encode `llm_request` for `wire_format`, POST it to `url` with the request's
317    /// forwarded headers plus the backend's static headers and auth, and return the
318    /// successful upstream response. A
319    /// buffered response is fully collected within the retry boundary; a streamed
320    /// response has its first decoded event checked within that boundary. The backend's
321    /// deadline, when set, spans every attempt, retry delay, and subsequent stream read. A
322    /// non-success status maps to a typed error — a 400 is classified as a context-window
323    /// overflow via the backend's provider rules. Shared by
324    /// [`call_rewrite_model`](Self::call_rewrite_model) (which POSTs to the
325    /// backend's completion URL and decodes a response) and
326    /// the model-bearing auxiliary operations, which return raw JSON.
327    async fn send_encoded(
328        &self,
329        backend: &Backend,
330        wire_format: WireFormat,
331        llm_request: LlmRequest,
332        metadata: Option<&Metadata>,
333        target_name: &ModelId,
334        endpoint: UpstreamEndpoint,
335    ) -> Result<EncodedResponse> {
336        let cooldown = backend.failure_cooldown();
337        let unavailable_until =
338            if matches!(endpoint, UpstreamEndpoint::Completion) && !cooldown.is_zero() {
339                self.unavailable_until.get(target_name)
340            } else {
341                None
342            };
343        if let Some(until) = unavailable_until
344            && until.load(Ordering::Relaxed) > duration_millis(self.cooldown_epoch.elapsed())
345        {
346            tracing::debug!(model = %target_name, wire_format = %wire_format, "skipping backend during failure cooldown");
347            return Err(LlmClientError::TemporarilyUnavailable);
348        }
349
350        let mut body = observed_translation::encode_request(&llm_request, wire_format)
351            .map_err(|error| LlmClientError::RequestEncoding(error.to_string()))?;
352        // `encode_request` round-trips a preserved same-format body verbatim,
353        // which keeps the caller's original `model`. Set the provider model explicitly.
354        let provider_model_id = self.provider_model(target_name);
355        set_json_model(&mut body, provider_model_id);
356        if matches!(backend, Backend::OpenAiResponses(_)) {
357            switchyard_translation::flatten_codex_namespaces_for_provider(&mut body);
358        }
359        // Strip before `merge_extra_body` so a target can reinstate either field
360        // deliberately via `extra_body`.
361        if matches!(backend, Backend::Anthropic(_)) {
362            strip_anthropic_incompatible_fields(&mut body);
363            strip_unsigned_thinking_blocks(&mut body);
364        }
365        omit_configured_body_fields(&mut body, backend.omit_body_fields());
366        merge_extra_body(&mut body, backend.extra_body());
367        if matches!(backend, Backend::OpenAiResponses(_)) {
368            let outbound_model_id = body
369                .get("model")
370                .and_then(Value::as_str)
371                .unwrap_or(provider_model_id)
372                .to_owned();
373            self.configs_by_target
374                .get(target_name)
375                .map(|config| config.responses_reasoning)
376                .unwrap_or_default()
377                .normalize(&mut body, backend.base_url(), &outbound_model_id);
378        }
379        // After the merge on purpose: the effort override must win over both the caller's
380        // value and any `reasoning` default a target set through `extra_body`. Token counting
381        // does not depend on effort, and Anthropic's count endpoint may reject the field.
382        if matches!(endpoint, UpstreamEndpoint::Completion) {
383            apply_reasoning_effort(&mut body, backend);
384        }
385        if matches!(backend, Backend::OpenAiResponses(_)) {
386            normalize_codex_string_input(&backend.url(), &mut body);
387        }
388        if matches!(backend, Backend::Anthropic(_)) {
389            if nvidia_inference_api_backend(backend) {
390                strip_anthropic_tool_strict(&mut body);
391            }
392            enable_anthropic_prompt_caching(&mut body, llm_request.temporary_note_count);
393        }
394        if matches!(
395            backend,
396            Backend::OpenAiChat(_) | Backend::OpenAiResponses(_)
397        ) {
398            enable_openai_guidance_caching(
399                &mut body,
400                wire_format,
401                provider_model_id,
402                llm_request.temporary_note_count,
403            );
404        }
405        if matches!(backend, Backend::OpenAiChat(_)) {
406            ensure_openai_stream_usage(&mut body);
407        }
408        let streaming = endpoint.allows_streaming()
409            && body.get("stream").and_then(Value::as_bool).unwrap_or(false);
410        let url = endpoint.url(backend);
411        record_gen_ai_request(&url, provider_model_id, streaming);
412
413        let result = self
414            .send_with_retries(&url, backend, &body, metadata, target_name, streaming)
415            .await;
416        // Keep quota failures request-local when forwarding auth or returning 429 to callers.
417        if let Some(until) = unavailable_until
418            && let Err(error) = &result
419            && is_transient_failure(error)
420            && !((backend.is_forwarding_auth() || !self.is_rate_limit_cooldown_enabled)
421                && matches!(error, LlmClientError::UpstreamHttp { status, .. } if *status == StatusCode::TOO_MANY_REQUESTS))
422        {
423            let deadline = duration_millis(self.cooldown_epoch.elapsed().saturating_add(cooldown));
424            until.fetch_max(deadline, Ordering::Relaxed);
425        }
426        // Let cooldown expire naturally; a successful in-flight call may overlap a newer failure.
427        result
428    }
429
430    // Sends the encoded body, retrying retryable failures within the backend's retry budget.
431    async fn send_with_retries(
432        &self,
433        url: &str,
434        backend: &Backend,
435        body: &Value,
436        metadata: Option<&Metadata>,
437        target_name: &ModelId,
438        streaming: bool,
439    ) -> Result<EncodedResponse> {
440        let max_retries = u64::from(backend.max_retries());
441        let max_attempts = max_retries
442            + 1
443            + u64::from(
444                matches!(backend, Backend::OpenAiChat(_))
445                    && body.get("chat_template_kwargs").is_some(),
446            );
447        let mut body = Cow::Borrowed(body);
448        let mut template_retry = false;
449        let expires_at = backend
450            .timeout()
451            .map(|timeout| (tokio::time::sleep(timeout).deadline(), timeout));
452        let deadline = async {
453            match expires_at {
454                Some((at, timeout)) => {
455                    tokio::time::sleep_until(at).await;
456                    timeout
457                }
458                None => std::future::pending().await,
459            }
460        };
461        tokio::pin!(deadline);
462        let mut attempt = 0_u64;
463        loop {
464            if let Some((at, timeout)) = expires_at
465                && tokio::time::Instant::now() >= at
466            {
467                return Err(deadline_error(timeout));
468            }
469            let span = tracing::debug_span!(
470                target: "libsy",
471                "libsy.upstream_attempt",
472                model = %target_name,
473                wire_format = %backend.wire_format(),
474                attempt = attempt + 1 + u64::from(template_retry),
475                max_attempts,
476                retry = attempt > 0 || template_retry,
477                openinference.span.kind = "CHAIN",
478                outcome = tracing::field::Empty,
479                status_code = tracing::field::Empty,
480                will_retry = tracing::field::Empty,
481                retry_delay_ms = tracing::field::Empty,
482            );
483            let mut attempt_started = false;
484            let result = tokio::select! {
485                biased;
486                timeout = &mut deadline => {
487                    if attempt_started {
488                        metrics::record_upstream_attempt(None);
489                    }
490                    span.record("outcome", "error");
491                    span.record("will_retry", false);
492                    return Err(deadline_error(timeout));
493                }
494                result = async {
495                    attempt_started = true;
496                    self.send_once(url, backend, body.as_ref(), metadata, target_name, streaming).await
497                }.instrument(span.clone()) => result,
498            };
499            // The retained handle updates this same attempt span with its outcome.
500            match result {
501                Ok(response) => {
502                    span.record("outcome", "ok");
503                    span.record("status_code", response.status());
504                    span.record("will_retry", false);
505                    if attempt > 0 || template_retry {
506                        metrics::record_retry_recovered();
507                    }
508                    return Ok(match response {
509                        EncodedResponse::Streaming {
510                            status,
511                            chunks,
512                            upstream_headers,
513                        } => EncodedResponse::Streaming {
514                            status,
515                            chunks: stream_with_deadline(chunks, expires_at),
516                            upstream_headers,
517                        },
518                        buffered => buffered,
519                    });
520                }
521                Err(failure) => {
522                    let retry_without_template = matches!(backend, Backend::OpenAiChat(_))
523                        && body.get("chat_template_kwargs")
524                            == Some(&json!({"enable_thinking": false}))
525                        && rejects_template_options(&failure.error);
526                    let will_retry =
527                        retry_without_template || (attempt < max_retries && failure.is_retryable());
528                    span.record("outcome", "error");
529                    if let Some(status) = failure.status {
530                        span.record("status_code", status.as_u16());
531                    }
532                    span.record("will_retry", will_retry);
533                    if !will_retry {
534                        return Err(failure.error);
535                    }
536
537                    if retry_without_template {
538                        if let Some(object) = body.to_mut().as_object_mut() {
539                            object.remove("chat_template_kwargs");
540                        }
541                        template_retry = true;
542                        span.record("retry_delay_ms", 0_u64);
543                        continue;
544                    }
545                    let delay = retry_delay(attempt, failure.retry_after);
546                    span.record("retry_delay_ms", duration_millis(delay));
547                    // Close the attempt span before sleeping so backoff is not attempt latency.
548                    drop(span);
549                    tokio::select! {
550                        biased;
551                        timeout = &mut deadline => return Err(deadline_error(timeout)),
552                        _ = tokio::time::sleep(delay) => {}
553                    }
554                    attempt += 1;
555                }
556            }
557        }
558    }
559
560    // Performs one HTTP attempt and retains the retry metadata alongside any error.
561    async fn send_once(
562        &self,
563        url: &str,
564        backend: &Backend,
565        body: &Value,
566        metadata: Option<&Metadata>,
567        target_name: &ModelId,
568        streaming: bool,
569    ) -> std::result::Result<EncodedResponse, AttemptFailure> {
570        let client = if backend.is_forwarding_auth() {
571            &self.forward_auth_client
572        } else {
573            &self.client
574        };
575        let builder = client.post(url).json(body);
576        let builder = forward_metadata_headers(builder, metadata, backend);
577        let builder = backend.apply_forwarded_auth(builder, metadata);
578        let builder = apply_extra_headers(builder, backend);
579        let builder = backend.apply_auth(builder);
580
581        let response = match async {
582            let request = builder.build()?;
583            if let Some(body) = request.body().and_then(reqwest::Body::as_bytes) {
584                crate::payload_capture::record("request", || String::from_utf8_lossy(body));
585            }
586            client.execute(request).await
587        }
588        .await
589        {
590            Ok(response) => response,
591            Err(error) => {
592                metrics::record_upstream_attempt(None);
593                return Err(AttemptFailure {
594                    error: convert_reqwest_error(error),
595                    status: None,
596                    retry_after: None,
597                });
598            }
599        };
600        let status = response.status();
601        if status.is_success() {
602            if streaming {
603                let upstream_headers = response.headers().clone();
604                let chunks = match prepare_response_stream(response, backend, target_name).await {
605                    Ok(chunks) => chunks,
606                    Err(error) => {
607                        metrics::record_upstream_attempt(None);
608                        return Err(AttemptFailure {
609                            error,
610                            status: Some(status),
611                            retry_after: None,
612                        });
613                    }
614                };
615                metrics::record_upstream_attempt(Some(status.as_u16()));
616                return Ok(EncodedResponse::Streaming {
617                    status: status.as_u16(),
618                    chunks,
619                    upstream_headers,
620                });
621            }
622            let upstream_headers = response.headers().clone();
623            let body = match response.bytes().await {
624                Ok(body) => body,
625                Err(error) => {
626                    metrics::record_upstream_attempt(None);
627                    return Err(AttemptFailure {
628                        error: convert_reqwest_error(error),
629                        status: Some(status),
630                        retry_after: None,
631                    });
632                }
633            };
634            metrics::record_upstream_attempt(Some(status.as_u16()));
635            crate::payload_capture::record("response", || String::from_utf8_lossy(&body));
636            return Ok(EncodedResponse::Buffered {
637                status: status.as_u16(),
638                body: body.to_vec(),
639                upstream_headers,
640            });
641        }
642
643        let retry_after = retry_after_delay(response.headers());
644        let headers = Box::new(response.headers().clone());
645        let body = match response.text().await {
646            Ok(body) => body,
647            Err(error) => {
648                metrics::record_upstream_attempt(None);
649                return Err(AttemptFailure {
650                    error: convert_reqwest_error(error),
651                    status: Some(status),
652                    retry_after,
653                });
654            }
655        };
656        let body = redact_forwarded_headers(body, metadata, backend.is_forwarding_auth());
657        metrics::record_upstream_attempt(Some(status.as_u16()));
658        let error =
659            if status == reqwest::StatusCode::BAD_REQUEST && backend.is_context_overflow(&body) {
660                LlmClientError::ContextWindowExceeded {
661                    model: target_name.clone(),
662                    message: body,
663                }
664            } else {
665                LlmClientError::UpstreamHttp {
666                    status,
667                    body,
668                    headers,
669                }
670            };
671        Err(AttemptFailure {
672            error,
673            status: Some(status),
674            retry_after,
675        })
676    }
677
678    /// Calls the selected target using its configured provider model and backend.
679    /// `target_name` takes precedence over the request's model field.
680    /// Request metadata selects the wire format, falling back to the target's default.
681    pub async fn call_rewrite_model(
682        &self,
683        request: Request,
684        target_name: Option<&ModelId>,
685    ) -> Result<Response> {
686        let Request {
687            mut llm_request,
688            metadata,
689            ..
690        } = request;
691
692        let selected_target = target_name
693            .cloned()
694            .or_else(|| llm_request.model.map(ModelId::from))
695            .ok_or_else(|| LlmClientError::InvalidRequest {
696                message: "no model given".to_string(),
697            })?;
698        llm_request.model = Some(self.provider_model(&selected_target).to_string());
699
700        let orig_format = metadata.as_ref().and_then(|m| m.wire_format);
701        let wire_format = orig_format.unwrap_or(
702            self.configs_by_target
703                .get(&selected_target)
704                .map(|config| config.default_backend.wire_format())
705                .ok_or_else(|| LlmClientError::Configuration {
706                    message: format!("no backend configured for model {selected_target:?}"),
707                })?,
708        );
709        let backend = self
710            .backend_for(&selected_target, wire_format)
711            .ok_or_else(|| LlmClientError::Configuration {
712                message: format!(
713                    "model {selected_target:?} has no backend for format {wire_format}"
714                ),
715            })?;
716
717        let http_response = self
718            .send_encoded(
719                backend,
720                wire_format,
721                llm_request,
722                metadata.as_ref(),
723                &selected_target,
724                UpstreamEndpoint::Completion,
725            )
726            .await?;
727
728        let (llm_response, upstream_headers) = match http_response {
729            EncodedResponse::Streaming {
730                chunks,
731                upstream_headers,
732                ..
733            } => (LlmResponse::Stream(chunks), upstream_headers),
734            EncodedResponse::Buffered {
735                body,
736                upstream_headers,
737                ..
738            } => {
739                let body = serde_json::from_slice::<Value>(&body).map_err(|error| {
740                    LlmClientError::ResponseTranslation(format!("invalid upstream JSON: {error}"))
741                })?;
742                // Map a provider's failed generation to 502, even under HTTP 200.
743                // Redact forwarded credentials before returning the provider error.
744                let mut agg =
745                    observed_translation::decode_response(&body, wire_format).map_err(|error| {
746                        match error {
747                            TranslationError::UpstreamFailure { error } => {
748                                LlmClientError::UpstreamHttp {
749                                    status: StatusCode::BAD_GATEWAY,
750                                    body: redact_forwarded_headers(
751                                        json!({ "error": error }).to_string(),
752                                        metadata.as_ref(),
753                                        backend.is_forwarding_auth(),
754                                    ),
755                                    headers: Box::new(upstream_headers.clone()),
756                                }
757                            }
758                            error => LlmClientError::ResponseTranslation(error.to_string()),
759                        }
760                    })?;
761                // The gateway may report a buffered charge only in its response header.
762                if agg.usage.provider_cost.is_none() {
763                    agg.usage.provider_cost = upstream_headers
764                        .get("x-litellm-response-cost")
765                        .and_then(|value| value.to_str().ok())
766                        .and_then(|value| value.trim().parse::<f64>().ok())
767                        .filter(|usd| usd.is_finite() && *usd >= 0.0);
768                }
769                (LlmResponse::Agg(agg), upstream_headers)
770            }
771        };
772
773        Ok(Response {
774            llm_response,
775            metadata,
776            upstream_headers,
777        })
778    }
779}
780
781#[async_trait]
782impl RoutedLlmClient for TranslatingLlmClient {
783    fn provider_model<'a>(&'a self, target: &'a ModelId) -> &'a ModelId {
784        TranslatingLlmClient::provider_model(self, target)
785    }
786
787    async fn call(&self, request: Request) -> Result<Response> {
788        self.call_rewrite_model(request, None).await
789    }
790}
791
792#[derive(Clone, Copy)]
793enum UpstreamEndpoint {
794    Completion,
795    Auxiliary(AuxiliaryOperation),
796}
797
798impl UpstreamEndpoint {
799    fn url(self, backend: &Backend) -> String {
800        match self {
801            UpstreamEndpoint::Completion => backend.url(),
802            UpstreamEndpoint::Auxiliary(operation) => operation.url(backend),
803        }
804    }
805
806    fn allows_streaming(self) -> bool {
807        matches!(self, UpstreamEndpoint::Completion)
808    }
809}
810
811enum EncodedResponse {
812    Buffered {
813        status: u16,
814        body: Vec<u8>,
815        upstream_headers: HeaderMap,
816    },
817    Streaming {
818        status: u16,
819        chunks: LlmResponseStream,
820        upstream_headers: HeaderMap,
821    },
822}
823
824impl EncodedResponse {
825    fn status(&self) -> u16 {
826        match self {
827            EncodedResponse::Buffered { status, .. }
828            | EncodedResponse::Streaming { status, .. } => *status,
829        }
830    }
831}
832
833// The typed error decides retry eligibility; status and Retry-After feed
834// attempt telemetry and delay selection.
835struct AttemptFailure {
836    error: LlmClientError,
837    status: Option<StatusCode>,
838    retry_after: Option<Duration>,
839}
840
841fn deadline_error(timeout: Duration) -> LlmClientError {
842    LlmClientError::Timeout {
843        source: Box::new(std::io::Error::new(
844            std::io::ErrorKind::TimedOut,
845            format!(
846                "response did not finish within {} ms, retries included",
847                duration_millis(timeout)
848            ),
849        )),
850    }
851}
852
853impl AttemptFailure {
854    fn is_retryable(&self) -> bool {
855        is_transient_failure(&self.error)
856    }
857}
858
859fn is_transient_failure(error: &LlmClientError) -> bool {
860    if error.is_attachment_rejection() {
861        return false;
862    }
863    match error {
864        LlmClientError::Transport { .. } | LlmClientError::Timeout { .. } => true,
865        LlmClientError::UpstreamHttp { status, .. } => {
866            metrics::is_retryable_http_status(status.as_u16())
867        }
868        _ => false,
869    }
870}
871
872fn stream_with_deadline(
873    chunks: LlmResponseStream,
874    deadline: Option<(tokio::time::Instant, Duration)>,
875) -> LlmResponseStream {
876    let Some((at, timeout)) = deadline else {
877        return chunks;
878    };
879    stream::unfold(Some(chunks), move |chunks| async move {
880        let mut chunks = chunks?;
881        let chunk = tokio::select! {
882            biased;
883            _ = tokio::time::sleep_until(at) => return Some((Err(deadline_error(timeout)), None)),
884            chunk = chunks.next() => chunk?,
885        };
886        let next = chunk.is_ok().then_some(chunks);
887        Some((chunk, next))
888    })
889    .boxed()
890}
891
892async fn prepare_response_stream(
893    response: reqwest::Response,
894    backend: &Backend,
895    target_name: &ModelId,
896) -> Result<LlmResponseStream> {
897    let bytes = response.bytes_stream().map(|chunk| {
898        chunk
899            .map(|bytes| bytes.to_vec())
900            .map_err(convert_reqwest_error)
901    });
902    let mut chunks = decode_stream(bytes, backend.wire_format())?;
903    match chunks.next().await {
904        None => Ok(stream::empty().boxed()),
905        // Nothing has reached the caller, so transport failures can still be retried.
906        Some(Err(error @ (LlmClientError::Transport { .. } | LlmClientError::Timeout { .. }))) => {
907            Err(error)
908        }
909        Some(first) => {
910            // An in-band context overflow skips retries and advances to another candidate.
911            if let Some(message) = first_event_overflow(&first, backend) {
912                return Err(LlmClientError::ContextWindowExceeded {
913                    model: target_name.clone(),
914                    message,
915                });
916            }
917            Ok(stream::once(ready(first)).chain(chunks).boxed())
918        }
919    }
920}
921
922// The overflow message when a stream's first event is an in-band provider rejection
923// of the whole request, rather than the start of a response.
924fn first_event_overflow(
925    first: &Result<LlmResponseStreamEvent>,
926    backend: &Backend,
927) -> Option<String> {
928    first
929        .as_ref()
930        .ok()?
931        .normalized()
932        .iter()
933        .find_map(|chunk| match chunk {
934            LlmResponseChunk::StreamError { message } if backend.is_context_overflow(message) => {
935                Some(message.clone())
936            }
937            _ => None,
938        })
939}
940
941// Uses Retry-After when supplied, capped so an upstream cannot stall a request indefinitely.
942fn retry_after_delay(headers: &HeaderMap) -> Option<Duration> {
943    let value = headers.get(RETRY_AFTER)?.to_str().ok()?;
944    let delay = if let Ok(seconds) = value.parse::<u64>() {
945        Duration::from_secs(seconds)
946    } else {
947        let retry_at = httpdate::parse_http_date(value).ok()?;
948        retry_at
949            .duration_since(SystemTime::now())
950            .unwrap_or(Duration::ZERO)
951    };
952    Some(delay.min(MAX_RETRY_AFTER))
953}
954
955fn retry_delay(retry_number: u64, retry_after: Option<Duration>) -> Duration {
956    // Retry-After wins; otherwise double 250 ms up to the two-second cap.
957    retry_after.unwrap_or_else(|| {
958        let multiplier = 1_u32 << retry_number.min(3);
959        INITIAL_RETRY_DELAY
960            .saturating_mul(multiplier)
961            .min(MAX_RETRY_BACKOFF)
962    })
963}
964
965fn duration_millis(duration: Duration) -> u64 {
966    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
967}
968
969fn record_gen_ai_request(url: &str, model: &str, streaming: bool) {
970    let span = tracing::Span::current();
971    span.record("gen_ai.request.model", model);
972    if streaming {
973        span.record("gen_ai.request.stream", true);
974    }
975    if let Ok(url) = reqwest::Url::parse(url) {
976        if let Some(host) = url.host_str() {
977            span.record("server.address", host);
978        }
979        if let Some(port) = url.port_or_known_default() {
980            span.record("server.port", i64::from(port));
981        }
982    }
983}
984
985pub(crate) fn convert_reqwest_error(error: reqwest::Error) -> LlmClientError {
986    // Reqwest labels truncated or otherwise unreadable response bodies as decode
987    // errors, so distinguish them from serde JSON failures at the call site.
988    let error = error.without_url();
989    // reqwest reports a connect-phase timeout as both `is_connect()` and
990    // `is_timeout()`. Check connect first: no request was sent on the failed
991    // connection, so it is a transport failure like a refused connection.
992    if error.is_connect() {
993        LlmClientError::Transport {
994            source: Box::new(error),
995        }
996    } else if error.is_timeout() {
997        LlmClientError::Timeout {
998            source: Box::new(error),
999        }
1000    } else if error.is_builder() {
1001        LlmClientError::Configuration {
1002            message: format!("failed to build upstream request: {error}"),
1003        }
1004    } else {
1005        LlmClientError::Transport {
1006            source: Box::new(error),
1007        }
1008    }
1009}
1010
1011// Forwards safe metadata headers, or all application headers when forwarding auth.
1012fn forward_metadata_headers(
1013    builder: RequestBuilder,
1014    metadata: Option<&Metadata>,
1015    backend: &Backend,
1016) -> RequestBuilder {
1017    let Some(headers) = metadata.and_then(|metadata| metadata.http_headers.as_ref()) else {
1018        return builder;
1019    };
1020    let mut forwarded = HeaderMap::with_capacity(headers.len());
1021    for (name, value) in headers {
1022        let is_allowed = if backend.is_forwarding_auth() {
1023            !is_non_forwardable_header(name.as_str(), headers)
1024                && !backend.is_provider_owned_header(name.as_str())
1025        } else {
1026            is_allowed_metadata_header(name.as_str())
1027        };
1028        if !is_allowed {
1029            continue;
1030        }
1031        forwarded.append(name, value.clone());
1032    }
1033    builder.headers(forwarded)
1034}
1035
1036// Configured headers replace existing values for the same case-insensitive name.
1037fn apply_extra_headers(builder: RequestBuilder, backend: &Backend) -> RequestBuilder {
1038    let mut headers = HeaderMap::with_capacity(backend.extra_headers().len());
1039    // Names and values are validated by TranslatingLlmClient::new.
1040    for (name, value) in backend.extra_headers() {
1041        let name = HeaderName::from_bytes(name.as_bytes()).expect("validated header name");
1042        let value = HeaderValue::from_bytes(value.as_bytes()).expect("validated header value");
1043        headers.insert(name, value);
1044    }
1045    builder.headers(headers)
1046}
1047
1048// Overwrites the outbound body's `model` field with the resolved model id.
1049fn set_json_model(body: &mut Value, model: &str) {
1050    if let Value::Object(object) = body {
1051        object.insert("model".to_string(), Value::String(model.to_string()));
1052    }
1053}
1054
1055// The Codex Responses endpoint requires item-list input even on the preserved-body path.
1056fn normalize_codex_string_input(url: &str, body: &mut Value) {
1057    let codex = reqwest::Url::parse(url).ok().is_some_and(|url| {
1058        url.path()
1059            .trim_end_matches('/')
1060            .ends_with("/backend-api/codex/responses")
1061    });
1062    if codex && let Some(input @ Value::String(_)) = body.get_mut("input") {
1063        let text = input.take();
1064        *input = json!([{"type": "message", "role": "user", "content": text}]);
1065    }
1066}
1067
1068fn rejects_template_options(error: &LlmClientError) -> bool {
1069    let LlmClientError::UpstreamHttp { status, body, .. } = error else {
1070        return false;
1071    };
1072    if !matches!(
1073        *status,
1074        StatusCode::BAD_REQUEST | StatusCode::UNPROCESSABLE_ENTITY
1075    ) {
1076        return false;
1077    }
1078    let parsed = serde_json::from_str::<Value>(body).ok();
1079    let error = parsed.as_ref().and_then(|value| value.get("error"));
1080    let message = match &parsed {
1081        Some(_) => error
1082            .and_then(|error| error.get("message"))
1083            .and_then(Value::as_str)
1084            .unwrap_or_default(),
1085        None => body,
1086    }
1087    .to_ascii_lowercase();
1088    let field = error
1089        .and_then(|error| error.get("param"))
1090        .and_then(Value::as_str);
1091    let code = error
1092        .and_then(|error| error.get("code"))
1093        .and_then(Value::as_str);
1094    (field == Some("chat_template_kwargs") || message.contains("chat_template_kwargs"))
1095        && (matches!(code, Some("unknown_parameter" | "unsupported_parameter"))
1096            || [
1097                "unrecognized request argument",
1098                "unknown parameter",
1099                "unsupported parameter",
1100                "unexpected keyword argument",
1101                "unknown field",
1102                "unsupported field",
1103                "extra inputs are not permitted",
1104            ]
1105            .iter()
1106            .any(|phrase| message.contains(phrase)))
1107}
1108
1109// Drops fields accepted by OpenAI-like APIs but rejected by Anthropic Messages.
1110//
1111// A router can serve earlier turns of a session from an OpenAI-format target and
1112// later turns from an Anthropic one. Clients such as Claude Code send
1113// `context_management` on every turn, so the Anthropic leg must strip it or the
1114// upstream rejects the request (for example `clear_thinking_20251015` strategy
1115// requires `thinking` to be enabled or adaptive).
1116fn strip_anthropic_incompatible_fields(body: &mut Value) {
1117    if let Value::Object(object) = body {
1118        object.remove("reasoning_effort");
1119        object.remove("context_management");
1120        // `strict: false` is the default, and Bedrock rejects the field outright.
1121        if let Some(Value::Array(tools)) = object.get_mut("tools") {
1122            for tool in tools {
1123                if let Value::Object(tool) = tool
1124                    && tool.get("strict") == Some(&Value::Bool(false))
1125                {
1126                    tool.remove("strict");
1127                }
1128            }
1129        }
1130    }
1131}
1132
1133// NVIDIA Inference API's Anthropic-compatible schema rejects the strict tool-use
1134// extension that native Anthropic accepts.
1135fn nvidia_inference_api_backend(backend: &Backend) -> bool {
1136    reqwest::Url::parse(backend.base_url())
1137        .ok()
1138        .is_some_and(|url| {
1139            url.host_str()
1140                .is_some_and(|host| host.eq_ignore_ascii_case("inference-api.nvidia.com"))
1141        })
1142}
1143
1144fn strip_anthropic_tool_strict(body: &mut Value) {
1145    let Some(tools) = body.get_mut("tools").and_then(Value::as_array_mut) else {
1146        return;
1147    };
1148    for tool in tools.iter_mut().filter_map(Value::as_object_mut) {
1149        tool.remove("strict");
1150    }
1151}
1152
1153// Removes replayed `thinking` blocks that carry no signature.
1154//
1155// Anthropic requires signed thinking blocks on replay. A router can serve earlier
1156// turns of a session from an OpenAI-format target whose thinking blocks are
1157// unsigned, so the Anthropic leg must drop them or the upstream rejects the
1158// request. Bedrock enforces this (surfacing as a SigV4 signature mismatch) where
1159// Azure-hosted Anthropic currently does not.
1160fn strip_unsigned_thinking_blocks(body: &mut Value) {
1161    let Value::Object(object) = body else {
1162        return;
1163    };
1164    let Some(Value::Array(messages)) = object.get_mut("messages") else {
1165        return;
1166    };
1167    for message in messages {
1168        strip_unsigned_thinking_from_message(message);
1169    }
1170}
1171
1172// Drops unsigned thinking blocks from one message, collapsing content that ends
1173// up empty to an empty string so the message stays valid.
1174fn strip_unsigned_thinking_from_message(message: &mut Value) {
1175    let Value::Object(message) = message else {
1176        return;
1177    };
1178    let Some(Value::Array(blocks)) = message.get("content") else {
1179        return;
1180    };
1181    if !blocks.iter().any(is_unsigned_thinking_block) {
1182        return;
1183    }
1184    let Some(Value::Array(blocks)) = message.get_mut("content") else {
1185        return;
1186    };
1187    blocks.retain(|block| !is_unsigned_thinking_block(block));
1188    if blocks.is_empty() {
1189        message.insert("content".to_string(), Value::String(String::new()));
1190    }
1191}
1192
1193// A thinking block is unsigned when `signature` is absent or empty.
1194fn is_unsigned_thinking_block(block: &Value) -> bool {
1195    if block.get("type").and_then(Value::as_str) != Some("thinking") {
1196        return false;
1197    }
1198    !matches!(
1199        block.get("signature").and_then(Value::as_str),
1200        Some(signature) if !signature.is_empty()
1201    )
1202}
1203
1204// Forces the target's configured reasoning effort onto the outbound body, replacing the
1205// caller's value. Unlike `extra_body`, this is an override: a route that sends one model at a
1206// higher effort than the client asked for is the point of the setting.
1207fn apply_reasoning_effort(body: &mut Value, backend: &Backend) {
1208    let Some(effort) = backend.reasoning_effort() else {
1209        return;
1210    };
1211    let Value::Object(object) = body else {
1212        return;
1213    };
1214    match backend {
1215        // Responses nests effort under `reasoning`, Anthropic under `output_config`.
1216        Backend::OpenAiResponses(_) => set_nested_effort(object, "reasoning", effort),
1217        Backend::Anthropic(_) => set_nested_effort(object, "output_config", effort),
1218        Backend::OpenAiChat(_) => {
1219            // Chat Completions takes effort as a top-level field.
1220            object.insert(
1221                "reasoning_effort".to_string(),
1222                Value::String(effort.to_string()),
1223            );
1224        }
1225    }
1226}
1227
1228// Replaces only `effort` inside `key`, keeping fields the caller set next to it (`summary` or
1229// `format`, for example). A non-object value there is malformed and is replaced whole.
1230fn set_nested_effort(object: &mut serde_json::Map<String, Value>, key: &str, effort: &str) {
1231    let container = object
1232        .entry(key.to_string())
1233        .or_insert_with(|| Value::Object(serde_json::Map::new()));
1234    if !container.is_object() {
1235        *container = Value::Object(serde_json::Map::new());
1236    }
1237    if let Value::Object(container) = container {
1238        container.insert("effort".to_string(), Value::String(effort.to_string()));
1239    }
1240}
1241
1242// Applies target defaults without overriding fields supplied by the caller.
1243fn merge_extra_body(body: &mut Value, extra_body: &BTreeMap<String, Value>) {
1244    let Value::Object(object) = body else {
1245        return;
1246    };
1247    for (key, value) in extra_body {
1248        object.entry(key.clone()).or_insert_with(|| value.clone());
1249    }
1250}
1251
1252fn omit_configured_body_fields(body: &mut Value, omit_body_fields: &BTreeSet<String>) {
1253    let Value::Object(object) = body else {
1254        return;
1255    };
1256    for key in omit_body_fields {
1257        object.remove(key);
1258    }
1259}
1260
1261// Anthropic and Bedrock both cap a request at four blocks carrying
1262// `cache_control`, counting tools, system blocks and message blocks together.
1263const MAX_CACHE_CONTROL_BLOCKS: usize = 4;
1264
1265// Counts the blocks upstream will see carrying a `cache_control` marker. The
1266// marker's own value holds no such key, so it is never counted twice.
1267fn count_cache_control_blocks(value: &Value) -> usize {
1268    match value {
1269        Value::Object(map) => {
1270            usize::from(map.contains_key("cache_control"))
1271                + map.values().map(count_cache_control_blocks).sum::<usize>()
1272        }
1273        Value::Array(items) => items.iter().map(count_cache_control_blocks).sum(),
1274        _ => 0,
1275    }
1276}
1277
1278// This helper marks the final caller content block before any temporary notes, if policy permits.
1279fn enable_anthropic_prompt_caching(body: &mut Value, temporary_note_count: usize) {
1280    // Anthropic rejects a fifth cache marker with HTTP 400.
1281    // This check preserves the caller's markers when the request has reached that limit.
1282    if count_cache_control_blocks(body) >= MAX_CACHE_CONTROL_BLOCKS {
1283        return;
1284    }
1285    // Requests with only a top-level `1h` policy can return HTTP 400.
1286    // New block markers match the caller's TTL on turns with or without notes.
1287    let marker = body
1288        .get("cache_control")
1289        .cloned()
1290        .unwrap_or_else(|| serde_json::json!({"type":"ephemeral"}));
1291    let Some(messages) = body.get_mut("messages").and_then(Value::as_array_mut) else {
1292        return;
1293    };
1294    let mut remaining = temporary_note_count;
1295    // Temporary guidance is absent next turn, so the breakpoint must precede it.
1296    for message in messages.iter_mut().rev() {
1297        match message.get_mut("content") {
1298            Some(content @ Value::String(_)) if remaining == 0 => {
1299                let text = std::mem::take(content);
1300                *content = serde_json::json!([{
1301                    "type": "text", "text": text, "cache_control": marker
1302                }]);
1303                return;
1304            }
1305            Some(Value::String(_)) => remaining = remaining.saturating_sub(1),
1306            Some(Value::Array(blocks)) => {
1307                if remaining >= blocks.len() {
1308                    remaining -= blocks.len();
1309                    continue;
1310                }
1311                let index = blocks.len() - remaining - 1;
1312                if let Some(block) = blocks[index].as_object_mut() {
1313                    block.entry("cache_control".to_string()).or_insert(marker);
1314                }
1315                return;
1316            }
1317            _ => {}
1318        }
1319    }
1320}
1321
1322// GPT-5.6 and GPT-6 cache writes end at selected message or content boundaries.
1323// A temporary suffix needs a separate cache entry before it so the next request can reuse the prefix.
1324fn enable_openai_guidance_caching(
1325    body: &mut Value,
1326    format: WireFormat,
1327    model: &ModelId,
1328    suffix: usize,
1329) {
1330    let name = model.as_str().rsplit('/').next().unwrap_or_default();
1331    let supported = name == "gpt-5.6"
1332        || name.starts_with("gpt-5.6-")
1333        || name == "gpt-6"
1334        || name.starts_with("gpt-6-")
1335        || name.starts_with("gpt-6.");
1336    // Explicit-only callers choose their write locations.
1337    // This helper adds markers only for names recognized by its model-name check.
1338    if suffix == 0
1339        || !supported
1340        || body
1341            .pointer("/prompt_cache_options/mode")
1342            .and_then(Value::as_str)
1343            == Some("explicit")
1344    {
1345        return;
1346    }
1347    let key = if format == WireFormat::OpenAiResponses {
1348        "input"
1349    } else {
1350        "messages"
1351    };
1352    let Some(items) = body.get_mut(key).and_then(Value::as_array_mut) else {
1353        return;
1354    };
1355    let marker_count = items
1356        .iter()
1357        .map(|item| {
1358            ["content", "output"]
1359                .iter()
1360                .filter_map(|key| item.get(key).and_then(Value::as_array))
1361                .flatten()
1362                .filter(|block| block.get("prompt_cache_breakpoint").is_some())
1363                .count()
1364        })
1365        .sum::<usize>();
1366    // Implicit mode reserves one of the four write slots for the provider's final breakpoint.
1367    if marker_count >= 3 {
1368        return;
1369    }
1370    let Some(prefix_len) = items.len().checked_sub(suffix) else {
1371        return;
1372    };
1373    for item in items[..prefix_len].iter_mut().rev() {
1374        let field = if item.get("type").and_then(Value::as_str) == Some("function_call_output") {
1375            "output"
1376        } else if matches!(
1377            item.get("role").and_then(Value::as_str),
1378            Some("user" | "tool" | "developer" | "system")
1379        ) {
1380            "content"
1381        } else {
1382            continue;
1383        };
1384        let Some(content) = item.get_mut(field) else {
1385            continue;
1386        };
1387        if let Value::String(text) = content {
1388            let text = std::mem::take(text);
1389            let kind = if format == WireFormat::OpenAiResponses {
1390                "input_text"
1391            } else {
1392                "text"
1393            };
1394            *content = serde_json::json!([{"type":kind,"text":text}]);
1395        }
1396        // Empty content arrays have no block to mark, so the search continues through earlier items.
1397        if let Some(block) = content
1398            .as_array_mut()
1399            .and_then(|blocks| blocks.last_mut())
1400            .and_then(Value::as_object_mut)
1401        {
1402            block
1403                .entry("prompt_cache_breakpoint".to_string())
1404                .or_insert_with(|| serde_json::json!({"mode":"explicit"}));
1405            return;
1406        }
1407    }
1408}
1409
1410// Requests streamed Chat usage by default while preserving an explicit caller choice.
1411fn ensure_openai_stream_usage(body: &mut Value) {
1412    let Value::Object(object) = body else {
1413        return;
1414    };
1415    if object.get("stream").and_then(Value::as_bool) != Some(true) {
1416        return;
1417    }
1418
1419    match object.get_mut("stream_options") {
1420        Some(Value::Object(options)) => {
1421            options
1422                .entry("include_usage".to_string())
1423                .or_insert(Value::Bool(true));
1424        }
1425        _ => {
1426            let mut options = Map::new();
1427            options.insert("include_usage".to_string(), Value::Bool(true));
1428            object.insert("stream_options".to_string(), Value::Object(options));
1429        }
1430    }
1431}
1432
1433fn is_allowed_metadata_header(name: &str) -> bool {
1434    ALLOWED_METADATA_HEADERS
1435        .iter()
1436        .any(|allowed| name.eq_ignore_ascii_case(allowed))
1437}
1438
1439fn is_non_forwardable_header(name: &str, headers: &HeaderMap) -> bool {
1440    NON_FORWARDABLE_HEADERS
1441        .iter()
1442        .any(|blocked| name.eq_ignore_ascii_case(blocked))
1443        || headers.get_all("connection").iter().any(|value| {
1444            value
1445                .as_bytes()
1446                .split(|byte| *byte == b',')
1447                .any(|option| option.trim_ascii().eq_ignore_ascii_case(name.as_bytes()))
1448        })
1449}
1450
1451// Unknown application headers can carry credentials when auth forwarding is enabled.
1452fn redact_forwarded_headers(
1453    mut body: String,
1454    metadata: Option<&Metadata>,
1455    is_forwarding_auth: bool,
1456) -> String {
1457    if !is_forwarding_auth {
1458        return body;
1459    }
1460    let Some(headers) = metadata.and_then(|metadata| metadata.http_headers.as_ref()) else {
1461        return body;
1462    };
1463    for (name, value) in headers {
1464        if is_non_forwardable_header(name.as_str(), headers) {
1465            continue;
1466        }
1467        let Ok(value) = value.to_str() else {
1468            continue;
1469        };
1470        if !value.is_empty() {
1471            body = body.replace(value, "[REDACTED]");
1472        }
1473    }
1474    body
1475}
1476
1477#[cfg(test)]
1478mod tests {
1479    use std::collections::BTreeMap;
1480    use std::error::Error;
1481    use std::io::{Read, Write};
1482    use std::sync::Arc;
1483    use std::sync::atomic::{AtomicUsize, Ordering};
1484    use std::thread::JoinHandle;
1485
1486    use serde_json::json;
1487    use switchyard_protocol::{completion_text, text_request};
1488    use wiremock::matchers::{method, path};
1489    use wiremock::{Mock, MockServer, ResponseTemplate};
1490
1491    use super::*;
1492    use crate::backend::HttpBackendConfig;
1493
1494    /// Decodes a wire body into a request, as a server endpoint does before calling the client.
1495    fn wire_request(
1496        body: Value,
1497        http_headers: Option<http::HeaderMap>,
1498        wire_format: WireFormat,
1499    ) -> switchyard_translation::Result<Request> {
1500        Ok(Request {
1501            llm_request: switchyard_translation::decode_request(wire_format, &body)?,
1502            raw_request: None,
1503            metadata: Some(Metadata {
1504                http_headers,
1505                ..Default::default()
1506            }),
1507        })
1508    }
1509
1510    fn assert_tool_call_name(agg: &switchyard_protocol::AggLlmResponse, name: &str) {
1511        let Some(switchyard_protocol::ContentBlock::ToolCall(call)) =
1512            agg.outputs[0].content.first()
1513        else {
1514            panic!("expected a tool call, got {:?}", agg.outputs[0].content);
1515        };
1516        assert_eq!(call.name, name);
1517    }
1518
1519    fn config(base_url: &str) -> HttpBackendConfig {
1520        HttpBackendConfig {
1521            base_url: base_url.to_string(),
1522            api_key: Some("secret".to_string()),
1523            forward_auth: false,
1524            extra_headers: BTreeMap::new(),
1525            extra_body: BTreeMap::new(),
1526            omit_body_fields: BTreeSet::new(),
1527            reasoning_effort: None,
1528            max_retries: 0,
1529            failure_cooldown: Duration::ZERO,
1530            timeout: None,
1531        }
1532    }
1533
1534    #[test]
1535    fn provider_endpoint_urls_preserve_query_and_fragment() {
1536        let invalid_url = "not a URL/";
1537        let backend = Backend::OpenAiResponses(config(invalid_url));
1538        assert!(openai_url(invalid_url, "/responses").is_err());
1539        assert_eq!(backend.url(), invalid_url);
1540        assert_eq!(
1541            AuxiliaryOperation::ResponsesCompact.url(&backend),
1542            invalid_url
1543        );
1544
1545        let anthropic = Backend::Anthropic(config(invalid_url));
1546        assert_eq!(anthropic.url(), invalid_url);
1547        assert_eq!(anthropic.count_tokens_url(), invalid_url);
1548
1549        for path in ["", "/v1/", "/v1/messages"] {
1550            for tail in [
1551                "",
1552                "?api-version=2026-09-01&value=%2F/",
1553                "#fragment?value=/",
1554            ] {
1555                let base_url = format!("https://example.com{path}{tail}");
1556                let backend = Backend::Anthropic(config(&base_url));
1557                assert_eq!(
1558                    backend.url(),
1559                    format!("https://example.com/v1/messages{tail}")
1560                );
1561                assert_eq!(
1562                    AuxiliaryOperation::AnthropicCountTokens.url(&backend),
1563                    format!("https://example.com/v1/messages/count_tokens{tail}")
1564                );
1565            }
1566        }
1567
1568        for path in ["/v1", "/v1/responses/", "/v1/chat/completions"] {
1569            for tail in [
1570                "",
1571                "?api-version=2026-09-01&value=%2F/",
1572                "#fragment?value=/",
1573            ] {
1574                let base_url = format!("https://example.com{path}{tail}");
1575                let responses = Backend::OpenAiResponses(config(&base_url));
1576                let chat = Backend::OpenAiChat(config(&base_url));
1577                for (actual, endpoint) in [
1578                    (responses.url(), "/responses"),
1579                    (chat.url(), "/chat/completions"),
1580                    (
1581                        AuxiliaryOperation::ResponsesCompact.url(&responses),
1582                        "/responses/compact",
1583                    ),
1584                    (
1585                        AuxiliaryOperation::ResponsesInputTokens.url(&responses),
1586                        "/responses/input_tokens",
1587                    ),
1588                ] {
1589                    assert_eq!(actual, format!("https://example.com/v1{endpoint}{tail}"));
1590                }
1591            }
1592        }
1593    }
1594
1595    fn config_with_retries(base_url: &str, max_retries: u32) -> HttpBackendConfig {
1596        HttpBackendConfig {
1597            max_retries,
1598            ..config(base_url)
1599        }
1600    }
1601
1602    fn forwarding_config(base_url: &str) -> HttpBackendConfig {
1603        HttpBackendConfig {
1604            api_key: None,
1605            forward_auth: true,
1606            ..config(base_url)
1607        }
1608    }
1609
1610    // A one-model config list: "gpt" served over OpenAI Chat at base_url.
1611    fn chat_map(base_url: &str) -> Vec<ModelConfig> {
1612        vec![ModelConfig::new(
1613            "gpt",
1614            Backend::OpenAiChat(config(base_url)),
1615            None,
1616        )]
1617    }
1618
1619    fn responses_map(base_url: &str) -> Vec<ModelConfig> {
1620        vec![ModelConfig::new(
1621            "gpt",
1622            Backend::OpenAiResponses(config(base_url)),
1623            None,
1624        )]
1625    }
1626
1627    fn chat_map_with_extra_body(
1628        base_url: &str,
1629        extra_body: BTreeMap<String, Value>,
1630    ) -> Vec<ModelConfig> {
1631        let mut backend = config(base_url);
1632        backend.extra_body = extra_body;
1633        vec![ModelConfig::new("gpt", Backend::OpenAiChat(backend), None)]
1634    }
1635
1636    fn chat_map_with_omit_body_fields(
1637        base_url: &str,
1638        omit_body_fields: BTreeSet<String>,
1639    ) -> Vec<ModelConfig> {
1640        let mut backend = config(base_url);
1641        backend.omit_body_fields = omit_body_fields;
1642        vec![ModelConfig::new("gpt", Backend::OpenAiChat(backend), None)]
1643    }
1644
1645    fn chat_map_with_effort(base_url: &str, effort: &str) -> Vec<ModelConfig> {
1646        let mut backend = config(base_url);
1647        backend.reasoning_effort = Some(effort.to_string());
1648        vec![ModelConfig::new("gpt", Backend::OpenAiChat(backend), None)]
1649    }
1650
1651    fn responses_map_with_effort(base_url: &str, effort: &str) -> Vec<ModelConfig> {
1652        let mut backend = config(base_url);
1653        backend.reasoning_effort = Some(effort.to_string());
1654        vec![ModelConfig::new(
1655            "gpt",
1656            Backend::OpenAiResponses(backend),
1657            None,
1658        )]
1659    }
1660
1661    fn anthropic_map(base_url: &str) -> Vec<ModelConfig> {
1662        vec![ModelConfig::new(
1663            "claude",
1664            Backend::Anthropic(config(base_url)),
1665            None,
1666        )]
1667    }
1668
1669    #[tokio::test]
1670    async fn model_properties_uses_configured_auth_and_backend_path()
1671    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
1672        for (base_path, props_path) in [
1673            ("/v1", "/props"),
1674            ("/v1/", "/props"),
1675            ("/v1/chat/completions", "/props"),
1676            ("/v1/responses/", "/props"),
1677            ("/prefix/v1", "/prefix/props"),
1678            ("/prefix/v1/chat/completions", "/prefix/props"),
1679            ("/prefix/v1/responses", "/prefix/props"),
1680            ("/prefix/", "/prefix/props"),
1681        ] {
1682            let server = MockServer::start().await;
1683            Mock::given(method("GET"))
1684                .and(path(props_path))
1685                .and(wiremock::matchers::header("authorization", "Bearer secret"))
1686                .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1687                    "default_generation_settings": {"n_ctx": 65_536}
1688                })))
1689                .expect(1)
1690                .mount(&server)
1691                .await;
1692            let client =
1693                TranslatingLlmClient::new(&chat_map(&format!("{}{base_path}", server.uri())))?;
1694            let properties = client
1695                .get_model_properties(
1696                    &ModelId::from("gpt"),
1697                    WireFormat::OpenAiChat,
1698                    Duration::from_secs(1),
1699                )
1700                .await?;
1701            assert_eq!(properties["default_generation_settings"]["n_ctx"], 65_536);
1702        }
1703        Ok(())
1704    }
1705
1706    fn chat_map_with_retries(base_url: &str, max_retries: u32) -> Vec<ModelConfig> {
1707        vec![ModelConfig::new(
1708            "gpt",
1709            Backend::OpenAiChat(config_with_retries(base_url, max_retries)),
1710            None,
1711        )]
1712    }
1713
1714    fn chat_success_response() -> ResponseTemplate {
1715        ResponseTemplate::new(200).set_body_json(json!({
1716            "id": "chatcmpl-1",
1717            "model": "gpt",
1718            "choices": [{
1719                "index": 0,
1720                "message": {"role": "assistant", "content": "recovered"},
1721                "finish_reason": "stop"
1722            }],
1723            "usage": {}
1724        }))
1725    }
1726
1727    fn truncated_response_server(
1728        content_type: &str,
1729        body: &str,
1730    ) -> std::io::Result<(String, JoinHandle<std::io::Result<()>>)> {
1731        response_sequence_server(vec![format!(
1732            "HTTP/1.1 200 OK\r\nContent-Type: {content_type}\r\n\
1733             Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
1734            body.len() + 100
1735        )])
1736    }
1737
1738    fn response_sequence_server(
1739        responses: Vec<String>,
1740    ) -> std::io::Result<(String, JoinHandle<std::io::Result<()>>)> {
1741        let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
1742        let address = listener.local_addr()?;
1743        let handle = std::thread::spawn(move || {
1744            for response in responses {
1745                let (mut stream, _) = listener.accept()?;
1746                let mut request = [0_u8; 1024];
1747                if stream.read(&mut request)? == 0 {
1748                    return Err(std::io::Error::new(
1749                        std::io::ErrorKind::UnexpectedEof,
1750                        "client closed before sending a request",
1751                    ));
1752                }
1753                stream.write_all(response.as_bytes())?;
1754            }
1755            Ok(())
1756        });
1757        Ok((format!("http://{address}/v1"), handle))
1758    }
1759
1760    fn raw_chat_success_response() -> String {
1761        let body = r#"{"id":"chatcmpl-1","model":"gpt","choices":[{"index":0,"message":{"role":"assistant","content":"recovered"},"finish_reason":"stop"}],"usage":{}}"#;
1762        format!(
1763            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\
1764             Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
1765            body.len()
1766        )
1767    }
1768
1769    fn request_for(model: Option<&str>, stream: bool) -> Request {
1770        let mut llm_request = text_request(model.map(str::to_string), "hi");
1771        llm_request.stream = stream;
1772        Request {
1773            llm_request,
1774            raw_request: None,
1775            metadata: None,
1776        }
1777    }
1778
1779    fn request_with_headers(model: &str, headers: HeaderMap) -> Request {
1780        let mut request = request_for(Some(model), false);
1781        request.metadata = Some(Metadata {
1782            http_headers: Some(headers),
1783            ..Default::default()
1784        });
1785        request
1786    }
1787
1788    #[tokio::test]
1789    async fn transport_errors_drop_the_upstream_url() {
1790        let error = reqwest::Client::new()
1791            .post("http://127.0.0.1:1/v1?key=CANARY")
1792            .send()
1793            .await
1794            .expect_err("closed port");
1795
1796        assert!(!convert_reqwest_error(error).to_string().contains("CANARY"));
1797    }
1798
1799    #[tokio::test]
1800    async fn captured_request_build_failure_remains_a_configuration_error() {
1801        let client = TranslatingLlmClient::new(&chat_map("://invalid")).unwrap();
1802        let result =
1803            crate::with_payload_capture(client.call(request_for(Some("gpt"), false))).await;
1804        assert!(matches!(result, Err(LlmClientError::Configuration { .. })));
1805    }
1806
1807    #[test]
1808    fn nvidia_anthropic_tools_drop_unsupported_strict_field() {
1809        let backend = Backend::Anthropic(config("https://inference-api.nvidia.com"));
1810        assert!(nvidia_inference_api_backend(&backend));
1811        assert!(!nvidia_inference_api_backend(&Backend::Anthropic(config(
1812            "https://inference-api.nvidia.com.example.test"
1813        ))));
1814        let mut body = json!({"tools": [{"name": "a", "input_schema": {}, "strict": true}]});
1815        strip_anthropic_tool_strict(&mut body);
1816        assert!(body["tools"][0].get("strict").is_none());
1817    }
1818
1819    #[test]
1820    fn anthropic_prompt_caching_marks_final_message() {
1821        let caller_managed = json!({
1822            "cache_control": {"type": "ephemeral", "ttl": "1h"},
1823            "messages": [{"role": "user", "content": "hello"}]
1824        });
1825        let mut body = caller_managed.clone();
1826        enable_anthropic_prompt_caching(&mut body, 0);
1827        assert_eq!(body["cache_control"], caller_managed["cache_control"]);
1828        assert_eq!(
1829            body["messages"][0]["content"],
1830            json!([{
1831                "type": "text", "text": "hello",
1832                "cache_control": {"type": "ephemeral", "ttl": "1h"}
1833            }])
1834        );
1835
1836        let mut body = json!({
1837            "messages": [{"role": "user", "content": "hello"}]
1838        });
1839
1840        enable_anthropic_prompt_caching(&mut body, 0);
1841
1842        assert_eq!(
1843            body["messages"][0]["content"][0]["cache_control"],
1844            json!({"type": "ephemeral"})
1845        );
1846    }
1847
1848    // Counts the blocks upstream will see carrying a `cache_control` marker.
1849    fn cache_control_blocks(value: &Value) -> usize {
1850        count_cache_control_blocks(value)
1851    }
1852
1853    // A body whose four breakpoints are all spent elsewhere: the caller manages
1854    // its own caching and left the final block unmarked on purpose.
1855    fn body_at_the_cache_control_limit() -> Value {
1856        json!({
1857            "system": [
1858                {"type": "text", "text": "a", "cache_control": {"type": "ephemeral"}},
1859                {"type": "text", "text": "b", "cache_control": {"type": "ephemeral"}}
1860            ],
1861            "tools": [
1862                {"name": "t", "input_schema": {"type": "object"},
1863                 "cache_control": {"type": "ephemeral"}}
1864            ],
1865            "messages": [
1866                {"role": "user", "content": [
1867                    {"type": "text", "text": "old", "cache_control": {"type": "ephemeral"}}
1868                ]},
1869                {"role": "assistant", "content": [{"type": "text", "text": "ok"}]},
1870                {"role": "user", "content": [{"type": "text", "text": "new"}]}
1871            ]
1872        })
1873    }
1874
1875    #[test]
1876    fn anthropic_prompt_caching_abstains_at_the_cache_control_limit() {
1877        let mut body = body_at_the_cache_control_limit();
1878        assert_eq!(cache_control_blocks(&body), 4);
1879
1880        enable_anthropic_prompt_caching(&mut body, 0);
1881
1882        // Anthropic and Bedrock both reject a fifth marker with HTTP 400, which
1883        // would fail a request that was valid before it reached us.
1884        assert_eq!(cache_control_blocks(&body), 4);
1885        assert!(
1886            body["messages"][2]["content"][0]
1887                .get("cache_control")
1888                .is_none()
1889        );
1890    }
1891
1892    #[test]
1893    fn anthropic_prompt_caching_still_marks_one_below_the_limit() {
1894        let mut body = body_at_the_cache_control_limit();
1895        // Free one breakpoint, so there is room for ours.
1896        body["system"].as_array_mut().unwrap().pop();
1897        assert_eq!(cache_control_blocks(&body), 3);
1898
1899        enable_anthropic_prompt_caching(&mut body, 0);
1900
1901        assert_eq!(cache_control_blocks(&body), 4);
1902        assert_eq!(
1903            body["messages"][2]["content"][0]["cache_control"],
1904            json!({"type": "ephemeral"})
1905        );
1906    }
1907
1908    // A request that pins `format` in its metadata, so the client resolves that
1909    // wire format instead of the model's default backend.
1910    fn request_with_wire_format(model: &str, format: WireFormat) -> Request {
1911        let mut request = request_for(Some(model), false);
1912        request.metadata = Some(Metadata {
1913            session_id: None,
1914            agent_id: None,
1915            task_id: None,
1916            correlation_id: None,
1917            extra_metadata: None,
1918            http_headers: None,
1919            wire_format: Some(format),
1920            ..Default::default()
1921        });
1922        request
1923    }
1924
1925    #[tokio::test]
1926    async fn missing_model_errors()
1927    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
1928        let client = TranslatingLlmClient::new(&[])?;
1929        let Err(error) = client
1930            .call_rewrite_model(request_for(None, false), None)
1931            .await
1932        else {
1933            panic!("expected an error");
1934        };
1935        assert!(matches!(
1936            error,
1937            LlmClientError::InvalidRequest { message } if message == "no model given"
1938        ));
1939        Ok(())
1940    }
1941
1942    #[tokio::test]
1943    async fn unknown_model_errors()
1944    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
1945        let client = TranslatingLlmClient::new(&[])?;
1946        let Err(error) = client
1947            .call_rewrite_model(request_for(Some("gpt"), false), None)
1948            .await
1949        else {
1950            panic!("expected an error");
1951        };
1952        assert!(matches!(
1953            error,
1954            LlmClientError::Configuration { message }
1955                if message.contains("gpt")
1956        ));
1957        Ok(())
1958    }
1959
1960    #[tokio::test]
1961    async fn unknown_model_format_errors()
1962    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
1963        // "gpt" exists but only over OpenAI Chat; the request pins Anthropic.
1964        let client = TranslatingLlmClient::new(&chat_map("https://example.test/v1"))?;
1965        let Err(error) = client
1966            .call_rewrite_model(
1967                request_with_wire_format("gpt", WireFormat::AnthropicMessages),
1968                None,
1969            )
1970            .await
1971        else {
1972            panic!("expected an error");
1973        };
1974        assert!(matches!(
1975            error,
1976            LlmClientError::Configuration { message }
1977                if message.contains("gpt")
1978                    && message.contains(&WireFormat::AnthropicMessages.to_string())
1979        ));
1980        Ok(())
1981    }
1982
1983    #[test]
1984    fn backend_for_resolves_configured_format()
1985    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
1986        let client = TranslatingLlmClient::new(&chat_map("https://example.test/v1"))?;
1987        // "gpt" is served over OpenAI Chat only; other formats and models miss.
1988        assert!(
1989            client
1990                .backend_for(&ModelId::from("gpt"), WireFormat::OpenAiChat)
1991                .is_some()
1992        );
1993        assert!(
1994            client
1995                .backend_for(&ModelId::from("gpt"), WireFormat::AnthropicMessages)
1996                .is_none()
1997        );
1998        assert!(
1999            client
2000                .backend_for(&ModelId::from("missing"), WireFormat::OpenAiChat)
2001                .is_none()
2002        );
2003        Ok(())
2004    }
2005
2006    #[tokio::test]
2007    async fn target_name_arg_wins_over_request_model()
2008    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2009        let client = TranslatingLlmClient::new(&[])?;
2010        // Arg "b" is looked up (and reported), not the request's "a".
2011        let Err(error) = client
2012            .call_rewrite_model(request_for(Some("a"), false), Some(&ModelId::from("b")))
2013            .await
2014        else {
2015            panic!("expected an error");
2016        };
2017        assert!(matches!(
2018            error,
2019            LlmClientError::Configuration { message }
2020                if message.contains("\"b\"")
2021        ));
2022        Ok(())
2023    }
2024
2025    #[tokio::test]
2026    async fn buffered_openai_chat_round_trips()
2027    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2028        let server = MockServer::start().await;
2029        Mock::given(method("POST"))
2030            .and(path("/v1/chat/completions"))
2031            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2032                "id": "chatcmpl-1",
2033                "model": "gpt",
2034                "choices": [{
2035                    "index": 0,
2036                    "message": {"role": "assistant", "content": "Hi there"},
2037                    "finish_reason": "stop"
2038                }],
2039                "usage": {"prompt_tokens": 1, "completion_tokens": 2, "total_tokens": 3}
2040            })))
2041            .mount(&server)
2042            .await;
2043
2044        let client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
2045
2046        let response = client
2047            .call_rewrite_model(request_for(Some("gpt"), false), None)
2048            .await?;
2049        let agg = response.llm_response.into_agg().await?;
2050        assert_eq!(completion_text(&agg), "Hi there");
2051
2052        Ok(())
2053    }
2054
2055    #[tokio::test]
2056    async fn invalid_json_is_a_response_translation_error()
2057    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2058        let server = MockServer::start().await;
2059        let calls = Arc::new(AtomicUsize::new(0));
2060        let observed_calls = Arc::clone(&calls);
2061        Mock::given(method("POST"))
2062            .respond_with(move |_: &wiremock::Request| {
2063                observed_calls.fetch_add(1, Ordering::SeqCst);
2064                ResponseTemplate::new(200).set_body_raw("not json", "application/json")
2065            })
2066            .mount(&server)
2067            .await;
2068
2069        let client =
2070            TranslatingLlmClient::new(&chat_map_with_retries(&format!("{}/v1", server.uri()), 2))?;
2071        let Err(error) = client
2072            .call_rewrite_model(request_for(Some("gpt"), false), None)
2073            .await
2074        else {
2075            panic!("expected invalid JSON to fail");
2076        };
2077
2078        assert!(matches!(
2079            error,
2080            LlmClientError::ResponseTranslation(message)
2081                if message.contains("invalid upstream JSON")
2082        ));
2083        assert_eq!(calls.load(Ordering::SeqCst), 1);
2084        Ok(())
2085    }
2086
2087    #[tokio::test]
2088    async fn response_body_io_failure_is_a_transport_error()
2089    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2090        let (base_url, server) = truncated_response_server("application/json", "{}")?;
2091        let client = TranslatingLlmClient::new(&chat_map(&base_url))?;
2092        let result = client
2093            .call_rewrite_model(request_for(Some("gpt"), false), None)
2094            .await;
2095        server
2096            .join()
2097            .map_err(|_| std::io::Error::other("response server thread panicked"))??;
2098
2099        let Err(error) = result else {
2100            panic!("expected the truncated response body to fail");
2101        };
2102        let LlmClientError::Transport { source } = error else {
2103            panic!("expected a transport error");
2104        };
2105        let Some(source) = source.downcast_ref::<reqwest::Error>() else {
2106            panic!("expected the reqwest transport source");
2107        };
2108        assert!(source.is_decode());
2109        assert!(
2110            !std::error::Error::source(&source)
2111                .is_some_and(|source| source.is::<serde_json::Error>())
2112        );
2113        Ok(())
2114    }
2115
2116    #[tokio::test]
2117    async fn response_body_transport_failures_are_retried()
2118    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2119        let truncated_responses = [
2120            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\
2121             Content-Length: 102\r\nConnection: close\r\n\r\n{}",
2122            "HTTP/1.1 401 Unauthorized\r\nContent-Type: text/plain\r\n\
2123             Content-Length: 100\r\nConnection: close\r\n\r\nbad",
2124        ];
2125
2126        for truncated in truncated_responses {
2127            let (base_url, server) =
2128                response_sequence_server(vec![truncated.to_string(), raw_chat_success_response()])?;
2129            let client = TranslatingLlmClient::new(&chat_map_with_retries(&base_url, 1))?;
2130            let response = client
2131                .call_rewrite_model(request_for(Some("gpt"), false), None)
2132                .await?;
2133            server
2134                .join()
2135                .map_err(|_| std::io::Error::other("response server thread panicked"))??;
2136
2137            assert_eq!(
2138                completion_text(&response.llm_response.into_agg().await?),
2139                "recovered"
2140            );
2141        }
2142        Ok(())
2143    }
2144
2145    #[tokio::test]
2146    async fn pre_first_event_transport_failure_uses_retry_budget()
2147    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2148        let truncated = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\
2149                         Content-Length: 100\r\nConnection: close\r\n\r\n";
2150        let body = "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"recovered\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n";
2151        let success = format!(
2152            "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\
2153             Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
2154            body.len()
2155        );
2156
2157        for second in [success, truncated.to_string()] {
2158            let is_exhausted = second == truncated;
2159            let (base_url, server) = response_sequence_server(vec![truncated.to_string(), second])?;
2160            let client = TranslatingLlmClient::new(&chat_map_with_retries(&base_url, 1))?;
2161            let result = client
2162                .call_rewrite_model(request_for(Some("gpt"), true), None)
2163                .await;
2164            if is_exhausted {
2165                assert!(matches!(result, Err(LlmClientError::Transport { .. })));
2166            } else {
2167                assert_eq!(
2168                    completion_text(&result?.llm_response.into_agg().await?),
2169                    "recovered"
2170                );
2171            }
2172            server
2173                .join()
2174                .map_err(|_| std::io::Error::other("response server thread panicked"))??;
2175        }
2176        Ok(())
2177    }
2178
2179    #[tokio::test]
2180    async fn streaming_body_io_failure_preserves_transport_error()
2181    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2182        let body = "data: {\"choices\":[{\"delta\":{\"content\":\"partial\"}}]}\n\n";
2183        let (base_url, server) = truncated_response_server("text/event-stream", body)?;
2184        let client = TranslatingLlmClient::new(&chat_map_with_retries(&base_url, 2))?;
2185        let response = client
2186            .call_rewrite_model(request_for(Some("gpt"), true), None)
2187            .await?;
2188        let result = response.llm_response.into_agg().await;
2189        server
2190            .join()
2191            .map_err(|_| std::io::Error::other("response server thread panicked"))??;
2192
2193        let Err(error) = result else {
2194            panic!("expected the truncated stream body to fail");
2195        };
2196
2197        assert!(matches!(error, LlmClientError::Transport { .. }));
2198        Ok(())
2199    }
2200
2201    #[tokio::test]
2202    async fn rewrites_model_to_resolved_upstream_id()
2203    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2204        // Inbound body says "switchyard"; the upstream must receive "gpt".
2205        let server = MockServer::start().await;
2206        Mock::given(method("POST"))
2207            .and(path("/v1/chat/completions"))
2208            .and(wiremock::matchers::body_partial_json(json!({"model": "gpt"})))
2209            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2210                "id": "1", "model": "gpt",
2211                "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
2212                "usage": {}
2213            })))
2214            .mount(&server)
2215            .await;
2216
2217        let client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
2218        // Inbound model differs from the map key / resolved model.
2219        client
2220            .call_rewrite_model(
2221                request_for(Some("switchyard"), false),
2222                Some(&ModelId::from("gpt")),
2223            )
2224            .await?;
2225        // The body_partial_json matcher asserts the upstream saw model "gpt".
2226        Ok(())
2227    }
2228
2229    /// A configured reasoning effort replaces the caller's value on both OpenAI wire formats,
2230    /// which `extra_body` (defaults only) cannot do.
2231    #[tokio::test]
2232    async fn reasoning_effort_override_replaces_the_callers_effort()
2233    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2234        let server = MockServer::start().await;
2235        Mock::given(method("POST"))
2236            .and(path("/v1/chat/completions"))
2237            .and(wiremock::matchers::body_partial_json(json!({
2238                "model": "gpt",
2239                "reasoning_effort": "max"
2240            })))
2241            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2242                "id": "1",
2243                "model": "gpt",
2244                "choices": [{
2245                    "index": 0,
2246                    "message": {"role": "assistant", "content": "ok"},
2247                    "finish_reason": "stop"
2248                }],
2249                "usage": {}
2250            })))
2251            .mount(&server)
2252            .await;
2253        let client = TranslatingLlmClient::new(&chat_map_with_effort(
2254            &format!("{}/v1", server.uri()),
2255            "max",
2256        ))?;
2257        client
2258            .call_rewrite_model(
2259                wire_request(
2260                    json!({
2261                        "model": "client-facing",
2262                        "messages": [{"role": "user", "content": "hi"}],
2263                        "reasoning_effort": "high"
2264                    }),
2265                    None,
2266                    WireFormat::OpenAiChat,
2267                )?,
2268                Some(&ModelId::from("gpt")),
2269            )
2270            .await?;
2271
2272        let server = MockServer::start().await;
2273        Mock::given(method("POST"))
2274            .and(path("/v1/responses"))
2275            .and(wiremock::matchers::body_partial_json(json!({
2276                "model": "gpt",
2277                "reasoning": {"effort": "max", "summary": "auto"}
2278            })))
2279            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2280                "id": "resp_1",
2281                "object": "response",
2282                "model": "gpt",
2283                "status": "completed",
2284                "output": [{
2285                    "type": "message",
2286                    "id": "msg_1",
2287                    "role": "assistant",
2288                    "status": "completed",
2289                    "content": [{"type": "output_text", "text": "ok"}]
2290                }],
2291                "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2}
2292            })))
2293            .mount(&server)
2294            .await;
2295        let client = TranslatingLlmClient::new(&responses_map_with_effort(
2296            &format!("{}/v1", server.uri()),
2297            "max",
2298        ))?;
2299        client
2300            .call_rewrite_model(
2301                wire_request(
2302                    json!({
2303                        "model": "client-facing",
2304                        "input": [{"role": "user", "content": "hi"}],
2305                        "reasoning": {"effort": "high", "summary": "auto"}
2306                    }),
2307                    None,
2308                    WireFormat::OpenAiResponses,
2309                )?,
2310                Some(&ModelId::from("gpt")),
2311            )
2312            .await?;
2313        Ok(())
2314    }
2315
2316    // Covers both a translated request and an Anthropic caller's body sent as is.
2317    #[tokio::test]
2318    async fn anthropic_requests_drop_tool_strict_false()
2319    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2320        let server = MockServer::start().await;
2321        Mock::given(method("POST"))
2322            .and(path("/v1/messages"))
2323            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2324                "id": "msg_1",
2325                "type": "message",
2326                "role": "assistant",
2327                "model": "claude",
2328                "content": [{"type": "text", "text": "ok"}],
2329                "stop_reason": "end_turn",
2330                "usage": {"input_tokens": 1, "output_tokens": 1}
2331            })))
2332            .expect(2)
2333            .mount(&server)
2334            .await;
2335        let client = TranslatingLlmClient::new(&[ModelConfig::new(
2336            "claude",
2337            Backend::Anthropic(config(&server.uri())),
2338            None,
2339        )])?;
2340        let schema = json!({"type": "object"});
2341        let requests = [
2342            (
2343                WireFormat::OpenAiChat,
2344                json!({
2345                    "model": "client-facing",
2346                    "messages": [{"role": "user", "content": "hi"}],
2347                    "tools": [
2348                        {"type": "function", "function": {"name": "loose", "parameters": schema, "strict": false}},
2349                        {"type": "function", "function": {"name": "exact", "parameters": schema, "strict": true}}
2350                    ]
2351                }),
2352            ),
2353            (
2354                WireFormat::AnthropicMessages,
2355                json!({
2356                    "model": "client-facing",
2357                    "max_tokens": 8,
2358                    "messages": [{"role": "user", "content": "hi"}],
2359                    "tools": [
2360                        {"name": "loose", "input_schema": schema, "strict": false},
2361                        {"name": "exact", "input_schema": schema, "strict": true}
2362                    ]
2363                }),
2364            ),
2365        ];
2366        for (format, request) in requests {
2367            client
2368                .call_rewrite_model(
2369                    wire_request(request, None, format)?,
2370                    Some(&ModelId::from("claude")),
2371                )
2372                .await?;
2373        }
2374        for received in server.received_requests().await.unwrap_or_default() {
2375            let body: Value = serde_json::from_slice(&received.body)?;
2376            assert!(body["tools"][0].get("strict").is_none(), "{body}");
2377            assert_eq!(body["tools"][1]["strict"], true, "{body}");
2378        }
2379        Ok(())
2380    }
2381
2382    #[tokio::test]
2383    async fn template_rejection_retries_once_without_changing_other_fields()
2384    -> std::result::Result<(), Box<dyn Error + Sync + Send>> {
2385        for (message, reject_retry, omit) in [
2386            (
2387                "Unrecognized request argument supplied: chat_template_kwargs",
2388                false,
2389                false,
2390            ),
2391            (
2392                "Unrecognized request argument supplied: chat_template_kwargs",
2393                true,
2394                false,
2395            ),
2396            (
2397                "Invalid temperature for chat_template_kwargs request",
2398                false,
2399                false,
2400            ),
2401            (
2402                "Unrecognized request argument supplied: chat_template_kwargs",
2403                false,
2404                true,
2405            ),
2406        ] {
2407            let server = MockServer::start().await;
2408            Mock::given(method("POST"))
2409                .respond_with(move |request: &wiremock::Request| {
2410                    let body: Value = serde_json::from_slice(&request.body).expect("request JSON");
2411                    if body.get("chat_template_kwargs").is_some() || reject_retry {
2412                        ResponseTemplate::new(400).set_body_json(json!({"error": {"message": message}}))
2413                    } else {
2414                        ResponseTemplate::new(200).set_body_json(json!({
2415                            "id": "1", "model": "gpt", "choices": [{"index": 0,
2416                                "message": {"role": "assistant", "content": "yes"}, "finish_reason": "stop"}],
2417                            "usage": {}
2418                        }))
2419                    }
2420                }).mount(&server).await;
2421            let fields = if omit {
2422                BTreeSet::from(["chat_template_kwargs".into()])
2423            } else {
2424                BTreeSet::new()
2425            };
2426            let client = TranslatingLlmClient::new(&chat_map_with_omit_body_fields(
2427                &format!("{}/v1", server.uri()),
2428                fields,
2429            ))?;
2430            let raw = json!({"model": "gpt", "messages": [{"role": "user", "content": "judge"}],
2431                "reasoning_effort": "none", "logprobs": true, "top_logprobs": 8,
2432                "chat_template_kwargs": {"enable_thinking": false}});
2433            let result = client
2434                .call_rewrite_model(
2435                    wire_request(raw.clone(), None, WireFormat::OpenAiChat)?,
2436                    Some(&ModelId::from("gpt")),
2437                )
2438                .await;
2439            let rejects_field = message.starts_with("Unrecognized");
2440            assert_eq!(result.is_ok(), omit || (rejects_field && !reject_retry));
2441            let calls = server.received_requests().await.ok_or("missing requests")?;
2442            assert_eq!(calls.len(), if !omit && rejects_field { 2 } else { 1 });
2443            for (index, call) in calls.iter().enumerate() {
2444                let mut expected = raw.clone();
2445                if omit || index > 0 {
2446                    expected
2447                        .as_object_mut()
2448                        .unwrap()
2449                        .remove("chat_template_kwargs");
2450                }
2451                assert_eq!(serde_json::from_slice::<Value>(&call.body)?, expected);
2452            }
2453        }
2454        Ok(())
2455    }
2456
2457    #[tokio::test]
2458    async fn template_compatibility_preserves_the_transient_retry_budget()
2459    -> std::result::Result<(), Box<dyn Error + Sync + Send>> {
2460        let server = MockServer::start().await;
2461        let count = Arc::new(AtomicUsize::new(0));
2462        let observed = Arc::clone(&count);
2463        Mock::given(method("POST"))
2464            .respond_with(move |request: &wiremock::Request| {
2465                let body: Value = serde_json::from_slice(&request.body).expect("request JSON");
2466                match observed.fetch_add(1, Ordering::SeqCst) {
2467                    0 => {
2468                        assert!(body.get("chat_template_kwargs").is_some());
2469                        ResponseTemplate::new(422).set_body_json(json!({"error": {
2470                            "code": "unsupported_parameter", "param": "chat_template_kwargs"
2471                        }}))
2472                    }
2473                    1 => {
2474                        assert!(body.get("chat_template_kwargs").is_none());
2475                        ResponseTemplate::new(503).insert_header("retry-after", "0")
2476                    }
2477                    _ => ResponseTemplate::new(200).set_body_json(json!({
2478                        "id": "1", "model": "gpt", "choices": [{"index": 0,
2479                            "message": {"role": "assistant", "content": "yes"}, "finish_reason": "stop"}],
2480                        "usage": {}
2481                    })),
2482                }
2483            }).mount(&server).await;
2484        let client =
2485            TranslatingLlmClient::new(&chat_map_with_retries(&format!("{}/v1", server.uri()), 1))?;
2486        client
2487            .call_rewrite_model(
2488                wire_request(
2489                    json!({"model": "gpt", "messages": [{"role": "user", "content": "judge"}],
2490                "chat_template_kwargs": {"enable_thinking": false}}),
2491                    None,
2492                    WireFormat::OpenAiChat,
2493                )?,
2494                Some(&ModelId::from("gpt")),
2495            )
2496            .await?;
2497        assert_eq!(count.load(Ordering::SeqCst), 3);
2498        Ok(())
2499    }
2500
2501    #[tokio::test]
2502    async fn preserved_codex_string_input_is_normalized_at_the_client_boundary()
2503    -> std::result::Result<(), Box<dyn Error + Sync + Send>> {
2504        for root in ["/backend-api/codex", "/v1"] {
2505            for input in [
2506                json!("hello"),
2507                json!([{"role": "user", "content": "hello"}]),
2508            ] {
2509                let server = MockServer::start().await;
2510                Mock::given(method("POST"))
2511                    .and(path(format!("{root}/responses")))
2512                    .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2513                        "id": "resp_1", "object": "response", "model": "gpt", "status": "completed", "output": [], "usage": {}
2514                    }))).expect(1).mount(&server).await;
2515                let client =
2516                    TranslatingLlmClient::new(&responses_map(&format!("{}{root}", server.uri())))?;
2517                let raw = json!({"model": "client-name", "input": input,
2518                    "instructions": "Be brief.", "store": false, "metadata": {"task": "judge"},
2519                    "custom_field": {"keep": true}});
2520                client
2521                    .call_rewrite_model(
2522                        wire_request(raw.clone(), None, WireFormat::OpenAiResponses)?,
2523                        Some(&ModelId::from("gpt")),
2524                    )
2525                    .await?;
2526                let mut expected = raw;
2527                expected["model"] = json!("gpt");
2528                if root == "/backend-api/codex" && input.is_string() {
2529                    expected["input"] =
2530                        json!([{"type": "message", "role": "user", "content": input}]);
2531                }
2532                let calls = server.received_requests().await.ok_or("missing requests")?;
2533                assert_eq!(serde_json::from_slice::<Value>(&calls[0].body)?, expected);
2534            }
2535        }
2536        Ok(())
2537    }
2538
2539    #[tokio::test]
2540    async fn token_counting_does_not_send_the_effort_override()
2541    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2542        let server = MockServer::start().await;
2543        Mock::given(method("POST"))
2544            .and(path("/v1/messages/count_tokens"))
2545            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"input_tokens": 3})))
2546            .expect(1)
2547            .mount(&server)
2548            .await;
2549        let mut backend = config(&server.uri());
2550        backend.reasoning_effort = Some("max".to_string());
2551        let client = TranslatingLlmClient::new(&[ModelConfig::new(
2552            "claude",
2553            Backend::Anthropic(backend),
2554            None,
2555        )])?;
2556        let llm_request = switchyard_translation::decode_request(
2557            WireFormat::AnthropicMessages,
2558            &json!({"model": "claude", "messages": [{"role": "user", "content": "hi"}]}),
2559        )?;
2560        let request = Request {
2561            llm_request,
2562            raw_request: None,
2563            metadata: None,
2564        };
2565        client
2566            .call_auxiliary(
2567                &ModelId::from("claude"),
2568                request,
2569                AuxiliaryOperation::AnthropicCountTokens,
2570            )
2571            .await?;
2572        let received = server.received_requests().await.unwrap_or_default();
2573        let body: Value = serde_json::from_slice(&received[0].body)?;
2574        assert!(body.get("output_config").is_none(), "{body}");
2575        Ok(())
2576    }
2577
2578    #[tokio::test]
2579    async fn reasoning_effort_override_sets_anthropic_output_config_effort()
2580    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2581        let server = MockServer::start().await;
2582        let format = json!({"type": "json_schema", "schema": {"type": "object"}});
2583        Mock::given(method("POST"))
2584            .and(path("/v1/messages"))
2585            .and(wiremock::matchers::body_partial_json(json!({
2586                "model": "claude",
2587                "output_config": {"effort": "max", "format": format}
2588            })))
2589            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2590                "id": "msg_1",
2591                "type": "message",
2592                "role": "assistant",
2593                "model": "claude",
2594                "content": [{"type": "text", "text": "ok"}],
2595                "stop_reason": "end_turn",
2596                "usage": {"input_tokens": 1, "output_tokens": 1}
2597            })))
2598            .expect(1)
2599            .mount(&server)
2600            .await;
2601        let mut backend = config(&server.uri());
2602        backend.reasoning_effort = Some("max".to_string());
2603        let client = TranslatingLlmClient::new(&[ModelConfig::new(
2604            "claude",
2605            Backend::Anthropic(backend),
2606            None,
2607        )])?;
2608        client
2609            .call_rewrite_model(
2610                wire_request(
2611                    json!({
2612                        "model": "client-facing",
2613                        "max_tokens": 7,
2614                        "messages": [{"role": "user", "content": "hi"}],
2615                        "output_config": {"effort": "high", "format": format}
2616                    }),
2617                    None,
2618                    WireFormat::AnthropicMessages,
2619                )?,
2620                Some(&ModelId::from("claude")),
2621            )
2622            .await?;
2623        Ok(())
2624    }
2625
2626    #[tokio::test]
2627    async fn extra_body_adds_defaults_without_overriding_the_request()
2628    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2629        let server = MockServer::start().await;
2630        Mock::given(method("POST"))
2631            .and(path("/v1/chat/completions"))
2632            .and(wiremock::matchers::body_partial_json(json!({
2633                "model": "gpt",
2634                "max_tokens": 7,
2635                "service_tier": "priority"
2636            })))
2637            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2638                "id": "1",
2639                "model": "gpt",
2640                "choices": [{
2641                    "index": 0,
2642                    "message": {"role": "assistant", "content": "ok"},
2643                    "finish_reason": "stop"
2644                }],
2645                "usage": {}
2646            })))
2647            .mount(&server)
2648            .await;
2649
2650        let extra_body = BTreeMap::from([
2651            ("max_tokens".to_string(), json!(999)),
2652            ("service_tier".to_string(), json!("priority")),
2653        ]);
2654        let client = TranslatingLlmClient::new(&chat_map_with_extra_body(
2655            &format!("{}/v1", server.uri()),
2656            extra_body,
2657        ))?;
2658        let raw = json!({
2659            "model": "client-facing",
2660            "messages": [{"role": "user", "content": "hi"}],
2661            "max_tokens": 7
2662        });
2663
2664        client
2665            .call_rewrite_model(
2666                wire_request(raw, None, WireFormat::OpenAiChat)?,
2667                Some(&ModelId::from("gpt")),
2668            )
2669            .await?;
2670        Ok(())
2671    }
2672
2673    #[tokio::test]
2674    async fn omit_body_fields_strips_a_field_extra_body_cannot_override()
2675    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2676        let server = MockServer::start().await;
2677        Mock::given(method("POST"))
2678            .and(path("/v1/chat/completions"))
2679            .and(|request: &wiremock::Request| {
2680                let body: Value = serde_json::from_slice(&request.body).unwrap_or(Value::Null);
2681                body.get("max_tokens").is_none()
2682            })
2683            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2684                "id": "1",
2685                "model": "gpt",
2686                "choices": [{
2687                    "index": 0,
2688                    "message": {"role": "assistant", "content": "ok"},
2689                    "finish_reason": "stop"
2690                }],
2691                "usage": {}
2692            })))
2693            .mount(&server)
2694            .await;
2695
2696        let client = TranslatingLlmClient::new(&chat_map_with_omit_body_fields(
2697            &format!("{}/v1", server.uri()),
2698            BTreeSet::from(["max_tokens".to_string()]),
2699        ))?;
2700        let raw = json!({
2701            "model": "client-facing",
2702            "messages": [{"role": "user", "content": "hi"}],
2703            "max_tokens": 7
2704        });
2705
2706        client
2707            .call_rewrite_model(
2708                wire_request(raw, None, WireFormat::OpenAiChat)?,
2709                Some(&ModelId::from("gpt")),
2710            )
2711            .await?;
2712        Ok(())
2713    }
2714
2715    // A weak OpenAI-format tier emits thinking blocks with no signature. Replaying
2716    // them to Anthropic is rejected (Bedrock reports it as a SigV4 mismatch), so
2717    // the Anthropic leg must drop them while keeping signed ones.
2718    #[tokio::test]
2719    async fn anthropic_requests_drop_unsigned_thinking_blocks()
2720    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2721        let server = MockServer::start().await;
2722        Mock::given(method("POST"))
2723            .and(path("/v1/messages"))
2724            .and(|request: &wiremock::Request| {
2725                let body: Value = serde_json::from_slice(&request.body).unwrap_or(Value::Null);
2726                let messages = body.get("messages").and_then(Value::as_array).cloned();
2727                let Some(messages) = messages else {
2728                    return false;
2729                };
2730                // The unsigned block is gone, the signed one survives, and the
2731                // message whose only block was unsigned is not left with an empty
2732                // content array.
2733                let blocks: Vec<&Value> = messages
2734                    .iter()
2735                    .filter_map(|message| message.get("content"))
2736                    .filter_map(Value::as_array)
2737                    .flatten()
2738                    .collect();
2739                let thinking: Vec<&&Value> = blocks
2740                    .iter()
2741                    .filter(|block| block.get("type").and_then(Value::as_str) == Some("thinking"))
2742                    .collect();
2743                thinking.len() == 1
2744                    && thinking[0].get("signature").and_then(Value::as_str) == Some("sig-abc")
2745                    && messages
2746                        .iter()
2747                        .all(|message| message.get("content") != Some(&json!([])))
2748            })
2749            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2750                "id": "msg_1",
2751                "type": "message",
2752                "role": "assistant",
2753                "model": "claude",
2754                "content": [{"type": "text", "text": "ok"}],
2755                "stop_reason": "end_turn",
2756                "usage": {"input_tokens": 1, "output_tokens": 1}
2757            })))
2758            .mount(&server)
2759            .await;
2760
2761        let client = TranslatingLlmClient::new(&anthropic_map(&server.uri()))?;
2762        let raw = json!({
2763            "model": "client-facing",
2764            "max_tokens": 7,
2765            "messages": [
2766                {"role": "user", "content": "fix the build"},
2767                {"role": "assistant", "content": [
2768                    {"type": "thinking", "thinking": "weak tier reasoning", "signature": ""}
2769                ]},
2770                {"role": "assistant", "content": [
2771                    {"type": "thinking", "thinking": "signed reasoning", "signature": "sig-abc"},
2772                    {"type": "text", "text": "here goes"}
2773                ]},
2774                {"role": "user", "content": "continue"}
2775            ]
2776        });
2777
2778        client
2779            .call_rewrite_model(
2780                wire_request(raw, None, WireFormat::AnthropicMessages)?,
2781                Some(&ModelId::from("claude")),
2782            )
2783            .await?;
2784        Ok(())
2785    }
2786
2787    #[tokio::test]
2788    async fn responses_reasoning_policy_preserves_replay_history()
2789    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2790        use crate::ResponsesReasoningPolicy::{Auto, Drop, PreserveEncrypted, PreservePlaintext};
2791        let summary = json!([{"type": "summary_text", "text": "Check the parser."}]);
2792        let history = json!([
2793            {"type": "message", "role": "user", "content": "continue"},
2794            {"type": "reasoning", "encrypted_content": "opaque", "content": [{"type": "reasoning_text", "text": "private"}]},
2795            {"type": "reasoning", "id": "rs_stored", "status": "completed", "summary": []},
2796            // GLM's plaintext forms, as Codex replays them.
2797            {"type": "reasoning", "id": "rs_glm", "summary": summary, "encrypted_content": null},
2798            {"type": "reasoning", "content": [{"type": "reasoning_text", "text": "Run the tests."}], "encrypted_content": ""},
2799            {"type": "reasoning"},
2800            {"type": "function_call", "call_id": "call_1", "name": "shell", "arguments": "{}"},
2801            {"type": "function_call_output", "call_id": "call_1", "output": "ok"}
2802        ]);
2803        // An explicit policy wins over the target. `Auto` follows the target.
2804        let cases = [
2805            (Auto, "openai/gpt-5", PreserveEncrypted),
2806            (Auto, "nvidia/zai-org/glm-5.3-flash", PreservePlaintext),
2807            (
2808                PreserveEncrypted,
2809                "nvidia/zai-org/glm-5.3-flash",
2810                PreserveEncrypted,
2811            ),
2812            (Drop, "openai/gpt-5", Drop),
2813        ];
2814        for store in [Some(true), Some(false), None] {
2815            for (policy, model, behavior) in cases {
2816                for has_input_override in [false, true] {
2817                    let server = MockServer::start().await;
2818                    Mock::given(method("POST"))
2819                        .and(path("/v1/responses"))
2820                        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2821                            "id": "resp_1", "object": "response", "model": "gpt",
2822                            "status": "completed", "output": [],
2823                            "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2}
2824                        })))
2825                        .expect(1)
2826                        .mount(&server)
2827                        .await;
2828                    let mut backend = config(&format!("{}/v1", server.uri()));
2829                    if has_input_override {
2830                        backend.omit_body_fields.insert("input".to_string());
2831                        backend
2832                            .extra_body
2833                            .insert("input".to_string(), history.clone());
2834                    }
2835                    let client = TranslatingLlmClient::new(&[ModelConfig::new(
2836                        model,
2837                        Backend::OpenAiResponses(backend),
2838                        None,
2839                    )
2840                    .with_responses_reasoning(policy)])?;
2841                    let mut request = json!({"model": "switchyard", "input": history});
2842                    if let Some(store) = store {
2843                        request["store"] = json!(store);
2844                    }
2845                    client
2846                        .call_rewrite_model(
2847                            wire_request(request, None, WireFormat::OpenAiResponses)?,
2848                            Some(&ModelId::from(model)),
2849                        )
2850                        .await?;
2851                    let requests = server.received_requests().await.ok_or("missing requests")?;
2852                    let body: Value = serde_json::from_slice(&requests[0].body)?;
2853                    let stored = store != Some(false);
2854                    let mut expected = vec![history[0].clone()];
2855                    match behavior {
2856                        // OpenAI reads its own payload and stored IDs, but rejects plaintext.
2857                        PreserveEncrypted => {
2858                            let indexes: &[usize] = if stored { &[1, 2, 3] } else { &[1] };
2859                            for &index in indexes {
2860                                let mut item = history[index].clone();
2861                                item["content"] = json!([]);
2862                                expected.push(item);
2863                            }
2864                        }
2865                        // Other targets keep plaintext and lose payloads of unknown origin.
2866                        PreservePlaintext => {
2867                            let mut item = history[1].clone();
2868                            item.as_object_mut()
2869                                .ok_or("object")?
2870                                .remove("encrypted_content");
2871                            expected.push(item);
2872                            if stored {
2873                                expected.push(history[2].clone());
2874                            }
2875                            expected.extend([history[3].clone(), history[4].clone()]);
2876                        }
2877                        _ => {}
2878                    }
2879                    expected.extend([history[6].clone(), history[7].clone()]);
2880                    assert_eq!(
2881                        body["input"],
2882                        json!(expected),
2883                        "store={store:?}, policy={policy:?}, model={model}, replace={has_input_override}"
2884                    );
2885                }
2886            }
2887        }
2888
2889        Ok(())
2890    }
2891
2892    #[tokio::test]
2893    async fn nvidia_anthropic_requests_strip_strict_from_extra_body()
2894    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2895        let server = MockServer::start().await;
2896        Mock::given(method("POST"))
2897            .and(path("/v1/messages"))
2898            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2899                "id": "msg_1",
2900                "type": "message",
2901                "role": "assistant",
2902                "model": "claude",
2903                "content": [{"type": "text", "text": "ok"}],
2904                "stop_reason": "end_turn",
2905                "usage": {"input_tokens": 1, "output_tokens": 1}
2906            })))
2907            .expect(1)
2908            .mount(&server)
2909            .await;
2910
2911        let mut backend = config(&format!(
2912            "http://inference-api.nvidia.com:{}",
2913            server.address().port()
2914        ));
2915        backend.extra_body.insert(
2916            "tools".into(),
2917            json!([{
2918                "name": "lookup",
2919                "input_schema": {"type": "object", "properties": {}},
2920                "strict": true
2921            }]),
2922        );
2923        let mut client = TranslatingLlmClient::new(&[ModelConfig::new(
2924            "claude",
2925            Backend::Anthropic(backend),
2926            None,
2927        )])?;
2928        client.client = reqwest::Client::builder()
2929            .no_proxy()
2930            .resolve("inference-api.nvidia.com", *server.address())
2931            .build()?;
2932        client
2933            .call_rewrite_model(
2934                wire_request(
2935                    json!({
2936                        "model": "claude",
2937                        "max_tokens": 7,
2938                        "messages": [{"role": "user", "content": "hi"}]
2939                    }),
2940                    None,
2941                    WireFormat::AnthropicMessages,
2942                )?,
2943                Some(&ModelId::from("claude")),
2944            )
2945            .await?;
2946
2947        let requests = server.received_requests().await.unwrap();
2948        let body: Value = serde_json::from_slice(&requests[0].body)?;
2949        assert_eq!(body["tools"][0]["name"], "lookup");
2950        assert!(body["tools"][0].get("strict").is_none());
2951        Ok(())
2952    }
2953
2954    // A router can serve earlier turns from an OpenAI target and later turns from
2955    // an Anthropic one, so the Anthropic leg must drop OpenAI-only fields the
2956    // caller keeps sending or the upstream rejects the whole request.
2957    #[tokio::test]
2958    async fn anthropic_requests_drop_openai_only_fields()
2959    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2960        let server = MockServer::start().await;
2961        Mock::given(method("POST"))
2962            .and(path("/v1/messages"))
2963            .and(|request: &wiremock::Request| {
2964                let body: Value = serde_json::from_slice(&request.body).unwrap_or(Value::Null);
2965                body.get("context_management").is_none() && body.get("reasoning_effort").is_none()
2966            })
2967            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2968                "id": "msg_1",
2969                "type": "message",
2970                "role": "assistant",
2971                "model": "claude",
2972                "content": [{"type": "text", "text": "ok"}],
2973                "stop_reason": "end_turn",
2974                "usage": {"input_tokens": 1, "output_tokens": 1}
2975            })))
2976            .mount(&server)
2977            .await;
2978
2979        let client = TranslatingLlmClient::new(&anthropic_map(&server.uri()))?;
2980        let raw = json!({
2981            "model": "client-facing",
2982            "messages": [{"role": "user", "content": "hi"}],
2983            "max_tokens": 7,
2984            "reasoning_effort": "high",
2985            "context_management": {
2986                "edits": [{"type": "clear_thinking_20251015"}]
2987            }
2988        });
2989
2990        client
2991            .call_rewrite_model(
2992                wire_request(raw, None, WireFormat::AnthropicMessages)?,
2993                Some(&ModelId::from("claude")),
2994            )
2995            .await?;
2996        Ok(())
2997    }
2998
2999    #[tokio::test]
3000    async fn streaming_openai_chat_aggregates()
3001    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3002        let server = MockServer::start().await;
3003        let sse = "data: {\"choices\":[{\"delta\":{\"content\":\"Hello\"}}]}\n\n\
3004             data: {\"choices\":[{\"delta\":{\"content\":\" world\"}}]}\n\n\
3005             data: {\"choices\":[],\"usage\":{\"prompt_tokens\":1,\"completion_tokens\":2,\"total_tokens\":3}}\n\n\
3006             data: [DONE]\n\n";
3007        Mock::given(method("POST"))
3008            .and(path("/v1/chat/completions"))
3009            .and(wiremock::matchers::body_partial_json(json!({
3010                "stream": true,
3011                "stream_options": {"include_usage": true}
3012            })))
3013            .respond_with(ResponseTemplate::new(200).set_body_raw(sse, "text/event-stream"))
3014            .mount(&server)
3015            .await;
3016
3017        let client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
3018
3019        let response = client
3020            .call_rewrite_model(request_for(Some("gpt"), true), None)
3021            .await?;
3022        assert!(matches!(response.llm_response, LlmResponse::Stream(_)));
3023        let agg = response.llm_response.into_agg().await?;
3024        assert_eq!(completion_text(&agg), "Hello world");
3025        assert_eq!(agg.usage.input_tokens, Some(1));
3026        assert_eq!(agg.usage.output_tokens, Some(2));
3027        assert_eq!(agg.usage.total_tokens, Some(3));
3028        Ok(())
3029    }
3030
3031    #[tokio::test]
3032    async fn streaming_openai_chat_preserves_usage_opt_out()
3033    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3034        let server = MockServer::start().await;
3035        Mock::given(method("POST"))
3036            .and(path("/v1/chat/completions"))
3037            .and(wiremock::matchers::body_partial_json(json!({
3038                "stream": true,
3039                "stream_options": {"include_usage": false}
3040            })))
3041            .respond_with(
3042                ResponseTemplate::new(200).set_body_raw("data: [DONE]\n\n", "text/event-stream"),
3043            )
3044            .mount(&server)
3045            .await;
3046
3047        let client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
3048        let raw = json!({
3049            "model": "client-facing",
3050            "messages": [{"role": "user", "content": "hi"}],
3051            "stream": true,
3052            "stream_options": {"include_usage": false}
3053        });
3054
3055        let response = client
3056            .call_rewrite_model(
3057                wire_request(raw, None, WireFormat::OpenAiChat)?,
3058                Some(&ModelId::from("gpt")),
3059            )
3060            .await?;
3061        assert!(matches!(response.llm_response, LlmResponse::Stream(_)));
3062        Ok(())
3063    }
3064
3065    #[tokio::test]
3066    async fn upstream_500_is_upstream_http()
3067    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3068        let server = MockServer::start().await;
3069        Mock::given(method("POST"))
3070            .respond_with(ResponseTemplate::new(500).set_body_string("boom"))
3071            .mount(&server)
3072            .await;
3073
3074        let client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
3075
3076        let Err(error) = client
3077            .call_rewrite_model(request_for(Some("gpt"), false), None)
3078            .await
3079        else {
3080            panic!("expected an error");
3081        };
3082        assert!(matches!(
3083            error,
3084            LlmClientError::UpstreamHttp {
3085                status: StatusCode::INTERNAL_SERVER_ERROR,
3086                ..
3087            }
3088        ));
3089        Ok(())
3090    }
3091
3092    #[tokio::test]
3093    async fn retryable_http_failure_recovers_within_budget()
3094    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3095        let server = MockServer::start().await;
3096        let calls = Arc::new(AtomicUsize::new(0));
3097        let observed_calls = Arc::clone(&calls);
3098        Mock::given(method("POST"))
3099            .respond_with(move |_: &wiremock::Request| {
3100                if observed_calls.fetch_add(1, Ordering::SeqCst) == 0 {
3101                    ResponseTemplate::new(503)
3102                        .insert_header("retry-after", "0")
3103                        .set_body_string("temporarily unavailable")
3104                } else {
3105                    chat_success_response()
3106                }
3107            })
3108            .mount(&server)
3109            .await;
3110
3111        let client =
3112            TranslatingLlmClient::new(&chat_map_with_retries(&format!("{}/v1", server.uri()), 1))?;
3113        let response = client
3114            .call_rewrite_model(request_for(Some("gpt"), false), None)
3115            .await?;
3116        let agg = response.llm_response.into_agg().await?;
3117
3118        assert_eq!(completion_text(&agg), "recovered");
3119        assert_eq!(calls.load(Ordering::SeqCst), 2);
3120        Ok(())
3121    }
3122
3123    #[tokio::test]
3124    async fn deterministic_http_failure_is_not_retried()
3125    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3126        let server = MockServer::start().await;
3127        let calls = Arc::new(AtomicUsize::new(0));
3128        let observed_calls = Arc::clone(&calls);
3129        Mock::given(method("POST"))
3130            .respond_with(move |_: &wiremock::Request| {
3131                observed_calls.fetch_add(1, Ordering::SeqCst);
3132                ResponseTemplate::new(401).set_body_string("invalid key")
3133            })
3134            .mount(&server)
3135            .await;
3136
3137        let client =
3138            TranslatingLlmClient::new(&chat_map_with_retries(&format!("{}/v1", server.uri()), 2))?;
3139        let Err(error) = client
3140            .call_rewrite_model(request_for(Some("gpt"), false), None)
3141            .await
3142        else {
3143            panic!("expected an upstream error");
3144        };
3145
3146        assert!(matches!(
3147            error,
3148            LlmClientError::UpstreamHttp {
3149                status: StatusCode::UNAUTHORIZED,
3150                body,
3151                ..
3152            } if body == "invalid key"
3153        ));
3154        assert_eq!(calls.load(Ordering::SeqCst), 1);
3155        Ok(())
3156    }
3157
3158    #[tokio::test]
3159    async fn rate_limit_cooldown_depends_on_shared_credentials()
3160    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3161        for forward_auth in [true, false] {
3162            let server = MockServer::start().await;
3163            Mock::given(method("POST"))
3164                .respond_with(ResponseTemplate::new(429).insert_header("retry-after", "0"))
3165                .expect(if forward_auth { 6 } else { 3 })
3166                .mount(&server)
3167                .await;
3168            let backend = HttpBackendConfig {
3169                forward_auth,
3170                failure_cooldown: Duration::from_secs(60),
3171                ..config_with_retries(&format!("{}/v1", server.uri()), 2)
3172            };
3173            let client = TranslatingLlmClient::new(&[ModelConfig::new(
3174                "gpt",
3175                Backend::OpenAiChat(backend),
3176                None,
3177            )])?;
3178            for credential in ["Bearer first-user", "Bearer second-user"] {
3179                let mut headers = http::HeaderMap::new();
3180                headers.insert("authorization", http::HeaderValue::from_static(credential));
3181                let result = client
3182                    .call_rewrite_model(request_with_headers("gpt", headers), None)
3183                    .await;
3184                if !forward_auth && credential == "Bearer second-user" {
3185                    assert!(matches!(
3186                        result,
3187                        Err(LlmClientError::TemporarilyUnavailable)
3188                    ));
3189                } else {
3190                    assert!(matches!(
3191                        result,
3192                        Err(LlmClientError::UpstreamHttp {
3193                            status: StatusCode::TOO_MANY_REQUESTS,
3194                            ..
3195                        })
3196                    ));
3197                }
3198            }
3199        }
3200        Ok(())
3201    }
3202
3203    #[tokio::test]
3204    async fn retry_exhaustion_returns_the_final_upstream_error()
3205    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3206        let server = MockServer::start().await;
3207        let calls = Arc::new(AtomicUsize::new(0));
3208        let observed_calls = Arc::clone(&calls);
3209        Mock::given(method("POST"))
3210            .respond_with(move |_: &wiremock::Request| {
3211                let attempt = observed_calls.fetch_add(1, Ordering::SeqCst) + 1;
3212                ResponseTemplate::new(500)
3213                    .insert_header("retry-after", "0")
3214                    .set_body_string(format!("attempt {attempt}"))
3215            })
3216            .mount(&server)
3217            .await;
3218
3219        let client =
3220            TranslatingLlmClient::new(&chat_map_with_retries(&format!("{}/v1", server.uri()), 2))?;
3221        let Err(error) = client
3222            .call_rewrite_model(request_for(Some("gpt"), false), None)
3223            .await
3224        else {
3225            panic!("expected retry exhaustion");
3226        };
3227
3228        assert!(matches!(
3229            error,
3230            LlmClientError::UpstreamHttp {
3231                status: StatusCode::INTERNAL_SERVER_ERROR,
3232                body,
3233                ..
3234            } if body == "attempt 3"
3235        ));
3236        assert_eq!(calls.load(Ordering::SeqCst), 3);
3237        Ok(())
3238    }
3239
3240    // The error keeps every header of the last attempt; consumers choose what to forward.
3241    #[tokio::test]
3242    async fn upstream_error_carries_headers_from_the_last_attempt()
3243    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3244        let server = MockServer::start().await;
3245        // A zero `retry-after` keeps the retry from sleeping.
3246        let reply = |id: &str| {
3247            ResponseTemplate::new(429)
3248                .insert_header("retry-after", "0")
3249                .insert_header("x-request-id", id)
3250                .insert_header("set-cookie", "a=b")
3251        };
3252        Mock::given(method("POST"))
3253            .respond_with(reply("first"))
3254            .up_to_n_times(1)
3255            .mount(&server)
3256            .await;
3257        Mock::given(method("POST"))
3258            .respond_with(reply("second"))
3259            .mount(&server)
3260            .await;
3261        let client =
3262            TranslatingLlmClient::new(&chat_map_with_retries(&format!("{}/v1", server.uri()), 1))?;
3263        let Err(LlmClientError::UpstreamHttp { headers, .. }) = client
3264            .call_rewrite_model(request_for(Some("gpt"), false), None)
3265            .await
3266        else {
3267            panic!("expected an upstream HTTP error");
3268        };
3269        assert_eq!(headers["x-request-id"], "second");
3270        assert_eq!(headers["retry-after"], "0");
3271        assert_eq!(headers["set-cookie"], "a=b");
3272        Ok(())
3273    }
3274
3275    #[tokio::test]
3276    async fn deadline_expires_before_send_or_stream_poll()
3277    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3278        let server = MockServer::start().await;
3279        Mock::given(method("POST"))
3280            .respond_with(ResponseTemplate::new(200).set_body_raw(
3281                "data: {\"id\":\"test\",\"model\":\"gpt\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n",
3282                "text/event-stream",
3283            ))
3284            .mount(&server)
3285            .await;
3286        for timeout in [Duration::ZERO, Duration::from_millis(200)] {
3287            let mut backend = config(&server.uri());
3288            backend.timeout = Some(timeout);
3289            let client = TranslatingLlmClient::new(&[ModelConfig::new(
3290                "gpt",
3291                Backend::OpenAiChat(backend),
3292                None,
3293            )])?;
3294            let result = client
3295                .call_rewrite_model(request_for(Some("gpt"), true), None)
3296                .await;
3297            if timeout.is_zero() {
3298                assert!(matches!(result, Err(LlmClientError::Timeout { .. })));
3299                assert!(
3300                    server
3301                        .received_requests()
3302                        .await
3303                        .expect("recorded requests")
3304                        .is_empty()
3305                );
3306            } else {
3307                let LlmResponse::Stream(mut chunks) = result?.llm_response else {
3308                    return Err("expected a streaming response".into());
3309                };
3310                tokio::time::sleep(Duration::from_millis(300)).await;
3311                assert!(matches!(
3312                    chunks.next().await,
3313                    Some(Err(LlmClientError::Timeout { .. }))
3314                ));
3315                assert!(chunks.next().await.is_none());
3316            }
3317        }
3318        Ok(())
3319    }
3320
3321    #[tokio::test]
3322    async fn timeout_is_retried_before_a_response_is_returned()
3323    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3324        let server = MockServer::start().await;
3325        let calls = Arc::new(AtomicUsize::new(0));
3326        let observed_calls = Arc::clone(&calls);
3327        Mock::given(method("POST"))
3328            .respond_with(move |_: &wiremock::Request| {
3329                if observed_calls.fetch_add(1, Ordering::SeqCst) == 0 {
3330                    ResponseTemplate::new(200).set_delay(Duration::from_millis(500))
3331                } else {
3332                    chat_success_response()
3333                }
3334            })
3335            .mount(&server)
3336            .await;
3337
3338        let mut client =
3339            TranslatingLlmClient::new(&chat_map_with_retries(&format!("{}/v1", server.uri()), 1))?;
3340        client.client = reqwest::Client::builder()
3341            .timeout(Duration::from_millis(100))
3342            .build()?;
3343        let response = client
3344            .call_rewrite_model(request_for(Some("gpt"), false), None)
3345            .await?;
3346
3347        assert_eq!(
3348            completion_text(&response.llm_response.into_agg().await?),
3349            "recovered"
3350        );
3351        assert_eq!(calls.load(Ordering::SeqCst), 2);
3352        Ok(())
3353    }
3354
3355    #[test]
3356    fn retryable_error_classes_are_explicit() {
3357        let transport = AttemptFailure {
3358            error: LlmClientError::Transport {
3359                source: std::io::Error::other("disconnected").into(),
3360            },
3361            status: None,
3362            retry_after: None,
3363        };
3364        assert!(transport.is_retryable());
3365
3366        for status in [
3367            StatusCode::REQUEST_TIMEOUT,
3368            StatusCode::TOO_MANY_REQUESTS,
3369            StatusCode::INTERNAL_SERVER_ERROR,
3370            StatusCode::SERVICE_UNAVAILABLE,
3371            StatusCode::from_u16(599)
3372                .expect("599 is a syntactically valid HTTP code in the http crate"),
3373        ] {
3374            let failure = AttemptFailure {
3375                error: LlmClientError::UpstreamHttp {
3376                    status,
3377                    body: String::new(),
3378                    headers: Box::default(),
3379                },
3380                status: Some(status),
3381                retry_after: None,
3382            };
3383            assert!(failure.is_retryable(), "HTTP {status} should retry");
3384        }
3385        for status in [
3386            StatusCode::BAD_REQUEST,
3387            StatusCode::UNAUTHORIZED,
3388            StatusCode::CONFLICT,
3389            StatusCode::from_u16(600)
3390                .expect("600 is a syntactically valid HTTP code in the http crate"),
3391        ] {
3392            let failure = AttemptFailure {
3393                error: LlmClientError::UpstreamHttp {
3394                    status,
3395                    body: String::new(),
3396                    headers: Box::default(),
3397                },
3398                status: Some(status),
3399                retry_after: None,
3400            };
3401            assert!(!failure.is_retryable(), "HTTP {status} should fail fast");
3402        }
3403
3404        let configuration = AttemptFailure {
3405            error: LlmClientError::Configuration {
3406                message: "invalid header".to_string(),
3407            },
3408            status: None,
3409            retry_after: None,
3410        };
3411        assert!(!configuration.is_retryable());
3412
3413        let context_window = AttemptFailure {
3414            error: LlmClientError::ContextWindowExceeded {
3415                model: ModelId::from("gpt"),
3416                message: "too long".to_string(),
3417            },
3418            status: Some(StatusCode::BAD_REQUEST),
3419            retry_after: None,
3420        };
3421        assert!(!context_window.is_retryable());
3422    }
3423
3424    #[test]
3425    fn retry_after_supports_seconds_and_http_dates() {
3426        let mut headers = HeaderMap::new();
3427        headers.insert(RETRY_AFTER, reqwest::header::HeaderValue::from_static("3"));
3428        assert_eq!(retry_after_delay(&headers), Some(Duration::from_secs(3)));
3429
3430        let retry_at = SystemTime::now() + Duration::from_secs(2);
3431        let value = httpdate::fmt_http_date(retry_at);
3432        let Ok(value) = reqwest::header::HeaderValue::from_str(&value) else {
3433            panic!("formatted HTTP date should be a valid header");
3434        };
3435        headers.insert(RETRY_AFTER, value);
3436        let Some(delay) = retry_after_delay(&headers) else {
3437            panic!("HTTP date should produce a retry delay");
3438        };
3439        assert!(delay <= Duration::from_secs(2));
3440    }
3441
3442    #[tokio::test]
3443    async fn routed_llm_client_exposes_timeout_variant()
3444    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3445        let server = MockServer::start().await;
3446        Mock::given(method("POST"))
3447            .respond_with(
3448                ResponseTemplate::new(200).set_delay(std::time::Duration::from_millis(100)),
3449            )
3450            .mount(&server)
3451            .await;
3452
3453        let mut client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
3454        client.client = reqwest::Client::builder()
3455            .timeout(std::time::Duration::from_millis(10))
3456            .build()?;
3457
3458        let Err(error) = client.call(request_for(Some("gpt"), false)).await else {
3459            panic!("expected a timeout");
3460        };
3461        let LlmClientError::Timeout { source } = error else {
3462            panic!("expected the protocol timeout variant");
3463        };
3464        let Some(source) = source.downcast_ref::<reqwest::Error>() else {
3465            panic!("expected the reqwest timeout source");
3466        };
3467        assert!(source.is_timeout());
3468        Ok(())
3469    }
3470
3471    // A connect that never completes sends nothing, like a refused connection.
3472    #[cfg(target_os = "linux")]
3473    #[tokio::test]
3474    async fn connect_timeout_is_a_transport_error()
3475    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3476        // Linux drops SYNs once a listener's accept queue is full, so later
3477        // connects hang like an upstream behind a dropping firewall.
3478        let socket = tokio::net::TcpSocket::new_v4()?;
3479        socket.bind("127.0.0.1:0".parse()?)?;
3480        let listener = socket.listen(0)?;
3481        let addr = listener.local_addr()?;
3482        let _queued: Vec<_> = (0..2)
3483            .map(|_| {
3484                std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(100))
3485            })
3486            .collect();
3487
3488        let mut client = TranslatingLlmClient::new(&chat_map(&format!("http://{addr}/v1")))?;
3489        // Stands in for the OS connect timeout (30 s on Linux via reqwest's default
3490        // TCP_USER_TIMEOUT); both surface as `is_connect() && is_timeout()`.
3491        client.client = reqwest::Client::builder()
3492            .connect_timeout(std::time::Duration::from_millis(100))
3493            .build()?;
3494
3495        let Err(error) = client.call(request_for(Some("gpt"), false)).await else {
3496            panic!("expected the connect to fail");
3497        };
3498        let LlmClientError::Transport { source } = error else {
3499            panic!("expected Transport, got {error:?}");
3500        };
3501        let Some(source) = source.downcast_ref::<reqwest::Error>() else {
3502            panic!("expected the reqwest connect-timeout source");
3503        };
3504        assert!(source.is_connect());
3505        assert!(source.is_timeout());
3506        Ok(())
3507    }
3508
3509    #[tokio::test]
3510    async fn llama_cpp_context_overflow_400_is_mapped()
3511    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3512        let server = MockServer::start().await;
3513        Mock::given(method("POST"))
3514            .respond_with(ResponseTemplate::new(400).set_body_json(json!({
3515                "error": {
3516                    "message": "request (6016 tokens) exceeds the available context size (4096 tokens), try increasing it"
3517                }
3518            })))
3519            .mount(&server)
3520            .await;
3521
3522        let client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
3523
3524        let Err(error) = client
3525            .call_rewrite_model(request_for(Some("gpt"), false), None)
3526            .await
3527        else {
3528            panic!("expected an error");
3529        };
3530        assert!(matches!(
3531            error,
3532            LlmClientError::ContextWindowExceeded { model, .. } if model == "gpt"
3533        ));
3534        Ok(())
3535    }
3536
3537    #[tokio::test]
3538    async fn content_policy_400_preserves_upstream_error()
3539    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3540        let server = MockServer::start().await;
3541        let body = json!({
3542            "error": {
3543                "code": "content_policy_violation",
3544                "message": "request blocked by content policy",
3545                "type": "invalid_request_error"
3546            },
3547            "metadata": {"documentation_section": "context window"}
3548        });
3549        Mock::given(method("POST"))
3550            .respond_with(ResponseTemplate::new(400).set_body_json(&body))
3551            .expect(1)
3552            .mount(&server)
3553            .await;
3554        let client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
3555        let Err(error) = client
3556            .call_rewrite_model(request_for(Some("gpt"), false), None)
3557            .await
3558        else {
3559            panic!("expected a policy denial");
3560        };
3561        let LlmClientError::UpstreamHttp {
3562            status,
3563            body: actual,
3564            ..
3565        } = error
3566        else {
3567            panic!("expected the upstream HTTP error, got {error:?}");
3568        };
3569        assert_eq!(status, StatusCode::BAD_REQUEST);
3570        assert_eq!(serde_json::from_str::<serde_json::Value>(&actual)?, body);
3571        Ok(())
3572    }
3573
3574    #[tokio::test]
3575    async fn forwards_only_allowlisted_metadata_headers()
3576    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3577        let server = MockServer::start().await;
3578        Mock::given(method("POST"))
3579            .and(wiremock::matchers::header("x-request-id", "abc"))
3580            // A forwarded Authorization must NOT override the backend's bearer key.
3581            .and(wiremock::matchers::header("authorization", "Bearer secret"))
3582            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
3583                "id": "1", "model": "gpt",
3584                "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
3585                "usage": {}
3586            })))
3587            .mount(&server)
3588            .await;
3589
3590        let mut headers = http::HeaderMap::new();
3591        headers.insert("x-request-id", http::HeaderValue::from_static("abc"));
3592        headers.insert(
3593            "authorization",
3594            http::HeaderValue::from_static("Bearer client-key"),
3595        );
3596        headers.insert(
3597            "x-goog-api-key",
3598            http::HeaderValue::from_static("client-google-key"),
3599        );
3600        headers.insert(
3601            "x-custom-internal-secret",
3602            http::HeaderValue::from_static("client-custom-key"),
3603        );
3604        let request = request_with_headers("gpt", headers);
3605
3606        let client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
3607
3608        // The allowed request id survives and caller authorization cannot replace
3609        // the backend's credential.
3610        client.call_rewrite_model(request, None).await?;
3611        let received = server
3612            .received_requests()
3613            .await
3614            .ok_or("request recording should be enabled")?;
3615        let received = received.first().ok_or("expected one upstream request")?;
3616        assert!(!received.headers.contains_key("x-goog-api-key"));
3617        assert!(!received.headers.contains_key("x-custom-internal-secret"));
3618        Ok(())
3619    }
3620
3621    #[tokio::test]
3622    async fn forwards_application_headers_with_forward_auth()
3623    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3624        let server = MockServer::start().await;
3625        Mock::given(method("POST"))
3626            .and(wiremock::matchers::header(
3627                "authorization",
3628                "Bearer client-key",
3629            ))
3630            .and(wiremock::matchers::header(
3631                "x-goog-api-key",
3632                "client-google-key",
3633            ))
3634            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
3635                "id": "1", "model": "gpt",
3636                "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
3637                "usage": {}
3638            })))
3639            .mount(&server)
3640            .await;
3641
3642        let mut headers = http::HeaderMap::new();
3643        headers.insert(
3644            "authorization",
3645            http::HeaderValue::from_static("Bearer client-key"),
3646        );
3647        headers.insert(
3648            "x-goog-api-key",
3649            http::HeaderValue::from_static("client-google-key"),
3650        );
3651        headers.append("x-custom", http::HeaderValue::from_static("caller-first"));
3652        headers.append("x-custom", http::HeaderValue::from_static("caller-second"));
3653        headers.insert("host", http::HeaderValue::from_static("client.example"));
3654        headers.insert("content-type", http::HeaderValue::from_static("text/plain"));
3655        headers.insert("connection", http::HeaderValue::from_static("x-hop-by-hop"));
3656        headers.insert(
3657            "x-hop-by-hop",
3658            http::HeaderValue::from_static("client-only"),
3659        );
3660        let request = request_with_headers("gpt", headers);
3661        let mut backend_config = forwarding_config(&format!("{}/v1", server.uri()));
3662        backend_config.extra_headers = BTreeMap::from([
3663            ("X-Custom".into(), "configured".into()),
3664            ("X-Configured-Only".into(), "static".into()),
3665        ]);
3666        let client = TranslatingLlmClient::new(&[ModelConfig::new(
3667            "gpt",
3668            Backend::OpenAiChat(backend_config),
3669            None,
3670        )])?;
3671
3672        client.call_rewrite_model(request, None).await?;
3673        let received = server
3674            .received_requests()
3675            .await
3676            .ok_or("request recording should be enabled")?;
3677        let received = received.first().ok_or("expected one upstream request")?;
3678        assert_ne!(received.headers["host"], "client.example");
3679        assert_eq!(received.headers["content-type"], "application/json");
3680        assert!(!received.headers.contains_key("connection"));
3681        assert!(!received.headers.contains_key("x-hop-by-hop"));
3682        assert_eq!(received.headers.get_all("x-custom").iter().count(), 1);
3683        assert_eq!(received.headers["x-custom"], "configured");
3684        assert_eq!(received.headers["x-configured-only"], "static");
3685        Ok(())
3686    }
3687
3688    #[tokio::test]
3689    async fn forward_auth_preserves_anthropic_headers_and_redacts_errors()
3690    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3691        let server = MockServer::start().await;
3692        Mock::given(method("POST"))
3693            .and(path("/v1/messages"))
3694            .and(|request: &wiremock::Request| {
3695                request
3696                    .headers
3697                    .get("anthropic-beta")
3698                    .and_then(|value| value.to_str().ok())
3699                    == Some("oauth-2025-04-20")
3700                    && request.headers.get_all("anthropic-version").iter().count() == 1
3701                    && request
3702                        .headers
3703                        .get("anthropic-version")
3704                        .and_then(|value| value.to_str().ok())
3705                        == Some("2023-06-01")
3706            })
3707            .respond_with(ResponseTemplate::new(401).set_body_json(json!({
3708                "error": {"message": "rejected client-google-key"}
3709            })))
3710            .mount(&server)
3711            .await;
3712
3713        let mut headers = http::HeaderMap::new();
3714        headers.insert(
3715            "authorization",
3716            http::HeaderValue::from_static("Bearer client-key"),
3717        );
3718        headers.insert(
3719            "x-goog-api-key",
3720            http::HeaderValue::from_static("client-google-key"),
3721        );
3722        headers.insert(
3723            "anthropic-beta",
3724            http::HeaderValue::from_static("oauth-2025-04-20,prompt-caching-2024-07-31"),
3725        );
3726        headers.insert(
3727            "anthropic-version",
3728            http::HeaderValue::from_static("caller-version"),
3729        );
3730        let backend_config = forwarding_config(&server.uri());
3731        let client = TranslatingLlmClient::new(&[ModelConfig::new(
3732            "claude",
3733            Backend::Anthropic(backend_config),
3734            None,
3735        )])?;
3736        let raw = json!({
3737            "model": "claude",
3738            "max_tokens": 8,
3739            "messages": [{"role": "user", "content": "hello"}]
3740        });
3741
3742        let Err(LlmClientError::UpstreamHttp { body, .. }) = client
3743            .call_rewrite_model(
3744                wire_request(raw, Some(headers), WireFormat::AnthropicMessages)?,
3745                Some(&ModelId::from("claude")),
3746            )
3747            .await
3748        else {
3749            panic!("expected an upstream HTTP error");
3750        };
3751        assert_eq!(body, r#"{"error":{"message":"rejected [REDACTED]"}}"#);
3752        Ok(())
3753    }
3754
3755    // Exercises the `RoutedLlmClient` impl: `call` uses the model already materialized in the
3756    // request and round-trips a buffered response.
3757    #[tokio::test]
3758    async fn routed_llm_client_serves_the_request_model()
3759    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3760        let server = MockServer::start().await;
3761        Mock::given(method("POST"))
3762            .and(path("/v1/chat/completions"))
3763            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
3764                "id": "chatcmpl-1",
3765                "model": "gpt",
3766                "choices": [{
3767                    "index": 0,
3768                    "message": {"role": "assistant", "content": "routed hi"},
3769                    "finish_reason": "stop"
3770                }],
3771                "usage": {"prompt_tokens": 1, "completion_tokens": 2, "total_tokens": 3}
3772            })))
3773            .mount(&server)
3774            .await;
3775
3776        let client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
3777        let response = client.call(request_for(Some("gpt"), false)).await?;
3778        let agg = response.llm_response.into_agg().await?;
3779        assert_eq!(completion_text(&agg), "routed hi");
3780        Ok(())
3781    }
3782
3783    // A Codex namespace is folded into the upstream tool name.
3784    #[tokio::test]
3785    async fn chat_backend_folds_codex_mcp_namespace_into_the_tool_name()
3786    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3787        let server = MockServer::start().await;
3788        Mock::given(method("POST"))
3789            .and(path("/v1/chat/completions"))
3790            .and(wiremock::matchers::body_partial_json(json!({
3791                "tools": [{
3792                    "type": "function",
3793                    "function": {"name": "mcp__open_websearch__search"}
3794                }]
3795            })))
3796            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
3797                "id": "chatcmpl-1",
3798                "model": "gpt",
3799                "choices": [{
3800                    "index": 0,
3801                    "message": {
3802                        "role": "assistant",
3803                        "content": null,
3804                        "tool_calls": [{
3805                            "id": "call_1",
3806                            "type": "function",
3807                            "function": {
3808                                "name": "mcp__open_websearch__search",
3809                                "arguments": "{\"q\":\"rust\"}"
3810                            }
3811                        }]
3812                    },
3813                    "finish_reason": "tool_calls"
3814                }],
3815                "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}
3816            })))
3817            .mount(&server)
3818            .await;
3819
3820        let client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
3821        let raw = json!({
3822            "model": "client-facing",
3823            "input": "Search for Rust.",
3824            "tools": [{
3825                "type": "namespace",
3826                "name": "mcp__open_websearch",
3827                "tools": [{
3828                    "type": "function",
3829                    "name": "search",
3830                    "description": "Search the web",
3831                    "parameters": {"type": "object", "properties": {"q": {"type": "string"}}}
3832                }]
3833            }]
3834        });
3835
3836        let response = client
3837            .call_rewrite_model(
3838                wire_request(raw, None, WireFormat::OpenAiResponses)?,
3839                Some(&ModelId::from("gpt")),
3840            )
3841            .await?;
3842        let agg = response.llm_response.into_agg().await?;
3843
3844        assert_tool_call_name(&agg, "mcp__open_websearch__search");
3845        Ok(())
3846    }
3847
3848    #[tokio::test]
3849    async fn openai_responses_backend_flattens_codex_namespaces_before_upstream()
3850    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3851        let server = MockServer::start().await;
3852        Mock::given(method("POST"))
3853            .and(path("/v1/responses"))
3854            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
3855                "id": "resp_1",
3856                "model": "gpt",
3857                "object": "response",
3858                "created_at": 0,
3859                "status": "completed",
3860                "output": [{
3861                    "type": "function_call",
3862                    "call_id": "call_1",
3863                    "name": "mcp__open_websearch__search",
3864                    "arguments": "{\"q\":\"rust\"}"
3865                }],
3866                "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2}
3867            })))
3868            .mount(&server)
3869            .await;
3870
3871        let client = TranslatingLlmClient::new(&responses_map(&format!("{}/v1", server.uri())))?;
3872        let parameters = json!({"type": "object", "properties": {"q": {"type": "string"}}});
3873        let raw = json!({
3874            "model": "client-facing",
3875            "input": [{
3876                "type": "function_call",
3877                "call_id": "call_0",
3878                "name": "search",
3879                "namespace": "mcp__open_websearch",
3880                "arguments": "{}"
3881            }],
3882            "tool_choice": {
3883                "type": "function",
3884                "name": "search",
3885                "namespace": "mcp__open_websearch"
3886            },
3887            "tools": [{
3888                "type": "namespace",
3889                "name": "mcp__open_websearch",
3890                "tools": [{
3891                    "type": "function",
3892                    "name": "search",
3893                    "parameters": parameters.clone()
3894                }]
3895            }]
3896        });
3897
3898        let response = client
3899            .call_rewrite_model(
3900                wire_request(raw, None, WireFormat::OpenAiResponses)?,
3901                Some(&ModelId::from("gpt")),
3902            )
3903            .await?;
3904        let agg = response.llm_response.into_agg().await?;
3905
3906        let received = server
3907            .received_requests()
3908            .await
3909            .ok_or("request recording should be enabled")?;
3910        let request_body: Value = serde_json::from_slice(&received[0].body)?;
3911        assert_eq!(request_body["model"], "gpt");
3912        assert_eq!(
3913            request_body["tools"],
3914            json!([{
3915                "type": "function",
3916                "name": "mcp__open_websearch__search",
3917                "description": "",
3918                "parameters": parameters
3919            }])
3920        );
3921        assert_eq!(
3922            request_body["tool_choice"],
3923            json!({"type": "function", "name": "mcp__open_websearch__search"})
3924        );
3925        assert_eq!(
3926            request_body["input"][0]["name"],
3927            "mcp__open_websearch__search"
3928        );
3929        assert!(request_body["input"][0].get("namespace").is_none());
3930        assert_tool_call_name(&agg, "mcp__open_websearch__search");
3931        Ok(())
3932    }
3933
3934    // A stage route can answer early steps of a Codex turn from Claude and a later step from
3935    // GPT, and Codex replays Claude's reasoning items on every step. OpenAI returns 400 for two
3936    // kinds: items with an ID but no `encrypted_content` when the request sets `store: false`,
3937    // and items whose `encrypted_content` holds Anthropic thinking that Switchyard packed for
3938    // the client. The Responses leg must drop both and keep GPT's own encrypted reasoning.
3939    // A non-OpenAI target instead keeps the plaintext and drops both payloads.
3940    #[tokio::test]
3941    async fn openai_responses_backend_drops_reasoning_the_provider_cannot_read()
3942    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3943        let server = MockServer::start().await;
3944        Mock::given(method("POST"))
3945            .and(path("/v1/responses"))
3946            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
3947                "id": "resp_1",
3948                "model": "gpt",
3949                "object": "response",
3950                "created_at": 0,
3951                "status": "completed",
3952                "output": [{
3953                    "type": "message",
3954                    "role": "assistant",
3955                    "content": [{"type": "output_text", "text": "ok"}]
3956                }],
3957                "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2}
3958            })))
3959            .mount(&server)
3960            .await;
3961
3962        let mut claude_reasoning = json!({
3963            "type": "reasoning",
3964            "id": "rs_b99feb9a-763d-4f7f-b6b2-2c0199b47ded",
3965            "summary": [{"type": "summary_text", "text": "Read the files first."}],
3966            "encrypted_content": null
3967        });
3968        // Build the item the way Switchyard does when it returns a Claude reply to a Responses
3969        // client, so the test follows any change to that format.
3970        let claude_reply = switchyard_translation::TranslationEngine::default()
3971            .translate_response(
3972                WireFormat::AnthropicMessages,
3973                WireFormat::OpenAiResponses,
3974                &json!({
3975                    "id": "msg_1",
3976                    "type": "message",
3977                    "role": "assistant",
3978                    "model": "claude",
3979                    "content": [
3980                        {"type": "thinking", "thinking": "Plan the edit.", "signature": "sig-abc"},
3981                        {"type": "text", "text": "ok"}
3982                    ],
3983                    "stop_reason": "end_turn",
3984                    "usage": {"input_tokens": 1, "output_tokens": 1}
3985                }),
3986                &switchyard_translation::TranslationPolicy::default(),
3987            )?
3988            .body;
3989        let switchyard_reasoning = claude_reply["output"]
3990            .as_array()
3991            .and_then(|output| output.iter().find(|item| item["type"] == "reasoning"))
3992            .cloned()
3993            .ok_or("translated Claude reply should contain a reasoning item")?;
3994        assert!(switchyard_translation::is_anthropic_thinking_envelope(
3995            switchyard_reasoning["encrypted_content"]
3996                .as_str()
3997                .unwrap_or_default()
3998        ));
3999        let mut gpt_reasoning = json!({
4000            "type": "reasoning",
4001            "id": "rs_gpt",
4002            "summary": [],
4003            "encrypted_content": "opaque-encrypted-reasoning"
4004        });
4005        let mut empty_reasoning =
4006            json!({"type": "reasoning", "id": "rs_empty", "summary": [], "encrypted_content": ""});
4007        let user = json!({"type": "message", "role": "user", "content": "fix the build"});
4008        let call = json!({"type": "function_call", "call_id": "call_1", "name": "exec", "arguments": "{}"});
4009        let output = json!({"type": "function_call_output", "call_id": "call_1", "output": "ok"});
4010        let input = json!([
4011            user,
4012            claude_reasoning,
4013            switchyard_reasoning,
4014            call,
4015            output,
4016            gpt_reasoning,
4017            empty_reasoning
4018        ]);
4019
4020        let models = ["openai/gpt-5", "nvidia/zai-org/glm-5.3-flash"].map(|model| {
4021            ModelConfig::new(
4022                model,
4023                Backend::OpenAiResponses(config(&format!("{}/v1", server.uri()))),
4024                None,
4025            )
4026        });
4027        let client = TranslatingLlmClient::new(&models)?;
4028        for model in ["openai/gpt-5", "nvidia/zai-org/glm-5.3-flash"] {
4029            for store in [json!(false), json!(true)] {
4030                let raw = json!({"model": "client-facing", "store": store, "input": input.clone()});
4031                client
4032                    .call_rewrite_model(
4033                        wire_request(raw, None, WireFormat::OpenAiResponses)?,
4034                        Some(&ModelId::from(model)),
4035                    )
4036                    .await?;
4037            }
4038        }
4039
4040        let received = server
4041            .received_requests()
4042            .await
4043            .ok_or("request recording should be enabled")?;
4044        let sent: Vec<Value> = received
4045            .iter()
4046            .map(|request| serde_json::from_slice::<Value>(&request.body))
4047            .collect::<std::result::Result<_, _>>()?;
4048        assert_eq!(sent.len(), 4);
4049        for request in &sent {
4050            assert!(
4051                request["input"]
4052                    .as_array()
4053                    .ok_or("expected input array")?
4054                    .iter()
4055                    .all(|item| !item["encrypted_content"]
4056                        .as_str()
4057                        .is_some_and(switchyard_translation::is_anthropic_thinking_envelope)),
4058                "provider cannot read translated Anthropic reasoning"
4059            );
4060        }
4061
4062        // GLM keeps the plaintext beside the Anthropic envelope and drops GPT's payload.
4063        let mut switchyard_plaintext = switchyard_reasoning.clone();
4064        switchyard_plaintext
4065            .as_object_mut()
4066            .ok_or("object")?
4067            .remove("encrypted_content");
4068        assert_eq!(
4069            sent[2]["input"],
4070            json!([user, claude_reasoning, switchyard_plaintext, call, output])
4071        );
4072        assert_eq!(
4073            sent[3]["input"],
4074            json!([
4075                user,
4076                claude_reasoning,
4077                switchyard_plaintext,
4078                call,
4079                output,
4080                empty_reasoning
4081            ])
4082        );
4083
4084        for item in [
4085            &mut claude_reasoning,
4086            &mut gpt_reasoning,
4087            &mut empty_reasoning,
4088        ] {
4089            item["content"] = json!([]);
4090        }
4091        // With `store: false`, only GPT's own encrypted reasoning survives.
4092        assert_eq!(sent[0]["input"], json!([user, call, output, gpt_reasoning]));
4093        // With `store: true`, IDs can refer to stored reasoning, but OpenAI still cannot
4094        // decrypt the Switchyard item.
4095        assert_eq!(
4096            sent[1]["input"],
4097            json!([
4098                user,
4099                claude_reasoning,
4100                call,
4101                output,
4102                gpt_reasoning,
4103                empty_reasoning
4104            ])
4105        );
4106        Ok(())
4107    }
4108
4109    // Allowed caller headers reach the upstream.
4110    #[tokio::test]
4111    async fn call_rewrite_model_forwards_caller_headers()
4112    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
4113        let server = MockServer::start().await;
4114        Mock::given(method("POST"))
4115            .and(wiremock::matchers::header("x-request-id", "abc"))
4116            // A forwarded authorization must NOT override the backend's bearer key.
4117            .and(wiremock::matchers::header("authorization", "Bearer secret"))
4118            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
4119                "id": "1", "model": "gpt",
4120                "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
4121                "usage": {}
4122            })))
4123            .mount(&server)
4124            .await;
4125
4126        let mut headers = http::HeaderMap::new();
4127        headers.insert("x-request-id", http::HeaderValue::from_static("abc"));
4128        headers.insert(
4129            "authorization",
4130            http::HeaderValue::from_static("Bearer client-key"),
4131        );
4132
4133        let client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
4134        let raw = json!({"model": "gpt", "messages": [{"role": "user", "content": "hi"}]});
4135        // The allowed request id survives and caller authorization cannot replace
4136        // the backend's credential.
4137        client
4138            .call_rewrite_model(
4139                wire_request(raw, Some(headers), WireFormat::OpenAiChat)?,
4140                Some(&ModelId::from("gpt")),
4141            )
4142            .await?;
4143        Ok(())
4144    }
4145    #[tokio::test]
4146    async fn bad_media_does_not_retry_or_cool_down_the_backend()
4147    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
4148        use switchyard_protocol::{ContentBlock, ImageSource};
4149        for retries in [0, 2] {
4150            let server = MockServer::start().await;
4151            let calls = Arc::new(AtomicUsize::new(0));
4152            let seen = calls.clone();
4153            Mock::given(method("POST"))
4154                .respond_with(move |request: &wiremock::Request| {
4155                    seen.fetch_add(1, Ordering::SeqCst);
4156                    if String::from_utf8_lossy(&request.body).contains("image_url") {
4157                        ResponseTemplate::new(500).set_body_json(json!({"error": {
4158                            "message": "cannot make GET request to image URL", "type": "server_error"
4159                        }}))
4160                    } else { chat_success_response() }
4161                }).mount(&server).await;
4162            let backend = HttpBackendConfig {
4163                failure_cooldown: Duration::from_secs(60),
4164                ..config_with_retries(&format!("{}/v1", server.uri()), retries)
4165            };
4166            let client = TranslatingLlmClient::new(&[ModelConfig::new(
4167                "gpt",
4168                Backend::OpenAiChat(backend),
4169                None,
4170            )])?;
4171            let mut broken = request_for(Some("gpt"), false);
4172            broken.llm_request.messages[0]
4173                .content
4174                .push(ContentBlock::Image {
4175                    source: ImageSource::Url {
4176                        url: "https://example.invalid/missing.png".into(),
4177                        detail: None,
4178                    },
4179                });
4180            assert!(matches!(
4181                client.call_rewrite_model(broken, None).await,
4182                Err(LlmClientError::UpstreamHttp {
4183                    status: StatusCode::INTERNAL_SERVER_ERROR,
4184                    ..
4185                })
4186            ));
4187            let response = client
4188                .call_rewrite_model(request_for(Some("gpt"), false), None)
4189                .await?;
4190            assert_eq!(
4191                completion_text(&response.llm_response.into_agg().await?),
4192                "recovered"
4193            );
4194            assert_eq!(calls.load(Ordering::SeqCst), 2);
4195        }
4196        Ok(())
4197    }
4198}