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", "x-session-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            !backend.is_provider_owned_header(name.as_str())
1024        } else {
1025            is_allowed_metadata_header(name.as_str())
1026        };
1027        if is_allowed && !is_non_forwardable_header(name.as_str(), headers) {
1028            forwarded.append(name, value.clone());
1029        }
1030    }
1031    builder.headers(forwarded)
1032}
1033
1034// Configured headers replace existing values for the same case-insensitive name.
1035fn apply_extra_headers(builder: RequestBuilder, backend: &Backend) -> RequestBuilder {
1036    let mut headers = HeaderMap::with_capacity(backend.extra_headers().len());
1037    // Names and values are validated by TranslatingLlmClient::new.
1038    for (name, value) in backend.extra_headers() {
1039        let name = HeaderName::from_bytes(name.as_bytes()).expect("validated header name");
1040        let value = HeaderValue::from_bytes(value.as_bytes()).expect("validated header value");
1041        headers.insert(name, value);
1042    }
1043    builder.headers(headers)
1044}
1045
1046// Overwrites the outbound body's `model` field with the resolved model id.
1047fn set_json_model(body: &mut Value, model: &str) {
1048    if let Value::Object(object) = body {
1049        object.insert("model".to_string(), Value::String(model.to_string()));
1050    }
1051}
1052
1053// The Codex Responses endpoint requires item-list input even on the preserved-body path.
1054fn normalize_codex_string_input(url: &str, body: &mut Value) {
1055    let codex = reqwest::Url::parse(url).ok().is_some_and(|url| {
1056        url.path()
1057            .trim_end_matches('/')
1058            .ends_with("/backend-api/codex/responses")
1059    });
1060    if codex && let Some(input @ Value::String(_)) = body.get_mut("input") {
1061        let text = input.take();
1062        *input = json!([{"type": "message", "role": "user", "content": text}]);
1063    }
1064}
1065
1066fn rejects_template_options(error: &LlmClientError) -> bool {
1067    let LlmClientError::UpstreamHttp { status, body, .. } = error else {
1068        return false;
1069    };
1070    if !matches!(
1071        *status,
1072        StatusCode::BAD_REQUEST | StatusCode::UNPROCESSABLE_ENTITY
1073    ) {
1074        return false;
1075    }
1076    let parsed = serde_json::from_str::<Value>(body).ok();
1077    let error = parsed.as_ref().and_then(|value| value.get("error"));
1078    let message = match &parsed {
1079        Some(_) => error
1080            .and_then(|error| error.get("message"))
1081            .and_then(Value::as_str)
1082            .unwrap_or_default(),
1083        None => body,
1084    }
1085    .to_ascii_lowercase();
1086    let field = error
1087        .and_then(|error| error.get("param"))
1088        .and_then(Value::as_str);
1089    let code = error
1090        .and_then(|error| error.get("code"))
1091        .and_then(Value::as_str);
1092    (field == Some("chat_template_kwargs") || message.contains("chat_template_kwargs"))
1093        && (matches!(code, Some("unknown_parameter" | "unsupported_parameter"))
1094            || [
1095                "unrecognized request argument",
1096                "unknown parameter",
1097                "unsupported parameter",
1098                "unexpected keyword argument",
1099                "unknown field",
1100                "unsupported field",
1101                "extra inputs are not permitted",
1102            ]
1103            .iter()
1104            .any(|phrase| message.contains(phrase)))
1105}
1106
1107// Drops fields accepted by OpenAI-like APIs but rejected by Anthropic Messages.
1108//
1109// A router can serve earlier turns of a session from an OpenAI-format target and
1110// later turns from an Anthropic one. Clients such as Claude Code send
1111// `context_management` on every turn, so the Anthropic leg must strip it or the
1112// upstream rejects the request (for example `clear_thinking_20251015` strategy
1113// requires `thinking` to be enabled or adaptive).
1114fn strip_anthropic_incompatible_fields(body: &mut Value) {
1115    if let Value::Object(object) = body {
1116        object.remove("reasoning_effort");
1117        object.remove("context_management");
1118        // `strict: false` is the default, and Bedrock rejects the field outright.
1119        if let Some(Value::Array(tools)) = object.get_mut("tools") {
1120            for tool in tools {
1121                if let Value::Object(tool) = tool
1122                    && tool.get("strict") == Some(&Value::Bool(false))
1123                {
1124                    tool.remove("strict");
1125                }
1126            }
1127        }
1128    }
1129}
1130
1131// NVIDIA Inference API's Anthropic-compatible schema rejects the strict tool-use
1132// extension that native Anthropic accepts.
1133fn nvidia_inference_api_backend(backend: &Backend) -> bool {
1134    reqwest::Url::parse(backend.base_url())
1135        .ok()
1136        .is_some_and(|url| {
1137            url.host_str()
1138                .is_some_and(|host| host.eq_ignore_ascii_case("inference-api.nvidia.com"))
1139        })
1140}
1141
1142fn strip_anthropic_tool_strict(body: &mut Value) {
1143    let Some(tools) = body.get_mut("tools").and_then(Value::as_array_mut) else {
1144        return;
1145    };
1146    for tool in tools.iter_mut().filter_map(Value::as_object_mut) {
1147        tool.remove("strict");
1148    }
1149}
1150
1151// Removes replayed `thinking` blocks that carry no signature.
1152//
1153// Anthropic requires signed thinking blocks on replay. A router can serve earlier
1154// turns of a session from an OpenAI-format target whose thinking blocks are
1155// unsigned, so the Anthropic leg must drop them or the upstream rejects the
1156// request. Bedrock enforces this (surfacing as a SigV4 signature mismatch) where
1157// Azure-hosted Anthropic currently does not.
1158fn strip_unsigned_thinking_blocks(body: &mut Value) {
1159    let Value::Object(object) = body else {
1160        return;
1161    };
1162    let Some(Value::Array(messages)) = object.get_mut("messages") else {
1163        return;
1164    };
1165    for message in messages {
1166        strip_unsigned_thinking_from_message(message);
1167    }
1168}
1169
1170// Drops unsigned thinking blocks from one message, collapsing content that ends
1171// up empty to an empty string so the message stays valid.
1172fn strip_unsigned_thinking_from_message(message: &mut Value) {
1173    let Value::Object(message) = message else {
1174        return;
1175    };
1176    let Some(Value::Array(blocks)) = message.get("content") else {
1177        return;
1178    };
1179    if !blocks.iter().any(is_unsigned_thinking_block) {
1180        return;
1181    }
1182    let Some(Value::Array(blocks)) = message.get_mut("content") else {
1183        return;
1184    };
1185    blocks.retain(|block| !is_unsigned_thinking_block(block));
1186    if blocks.is_empty() {
1187        message.insert("content".to_string(), Value::String(String::new()));
1188    }
1189}
1190
1191// A thinking block is unsigned when `signature` is absent or empty.
1192fn is_unsigned_thinking_block(block: &Value) -> bool {
1193    if block.get("type").and_then(Value::as_str) != Some("thinking") {
1194        return false;
1195    }
1196    !matches!(
1197        block.get("signature").and_then(Value::as_str),
1198        Some(signature) if !signature.is_empty()
1199    )
1200}
1201
1202// Forces the target's configured reasoning effort onto the outbound body, replacing the
1203// caller's value. Unlike `extra_body`, this is an override: a route that sends one model at a
1204// higher effort than the client asked for is the point of the setting.
1205fn apply_reasoning_effort(body: &mut Value, backend: &Backend) {
1206    let Some(effort) = backend.reasoning_effort() else {
1207        return;
1208    };
1209    let Value::Object(object) = body else {
1210        return;
1211    };
1212    match backend {
1213        // Responses nests effort under `reasoning`, Anthropic under `output_config`.
1214        Backend::OpenAiResponses(_) => set_nested_effort(object, "reasoning", effort),
1215        Backend::Anthropic(_) => set_nested_effort(object, "output_config", effort),
1216        Backend::OpenAiChat(_) => {
1217            // Chat Completions takes effort as a top-level field.
1218            object.insert(
1219                "reasoning_effort".to_string(),
1220                Value::String(effort.to_string()),
1221            );
1222        }
1223    }
1224}
1225
1226// Replaces only `effort` inside `key`, keeping fields the caller set next to it (`summary` or
1227// `format`, for example). A non-object value there is malformed and is replaced whole.
1228fn set_nested_effort(object: &mut serde_json::Map<String, Value>, key: &str, effort: &str) {
1229    let container = object
1230        .entry(key.to_string())
1231        .or_insert_with(|| Value::Object(serde_json::Map::new()));
1232    if !container.is_object() {
1233        *container = Value::Object(serde_json::Map::new());
1234    }
1235    if let Value::Object(container) = container {
1236        container.insert("effort".to_string(), Value::String(effort.to_string()));
1237    }
1238}
1239
1240// Applies target defaults without overriding fields supplied by the caller.
1241fn merge_extra_body(body: &mut Value, extra_body: &BTreeMap<String, Value>) {
1242    let Value::Object(object) = body else {
1243        return;
1244    };
1245    for (key, value) in extra_body {
1246        object.entry(key.clone()).or_insert_with(|| value.clone());
1247    }
1248}
1249
1250fn omit_configured_body_fields(body: &mut Value, omit_body_fields: &BTreeSet<String>) {
1251    let Value::Object(object) = body else {
1252        return;
1253    };
1254    for key in omit_body_fields {
1255        object.remove(key);
1256    }
1257}
1258
1259// Anthropic and Bedrock both cap a request at four blocks carrying
1260// `cache_control`, counting tools, system blocks and message blocks together.
1261const MAX_CACHE_CONTROL_BLOCKS: usize = 4;
1262
1263// Counts the blocks upstream will see carrying a `cache_control` marker. The
1264// marker's own value holds no such key, so it is never counted twice.
1265fn count_cache_control_blocks(value: &Value) -> usize {
1266    match value {
1267        Value::Object(map) => {
1268            usize::from(map.contains_key("cache_control"))
1269                + map.values().map(count_cache_control_blocks).sum::<usize>()
1270        }
1271        Value::Array(items) => items.iter().map(count_cache_control_blocks).sum(),
1272        _ => 0,
1273    }
1274}
1275
1276// This helper marks the final caller content block before any temporary notes, if policy permits.
1277fn enable_anthropic_prompt_caching(body: &mut Value, temporary_note_count: usize) {
1278    // Anthropic rejects a fifth cache marker with HTTP 400.
1279    // This check preserves the caller's markers when the request has reached that limit.
1280    if count_cache_control_blocks(body) >= MAX_CACHE_CONTROL_BLOCKS {
1281        return;
1282    }
1283    // Requests with only a top-level `1h` policy can return HTTP 400.
1284    // New block markers match the caller's TTL on turns with or without notes.
1285    let marker = body
1286        .get("cache_control")
1287        .cloned()
1288        .unwrap_or_else(|| serde_json::json!({"type":"ephemeral"}));
1289    let Some(messages) = body.get_mut("messages").and_then(Value::as_array_mut) else {
1290        return;
1291    };
1292    let mut remaining = temporary_note_count;
1293    // Temporary guidance is absent next turn, so the breakpoint must precede it.
1294    for message in messages.iter_mut().rev() {
1295        match message.get_mut("content") {
1296            Some(content @ Value::String(_)) if remaining == 0 => {
1297                let text = std::mem::take(content);
1298                *content = serde_json::json!([{
1299                    "type": "text", "text": text, "cache_control": marker
1300                }]);
1301                return;
1302            }
1303            Some(Value::String(_)) => remaining = remaining.saturating_sub(1),
1304            Some(Value::Array(blocks)) => {
1305                if remaining >= blocks.len() {
1306                    remaining -= blocks.len();
1307                    continue;
1308                }
1309                let index = blocks.len() - remaining - 1;
1310                if let Some(block) = blocks[index].as_object_mut() {
1311                    block.entry("cache_control".to_string()).or_insert(marker);
1312                }
1313                return;
1314            }
1315            _ => {}
1316        }
1317    }
1318}
1319
1320// GPT-5.6 and GPT-6 cache writes end at selected message or content boundaries.
1321// A temporary suffix needs a separate cache entry before it so the next request can reuse the prefix.
1322fn enable_openai_guidance_caching(
1323    body: &mut Value,
1324    format: WireFormat,
1325    model: &ModelId,
1326    suffix: usize,
1327) {
1328    let name = model.as_str().rsplit('/').next().unwrap_or_default();
1329    let supported = name == "gpt-5.6"
1330        || name.starts_with("gpt-5.6-")
1331        || name == "gpt-6"
1332        || name.starts_with("gpt-6-")
1333        || name.starts_with("gpt-6.");
1334    // Explicit-only callers choose their write locations.
1335    // This helper adds markers only for names recognized by its model-name check.
1336    if suffix == 0
1337        || !supported
1338        || body
1339            .pointer("/prompt_cache_options/mode")
1340            .and_then(Value::as_str)
1341            == Some("explicit")
1342    {
1343        return;
1344    }
1345    let key = if format == WireFormat::OpenAiResponses {
1346        "input"
1347    } else {
1348        "messages"
1349    };
1350    let Some(items) = body.get_mut(key).and_then(Value::as_array_mut) else {
1351        return;
1352    };
1353    let marker_count = items
1354        .iter()
1355        .map(|item| {
1356            ["content", "output"]
1357                .iter()
1358                .filter_map(|key| item.get(key).and_then(Value::as_array))
1359                .flatten()
1360                .filter(|block| block.get("prompt_cache_breakpoint").is_some())
1361                .count()
1362        })
1363        .sum::<usize>();
1364    // Implicit mode reserves one of the four write slots for the provider's final breakpoint.
1365    if marker_count >= 3 {
1366        return;
1367    }
1368    let Some(prefix_len) = items.len().checked_sub(suffix) else {
1369        return;
1370    };
1371    for item in items[..prefix_len].iter_mut().rev() {
1372        let field = if item.get("type").and_then(Value::as_str) == Some("function_call_output") {
1373            "output"
1374        } else if matches!(
1375            item.get("role").and_then(Value::as_str),
1376            Some("user" | "tool" | "developer" | "system")
1377        ) {
1378            "content"
1379        } else {
1380            continue;
1381        };
1382        let Some(content) = item.get_mut(field) else {
1383            continue;
1384        };
1385        if let Value::String(text) = content {
1386            let text = std::mem::take(text);
1387            let kind = if format == WireFormat::OpenAiResponses {
1388                "input_text"
1389            } else {
1390                "text"
1391            };
1392            *content = serde_json::json!([{"type":kind,"text":text}]);
1393        }
1394        // Empty content arrays have no block to mark, so the search continues through earlier items.
1395        if let Some(block) = content
1396            .as_array_mut()
1397            .and_then(|blocks| blocks.last_mut())
1398            .and_then(Value::as_object_mut)
1399        {
1400            block
1401                .entry("prompt_cache_breakpoint".to_string())
1402                .or_insert_with(|| serde_json::json!({"mode":"explicit"}));
1403            return;
1404        }
1405    }
1406}
1407
1408// Requests streamed Chat usage by default while preserving an explicit caller choice.
1409fn ensure_openai_stream_usage(body: &mut Value) {
1410    let Value::Object(object) = body else {
1411        return;
1412    };
1413    if object.get("stream").and_then(Value::as_bool) != Some(true) {
1414        return;
1415    }
1416
1417    match object.get_mut("stream_options") {
1418        Some(Value::Object(options)) => {
1419            options
1420                .entry("include_usage".to_string())
1421                .or_insert(Value::Bool(true));
1422        }
1423        _ => {
1424            let mut options = Map::new();
1425            options.insert("include_usage".to_string(), Value::Bool(true));
1426            object.insert("stream_options".to_string(), Value::Object(options));
1427        }
1428    }
1429}
1430
1431fn is_allowed_metadata_header(name: &str) -> bool {
1432    ALLOWED_METADATA_HEADERS
1433        .iter()
1434        .any(|allowed| name.eq_ignore_ascii_case(allowed))
1435}
1436
1437fn is_non_forwardable_header(name: &str, headers: &HeaderMap) -> bool {
1438    NON_FORWARDABLE_HEADERS
1439        .iter()
1440        .any(|blocked| name.eq_ignore_ascii_case(blocked))
1441        || headers.get_all("connection").iter().any(|value| {
1442            value
1443                .as_bytes()
1444                .split(|byte| *byte == b',')
1445                .any(|option| option.trim_ascii().eq_ignore_ascii_case(name.as_bytes()))
1446        })
1447}
1448
1449// Unknown application headers can carry credentials when auth forwarding is enabled.
1450fn redact_forwarded_headers(
1451    mut body: String,
1452    metadata: Option<&Metadata>,
1453    is_forwarding_auth: bool,
1454) -> String {
1455    if !is_forwarding_auth {
1456        return body;
1457    }
1458    let Some(headers) = metadata.and_then(|metadata| metadata.http_headers.as_ref()) else {
1459        return body;
1460    };
1461    for (name, value) in headers {
1462        if is_non_forwardable_header(name.as_str(), headers) {
1463            continue;
1464        }
1465        let Ok(value) = value.to_str() else {
1466            continue;
1467        };
1468        if !value.is_empty() {
1469            body = body.replace(value, "[REDACTED]");
1470        }
1471    }
1472    body
1473}
1474
1475#[cfg(test)]
1476mod tests {
1477    use std::collections::BTreeMap;
1478    use std::error::Error;
1479    use std::io::{Read, Write};
1480    use std::sync::Arc;
1481    use std::sync::atomic::{AtomicUsize, Ordering};
1482    use std::thread::JoinHandle;
1483
1484    use serde_json::json;
1485    use switchyard_protocol::{completion_text, text_request};
1486    use wiremock::matchers::{method, path};
1487    use wiremock::{Mock, MockServer, ResponseTemplate};
1488
1489    use super::*;
1490    use crate::backend::HttpBackendConfig;
1491
1492    /// Decodes a wire body into a request, as a server endpoint does before calling the client.
1493    fn wire_request(
1494        body: Value,
1495        http_headers: Option<http::HeaderMap>,
1496        wire_format: WireFormat,
1497    ) -> switchyard_translation::Result<Request> {
1498        Ok(Request {
1499            llm_request: switchyard_translation::decode_request(wire_format, &body)?,
1500            raw_request: None,
1501            metadata: Some(Metadata {
1502                http_headers,
1503                ..Default::default()
1504            }),
1505        })
1506    }
1507
1508    fn assert_tool_call_name(agg: &switchyard_protocol::AggLlmResponse, name: &str) {
1509        let Some(switchyard_protocol::ContentBlock::ToolCall(call)) =
1510            agg.outputs[0].content.first()
1511        else {
1512            panic!("expected a tool call, got {:?}", agg.outputs[0].content);
1513        };
1514        assert_eq!(call.name, name);
1515    }
1516
1517    fn config(base_url: &str) -> HttpBackendConfig {
1518        HttpBackendConfig {
1519            base_url: base_url.to_string(),
1520            api_key: Some("secret".to_string()),
1521            forward_auth: false,
1522            extra_headers: BTreeMap::new(),
1523            extra_body: BTreeMap::new(),
1524            omit_body_fields: BTreeSet::new(),
1525            reasoning_effort: None,
1526            max_retries: 0,
1527            failure_cooldown: Duration::ZERO,
1528            timeout: None,
1529        }
1530    }
1531
1532    #[test]
1533    fn provider_endpoint_urls_preserve_query_and_fragment() {
1534        let invalid_url = "not a URL/";
1535        let backend = Backend::OpenAiResponses(config(invalid_url));
1536        assert!(openai_url(invalid_url, "/responses").is_err());
1537        assert_eq!(backend.url(), invalid_url);
1538        assert_eq!(
1539            AuxiliaryOperation::ResponsesCompact.url(&backend),
1540            invalid_url
1541        );
1542
1543        let anthropic = Backend::Anthropic(config(invalid_url));
1544        assert_eq!(anthropic.url(), invalid_url);
1545        assert_eq!(anthropic.count_tokens_url(), invalid_url);
1546
1547        for path in ["", "/v1/", "/v1/messages"] {
1548            for tail in [
1549                "",
1550                "?api-version=2026-09-01&value=%2F/",
1551                "#fragment?value=/",
1552            ] {
1553                let base_url = format!("https://example.com{path}{tail}");
1554                let backend = Backend::Anthropic(config(&base_url));
1555                assert_eq!(
1556                    backend.url(),
1557                    format!("https://example.com/v1/messages{tail}")
1558                );
1559                assert_eq!(
1560                    AuxiliaryOperation::AnthropicCountTokens.url(&backend),
1561                    format!("https://example.com/v1/messages/count_tokens{tail}")
1562                );
1563            }
1564        }
1565
1566        for path in ["/v1", "/v1/responses/", "/v1/chat/completions"] {
1567            for tail in [
1568                "",
1569                "?api-version=2026-09-01&value=%2F/",
1570                "#fragment?value=/",
1571            ] {
1572                let base_url = format!("https://example.com{path}{tail}");
1573                let responses = Backend::OpenAiResponses(config(&base_url));
1574                let chat = Backend::OpenAiChat(config(&base_url));
1575                for (actual, endpoint) in [
1576                    (responses.url(), "/responses"),
1577                    (chat.url(), "/chat/completions"),
1578                    (
1579                        AuxiliaryOperation::ResponsesCompact.url(&responses),
1580                        "/responses/compact",
1581                    ),
1582                    (
1583                        AuxiliaryOperation::ResponsesInputTokens.url(&responses),
1584                        "/responses/input_tokens",
1585                    ),
1586                ] {
1587                    assert_eq!(actual, format!("https://example.com/v1{endpoint}{tail}"));
1588                }
1589            }
1590        }
1591    }
1592
1593    fn config_with_retries(base_url: &str, max_retries: u32) -> HttpBackendConfig {
1594        HttpBackendConfig {
1595            max_retries,
1596            ..config(base_url)
1597        }
1598    }
1599
1600    fn forwarding_config(base_url: &str) -> HttpBackendConfig {
1601        HttpBackendConfig {
1602            api_key: None,
1603            forward_auth: true,
1604            ..config(base_url)
1605        }
1606    }
1607
1608    // A one-model config list: "gpt" served over OpenAI Chat at base_url.
1609    fn chat_map(base_url: &str) -> Vec<ModelConfig> {
1610        vec![ModelConfig::new(
1611            "gpt",
1612            Backend::OpenAiChat(config(base_url)),
1613            None,
1614        )]
1615    }
1616
1617    fn responses_map(base_url: &str) -> Vec<ModelConfig> {
1618        vec![ModelConfig::new(
1619            "gpt",
1620            Backend::OpenAiResponses(config(base_url)),
1621            None,
1622        )]
1623    }
1624
1625    fn chat_map_with_extra_body(
1626        base_url: &str,
1627        extra_body: BTreeMap<String, Value>,
1628    ) -> Vec<ModelConfig> {
1629        let mut backend = config(base_url);
1630        backend.extra_body = extra_body;
1631        vec![ModelConfig::new("gpt", Backend::OpenAiChat(backend), None)]
1632    }
1633
1634    fn chat_map_with_omit_body_fields(
1635        base_url: &str,
1636        omit_body_fields: BTreeSet<String>,
1637    ) -> Vec<ModelConfig> {
1638        let mut backend = config(base_url);
1639        backend.omit_body_fields = omit_body_fields;
1640        vec![ModelConfig::new("gpt", Backend::OpenAiChat(backend), None)]
1641    }
1642
1643    fn chat_map_with_effort(base_url: &str, effort: &str) -> Vec<ModelConfig> {
1644        let mut backend = config(base_url);
1645        backend.reasoning_effort = Some(effort.to_string());
1646        vec![ModelConfig::new("gpt", Backend::OpenAiChat(backend), None)]
1647    }
1648
1649    fn responses_map_with_effort(base_url: &str, effort: &str) -> Vec<ModelConfig> {
1650        let mut backend = config(base_url);
1651        backend.reasoning_effort = Some(effort.to_string());
1652        vec![ModelConfig::new(
1653            "gpt",
1654            Backend::OpenAiResponses(backend),
1655            None,
1656        )]
1657    }
1658
1659    fn anthropic_map(base_url: &str) -> Vec<ModelConfig> {
1660        vec![ModelConfig::new(
1661            "claude",
1662            Backend::Anthropic(config(base_url)),
1663            None,
1664        )]
1665    }
1666
1667    #[tokio::test]
1668    async fn model_properties_uses_configured_auth_and_backend_path()
1669    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
1670        for (base_path, props_path) in [
1671            ("/v1", "/props"),
1672            ("/v1/", "/props"),
1673            ("/v1/chat/completions", "/props"),
1674            ("/v1/responses/", "/props"),
1675            ("/prefix/v1", "/prefix/props"),
1676            ("/prefix/v1/chat/completions", "/prefix/props"),
1677            ("/prefix/v1/responses", "/prefix/props"),
1678            ("/prefix/", "/prefix/props"),
1679        ] {
1680            let server = MockServer::start().await;
1681            Mock::given(method("GET"))
1682                .and(path(props_path))
1683                .and(wiremock::matchers::header("authorization", "Bearer secret"))
1684                .respond_with(ResponseTemplate::new(200).set_body_json(json!({
1685                    "default_generation_settings": {"n_ctx": 65_536}
1686                })))
1687                .expect(1)
1688                .mount(&server)
1689                .await;
1690            let client =
1691                TranslatingLlmClient::new(&chat_map(&format!("{}{base_path}", server.uri())))?;
1692            let properties = client
1693                .get_model_properties(
1694                    &ModelId::from("gpt"),
1695                    WireFormat::OpenAiChat,
1696                    Duration::from_secs(1),
1697                )
1698                .await?;
1699            assert_eq!(properties["default_generation_settings"]["n_ctx"], 65_536);
1700        }
1701        Ok(())
1702    }
1703
1704    fn chat_map_with_retries(base_url: &str, max_retries: u32) -> Vec<ModelConfig> {
1705        vec![ModelConfig::new(
1706            "gpt",
1707            Backend::OpenAiChat(config_with_retries(base_url, max_retries)),
1708            None,
1709        )]
1710    }
1711
1712    fn chat_success_response() -> ResponseTemplate {
1713        ResponseTemplate::new(200).set_body_json(json!({
1714            "id": "chatcmpl-1",
1715            "model": "gpt",
1716            "choices": [{
1717                "index": 0,
1718                "message": {"role": "assistant", "content": "recovered"},
1719                "finish_reason": "stop"
1720            }],
1721            "usage": {}
1722        }))
1723    }
1724
1725    fn truncated_response_server(
1726        content_type: &str,
1727        body: &str,
1728    ) -> std::io::Result<(String, JoinHandle<std::io::Result<()>>)> {
1729        response_sequence_server(vec![format!(
1730            "HTTP/1.1 200 OK\r\nContent-Type: {content_type}\r\n\
1731             Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
1732            body.len() + 100
1733        )])
1734    }
1735
1736    fn response_sequence_server(
1737        responses: Vec<String>,
1738    ) -> std::io::Result<(String, JoinHandle<std::io::Result<()>>)> {
1739        let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
1740        let address = listener.local_addr()?;
1741        let handle = std::thread::spawn(move || {
1742            for response in responses {
1743                let (mut stream, _) = listener.accept()?;
1744                let mut request = [0_u8; 1024];
1745                if stream.read(&mut request)? == 0 {
1746                    return Err(std::io::Error::new(
1747                        std::io::ErrorKind::UnexpectedEof,
1748                        "client closed before sending a request",
1749                    ));
1750                }
1751                stream.write_all(response.as_bytes())?;
1752            }
1753            Ok(())
1754        });
1755        Ok((format!("http://{address}/v1"), handle))
1756    }
1757
1758    fn raw_chat_success_response() -> String {
1759        let body = r#"{"id":"chatcmpl-1","model":"gpt","choices":[{"index":0,"message":{"role":"assistant","content":"recovered"},"finish_reason":"stop"}],"usage":{}}"#;
1760        format!(
1761            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\
1762             Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
1763            body.len()
1764        )
1765    }
1766
1767    fn request_for(model: Option<&str>, stream: bool) -> Request {
1768        let mut llm_request = text_request(model.map(str::to_string), "hi");
1769        llm_request.stream = stream;
1770        Request {
1771            llm_request,
1772            raw_request: None,
1773            metadata: None,
1774        }
1775    }
1776
1777    fn request_with_headers(model: &str, headers: HeaderMap) -> Request {
1778        let mut request = request_for(Some(model), false);
1779        request.metadata = Some(Metadata {
1780            http_headers: Some(headers),
1781            ..Default::default()
1782        });
1783        request
1784    }
1785
1786    #[tokio::test]
1787    async fn transport_errors_drop_the_upstream_url() {
1788        let error = reqwest::Client::new()
1789            .post("http://127.0.0.1:1/v1?key=CANARY")
1790            .send()
1791            .await
1792            .expect_err("closed port");
1793
1794        assert!(!convert_reqwest_error(error).to_string().contains("CANARY"));
1795    }
1796
1797    #[tokio::test]
1798    async fn captured_request_build_failure_remains_a_configuration_error() {
1799        let client = TranslatingLlmClient::new(&chat_map("://invalid")).unwrap();
1800        let result =
1801            crate::with_payload_capture(client.call(request_for(Some("gpt"), false))).await;
1802        assert!(matches!(result, Err(LlmClientError::Configuration { .. })));
1803    }
1804
1805    #[test]
1806    fn nvidia_anthropic_tools_drop_unsupported_strict_field() {
1807        let backend = Backend::Anthropic(config("https://inference-api.nvidia.com"));
1808        assert!(nvidia_inference_api_backend(&backend));
1809        assert!(!nvidia_inference_api_backend(&Backend::Anthropic(config(
1810            "https://inference-api.nvidia.com.example.test"
1811        ))));
1812        let mut body = json!({"tools": [{"name": "a", "input_schema": {}, "strict": true}]});
1813        strip_anthropic_tool_strict(&mut body);
1814        assert!(body["tools"][0].get("strict").is_none());
1815    }
1816
1817    #[test]
1818    fn anthropic_prompt_caching_marks_final_message() {
1819        let caller_managed = json!({
1820            "cache_control": {"type": "ephemeral", "ttl": "1h"},
1821            "messages": [{"role": "user", "content": "hello"}]
1822        });
1823        let mut body = caller_managed.clone();
1824        enable_anthropic_prompt_caching(&mut body, 0);
1825        assert_eq!(body["cache_control"], caller_managed["cache_control"]);
1826        assert_eq!(
1827            body["messages"][0]["content"],
1828            json!([{
1829                "type": "text", "text": "hello",
1830                "cache_control": {"type": "ephemeral", "ttl": "1h"}
1831            }])
1832        );
1833
1834        let mut body = json!({
1835            "messages": [{"role": "user", "content": "hello"}]
1836        });
1837
1838        enable_anthropic_prompt_caching(&mut body, 0);
1839
1840        assert_eq!(
1841            body["messages"][0]["content"][0]["cache_control"],
1842            json!({"type": "ephemeral"})
1843        );
1844    }
1845
1846    // Counts the blocks upstream will see carrying a `cache_control` marker.
1847    fn cache_control_blocks(value: &Value) -> usize {
1848        count_cache_control_blocks(value)
1849    }
1850
1851    // A body whose four breakpoints are all spent elsewhere: the caller manages
1852    // its own caching and left the final block unmarked on purpose.
1853    fn body_at_the_cache_control_limit() -> Value {
1854        json!({
1855            "system": [
1856                {"type": "text", "text": "a", "cache_control": {"type": "ephemeral"}},
1857                {"type": "text", "text": "b", "cache_control": {"type": "ephemeral"}}
1858            ],
1859            "tools": [
1860                {"name": "t", "input_schema": {"type": "object"},
1861                 "cache_control": {"type": "ephemeral"}}
1862            ],
1863            "messages": [
1864                {"role": "user", "content": [
1865                    {"type": "text", "text": "old", "cache_control": {"type": "ephemeral"}}
1866                ]},
1867                {"role": "assistant", "content": [{"type": "text", "text": "ok"}]},
1868                {"role": "user", "content": [{"type": "text", "text": "new"}]}
1869            ]
1870        })
1871    }
1872
1873    #[test]
1874    fn anthropic_prompt_caching_abstains_at_the_cache_control_limit() {
1875        let mut body = body_at_the_cache_control_limit();
1876        assert_eq!(cache_control_blocks(&body), 4);
1877
1878        enable_anthropic_prompt_caching(&mut body, 0);
1879
1880        // Anthropic and Bedrock both reject a fifth marker with HTTP 400, which
1881        // would fail a request that was valid before it reached us.
1882        assert_eq!(cache_control_blocks(&body), 4);
1883        assert!(
1884            body["messages"][2]["content"][0]
1885                .get("cache_control")
1886                .is_none()
1887        );
1888    }
1889
1890    #[test]
1891    fn anthropic_prompt_caching_still_marks_one_below_the_limit() {
1892        let mut body = body_at_the_cache_control_limit();
1893        // Free one breakpoint, so there is room for ours.
1894        body["system"].as_array_mut().unwrap().pop();
1895        assert_eq!(cache_control_blocks(&body), 3);
1896
1897        enable_anthropic_prompt_caching(&mut body, 0);
1898
1899        assert_eq!(cache_control_blocks(&body), 4);
1900        assert_eq!(
1901            body["messages"][2]["content"][0]["cache_control"],
1902            json!({"type": "ephemeral"})
1903        );
1904    }
1905
1906    // A request that pins `format` in its metadata, so the client resolves that
1907    // wire format instead of the model's default backend.
1908    fn request_with_wire_format(model: &str, format: WireFormat) -> Request {
1909        let mut request = request_for(Some(model), false);
1910        request.metadata = Some(Metadata {
1911            session_id: None,
1912            agent_id: None,
1913            task_id: None,
1914            correlation_id: None,
1915            extra_metadata: None,
1916            http_headers: None,
1917            wire_format: Some(format),
1918            ..Default::default()
1919        });
1920        request
1921    }
1922
1923    #[tokio::test]
1924    async fn missing_model_errors()
1925    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
1926        let client = TranslatingLlmClient::new(&[])?;
1927        let Err(error) = client
1928            .call_rewrite_model(request_for(None, false), None)
1929            .await
1930        else {
1931            panic!("expected an error");
1932        };
1933        assert!(matches!(
1934            error,
1935            LlmClientError::InvalidRequest { message } if message == "no model given"
1936        ));
1937        Ok(())
1938    }
1939
1940    #[tokio::test]
1941    async fn unknown_model_errors()
1942    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
1943        let client = TranslatingLlmClient::new(&[])?;
1944        let Err(error) = client
1945            .call_rewrite_model(request_for(Some("gpt"), false), None)
1946            .await
1947        else {
1948            panic!("expected an error");
1949        };
1950        assert!(matches!(
1951            error,
1952            LlmClientError::Configuration { message }
1953                if message.contains("gpt")
1954        ));
1955        Ok(())
1956    }
1957
1958    #[tokio::test]
1959    async fn unknown_model_format_errors()
1960    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
1961        // "gpt" exists but only over OpenAI Chat; the request pins Anthropic.
1962        let client = TranslatingLlmClient::new(&chat_map("https://example.test/v1"))?;
1963        let Err(error) = client
1964            .call_rewrite_model(
1965                request_with_wire_format("gpt", WireFormat::AnthropicMessages),
1966                None,
1967            )
1968            .await
1969        else {
1970            panic!("expected an error");
1971        };
1972        assert!(matches!(
1973            error,
1974            LlmClientError::Configuration { message }
1975                if message.contains("gpt")
1976                    && message.contains(&WireFormat::AnthropicMessages.to_string())
1977        ));
1978        Ok(())
1979    }
1980
1981    #[test]
1982    fn backend_for_resolves_configured_format()
1983    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
1984        let client = TranslatingLlmClient::new(&chat_map("https://example.test/v1"))?;
1985        // "gpt" is served over OpenAI Chat only; other formats and models miss.
1986        assert!(
1987            client
1988                .backend_for(&ModelId::from("gpt"), WireFormat::OpenAiChat)
1989                .is_some()
1990        );
1991        assert!(
1992            client
1993                .backend_for(&ModelId::from("gpt"), WireFormat::AnthropicMessages)
1994                .is_none()
1995        );
1996        assert!(
1997            client
1998                .backend_for(&ModelId::from("missing"), WireFormat::OpenAiChat)
1999                .is_none()
2000        );
2001        Ok(())
2002    }
2003
2004    #[tokio::test]
2005    async fn target_name_arg_wins_over_request_model()
2006    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2007        let client = TranslatingLlmClient::new(&[])?;
2008        // Arg "b" is looked up (and reported), not the request's "a".
2009        let Err(error) = client
2010            .call_rewrite_model(request_for(Some("a"), false), Some(&ModelId::from("b")))
2011            .await
2012        else {
2013            panic!("expected an error");
2014        };
2015        assert!(matches!(
2016            error,
2017            LlmClientError::Configuration { message }
2018                if message.contains("\"b\"")
2019        ));
2020        Ok(())
2021    }
2022
2023    #[tokio::test]
2024    async fn buffered_openai_chat_round_trips()
2025    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2026        let server = MockServer::start().await;
2027        Mock::given(method("POST"))
2028            .and(path("/v1/chat/completions"))
2029            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2030                "id": "chatcmpl-1",
2031                "model": "gpt",
2032                "choices": [{
2033                    "index": 0,
2034                    "message": {"role": "assistant", "content": "Hi there"},
2035                    "finish_reason": "stop"
2036                }],
2037                "usage": {"prompt_tokens": 1, "completion_tokens": 2, "total_tokens": 3}
2038            })))
2039            .mount(&server)
2040            .await;
2041
2042        let client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
2043
2044        let response = client
2045            .call_rewrite_model(request_for(Some("gpt"), false), None)
2046            .await?;
2047        let agg = response.llm_response.into_agg().await?;
2048        assert_eq!(completion_text(&agg), "Hi there");
2049
2050        Ok(())
2051    }
2052
2053    #[tokio::test]
2054    async fn invalid_json_is_a_response_translation_error()
2055    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2056        let server = MockServer::start().await;
2057        let calls = Arc::new(AtomicUsize::new(0));
2058        let observed_calls = Arc::clone(&calls);
2059        Mock::given(method("POST"))
2060            .respond_with(move |_: &wiremock::Request| {
2061                observed_calls.fetch_add(1, Ordering::SeqCst);
2062                ResponseTemplate::new(200).set_body_raw("not json", "application/json")
2063            })
2064            .mount(&server)
2065            .await;
2066
2067        let client =
2068            TranslatingLlmClient::new(&chat_map_with_retries(&format!("{}/v1", server.uri()), 2))?;
2069        let Err(error) = client
2070            .call_rewrite_model(request_for(Some("gpt"), false), None)
2071            .await
2072        else {
2073            panic!("expected invalid JSON to fail");
2074        };
2075
2076        assert!(matches!(
2077            error,
2078            LlmClientError::ResponseTranslation(message)
2079                if message.contains("invalid upstream JSON")
2080        ));
2081        assert_eq!(calls.load(Ordering::SeqCst), 1);
2082        Ok(())
2083    }
2084
2085    #[tokio::test]
2086    async fn response_body_io_failure_is_a_transport_error()
2087    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2088        let (base_url, server) = truncated_response_server("application/json", "{}")?;
2089        let client = TranslatingLlmClient::new(&chat_map(&base_url))?;
2090        let result = client
2091            .call_rewrite_model(request_for(Some("gpt"), false), None)
2092            .await;
2093        server
2094            .join()
2095            .map_err(|_| std::io::Error::other("response server thread panicked"))??;
2096
2097        let Err(error) = result else {
2098            panic!("expected the truncated response body to fail");
2099        };
2100        let LlmClientError::Transport { source } = error else {
2101            panic!("expected a transport error");
2102        };
2103        let Some(source) = source.downcast_ref::<reqwest::Error>() else {
2104            panic!("expected the reqwest transport source");
2105        };
2106        assert!(source.is_decode());
2107        assert!(
2108            !std::error::Error::source(&source)
2109                .is_some_and(|source| source.is::<serde_json::Error>())
2110        );
2111        Ok(())
2112    }
2113
2114    #[tokio::test]
2115    async fn response_body_transport_failures_are_retried()
2116    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2117        let truncated_responses = [
2118            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\
2119             Content-Length: 102\r\nConnection: close\r\n\r\n{}",
2120            "HTTP/1.1 401 Unauthorized\r\nContent-Type: text/plain\r\n\
2121             Content-Length: 100\r\nConnection: close\r\n\r\nbad",
2122        ];
2123
2124        for truncated in truncated_responses {
2125            let (base_url, server) =
2126                response_sequence_server(vec![truncated.to_string(), raw_chat_success_response()])?;
2127            let client = TranslatingLlmClient::new(&chat_map_with_retries(&base_url, 1))?;
2128            let response = client
2129                .call_rewrite_model(request_for(Some("gpt"), false), None)
2130                .await?;
2131            server
2132                .join()
2133                .map_err(|_| std::io::Error::other("response server thread panicked"))??;
2134
2135            assert_eq!(
2136                completion_text(&response.llm_response.into_agg().await?),
2137                "recovered"
2138            );
2139        }
2140        Ok(())
2141    }
2142
2143    #[tokio::test]
2144    async fn pre_first_event_transport_failure_uses_retry_budget()
2145    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2146        let truncated = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\
2147                         Content-Length: 100\r\nConnection: close\r\n\r\n";
2148        let body = "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"recovered\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n";
2149        let success = format!(
2150            "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\
2151             Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
2152            body.len()
2153        );
2154
2155        for second in [success, truncated.to_string()] {
2156            let is_exhausted = second == truncated;
2157            let (base_url, server) = response_sequence_server(vec![truncated.to_string(), second])?;
2158            let client = TranslatingLlmClient::new(&chat_map_with_retries(&base_url, 1))?;
2159            let result = client
2160                .call_rewrite_model(request_for(Some("gpt"), true), None)
2161                .await;
2162            if is_exhausted {
2163                assert!(matches!(result, Err(LlmClientError::Transport { .. })));
2164            } else {
2165                assert_eq!(
2166                    completion_text(&result?.llm_response.into_agg().await?),
2167                    "recovered"
2168                );
2169            }
2170            server
2171                .join()
2172                .map_err(|_| std::io::Error::other("response server thread panicked"))??;
2173        }
2174        Ok(())
2175    }
2176
2177    #[tokio::test]
2178    async fn streaming_body_io_failure_preserves_transport_error()
2179    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2180        let body = "data: {\"choices\":[{\"delta\":{\"content\":\"partial\"}}]}\n\n";
2181        let (base_url, server) = truncated_response_server("text/event-stream", body)?;
2182        let client = TranslatingLlmClient::new(&chat_map_with_retries(&base_url, 2))?;
2183        let response = client
2184            .call_rewrite_model(request_for(Some("gpt"), true), None)
2185            .await?;
2186        let result = response.llm_response.into_agg().await;
2187        server
2188            .join()
2189            .map_err(|_| std::io::Error::other("response server thread panicked"))??;
2190
2191        let Err(error) = result else {
2192            panic!("expected the truncated stream body to fail");
2193        };
2194
2195        assert!(matches!(error, LlmClientError::Transport { .. }));
2196        Ok(())
2197    }
2198
2199    #[tokio::test]
2200    async fn rewrites_model_to_resolved_upstream_id()
2201    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2202        // Inbound body says "switchyard"; the upstream must receive "gpt".
2203        let server = MockServer::start().await;
2204        Mock::given(method("POST"))
2205            .and(path("/v1/chat/completions"))
2206            .and(wiremock::matchers::body_partial_json(json!({"model": "gpt"})))
2207            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2208                "id": "1", "model": "gpt",
2209                "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
2210                "usage": {}
2211            })))
2212            .mount(&server)
2213            .await;
2214
2215        let client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
2216        // Inbound model differs from the map key / resolved model.
2217        client
2218            .call_rewrite_model(
2219                request_for(Some("switchyard"), false),
2220                Some(&ModelId::from("gpt")),
2221            )
2222            .await?;
2223        // The body_partial_json matcher asserts the upstream saw model "gpt".
2224        Ok(())
2225    }
2226
2227    /// A configured reasoning effort replaces the caller's value on both OpenAI wire formats,
2228    /// which `extra_body` (defaults only) cannot do.
2229    #[tokio::test]
2230    async fn reasoning_effort_override_replaces_the_callers_effort()
2231    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2232        let server = MockServer::start().await;
2233        Mock::given(method("POST"))
2234            .and(path("/v1/chat/completions"))
2235            .and(wiremock::matchers::body_partial_json(json!({
2236                "model": "gpt",
2237                "reasoning_effort": "max"
2238            })))
2239            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2240                "id": "1",
2241                "model": "gpt",
2242                "choices": [{
2243                    "index": 0,
2244                    "message": {"role": "assistant", "content": "ok"},
2245                    "finish_reason": "stop"
2246                }],
2247                "usage": {}
2248            })))
2249            .mount(&server)
2250            .await;
2251        let client = TranslatingLlmClient::new(&chat_map_with_effort(
2252            &format!("{}/v1", server.uri()),
2253            "max",
2254        ))?;
2255        client
2256            .call_rewrite_model(
2257                wire_request(
2258                    json!({
2259                        "model": "client-facing",
2260                        "messages": [{"role": "user", "content": "hi"}],
2261                        "reasoning_effort": "high"
2262                    }),
2263                    None,
2264                    WireFormat::OpenAiChat,
2265                )?,
2266                Some(&ModelId::from("gpt")),
2267            )
2268            .await?;
2269
2270        let server = MockServer::start().await;
2271        Mock::given(method("POST"))
2272            .and(path("/v1/responses"))
2273            .and(wiremock::matchers::body_partial_json(json!({
2274                "model": "gpt",
2275                "reasoning": {"effort": "max", "summary": "auto"}
2276            })))
2277            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2278                "id": "resp_1",
2279                "object": "response",
2280                "model": "gpt",
2281                "status": "completed",
2282                "output": [{
2283                    "type": "message",
2284                    "id": "msg_1",
2285                    "role": "assistant",
2286                    "status": "completed",
2287                    "content": [{"type": "output_text", "text": "ok"}]
2288                }],
2289                "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2}
2290            })))
2291            .mount(&server)
2292            .await;
2293        let client = TranslatingLlmClient::new(&responses_map_with_effort(
2294            &format!("{}/v1", server.uri()),
2295            "max",
2296        ))?;
2297        client
2298            .call_rewrite_model(
2299                wire_request(
2300                    json!({
2301                        "model": "client-facing",
2302                        "input": [{"role": "user", "content": "hi"}],
2303                        "reasoning": {"effort": "high", "summary": "auto"}
2304                    }),
2305                    None,
2306                    WireFormat::OpenAiResponses,
2307                )?,
2308                Some(&ModelId::from("gpt")),
2309            )
2310            .await?;
2311        Ok(())
2312    }
2313
2314    // Covers both a translated request and an Anthropic caller's body sent as is.
2315    #[tokio::test]
2316    async fn anthropic_requests_drop_tool_strict_false()
2317    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2318        let server = MockServer::start().await;
2319        Mock::given(method("POST"))
2320            .and(path("/v1/messages"))
2321            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2322                "id": "msg_1",
2323                "type": "message",
2324                "role": "assistant",
2325                "model": "claude",
2326                "content": [{"type": "text", "text": "ok"}],
2327                "stop_reason": "end_turn",
2328                "usage": {"input_tokens": 1, "output_tokens": 1}
2329            })))
2330            .expect(2)
2331            .mount(&server)
2332            .await;
2333        let client = TranslatingLlmClient::new(&[ModelConfig::new(
2334            "claude",
2335            Backend::Anthropic(config(&server.uri())),
2336            None,
2337        )])?;
2338        let schema = json!({"type": "object"});
2339        let requests = [
2340            (
2341                WireFormat::OpenAiChat,
2342                json!({
2343                    "model": "client-facing",
2344                    "messages": [{"role": "user", "content": "hi"}],
2345                    "tools": [
2346                        {"type": "function", "function": {"name": "loose", "parameters": schema, "strict": false}},
2347                        {"type": "function", "function": {"name": "exact", "parameters": schema, "strict": true}}
2348                    ]
2349                }),
2350            ),
2351            (
2352                WireFormat::AnthropicMessages,
2353                json!({
2354                    "model": "client-facing",
2355                    "max_tokens": 8,
2356                    "messages": [{"role": "user", "content": "hi"}],
2357                    "tools": [
2358                        {"name": "loose", "input_schema": schema, "strict": false},
2359                        {"name": "exact", "input_schema": schema, "strict": true}
2360                    ]
2361                }),
2362            ),
2363        ];
2364        for (format, request) in requests {
2365            client
2366                .call_rewrite_model(
2367                    wire_request(request, None, format)?,
2368                    Some(&ModelId::from("claude")),
2369                )
2370                .await?;
2371        }
2372        for received in server.received_requests().await.unwrap_or_default() {
2373            let body: Value = serde_json::from_slice(&received.body)?;
2374            assert!(body["tools"][0].get("strict").is_none(), "{body}");
2375            assert_eq!(body["tools"][1]["strict"], true, "{body}");
2376        }
2377        Ok(())
2378    }
2379
2380    #[tokio::test]
2381    async fn template_rejection_retries_once_without_changing_other_fields()
2382    -> std::result::Result<(), Box<dyn Error + Sync + Send>> {
2383        for (message, reject_retry, omit) in [
2384            (
2385                "Unrecognized request argument supplied: chat_template_kwargs",
2386                false,
2387                false,
2388            ),
2389            (
2390                "Unrecognized request argument supplied: chat_template_kwargs",
2391                true,
2392                false,
2393            ),
2394            (
2395                "Invalid temperature for chat_template_kwargs request",
2396                false,
2397                false,
2398            ),
2399            (
2400                "Unrecognized request argument supplied: chat_template_kwargs",
2401                false,
2402                true,
2403            ),
2404        ] {
2405            let server = MockServer::start().await;
2406            Mock::given(method("POST"))
2407                .respond_with(move |request: &wiremock::Request| {
2408                    let body: Value = serde_json::from_slice(&request.body).expect("request JSON");
2409                    if body.get("chat_template_kwargs").is_some() || reject_retry {
2410                        ResponseTemplate::new(400).set_body_json(json!({"error": {"message": message}}))
2411                    } else {
2412                        ResponseTemplate::new(200).set_body_json(json!({
2413                            "id": "1", "model": "gpt", "choices": [{"index": 0,
2414                                "message": {"role": "assistant", "content": "yes"}, "finish_reason": "stop"}],
2415                            "usage": {}
2416                        }))
2417                    }
2418                }).mount(&server).await;
2419            let fields = if omit {
2420                BTreeSet::from(["chat_template_kwargs".into()])
2421            } else {
2422                BTreeSet::new()
2423            };
2424            let client = TranslatingLlmClient::new(&chat_map_with_omit_body_fields(
2425                &format!("{}/v1", server.uri()),
2426                fields,
2427            ))?;
2428            let raw = json!({"model": "gpt", "messages": [{"role": "user", "content": "judge"}],
2429                "reasoning_effort": "none", "logprobs": true, "top_logprobs": 8,
2430                "chat_template_kwargs": {"enable_thinking": false}});
2431            let result = client
2432                .call_rewrite_model(
2433                    wire_request(raw.clone(), None, WireFormat::OpenAiChat)?,
2434                    Some(&ModelId::from("gpt")),
2435                )
2436                .await;
2437            let rejects_field = message.starts_with("Unrecognized");
2438            assert_eq!(result.is_ok(), omit || (rejects_field && !reject_retry));
2439            let calls = server.received_requests().await.ok_or("missing requests")?;
2440            assert_eq!(calls.len(), if !omit && rejects_field { 2 } else { 1 });
2441            for (index, call) in calls.iter().enumerate() {
2442                let mut expected = raw.clone();
2443                if omit || index > 0 {
2444                    expected
2445                        .as_object_mut()
2446                        .unwrap()
2447                        .remove("chat_template_kwargs");
2448                }
2449                assert_eq!(serde_json::from_slice::<Value>(&call.body)?, expected);
2450            }
2451        }
2452        Ok(())
2453    }
2454
2455    #[tokio::test]
2456    async fn template_compatibility_preserves_the_transient_retry_budget()
2457    -> std::result::Result<(), Box<dyn Error + Sync + Send>> {
2458        let server = MockServer::start().await;
2459        let count = Arc::new(AtomicUsize::new(0));
2460        let observed = Arc::clone(&count);
2461        Mock::given(method("POST"))
2462            .respond_with(move |request: &wiremock::Request| {
2463                let body: Value = serde_json::from_slice(&request.body).expect("request JSON");
2464                match observed.fetch_add(1, Ordering::SeqCst) {
2465                    0 => {
2466                        assert!(body.get("chat_template_kwargs").is_some());
2467                        ResponseTemplate::new(422).set_body_json(json!({"error": {
2468                            "code": "unsupported_parameter", "param": "chat_template_kwargs"
2469                        }}))
2470                    }
2471                    1 => {
2472                        assert!(body.get("chat_template_kwargs").is_none());
2473                        ResponseTemplate::new(503).insert_header("retry-after", "0")
2474                    }
2475                    _ => ResponseTemplate::new(200).set_body_json(json!({
2476                        "id": "1", "model": "gpt", "choices": [{"index": 0,
2477                            "message": {"role": "assistant", "content": "yes"}, "finish_reason": "stop"}],
2478                        "usage": {}
2479                    })),
2480                }
2481            }).mount(&server).await;
2482        let client =
2483            TranslatingLlmClient::new(&chat_map_with_retries(&format!("{}/v1", server.uri()), 1))?;
2484        client
2485            .call_rewrite_model(
2486                wire_request(
2487                    json!({"model": "gpt", "messages": [{"role": "user", "content": "judge"}],
2488                "chat_template_kwargs": {"enable_thinking": false}}),
2489                    None,
2490                    WireFormat::OpenAiChat,
2491                )?,
2492                Some(&ModelId::from("gpt")),
2493            )
2494            .await?;
2495        assert_eq!(count.load(Ordering::SeqCst), 3);
2496        Ok(())
2497    }
2498
2499    #[tokio::test]
2500    async fn preserved_codex_string_input_is_normalized_at_the_client_boundary()
2501    -> std::result::Result<(), Box<dyn Error + Sync + Send>> {
2502        for root in ["/backend-api/codex", "/v1"] {
2503            for input in [
2504                json!("hello"),
2505                json!([{"role": "user", "content": "hello"}]),
2506            ] {
2507                let server = MockServer::start().await;
2508                Mock::given(method("POST"))
2509                    .and(path(format!("{root}/responses")))
2510                    .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2511                        "id": "resp_1", "object": "response", "model": "gpt", "status": "completed", "output": [], "usage": {}
2512                    }))).expect(1).mount(&server).await;
2513                let client =
2514                    TranslatingLlmClient::new(&responses_map(&format!("{}{root}", server.uri())))?;
2515                let raw = json!({"model": "client-name", "input": input,
2516                    "instructions": "Be brief.", "store": false, "metadata": {"task": "judge"},
2517                    "custom_field": {"keep": true}});
2518                client
2519                    .call_rewrite_model(
2520                        wire_request(raw.clone(), None, WireFormat::OpenAiResponses)?,
2521                        Some(&ModelId::from("gpt")),
2522                    )
2523                    .await?;
2524                let mut expected = raw;
2525                expected["model"] = json!("gpt");
2526                if root == "/backend-api/codex" && input.is_string() {
2527                    expected["input"] =
2528                        json!([{"type": "message", "role": "user", "content": input}]);
2529                }
2530                let calls = server.received_requests().await.ok_or("missing requests")?;
2531                assert_eq!(serde_json::from_slice::<Value>(&calls[0].body)?, expected);
2532            }
2533        }
2534        Ok(())
2535    }
2536
2537    #[tokio::test]
2538    async fn token_counting_does_not_send_the_effort_override()
2539    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2540        let server = MockServer::start().await;
2541        Mock::given(method("POST"))
2542            .and(path("/v1/messages/count_tokens"))
2543            .respond_with(ResponseTemplate::new(200).set_body_json(json!({"input_tokens": 3})))
2544            .expect(1)
2545            .mount(&server)
2546            .await;
2547        let mut backend = config(&server.uri());
2548        backend.reasoning_effort = Some("max".to_string());
2549        let client = TranslatingLlmClient::new(&[ModelConfig::new(
2550            "claude",
2551            Backend::Anthropic(backend),
2552            None,
2553        )])?;
2554        let llm_request = switchyard_translation::decode_request(
2555            WireFormat::AnthropicMessages,
2556            &json!({"model": "claude", "messages": [{"role": "user", "content": "hi"}]}),
2557        )?;
2558        let request = Request {
2559            llm_request,
2560            raw_request: None,
2561            metadata: None,
2562        };
2563        client
2564            .call_auxiliary(
2565                &ModelId::from("claude"),
2566                request,
2567                AuxiliaryOperation::AnthropicCountTokens,
2568            )
2569            .await?;
2570        let received = server.received_requests().await.unwrap_or_default();
2571        let body: Value = serde_json::from_slice(&received[0].body)?;
2572        assert!(body.get("output_config").is_none(), "{body}");
2573        Ok(())
2574    }
2575
2576    #[tokio::test]
2577    async fn reasoning_effort_override_sets_anthropic_output_config_effort()
2578    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2579        let server = MockServer::start().await;
2580        let format = json!({"type": "json_schema", "schema": {"type": "object"}});
2581        Mock::given(method("POST"))
2582            .and(path("/v1/messages"))
2583            .and(wiremock::matchers::body_partial_json(json!({
2584                "model": "claude",
2585                "output_config": {"effort": "max", "format": format}
2586            })))
2587            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2588                "id": "msg_1",
2589                "type": "message",
2590                "role": "assistant",
2591                "model": "claude",
2592                "content": [{"type": "text", "text": "ok"}],
2593                "stop_reason": "end_turn",
2594                "usage": {"input_tokens": 1, "output_tokens": 1}
2595            })))
2596            .expect(1)
2597            .mount(&server)
2598            .await;
2599        let mut backend = config(&server.uri());
2600        backend.reasoning_effort = Some("max".to_string());
2601        let client = TranslatingLlmClient::new(&[ModelConfig::new(
2602            "claude",
2603            Backend::Anthropic(backend),
2604            None,
2605        )])?;
2606        client
2607            .call_rewrite_model(
2608                wire_request(
2609                    json!({
2610                        "model": "client-facing",
2611                        "max_tokens": 7,
2612                        "messages": [{"role": "user", "content": "hi"}],
2613                        "output_config": {"effort": "high", "format": format}
2614                    }),
2615                    None,
2616                    WireFormat::AnthropicMessages,
2617                )?,
2618                Some(&ModelId::from("claude")),
2619            )
2620            .await?;
2621        Ok(())
2622    }
2623
2624    #[tokio::test]
2625    async fn extra_body_adds_defaults_without_overriding_the_request()
2626    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2627        let server = MockServer::start().await;
2628        Mock::given(method("POST"))
2629            .and(path("/v1/chat/completions"))
2630            .and(wiremock::matchers::body_partial_json(json!({
2631                "model": "gpt",
2632                "max_tokens": 7,
2633                "service_tier": "priority"
2634            })))
2635            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2636                "id": "1",
2637                "model": "gpt",
2638                "choices": [{
2639                    "index": 0,
2640                    "message": {"role": "assistant", "content": "ok"},
2641                    "finish_reason": "stop"
2642                }],
2643                "usage": {}
2644            })))
2645            .mount(&server)
2646            .await;
2647
2648        let extra_body = BTreeMap::from([
2649            ("max_tokens".to_string(), json!(999)),
2650            ("service_tier".to_string(), json!("priority")),
2651        ]);
2652        let client = TranslatingLlmClient::new(&chat_map_with_extra_body(
2653            &format!("{}/v1", server.uri()),
2654            extra_body,
2655        ))?;
2656        let raw = json!({
2657            "model": "client-facing",
2658            "messages": [{"role": "user", "content": "hi"}],
2659            "max_tokens": 7
2660        });
2661
2662        client
2663            .call_rewrite_model(
2664                wire_request(raw, None, WireFormat::OpenAiChat)?,
2665                Some(&ModelId::from("gpt")),
2666            )
2667            .await?;
2668        Ok(())
2669    }
2670
2671    #[tokio::test]
2672    async fn omit_body_fields_strips_a_field_extra_body_cannot_override()
2673    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2674        let server = MockServer::start().await;
2675        Mock::given(method("POST"))
2676            .and(path("/v1/chat/completions"))
2677            .and(|request: &wiremock::Request| {
2678                let body: Value = serde_json::from_slice(&request.body).unwrap_or(Value::Null);
2679                body.get("max_tokens").is_none()
2680            })
2681            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2682                "id": "1",
2683                "model": "gpt",
2684                "choices": [{
2685                    "index": 0,
2686                    "message": {"role": "assistant", "content": "ok"},
2687                    "finish_reason": "stop"
2688                }],
2689                "usage": {}
2690            })))
2691            .mount(&server)
2692            .await;
2693
2694        let client = TranslatingLlmClient::new(&chat_map_with_omit_body_fields(
2695            &format!("{}/v1", server.uri()),
2696            BTreeSet::from(["max_tokens".to_string()]),
2697        ))?;
2698        let raw = json!({
2699            "model": "client-facing",
2700            "messages": [{"role": "user", "content": "hi"}],
2701            "max_tokens": 7
2702        });
2703
2704        client
2705            .call_rewrite_model(
2706                wire_request(raw, None, WireFormat::OpenAiChat)?,
2707                Some(&ModelId::from("gpt")),
2708            )
2709            .await?;
2710        Ok(())
2711    }
2712
2713    // A weak OpenAI-format tier emits thinking blocks with no signature. Replaying
2714    // them to Anthropic is rejected (Bedrock reports it as a SigV4 mismatch), so
2715    // the Anthropic leg must drop them while keeping signed ones.
2716    #[tokio::test]
2717    async fn anthropic_requests_drop_unsigned_thinking_blocks()
2718    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2719        let server = MockServer::start().await;
2720        Mock::given(method("POST"))
2721            .and(path("/v1/messages"))
2722            .and(|request: &wiremock::Request| {
2723                let body: Value = serde_json::from_slice(&request.body).unwrap_or(Value::Null);
2724                let messages = body.get("messages").and_then(Value::as_array).cloned();
2725                let Some(messages) = messages else {
2726                    return false;
2727                };
2728                // The unsigned block is gone, the signed one survives, and the
2729                // message whose only block was unsigned is not left with an empty
2730                // content array.
2731                let blocks: Vec<&Value> = messages
2732                    .iter()
2733                    .filter_map(|message| message.get("content"))
2734                    .filter_map(Value::as_array)
2735                    .flatten()
2736                    .collect();
2737                let thinking: Vec<&&Value> = blocks
2738                    .iter()
2739                    .filter(|block| block.get("type").and_then(Value::as_str) == Some("thinking"))
2740                    .collect();
2741                thinking.len() == 1
2742                    && thinking[0].get("signature").and_then(Value::as_str) == Some("sig-abc")
2743                    && messages
2744                        .iter()
2745                        .all(|message| message.get("content") != Some(&json!([])))
2746            })
2747            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2748                "id": "msg_1",
2749                "type": "message",
2750                "role": "assistant",
2751                "model": "claude",
2752                "content": [{"type": "text", "text": "ok"}],
2753                "stop_reason": "end_turn",
2754                "usage": {"input_tokens": 1, "output_tokens": 1}
2755            })))
2756            .mount(&server)
2757            .await;
2758
2759        let client = TranslatingLlmClient::new(&anthropic_map(&server.uri()))?;
2760        let raw = json!({
2761            "model": "client-facing",
2762            "max_tokens": 7,
2763            "messages": [
2764                {"role": "user", "content": "fix the build"},
2765                {"role": "assistant", "content": [
2766                    {"type": "thinking", "thinking": "weak tier reasoning", "signature": ""}
2767                ]},
2768                {"role": "assistant", "content": [
2769                    {"type": "thinking", "thinking": "signed reasoning", "signature": "sig-abc"},
2770                    {"type": "text", "text": "here goes"}
2771                ]},
2772                {"role": "user", "content": "continue"}
2773            ]
2774        });
2775
2776        client
2777            .call_rewrite_model(
2778                wire_request(raw, None, WireFormat::AnthropicMessages)?,
2779                Some(&ModelId::from("claude")),
2780            )
2781            .await?;
2782        Ok(())
2783    }
2784
2785    #[tokio::test]
2786    async fn responses_reasoning_policy_preserves_replay_history()
2787    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2788        use crate::ResponsesReasoningPolicy::{Auto, Drop, PreserveEncrypted, PreservePlaintext};
2789        let summary = json!([{"type": "summary_text", "text": "Check the parser."}]);
2790        let history = json!([
2791            {"type": "message", "role": "user", "content": "continue"},
2792            {"type": "reasoning", "encrypted_content": "opaque", "content": [{"type": "reasoning_text", "text": "private"}]},
2793            {"type": "reasoning", "id": "rs_stored", "status": "completed", "summary": []},
2794            // GLM's plaintext forms, as Codex replays them.
2795            {"type": "reasoning", "id": "rs_glm", "summary": summary, "encrypted_content": null},
2796            {"type": "reasoning", "content": [{"type": "reasoning_text", "text": "Run the tests."}], "encrypted_content": ""},
2797            {"type": "reasoning"},
2798            {"type": "function_call", "call_id": "call_1", "name": "shell", "arguments": "{}"},
2799            {"type": "function_call_output", "call_id": "call_1", "output": "ok"}
2800        ]);
2801        // An explicit policy wins over the target. `Auto` follows the target.
2802        let cases = [
2803            (Auto, "openai/gpt-5", PreserveEncrypted),
2804            (Auto, "nvidia/zai-org/glm-5.3-flash", PreservePlaintext),
2805            (
2806                PreserveEncrypted,
2807                "nvidia/zai-org/glm-5.3-flash",
2808                PreserveEncrypted,
2809            ),
2810            (Drop, "openai/gpt-5", Drop),
2811        ];
2812        for store in [Some(true), Some(false), None] {
2813            for (policy, model, behavior) in cases {
2814                for has_input_override in [false, true] {
2815                    let server = MockServer::start().await;
2816                    Mock::given(method("POST"))
2817                        .and(path("/v1/responses"))
2818                        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2819                            "id": "resp_1", "object": "response", "model": "gpt",
2820                            "status": "completed", "output": [],
2821                            "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2}
2822                        })))
2823                        .expect(1)
2824                        .mount(&server)
2825                        .await;
2826                    let mut backend = config(&format!("{}/v1", server.uri()));
2827                    if has_input_override {
2828                        backend.omit_body_fields.insert("input".to_string());
2829                        backend
2830                            .extra_body
2831                            .insert("input".to_string(), history.clone());
2832                    }
2833                    let client = TranslatingLlmClient::new(&[ModelConfig::new(
2834                        model,
2835                        Backend::OpenAiResponses(backend),
2836                        None,
2837                    )
2838                    .with_responses_reasoning(policy)])?;
2839                    let mut request = json!({"model": "switchyard", "input": history});
2840                    if let Some(store) = store {
2841                        request["store"] = json!(store);
2842                    }
2843                    client
2844                        .call_rewrite_model(
2845                            wire_request(request, None, WireFormat::OpenAiResponses)?,
2846                            Some(&ModelId::from(model)),
2847                        )
2848                        .await?;
2849                    let requests = server.received_requests().await.ok_or("missing requests")?;
2850                    let body: Value = serde_json::from_slice(&requests[0].body)?;
2851                    let stored = store != Some(false);
2852                    let mut expected = vec![history[0].clone()];
2853                    match behavior {
2854                        // OpenAI reads its own payload and stored IDs, but rejects plaintext.
2855                        PreserveEncrypted => {
2856                            let indexes: &[usize] = if stored { &[1, 2, 3] } else { &[1] };
2857                            for &index in indexes {
2858                                let mut item = history[index].clone();
2859                                item["content"] = json!([]);
2860                                expected.push(item);
2861                            }
2862                        }
2863                        // Other targets keep plaintext and lose payloads of unknown origin.
2864                        PreservePlaintext => {
2865                            let mut item = history[1].clone();
2866                            item.as_object_mut()
2867                                .ok_or("object")?
2868                                .remove("encrypted_content");
2869                            expected.push(item);
2870                            if stored {
2871                                expected.push(history[2].clone());
2872                            }
2873                            expected.extend([history[3].clone(), history[4].clone()]);
2874                        }
2875                        _ => {}
2876                    }
2877                    expected.extend([history[6].clone(), history[7].clone()]);
2878                    assert_eq!(
2879                        body["input"],
2880                        json!(expected),
2881                        "store={store:?}, policy={policy:?}, model={model}, replace={has_input_override}"
2882                    );
2883                }
2884            }
2885        }
2886
2887        Ok(())
2888    }
2889
2890    #[tokio::test]
2891    async fn nvidia_anthropic_requests_strip_strict_from_extra_body()
2892    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2893        let server = MockServer::start().await;
2894        Mock::given(method("POST"))
2895            .and(path("/v1/messages"))
2896            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2897                "id": "msg_1",
2898                "type": "message",
2899                "role": "assistant",
2900                "model": "claude",
2901                "content": [{"type": "text", "text": "ok"}],
2902                "stop_reason": "end_turn",
2903                "usage": {"input_tokens": 1, "output_tokens": 1}
2904            })))
2905            .expect(1)
2906            .mount(&server)
2907            .await;
2908
2909        let mut backend = config(&format!(
2910            "http://inference-api.nvidia.com:{}",
2911            server.address().port()
2912        ));
2913        backend.extra_body.insert(
2914            "tools".into(),
2915            json!([{
2916                "name": "lookup",
2917                "input_schema": {"type": "object", "properties": {}},
2918                "strict": true
2919            }]),
2920        );
2921        let mut client = TranslatingLlmClient::new(&[ModelConfig::new(
2922            "claude",
2923            Backend::Anthropic(backend),
2924            None,
2925        )])?;
2926        client.client = reqwest::Client::builder()
2927            .no_proxy()
2928            .resolve("inference-api.nvidia.com", *server.address())
2929            .build()?;
2930        client
2931            .call_rewrite_model(
2932                wire_request(
2933                    json!({
2934                        "model": "claude",
2935                        "max_tokens": 7,
2936                        "messages": [{"role": "user", "content": "hi"}]
2937                    }),
2938                    None,
2939                    WireFormat::AnthropicMessages,
2940                )?,
2941                Some(&ModelId::from("claude")),
2942            )
2943            .await?;
2944
2945        let requests = server.received_requests().await.unwrap();
2946        let body: Value = serde_json::from_slice(&requests[0].body)?;
2947        assert_eq!(body["tools"][0]["name"], "lookup");
2948        assert!(body["tools"][0].get("strict").is_none());
2949        Ok(())
2950    }
2951
2952    // A router can serve earlier turns from an OpenAI target and later turns from
2953    // an Anthropic one, so the Anthropic leg must drop OpenAI-only fields the
2954    // caller keeps sending or the upstream rejects the whole request.
2955    #[tokio::test]
2956    async fn anthropic_requests_drop_openai_only_fields()
2957    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
2958        let server = MockServer::start().await;
2959        Mock::given(method("POST"))
2960            .and(path("/v1/messages"))
2961            .and(|request: &wiremock::Request| {
2962                let body: Value = serde_json::from_slice(&request.body).unwrap_or(Value::Null);
2963                body.get("context_management").is_none() && body.get("reasoning_effort").is_none()
2964            })
2965            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
2966                "id": "msg_1",
2967                "type": "message",
2968                "role": "assistant",
2969                "model": "claude",
2970                "content": [{"type": "text", "text": "ok"}],
2971                "stop_reason": "end_turn",
2972                "usage": {"input_tokens": 1, "output_tokens": 1}
2973            })))
2974            .mount(&server)
2975            .await;
2976
2977        let client = TranslatingLlmClient::new(&anthropic_map(&server.uri()))?;
2978        let raw = json!({
2979            "model": "client-facing",
2980            "messages": [{"role": "user", "content": "hi"}],
2981            "max_tokens": 7,
2982            "reasoning_effort": "high",
2983            "context_management": {
2984                "edits": [{"type": "clear_thinking_20251015"}]
2985            }
2986        });
2987
2988        client
2989            .call_rewrite_model(
2990                wire_request(raw, None, WireFormat::AnthropicMessages)?,
2991                Some(&ModelId::from("claude")),
2992            )
2993            .await?;
2994        Ok(())
2995    }
2996
2997    #[tokio::test]
2998    async fn streaming_openai_chat_aggregates()
2999    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3000        let server = MockServer::start().await;
3001        let sse = "data: {\"choices\":[{\"delta\":{\"content\":\"Hello\"}}]}\n\n\
3002             data: {\"choices\":[{\"delta\":{\"content\":\" world\"}}]}\n\n\
3003             data: {\"choices\":[],\"usage\":{\"prompt_tokens\":1,\"completion_tokens\":2,\"total_tokens\":3}}\n\n\
3004             data: [DONE]\n\n";
3005        Mock::given(method("POST"))
3006            .and(path("/v1/chat/completions"))
3007            .and(wiremock::matchers::body_partial_json(json!({
3008                "stream": true,
3009                "stream_options": {"include_usage": true}
3010            })))
3011            .respond_with(ResponseTemplate::new(200).set_body_raw(sse, "text/event-stream"))
3012            .mount(&server)
3013            .await;
3014
3015        let client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
3016
3017        let response = client
3018            .call_rewrite_model(request_for(Some("gpt"), true), None)
3019            .await?;
3020        assert!(matches!(response.llm_response, LlmResponse::Stream(_)));
3021        let agg = response.llm_response.into_agg().await?;
3022        assert_eq!(completion_text(&agg), "Hello world");
3023        assert_eq!(agg.usage.input_tokens, Some(1));
3024        assert_eq!(agg.usage.output_tokens, Some(2));
3025        assert_eq!(agg.usage.total_tokens, Some(3));
3026        Ok(())
3027    }
3028
3029    #[tokio::test]
3030    async fn streaming_openai_chat_preserves_usage_opt_out()
3031    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3032        let server = MockServer::start().await;
3033        Mock::given(method("POST"))
3034            .and(path("/v1/chat/completions"))
3035            .and(wiremock::matchers::body_partial_json(json!({
3036                "stream": true,
3037                "stream_options": {"include_usage": false}
3038            })))
3039            .respond_with(
3040                ResponseTemplate::new(200).set_body_raw("data: [DONE]\n\n", "text/event-stream"),
3041            )
3042            .mount(&server)
3043            .await;
3044
3045        let client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
3046        let raw = json!({
3047            "model": "client-facing",
3048            "messages": [{"role": "user", "content": "hi"}],
3049            "stream": true,
3050            "stream_options": {"include_usage": false}
3051        });
3052
3053        let response = client
3054            .call_rewrite_model(
3055                wire_request(raw, None, WireFormat::OpenAiChat)?,
3056                Some(&ModelId::from("gpt")),
3057            )
3058            .await?;
3059        assert!(matches!(response.llm_response, LlmResponse::Stream(_)));
3060        Ok(())
3061    }
3062
3063    #[tokio::test]
3064    async fn upstream_500_is_upstream_http()
3065    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3066        let server = MockServer::start().await;
3067        Mock::given(method("POST"))
3068            .respond_with(ResponseTemplate::new(500).set_body_string("boom"))
3069            .mount(&server)
3070            .await;
3071
3072        let client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
3073
3074        let Err(error) = client
3075            .call_rewrite_model(request_for(Some("gpt"), false), None)
3076            .await
3077        else {
3078            panic!("expected an error");
3079        };
3080        assert!(matches!(
3081            error,
3082            LlmClientError::UpstreamHttp {
3083                status: StatusCode::INTERNAL_SERVER_ERROR,
3084                ..
3085            }
3086        ));
3087        Ok(())
3088    }
3089
3090    #[tokio::test]
3091    async fn retryable_http_failure_recovers_within_budget()
3092    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3093        let server = MockServer::start().await;
3094        let calls = Arc::new(AtomicUsize::new(0));
3095        let observed_calls = Arc::clone(&calls);
3096        Mock::given(method("POST"))
3097            .respond_with(move |_: &wiremock::Request| {
3098                if observed_calls.fetch_add(1, Ordering::SeqCst) == 0 {
3099                    ResponseTemplate::new(503)
3100                        .insert_header("retry-after", "0")
3101                        .set_body_string("temporarily unavailable")
3102                } else {
3103                    chat_success_response()
3104                }
3105            })
3106            .mount(&server)
3107            .await;
3108
3109        let client =
3110            TranslatingLlmClient::new(&chat_map_with_retries(&format!("{}/v1", server.uri()), 1))?;
3111        let response = client
3112            .call_rewrite_model(request_for(Some("gpt"), false), None)
3113            .await?;
3114        let agg = response.llm_response.into_agg().await?;
3115
3116        assert_eq!(completion_text(&agg), "recovered");
3117        assert_eq!(calls.load(Ordering::SeqCst), 2);
3118        Ok(())
3119    }
3120
3121    #[tokio::test]
3122    async fn deterministic_http_failure_is_not_retried()
3123    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3124        let server = MockServer::start().await;
3125        let calls = Arc::new(AtomicUsize::new(0));
3126        let observed_calls = Arc::clone(&calls);
3127        Mock::given(method("POST"))
3128            .respond_with(move |_: &wiremock::Request| {
3129                observed_calls.fetch_add(1, Ordering::SeqCst);
3130                ResponseTemplate::new(401).set_body_string("invalid key")
3131            })
3132            .mount(&server)
3133            .await;
3134
3135        let client =
3136            TranslatingLlmClient::new(&chat_map_with_retries(&format!("{}/v1", server.uri()), 2))?;
3137        let Err(error) = client
3138            .call_rewrite_model(request_for(Some("gpt"), false), None)
3139            .await
3140        else {
3141            panic!("expected an upstream error");
3142        };
3143
3144        assert!(matches!(
3145            error,
3146            LlmClientError::UpstreamHttp {
3147                status: StatusCode::UNAUTHORIZED,
3148                body,
3149                ..
3150            } if body == "invalid key"
3151        ));
3152        assert_eq!(calls.load(Ordering::SeqCst), 1);
3153        Ok(())
3154    }
3155
3156    #[tokio::test]
3157    async fn rate_limit_cooldown_depends_on_shared_credentials()
3158    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3159        for forward_auth in [true, false] {
3160            let server = MockServer::start().await;
3161            Mock::given(method("POST"))
3162                .respond_with(ResponseTemplate::new(429).insert_header("retry-after", "0"))
3163                .expect(if forward_auth { 6 } else { 3 })
3164                .mount(&server)
3165                .await;
3166            let backend = HttpBackendConfig {
3167                forward_auth,
3168                failure_cooldown: Duration::from_secs(60),
3169                ..config_with_retries(&format!("{}/v1", server.uri()), 2)
3170            };
3171            let client = TranslatingLlmClient::new(&[ModelConfig::new(
3172                "gpt",
3173                Backend::OpenAiChat(backend),
3174                None,
3175            )])?;
3176            for credential in ["Bearer first-user", "Bearer second-user"] {
3177                let mut headers = http::HeaderMap::new();
3178                headers.insert("authorization", http::HeaderValue::from_static(credential));
3179                let result = client
3180                    .call_rewrite_model(request_with_headers("gpt", headers), None)
3181                    .await;
3182                if !forward_auth && credential == "Bearer second-user" {
3183                    assert!(matches!(
3184                        result,
3185                        Err(LlmClientError::TemporarilyUnavailable)
3186                    ));
3187                } else {
3188                    assert!(matches!(
3189                        result,
3190                        Err(LlmClientError::UpstreamHttp {
3191                            status: StatusCode::TOO_MANY_REQUESTS,
3192                            ..
3193                        })
3194                    ));
3195                }
3196            }
3197        }
3198        Ok(())
3199    }
3200
3201    #[tokio::test]
3202    async fn retry_exhaustion_returns_the_final_upstream_error()
3203    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3204        let server = MockServer::start().await;
3205        let calls = Arc::new(AtomicUsize::new(0));
3206        let observed_calls = Arc::clone(&calls);
3207        Mock::given(method("POST"))
3208            .respond_with(move |_: &wiremock::Request| {
3209                let attempt = observed_calls.fetch_add(1, Ordering::SeqCst) + 1;
3210                ResponseTemplate::new(500)
3211                    .insert_header("retry-after", "0")
3212                    .set_body_string(format!("attempt {attempt}"))
3213            })
3214            .mount(&server)
3215            .await;
3216
3217        let client =
3218            TranslatingLlmClient::new(&chat_map_with_retries(&format!("{}/v1", server.uri()), 2))?;
3219        let Err(error) = client
3220            .call_rewrite_model(request_for(Some("gpt"), false), None)
3221            .await
3222        else {
3223            panic!("expected retry exhaustion");
3224        };
3225
3226        assert!(matches!(
3227            error,
3228            LlmClientError::UpstreamHttp {
3229                status: StatusCode::INTERNAL_SERVER_ERROR,
3230                body,
3231                ..
3232            } if body == "attempt 3"
3233        ));
3234        assert_eq!(calls.load(Ordering::SeqCst), 3);
3235        Ok(())
3236    }
3237
3238    // The error keeps every header of the last attempt; consumers choose what to forward.
3239    #[tokio::test]
3240    async fn upstream_error_carries_headers_from_the_last_attempt()
3241    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3242        let server = MockServer::start().await;
3243        // A zero `retry-after` keeps the retry from sleeping.
3244        let reply = |id: &str| {
3245            ResponseTemplate::new(429)
3246                .insert_header("retry-after", "0")
3247                .insert_header("x-request-id", id)
3248                .insert_header("set-cookie", "a=b")
3249        };
3250        Mock::given(method("POST"))
3251            .respond_with(reply("first"))
3252            .up_to_n_times(1)
3253            .mount(&server)
3254            .await;
3255        Mock::given(method("POST"))
3256            .respond_with(reply("second"))
3257            .mount(&server)
3258            .await;
3259        let client =
3260            TranslatingLlmClient::new(&chat_map_with_retries(&format!("{}/v1", server.uri()), 1))?;
3261        let Err(LlmClientError::UpstreamHttp { headers, .. }) = client
3262            .call_rewrite_model(request_for(Some("gpt"), false), None)
3263            .await
3264        else {
3265            panic!("expected an upstream HTTP error");
3266        };
3267        assert_eq!(headers["x-request-id"], "second");
3268        assert_eq!(headers["retry-after"], "0");
3269        assert_eq!(headers["set-cookie"], "a=b");
3270        Ok(())
3271    }
3272
3273    #[tokio::test]
3274    async fn deadline_expires_before_send_or_stream_poll()
3275    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3276        let server = MockServer::start().await;
3277        Mock::given(method("POST"))
3278            .respond_with(ResponseTemplate::new(200).set_body_raw(
3279                "data: {\"id\":\"test\",\"model\":\"gpt\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"ok\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n",
3280                "text/event-stream",
3281            ))
3282            .mount(&server)
3283            .await;
3284        for timeout in [Duration::ZERO, Duration::from_millis(200)] {
3285            let mut backend = config(&server.uri());
3286            backend.timeout = Some(timeout);
3287            let client = TranslatingLlmClient::new(&[ModelConfig::new(
3288                "gpt",
3289                Backend::OpenAiChat(backend),
3290                None,
3291            )])?;
3292            let result = client
3293                .call_rewrite_model(request_for(Some("gpt"), true), None)
3294                .await;
3295            if timeout.is_zero() {
3296                assert!(matches!(result, Err(LlmClientError::Timeout { .. })));
3297                assert!(
3298                    server
3299                        .received_requests()
3300                        .await
3301                        .expect("recorded requests")
3302                        .is_empty()
3303                );
3304            } else {
3305                let LlmResponse::Stream(mut chunks) = result?.llm_response else {
3306                    return Err("expected a streaming response".into());
3307                };
3308                tokio::time::sleep(Duration::from_millis(300)).await;
3309                assert!(matches!(
3310                    chunks.next().await,
3311                    Some(Err(LlmClientError::Timeout { .. }))
3312                ));
3313                assert!(chunks.next().await.is_none());
3314            }
3315        }
3316        Ok(())
3317    }
3318
3319    #[tokio::test]
3320    async fn timeout_is_retried_before_a_response_is_returned()
3321    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3322        let server = MockServer::start().await;
3323        let calls = Arc::new(AtomicUsize::new(0));
3324        let observed_calls = Arc::clone(&calls);
3325        Mock::given(method("POST"))
3326            .respond_with(move |_: &wiremock::Request| {
3327                if observed_calls.fetch_add(1, Ordering::SeqCst) == 0 {
3328                    ResponseTemplate::new(200).set_delay(Duration::from_millis(500))
3329                } else {
3330                    chat_success_response()
3331                }
3332            })
3333            .mount(&server)
3334            .await;
3335
3336        let mut client =
3337            TranslatingLlmClient::new(&chat_map_with_retries(&format!("{}/v1", server.uri()), 1))?;
3338        client.client = reqwest::Client::builder()
3339            .timeout(Duration::from_millis(100))
3340            .build()?;
3341        let response = client
3342            .call_rewrite_model(request_for(Some("gpt"), false), None)
3343            .await?;
3344
3345        assert_eq!(
3346            completion_text(&response.llm_response.into_agg().await?),
3347            "recovered"
3348        );
3349        assert_eq!(calls.load(Ordering::SeqCst), 2);
3350        Ok(())
3351    }
3352
3353    #[test]
3354    fn retryable_error_classes_are_explicit() {
3355        let transport = AttemptFailure {
3356            error: LlmClientError::Transport {
3357                source: std::io::Error::other("disconnected").into(),
3358            },
3359            status: None,
3360            retry_after: None,
3361        };
3362        assert!(transport.is_retryable());
3363
3364        for status in [
3365            StatusCode::REQUEST_TIMEOUT,
3366            StatusCode::TOO_MANY_REQUESTS,
3367            StatusCode::INTERNAL_SERVER_ERROR,
3368            StatusCode::SERVICE_UNAVAILABLE,
3369            StatusCode::from_u16(599)
3370                .expect("599 is a syntactically valid HTTP code in the http crate"),
3371        ] {
3372            let failure = AttemptFailure {
3373                error: LlmClientError::UpstreamHttp {
3374                    status,
3375                    body: String::new(),
3376                    headers: Box::default(),
3377                },
3378                status: Some(status),
3379                retry_after: None,
3380            };
3381            assert!(failure.is_retryable(), "HTTP {status} should retry");
3382        }
3383        for status in [
3384            StatusCode::BAD_REQUEST,
3385            StatusCode::UNAUTHORIZED,
3386            StatusCode::CONFLICT,
3387            StatusCode::from_u16(600)
3388                .expect("600 is a syntactically valid HTTP code in the http crate"),
3389        ] {
3390            let failure = AttemptFailure {
3391                error: LlmClientError::UpstreamHttp {
3392                    status,
3393                    body: String::new(),
3394                    headers: Box::default(),
3395                },
3396                status: Some(status),
3397                retry_after: None,
3398            };
3399            assert!(!failure.is_retryable(), "HTTP {status} should fail fast");
3400        }
3401
3402        let configuration = AttemptFailure {
3403            error: LlmClientError::Configuration {
3404                message: "invalid header".to_string(),
3405            },
3406            status: None,
3407            retry_after: None,
3408        };
3409        assert!(!configuration.is_retryable());
3410
3411        let context_window = AttemptFailure {
3412            error: LlmClientError::ContextWindowExceeded {
3413                model: ModelId::from("gpt"),
3414                message: "too long".to_string(),
3415            },
3416            status: Some(StatusCode::BAD_REQUEST),
3417            retry_after: None,
3418        };
3419        assert!(!context_window.is_retryable());
3420    }
3421
3422    #[test]
3423    fn retry_after_supports_seconds_and_http_dates() {
3424        let mut headers = HeaderMap::new();
3425        headers.insert(RETRY_AFTER, reqwest::header::HeaderValue::from_static("3"));
3426        assert_eq!(retry_after_delay(&headers), Some(Duration::from_secs(3)));
3427
3428        let retry_at = SystemTime::now() + Duration::from_secs(2);
3429        let value = httpdate::fmt_http_date(retry_at);
3430        let Ok(value) = reqwest::header::HeaderValue::from_str(&value) else {
3431            panic!("formatted HTTP date should be a valid header");
3432        };
3433        headers.insert(RETRY_AFTER, value);
3434        let Some(delay) = retry_after_delay(&headers) else {
3435            panic!("HTTP date should produce a retry delay");
3436        };
3437        assert!(delay <= Duration::from_secs(2));
3438    }
3439
3440    #[tokio::test]
3441    async fn routed_llm_client_exposes_timeout_variant()
3442    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3443        let server = MockServer::start().await;
3444        Mock::given(method("POST"))
3445            .respond_with(
3446                ResponseTemplate::new(200).set_delay(std::time::Duration::from_millis(100)),
3447            )
3448            .mount(&server)
3449            .await;
3450
3451        let mut client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
3452        client.client = reqwest::Client::builder()
3453            .timeout(std::time::Duration::from_millis(10))
3454            .build()?;
3455
3456        let Err(error) = client.call(request_for(Some("gpt"), false)).await else {
3457            panic!("expected a timeout");
3458        };
3459        let LlmClientError::Timeout { source } = error else {
3460            panic!("expected the protocol timeout variant");
3461        };
3462        let Some(source) = source.downcast_ref::<reqwest::Error>() else {
3463            panic!("expected the reqwest timeout source");
3464        };
3465        assert!(source.is_timeout());
3466        Ok(())
3467    }
3468
3469    // A connect that never completes sends nothing, like a refused connection.
3470    #[cfg(target_os = "linux")]
3471    #[tokio::test]
3472    async fn connect_timeout_is_a_transport_error()
3473    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3474        // Linux drops SYNs once a listener's accept queue is full, so later
3475        // connects hang like an upstream behind a dropping firewall.
3476        let socket = tokio::net::TcpSocket::new_v4()?;
3477        socket.bind("127.0.0.1:0".parse()?)?;
3478        let listener = socket.listen(0)?;
3479        let addr = listener.local_addr()?;
3480        let _queued: Vec<_> = (0..2)
3481            .map(|_| {
3482                std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(100))
3483            })
3484            .collect();
3485
3486        let mut client = TranslatingLlmClient::new(&chat_map(&format!("http://{addr}/v1")))?;
3487        // Stands in for the OS connect timeout (30 s on Linux via reqwest's default
3488        // TCP_USER_TIMEOUT); both surface as `is_connect() && is_timeout()`.
3489        client.client = reqwest::Client::builder()
3490            .connect_timeout(std::time::Duration::from_millis(100))
3491            .build()?;
3492
3493        let Err(error) = client.call(request_for(Some("gpt"), false)).await else {
3494            panic!("expected the connect to fail");
3495        };
3496        let LlmClientError::Transport { source } = error else {
3497            panic!("expected Transport, got {error:?}");
3498        };
3499        let Some(source) = source.downcast_ref::<reqwest::Error>() else {
3500            panic!("expected the reqwest connect-timeout source");
3501        };
3502        assert!(source.is_connect());
3503        assert!(source.is_timeout());
3504        Ok(())
3505    }
3506
3507    #[tokio::test]
3508    async fn llama_cpp_context_overflow_400_is_mapped()
3509    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3510        let server = MockServer::start().await;
3511        Mock::given(method("POST"))
3512            .respond_with(ResponseTemplate::new(400).set_body_json(json!({
3513                "error": {
3514                    "message": "request (6016 tokens) exceeds the available context size (4096 tokens), try increasing it"
3515                }
3516            })))
3517            .mount(&server)
3518            .await;
3519
3520        let client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
3521
3522        let Err(error) = client
3523            .call_rewrite_model(request_for(Some("gpt"), false), None)
3524            .await
3525        else {
3526            panic!("expected an error");
3527        };
3528        assert!(matches!(
3529            error,
3530            LlmClientError::ContextWindowExceeded { model, .. } if model == "gpt"
3531        ));
3532        Ok(())
3533    }
3534
3535    #[tokio::test]
3536    async fn content_policy_400_preserves_upstream_error()
3537    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3538        let server = MockServer::start().await;
3539        let body = json!({
3540            "error": {
3541                "code": "content_policy_violation",
3542                "message": "request blocked by content policy",
3543                "type": "invalid_request_error"
3544            },
3545            "metadata": {"documentation_section": "context window"}
3546        });
3547        Mock::given(method("POST"))
3548            .respond_with(ResponseTemplate::new(400).set_body_json(&body))
3549            .expect(1)
3550            .mount(&server)
3551            .await;
3552        let client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
3553        let Err(error) = client
3554            .call_rewrite_model(request_for(Some("gpt"), false), None)
3555            .await
3556        else {
3557            panic!("expected a policy denial");
3558        };
3559        let LlmClientError::UpstreamHttp {
3560            status,
3561            body: actual,
3562            ..
3563        } = error
3564        else {
3565            panic!("expected the upstream HTTP error, got {error:?}");
3566        };
3567        assert_eq!(status, StatusCode::BAD_REQUEST);
3568        assert_eq!(serde_json::from_str::<serde_json::Value>(&actual)?, body);
3569        Ok(())
3570    }
3571
3572    #[tokio::test]
3573    async fn forwards_only_allowlisted_metadata_headers()
3574    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3575        let server = MockServer::start().await;
3576        Mock::given(method("POST"))
3577            .and(wiremock::matchers::header("x-request-id", "abc"))
3578            // A forwarded Authorization must NOT override the backend's bearer key.
3579            .and(wiremock::matchers::header("authorization", "Bearer secret"))
3580            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
3581                "id": "1", "model": "gpt",
3582                "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
3583                "usage": {}
3584            })))
3585            .mount(&server)
3586            .await;
3587
3588        let mut headers = http::HeaderMap::new();
3589        headers.insert("x-request-id", http::HeaderValue::from_static("abc"));
3590        let session_id = http::HeaderValue::from_static("conversation");
3591        headers.insert("x-session-id", session_id.clone());
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_eq!(received.headers.get("x-session-id"), Some(&session_id));
3617        assert!(!received.headers.contains_key("x-goog-api-key"));
3618        assert!(!received.headers.contains_key("x-custom-internal-secret"));
3619        Ok(())
3620    }
3621
3622    #[tokio::test]
3623    async fn forwards_application_headers_with_forward_auth()
3624    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3625        let server = MockServer::start().await;
3626        Mock::given(method("POST"))
3627            .and(wiremock::matchers::header(
3628                "authorization",
3629                "Bearer client-key",
3630            ))
3631            .and(wiremock::matchers::header(
3632                "x-goog-api-key",
3633                "client-google-key",
3634            ))
3635            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
3636                "id": "1", "model": "gpt",
3637                "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
3638                "usage": {}
3639            })))
3640            .mount(&server)
3641            .await;
3642
3643        let mut headers = http::HeaderMap::new();
3644        headers.insert(
3645            "authorization",
3646            http::HeaderValue::from_static("Bearer client-key"),
3647        );
3648        headers.insert(
3649            "x-goog-api-key",
3650            http::HeaderValue::from_static("client-google-key"),
3651        );
3652        headers.append("x-custom", http::HeaderValue::from_static("caller-first"));
3653        headers.append("x-custom", http::HeaderValue::from_static("caller-second"));
3654        headers.insert("host", http::HeaderValue::from_static("client.example"));
3655        headers.insert("content-type", http::HeaderValue::from_static("text/plain"));
3656        headers.insert("connection", http::HeaderValue::from_static("x-hop-by-hop"));
3657        headers.insert(
3658            "x-hop-by-hop",
3659            http::HeaderValue::from_static("client-only"),
3660        );
3661        let request = request_with_headers("gpt", headers);
3662        let mut backend_config = forwarding_config(&format!("{}/v1", server.uri()));
3663        backend_config.extra_headers = BTreeMap::from([
3664            ("X-Custom".into(), "configured".into()),
3665            ("X-Configured-Only".into(), "static".into()),
3666        ]);
3667        let client = TranslatingLlmClient::new(&[ModelConfig::new(
3668            "gpt",
3669            Backend::OpenAiChat(backend_config),
3670            None,
3671        )])?;
3672
3673        client.call_rewrite_model(request, None).await?;
3674        let received = server
3675            .received_requests()
3676            .await
3677            .ok_or("request recording should be enabled")?;
3678        let received = received.first().ok_or("expected one upstream request")?;
3679        assert_ne!(received.headers["host"], "client.example");
3680        assert_eq!(received.headers["content-type"], "application/json");
3681        assert!(!received.headers.contains_key("connection"));
3682        assert!(!received.headers.contains_key("x-hop-by-hop"));
3683        assert_eq!(received.headers.get_all("x-custom").iter().count(), 1);
3684        assert_eq!(received.headers["x-custom"], "configured");
3685        assert_eq!(received.headers["x-configured-only"], "static");
3686        Ok(())
3687    }
3688
3689    #[tokio::test]
3690    async fn forward_auth_preserves_anthropic_headers_and_redacts_errors()
3691    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3692        let server = MockServer::start().await;
3693        Mock::given(method("POST"))
3694            .and(path("/v1/messages"))
3695            .and(|request: &wiremock::Request| {
3696                request
3697                    .headers
3698                    .get("anthropic-beta")
3699                    .and_then(|value| value.to_str().ok())
3700                    == Some("oauth-2025-04-20")
3701                    && request.headers.get_all("anthropic-version").iter().count() == 1
3702                    && request
3703                        .headers
3704                        .get("anthropic-version")
3705                        .and_then(|value| value.to_str().ok())
3706                        == Some("2023-06-01")
3707            })
3708            .respond_with(ResponseTemplate::new(401).set_body_json(json!({
3709                "error": {"message": "rejected client-google-key"}
3710            })))
3711            .mount(&server)
3712            .await;
3713
3714        let mut headers = http::HeaderMap::new();
3715        headers.insert(
3716            "authorization",
3717            http::HeaderValue::from_static("Bearer client-key"),
3718        );
3719        headers.insert(
3720            "x-goog-api-key",
3721            http::HeaderValue::from_static("client-google-key"),
3722        );
3723        headers.insert(
3724            "anthropic-beta",
3725            http::HeaderValue::from_static("oauth-2025-04-20,prompt-caching-2024-07-31"),
3726        );
3727        headers.insert(
3728            "anthropic-version",
3729            http::HeaderValue::from_static("caller-version"),
3730        );
3731        let backend_config = forwarding_config(&server.uri());
3732        let client = TranslatingLlmClient::new(&[ModelConfig::new(
3733            "claude",
3734            Backend::Anthropic(backend_config),
3735            None,
3736        )])?;
3737        let raw = json!({
3738            "model": "claude",
3739            "max_tokens": 8,
3740            "messages": [{"role": "user", "content": "hello"}]
3741        });
3742
3743        let Err(LlmClientError::UpstreamHttp { body, .. }) = client
3744            .call_rewrite_model(
3745                wire_request(raw, Some(headers), WireFormat::AnthropicMessages)?,
3746                Some(&ModelId::from("claude")),
3747            )
3748            .await
3749        else {
3750            panic!("expected an upstream HTTP error");
3751        };
3752        assert_eq!(body, r#"{"error":{"message":"rejected [REDACTED]"}}"#);
3753        Ok(())
3754    }
3755
3756    // Exercises the `RoutedLlmClient` impl: `call` uses the model already materialized in the
3757    // request and round-trips a buffered response.
3758    #[tokio::test]
3759    async fn routed_llm_client_serves_the_request_model()
3760    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3761        let server = MockServer::start().await;
3762        Mock::given(method("POST"))
3763            .and(path("/v1/chat/completions"))
3764            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
3765                "id": "chatcmpl-1",
3766                "model": "gpt",
3767                "choices": [{
3768                    "index": 0,
3769                    "message": {"role": "assistant", "content": "routed hi"},
3770                    "finish_reason": "stop"
3771                }],
3772                "usage": {"prompt_tokens": 1, "completion_tokens": 2, "total_tokens": 3}
3773            })))
3774            .mount(&server)
3775            .await;
3776
3777        let client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
3778        let response = client.call(request_for(Some("gpt"), false)).await?;
3779        let agg = response.llm_response.into_agg().await?;
3780        assert_eq!(completion_text(&agg), "routed hi");
3781        Ok(())
3782    }
3783
3784    // A Codex namespace is folded into the upstream tool name.
3785    #[tokio::test]
3786    async fn chat_backend_folds_codex_mcp_namespace_into_the_tool_name()
3787    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3788        let server = MockServer::start().await;
3789        Mock::given(method("POST"))
3790            .and(path("/v1/chat/completions"))
3791            .and(wiremock::matchers::body_partial_json(json!({
3792                "tools": [{
3793                    "type": "function",
3794                    "function": {"name": "mcp__open_websearch__search"}
3795                }]
3796            })))
3797            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
3798                "id": "chatcmpl-1",
3799                "model": "gpt",
3800                "choices": [{
3801                    "index": 0,
3802                    "message": {
3803                        "role": "assistant",
3804                        "content": null,
3805                        "tool_calls": [{
3806                            "id": "call_1",
3807                            "type": "function",
3808                            "function": {
3809                                "name": "mcp__open_websearch__search",
3810                                "arguments": "{\"q\":\"rust\"}"
3811                            }
3812                        }]
3813                    },
3814                    "finish_reason": "tool_calls"
3815                }],
3816                "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}
3817            })))
3818            .mount(&server)
3819            .await;
3820
3821        let client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
3822        let raw = json!({
3823            "model": "client-facing",
3824            "input": "Search for Rust.",
3825            "tools": [{
3826                "type": "namespace",
3827                "name": "mcp__open_websearch",
3828                "tools": [{
3829                    "type": "function",
3830                    "name": "search",
3831                    "description": "Search the web",
3832                    "parameters": {"type": "object", "properties": {"q": {"type": "string"}}}
3833                }]
3834            }]
3835        });
3836
3837        let response = client
3838            .call_rewrite_model(
3839                wire_request(raw, None, WireFormat::OpenAiResponses)?,
3840                Some(&ModelId::from("gpt")),
3841            )
3842            .await?;
3843        let agg = response.llm_response.into_agg().await?;
3844
3845        assert_tool_call_name(&agg, "mcp__open_websearch__search");
3846        Ok(())
3847    }
3848
3849    #[tokio::test]
3850    async fn openai_responses_backend_flattens_codex_namespaces_before_upstream()
3851    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3852        let server = MockServer::start().await;
3853        Mock::given(method("POST"))
3854            .and(path("/v1/responses"))
3855            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
3856                "id": "resp_1",
3857                "model": "gpt",
3858                "object": "response",
3859                "created_at": 0,
3860                "status": "completed",
3861                "output": [{
3862                    "type": "function_call",
3863                    "call_id": "call_1",
3864                    "name": "mcp__open_websearch__search",
3865                    "arguments": "{\"q\":\"rust\"}"
3866                }],
3867                "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2}
3868            })))
3869            .mount(&server)
3870            .await;
3871
3872        let client = TranslatingLlmClient::new(&responses_map(&format!("{}/v1", server.uri())))?;
3873        let parameters = json!({"type": "object", "properties": {"q": {"type": "string"}}});
3874        let raw = json!({
3875            "model": "client-facing",
3876            "input": [{
3877                "type": "function_call",
3878                "call_id": "call_0",
3879                "name": "search",
3880                "namespace": "mcp__open_websearch",
3881                "arguments": "{}"
3882            }],
3883            "tool_choice": {
3884                "type": "function",
3885                "name": "search",
3886                "namespace": "mcp__open_websearch"
3887            },
3888            "tools": [{
3889                "type": "namespace",
3890                "name": "mcp__open_websearch",
3891                "tools": [{
3892                    "type": "function",
3893                    "name": "search",
3894                    "parameters": parameters.clone()
3895                }]
3896            }]
3897        });
3898
3899        let response = client
3900            .call_rewrite_model(
3901                wire_request(raw, None, WireFormat::OpenAiResponses)?,
3902                Some(&ModelId::from("gpt")),
3903            )
3904            .await?;
3905        let agg = response.llm_response.into_agg().await?;
3906
3907        let received = server
3908            .received_requests()
3909            .await
3910            .ok_or("request recording should be enabled")?;
3911        let request_body: Value = serde_json::from_slice(&received[0].body)?;
3912        assert_eq!(request_body["model"], "gpt");
3913        assert_eq!(
3914            request_body["tools"],
3915            json!([{
3916                "type": "function",
3917                "name": "mcp__open_websearch__search",
3918                "description": "",
3919                "parameters": parameters
3920            }])
3921        );
3922        assert_eq!(
3923            request_body["tool_choice"],
3924            json!({"type": "function", "name": "mcp__open_websearch__search"})
3925        );
3926        assert_eq!(
3927            request_body["input"][0]["name"],
3928            "mcp__open_websearch__search"
3929        );
3930        assert!(request_body["input"][0].get("namespace").is_none());
3931        assert_tool_call_name(&agg, "mcp__open_websearch__search");
3932        Ok(())
3933    }
3934
3935    // A stage route can answer early steps of a Codex turn from Claude and a later step from
3936    // GPT, and Codex replays Claude's reasoning items on every step. OpenAI returns 400 for two
3937    // kinds: items with an ID but no `encrypted_content` when the request sets `store: false`,
3938    // and items whose `encrypted_content` holds Anthropic thinking that Switchyard packed for
3939    // the client. The Responses leg must drop both and keep GPT's own encrypted reasoning.
3940    // A non-OpenAI target instead keeps the plaintext and drops both payloads.
3941    #[tokio::test]
3942    async fn openai_responses_backend_drops_reasoning_the_provider_cannot_read()
3943    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
3944        let server = MockServer::start().await;
3945        Mock::given(method("POST"))
3946            .and(path("/v1/responses"))
3947            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
3948                "id": "resp_1",
3949                "model": "gpt",
3950                "object": "response",
3951                "created_at": 0,
3952                "status": "completed",
3953                "output": [{
3954                    "type": "message",
3955                    "role": "assistant",
3956                    "content": [{"type": "output_text", "text": "ok"}]
3957                }],
3958                "usage": {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2}
3959            })))
3960            .mount(&server)
3961            .await;
3962
3963        let mut claude_reasoning = json!({
3964            "type": "reasoning",
3965            "id": "rs_b99feb9a-763d-4f7f-b6b2-2c0199b47ded",
3966            "summary": [{"type": "summary_text", "text": "Read the files first."}],
3967            "encrypted_content": null
3968        });
3969        // Build the item the way Switchyard does when it returns a Claude reply to a Responses
3970        // client, so the test follows any change to that format.
3971        let claude_reply = switchyard_translation::TranslationEngine::default()
3972            .translate_response(
3973                WireFormat::AnthropicMessages,
3974                WireFormat::OpenAiResponses,
3975                &json!({
3976                    "id": "msg_1",
3977                    "type": "message",
3978                    "role": "assistant",
3979                    "model": "claude",
3980                    "content": [
3981                        {"type": "thinking", "thinking": "Plan the edit.", "signature": "sig-abc"},
3982                        {"type": "text", "text": "ok"}
3983                    ],
3984                    "stop_reason": "end_turn",
3985                    "usage": {"input_tokens": 1, "output_tokens": 1}
3986                }),
3987                &switchyard_translation::TranslationPolicy::default(),
3988            )?
3989            .body;
3990        let switchyard_reasoning = claude_reply["output"]
3991            .as_array()
3992            .and_then(|output| output.iter().find(|item| item["type"] == "reasoning"))
3993            .cloned()
3994            .ok_or("translated Claude reply should contain a reasoning item")?;
3995        assert!(switchyard_translation::is_anthropic_thinking_envelope(
3996            switchyard_reasoning["encrypted_content"]
3997                .as_str()
3998                .unwrap_or_default()
3999        ));
4000        let mut gpt_reasoning = json!({
4001            "type": "reasoning",
4002            "id": "rs_gpt",
4003            "summary": [],
4004            "encrypted_content": "opaque-encrypted-reasoning"
4005        });
4006        let mut empty_reasoning =
4007            json!({"type": "reasoning", "id": "rs_empty", "summary": [], "encrypted_content": ""});
4008        let user = json!({"type": "message", "role": "user", "content": "fix the build"});
4009        let call = json!({"type": "function_call", "call_id": "call_1", "name": "exec", "arguments": "{}"});
4010        let output = json!({"type": "function_call_output", "call_id": "call_1", "output": "ok"});
4011        let input = json!([
4012            user,
4013            claude_reasoning,
4014            switchyard_reasoning,
4015            call,
4016            output,
4017            gpt_reasoning,
4018            empty_reasoning
4019        ]);
4020
4021        let models = ["openai/gpt-5", "nvidia/zai-org/glm-5.3-flash"].map(|model| {
4022            ModelConfig::new(
4023                model,
4024                Backend::OpenAiResponses(config(&format!("{}/v1", server.uri()))),
4025                None,
4026            )
4027        });
4028        let client = TranslatingLlmClient::new(&models)?;
4029        for model in ["openai/gpt-5", "nvidia/zai-org/glm-5.3-flash"] {
4030            for store in [json!(false), json!(true)] {
4031                let raw = json!({"model": "client-facing", "store": store, "input": input.clone()});
4032                client
4033                    .call_rewrite_model(
4034                        wire_request(raw, None, WireFormat::OpenAiResponses)?,
4035                        Some(&ModelId::from(model)),
4036                    )
4037                    .await?;
4038            }
4039        }
4040
4041        let received = server
4042            .received_requests()
4043            .await
4044            .ok_or("request recording should be enabled")?;
4045        let sent: Vec<Value> = received
4046            .iter()
4047            .map(|request| serde_json::from_slice::<Value>(&request.body))
4048            .collect::<std::result::Result<_, _>>()?;
4049        assert_eq!(sent.len(), 4);
4050        for request in &sent {
4051            assert!(
4052                request["input"]
4053                    .as_array()
4054                    .ok_or("expected input array")?
4055                    .iter()
4056                    .all(|item| !item["encrypted_content"]
4057                        .as_str()
4058                        .is_some_and(switchyard_translation::is_anthropic_thinking_envelope)),
4059                "provider cannot read translated Anthropic reasoning"
4060            );
4061        }
4062
4063        // GLM keeps the plaintext beside the Anthropic envelope and drops GPT's payload.
4064        let mut switchyard_plaintext = switchyard_reasoning.clone();
4065        switchyard_plaintext
4066            .as_object_mut()
4067            .ok_or("object")?
4068            .remove("encrypted_content");
4069        assert_eq!(
4070            sent[2]["input"],
4071            json!([user, claude_reasoning, switchyard_plaintext, call, output])
4072        );
4073        assert_eq!(
4074            sent[3]["input"],
4075            json!([
4076                user,
4077                claude_reasoning,
4078                switchyard_plaintext,
4079                call,
4080                output,
4081                empty_reasoning
4082            ])
4083        );
4084
4085        for item in [
4086            &mut claude_reasoning,
4087            &mut gpt_reasoning,
4088            &mut empty_reasoning,
4089        ] {
4090            item["content"] = json!([]);
4091        }
4092        // With `store: false`, only GPT's own encrypted reasoning survives.
4093        assert_eq!(sent[0]["input"], json!([user, call, output, gpt_reasoning]));
4094        // With `store: true`, IDs can refer to stored reasoning, but OpenAI still cannot
4095        // decrypt the Switchyard item.
4096        assert_eq!(
4097            sent[1]["input"],
4098            json!([
4099                user,
4100                claude_reasoning,
4101                call,
4102                output,
4103                gpt_reasoning,
4104                empty_reasoning
4105            ])
4106        );
4107        Ok(())
4108    }
4109
4110    // Allowed caller headers reach the upstream.
4111    #[tokio::test]
4112    async fn call_rewrite_model_forwards_caller_headers()
4113    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
4114        let server = MockServer::start().await;
4115        Mock::given(method("POST"))
4116            .and(wiremock::matchers::header("x-request-id", "abc"))
4117            .and(|req: &wiremock::Request| !req.headers.contains_key("x-session-id"))
4118            // A forwarded authorization must NOT override the backend's bearer key.
4119            .and(wiremock::matchers::header("authorization", "Bearer secret"))
4120            .respond_with(ResponseTemplate::new(200).set_body_json(json!({
4121                "id": "1", "model": "gpt",
4122                "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
4123                "usage": {}
4124            })))
4125            .mount(&server)
4126            .await;
4127
4128        let mut headers = http::HeaderMap::new();
4129        headers.insert("x-request-id", http::HeaderValue::from_static("abc"));
4130        headers.insert("x-session-id", http::HeaderValue::from_static("local"));
4131        headers.insert("connection", http::HeaderValue::from_static("X-Session-Id"));
4132        headers.insert(
4133            "authorization",
4134            http::HeaderValue::from_static("Bearer client-key"),
4135        );
4136
4137        let client = TranslatingLlmClient::new(&chat_map(&format!("{}/v1", server.uri())))?;
4138        let raw = json!({"model": "gpt", "messages": [{"role": "user", "content": "hi"}]});
4139        // The allowed request id survives and caller authorization cannot replace
4140        // the backend's credential.
4141        client
4142            .call_rewrite_model(
4143                wire_request(raw, Some(headers), WireFormat::OpenAiChat)?,
4144                Some(&ModelId::from("gpt")),
4145            )
4146            .await?;
4147        Ok(())
4148    }
4149    #[tokio::test]
4150    async fn bad_media_does_not_retry_or_cool_down_the_backend()
4151    -> std::result::Result<(), Box<dyn Error + Sync + Send + 'static>> {
4152        use switchyard_protocol::{ContentBlock, ImageSource};
4153        for retries in [0, 2] {
4154            let server = MockServer::start().await;
4155            let calls = Arc::new(AtomicUsize::new(0));
4156            let seen = calls.clone();
4157            Mock::given(method("POST"))
4158                .respond_with(move |request: &wiremock::Request| {
4159                    seen.fetch_add(1, Ordering::SeqCst);
4160                    if String::from_utf8_lossy(&request.body).contains("image_url") {
4161                        ResponseTemplate::new(500).set_body_json(json!({"error": {
4162                            "message": "cannot make GET request to image URL", "type": "server_error"
4163                        }}))
4164                    } else { chat_success_response() }
4165                }).mount(&server).await;
4166            let backend = HttpBackendConfig {
4167                failure_cooldown: Duration::from_secs(60),
4168                ..config_with_retries(&format!("{}/v1", server.uri()), retries)
4169            };
4170            let client = TranslatingLlmClient::new(&[ModelConfig::new(
4171                "gpt",
4172                Backend::OpenAiChat(backend),
4173                None,
4174            )])?;
4175            let mut broken = request_for(Some("gpt"), false);
4176            broken.llm_request.messages[0]
4177                .content
4178                .push(ContentBlock::Image {
4179                    source: ImageSource::Url {
4180                        url: "https://example.invalid/missing.png".into(),
4181                        detail: None,
4182                    },
4183                });
4184            assert!(matches!(
4185                client.call_rewrite_model(broken, None).await,
4186                Err(LlmClientError::UpstreamHttp {
4187                    status: StatusCode::INTERNAL_SERVER_ERROR,
4188                    ..
4189                })
4190            ));
4191            let response = client
4192                .call_rewrite_model(request_for(Some("gpt"), false), None)
4193                .await?;
4194            assert_eq!(
4195                completion_text(&response.llm_response.into_agg().await?),
4196                "recovered"
4197            );
4198            assert_eq!(calls.load(Ordering::SeqCst), 2);
4199        }
4200        Ok(())
4201    }
4202}