| 1 | //! Native Anthropic Messages API adapter (#3014). |
| 2 | //! |
| 3 | //! CodeWhale's internal wire types are already Anthropic-shaped (the harness |
| 4 | //! speaks Messages internally and translates *out* to OpenAI dialects), so |
| 5 | //! this adapter is mostly native serialization plus an SSE pass-through: |
| 6 | //! `StreamEvent` deserializes Anthropic's `message_start` / |
| 7 | //! `content_block_*` / `message_delta` / `message_stop` / `ping` events |
| 8 | //! directly. What the adapter adds on top: |
| 9 | //! |
| 10 | //! - request shaping: adaptive thinking + `output_config.effort` from |
| 11 | //! CodeWhale's `reasoning_effort` tiers, sampling-parameter rules for |
| 12 | //! models that reject them, and `cache_control` breakpoint placement |
| 13 | //! aligned with the prefix-zone model in `prefix_cache.rs`; |
| 14 | //! - usage normalization (#2961 / #4318): `prompt_cache_hit_tokens` comes from |
| 15 | //! `cache_read_input_tokens`, `prompt_cache_write_tokens` from |
| 16 | //! `cache_creation_input_tokens`, `prompt_cache_miss_tokens` is the raw |
| 17 | //! non-cached `input_tokens`, and the normalized `input_tokens` is the sum |
| 18 | //! of all three (total prompt, the DeepSeek convention); |
| 19 | //! - signed-thinking handling: `signature_delta` is captured into |
| 20 | //! [`codewhale_models::Delta::SignatureDelta`] and assistant thinking blocks |
| 21 | //! replay verbatim (signature included); unsigned thinking blocks are |
| 22 | //! dropped from replay because the API rejects them. |
| 23 | //! |
| 24 | //! Modeled on `client/responses.rs` (separate file per dialect, no protocol |
| 25 | //! hacks in the shared paths). |
| 26 | |
| 27 | use anyhow::{Context, Result}; |
| 28 | use serde::Deserialize; |
| 29 | use serde_json::{Value, json}; |
| 30 | |
| 31 | use crate::llm_client::StreamEventBox; |
| 32 | use codewhale_config::ProviderKind; |
| 33 | use codewhale_models::tool_projection::{ |
| 34 | RouteToolProjection, ToolSchemaProjection, description_with_constraint_note, forced_tool_name, |
| 35 | project_tool_schema, |
| 36 | }; |
| 37 | use codewhale_models::{ |
| 38 | ContentBlock, ContentBlockStart, MessageRequest, MessageResponse, StreamEvent, Usage, |
| 39 | }; |
| 40 | use codewhale_runtime::logging; |
| 41 | |
| 42 | use super::CodewhaleClient; |
| 43 | use super::prepared::WireDialect; |
| 44 | use super::role_placement::{RolePlacement, role_placement}; |
| 45 | use super::wire::{ |
| 46 | ToolNameWire, check_history_tool_names, documented_tool_name_limit, extract_sse_data_value, |
| 47 | from_api_tool_name, next_sse_line, over_limit_tool_name_message, push_sse_event_data, |
| 48 | to_api_tool_name, tool_name_exceeds_limit, tool_name_limit, |
| 49 | }; |
| 50 | |
| 51 | /// Maximum `cache_control` breakpoints Anthropic accepts per request. |
| 52 | const MAX_CACHE_BREAKPOINTS: usize = 4; |
| 53 | |
| 54 | impl CodewhaleClient { |
| 55 | #[cfg(test)] |
| 56 | pub(super) fn build_anthropic_body(&self, request: &MessageRequest, stream: bool) -> Value { |
| 57 | self.build_anthropic_wire_body(request, stream) |
| 58 | .expect("anthropic body builds") |
| 59 | .0 |
| 60 | } |
| 61 | |
| 62 | /// Build the native Messages API request body from a [`MessageRequest`]. |
| 63 | pub(super) fn build_anthropic_wire_body( |
| 64 | &self, |
| 65 | request: &MessageRequest, |
| 66 | stream: bool, |
| 67 | ) -> Result<(Value, Vec<String>)> { |
| 68 | let model = codewhale_config::route::resolve_model( |
| 69 | self.api_provider, |
| 70 | &request.model, |
| 71 | Some(&self.base_url), |
| 72 | ) |
| 73 | .map_or_else( |
| 74 | |_| request.model.trim().to_string(), |
| 75 | |resolved| resolved.wire_id, |
| 76 | ); |
| 77 | let mut body = json!({ |
| 78 | "model": model, |
| 79 | "max_tokens": request.max_tokens, |
| 80 | "stream": stream, |
| 81 | }); |
| 82 | |
| 83 | if let Some(system) = request.system.as_ref() { |
| 84 | body["system"] = match system { |
| 85 | codewhale_models::SystemPrompt::Text(text) => json!(text), |
| 86 | codewhale_models::SystemPrompt::Blocks(blocks) => json!( |
| 87 | blocks |
| 88 | .iter() |
| 89 | .map(|block| { |
| 90 | let mut value = json!({ |
| 91 | "type": "text", |
| 92 | "text": block.text, |
| 93 | }); |
| 94 | if let Some(cache) = block.cache_control.as_ref() { |
| 95 | value["cache_control"] = json!({ "type": cache.cache_type }); |
| 96 | } |
| 97 | value |
| 98 | }) |
| 99 | .collect::<Vec<_>>() |
| 100 | ), |
| 101 | }; |
| 102 | } |
| 103 | |
| 104 | super::role_placement::validate_latest_reminder_messages(&request.messages)?; |
| 105 | super::deepseek_tools::validate_and_apply_safety_check_and_title( |
| 106 | request, |
| 107 | &mut body, |
| 108 | matches!( |
| 109 | self.api_provider, |
| 110 | ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic |
| 111 | ), |
| 112 | )?; |
| 113 | |
| 114 | let mut messages: Vec<Value> = request |
| 115 | .messages |
| 116 | .iter() |
| 117 | .filter_map(message_to_anthropic) |
| 118 | .collect(); |
| 119 | merge_split_tool_results(&mut messages); |
| 120 | repair_dangling_tool_uses(&mut messages); |
| 121 | body["messages"] = Value::Array(messages); |
| 122 | |
| 123 | let tool_name_limit = tool_name_limit(self.api_provider, ToolNameWire::AnthropicMessages); |
| 124 | check_history_tool_names( |
| 125 | request, |
| 126 | documented_tool_name_limit(self.api_provider, ToolNameWire::AnthropicMessages), |
| 127 | )?; |
| 128 | let mut omitted_tool_names = Vec::new(); |
| 129 | let mut omitted_logical_names = Vec::new(); |
| 130 | let mut has_deepseek_web_tools = false; |
| 131 | if let Some(tools) = request.tools.as_ref() |
| 132 | && !tools.is_empty() |
| 133 | { |
| 134 | has_deepseek_web_tools = super::deepseek_tools::validate_deepseek_web_tools( |
| 135 | tools, |
| 136 | WireDialect::AnthropicMessages, |
| 137 | )?; |
| 138 | let route_projection = RouteToolProjection::Relaxed { |
| 139 | strict_honored: !self.is_local_ds4_model(&request.model), |
| 140 | }; |
| 141 | let mut wire_tools = Vec::new(); |
| 142 | for tool in tools { |
| 143 | if let Some(kind) = super::deepseek_tools::deepseek_web_tool_kind(tool) { |
| 144 | let mut value = json!({ |
| 145 | "type": kind, |
| 146 | "name": kind, |
| 147 | }); |
| 148 | if let Some(cache) = tool.cache_control.as_ref() { |
| 149 | value["cache_control"] = json!({ "type": cache.cache_type }); |
| 150 | } |
| 151 | wire_tools.push(value); |
| 152 | continue; |
| 153 | } |
| 154 | if tool_name_exceeds_limit(&tool.name, tool_name_limit) { |
| 155 | omitted_logical_names.push(tool.name.clone()); |
| 156 | omitted_tool_names.push(to_api_tool_name(&tool.name)); |
| 157 | continue; |
| 158 | } |
| 159 | match project_tool_schema(route_projection, &tool.input_schema, tool.strict) { |
| 160 | ToolSchemaProjection::Exact { |
| 161 | parameters, |
| 162 | strict, |
| 163 | constraint_note, |
| 164 | } |
| 165 | | ToolSchemaProjection::Relaxed { |
| 166 | parameters, |
| 167 | strict, |
| 168 | constraint_note, |
| 169 | } => { |
| 170 | let mut value = json!({ |
| 171 | "name": to_api_tool_name(&tool.name), |
| 172 | "description": description_with_constraint_note( |
| 173 | &tool.description, |
| 174 | constraint_note, |
| 175 | ), |
| 176 | "input_schema": parameters, |
| 177 | }); |
| 178 | if let Some(strict) = strict { |
| 179 | value["strict"] = json!(strict); |
| 180 | } |
| 181 | if let Some(cache) = tool.cache_control.as_ref() { |
| 182 | value["cache_control"] = json!({ "type": cache.cache_type }); |
| 183 | } |
| 184 | wire_tools.push(value); |
| 185 | } |
| 186 | ToolSchemaProjection::Omitted { .. } => { |
| 187 | omitted_logical_names.push(tool.name.clone()); |
| 188 | omitted_tool_names.push(to_api_tool_name(&tool.name)); |
| 189 | } |
| 190 | } |
| 191 | } |
| 192 | if !wire_tools.is_empty() { |
| 193 | body["tools"] = json!(wire_tools); |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | if let Some(tool_choice) = request.tool_choice.as_ref() { |
| 198 | super::deepseek_tools::validate_deepseek_web_tool_choice( |
| 199 | tool_choice, |
| 200 | has_deepseek_web_tools, |
| 201 | )?; |
| 202 | if let Some(name) = forced_tool_name(tool_choice) |
| 203 | && omitted_logical_names.iter().any(|omitted| omitted == name) |
| 204 | { |
| 205 | if tool_name_exceeds_limit(name, tool_name_limit) { |
| 206 | anyhow::bail!(over_limit_tool_name_message(name, tool_name_limit)); |
| 207 | } |
| 208 | anyhow::bail!( |
| 209 | "cannot force an omitted tool because its input schema is incompatible with this route" |
| 210 | ); |
| 211 | } |
| 212 | if body.get("tools").is_some() { |
| 213 | body["tool_choice"] = anthropic_tool_choice(tool_choice, &model); |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | // Thinking + effort shaping. MiniMax supports adaptive/disabled but |
| 218 | // not Anthropic's output_config effort field; native Anthropic routes |
| 219 | // keep the existing effort mapping. Other Messages-compatible |
| 220 | // gateways (#4978, e.g. Sensenova) only accept the documented |
| 221 | // enabled/disabled/auto thinking types, so non-native routes get the |
| 222 | // portable `{"type":"enabled","budget_tokens":N}` shape instead. |
| 223 | let thinking_capable = self |
| 224 | .route_facts |
| 225 | .as_ref() |
| 226 | .filter(|facts| facts.wire_model_id == request.model) |
| 227 | .and_then(|facts| facts.reasoning) |
| 228 | .unwrap_or_else(|| codewhale_models::model_supports_reasoning(&model)); |
| 229 | let is_minimax_provider = self.api_provider == ProviderKind::MinimaxAnthropic; |
| 230 | let is_minimax_m3 = codewhale_runtime::config::is_exact_minimax_anthropic_m3_route( |
| 231 | self.api_provider, |
| 232 | &self.base_url, |
| 233 | &model, |
| 234 | ); |
| 235 | let fallback_minimax_offering = is_minimax_provider |
| 236 | .then(|| { |
| 237 | self.route_facts |
| 238 | .as_ref() |
| 239 | .filter(|facts| facts.wire_model_id == request.model) |
| 240 | .map(|facts| facts.reasoning_options.as_slice()) |
| 241 | .is_none() |
| 242 | .then(|| { |
| 243 | crate::provider_lake::catalog_offering_for_model( |
| 244 | ProviderKind::MinimaxAnthropic, |
| 245 | &model, |
| 246 | ) |
| 247 | }) |
| 248 | .flatten() |
| 249 | }) |
| 250 | .flatten(); |
| 251 | let minimax_options = self |
| 252 | .route_facts |
| 253 | .as_ref() |
| 254 | .filter(|facts| facts.wire_model_id == request.model) |
| 255 | .map(|facts| facts.reasoning_options.as_slice()) |
| 256 | .or_else(|| { |
| 257 | fallback_minimax_offering |
| 258 | .as_ref() |
| 259 | .map(|offering| offering.reasoning_options.as_slice()) |
| 260 | }); |
| 261 | let minimax_has_effort = minimax_options.is_some_and(|options| { |
| 262 | options |
| 263 | .iter() |
| 264 | .any(|option| option.get("type").and_then(Value::as_str) == Some("effort")) |
| 265 | }); |
| 266 | let is_minimax = is_minimax_m3 |
| 267 | || (is_minimax_provider |
| 268 | && codewhale_config::provider::is_exact_minimax_anthropic_route( |
| 269 | self.api_provider, |
| 270 | &self.base_url, |
| 271 | ) |
| 272 | && thinking_capable |
| 273 | && minimax_options.is_some_and(|options| !options.is_empty())); |
| 274 | let is_deepseek = self.api_provider == ProviderKind::DeepseekAnthropic; |
| 275 | // Model Studio's Anthropic-compatible endpoint documents the portable |
| 276 | // `{"type":"enabled","budget_tokens":N}` shape AND `{"type":"disabled"}` |
| 277 | // (alibabacloud.com/help/en/model-studio/anthropic-api-messages), so |
| 278 | // an explicit "off" can be honored on the wire instead of silently |
| 279 | // falling through to the server default (which is thinking-ON for the |
| 280 | // qwen3.x families). |
| 281 | let is_modelstudio = matches!( |
| 282 | self.api_provider, |
| 283 | ProviderKind::ModelstudioTokenPlan |
| 284 | | ProviderKind::ModelstudioTokenPlanAnthropic |
| 285 | | ProviderKind::ModelstudioCodingPlan |
| 286 | | ProviderKind::ModelstudioCodingPlanAnthropic |
| 287 | ); |
| 288 | // MiniMax's exact M3 route and DeepSeek's Messages dialect both |
| 289 | // document adaptive support; everything else needs the native host. |
| 290 | let supports_adaptive = |
| 291 | is_native_anthropic_base_url(&self.base_url) || is_minimax || is_deepseek; |
| 292 | let effort = request |
| 293 | .reasoning_effort |
| 294 | .as_deref() |
| 295 | .map(|raw| raw.trim().to_ascii_lowercase()); |
| 296 | match effort.as_deref() { |
| 297 | _ if is_minimax_provider && !is_minimax => {} |
| 298 | Some("off" | "disabled" | "none" | "false") |
| 299 | if (is_minimax || is_deepseek || is_modelstudio) && thinking_capable => |
| 300 | { |
| 301 | // Deliberately includes thinking-only Model Studio models |
| 302 | // (qwen3.8-max family): unlike the chat dialect's |
| 303 | // enable_thinking switch, the Messages endpoint documents the |
| 304 | // portable {"type":"disabled"} shape for them |
| 305 | // (alibabacloud.com/help/en/model-studio/anthropic-api-messages) |
| 306 | // — pinned by modelstudio_messages_body_requests_thinking_ |
| 307 | // with_budget. Re-checked 2026-08-04. |
| 308 | body["thinking"] = json!({ "type": "disabled" }); |
| 309 | } |
| 310 | Some("off" | "disabled" | "none" | "false") => {} |
| 311 | Some(level) if thinking_capable && supports_adaptive => { |
| 312 | body["thinking"] = json!({ "type": "adaptive" }); |
| 313 | if !is_minimax || minimax_has_effort { |
| 314 | let row_lists_xhigh = minimax_options.is_some_and(|options| { |
| 315 | options.iter().any(|option| { |
| 316 | option.get("type").and_then(Value::as_str) == Some("effort") |
| 317 | && option.get("values").and_then(Value::as_array).is_some_and( |
| 318 | |values| values.iter().any(|v| v.as_str() == Some("xhigh")), |
| 319 | ) |
| 320 | }) |
| 321 | }); |
| 322 | let mapped = match level { |
| 323 | "low" | "minimal" => "low", |
| 324 | "medium" | "mid" => "medium", |
| 325 | "xhigh" if row_lists_xhigh => "xhigh", |
| 326 | "max" | "xhigh" | "highest" => "max", |
| 327 | _ => "high", |
| 328 | }; |
| 329 | body["output_config"] = json!({ "effort": mapped }); |
| 330 | } |
| 331 | } |
| 332 | None if thinking_capable && supports_adaptive => { |
| 333 | body["thinking"] = json!({ "type": "adaptive" }); |
| 334 | } |
| 335 | _ if thinking_capable => { |
| 336 | if let Some(mut budget) = |
| 337 | compat_thinking_budget(effort.as_deref(), request.max_tokens) |
| 338 | { |
| 339 | let mut minimum = u64::from(MIN_THINKING_BUDGET_TOKENS); |
| 340 | if let Some(facts) = self |
| 341 | .route_facts |
| 342 | .as_ref() |
| 343 | .filter(|facts| facts.wire_model_id == request.model) |
| 344 | && let Some(option) = facts.reasoning_options.iter().find(|option| { |
| 345 | matches!( |
| 346 | option.get("type").and_then(Value::as_str), |
| 347 | Some("budget" | "budget_tokens") |
| 348 | ) |
| 349 | }) |
| 350 | { |
| 351 | minimum = option.get("min").and_then(Value::as_u64).unwrap_or(minimum); |
| 352 | let maximum = option |
| 353 | .get("max") |
| 354 | .and_then(Value::as_u64) |
| 355 | .unwrap_or(u64::from(request.max_tokens.saturating_sub(1))); |
| 356 | budget = budget.min(u32::try_from(maximum).unwrap_or(u32::MAX)); |
| 357 | } |
| 358 | if u64::from(budget) >= minimum { |
| 359 | body["thinking"] = json!({ "type": "enabled", "budget_tokens": budget }); |
| 360 | } else { |
| 361 | tracing::warn!( |
| 362 | "The output allowance cannot represent the offering's minimum reasoning budget; thinking was omitted" |
| 363 | ); |
| 364 | } |
| 365 | } |
| 366 | } |
| 367 | _ => {} |
| 368 | } |
| 369 | |
| 370 | // Anthropic documents `redacted_thinking.data` as opaque encrypted |
| 371 | // content to pass back unchanged and says nothing about third-party |
| 372 | // gateways understanding the block type, and we cannot tell a |
| 373 | // terminating gateway from a forwarding proxy to the first-party |
| 374 | // API (which would handle the block). Withholding on every |
| 375 | // non-native host is the conservative call: a strict terminating |
| 376 | // gateway would reject the unknown block type outright, while a |
| 377 | // forwarding proxy only loses the block's continuity (a |
| 378 | // redacted-only current tool turn can still 400 there). Native |
| 379 | // `*.anthropic.com` routes keep the payload byte-exact. |
| 380 | if !is_native_anthropic_base_url(&self.base_url) |
| 381 | && let Some(messages) = body.get_mut("messages").and_then(Value::as_array_mut) |
| 382 | { |
| 383 | messages.retain_mut(|message| { |
| 384 | let is_assistant = message.get("role").and_then(Value::as_str) == Some("assistant"); |
| 385 | let Some(blocks) = message.get_mut("content").and_then(Value::as_array_mut) else { |
| 386 | return true; |
| 387 | }; |
| 388 | blocks.retain(|block| { |
| 389 | block.get("type").and_then(Value::as_str) != Some("redacted_thinking") |
| 390 | }); |
| 391 | // A message that only carried redacted blocks would |
| 392 | // otherwise go out with an empty `content: []`, which |
| 393 | // Messages-compatible endpoints reject — the same |
| 394 | // every-retry 400 this withhold exists to prevent. Dropping |
| 395 | // the message is safe: a redacted-only assistant turn |
| 396 | // carries no `tool_use`, so no `tool_result` can dangle. |
| 397 | // Reachable only from foreign/imported sessions; the live |
| 398 | // engine never persists a reasoning-only turn. |
| 399 | !(is_assistant && blocks.is_empty()) |
| 400 | }); |
| 401 | } |
| 402 | |
| 403 | // Sampling parameters: every model from Claude 4.7 on (including the |
| 404 | // Claude 5 generation and Haiku 5.5) rejects non-default |
| 405 | // temperature/top_p; earlier models reject the two together. Send at |
| 406 | // most one (temperature wins), or neither for models that forbid |
| 407 | // them. |
| 408 | if !anthropic_model_rejects_sampling(&request.model) { |
| 409 | if let Some(temperature) = request.temperature { |
| 410 | body["temperature"] = json!(temperature); |
| 411 | } else if let Some(top_p) = request.top_p { |
| 412 | body["top_p"] = json!(top_p); |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | apply_anthropic_cache_breakpoints(&mut body); |
| 417 | Ok((body, omitted_tool_names)) |
| 418 | } |
| 419 | |
| 420 | /// Non-streaming send through the shared typed retry path |
| 421 | /// (`send_with_retry`): 429/5xx/transport failures retry with backoff and |
| 422 | /// honor `Retry-After`, and a final failure stays a downcastable |
| 423 | /// `LlmError` so the engine can classify auth, rate-limit, context and |
| 424 | /// invalid-request failures like every other wire. |
| 425 | async fn send_anthropic_request(&self, url: &str, body: &Value) -> Result<reqwest::Response> { |
| 426 | let url = self.messages_transport_url(url); |
| 427 | let request_body = |
| 428 | serde_json::to_vec(body).context("Failed to serialize Anthropic Messages request")?; |
| 429 | let needs_files_beta = has_files_api_document(body); |
| 430 | self.send_with_retry(|| { |
| 431 | let mut req = self |
| 432 | .http_client |
| 433 | .post(&url) |
| 434 | .header(reqwest::header::CONTENT_TYPE, "application/json") |
| 435 | .header("Accept", "text/event-stream"); |
| 436 | if needs_files_beta { |
| 437 | req = req.header("anthropic-beta", "files-api-2025-04-14"); |
| 438 | } |
| 439 | req.body(request_body.clone()) |
| 440 | }) |
| 441 | .await |
| 442 | .context("Anthropic Messages API request failed") |
| 443 | } |
| 444 | |
| 445 | /// Open Messages through the shared provider retry and stream-entry |
| 446 | /// policy. Each physical request has its own header wait and at most one |
| 447 | /// HTTP/1.1 fallback; provider backoff stays outside that wait. Request |
| 448 | /// construction remains at this wire-specific edge. |
| 449 | async fn open_anthropic_stream_response( |
| 450 | &self, |
| 451 | url: &str, |
| 452 | body: &Value, |
| 453 | ) -> Result<reqwest::Response> { |
| 454 | let url = self.messages_transport_url(url); |
| 455 | let request_body = |
| 456 | serde_json::to_vec(body).context("Failed to serialize Anthropic Messages request")?; |
| 457 | let needs_files_beta = has_files_api_document(body); |
| 458 | self.send_stream_open_with_retry(|policy| { |
| 459 | let mut req = super::stream_entry::client_for_policy( |
| 460 | &self.http_client, |
| 461 | self.http1_fallback_client(), |
| 462 | policy, |
| 463 | ) |
| 464 | .post(&url) |
| 465 | .header(reqwest::header::CONTENT_TYPE, "application/json") |
| 466 | .header("Accept", "text/event-stream"); |
| 467 | if needs_files_beta { |
| 468 | req = req.header("anthropic-beta", "files-api-2025-04-14"); |
| 469 | } |
| 470 | req.body(request_body.clone()) |
| 471 | }) |
| 472 | .await |
| 473 | .context("Anthropic Messages API request failed") |
| 474 | } |
| 475 | |
| 476 | /// Handle a streaming Messages API request. |
| 477 | pub(super) async fn handle_anthropic_stream( |
| 478 | &self, |
| 479 | prepared: &super::PreparedOutboundRequest, |
| 480 | ) -> Result<StreamEventBox> { |
| 481 | // Body and endpoint come from the shared prepared-request seam |
| 482 | // (`prepare_outbound_request`), never from a second builder. |
| 483 | let body = &prepared.body; |
| 484 | let response = self |
| 485 | .open_anthropic_stream_response(&prepared.endpoint.url, body) |
| 486 | .await?; |
| 487 | |
| 488 | let stream_idle_timeout = self.stream_idle_timeout; |
| 489 | let first_byte = super::stream_entry::first_byte_timeout(stream_idle_timeout); |
| 490 | let provider_label = self.api_provider.provider().display_name(); |
| 491 | let byte_stream = response.bytes_stream(); |
| 492 | |
| 493 | let stream = async_stream::stream! { |
| 494 | use futures_util::StreamExt; |
| 495 | |
| 496 | // Raw byte buffer: decode only COMPLETE lines (or the stream-end |
| 497 | // tail) via the shared take_sse_line / flush_sse_line helpers so a |
| 498 | // multi-byte UTF-8 char (CJK/emoji) split across HTTP/2 DATA is |
| 499 | // never corrupted to U+FFFD. Genuine invalid bytes fail closed. |
| 500 | let mut buffer: Vec<u8> = Vec::new(); |
| 501 | // `data:` fields of the event being assembled, dispatched at the |
| 502 | // blank line that ends it (or at stream end). |
| 503 | let mut event_data = String::new(); |
| 504 | let stream_start = std::time::Instant::now(); |
| 505 | let mut last_chunk_at = std::time::Instant::now(); |
| 506 | let mut bytes_received: usize = 0; |
| 507 | let mut ended = false; |
| 508 | tokio::pin!(byte_stream); |
| 509 | |
| 510 | loop { |
| 511 | if !ended { |
| 512 | let wait = super::stream_entry::next_chunk_timeout( |
| 513 | stream_idle_timeout, |
| 514 | first_byte, |
| 515 | bytes_received, |
| 516 | ); |
| 517 | match tokio::time::timeout(wait, byte_stream.next()).await { |
| 518 | Ok(Some(Ok(chunk))) => { |
| 519 | bytes_received += chunk.len(); |
| 520 | last_chunk_at = std::time::Instant::now(); |
| 521 | buffer.extend_from_slice(&chunk); |
| 522 | } |
| 523 | Ok(Some(Err(e))) => { |
| 524 | yield Err(anyhow::anyhow!("Stream read error: {e}")); |
| 525 | return; |
| 526 | } |
| 527 | Ok(None) => ended = true, |
| 528 | Err(_) => { |
| 529 | yield Err(anyhow::anyhow!(super::stream_entry::body_timeout_message( |
| 530 | wait, |
| 531 | bytes_received, |
| 532 | stream_start.elapsed(), |
| 533 | last_chunk_at.elapsed(), |
| 534 | provider_label, |
| 535 | ))); |
| 536 | return; |
| 537 | } |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | loop { |
| 542 | let data = match next_sse_line(&mut buffer, ended) { |
| 543 | // A blank line ends the event. |
| 544 | Ok(Some(line)) if line.is_empty() => std::mem::take(&mut event_data), |
| 545 | Ok(Some(line)) => { |
| 546 | // `event:` lines are redundant (the data payload |
| 547 | // carries `type`) and comment/heartbeat lines are |
| 548 | // ignorable. |
| 549 | if let Some(value) = extract_sse_data_value(&line) |
| 550 | && let Err(err) = push_sse_event_data(&mut event_data, value) |
| 551 | { |
| 552 | yield Err(anyhow::anyhow!("{err}")); |
| 553 | return; |
| 554 | } |
| 555 | continue; |
| 556 | } |
| 557 | // The final event may arrive without its blank line. |
| 558 | Ok(None) if ended && !event_data.is_empty() => { |
| 559 | std::mem::take(&mut event_data) |
| 560 | } |
| 561 | Ok(None) => break, |
| 562 | Err(err) => { |
| 563 | yield Err(anyhow::anyhow!("{err}")); |
| 564 | return; |
| 565 | } |
| 566 | }; |
| 567 | if data.is_empty() { |
| 568 | continue; |
| 569 | } |
| 570 | |
| 571 | match convert_anthropic_sse_data(&data) { |
| 572 | Some(Ok(StreamEvent::Error { error })) => { |
| 573 | let (error_type, message) = anthropic_error_fields(&error); |
| 574 | yield Err(anyhow::anyhow!( |
| 575 | "Anthropic stream error ({error_type}): {message}" |
| 576 | )); |
| 577 | return; |
| 578 | } |
| 579 | Some(Ok(event)) => { |
| 580 | let is_stop = matches!(event, StreamEvent::MessageStop); |
| 581 | yield Ok(event); |
| 582 | if is_stop { |
| 583 | return; |
| 584 | } |
| 585 | } |
| 586 | Some(Err(e)) => { |
| 587 | logging::warn(format!("Failed to parse Anthropic SSE event: {e}")); |
| 588 | } |
| 589 | None => {} |
| 590 | } |
| 591 | } |
| 592 | |
| 593 | if ended { |
| 594 | break; |
| 595 | } |
| 596 | } |
| 597 | // Only `message_stop` (returned above) or a provider error proves |
| 598 | // the response is whole. A bare HTTP EOF is truncation, and ending |
| 599 | // the stream quietly would hand the turn a partial answer as done. |
| 600 | yield Err(anyhow::anyhow!( |
| 601 | "Anthropic Messages stream closed before message_stop" |
| 602 | )); |
| 603 | }; |
| 604 | |
| 605 | Ok(Box::pin(stream)) |
| 606 | } |
| 607 | |
| 608 | /// Handle a non-streaming Messages API request. |
| 609 | pub(super) async fn handle_anthropic_message( |
| 610 | &self, |
| 611 | prepared: &super::PreparedOutboundRequest, |
| 612 | ) -> Result<MessageResponse> { |
| 613 | let response = self |
| 614 | .send_anthropic_request(&prepared.endpoint.url, &prepared.body) |
| 615 | .await?; |
| 616 | let value: Value = response |
| 617 | .json() |
| 618 | .await |
| 619 | .context("Failed to parse Anthropic Messages response")?; |
| 620 | decode_anthropic_message(value) |
| 621 | } |
| 622 | } |
| 623 | |
| 624 | fn discard_provider_execution_ids(value: &mut Value) { |
| 625 | // Shared history retains execution ids on disk. Incoming provider content |
| 626 | // cannot choose one, including a value that would not deserialize as the |
| 627 | // host field. Live execution must mint its own correlation instead. |
| 628 | if let Some(blocks) = value.get_mut("content").and_then(Value::as_array_mut) { |
| 629 | for block in blocks { |
| 630 | if let Some(block) = block.as_object_mut() { |
| 631 | block.remove("execution_id"); |
| 632 | } |
| 633 | } |
| 634 | } |
| 635 | } |
| 636 | |
| 637 | fn decode_tool_use_names(value: &mut Value) { |
| 638 | let Some(content) = value.get_mut("content").and_then(Value::as_array_mut) else { |
| 639 | return; |
| 640 | }; |
| 641 | for block in content.iter_mut() { |
| 642 | if block.get("type").and_then(Value::as_str) == Some("tool_use") |
| 643 | && let Some(name) = block.get("name").and_then(Value::as_str) |
| 644 | { |
| 645 | block["name"] = json!(from_api_tool_name(name)); |
| 646 | } |
| 647 | } |
| 648 | } |
| 649 | |
| 650 | fn has_files_api_document(body: &Value) -> bool { |
| 651 | body.get("messages") |
| 652 | .and_then(Value::as_array) |
| 653 | .is_some_and(|messages| { |
| 654 | messages.iter().any(|message| { |
| 655 | message |
| 656 | .get("content") |
| 657 | .and_then(Value::as_array) |
| 658 | .is_some_and(|blocks| { |
| 659 | blocks.iter().any(|block| { |
| 660 | block.get("type").and_then(Value::as_str) == Some("document") |
| 661 | && block.pointer("/source/type").and_then(Value::as_str) |
| 662 | == Some("file") |
| 663 | }) |
| 664 | }) |
| 665 | }) |
| 666 | }) |
| 667 | } |
| 668 | |
| 669 | fn decode_anthropic_message(mut value: Value) -> Result<MessageResponse> { |
| 670 | if value.get("type").and_then(Value::as_str) == Some("error") { |
| 671 | let err = value.get("error").unwrap_or(&value); |
| 672 | let (error_type, message) = anthropic_error_fields(err); |
| 673 | anyhow::bail!("Anthropic Messages error ({error_type}): {message}"); |
| 674 | } |
| 675 | discard_provider_execution_ids(&mut value); |
| 676 | if let Some(usage) = value.get_mut("usage") { |
| 677 | *usage = json!(parse_anthropic_usage(usage)); |
| 678 | } |
| 679 | normalize_redacted_thinking_blocks(&mut value); |
| 680 | decode_tool_use_names(&mut value); |
| 681 | serde_json::from_value(value).context("Failed to decode Anthropic Messages response") |
| 682 | } |
| 683 | |
| 684 | /// Rewrite non-stream `redacted_thinking` content blocks into the |
| 685 | /// provider-neutral shape (`Thinking` with `redacted_data`) before decoding. |
| 686 | /// |
| 687 | /// The provider-neutral content model has no `redacted_thinking` tag, so an |
| 688 | /// unknown block type would fail the whole response decode and lose the turn |
| 689 | /// — including the tool calls. Streaming responses carry the same blocks as |
| 690 | /// typed `ContentBlockStart::RedactedThinking` events and need no shim. |
| 691 | /// A block whose `data` is missing or not a string violates the contract; |
| 692 | /// it is still rewritten (with an empty payload) so the turn decodes and the |
| 693 | /// failure surfaces at replay with a diagnosable shape instead of as a |
| 694 | /// whole-response decode error. |
| 695 | fn normalize_redacted_thinking_blocks(value: &mut Value) { |
| 696 | let Some(content) = value.get_mut("content").and_then(Value::as_array_mut) else { |
| 697 | return; |
| 698 | }; |
| 699 | for block in content.iter_mut() { |
| 700 | if block.get("type").and_then(Value::as_str) == Some("redacted_thinking") { |
| 701 | let data = block.get("data").and_then(Value::as_str).unwrap_or(""); |
| 702 | if data.is_empty() { |
| 703 | logging::warn( |
| 704 | "Response carried a redacted thinking block with a missing or non-string payload; capturing it with an empty payload", |
| 705 | ); |
| 706 | } |
| 707 | *block = json!({ |
| 708 | "type": "thinking", |
| 709 | "thinking": "", |
| 710 | "redacted_data": data, |
| 711 | }); |
| 712 | } |
| 713 | } |
| 714 | } |
| 715 | |
| 716 | /// Build the `/v1/messages` endpoint URL, tolerating base URLs that already |
| 717 | /// carry a `/v1` suffix. |
| 718 | pub(super) fn anthropic_messages_url(base_url: &str) -> String { |
| 719 | let trimmed = base_url.trim_end_matches('/'); |
| 720 | if trimmed.ends_with("/v1") { |
| 721 | format!("{trimmed}/messages") |
| 722 | } else { |
| 723 | format!("{trimmed}/v1/messages") |
| 724 | } |
| 725 | } |
| 726 | |
| 727 | /// Whether the route targets first-party Anthropic (`api.anthropic.com`), |
| 728 | /// where the `{"type":"adaptive"}` thinking control is valid. Strict |
| 729 | /// Anthropic-compatible gateways reject it (#4978). |
| 730 | fn is_native_anthropic_base_url(base_url: &str) -> bool { |
| 731 | let rest = base_url |
| 732 | .trim() |
| 733 | .trim_start_matches("https://") |
| 734 | .trim_start_matches("http://"); |
| 735 | let host = rest |
| 736 | .split(['/', ':', '?', '#']) |
| 737 | .next() |
| 738 | .unwrap_or("") |
| 739 | .to_ascii_lowercase(); |
| 740 | host == "api.anthropic.com" || host.ends_with(".anthropic.com") |
| 741 | } |
| 742 | |
| 743 | /// Minimum `budget_tokens` the Messages API accepts for extended thinking. |
| 744 | const MIN_THINKING_BUDGET_TOKENS: u32 = 1024; |
| 745 | |
| 746 | /// Effort-tier `budget_tokens` for gateways that only accept the documented |
| 747 | /// `{"type":"enabled","budget_tokens":N}` thinking shape (#4978). The wire |
| 748 | /// contract requires `budget_tokens >= 1024` and `< max_tokens`, so requests |
| 749 | /// too small to fit the minimum budget send no thinking block at all. |
| 750 | fn compat_thinking_budget(effort: Option<&str>, max_tokens: u32) -> Option<u32> { |
| 751 | let tier: u32 = match effort { |
| 752 | Some("low" | "minimal") => 4_096, |
| 753 | Some("medium" | "mid") => 8_192, |
| 754 | Some("max" | "xhigh" | "highest") => 32_768, |
| 755 | // "high" and unspecified effort share the adaptive default tier. |
| 756 | _ => 16_384, |
| 757 | }; |
| 758 | let budget = tier.min(max_tokens.checked_sub(1)?); |
| 759 | (budget >= MIN_THINKING_BUDGET_TOKENS).then_some(budget) |
| 760 | } |
| 761 | |
| 762 | /// Fold a user turn that carries `tool_result`s into the user turn before it |
| 763 | /// (#6378). |
| 764 | /// |
| 765 | /// The engine records each tool result as its own user message, so a parallel |
| 766 | /// tool-call batch arrives here as `assistant{use_a, use_b}`, `user{result_a}`, |
| 767 | /// `user{result_b}`. Anthropic wants every result in the user turn right after |
| 768 | /// the `tool_use`s, and the repair below reads only that turn: it would answer |
| 769 | /// `use_b` with an error placeholder while the real result sits in the next |
| 770 | /// message. Only turns carrying a `tool_result` are folded, so any other |
| 771 | /// consecutive user turns keep their shape; inside the merged turn the results |
| 772 | /// stay ahead of other content so they still lead it. |
| 773 | fn merge_split_tool_results(messages: &mut Vec<Value>) { |
| 774 | let is_user = |message: &Value| message.get("role").and_then(Value::as_str) == Some("user"); |
| 775 | let is_tool_result = |
| 776 | |block: &Value| block.get("type").and_then(Value::as_str) == Some("tool_result"); |
| 777 | let carries_tool_result = |message: &Value| { |
| 778 | message |
| 779 | .get("content") |
| 780 | .and_then(Value::as_array) |
| 781 | .is_some_and(|blocks| blocks.iter().any(is_tool_result)) |
| 782 | }; |
| 783 | let mut merged: Vec<Value> = Vec::with_capacity(messages.len()); |
| 784 | for mut message in messages.drain(..) { |
| 785 | if is_user(&message) |
| 786 | && carries_tool_result(&message) |
| 787 | && let Some(previous) = merged.last_mut() |
| 788 | && is_user(previous) |
| 789 | { |
| 790 | let mut blocks = match previous["content"].take() { |
| 791 | Value::Array(blocks) => blocks, |
| 792 | other => vec![other], |
| 793 | }; |
| 794 | match message["content"].take() { |
| 795 | Value::Array(incoming) => blocks.extend(incoming), |
| 796 | other => blocks.push(other), |
| 797 | } |
| 798 | // Stable sort: results keep their order and lead the turn. |
| 799 | blocks.sort_by_key(|block| !is_tool_result(block)); |
| 800 | previous["content"] = Value::Array(blocks); |
| 801 | } else { |
| 802 | merged.push(message); |
| 803 | } |
| 804 | } |
| 805 | *messages = merged; |
| 806 | } |
| 807 | |
| 808 | /// Placeholder body for a `tool_use` that never produced a `tool_result`. |
| 809 | const UNEXECUTED_TOOL_RESULT: &str = "tool call was not executed"; |
| 810 | |
| 811 | /// Defensive wire repair (#5002): every assistant `tool_use` must be answered |
| 812 | /// by a `tool_result` in the immediately following user message, or the API |
| 813 | /// rejects the whole conversation with a 400 on every retry. Pre-dispatch |
| 814 | /// failure paths (e.g. the model calling an unavailable tool) can strand an |
| 815 | /// orphaned `tool_use` in history, so missing results get an explicit |
| 816 | /// error placeholder instead of poisoning the session. |
| 817 | fn repair_dangling_tool_uses(messages: &mut Vec<Value>) { |
| 818 | let mut index = 0; |
| 819 | while index < messages.len() { |
| 820 | let ids = assistant_tool_use_ids(&messages[index]); |
| 821 | if ids.is_empty() { |
| 822 | index += 1; |
| 823 | continue; |
| 824 | } |
| 825 | let next_is_user = messages |
| 826 | .get(index + 1) |
| 827 | .and_then(|message| message.get("role")) |
| 828 | .and_then(Value::as_str) |
| 829 | == Some("user"); |
| 830 | if !next_is_user { |
| 831 | messages.insert(index + 1, json!({ "role": "user", "content": [] })); |
| 832 | } |
| 833 | if let Some(blocks) = messages[index + 1] |
| 834 | .get_mut("content") |
| 835 | .and_then(Value::as_array_mut) |
| 836 | { |
| 837 | let answered: std::collections::HashSet<String> = blocks |
| 838 | .iter() |
| 839 | .filter(|block| block.get("type").and_then(Value::as_str) == Some("tool_result")) |
| 840 | .filter_map(|block| block.get("tool_use_id").and_then(Value::as_str)) |
| 841 | .map(str::to_string) |
| 842 | .collect(); |
| 843 | // tool_result blocks must lead the user turn, so placeholders are |
| 844 | // prepended in tool_use order. |
| 845 | for (offset, id) in ids |
| 846 | .iter() |
| 847 | .filter(|id| !answered.contains(id.as_str())) |
| 848 | .enumerate() |
| 849 | { |
| 850 | blocks.insert( |
| 851 | offset, |
| 852 | json!({ |
| 853 | "type": "tool_result", |
| 854 | "tool_use_id": id, |
| 855 | "content": UNEXECUTED_TOOL_RESULT, |
| 856 | "is_error": true, |
| 857 | }), |
| 858 | ); |
| 859 | } |
| 860 | } |
| 861 | index += 1; |
| 862 | } |
| 863 | } |
| 864 | |
| 865 | fn assistant_tool_use_ids(message: &Value) -> Vec<String> { |
| 866 | if message.get("role").and_then(Value::as_str) != Some("assistant") { |
| 867 | return Vec::new(); |
| 868 | } |
| 869 | message |
| 870 | .get("content") |
| 871 | .and_then(Value::as_array) |
| 872 | .map(|blocks| { |
| 873 | blocks |
| 874 | .iter() |
| 875 | .filter(|block| block.get("type").and_then(Value::as_str) == Some("tool_use")) |
| 876 | .filter_map(|block| block.get("id").and_then(Value::as_str)) |
| 877 | .map(str::to_string) |
| 878 | .collect() |
| 879 | }) |
| 880 | .unwrap_or_default() |
| 881 | } |
| 882 | |
| 883 | /// Models that reject non-default `temperature` / `top_p` outright (every |
| 884 | /// model released after Opus 4.6). The Messages API reference states those |
| 885 | /// models "do not support" setting `temperature` / `top_p` beyond their |
| 886 | /// backwards-compatible defaults (`temperature: 1.0`, `top_p >= 0.99`), and |
| 887 | /// the migration guides restate it per family: "Setting `temperature`, |
| 888 | /// `top_p`, or `top_k` to any non-default value on Claude Opus 4.7 and |
| 889 | /// later models, including Claude Opus 5.5, returns a 400 error". That |
| 890 | /// covers the Claude 5 generation (`claude-opus-5(-5)`, `claude-sonnet-5(-5)`) |
| 891 | /// and Haiku 5.5 (which admits only its defaults — `temperature: 1`, a lone |
| 892 | /// `top_p: 0.99`; `top_p: 1`, any `top_k`, or both params together 400), |
| 893 | /// besides the Fable/Mythos lines. Dropping the params entirely is always |
| 894 | /// safe; sending a forbidden one bricks the request. Re-checked 2026-10-08. |
| 895 | fn anthropic_model_rejects_sampling(model: &str) -> bool { |
| 896 | let lower = model.to_ascii_lowercase(); |
| 897 | lower.contains("opus-4-7") |
| 898 | || lower.contains("opus-4-8") |
| 899 | || ["opus-5", "sonnet-5", "haiku-5"] |
| 900 | .iter() |
| 901 | .any(|family| lower.contains(family)) |
| 902 | || lower.contains("fable") |
| 903 | || lower.contains("mythos") |
| 904 | } |
| 905 | |
| 906 | /// Convert the engine's `tool_choice` value (OpenAI-style string or object) |
| 907 | /// to the Anthropic object form. The Messages API tool-use reference lists |
| 908 | /// Opus 5.5, Sonnet 5.5, Fable 5.1 and Mythos 5.1 as answering `any`/`tool` |
| 909 | /// with a 400 error, so those models fall back to the server default `auto` |
| 910 | /// (`none` still works and is passed through unchanged). |
| 911 | fn anthropic_tool_choice(tool_choice: &Value, model: &str) -> Value { |
| 912 | let lower = model.to_ascii_lowercase(); |
| 913 | let rejects_forced = lower.contains("opus-5-5") |
| 914 | || lower.contains("sonnet-5-5") |
| 915 | || lower.contains("fable") |
| 916 | || lower.contains("mythos"); |
| 917 | let forced = match tool_choice.as_str() { |
| 918 | Some("any" | "required") => true, |
| 919 | Some(name) => !matches!(name, "auto" | "none"), |
| 920 | None => matches!( |
| 921 | tool_choice.get("type").and_then(Value::as_str), |
| 922 | Some("any" | "required" | "tool" | "function") |
| 923 | ), |
| 924 | }; |
| 925 | if forced && rejects_forced { |
| 926 | return json!({ "type": "auto" }); |
| 927 | } |
| 928 | match tool_choice.as_str() { |
| 929 | Some("auto") => json!({ "type": "auto" }), |
| 930 | Some("none") => json!({ "type": "none" }), |
| 931 | Some("any" | "required") => json!({ "type": "any" }), |
| 932 | Some(name) => json!({ "type": "tool", "name": to_api_tool_name(name) }), |
| 933 | None => match forced_tool_name(tool_choice) { |
| 934 | Some(name) => { |
| 935 | let mut choice = tool_choice.clone(); |
| 936 | choice["type"] = json!("tool"); |
| 937 | choice["name"] = json!(to_api_tool_name(name)); |
| 938 | if let Some(object) = choice.as_object_mut() { |
| 939 | object.remove("function"); |
| 940 | } |
| 941 | choice |
| 942 | } |
| 943 | None => tool_choice.clone(), |
| 944 | }, |
| 945 | } |
| 946 | } |
| 947 | |
| 948 | /// Convert one internal message to the Anthropic wire shape. Returns `None` |
| 949 | /// when no blocks survive conversion (Anthropic rejects empty content) or |
| 950 | /// when the role has no Anthropic channel. |
| 951 | /// |
| 952 | /// The wire role used to be `message.role` forwarded verbatim, which is how a |
| 953 | /// `system` message ended up on the wire for the provider to 400 on. It now |
| 954 | /// comes from the shared placement table, and pairs the table rejects are |
| 955 | /// refused at the outbound seam before this function ever runs. |
| 956 | pub(super) fn message_to_anthropic(message: &codewhale_models::Message) -> Option<Value> { |
| 957 | let placement = role_placement(&message.role, WireDialect::AnthropicMessages); |
| 958 | let wire_role = match placement { |
| 959 | RolePlacement::User | RolePlacement::Developer => "user", |
| 960 | RolePlacement::Assistant | RolePlacement::InterruptedAssistant => "assistant", |
| 961 | RolePlacement::LatestReminder => { |
| 962 | let text = message |
| 963 | .content |
| 964 | .iter() |
| 965 | .filter_map(|block| match block { |
| 966 | ContentBlock::Text { text, .. } => Some(text.as_str()), |
| 967 | _ => None, |
| 968 | }) |
| 969 | .collect::<Vec<_>>() |
| 970 | .join("\n"); |
| 971 | if text.is_empty() { |
| 972 | return None; |
| 973 | } |
| 974 | return Some(json!({ "role": "latest_reminder", "content": text })); |
| 975 | } |
| 976 | // Unreachable in production: `reject_unsupported_roles` refuses these |
| 977 | // pairs at the seam. Failing closed here keeps a future caller that |
| 978 | // skips the seam from putting an unrepresentable role on the wire. |
| 979 | RolePlacement::System | RolePlacement::Omitted | RolePlacement::Rejected => return None, |
| 980 | }; |
| 981 | let mut blocks: Vec<Value> = message |
| 982 | .content |
| 983 | .iter() |
| 984 | .filter_map(content_block_to_anthropic) |
| 985 | .collect(); |
| 986 | if blocks.is_empty() { |
| 987 | return None; |
| 988 | } |
| 989 | if placement == RolePlacement::InterruptedAssistant |
| 990 | && let Some(text) = blocks |
| 991 | .iter_mut() |
| 992 | .find(|block| block.get("type").and_then(Value::as_str) == Some("text")) |
| 993 | { |
| 994 | let existing = text |
| 995 | .get("text") |
| 996 | .and_then(Value::as_str) |
| 997 | .unwrap_or_default() |
| 998 | .to_string(); |
| 999 | text["text"] = json!(format!( |
| 1000 | "{}{}", |
| 1001 | codewhale_models::INTERRUPTED_ASSISTANT_CONTEXT_PREFIX, |
| 1002 | existing |
| 1003 | )); |
| 1004 | } |
| 1005 | Some(json!({ "role": wire_role, "content": blocks })) |
| 1006 | } |
| 1007 | |
| 1008 | /// Project the shared `ImageUrl` block onto Anthropic's tagged image source. |
| 1009 | /// |
| 1010 | /// The OpenAI dialects carry an image as a single URL string, so that is what |
| 1011 | /// [`ContentBlock::ImageUrl`] stores. Anthropic instead models the source as a |
| 1012 | /// tagged union, and — this is the part that used to be wrong here — it does |
| 1013 | /// **not** accept a `data:` URL under `{"type":"url"}`. Sending a local |
| 1014 | /// screenshot that way earns an opaque provider-side 400, which is exactly the |
| 1015 | /// confusing failure this whole path exists to avoid, so the data URL is taken |
| 1016 | /// back apart into `{"type":"base64", media_type, data}`. |
| 1017 | fn anthropic_image_block(url: &str) -> Value { |
| 1018 | if let Some((media_type, data)) = codewhale_models::image_window::parse_data_url(url) { |
| 1019 | return json!({ |
| 1020 | "type": "image", |
| 1021 | "source": { "type": "base64", "media_type": media_type, "data": data }, |
| 1022 | }); |
| 1023 | } |
| 1024 | if codewhale_models::image_window::is_remote_image_url(url) { |
| 1025 | return json!({ |
| 1026 | "type": "image", |
| 1027 | "source": { "type": "url", "url": url }, |
| 1028 | }); |
| 1029 | } |
| 1030 | // Anything else (a bare path, a `file://`, a truncated data URL) has no |
| 1031 | // Anthropic representation. Degrade to visible text rather than emitting a |
| 1032 | // source the API will reject: the turn survives and the model can see that |
| 1033 | // something was meant to be here. |
| 1034 | json!({ |
| 1035 | "type": "text", |
| 1036 | "text": format!("[unsupported image reference: {url}]"), |
| 1037 | }) |
| 1038 | } |
| 1039 | |
| 1040 | pub(super) fn anthropic_tool_result_content( |
| 1041 | content: &str, |
| 1042 | content_blocks: Option<&[Value]>, |
| 1043 | ) -> Value { |
| 1044 | let (image, omitted) = crate::image_attach::provider_tool_result_image_refs(content_blocks); |
| 1045 | let content = codewhale_models::image_window::tool_result_text_with_omission(content, omitted); |
| 1046 | let Some((mime_type, data)) = image else { |
| 1047 | return json!(content); |
| 1048 | }; |
| 1049 | let mut blocks = Vec::with_capacity(2); |
| 1050 | if !content.is_empty() { |
| 1051 | blocks.push(json!({ "type": "text", "text": content })); |
| 1052 | } |
| 1053 | blocks.push(json!({ |
| 1054 | "type": "image", |
| 1055 | "source": { "type": "base64", "media_type": mime_type, "data": data }, |
| 1056 | })); |
| 1057 | json!(blocks) |
| 1058 | } |
| 1059 | |
| 1060 | fn content_block_to_anthropic(block: &ContentBlock) -> Option<Value> { |
| 1061 | match block { |
| 1062 | ContentBlock::Text { |
| 1063 | text, |
| 1064 | cache_control, |
| 1065 | } => { |
| 1066 | let mut value = json!({ "type": "text", "text": text }); |
| 1067 | if let Some(cache) = cache_control { |
| 1068 | value["cache_control"] = json!({ "type": cache.cache_type }); |
| 1069 | } |
| 1070 | Some(value) |
| 1071 | } |
| 1072 | ContentBlock::Thinking { |
| 1073 | thinking, |
| 1074 | signature, |
| 1075 | redacted_data, |
| 1076 | .. |
| 1077 | } => { |
| 1078 | // A redacted thinking block is provider-encrypted content with no |
| 1079 | // readable text: replay it byte-exact so the API can decrypt it, |
| 1080 | // exactly like a signed block. Anthropic requires the complete |
| 1081 | // unmodified block in tool loops and decrypts it to restore the |
| 1082 | // turn's reasoning. |
| 1083 | if let Some(data) = redacted_data { |
| 1084 | return Some(json!({ |
| 1085 | "type": "redacted_thinking", |
| 1086 | "data": data, |
| 1087 | })); |
| 1088 | } |
| 1089 | // Anthropic rejects unsigned thinking blocks on replay (and the |
| 1090 | // DeepSeek-era "(reasoning omitted)" placeholders mean nothing to |
| 1091 | // it), so only signed blocks are replayed — verbatim, signature |
| 1092 | // included. |
| 1093 | signature.as_ref().map(|signature| { |
| 1094 | json!({ |
| 1095 | "type": "thinking", |
| 1096 | "thinking": thinking, |
| 1097 | "signature": signature, |
| 1098 | }) |
| 1099 | }) |
| 1100 | } |
| 1101 | ContentBlock::ToolUse { |
| 1102 | id, name, input, .. |
| 1103 | } => Some(json!({ |
| 1104 | "type": "tool_use", |
| 1105 | "id": id, |
| 1106 | "name": to_api_tool_name(name), |
| 1107 | "input": input, |
| 1108 | })), |
| 1109 | ContentBlock::ToolResult { |
| 1110 | tool_use_id, |
| 1111 | content, |
| 1112 | is_error, |
| 1113 | content_blocks, |
| 1114 | .. |
| 1115 | } => { |
| 1116 | let mut value = json!({ |
| 1117 | "type": "tool_result", |
| 1118 | "tool_use_id": tool_use_id, |
| 1119 | "content": anthropic_tool_result_content(content, content_blocks.as_deref()), |
| 1120 | }); |
| 1121 | if *is_error == Some(true) { |
| 1122 | value["is_error"] = json!(true); |
| 1123 | } |
| 1124 | Some(value) |
| 1125 | } |
| 1126 | ContentBlock::ImageUrl { image_url } => Some(anthropic_image_block(&image_url.url)), |
| 1127 | ContentBlock::ServerToolUse { |
| 1128 | id, |
| 1129 | name, |
| 1130 | input, |
| 1131 | kind, |
| 1132 | caller, |
| 1133 | } => { |
| 1134 | let mut value = json!({ |
| 1135 | "type": "server_tool_use", |
| 1136 | "id": id, |
| 1137 | "name": name, |
| 1138 | "input": input, |
| 1139 | }); |
| 1140 | if let Some(kind) = kind { |
| 1141 | value["kind"] = json!(kind); |
| 1142 | } |
| 1143 | if let Some(caller) = caller { |
| 1144 | value["caller"] = json!(caller); |
| 1145 | } |
| 1146 | Some(value) |
| 1147 | } |
| 1148 | ContentBlock::WebSearchToolResult { |
| 1149 | tool_use_id, |
| 1150 | content, |
| 1151 | kind, |
| 1152 | } => { |
| 1153 | let mut value = json!({ |
| 1154 | "type": "web_search_tool_result", |
| 1155 | "tool_use_id": tool_use_id, |
| 1156 | "content": content, |
| 1157 | }); |
| 1158 | if let Some(kind) = kind { |
| 1159 | value["kind"] = json!(kind); |
| 1160 | } |
| 1161 | Some(value) |
| 1162 | } |
| 1163 | ContentBlock::WebFetchToolResult { |
| 1164 | tool_use_id, |
| 1165 | content, |
| 1166 | kind, |
| 1167 | signature, |
| 1168 | } => { |
| 1169 | let mut value = json!({ |
| 1170 | "type": "web_fetch_tool_result", |
| 1171 | "tool_use_id": tool_use_id, |
| 1172 | "content": content, |
| 1173 | }); |
| 1174 | if let Some(kind) = kind { |
| 1175 | value["kind"] = json!(kind); |
| 1176 | } |
| 1177 | if let Some(signature) = signature { |
| 1178 | value["signature"] = json!(signature); |
| 1179 | } |
| 1180 | Some(value) |
| 1181 | } |
| 1182 | ContentBlock::File { file_id } => Some(json!({ |
| 1183 | "type": "document", |
| 1184 | "source": { |
| 1185 | "type": "file", |
| 1186 | "file_id": file_id, |
| 1187 | }, |
| 1188 | })), |
| 1189 | ContentBlock::ToolSearchToolResult { .. } |
| 1190 | | ContentBlock::CodeExecutionToolResult { .. } |
| 1191 | | ContentBlock::WebSearchCall { .. } |
| 1192 | | ContentBlock::ServerToolCalls { .. } => None, |
| 1193 | } |
| 1194 | } |
| 1195 | |
| 1196 | /// Enforce the prefix-zone breakpoint policy (#3014): |
| 1197 | /// 1. the last tool in the catalog (or, with no tools, the last system |
| 1198 | /// block) — caches the immutable prefix; |
| 1199 | /// 2. the last content block of the most recent user turn — caches the |
| 1200 | /// append-only history. |
| 1201 | /// |
| 1202 | /// Caller-provided breakpoints are preserved, but the total is capped at |
| 1203 | /// [`MAX_CACHE_BREAKPOINTS`] by dropping the earliest markers first (the |
| 1204 | /// latest markers cover the longest prefixes). |
| 1205 | fn apply_anthropic_cache_breakpoints(body: &mut Value) { |
| 1206 | // Place breakpoint 1: prefer the last tool; otherwise last system block. |
| 1207 | let mut placed_prefix = false; |
| 1208 | if let Some(tools) = body.get_mut("tools").and_then(Value::as_array_mut) |
| 1209 | && let Some(last) = tools.last_mut() |
| 1210 | { |
| 1211 | last["cache_control"] = json!({ "type": "ephemeral" }); |
| 1212 | placed_prefix = true; |
| 1213 | } |
| 1214 | if !placed_prefix |
| 1215 | && let Some(system) = body.get_mut("system").and_then(Value::as_array_mut) |
| 1216 | && let Some(last) = system.last_mut() |
| 1217 | { |
| 1218 | last["cache_control"] = json!({ "type": "ephemeral" }); |
| 1219 | } |
| 1220 | |
| 1221 | // Place breakpoint 2: last content block of the latest user message. |
| 1222 | if let Some(messages) = body.get_mut("messages").and_then(Value::as_array_mut) |
| 1223 | && let Some(last_user) = messages |
| 1224 | .iter_mut() |
| 1225 | .rev() |
| 1226 | .find(|message| message.get("role").and_then(Value::as_str) == Some("user")) |
| 1227 | && let Some(last_block) = last_user |
| 1228 | .get_mut("content") |
| 1229 | .and_then(Value::as_array_mut) |
| 1230 | .and_then(|blocks| blocks.last_mut()) |
| 1231 | { |
| 1232 | last_block["cache_control"] = json!({ "type": "ephemeral" }); |
| 1233 | } |
| 1234 | |
| 1235 | // Cap at MAX_CACHE_BREAKPOINTS in render order (tools → system → |
| 1236 | // messages), dropping the earliest extras. |
| 1237 | let mut marked: Vec<*mut Value> = Vec::new(); |
| 1238 | let collect = |value: Option<&mut Value>| { |
| 1239 | let Some(array) = value.and_then(Value::as_array_mut) else { |
| 1240 | return Vec::new(); |
| 1241 | }; |
| 1242 | array |
| 1243 | .iter_mut() |
| 1244 | .filter(|item| item.get("cache_control").is_some()) |
| 1245 | .map(|item| item as *mut Value) |
| 1246 | .collect::<Vec<_>>() |
| 1247 | }; |
| 1248 | marked.extend(collect(body.get_mut("tools"))); |
| 1249 | marked.extend(collect(body.get_mut("system"))); |
| 1250 | if let Some(messages) = body.get_mut("messages").and_then(Value::as_array_mut) { |
| 1251 | for message in messages.iter_mut() { |
| 1252 | if let Some(blocks) = message.get_mut("content").and_then(Value::as_array_mut) { |
| 1253 | marked.extend( |
| 1254 | blocks |
| 1255 | .iter_mut() |
| 1256 | .filter(|block| block.get("cache_control").is_some()) |
| 1257 | .map(|block| block as *mut Value), |
| 1258 | ); |
| 1259 | } |
| 1260 | } |
| 1261 | } |
| 1262 | if marked.len() > MAX_CACHE_BREAKPOINTS { |
| 1263 | let excess = marked.len() - MAX_CACHE_BREAKPOINTS; |
| 1264 | for pointer in marked.into_iter().take(excess) { |
| 1265 | // SAFETY: the pointers were collected from `body`, which is |
| 1266 | // exclusively borrowed for the duration of this function, and |
| 1267 | // each pointer targets a distinct JSON node. |
| 1268 | unsafe { |
| 1269 | if let Some(map) = (*pointer).as_object_mut() { |
| 1270 | map.remove("cache_control"); |
| 1271 | } |
| 1272 | } |
| 1273 | } |
| 1274 | } |
| 1275 | } |
| 1276 | |
| 1277 | /// Provider event types [`convert_anthropic_sse_data`] accepts. Anything else |
| 1278 | /// with a string `type` is tolerated as `None` (future additions); note |
| 1279 | /// `tool_projection_warning` is deliberately absent — it is local-only and |
| 1280 | /// must never decode from provider SSE. |
| 1281 | fn is_known_sse_type(event_type: &str) -> bool { |
| 1282 | matches!( |
| 1283 | event_type, |
| 1284 | "message_start" |
| 1285 | | "content_block_start" |
| 1286 | | "content_block_delta" |
| 1287 | | "content_block_stop" |
| 1288 | | "message_delta" |
| 1289 | | "message_stop" |
| 1290 | | "ping" |
| 1291 | | "error" |
| 1292 | ) |
| 1293 | } |
| 1294 | |
| 1295 | /// Peek at an SSE payload's `type` without building a DOM. |
| 1296 | #[derive(Deserialize)] |
| 1297 | struct SseTagPeek<'a> { |
| 1298 | #[serde(borrow)] |
| 1299 | r#type: Option<&'a str>, |
| 1300 | } |
| 1301 | |
| 1302 | /// Convert one SSE `data:` payload into a [`StreamEvent`], normalizing usage |
| 1303 | /// objects to the #2961 convention. Returns `None` for ignorable payloads. |
| 1304 | /// |
| 1305 | /// #6213 T7: the per-token path deserializes directly into the tagged |
| 1306 | /// [`StreamEvent`] instead of building a `Value` DOM and converting it. |
| 1307 | /// Usage-bearing events (two per stream) keep the exact legacy path — the |
| 1308 | /// usage rewrite reads wire fields the normalized [`Usage`] cannot |
| 1309 | /// represent — and decode failures keep their exact legacy outcomes. |
| 1310 | fn convert_anthropic_sse_data(data: &str) -> Option<Result<StreamEvent>> { |
| 1311 | let trimmed = data.trim(); |
| 1312 | if trimmed.is_empty() { |
| 1313 | return None; |
| 1314 | } |
| 1315 | let usage_event = matches!( |
| 1316 | serde_json::from_str::<SseTagPeek>(trimmed).map(|peek| peek.r#type), |
| 1317 | Ok(Some("message_start" | "message_delta")) |
| 1318 | ); |
| 1319 | if usage_event { |
| 1320 | return convert_anthropic_sse_usage_event(trimmed); |
| 1321 | } |
| 1322 | match serde_json::from_str::<StreamEvent>(trimmed) { |
| 1323 | // Local-only receipt: the legacy path ignored it (not a provider |
| 1324 | // type), so it stays ignored rather than decoding. |
| 1325 | Ok(StreamEvent::ToolProjectionWarning { .. }) => None, |
| 1326 | Ok(mut event) => { |
| 1327 | if let StreamEvent::ContentBlockStart { |
| 1328 | content_block: ContentBlockStart::ToolUse { name, .. }, |
| 1329 | .. |
| 1330 | } = &mut event |
| 1331 | { |
| 1332 | *name = from_api_tool_name(name); |
| 1333 | } |
| 1334 | Some(Ok(event)) |
| 1335 | } |
| 1336 | Err(error) => { |
| 1337 | // Cold path, reached only when direct decode fails: invalid JSON |
| 1338 | // and unknown types keep their exact legacy outcomes. |
| 1339 | let value: Value = match serde_json::from_str(trimmed) { |
| 1340 | Ok(value) => value, |
| 1341 | Err(e) => return Some(Err(anyhow::anyhow!("invalid SSE JSON: {e}"))), |
| 1342 | }; |
| 1343 | match value.get("type").and_then(Value::as_str) { |
| 1344 | // Tolerate unknown event types (e.g. future additions) silently. |
| 1345 | Some(known) if !is_known_sse_type(known) => None, |
| 1346 | _ => Some(Err(anyhow::anyhow!("unrecognized SSE event: {error}"))), |
| 1347 | } |
| 1348 | } |
| 1349 | } |
| 1350 | } |
| 1351 | |
| 1352 | /// Legacy `Value` path for `message_start`/`message_delta`: the usage |
| 1353 | /// rewrite reads wire fields the normalized [`Usage`] cannot represent, so |
| 1354 | /// these two events normalize before decoding, exactly as before. |
| 1355 | fn convert_anthropic_sse_usage_event(trimmed: &str) -> Option<Result<StreamEvent>> { |
| 1356 | let mut value: Value = match serde_json::from_str(trimmed) { |
| 1357 | Ok(value) => value, |
| 1358 | Err(e) => return Some(Err(anyhow::anyhow!("invalid SSE JSON: {e}"))), |
| 1359 | }; |
| 1360 | |
| 1361 | match value.get("type").and_then(Value::as_str) { |
| 1362 | Some("message_start") => { |
| 1363 | if let Some(message) = value.get_mut("message") { |
| 1364 | discard_provider_execution_ids(message); |
| 1365 | if let Some(usage) = message.get_mut("usage") { |
| 1366 | *usage = json!(parse_anthropic_usage(usage)); |
| 1367 | } |
| 1368 | } |
| 1369 | } |
| 1370 | Some("message_delta") => { |
| 1371 | let top_title = value.get("title").cloned(); |
| 1372 | let top_stop_details = value.get("stop_details").cloned(); |
| 1373 | if let Some(delta) = value.get_mut("delta").and_then(Value::as_object_mut) { |
| 1374 | if !delta.contains_key("title") |
| 1375 | && let Some(title) = top_title |
| 1376 | { |
| 1377 | delta.insert("title".to_string(), title); |
| 1378 | } |
| 1379 | if !delta.contains_key("stop_details") |
| 1380 | && let Some(stop_details) = top_stop_details |
| 1381 | { |
| 1382 | delta.insert("stop_details".to_string(), stop_details); |
| 1383 | } |
| 1384 | } |
| 1385 | if let Some(usage) = value.get_mut("usage") { |
| 1386 | *usage = json!(parse_anthropic_usage(usage)); |
| 1387 | } |
| 1388 | } |
| 1389 | // Tolerate unknown event types (e.g. future additions) silently. |
| 1390 | Some(known) if !is_known_sse_type(known) => { |
| 1391 | return None; |
| 1392 | } |
| 1393 | _ => {} |
| 1394 | } |
| 1395 | |
| 1396 | Some(serde_json::from_value(value).map_err(|e| anyhow::anyhow!("unrecognized SSE event: {e}"))) |
| 1397 | } |
| 1398 | |
| 1399 | /// Map Anthropic's usage payload onto the normalized [`Usage`] convention |
| 1400 | /// (#2961 / #4318): hit = cache reads, write = cache creation, miss = raw |
| 1401 | /// uncached input, `input_tokens` = the total prompt across all three. |
| 1402 | fn parse_anthropic_usage(usage: &Value) -> Usage { |
| 1403 | let field = |name: &str| { |
| 1404 | usage |
| 1405 | .get(name) |
| 1406 | .and_then(Value::as_u64) |
| 1407 | .and_then(|value| u32::try_from(value).ok()) |
| 1408 | .unwrap_or(0) |
| 1409 | }; |
| 1410 | let input_raw = field("input_tokens"); |
| 1411 | let cache_creation = field("cache_creation_input_tokens"); |
| 1412 | let cache_read = field("cache_read_input_tokens"); |
| 1413 | let output = field("output_tokens"); |
| 1414 | |
| 1415 | let server_tool_use = super::wire::parse_server_tool_usage(Some(usage)); |
| 1416 | let safety_tokens = super::wire::parse_safety_tokens(Some(usage)); |
| 1417 | |
| 1418 | Usage { |
| 1419 | input_tokens: input_raw |
| 1420 | .saturating_add(cache_creation) |
| 1421 | .saturating_add(cache_read), |
| 1422 | output_tokens: output, |
| 1423 | prompt_cache_hit_tokens: Some(cache_read), |
| 1424 | prompt_cache_miss_tokens: Some(input_raw), |
| 1425 | prompt_cache_write_tokens: Some(cache_creation), |
| 1426 | reasoning_tokens: None, |
| 1427 | reasoning_replay_tokens: None, |
| 1428 | server_tool_use, |
| 1429 | safety_tokens, |
| 1430 | |
| 1431 | input_audio_tokens: None, |
| 1432 | output_audio_tokens: None, |
| 1433 | |
| 1434 | request_usages: Vec::new(), |
| 1435 | } |
| 1436 | } |
| 1437 | |
| 1438 | /// Extract `error.type` / `error.message` from an Anthropic error envelope |
| 1439 | /// (`{"type":"error","error":{"type":...,"message":...}}`), falling back to |
| 1440 | /// the raw body so nothing is swallowed. |
| 1441 | fn anthropic_error_fields(error: &Value) -> (String, String) { |
| 1442 | let error_type = error |
| 1443 | .get("type") |
| 1444 | .and_then(Value::as_str) |
| 1445 | .unwrap_or("unknown") |
| 1446 | .to_string(); |
| 1447 | let message = error |
| 1448 | .get("message") |
| 1449 | .and_then(Value::as_str) |
| 1450 | .map(str::to_string) |
| 1451 | .unwrap_or_else(|| error.to_string()); |
| 1452 | (error_type, message) |
| 1453 | } |
| 1454 | |
| 1455 | #[cfg(test)] |
| 1456 | mod tests { |
| 1457 | use super::*; |
| 1458 | use codewhale_models::Role; |
| 1459 | use codewhale_models::{CacheControl, Message, SystemBlock, SystemPrompt, Tool}; |
| 1460 | |
| 1461 | #[test] |
| 1462 | fn provider_messages_cannot_supply_host_execution_identity() { |
| 1463 | for supplied in [json!("forged-local"), json!({"invalid": "host id"})] { |
| 1464 | let value = json!({ |
| 1465 | "id": "provider-message", "type": "message", "role": "assistant", |
| 1466 | "model": "claude-sonnet-4-6", "stop_reason": "tool_use", |
| 1467 | "content": [ |
| 1468 | {"type": "tool_use", "id": "wire-call", "name": "read", |
| 1469 | "input": {"execution_id": "ordinary argument"}, |
| 1470 | "execution_id": supplied, |
| 1471 | "caller": {"type": "code_execution", "tool_id": "parent-wire"}, |
| 1472 | "thought_signature": "provider-signature"}, |
| 1473 | {"type": "tool_result", "tool_use_id": "wire-call", "content": "result", |
| 1474 | "execution_id": supplied}, |
| 1475 | ], |
| 1476 | "usage": {"input_tokens": 3, "output_tokens": 2}, |
| 1477 | }); |
| 1478 | let decoded = decode_anthropic_message(value.clone()).unwrap(); |
| 1479 | let event = convert_anthropic_sse_data( |
| 1480 | &json!({ |
| 1481 | "type": "message_start", "message": value, |
| 1482 | }) |
| 1483 | .to_string(), |
| 1484 | ) |
| 1485 | .unwrap() |
| 1486 | .unwrap(); |
| 1487 | let StreamEvent::MessageStart { message: streamed } = event else { |
| 1488 | panic!("expected message start") |
| 1489 | }; |
| 1490 | for message in [decoded, streamed] { |
| 1491 | let ContentBlock::ToolUse { |
| 1492 | id, |
| 1493 | input, |
| 1494 | execution_id, |
| 1495 | caller, |
| 1496 | thought_signature, |
| 1497 | .. |
| 1498 | } = &message.content[0] |
| 1499 | else { |
| 1500 | panic!("expected tool use") |
| 1501 | }; |
| 1502 | assert!(execution_id.is_none()); |
| 1503 | assert_eq!(id, "wire-call"); |
| 1504 | assert_eq!(input["execution_id"], "ordinary argument"); |
| 1505 | assert_eq!( |
| 1506 | caller.as_ref().unwrap().tool_id.as_deref(), |
| 1507 | Some("parent-wire") |
| 1508 | ); |
| 1509 | assert_eq!(thought_signature.as_deref(), Some("provider-signature")); |
| 1510 | assert!(matches!( |
| 1511 | &message.content[1], |
| 1512 | ContentBlock::ToolResult { |
| 1513 | execution_id: None, |
| 1514 | .. |
| 1515 | } |
| 1516 | )); |
| 1517 | assert_eq!(message.usage.input_tokens, 3); |
| 1518 | } |
| 1519 | } |
| 1520 | } |
| 1521 | |
| 1522 | #[test] |
| 1523 | fn over_long_encoded_tool_names_are_withheld_at_128() { |
| 1524 | let client = anthropic_test_client(None); |
| 1525 | let tool = |name: &str| Tool { |
| 1526 | tool_type: None, |
| 1527 | name: name.to_string(), |
| 1528 | description: "d".to_string(), |
| 1529 | input_schema: json!({"type": "object", "additionalProperties": false}), |
| 1530 | allowed_callers: None, |
| 1531 | defer_loading: None, |
| 1532 | input_examples: None, |
| 1533 | strict: None, |
| 1534 | cache_control: None, |
| 1535 | }; |
| 1536 | let mid = "mcp__tracker__projects.v2.issues.list-by-assignee"; |
| 1537 | let long = format!( |
| 1538 | "mcp__tracker__{}.v2.issues.list-by-assignee", |
| 1539 | "a".repeat(70) |
| 1540 | ); |
| 1541 | assert!(to_api_tool_name(mid).len() > 64 && to_api_tool_name(mid).len() <= 128); |
| 1542 | assert!(to_api_tool_name(&long).len() > 128); |
| 1543 | |
| 1544 | let mut request = request_with("claude-sonnet-4-6", None, None, None); |
| 1545 | request.tools = Some(vec![tool("read_file"), tool(mid), tool(&long)]); |
| 1546 | let (body, omitted) = client |
| 1547 | .build_anthropic_wire_body(&request, true) |
| 1548 | .expect("body builds"); |
| 1549 | let sent: Vec<&str> = body["tools"] |
| 1550 | .as_array() |
| 1551 | .expect("tools") |
| 1552 | .iter() |
| 1553 | .filter_map(|t| t["name"].as_str()) |
| 1554 | .collect(); |
| 1555 | assert_eq!(sent, vec!["read_file".to_string(), to_api_tool_name(mid)]); |
| 1556 | assert_eq!(omitted, vec![to_api_tool_name(&long)]); |
| 1557 | |
| 1558 | request.tool_choice = Some(json!({"type": "tool", "name": long})); |
| 1559 | let error = client |
| 1560 | .build_anthropic_wire_body(&request, true) |
| 1561 | .expect_err("forcing a withheld tool is refused"); |
| 1562 | assert!(error.to_string().contains("at most 128"), "{error}"); |
| 1563 | } |
| 1564 | |
| 1565 | #[test] |
| 1566 | fn a_100_character_encoded_name_is_offered_on_an_anthropic_wire_route_without_a_documented_limit() |
| 1567 | { |
| 1568 | let tool = |name: &str| Tool { |
| 1569 | tool_type: None, |
| 1570 | name: name.to_string(), |
| 1571 | description: "d".to_string(), |
| 1572 | input_schema: json!({"type": "object", "additionalProperties": false}), |
| 1573 | allowed_callers: None, |
| 1574 | defer_loading: None, |
| 1575 | input_examples: None, |
| 1576 | strict: None, |
| 1577 | cache_control: None, |
| 1578 | }; |
| 1579 | let name = "a".repeat(100); |
| 1580 | assert_eq!(to_api_tool_name(&name).len(), 100); |
| 1581 | let client = minimax_test_client(); |
| 1582 | let mut request = request_with("MiniMax-M2", None, None, None); |
| 1583 | request.tools = Some(vec![tool(&name)]); |
| 1584 | let (body, omitted) = client |
| 1585 | .build_anthropic_wire_body(&request, true) |
| 1586 | .expect("body builds"); |
| 1587 | assert_eq!(body["tools"][0]["name"], name); |
| 1588 | assert!(omitted.is_empty()); |
| 1589 | } |
| 1590 | |
| 1591 | fn request_with( |
| 1592 | model: &str, |
| 1593 | reasoning_effort: Option<&str>, |
| 1594 | temperature: Option<f32>, |
| 1595 | top_p: Option<f32>, |
| 1596 | ) -> MessageRequest { |
| 1597 | MessageRequest { |
| 1598 | model: model.to_string(), |
| 1599 | messages: vec![Message { |
| 1600 | role: Role::User, |
| 1601 | content: vec![ContentBlock::Text { |
| 1602 | text: "hello".to_string(), |
| 1603 | cache_control: None, |
| 1604 | }], |
| 1605 | }], |
| 1606 | max_tokens: 1024, |
| 1607 | system: Some(SystemPrompt::Blocks(vec![SystemBlock { |
| 1608 | block_type: "text".to_string(), |
| 1609 | text: "be helpful".to_string(), |
| 1610 | cache_control: Some(CacheControl { |
| 1611 | cache_type: "ephemeral".to_string(), |
| 1612 | }), |
| 1613 | }])), |
| 1614 | tools: None, |
| 1615 | tool_choice: None, |
| 1616 | metadata: None, |
| 1617 | thinking: None, |
| 1618 | reasoning_effort: reasoning_effort.map(str::to_string), |
| 1619 | stream: Some(true), |
| 1620 | temperature, |
| 1621 | top_p, |
| 1622 | safety_check: None, |
| 1623 | title: None, |
| 1624 | } |
| 1625 | } |
| 1626 | |
| 1627 | fn test_client() -> CodewhaleClient { |
| 1628 | anthropic_test_client(None) |
| 1629 | } |
| 1630 | |
| 1631 | /// #6378: the engine stores each tool result as its own user message, so |
| 1632 | /// a parallel batch reaches the wire as `assistant{a, b}`, `user{a}`, |
| 1633 | /// `user{b}`. Both results must land in the one user turn after the batch, |
| 1634 | /// and the dangling-use repair must not answer `b` a second time. |
| 1635 | #[test] |
| 1636 | fn parallel_tool_results_split_across_user_turns_are_answered_once() { |
| 1637 | let client = test_client(); |
| 1638 | let mut request = request_with("claude-sonnet-4-6", None, None, None); |
| 1639 | let tool_use = |id: &str, path: &str| ContentBlock::ToolUse { |
| 1640 | execution_id: None, |
| 1641 | id: id.to_string(), |
| 1642 | name: "read".to_string(), |
| 1643 | input: json!({ "path": path }), |
| 1644 | caller: None, |
| 1645 | thought_signature: None, |
| 1646 | }; |
| 1647 | let tool_result = |id: &str, content: &str| ContentBlock::ToolResult { |
| 1648 | execution_id: None, |
| 1649 | tool_use_id: id.to_string(), |
| 1650 | content: content.to_string(), |
| 1651 | is_error: Some(false), |
| 1652 | content_blocks: None, |
| 1653 | }; |
| 1654 | request.messages = vec![ |
| 1655 | Message { |
| 1656 | role: Role::User, |
| 1657 | content: vec![ContentBlock::Text { |
| 1658 | text: "Read a.txt and b.txt".to_string(), |
| 1659 | cache_control: None, |
| 1660 | }], |
| 1661 | }, |
| 1662 | Message { |
| 1663 | role: Role::Assistant, |
| 1664 | content: vec![ |
| 1665 | ContentBlock::Text { |
| 1666 | text: "I will read both files in parallel.".to_string(), |
| 1667 | cache_control: None, |
| 1668 | }, |
| 1669 | tool_use("toolu_a", "a.txt"), |
| 1670 | tool_use("toolu_b", "b.txt"), |
| 1671 | ], |
| 1672 | }, |
| 1673 | Message { |
| 1674 | role: Role::User, |
| 1675 | content: vec![tool_result("toolu_a", "content of file A")], |
| 1676 | }, |
| 1677 | Message { |
| 1678 | role: Role::User, |
| 1679 | content: vec![tool_result("toolu_b", "content of file B")], |
| 1680 | }, |
| 1681 | ]; |
| 1682 | |
| 1683 | let body = client.build_anthropic_body(&request, true); |
| 1684 | let messages = body["messages"].as_array().expect("messages array"); |
| 1685 | assert_eq!( |
| 1686 | messages.len(), |
| 1687 | 3, |
| 1688 | "both results share one user turn: {body}" |
| 1689 | ); |
| 1690 | let results = messages[2]["content"].as_array().expect("user content"); |
| 1691 | assert_eq!( |
| 1692 | results |
| 1693 | .iter() |
| 1694 | .map(|block| (block["tool_use_id"].as_str(), block["content"].as_str())) |
| 1695 | .collect::<Vec<_>>(), |
| 1696 | vec![ |
| 1697 | (Some("toolu_a"), Some("content of file A")), |
| 1698 | (Some("toolu_b"), Some("content of file B")), |
| 1699 | ], |
| 1700 | "{body}" |
| 1701 | ); |
| 1702 | assert!( |
| 1703 | results.iter().all(|block| block.get("is_error").is_none()), |
| 1704 | "{body}" |
| 1705 | ); |
| 1706 | assert!(!body.to_string().contains(UNEXECUTED_TOOL_RESULT), "{body}"); |
| 1707 | } |
| 1708 | |
| 1709 | fn anthropic_test_client(base_url: Option<&str>) -> CodewhaleClient { |
| 1710 | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 1711 | let config = { |
| 1712 | let __cw_config_init_0_0 = Some("anthropic".to_string()); |
| 1713 | let __cw_config_init_0_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1714 | anthropic: codewhale_runtime::config::ProviderConfig { |
| 1715 | api_key: Some("test-key".to_string()), |
| 1716 | base_url: base_url.map(str::to_string), |
| 1717 | ..Default::default() |
| 1718 | }, |
| 1719 | ..Default::default() |
| 1720 | }); |
| 1721 | let mut __cw_config_init_0_value: codewhale_runtime::config::Config = |
| 1722 | Default::default(); |
| 1723 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 1724 | __cw_config_init_0_value.providers = __cw_config_init_0_1; |
| 1725 | __cw_config_init_0_value |
| 1726 | }; |
| 1727 | CodewhaleClient::new(&config).expect("anthropic client constructs") |
| 1728 | } |
| 1729 | |
| 1730 | fn minimax_test_client() -> CodewhaleClient { |
| 1731 | minimax_test_client_for( |
| 1732 | codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_ANTHROPIC_BASE_URL, |
| 1733 | ) |
| 1734 | } |
| 1735 | |
| 1736 | fn minimax_test_client_for(base_url: &str) -> CodewhaleClient { |
| 1737 | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 1738 | let config = { |
| 1739 | let __cw_config_init_1_0 = Some("minimax-anthropic".to_string()); |
| 1740 | let __cw_config_init_1_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1741 | minimax_anthropic: codewhale_runtime::config::ProviderConfig { |
| 1742 | api_key: Some("test-key".to_string()), |
| 1743 | base_url: Some(base_url.to_string()), |
| 1744 | ..Default::default() |
| 1745 | }, |
| 1746 | ..Default::default() |
| 1747 | }); |
| 1748 | let mut __cw_config_init_1_value: codewhale_runtime::config::Config = |
| 1749 | Default::default(); |
| 1750 | __cw_config_init_1_value.provider = __cw_config_init_1_0; |
| 1751 | __cw_config_init_1_value.providers = __cw_config_init_1_1; |
| 1752 | __cw_config_init_1_value |
| 1753 | }; |
| 1754 | CodewhaleClient::new(&config).expect("MiniMax Messages client constructs") |
| 1755 | } |
| 1756 | |
| 1757 | fn deepseek_test_client(base_url: &str) -> CodewhaleClient { |
| 1758 | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 1759 | let config = { |
| 1760 | let __cw_config_init_2_0 = Some("deepseek-anthropic".to_string()); |
| 1761 | let __cw_config_init_2_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1762 | deepseek_anthropic: codewhale_runtime::config::ProviderConfig { |
| 1763 | api_key: Some("test-key".to_string()), |
| 1764 | base_url: Some(base_url.to_string()), |
| 1765 | ..Default::default() |
| 1766 | }, |
| 1767 | ..Default::default() |
| 1768 | }); |
| 1769 | let mut __cw_config_init_2_value: codewhale_runtime::config::Config = |
| 1770 | Default::default(); |
| 1771 | __cw_config_init_2_value.provider = __cw_config_init_2_0; |
| 1772 | __cw_config_init_2_value.providers = __cw_config_init_2_1; |
| 1773 | __cw_config_init_2_value |
| 1774 | }; |
| 1775 | CodewhaleClient::new(&config).expect("DeepSeek Messages client constructs") |
| 1776 | } |
| 1777 | |
| 1778 | fn modelstudio_test_client(base_url: &str) -> CodewhaleClient { |
| 1779 | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 1780 | let config = { |
| 1781 | let __cw_config_init_3_0 = Some("modelstudio-token-plan-anthropic".to_string()); |
| 1782 | let __cw_config_init_3_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1783 | // Durable secret-store keys share a family slot, but a literal |
| 1784 | // config key belongs to the selected route's own table. |
| 1785 | modelstudio_token_plan_anthropic: codewhale_runtime::config::ProviderConfig { |
| 1786 | api_key: Some("test-key".to_string()), |
| 1787 | base_url: Some(base_url.to_string()), |
| 1788 | ..Default::default() |
| 1789 | }, |
| 1790 | ..Default::default() |
| 1791 | }); |
| 1792 | let mut __cw_config_init_3_value: codewhale_runtime::config::Config = |
| 1793 | Default::default(); |
| 1794 | __cw_config_init_3_value.provider = __cw_config_init_3_0; |
| 1795 | __cw_config_init_3_value.providers = __cw_config_init_3_1; |
| 1796 | __cw_config_init_3_value |
| 1797 | }; |
| 1798 | CodewhaleClient::new(&config).expect("Model Studio Messages client constructs") |
| 1799 | } |
| 1800 | |
| 1801 | #[test] |
| 1802 | fn dotted_tool_names_stay_inside_the_anthropic_pattern_and_decode_back() { |
| 1803 | let client = test_client(); |
| 1804 | let mut request = request_with("claude-sonnet-4-6", None, None, None); |
| 1805 | let tool = |name: &str| Tool { |
| 1806 | tool_type: None, |
| 1807 | name: name.to_string(), |
| 1808 | description: "d".to_string(), |
| 1809 | input_schema: json!({"type": "object", "additionalProperties": false}), |
| 1810 | allowed_callers: None, |
| 1811 | defer_loading: None, |
| 1812 | input_examples: None, |
| 1813 | strict: None, |
| 1814 | cache_control: None, |
| 1815 | }; |
| 1816 | request.tools = Some(vec![tool("read_file"), tool("web.run")]); |
| 1817 | request.tool_choice = Some(json!({"type": "tool", "name": "web.run"})); |
| 1818 | request.messages.push(Message { |
| 1819 | role: Role::Assistant, |
| 1820 | content: vec![ContentBlock::ToolUse { |
| 1821 | execution_id: None, |
| 1822 | id: "toolu_w".to_string(), |
| 1823 | name: "web.run".to_string(), |
| 1824 | input: json!({}), |
| 1825 | caller: None, |
| 1826 | thought_signature: None, |
| 1827 | }], |
| 1828 | }); |
| 1829 | |
| 1830 | let body = client.build_anthropic_body(&request, true); |
| 1831 | let valid = |name: &str| { |
| 1832 | (1..=128).contains(&name.len()) |
| 1833 | && name |
| 1834 | .chars() |
| 1835 | .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') |
| 1836 | }; |
| 1837 | let mut sent = Vec::new(); |
| 1838 | for tool in body["tools"].as_array().expect("tools") { |
| 1839 | sent.push(tool["name"].as_str().expect("tool name").to_string()); |
| 1840 | } |
| 1841 | sent.push( |
| 1842 | body.pointer("/tool_choice/name") |
| 1843 | .and_then(Value::as_str) |
| 1844 | .expect("forced tool name") |
| 1845 | .to_string(), |
| 1846 | ); |
| 1847 | for message in body["messages"].as_array().expect("messages") { |
| 1848 | for block in message["content"].as_array().into_iter().flatten() { |
| 1849 | if block["type"] == "tool_use" { |
| 1850 | sent.push(block["name"].as_str().expect("tool_use name").to_string()); |
| 1851 | } |
| 1852 | } |
| 1853 | } |
| 1854 | assert!(sent.iter().all(|name| valid(name)), "{sent:?}"); |
| 1855 | assert!(sent.iter().any(|name| name != "read_file"), "{sent:?}"); |
| 1856 | |
| 1857 | let wire = to_api_tool_name("web.run"); |
| 1858 | let message = decode_anthropic_message(json!({ |
| 1859 | "id": "m", "type": "message", "role": "assistant", |
| 1860 | "model": "claude-sonnet-4-6", "stop_reason": "tool_use", |
| 1861 | "content": [{"type": "tool_use", "id": "toolu_w", "name": wire, "input": {}}], |
| 1862 | "usage": {"input_tokens": 1, "output_tokens": 1}, |
| 1863 | })) |
| 1864 | .unwrap(); |
| 1865 | let ContentBlock::ToolUse { name, .. } = &message.content[0] else { |
| 1866 | panic!("expected tool_use") |
| 1867 | }; |
| 1868 | assert_eq!(name, "web.run"); |
| 1869 | |
| 1870 | let event = convert_anthropic_sse_data( |
| 1871 | &json!({ |
| 1872 | "type": "content_block_start", "index": 0, |
| 1873 | "content_block": {"type": "tool_use", "id": "toolu_w", "name": wire, "input": {}}, |
| 1874 | }) |
| 1875 | .to_string(), |
| 1876 | ) |
| 1877 | .unwrap() |
| 1878 | .unwrap(); |
| 1879 | let StreamEvent::ContentBlockStart { |
| 1880 | content_block: codewhale_models::ContentBlockStart::ToolUse { name, .. }, |
| 1881 | .. |
| 1882 | } = event |
| 1883 | else { |
| 1884 | panic!("expected tool_use start") |
| 1885 | }; |
| 1886 | assert_eq!(name, "web.run"); |
| 1887 | } |
| 1888 | |
| 1889 | #[test] |
| 1890 | fn body_keeps_native_cache_control_on_system_and_tools() { |
| 1891 | let client = test_client(); |
| 1892 | let mut request = request_with("claude-sonnet-4-6", Some("high"), None, None); |
| 1893 | request.tools = Some(vec![Tool { |
| 1894 | tool_type: None, |
| 1895 | name: "read_file".to_string(), |
| 1896 | description: "Read a file".to_string(), |
| 1897 | input_schema: json!({"type": "object", "additionalProperties": false}), |
| 1898 | allowed_callers: None, |
| 1899 | defer_loading: None, |
| 1900 | input_examples: None, |
| 1901 | strict: Some(true), |
| 1902 | cache_control: None, |
| 1903 | }]); |
| 1904 | |
| 1905 | let body = client.build_anthropic_body(&request, true); |
| 1906 | |
| 1907 | assert_eq!( |
| 1908 | body.pointer("/system/0/cache_control/type") |
| 1909 | .and_then(Value::as_str), |
| 1910 | Some("ephemeral"), |
| 1911 | "system cache_control must survive natively: {body}" |
| 1912 | ); |
| 1913 | assert_eq!( |
| 1914 | body.pointer("/tools/0/strict").and_then(Value::as_bool), |
| 1915 | Some(true) |
| 1916 | ); |
| 1917 | assert_eq!( |
| 1918 | body.pointer("/tools/0/cache_control/type") |
| 1919 | .and_then(Value::as_str), |
| 1920 | Some("ephemeral"), |
| 1921 | "breakpoint 1 lands on the last tool: {body}" |
| 1922 | ); |
| 1923 | // Breakpoint 2 lands on the latest user turn's last block. |
| 1924 | assert_eq!( |
| 1925 | body.pointer("/messages/0/content/0/cache_control/type") |
| 1926 | .and_then(Value::as_str), |
| 1927 | Some("ephemeral") |
| 1928 | ); |
| 1929 | } |
| 1930 | |
| 1931 | #[test] |
| 1932 | fn body_maps_reasoning_effort_to_adaptive_thinking_and_effort() { |
| 1933 | let client = test_client(); |
| 1934 | |
| 1935 | let body = client.build_anthropic_body( |
| 1936 | &request_with("claude-sonnet-4-6", Some("high"), None, None), |
| 1937 | true, |
| 1938 | ); |
| 1939 | assert_eq!( |
| 1940 | body.pointer("/thinking/type").and_then(Value::as_str), |
| 1941 | Some("adaptive") |
| 1942 | ); |
| 1943 | assert_eq!( |
| 1944 | body.pointer("/output_config/effort") |
| 1945 | .and_then(Value::as_str), |
| 1946 | Some("high") |
| 1947 | ); |
| 1948 | |
| 1949 | let body = client.build_anthropic_body( |
| 1950 | &request_with("claude-opus-4-8", Some("xhigh"), None, None), |
| 1951 | true, |
| 1952 | ); |
| 1953 | assert_eq!( |
| 1954 | body.pointer("/output_config/effort") |
| 1955 | .and_then(Value::as_str), |
| 1956 | Some("max") |
| 1957 | ); |
| 1958 | |
| 1959 | let offering = |model: &str| { |
| 1960 | client |
| 1961 | .catalog_facts_for_model(model) |
| 1962 | .unwrap_or_else(|| panic!("bundled catalog carries {model}")) |
| 1963 | }; |
| 1964 | let mut xhigh_client = test_client(); |
| 1965 | xhigh_client.route_facts = Some(offering("claude-opus-4-8")); |
| 1966 | let body = xhigh_client.build_anthropic_body( |
| 1967 | &request_with("claude-opus-4-8", Some("xhigh"), None, None), |
| 1968 | true, |
| 1969 | ); |
| 1970 | assert_eq!( |
| 1971 | body.pointer("/output_config/effort") |
| 1972 | .and_then(Value::as_str), |
| 1973 | Some("xhigh"), |
| 1974 | "a row that lists xhigh is sent xhigh: {body}" |
| 1975 | ); |
| 1976 | let mut no_xhigh_client = test_client(); |
| 1977 | no_xhigh_client.route_facts = Some(offering("claude-sonnet-4-6")); |
| 1978 | let body = no_xhigh_client.build_anthropic_body( |
| 1979 | &request_with("claude-sonnet-4-6", Some("xhigh"), None, None), |
| 1980 | true, |
| 1981 | ); |
| 1982 | assert_eq!( |
| 1983 | body.pointer("/output_config/effort") |
| 1984 | .and_then(Value::as_str), |
| 1985 | Some("max"), |
| 1986 | "a row without xhigh keeps the max mapping: {body}" |
| 1987 | ); |
| 1988 | |
| 1989 | let body = client.build_anthropic_body( |
| 1990 | &request_with("claude-sonnet-4-6", Some("off"), None, None), |
| 1991 | true, |
| 1992 | ); |
| 1993 | assert!(body.get("thinking").is_none(), "off omits thinking: {body}"); |
| 1994 | assert!(body.get("output_config").is_none()); |
| 1995 | |
| 1996 | // A model the reviewed catalog does not carry is not thinking-capable: |
| 1997 | // no thinking, no effort. `claude-3-5-haiku-latest` (and Haiku 4.5, |
| 1998 | // which the reviewed catalog now marks `reasoning: true`) are not |
| 1999 | // interchangeable here. |
| 2000 | let body = client.build_anthropic_body( |
| 2001 | &request_with("claude-3-5-haiku-latest", Some("high"), None, None), |
| 2002 | true, |
| 2003 | ); |
| 2004 | assert!(body.get("thinking").is_none(), "{body}"); |
| 2005 | assert!(body.get("output_config").is_none(), "{body}"); |
| 2006 | } |
| 2007 | |
| 2008 | #[test] |
| 2009 | fn compat_gateway_sends_enabled_budget_thinking_instead_of_adaptive() { |
| 2010 | // #4978: strict Anthropic-compatible gateways (e.g. Sensenova) reject |
| 2011 | // {"type":"adaptive"} with a 400; non-native routes must send the |
| 2012 | // documented enabled+budget shape and no output_config. |
| 2013 | let client = anthropic_test_client(Some("https://api.sensenova.example/v1")); |
| 2014 | |
| 2015 | let mut request = request_with("claude-sonnet-4-6", Some("high"), None, None); |
| 2016 | request.max_tokens = 64_000; |
| 2017 | let body = client.build_anthropic_body(&request, true); |
| 2018 | assert_eq!( |
| 2019 | body.pointer("/thinking/type").and_then(Value::as_str), |
| 2020 | Some("enabled"), |
| 2021 | "{body}" |
| 2022 | ); |
| 2023 | assert_eq!( |
| 2024 | body.pointer("/thinking/budget_tokens") |
| 2025 | .and_then(Value::as_u64), |
| 2026 | Some(16_384) |
| 2027 | ); |
| 2028 | assert!(body.get("output_config").is_none(), "{body}"); |
| 2029 | |
| 2030 | // Effort tiers map onto budgets, capped below max_tokens. |
| 2031 | let mut request = request_with("claude-sonnet-4-6", Some("max"), None, None); |
| 2032 | request.max_tokens = 64_000; |
| 2033 | let body = client.build_anthropic_body(&request, true); |
| 2034 | assert_eq!( |
| 2035 | body.pointer("/thinking/budget_tokens") |
| 2036 | .and_then(Value::as_u64), |
| 2037 | Some(32_768) |
| 2038 | ); |
| 2039 | let mut request = request_with("claude-sonnet-4-6", Some("max"), None, None); |
| 2040 | request.max_tokens = 8_000; |
| 2041 | let body = client.build_anthropic_body(&request, true); |
| 2042 | assert_eq!( |
| 2043 | body.pointer("/thinking/budget_tokens") |
| 2044 | .and_then(Value::as_u64), |
| 2045 | Some(7_999), |
| 2046 | "budget stays below max_tokens: {body}" |
| 2047 | ); |
| 2048 | |
| 2049 | // Unspecified effort defaults to the "high" tier. |
| 2050 | let mut request = request_with("claude-sonnet-4-6", None, None, None); |
| 2051 | request.max_tokens = 64_000; |
| 2052 | let body = client.build_anthropic_body(&request, true); |
| 2053 | assert_eq!( |
| 2054 | body.pointer("/thinking/type").and_then(Value::as_str), |
| 2055 | Some("enabled") |
| 2056 | ); |
| 2057 | assert_eq!( |
| 2058 | body.pointer("/thinking/budget_tokens") |
| 2059 | .and_then(Value::as_u64), |
| 2060 | Some(16_384) |
| 2061 | ); |
| 2062 | |
| 2063 | // "off" and requests too small for the 1024-token minimum budget |
| 2064 | // omit thinking entirely. |
| 2065 | let mut request = request_with("claude-sonnet-4-6", Some("off"), None, None); |
| 2066 | request.max_tokens = 64_000; |
| 2067 | let body = client.build_anthropic_body(&request, true); |
| 2068 | assert!(body.get("thinking").is_none(), "{body}"); |
| 2069 | let body = client.build_anthropic_body( |
| 2070 | &request_with("claude-sonnet-4-6", Some("high"), None, None), |
| 2071 | true, |
| 2072 | ); |
| 2073 | assert!( |
| 2074 | body.get("thinking").is_none(), |
| 2075 | "max_tokens=1024 cannot fit the minimum budget: {body}" |
| 2076 | ); |
| 2077 | |
| 2078 | // The native route keeps adaptive; the compat shape is only for |
| 2079 | // non-anthropic.com hosts. |
| 2080 | let native = test_client().build_anthropic_body( |
| 2081 | &request_with("claude-sonnet-4-6", Some("high"), None, None), |
| 2082 | true, |
| 2083 | ); |
| 2084 | assert_eq!( |
| 2085 | native.pointer("/thinking/type").and_then(Value::as_str), |
| 2086 | Some("adaptive") |
| 2087 | ); |
| 2088 | } |
| 2089 | |
| 2090 | #[test] |
| 2091 | fn dangling_tool_use_gets_placeholder_tool_result() { |
| 2092 | // #5002: an orphaned tool_use with no matching tool_result poisons |
| 2093 | // the conversation with repeated 400s; request preparation must |
| 2094 | // repair it with an explicit placeholder result. |
| 2095 | let client = test_client(); |
| 2096 | let mut request = request_with("claude-sonnet-4-6", None, None, None); |
| 2097 | request.messages = vec![ |
| 2098 | Message { |
| 2099 | role: Role::User, |
| 2100 | content: vec![ContentBlock::Text { |
| 2101 | text: "run both tools".to_string(), |
| 2102 | cache_control: None, |
| 2103 | }], |
| 2104 | }, |
| 2105 | Message { |
| 2106 | role: Role::Assistant, |
| 2107 | content: vec![ |
| 2108 | ContentBlock::ToolUse { |
| 2109 | execution_id: None, |
| 2110 | id: "toolu_ok".to_string(), |
| 2111 | name: "read_file".to_string(), |
| 2112 | input: json!({"path": "a.txt"}), |
| 2113 | caller: None, |
| 2114 | thought_signature: None, |
| 2115 | }, |
| 2116 | ContentBlock::ToolUse { |
| 2117 | execution_id: None, |
| 2118 | id: "toolu_orphan".to_string(), |
| 2119 | name: "task".to_string(), |
| 2120 | input: json!({}), |
| 2121 | caller: None, |
| 2122 | thought_signature: None, |
| 2123 | }, |
| 2124 | ], |
| 2125 | }, |
| 2126 | // Pre-dispatch failure left only one tool_result behind. |
| 2127 | Message { |
| 2128 | role: Role::User, |
| 2129 | content: vec![ContentBlock::ToolResult { |
| 2130 | execution_id: None, |
| 2131 | tool_use_id: "toolu_ok".to_string(), |
| 2132 | content: "contents".to_string(), |
| 2133 | is_error: None, |
| 2134 | content_blocks: None, |
| 2135 | }], |
| 2136 | }, |
| 2137 | // Trailing assistant tool_use with no user turn at all. |
| 2138 | Message { |
| 2139 | role: Role::Assistant, |
| 2140 | content: vec![ContentBlock::ToolUse { |
| 2141 | execution_id: None, |
| 2142 | id: "toolu_tail".to_string(), |
| 2143 | name: "task".to_string(), |
| 2144 | input: json!({}), |
| 2145 | caller: None, |
| 2146 | thought_signature: None, |
| 2147 | }], |
| 2148 | }, |
| 2149 | ]; |
| 2150 | |
| 2151 | let body = client.build_anthropic_body(&request, true); |
| 2152 | let messages = body["messages"].as_array().expect("messages array"); |
| 2153 | assert_eq!(messages.len(), 5, "a repair turn is appended: {body}"); |
| 2154 | |
| 2155 | // The orphaned id gets a leading placeholder; the answered one is |
| 2156 | // untouched (no duplicate result). |
| 2157 | let repaired = messages[2]["content"].as_array().expect("user content"); |
| 2158 | assert_eq!(repaired.len(), 2, "{body}"); |
| 2159 | assert_eq!(repaired[0]["type"].as_str(), Some("tool_result")); |
| 2160 | assert_eq!(repaired[0]["tool_use_id"].as_str(), Some("toolu_orphan")); |
| 2161 | assert_eq!( |
| 2162 | repaired[0]["content"].as_str(), |
| 2163 | Some(UNEXECUTED_TOOL_RESULT) |
| 2164 | ); |
| 2165 | assert_eq!(repaired[0]["is_error"].as_bool(), Some(true)); |
| 2166 | assert_eq!(repaired[1]["tool_use_id"].as_str(), Some("toolu_ok")); |
| 2167 | assert_eq!(repaired[1]["content"].as_str(), Some("contents")); |
| 2168 | |
| 2169 | // The trailing tool_use gains a synthesized user turn. |
| 2170 | assert_eq!(messages[4]["role"].as_str(), Some("user")); |
| 2171 | let tail = messages[4]["content"].as_array().expect("tail content"); |
| 2172 | assert_eq!(tail.len(), 1, "{body}"); |
| 2173 | assert_eq!(tail[0]["type"].as_str(), Some("tool_result")); |
| 2174 | assert_eq!(tail[0]["tool_use_id"].as_str(), Some("toolu_tail")); |
| 2175 | assert_eq!(tail[0]["content"].as_str(), Some(UNEXECUTED_TOOL_RESULT)); |
| 2176 | |
| 2177 | // A fully answered history is left alone. |
| 2178 | request.messages.truncate(3); |
| 2179 | request.messages[1].content.retain( |
| 2180 | |block| !matches!(block, ContentBlock::ToolUse { id, ..} if id == "toolu_orphan"), |
| 2181 | ); |
| 2182 | let body = client.build_anthropic_body(&request, true); |
| 2183 | let messages = body["messages"].as_array().expect("messages array"); |
| 2184 | assert_eq!(messages.len(), 3, "no repair turn appended: {body}"); |
| 2185 | let untouched = messages[2]["content"].as_array().expect("user content"); |
| 2186 | assert_eq!(untouched.len(), 1, "{body}"); |
| 2187 | assert_eq!(untouched[0]["tool_use_id"].as_str(), Some("toolu_ok")); |
| 2188 | } |
| 2189 | |
| 2190 | #[test] |
| 2191 | fn modelstudio_messages_body_requests_thinking_with_budget() { |
| 2192 | // Model Studio's Anthropic-compatible endpoint documents the portable |
| 2193 | // {"type":"enabled","budget_tokens":N} shape plus {"type":"disabled"} |
| 2194 | // (alibabacloud.com/help/en/model-studio/anthropic-api-messages). |
| 2195 | let client = modelstudio_test_client( |
| 2196 | "https://token-plan.ap-southeast-1.maas.aliyuncs.com/apps/anthropic", |
| 2197 | ); |
| 2198 | |
| 2199 | let mut request = request_with("qwen3.8-max", Some("high"), None, None); |
| 2200 | request.max_tokens = 64_000; |
| 2201 | let body = client.build_anthropic_body(&request, true); |
| 2202 | assert_eq!( |
| 2203 | body.pointer("/thinking/type").and_then(Value::as_str), |
| 2204 | Some("enabled"), |
| 2205 | "{body}" |
| 2206 | ); |
| 2207 | assert!( |
| 2208 | body.pointer("/thinking/budget_tokens") |
| 2209 | .and_then(Value::as_u64) |
| 2210 | .is_some(), |
| 2211 | "{body}" |
| 2212 | ); |
| 2213 | assert!(body.get("output_config").is_none(), "{body}"); |
| 2214 | assert_eq!( |
| 2215 | body.get("model").and_then(Value::as_str), |
| 2216 | Some("qwen3.8-max"), |
| 2217 | "{body}" |
| 2218 | ); |
| 2219 | |
| 2220 | // An explicit "off" is honored on the wire instead of silently |
| 2221 | // falling through to the server default (thinking-ON for qwen3.x). |
| 2222 | let mut request = request_with("qwen3.8-max", Some("off"), None, None); |
| 2223 | request.max_tokens = 64_000; |
| 2224 | let body = client.build_anthropic_body(&request, true); |
| 2225 | assert_eq!( |
| 2226 | body.pointer("/thinking/type").and_then(Value::as_str), |
| 2227 | Some("disabled"), |
| 2228 | "{body}" |
| 2229 | ); |
| 2230 | |
| 2231 | let mut preview_client = modelstudio_test_client( |
| 2232 | "https://token-plan.ap-southeast-1.maas.aliyuncs.com/apps/anthropic", |
| 2233 | ); |
| 2234 | preview_client.route_facts = preview_client.catalog_facts_for_model("qwen4-max-preview"); |
| 2235 | for effort in [None, Some("high"), Some("max"), Some("off")] { |
| 2236 | let mut request = request_with("qwen4-max-preview", effort, None, None); |
| 2237 | request.max_tokens = 64_000; |
| 2238 | let body = preview_client.build_anthropic_body(&request, true); |
| 2239 | assert!(body.get("thinking").is_none(), "{effort:?}: {body}"); |
| 2240 | assert!(body.get("output_config").is_none(), "{effort:?}: {body}"); |
| 2241 | } |
| 2242 | } |
| 2243 | |
| 2244 | #[test] |
| 2245 | fn deepseek_messages_body_retires_aliases_and_keeps_thinking_control() { |
| 2246 | let client = deepseek_test_client( |
| 2247 | codewhale_config::descriptors::defaults::DEFAULT_DEEPSEEK_ANTHROPIC_BASE_URL, |
| 2248 | ); |
| 2249 | |
| 2250 | let chat = client.build_anthropic_body( |
| 2251 | &request_with("deepseek-chat", Some("off"), None, None), |
| 2252 | true, |
| 2253 | ); |
| 2254 | assert_eq!( |
| 2255 | chat.get("model").and_then(Value::as_str), |
| 2256 | Some(codewhale_config::catalog::reviewed::constants::DEEPSEEK_ALIAS_REPLACEMENT) |
| 2257 | ); |
| 2258 | assert_eq!( |
| 2259 | chat.pointer("/thinking/type").and_then(Value::as_str), |
| 2260 | Some("disabled") |
| 2261 | ); |
| 2262 | |
| 2263 | let reasoner = client.build_anthropic_body( |
| 2264 | &request_with("deepseek-reasoner", Some("high"), None, None), |
| 2265 | true, |
| 2266 | ); |
| 2267 | assert_eq!( |
| 2268 | reasoner.get("model").and_then(Value::as_str), |
| 2269 | Some(codewhale_config::catalog::reviewed::constants::DEEPSEEK_ALIAS_REPLACEMENT) |
| 2270 | ); |
| 2271 | assert_eq!( |
| 2272 | reasoner.pointer("/thinking/type").and_then(Value::as_str), |
| 2273 | Some("adaptive") |
| 2274 | ); |
| 2275 | assert_eq!( |
| 2276 | reasoner |
| 2277 | .pointer("/output_config/effort") |
| 2278 | .and_then(Value::as_str), |
| 2279 | Some("high") |
| 2280 | ); |
| 2281 | |
| 2282 | let custom = deepseek_test_client("https://messages.example/v1"); |
| 2283 | let custom_body = custom.build_anthropic_body( |
| 2284 | &request_with("deepseek-reasoner", Some("high"), None, None), |
| 2285 | true, |
| 2286 | ); |
| 2287 | assert_eq!( |
| 2288 | custom_body.get("model").and_then(Value::as_str), |
| 2289 | Some("deepseek-reasoner") |
| 2290 | ); |
| 2291 | } |
| 2292 | |
| 2293 | #[test] |
| 2294 | fn omitted_alias_effort_is_migrated_into_deepseek_messages_body() { |
| 2295 | for (alias, expected_effort, expected_thinking) in [ |
| 2296 | ("deepseek-chat", "off", "disabled"), |
| 2297 | ("deepseek-reasoner", "high", "adaptive"), |
| 2298 | ] { |
| 2299 | let mut config = { |
| 2300 | let __cw_config_init_4_0 = Some("deepseek-anthropic".to_string()); |
| 2301 | let __cw_config_init_4_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 2302 | deepseek_anthropic: codewhale_runtime::config::ProviderConfig { |
| 2303 | api_key: Some("test-key".to_string()), |
| 2304 | model: Some(alias.to_string()), |
| 2305 | ..Default::default() |
| 2306 | }, |
| 2307 | ..Default::default() |
| 2308 | }); |
| 2309 | let mut __cw_config_init_4_value: codewhale_runtime::config::Config = |
| 2310 | Default::default(); |
| 2311 | __cw_config_init_4_value.provider = __cw_config_init_4_0; |
| 2312 | __cw_config_init_4_value.providers = __cw_config_init_4_1; |
| 2313 | __cw_config_init_4_value |
| 2314 | }; |
| 2315 | assert!( |
| 2316 | config.reasoning_effort().is_none(), |
| 2317 | "fixture must omit effort" |
| 2318 | ); |
| 2319 | |
| 2320 | codewhale_runtime::config::normalize_model_config_for_test(&mut config); |
| 2321 | let client = CodewhaleClient::new(&config).expect("DeepSeek Messages client"); |
| 2322 | let model = config.default_model(); |
| 2323 | let body = client.build_anthropic_body( |
| 2324 | &request_with(&model, config.reasoning_effort(), None, None), |
| 2325 | true, |
| 2326 | ); |
| 2327 | |
| 2328 | assert_eq!( |
| 2329 | body.get("model").and_then(Value::as_str), |
| 2330 | Some(codewhale_config::catalog::reviewed::constants::DEEPSEEK_ALIAS_REPLACEMENT), |
| 2331 | "{alias}: {body}" |
| 2332 | ); |
| 2333 | assert_eq!(config.reasoning_effort(), Some(expected_effort)); |
| 2334 | assert_eq!( |
| 2335 | body.pointer("/thinking/type").and_then(Value::as_str), |
| 2336 | Some(expected_thinking), |
| 2337 | "{alias}: {body}" |
| 2338 | ); |
| 2339 | if alias == "deepseek-reasoner" { |
| 2340 | assert_eq!( |
| 2341 | body.pointer("/output_config/effort") |
| 2342 | .and_then(Value::as_str), |
| 2343 | Some("high"), |
| 2344 | "{body}" |
| 2345 | ); |
| 2346 | } else { |
| 2347 | assert!(body.get("output_config").is_none(), "{body}"); |
| 2348 | } |
| 2349 | } |
| 2350 | } |
| 2351 | |
| 2352 | #[test] |
| 2353 | fn minimax_body_uses_supported_thinking_controls() { |
| 2354 | let client = minimax_test_client(); |
| 2355 | let body = |
| 2356 | client.build_anthropic_body(&request_with("MiniMax-M3", Some("off"), None, None), true); |
| 2357 | assert_eq!( |
| 2358 | body.pointer("/thinking/type").and_then(Value::as_str), |
| 2359 | Some("disabled") |
| 2360 | ); |
| 2361 | assert!(body.get("output_config").is_none(), "{body}"); |
| 2362 | |
| 2363 | let mut enabled_bodies = Vec::new(); |
| 2364 | for effort in ["high", "max"] { |
| 2365 | let body = client |
| 2366 | .build_anthropic_body(&request_with("MiniMax-M3", Some(effort), None, None), true); |
| 2367 | assert_eq!( |
| 2368 | body.pointer("/thinking/type").and_then(Value::as_str), |
| 2369 | Some("adaptive"), |
| 2370 | "{effort}: {body}" |
| 2371 | ); |
| 2372 | assert!(body.get("output_config").is_none(), "{effort}: {body}"); |
| 2373 | enabled_bodies.push(body); |
| 2374 | } |
| 2375 | assert_eq!( |
| 2376 | enabled_bodies[0].get("thinking"), |
| 2377 | enabled_bodies[1].get("thinking"), |
| 2378 | "MiniMax high/max select the same untiered adaptive wire control" |
| 2379 | ); |
| 2380 | |
| 2381 | let flash_body = client.build_anthropic_body( |
| 2382 | &request_with("MiniMax-M3.1-Flash", Some("xhigh"), None, None), |
| 2383 | true, |
| 2384 | ); |
| 2385 | assert_eq!( |
| 2386 | flash_body.pointer("/thinking/type").and_then(Value::as_str), |
| 2387 | Some("adaptive") |
| 2388 | ); |
| 2389 | assert_eq!( |
| 2390 | flash_body |
| 2391 | .pointer("/output_config/effort") |
| 2392 | .and_then(Value::as_str), |
| 2393 | Some("xhigh") |
| 2394 | ); |
| 2395 | } |
| 2396 | |
| 2397 | #[test] |
| 2398 | fn minimax_messages_reasoning_controls_require_exact_first_party_m3_route() { |
| 2399 | for (base_url, model) in [ |
| 2400 | ( |
| 2401 | "https://gateway.example/anthropic", |
| 2402 | codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_MODEL, |
| 2403 | ), |
| 2404 | ( |
| 2405 | codewhale_config::descriptors::defaults::DEFAULT_MINIMAX_ANTHROPIC_BASE_URL, |
| 2406 | "MiniMax-M2", |
| 2407 | ), |
| 2408 | ] { |
| 2409 | let client = minimax_test_client_for(base_url); |
| 2410 | for effort in ["off", "high", "max"] { |
| 2411 | let body = client |
| 2412 | .build_anthropic_body(&request_with(model, Some(effort), None, None), true); |
| 2413 | assert!( |
| 2414 | body.get("thinking").is_none(), |
| 2415 | "{base_url} {model} {effort}: {body}" |
| 2416 | ); |
| 2417 | assert!( |
| 2418 | body.get("output_config").is_none(), |
| 2419 | "{base_url} {model} {effort}: {body}" |
| 2420 | ); |
| 2421 | } |
| 2422 | } |
| 2423 | } |
| 2424 | |
| 2425 | #[test] |
| 2426 | fn body_drops_sampling_params_for_models_that_reject_them() { |
| 2427 | let client = test_client(); |
| 2428 | |
| 2429 | let body = client.build_anthropic_body( |
| 2430 | &request_with("claude-opus-4-8", None, Some(0.7), Some(0.9)), |
| 2431 | true, |
| 2432 | ); |
| 2433 | assert!(body.get("temperature").is_none(), "{body}"); |
| 2434 | assert!(body.get("top_p").is_none(), "{body}"); |
| 2435 | |
| 2436 | // The Claude 5 generation and Haiku 5.5 reject sampling too. The |
| 2437 | // datestamped spelling pins the substring match against snapshot |
| 2438 | // suffixes. |
| 2439 | for model in [ |
| 2440 | "claude-opus-5", |
| 2441 | "claude-opus-5-5", |
| 2442 | "claude-opus-5-20260101", |
| 2443 | "claude-sonnet-5", |
| 2444 | "claude-sonnet-5-5", |
| 2445 | "claude-haiku-5-5", |
| 2446 | "claude-fable-5", |
| 2447 | "claude-mythos-5", |
| 2448 | ] { |
| 2449 | let body = |
| 2450 | client.build_anthropic_body(&request_with(model, None, Some(0.7), Some(0.9)), true); |
| 2451 | assert!( |
| 2452 | body.get("temperature").is_none() && body.get("top_p").is_none(), |
| 2453 | "{model} must not receive sampling params: {body}" |
| 2454 | ); |
| 2455 | } |
| 2456 | |
| 2457 | // Older models accept ONE of temperature / top_p (temperature wins). |
| 2458 | // The pre-4.7 generations stay ungated, so a future over-broad arm |
| 2459 | // like `contains("opus-4-")` cannot slip through. |
| 2460 | for model in ["claude-sonnet-4-6", "claude-opus-4-6", "claude-haiku-4-5"] { |
| 2461 | let body = |
| 2462 | client.build_anthropic_body(&request_with(model, None, Some(0.7), Some(0.9)), true); |
| 2463 | assert_eq!( |
| 2464 | body.get("temperature").and_then(Value::as_f64), |
| 2465 | Some(f64::from(0.7f32)), |
| 2466 | "{model} keeps temperature" |
| 2467 | ); |
| 2468 | assert!( |
| 2469 | body.get("top_p").is_none(), |
| 2470 | "{model}: never send both: {body}" |
| 2471 | ); |
| 2472 | } |
| 2473 | let body = client.build_anthropic_body( |
| 2474 | &request_with("claude-sonnet-4-6", None, None, Some(0.9)), |
| 2475 | true, |
| 2476 | ); |
| 2477 | assert_eq!( |
| 2478 | body.get("top_p").and_then(Value::as_f64), |
| 2479 | Some(f64::from(0.9f32)), |
| 2480 | "top_p alone passes through: {body}" |
| 2481 | ); |
| 2482 | } |
| 2483 | |
| 2484 | #[test] |
| 2485 | fn body_replays_signed_thinking_and_drops_unsigned_placeholders() { |
| 2486 | let client = test_client(); |
| 2487 | let mut request = request_with("claude-sonnet-4-6", None, None, None); |
| 2488 | request.messages = vec![ |
| 2489 | Message { |
| 2490 | role: Role::User, |
| 2491 | content: vec![ContentBlock::Text { |
| 2492 | text: "do the thing".to_string(), |
| 2493 | cache_control: None, |
| 2494 | }], |
| 2495 | }, |
| 2496 | Message { |
| 2497 | role: Role::Assistant, |
| 2498 | content: vec![ |
| 2499 | ContentBlock::Thinking { |
| 2500 | thinking: "signed reasoning".to_string(), |
| 2501 | signature: Some("sig-abc".to_string()), |
| 2502 | state: None, |
| 2503 | redacted_data: None, |
| 2504 | }, |
| 2505 | ContentBlock::Thinking { |
| 2506 | thinking: "(reasoning omitted)".to_string(), |
| 2507 | signature: None, |
| 2508 | state: None, |
| 2509 | redacted_data: None, |
| 2510 | }, |
| 2511 | ContentBlock::ToolUse { |
| 2512 | execution_id: None, |
| 2513 | id: "toolu_1".to_string(), |
| 2514 | name: "read_file".to_string(), |
| 2515 | input: json!({"path": "a.txt"}), |
| 2516 | caller: None, |
| 2517 | thought_signature: None, |
| 2518 | }, |
| 2519 | ], |
| 2520 | }, |
| 2521 | Message { |
| 2522 | role: Role::User, |
| 2523 | content: vec![ContentBlock::ToolResult { |
| 2524 | execution_id: None, |
| 2525 | tool_use_id: "toolu_1".to_string(), |
| 2526 | content: "contents".to_string(), |
| 2527 | is_error: None, |
| 2528 | content_blocks: None, |
| 2529 | }], |
| 2530 | }, |
| 2531 | ]; |
| 2532 | |
| 2533 | let body = client.build_anthropic_body(&request, true); |
| 2534 | let assistant = &body["messages"][1]["content"]; |
| 2535 | assert_eq!(assistant.as_array().map(Vec::len), Some(2)); |
| 2536 | assert_eq!( |
| 2537 | assistant[0]["signature"].as_str(), |
| 2538 | Some("sig-abc"), |
| 2539 | "signed thinking replays verbatim: {assistant}" |
| 2540 | ); |
| 2541 | assert_eq!(assistant[1]["type"].as_str(), Some("tool_use")); |
| 2542 | assert!( |
| 2543 | assistant[1].get("caller").is_none(), |
| 2544 | "internal caller metadata must not reach the wire" |
| 2545 | ); |
| 2546 | assert_eq!( |
| 2547 | body["messages"][2]["content"][0]["type"].as_str(), |
| 2548 | Some("tool_result") |
| 2549 | ); |
| 2550 | } |
| 2551 | |
| 2552 | #[test] |
| 2553 | fn body_replays_redacted_thinking_blocks_byte_exact() { |
| 2554 | let client = test_client(); |
| 2555 | let mut request = request_with("claude-sonnet-4-6", None, None, None); |
| 2556 | request.messages = vec![ |
| 2557 | Message { |
| 2558 | role: Role::User, |
| 2559 | content: vec![ContentBlock::Text { |
| 2560 | text: "do the thing".to_string(), |
| 2561 | cache_control: None, |
| 2562 | }], |
| 2563 | }, |
| 2564 | Message { |
| 2565 | role: Role::Assistant, |
| 2566 | content: vec![ |
| 2567 | ContentBlock::Thinking { |
| 2568 | thinking: String::new(), |
| 2569 | signature: None, |
| 2570 | state: None, |
| 2571 | redacted_data: Some("ENC_REDACTED_PAYLOAD".to_string()), |
| 2572 | }, |
| 2573 | ContentBlock::ToolUse { |
| 2574 | execution_id: None, |
| 2575 | id: "toolu_1".to_string(), |
| 2576 | name: "read_file".to_string(), |
| 2577 | input: json!({"path": "a.txt"}), |
| 2578 | caller: None, |
| 2579 | thought_signature: None, |
| 2580 | }, |
| 2581 | ], |
| 2582 | }, |
| 2583 | Message { |
| 2584 | role: Role::User, |
| 2585 | content: vec![ContentBlock::ToolResult { |
| 2586 | execution_id: None, |
| 2587 | tool_use_id: "toolu_1".to_string(), |
| 2588 | content: "contents".to_string(), |
| 2589 | is_error: None, |
| 2590 | content_blocks: None, |
| 2591 | }], |
| 2592 | }, |
| 2593 | ]; |
| 2594 | |
| 2595 | let body = client.build_anthropic_body(&request, true); |
| 2596 | let assistant = &body["messages"][1]["content"]; |
| 2597 | assert_eq!(assistant.as_array().map(Vec::len), Some(2)); |
| 2598 | assert_eq!(assistant[0]["type"].as_str(), Some("redacted_thinking")); |
| 2599 | assert_eq!(assistant[0]["data"].as_str(), Some("ENC_REDACTED_PAYLOAD")); |
| 2600 | assert_eq!(assistant[1]["type"].as_str(), Some("tool_use")); |
| 2601 | } |
| 2602 | |
| 2603 | #[test] |
| 2604 | fn non_native_gateways_never_receive_redacted_thinking_blocks() { |
| 2605 | // Conservative withholding: the docs promise nothing about |
| 2606 | // third-party gateways understanding `redacted_thinking`, and a |
| 2607 | // strict Messages-compatible gateway would reject the unknown type. |
| 2608 | let client = anthropic_test_client(Some("https://gateway.example.com/anthropic")); |
| 2609 | let mut request = request_with("claude-sonnet-4-6", None, None, None); |
| 2610 | request.messages = vec![Message { |
| 2611 | role: Role::Assistant, |
| 2612 | content: vec![ |
| 2613 | ContentBlock::Thinking { |
| 2614 | thinking: String::new(), |
| 2615 | signature: None, |
| 2616 | state: None, |
| 2617 | redacted_data: Some("ENC_REDACTED".to_string()), |
| 2618 | }, |
| 2619 | ContentBlock::ToolUse { |
| 2620 | execution_id: None, |
| 2621 | id: "toolu_1".to_string(), |
| 2622 | name: "read_file".to_string(), |
| 2623 | input: json!({}), |
| 2624 | caller: None, |
| 2625 | thought_signature: None, |
| 2626 | }, |
| 2627 | ], |
| 2628 | }]; |
| 2629 | |
| 2630 | let body = client.build_anthropic_body(&request, true); |
| 2631 | let wire = body.to_string(); |
| 2632 | assert!( |
| 2633 | !wire.contains("redacted_thinking") && !wire.contains("ENC_REDACTED"), |
| 2634 | "non-native gateway must not receive redacted blocks: {body}" |
| 2635 | ); |
| 2636 | let assistant = &body["messages"][0]["content"]; |
| 2637 | assert_eq!(assistant.as_array().map(Vec::len), Some(1)); |
| 2638 | |
| 2639 | // First-party Anthropic keeps the block: it can decrypt it. |
| 2640 | let native = test_client().build_anthropic_body(&request, true); |
| 2641 | assert!( |
| 2642 | native.to_string().contains("ENC_REDACTED"), |
| 2643 | "first-party route must replay redacted blocks: {native}" |
| 2644 | ); |
| 2645 | } |
| 2646 | |
| 2647 | #[test] |
| 2648 | fn gateway_withhold_drops_messages_that_only_carried_redacted_blocks() { |
| 2649 | // A redacted-only assistant message (reachable from foreign or |
| 2650 | // imported sessions; the live engine never persists a reasoning-only |
| 2651 | // turn) must not go out as `content: []` after the withhold — that |
| 2652 | // is exactly the every-retry 400 this withhold exists to prevent. |
| 2653 | // Dropping the message is safe: no `tool_use` means no dangling |
| 2654 | // `tool_result`. |
| 2655 | let client = anthropic_test_client(Some("https://gateway.example.com/anthropic")); |
| 2656 | let mut request = request_with("claude-sonnet-4-6", None, None, None); |
| 2657 | request.messages = vec![ |
| 2658 | Message { |
| 2659 | role: Role::User, |
| 2660 | content: vec![ContentBlock::Text { |
| 2661 | text: "do the thing".to_string(), |
| 2662 | cache_control: None, |
| 2663 | }], |
| 2664 | }, |
| 2665 | Message { |
| 2666 | role: Role::Assistant, |
| 2667 | content: vec![ContentBlock::Thinking { |
| 2668 | thinking: String::new(), |
| 2669 | signature: None, |
| 2670 | state: None, |
| 2671 | redacted_data: Some("ENC_REDACTED_ONLY".to_string()), |
| 2672 | }], |
| 2673 | }, |
| 2674 | Message { |
| 2675 | role: Role::User, |
| 2676 | content: vec![ContentBlock::Text { |
| 2677 | text: "continue".to_string(), |
| 2678 | cache_control: None, |
| 2679 | }], |
| 2680 | }, |
| 2681 | ]; |
| 2682 | |
| 2683 | let body = client.build_anthropic_body(&request, true); |
| 2684 | let messages = body["messages"].as_array().expect("messages array"); |
| 2685 | assert_eq!( |
| 2686 | messages.len(), |
| 2687 | 2, |
| 2688 | "the redacted-only assistant message must be dropped, not emptied: {body}" |
| 2689 | ); |
| 2690 | assert_eq!(messages[0]["role"].as_str(), Some("user")); |
| 2691 | assert_eq!(messages[1]["role"].as_str(), Some("user")); |
| 2692 | assert!( |
| 2693 | !body.to_string().contains("ENC_REDACTED_ONLY"), |
| 2694 | "the payload must stay withheld: {body}" |
| 2695 | ); |
| 2696 | |
| 2697 | // First-party Anthropic keeps the message and its block. |
| 2698 | let native = test_client().build_anthropic_body(&request, true); |
| 2699 | assert_eq!( |
| 2700 | native["messages"].as_array().map(Vec::len), |
| 2701 | Some(3), |
| 2702 | "native routes keep the redacted-only turn: {native}" |
| 2703 | ); |
| 2704 | } |
| 2705 | |
| 2706 | #[test] |
| 2707 | fn sse_redacted_content_block_start_decodes_through_the_stream_decoder() { |
| 2708 | // The exact event whose decode used to drop the turn's block: a |
| 2709 | // `redacted_thinking` content_block_start through the SSE decoder. |
| 2710 | // The contract-violating no-data form must still decode (empty |
| 2711 | // payload + capture warn) instead of failing the event and silently |
| 2712 | // losing the block. |
| 2713 | use codewhale_models::ContentBlockStart; |
| 2714 | |
| 2715 | let decode = |line: &str| { |
| 2716 | convert_anthropic_sse_data(line) |
| 2717 | .expect("content_block_start must be recognized") |
| 2718 | .expect("decode must succeed") |
| 2719 | }; |
| 2720 | |
| 2721 | let event = decode( |
| 2722 | r#"{"type":"content_block_start","index":1,"content_block":{"type":"redacted_thinking","data":"ENC"}}"#, |
| 2723 | ); |
| 2724 | match event { |
| 2725 | StreamEvent::ContentBlockStart { |
| 2726 | index, |
| 2727 | content_block: ContentBlockStart::RedactedThinking { data }, |
| 2728 | } => { |
| 2729 | assert_eq!(index, 1); |
| 2730 | assert_eq!(data, "ENC"); |
| 2731 | } |
| 2732 | other => panic!("unexpected event for redacted start: {other:?}"), |
| 2733 | } |
| 2734 | |
| 2735 | let malformed = decode( |
| 2736 | r#"{"type":"content_block_start","index":2,"content_block":{"type":"redacted_thinking"}}"#, |
| 2737 | ); |
| 2738 | match malformed { |
| 2739 | StreamEvent::ContentBlockStart { |
| 2740 | content_block: ContentBlockStart::RedactedThinking { data }, |
| 2741 | .. |
| 2742 | } => assert_eq!(data, "", "missing data must default to an empty payload"), |
| 2743 | other => panic!("unexpected event for malformed redacted start: {other:?}"), |
| 2744 | } |
| 2745 | } |
| 2746 | |
| 2747 | #[test] |
| 2748 | fn non_stream_redacted_thinking_blocks_decode_into_redacted_data() { |
| 2749 | let payload = json!({ |
| 2750 | "id": "msg_1", |
| 2751 | "type": "message", |
| 2752 | "role": "assistant", |
| 2753 | "model": "claude-sonnet-4-6", |
| 2754 | "content": [ |
| 2755 | { "type": "redacted_thinking", "data": "ENC_FROM_API" }, |
| 2756 | { "type": "text", "text": "answer" } |
| 2757 | ], |
| 2758 | "stop_reason": "end_turn", |
| 2759 | "stop_sequence": null, |
| 2760 | "usage": { |
| 2761 | "input_tokens": 1, |
| 2762 | "output_tokens": 1 |
| 2763 | } |
| 2764 | }); |
| 2765 | |
| 2766 | // An unknown block tag used to fail the whole response decode; the |
| 2767 | // shim must rewrite it into the provider-neutral shape instead. |
| 2768 | let mut value = payload; |
| 2769 | if let Some(usage) = value.get_mut("usage") { |
| 2770 | *usage = json!(parse_anthropic_usage(usage)); |
| 2771 | } |
| 2772 | normalize_redacted_thinking_blocks(&mut value); |
| 2773 | let response: MessageResponse = serde_json::from_value(value) |
| 2774 | .expect("redacted_thinking must not fail the response decode"); |
| 2775 | assert_eq!(response.content.len(), 2); |
| 2776 | match &response.content[0] { |
| 2777 | ContentBlock::Thinking { |
| 2778 | thinking, |
| 2779 | redacted_data, |
| 2780 | .. |
| 2781 | } => { |
| 2782 | assert_eq!(redacted_data.as_deref(), Some("ENC_FROM_API")); |
| 2783 | assert!(thinking.is_empty()); |
| 2784 | } |
| 2785 | other => panic!("expected thinking block, got {other:?}"), |
| 2786 | } |
| 2787 | } |
| 2788 | |
| 2789 | #[test] |
| 2790 | fn breakpoints_are_capped_at_four_dropping_earliest() { |
| 2791 | let client = test_client(); |
| 2792 | let mut request = request_with("claude-sonnet-4-6", None, None, None); |
| 2793 | // Five caller-marked user turns + the two placed breakpoints. |
| 2794 | request.messages = (0..5) |
| 2795 | .map(|i| Message { |
| 2796 | role: Role::User, |
| 2797 | content: vec![ContentBlock::Text { |
| 2798 | text: format!("turn {i}"), |
| 2799 | cache_control: Some(CacheControl { |
| 2800 | cache_type: "ephemeral".to_string(), |
| 2801 | }), |
| 2802 | }], |
| 2803 | }) |
| 2804 | .collect(); |
| 2805 | |
| 2806 | let body = client.build_anthropic_body(&request, true); |
| 2807 | let mut count = 0; |
| 2808 | if body.pointer("/system/0/cache_control").is_some() { |
| 2809 | count += 1; |
| 2810 | } |
| 2811 | for message in body["messages"].as_array().unwrap() { |
| 2812 | for block in message["content"].as_array().unwrap() { |
| 2813 | if block.get("cache_control").is_some() { |
| 2814 | count += 1; |
| 2815 | } |
| 2816 | } |
| 2817 | } |
| 2818 | assert!( |
| 2819 | count <= MAX_CACHE_BREAKPOINTS, |
| 2820 | "breakpoints must be capped at {MAX_CACHE_BREAKPOINTS}, got {count}: {body}" |
| 2821 | ); |
| 2822 | // The latest user turn keeps its marker (longest prefix coverage). |
| 2823 | assert!( |
| 2824 | body.pointer("/messages/4/content/0/cache_control") |
| 2825 | .is_some(), |
| 2826 | "{body}" |
| 2827 | ); |
| 2828 | } |
| 2829 | |
| 2830 | #[test] |
| 2831 | fn sse_fixture_decodes_text_thinking_signature_and_tool_use() { |
| 2832 | use codewhale_models::{ContentBlockStart, Delta}; |
| 2833 | |
| 2834 | let events = [ |
| 2835 | r#"{"type":"message_start","message":{"id":"msg_01","type":"message","role":"assistant","content":[],"model":"claude-sonnet-4-6","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":2045,"cache_read_input_tokens":18000,"output_tokens":1}}}"#, |
| 2836 | r#"{"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}"#, |
| 2837 | r#"{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"Let me check"}}"#, |
| 2838 | r#"{"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"sig-xyz"}}"#, |
| 2839 | r#"{"type":"content_block_stop","index":0}"#, |
| 2840 | r#"{"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}}"#, |
| 2841 | r#"{"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"Reading the file."}}"#, |
| 2842 | r#"{"type":"content_block_stop","index":1}"#, |
| 2843 | r#"{"type":"content_block_start","index":2,"content_block":{"type":"tool_use","id":"toolu_9","name":"read_file","input":{}}}"#, |
| 2844 | r#"{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"{\"path\":"}}"#, |
| 2845 | r#"{"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"\"a.txt\"}"}}"#, |
| 2846 | r#"{"type":"content_block_stop","index":2}"#, |
| 2847 | r#"{"type":"ping"}"#, |
| 2848 | r#"{"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":42}}"#, |
| 2849 | r#"{"type":"message_stop"}"#, |
| 2850 | ]; |
| 2851 | |
| 2852 | let decoded: Vec<StreamEvent> = events |
| 2853 | .iter() |
| 2854 | .map(|data| { |
| 2855 | convert_anthropic_sse_data(data) |
| 2856 | .expect("known event") |
| 2857 | .expect("decodes") |
| 2858 | }) |
| 2859 | .collect(); |
| 2860 | |
| 2861 | // message_start usage normalized to the #2961 convention. |
| 2862 | let StreamEvent::MessageStart { message } = &decoded[0] else { |
| 2863 | panic!("expected MessageStart, got {:?}", decoded[0]); |
| 2864 | }; |
| 2865 | assert_eq!(message.usage.input_tokens, 3 + 2045 + 18000); |
| 2866 | assert_eq!(message.usage.prompt_cache_hit_tokens, Some(18000)); |
| 2867 | assert_eq!(message.usage.prompt_cache_miss_tokens, Some(3)); |
| 2868 | assert_eq!(message.usage.prompt_cache_write_tokens, Some(2045)); |
| 2869 | |
| 2870 | assert!(matches!( |
| 2871 | &decoded[1], |
| 2872 | StreamEvent::ContentBlockStart { |
| 2873 | content_block: ContentBlockStart::Thinking { .. }, |
| 2874 | .. |
| 2875 | } |
| 2876 | )); |
| 2877 | assert!(matches!( |
| 2878 | &decoded[3], |
| 2879 | StreamEvent::ContentBlockDelta { |
| 2880 | delta: Delta::SignatureDelta { signature }, |
| 2881 | .. |
| 2882 | } if signature == "sig-xyz" |
| 2883 | )); |
| 2884 | assert!(matches!( |
| 2885 | &decoded[6], |
| 2886 | StreamEvent::ContentBlockDelta { |
| 2887 | delta: Delta::TextDelta { text }, |
| 2888 | .. |
| 2889 | } if text == "Reading the file." |
| 2890 | )); |
| 2891 | let mut tool_json = String::new(); |
| 2892 | for event in &decoded { |
| 2893 | if let StreamEvent::ContentBlockDelta { |
| 2894 | delta: Delta::InputJsonDelta { partial_json }, |
| 2895 | .. |
| 2896 | } = event |
| 2897 | { |
| 2898 | tool_json.push_str(partial_json); |
| 2899 | } |
| 2900 | } |
| 2901 | assert_eq!( |
| 2902 | serde_json::from_str::<Value>(&tool_json).expect("accumulated tool args parse"), |
| 2903 | json!({"path": "a.txt"}) |
| 2904 | ); |
| 2905 | assert!(matches!(&decoded[12], StreamEvent::Ping)); |
| 2906 | let StreamEvent::MessageDelta { delta, usage } = &decoded[13] else { |
| 2907 | panic!("expected MessageDelta"); |
| 2908 | }; |
| 2909 | assert_eq!(delta.stop_reason.as_deref(), Some("tool_use")); |
| 2910 | assert_eq!(usage.as_ref().map(|u| u.output_tokens), Some(42)); |
| 2911 | assert!(matches!(&decoded[14], StreamEvent::MessageStop)); |
| 2912 | } |
| 2913 | |
| 2914 | #[test] |
| 2915 | fn sse_error_event_and_unknown_events_are_handled() { |
| 2916 | let error = convert_anthropic_sse_data( |
| 2917 | r#"{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}"#, |
| 2918 | ) |
| 2919 | .expect("error event decodes") |
| 2920 | .expect("error event is a StreamEvent"); |
| 2921 | let StreamEvent::Error { error } = error else { |
| 2922 | panic!("expected StreamEvent::Error"); |
| 2923 | }; |
| 2924 | let (error_type, message) = anthropic_error_fields(&error); |
| 2925 | assert_eq!(error_type, "overloaded_error"); |
| 2926 | assert_eq!(message, "Overloaded"); |
| 2927 | |
| 2928 | assert!( |
| 2929 | convert_anthropic_sse_data(r#"{"type":"content_block_started_v2","index":0}"#) |
| 2930 | .is_none(), |
| 2931 | "unknown event types are tolerated" |
| 2932 | ); |
| 2933 | assert!(convert_anthropic_sse_data(" ").is_none()); |
| 2934 | } |
| 2935 | |
| 2936 | #[test] |
| 2937 | fn sse_decode_failures_keep_legacy_outcomes_on_the_direct_path() { |
| 2938 | // Malformed JSON: the invalid-input error, not the unrecognized one. |
| 2939 | let error = convert_anthropic_sse_data("{oops") |
| 2940 | .expect("malformed is Some") |
| 2941 | .expect_err("malformed is Err"); |
| 2942 | assert!(error.to_string().contains("invalid SSE JSON"), "{error:?}"); |
| 2943 | // Structurally invalid known event: unrecognized, not tolerated. |
| 2944 | let error = convert_anthropic_sse_data(r#"{"type":"content_block_stop"}"#) |
| 2945 | .expect("known type is Some") |
| 2946 | .expect_err("missing index is Err"); |
| 2947 | assert!( |
| 2948 | error.to_string().contains("unrecognized SSE event"), |
| 2949 | "{error:?}" |
| 2950 | ); |
| 2951 | // Local-only receipt: never provider SSE, stays ignored. |
| 2952 | assert!( |
| 2953 | convert_anthropic_sse_data( |
| 2954 | r#"{"type":"tool_projection_warning","provider":"x","omitted_tool_names":[],"omitted_tool_count":0}"# |
| 2955 | ) |
| 2956 | .is_none() |
| 2957 | ); |
| 2958 | } |
| 2959 | |
| 2960 | #[test] |
| 2961 | fn usage_mapping_handles_missing_cache_fields() { |
| 2962 | let usage = parse_anthropic_usage(&json!({"input_tokens": 10, "output_tokens": 5})); |
| 2963 | assert_eq!(usage.input_tokens, 10); |
| 2964 | assert_eq!(usage.output_tokens, 5); |
| 2965 | assert_eq!(usage.prompt_cache_hit_tokens, Some(0)); |
| 2966 | assert_eq!(usage.prompt_cache_miss_tokens, Some(10)); |
| 2967 | assert_eq!(usage.prompt_cache_write_tokens, Some(0)); |
| 2968 | } |
| 2969 | |
| 2970 | #[test] |
| 2971 | fn usage_mapping_keeps_cache_write_separate_from_miss() { |
| 2972 | let usage = parse_anthropic_usage(&json!({ |
| 2973 | "input_tokens": 3, |
| 2974 | "cache_creation_input_tokens": 2045, |
| 2975 | "cache_read_input_tokens": 18000, |
| 2976 | "output_tokens": 1, |
| 2977 | })); |
| 2978 | assert_eq!(usage.input_tokens, 3 + 2045 + 18000); |
| 2979 | assert_eq!(usage.prompt_cache_hit_tokens, Some(18000)); |
| 2980 | assert_eq!(usage.prompt_cache_miss_tokens, Some(3)); |
| 2981 | assert_eq!(usage.prompt_cache_write_tokens, Some(2045)); |
| 2982 | } |
| 2983 | |
| 2984 | #[test] |
| 2985 | fn data_url_image_becomes_a_base64_source_not_a_url_source() { |
| 2986 | // Anthropic rejects a `data:` URL under `{"type":"url"}`. This is the |
| 2987 | // whole reason the projection exists; if it regresses, every locally |
| 2988 | // attached screenshot 400s on the native route. |
| 2989 | let block = content_block_to_anthropic(&ContentBlock::ImageUrl { |
| 2990 | image_url: codewhale_models::ImageUrlContent { |
| 2991 | url: "data:image/png;base64,QUJD".to_string(), |
| 2992 | }, |
| 2993 | }) |
| 2994 | .expect("image block"); |
| 2995 | |
| 2996 | assert_eq!(block["type"], "image"); |
| 2997 | assert_eq!(block["source"]["type"], "base64"); |
| 2998 | assert_eq!(block["source"]["media_type"], "image/png"); |
| 2999 | assert_eq!(block["source"]["data"], "QUJD"); |
| 3000 | assert!( |
| 3001 | block["source"].get("url").is_none(), |
| 3002 | "base64 sources must not carry a url field: {block}" |
| 3003 | ); |
| 3004 | } |
| 3005 | |
| 3006 | #[test] |
| 3007 | fn tool_result_image_stays_inside_the_native_tool_result_block() { |
| 3008 | let content = anthropic_tool_result_content( |
| 3009 | "screenshot captured", |
| 3010 | Some(&[json!({ |
| 3011 | "type": "image", |
| 3012 | "mime_type": "image/png", |
| 3013 | "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==", |
| 3014 | })]), |
| 3015 | ); |
| 3016 | let blocks = content.as_array().expect("rich tool_result content"); |
| 3017 | |
| 3018 | assert_eq!( |
| 3019 | blocks[0], |
| 3020 | json!({"type": "text", "text": "screenshot captured"}) |
| 3021 | ); |
| 3022 | assert_eq!(blocks[1]["type"], "image"); |
| 3023 | assert_eq!(blocks[1]["source"]["type"], "base64"); |
| 3024 | assert_eq!(blocks[1]["source"]["media_type"], "image/png"); |
| 3025 | assert_eq!( |
| 3026 | blocks[1]["source"]["data"], |
| 3027 | "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==" |
| 3028 | ); |
| 3029 | } |
| 3030 | |
| 3031 | #[test] |
| 3032 | fn remote_image_url_stays_a_url_source() { |
| 3033 | let block = content_block_to_anthropic(&ContentBlock::ImageUrl { |
| 3034 | image_url: codewhale_models::ImageUrlContent { |
| 3035 | url: "https://example.com/shot.png".to_string(), |
| 3036 | }, |
| 3037 | }) |
| 3038 | .expect("image block"); |
| 3039 | |
| 3040 | assert_eq!(block["type"], "image"); |
| 3041 | assert_eq!(block["source"]["type"], "url"); |
| 3042 | assert_eq!(block["source"]["url"], "https://example.com/shot.png"); |
| 3043 | } |
| 3044 | |
| 3045 | #[test] |
| 3046 | fn unrepresentable_image_reference_degrades_to_visible_text() { |
| 3047 | for url in [ |
| 3048 | "file:///tmp/shot.png", |
| 3049 | "/tmp/shot.png", |
| 3050 | "data:image/png,QUJD", |
| 3051 | ] { |
| 3052 | let block = content_block_to_anthropic(&ContentBlock::ImageUrl { |
| 3053 | image_url: codewhale_models::ImageUrlContent { |
| 3054 | url: url.to_string(), |
| 3055 | }, |
| 3056 | }) |
| 3057 | .expect("block"); |
| 3058 | |
| 3059 | assert_eq!(block["type"], "text", "{url} should degrade: {block}"); |
| 3060 | assert!( |
| 3061 | block["text"].as_str().expect("text").contains(url), |
| 3062 | "the degraded text should name the reference: {block}" |
| 3063 | ); |
| 3064 | } |
| 3065 | } |
| 3066 | |
| 3067 | #[test] |
| 3068 | fn messages_url_tolerates_v1_suffix() { |
| 3069 | assert_eq!( |
| 3070 | anthropic_messages_url("https://api.anthropic.com"), |
| 3071 | "https://api.anthropic.com/v1/messages" |
| 3072 | ); |
| 3073 | assert_eq!( |
| 3074 | anthropic_messages_url("https://api.anthropic.com/"), |
| 3075 | "https://api.anthropic.com/v1/messages" |
| 3076 | ); |
| 3077 | assert_eq!( |
| 3078 | anthropic_messages_url("https://gateway.example/v1"), |
| 3079 | "https://gateway.example/v1/messages" |
| 3080 | ); |
| 3081 | assert_eq!( |
| 3082 | anthropic_messages_url("https://api.deepseek.com/anthropic"), |
| 3083 | "https://api.deepseek.com/anthropic/v1/messages" |
| 3084 | ); |
| 3085 | assert_eq!( |
| 3086 | anthropic_messages_url("https://api.minimax.io/anthropic"), |
| 3087 | "https://api.minimax.io/anthropic/v1/messages" |
| 3088 | ); |
| 3089 | assert_eq!( |
| 3090 | anthropic_messages_url("https://api.minimaxi.com/anthropic"), |
| 3091 | "https://api.minimaxi.com/anthropic/v1/messages" |
| 3092 | ); |
| 3093 | } |
| 3094 | |
| 3095 | #[test] |
| 3096 | fn anthropic_body_serializes_the_child_catalog_without_duplication() { |
| 3097 | // The real child catalog fixture (not a hand-built tool list) must |
| 3098 | // survive Messages serialization with exactly one canonical `read` |
| 3099 | // entry — no dedup, filter, or sanitizer may drop or duplicate it. |
| 3100 | // `load_skill` is eager in DEFAULT_ACTIVE_NATIVE_TOOLS, and children |
| 3101 | // resolve the same catalog authority the parent does, so it appears |
| 3102 | // here exactly once like any other default tool. |
| 3103 | let tools = crate::tools::subagent::kimi_general_child_request_tools_fixture(); |
| 3104 | assert_eq!( |
| 3105 | tools.iter().filter(|tool| tool.name == "read").count(), |
| 3106 | 1, |
| 3107 | "catalog fixture carries one canonical read" |
| 3108 | ); |
| 3109 | assert_eq!( |
| 3110 | tools |
| 3111 | .iter() |
| 3112 | .filter(|tool| tool.name == "load_skill") |
| 3113 | .count(), |
| 3114 | 1, |
| 3115 | "child wire catalog carries one canonical load_skill" |
| 3116 | ); |
| 3117 | let client = test_client(); |
| 3118 | let mut request = request_with("claude-sonnet-4-6", None, None, None); |
| 3119 | request.tools = Some(tools); |
| 3120 | let body = client.build_anthropic_body(&request, true); |
| 3121 | let serialized = body["tools"] |
| 3122 | .as_array() |
| 3123 | .expect("tools serialize as an array"); |
| 3124 | let reads: Vec<_> = serialized |
| 3125 | .iter() |
| 3126 | .filter(|tool| tool["name"] == "read") |
| 3127 | .collect(); |
| 3128 | assert_eq!( |
| 3129 | reads.len(), |
| 3130 | 1, |
| 3131 | "exactly one canonical read definition reaches the Messages wire" |
| 3132 | ); |
| 3133 | assert!( |
| 3134 | reads[0]["input_schema"]["properties"].is_object(), |
| 3135 | "read keeps a valid object schema: {}", |
| 3136 | reads[0] |
| 3137 | ); |
| 3138 | assert_eq!( |
| 3139 | serialized |
| 3140 | .iter() |
| 3141 | .filter(|tool| tool["name"] == "load_skill") |
| 3142 | .count(), |
| 3143 | 1, |
| 3144 | "exactly one canonical load_skill definition reaches the Messages wire" |
| 3145 | ); |
| 3146 | } |
| 3147 | |
| 3148 | #[tokio::test] |
| 3149 | async fn anthropic_stream_opens_through_shared_seam_preserving_headers() { |
| 3150 | use futures_util::StreamExt; |
| 3151 | use wiremock::matchers::{header, method, path}; |
| 3152 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 3153 | |
| 3154 | let server = MockServer::start().await; |
| 3155 | // The wire-specific Accept header must survive the shared stream-entry |
| 3156 | // open path; the mock only answers when it is present. |
| 3157 | Mock::given(method("POST")) |
| 3158 | .and(path("/v1/messages")) |
| 3159 | .and(header("Accept", "text/event-stream")) |
| 3160 | .respond_with( |
| 3161 | ResponseTemplate::new(200) |
| 3162 | .insert_header("Content-Type", "text/event-stream") |
| 3163 | .set_body_string("data: {\"type\":\"message_stop\"}\n\n"), |
| 3164 | ) |
| 3165 | .expect(1) |
| 3166 | .mount(&server) |
| 3167 | .await; |
| 3168 | |
| 3169 | let client = deepseek_test_client(&server.uri()); |
| 3170 | let mut stream = client |
| 3171 | .handle_anthropic_stream( |
| 3172 | &client |
| 3173 | .prepare_outbound_request(request_with("deepseek-v4", None, None, None), true) |
| 3174 | .expect("anthropic request prepares"), |
| 3175 | ) |
| 3176 | .await |
| 3177 | .expect("stream opens through the shared seam"); |
| 3178 | |
| 3179 | let mut saw_stop = false; |
| 3180 | tokio::time::timeout(std::time::Duration::from_secs(5), async { |
| 3181 | while let Some(event) = stream.next().await { |
| 3182 | if matches!(event.expect("stream event"), StreamEvent::MessageStop) { |
| 3183 | saw_stop = true; |
| 3184 | } |
| 3185 | } |
| 3186 | }) |
| 3187 | .await |
| 3188 | .expect("stream finishes after message_stop"); |
| 3189 | assert!(saw_stop, "message_stop should arrive through the seam"); |
| 3190 | } |
| 3191 | |
| 3192 | async fn collect_anthropic_stream(body: &'static str) -> Vec<Result<StreamEvent>> { |
| 3193 | use futures_util::StreamExt; |
| 3194 | use wiremock::matchers::{method, path}; |
| 3195 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 3196 | |
| 3197 | let server = MockServer::start().await; |
| 3198 | Mock::given(method("POST")) |
| 3199 | .and(path("/v1/messages")) |
| 3200 | .respond_with( |
| 3201 | ResponseTemplate::new(200) |
| 3202 | .insert_header("Content-Type", "text/event-stream") |
| 3203 | .set_body_string(body), |
| 3204 | ) |
| 3205 | .mount(&server) |
| 3206 | .await; |
| 3207 | let client = deepseek_test_client(&server.uri()); |
| 3208 | let stream = client |
| 3209 | .handle_anthropic_stream( |
| 3210 | &client |
| 3211 | .prepare_outbound_request(request_with("deepseek-v4", None, None, None), true) |
| 3212 | .expect("anthropic request prepares"), |
| 3213 | ) |
| 3214 | .await |
| 3215 | .expect("stream opens"); |
| 3216 | tokio::time::timeout(std::time::Duration::from_secs(5), stream.collect()) |
| 3217 | .await |
| 3218 | .expect("stream ends") |
| 3219 | } |
| 3220 | |
| 3221 | #[tokio::test] |
| 3222 | async fn anthropic_stream_joins_multiline_data_fields_into_one_event() { |
| 3223 | use codewhale_models::Delta; |
| 3224 | // One JSON payload split across two `data:` fields of a single event. |
| 3225 | let events = collect_anthropic_stream(concat!( |
| 3226 | "event: content_block_delta\n", |
| 3227 | "data: {\"type\":\"content_block_delta\",\"index\":0,\n", |
| 3228 | "data: \"delta\":{\"type\":\"text_delta\",\"text\":\"joined\"}}\n\n", |
| 3229 | "data: {\"type\":\"message_stop\"}\n\n", |
| 3230 | )) |
| 3231 | .await; |
| 3232 | assert!( |
| 3233 | events.iter().any(|event| matches!( |
| 3234 | event, |
| 3235 | Ok(StreamEvent::ContentBlockDelta { |
| 3236 | delta: Delta::TextDelta { text }, |
| 3237 | .. |
| 3238 | }) if text == "joined" |
| 3239 | )), |
| 3240 | "the split event was lost: {events:?}" |
| 3241 | ); |
| 3242 | assert!(matches!(events.last(), Some(Ok(StreamEvent::MessageStop)))); |
| 3243 | } |
| 3244 | |
| 3245 | #[tokio::test] |
| 3246 | async fn anthropic_stream_eof_without_message_stop_is_an_error() { |
| 3247 | let events = collect_anthropic_stream( |
| 3248 | "data: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"partial\"}}\n\n", |
| 3249 | ) |
| 3250 | .await; |
| 3251 | let last = events.last().expect("the delta and a terminal item"); |
| 3252 | assert!( |
| 3253 | last.as_ref() |
| 3254 | .is_err_and(|error| error.to_string().contains("closed before message_stop")), |
| 3255 | "a truncated stream must not end quietly: {events:?}" |
| 3256 | ); |
| 3257 | } |
| 3258 | |
| 3259 | /// Fault injection (#6184): a provider that answers the headers and then |
| 3260 | /// sends nothing fails the stream at the first-byte bound with a |
| 3261 | /// distinct error and a `crashes/` stall record, instead of holding the |
| 3262 | /// turn for the full idle budget. |
| 3263 | #[tokio::test] |
| 3264 | async fn stall_first_byte_timeout_fails_stream_and_records_stall() { |
| 3265 | use futures_util::StreamExt; |
| 3266 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 3267 | |
| 3268 | let dir = tempfile::tempdir().expect("tempdir"); |
| 3269 | codewhale_runtime::stall_report::set_test_stall_record_dir(Some(dir.path().to_path_buf())); |
| 3270 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0") |
| 3271 | .await |
| 3272 | .expect("bind"); |
| 3273 | let base_url = format!("http://{}", listener.local_addr().expect("addr")); |
| 3274 | let server = tokio::spawn(async move { |
| 3275 | let (mut socket, _) = listener.accept().await.expect("accept"); |
| 3276 | let mut buf = vec![0u8; 64 * 1024]; |
| 3277 | let _ = socket.read(&mut buf).await; |
| 3278 | socket |
| 3279 | .write_all( |
| 3280 | b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\n\r\n", |
| 3281 | ) |
| 3282 | .await |
| 3283 | .expect("headers"); |
| 3284 | // Hold the connection open with no body bytes. |
| 3285 | tokio::time::sleep(std::time::Duration::from_secs(60)).await; |
| 3286 | drop(socket); |
| 3287 | }); |
| 3288 | |
| 3289 | let mut client = deepseek_test_client(&base_url); |
| 3290 | client.stream_idle_timeout = std::time::Duration::from_secs(1); |
| 3291 | let started = std::time::Instant::now(); |
| 3292 | let mut stream = client |
| 3293 | .handle_anthropic_stream( |
| 3294 | &client |
| 3295 | .prepare_outbound_request(request_with("deepseek-v4", None, None, None), true) |
| 3296 | .expect("anthropic request prepares"), |
| 3297 | ) |
| 3298 | .await |
| 3299 | .expect("headers arrive"); |
| 3300 | let error = tokio::time::timeout(std::time::Duration::from_secs(10), async { |
| 3301 | loop { |
| 3302 | match stream.next().await { |
| 3303 | Some(Err(error)) => break error, |
| 3304 | Some(Ok(_)) => continue, |
| 3305 | None => panic!("stream ended without the first-byte error"), |
| 3306 | } |
| 3307 | } |
| 3308 | }) |
| 3309 | .await |
| 3310 | .expect("first-byte bound fires"); |
| 3311 | assert!(error.to_string().contains("first-byte timeout"), "{error}"); |
| 3312 | assert!(started.elapsed() < std::time::Duration::from_secs(10)); |
| 3313 | let records: Vec<String> = std::fs::read_dir(dir.path()) |
| 3314 | .expect("record dir") |
| 3315 | .flatten() |
| 3316 | .filter_map(|entry| std::fs::read_to_string(entry.path()).ok()) |
| 3317 | .collect(); |
| 3318 | assert_eq!(records.len(), 1, "{records:?}"); |
| 3319 | assert!(records[0].contains("first byte"), "{}", records[0]); |
| 3320 | server.abort(); |
| 3321 | codewhale_runtime::stall_report::set_test_stall_record_dir(None); |
| 3322 | } |
| 3323 | |
| 3324 | #[tokio::test] |
| 3325 | async fn anthropic_stream_open_error_is_not_retried() { |
| 3326 | use wiremock::matchers::{method, path}; |
| 3327 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 3328 | |
| 3329 | let server = MockServer::start().await; |
| 3330 | // A definitive provider error before any stream body must fail fast: |
| 3331 | // exactly one request, no H1 fallback, envelope preserved. |
| 3332 | Mock::given(method("POST")) |
| 3333 | .and(path("/v1/messages")) |
| 3334 | .respond_with(ResponseTemplate::new(401).set_body_string( |
| 3335 | "{\"error\":{\"type\":\"authentication_error\",\"message\":\"bad key\"}}", |
| 3336 | )) |
| 3337 | .expect(1) |
| 3338 | .mount(&server) |
| 3339 | .await; |
| 3340 | |
| 3341 | let client = deepseek_test_client(&server.uri()); |
| 3342 | let err = match client |
| 3343 | .handle_anthropic_stream( |
| 3344 | &client |
| 3345 | .prepare_outbound_request(request_with("deepseek-v4", None, None, None), true) |
| 3346 | .expect("anthropic request prepares"), |
| 3347 | ) |
| 3348 | .await |
| 3349 | { |
| 3350 | Ok(_) => panic!("auth errors must fail fast"), |
| 3351 | Err(err) => err, |
| 3352 | }; |
| 3353 | // Typed through the shared classifier, provider message kept. |
| 3354 | assert!( |
| 3355 | matches!( |
| 3356 | err.chain() |
| 3357 | .find_map(|cause| cause.downcast_ref::<crate::llm_client::LlmError>()), |
| 3358 | Some(crate::llm_client::LlmError::AuthenticationError(_)) |
| 3359 | ), |
| 3360 | "a 401 must stay a typed authentication error: {err:#}" |
| 3361 | ); |
| 3362 | assert!(format!("{err:#}").contains("bad key"), "{err:#}"); |
| 3363 | } |
| 3364 | |
| 3365 | #[tokio::test] |
| 3366 | async fn anthropic_rate_limit_is_retried_honoring_retry_after() { |
| 3367 | use wiremock::matchers::{method, path}; |
| 3368 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 3369 | |
| 3370 | for force_http1 in [false, true] { |
| 3371 | let server = MockServer::start().await; |
| 3372 | Mock::given(method("POST")) |
| 3373 | .and(path("/v1/messages")) |
| 3374 | .respond_with( |
| 3375 | ResponseTemplate::new(429) |
| 3376 | .insert_header("retry-after", "1") |
| 3377 | .set_body_string( |
| 3378 | "{\"type\":\"error\",\"error\":{\"type\":\"rate_limit_error\",\"message\":\"slow down\"}}", |
| 3379 | ), |
| 3380 | ) |
| 3381 | .up_to_n_times(1) |
| 3382 | .expect(1) |
| 3383 | .mount(&server) |
| 3384 | .await; |
| 3385 | Mock::given(method("POST")) |
| 3386 | .and(path("/v1/messages")) |
| 3387 | .respond_with( |
| 3388 | ResponseTemplate::new(200) |
| 3389 | .insert_header("Content-Type", "text/event-stream") |
| 3390 | .set_body_string("data: {\"type\":\"message_stop\"}\n\n"), |
| 3391 | ) |
| 3392 | .expect(1) |
| 3393 | .mount(&server) |
| 3394 | .await; |
| 3395 | |
| 3396 | let mut client = deepseek_test_client(&server.uri()); |
| 3397 | client.force_http1 = force_http1; |
| 3398 | client.stream_open_timeout = std::time::Duration::from_millis(250); |
| 3399 | client.retry.enabled = true; |
| 3400 | client.retry.max_retries = 2; |
| 3401 | client.retry.initial_delay = 0.0; |
| 3402 | client.retry.max_delay = 0.0; |
| 3403 | let started = std::time::Instant::now(); |
| 3404 | let stream = client |
| 3405 | .handle_anthropic_stream( |
| 3406 | &client |
| 3407 | .prepare_outbound_request( |
| 3408 | request_with("deepseek-v4", None, None, None), |
| 3409 | true, |
| 3410 | ) |
| 3411 | .expect("anthropic request prepares"), |
| 3412 | ) |
| 3413 | .await; |
| 3414 | assert!( |
| 3415 | stream.is_ok(), |
| 3416 | "a 429 before the stream body must be retried, not surfaced" |
| 3417 | ); |
| 3418 | // The backoff is configured to zero, so only the provider's |
| 3419 | // `Retry-After: 1` can account for the wait before the retry. |
| 3420 | assert!( |
| 3421 | started.elapsed() >= std::time::Duration::from_millis(900), |
| 3422 | "the retry must wait out Retry-After, waited {:?}", |
| 3423 | started.elapsed() |
| 3424 | ); |
| 3425 | } |
| 3426 | } |
| 3427 | |
| 3428 | /// A `system`-role history message — what a compaction summary, a branch |
| 3429 | /// summary, or an imported journal `system` entry becomes once it reaches |
| 3430 | /// `MessageRequest::messages` — must not be emitted verbatim: the Messages |
| 3431 | /// API accepts only `user` and `assistant` in `messages[].role` and 400s |
| 3432 | /// the whole conversation otherwise, on every retry. |
| 3433 | #[test] |
| 3434 | fn system_role_history_message_is_not_emitted_verbatim_on_the_messages_wire() { |
| 3435 | let mut request = request_with("claude-opus-4-6", None, None, None); |
| 3436 | request.messages.insert( |
| 3437 | 0, |
| 3438 | Message { |
| 3439 | role: Role::System, |
| 3440 | content: vec![ContentBlock::Text { |
| 3441 | text: "[compaction summary] the user is porting the parser".to_string(), |
| 3442 | cache_control: None, |
| 3443 | }], |
| 3444 | }, |
| 3445 | ); |
| 3446 | |
| 3447 | let body = test_client().build_anthropic_body(&request, false); |
| 3448 | let messages = body["messages"].as_array().expect("messages array"); |
| 3449 | |
| 3450 | for message in messages { |
| 3451 | let role = message["role"].as_str().expect("role is a string"); |
| 3452 | assert!( |
| 3453 | role == "user" || role == "assistant", |
| 3454 | "Messages API rejects role {role:?}" |
| 3455 | ); |
| 3456 | } |
| 3457 | let carried = messages.iter().any(|message| { |
| 3458 | message["content"].as_array().is_some_and(|blocks| { |
| 3459 | blocks.iter().any(|block| { |
| 3460 | block["text"].as_str() |
| 3461 | == Some("[compaction summary] the user is porting the parser") |
| 3462 | }) |
| 3463 | }) |
| 3464 | }); |
| 3465 | assert!(carried, "the summary text must survive: {messages:?}"); |
| 3466 | } |
| 3467 | |
| 3468 | #[test] |
| 3469 | fn deepseek_anthropic_web_tools_chatbot_options_and_replay() { |
| 3470 | let client = deepseek_test_client("https://api.deepseek.com/anthropic"); |
| 3471 | let request = MessageRequest { |
| 3472 | model: "deepseek-v4".to_string(), |
| 3473 | messages: vec![ |
| 3474 | Message { |
| 3475 | role: Role::User, |
| 3476 | content: vec![ |
| 3477 | ContentBlock::Text { |
| 3478 | text: "Summarize".to_string(), |
| 3479 | cache_control: None, |
| 3480 | }, |
| 3481 | ContentBlock::File { |
| 3482 | file_id: "file_doc_1".to_string(), |
| 3483 | }, |
| 3484 | ], |
| 3485 | }, |
| 3486 | Message { |
| 3487 | role: Role::Assistant, |
| 3488 | content: vec![ |
| 3489 | ContentBlock::ServerToolUse { |
| 3490 | id: "srv_1".to_string(), |
| 3491 | name: "deepseek_web_search".to_string(), |
| 3492 | input: json!({ "query": "rust 2024" }), |
| 3493 | kind: Some("search".to_string()), |
| 3494 | caller: None, |
| 3495 | }, |
| 3496 | ContentBlock::WebSearchToolResult { |
| 3497 | tool_use_id: "srv_1".to_string(), |
| 3498 | content: json!([{ |
| 3499 | "type": "web_search_result_location", |
| 3500 | "url": "https://example.com", |
| 3501 | "title": "Rust" |
| 3502 | }]), |
| 3503 | kind: Some("search".to_string()), |
| 3504 | }, |
| 3505 | ContentBlock::WebFetchToolResult { |
| 3506 | tool_use_id: "srv_2".to_string(), |
| 3507 | content: json!({ "type": "web_fetch_result", "url": "https://example.com" }), |
| 3508 | kind: Some("read_link".to_string()), |
| 3509 | signature: Some("sig_fetch".to_string()), |
| 3510 | }, |
| 3511 | ], |
| 3512 | }, |
| 3513 | Message { |
| 3514 | role: Role::LatestReminder, |
| 3515 | content: vec![ContentBlock::Text { |
| 3516 | text: "Cite URLs inline".to_string(), |
| 3517 | cache_control: None, |
| 3518 | }], |
| 3519 | }, |
| 3520 | Message { |
| 3521 | role: Role::User, |
| 3522 | content: vec![ContentBlock::Text { |
| 3523 | text: "Continue".to_string(), |
| 3524 | cache_control: None, |
| 3525 | }], |
| 3526 | }, |
| 3527 | ], |
| 3528 | max_tokens: 1024, |
| 3529 | system: None, |
| 3530 | tools: Some(vec![ |
| 3531 | Tool { |
| 3532 | tool_type: Some("deepseek_web_search".to_string()), |
| 3533 | name: "deepseek_web_search".to_string(), |
| 3534 | description: String::new(), |
| 3535 | input_schema: json!({}), |
| 3536 | allowed_callers: None, |
| 3537 | defer_loading: None, |
| 3538 | input_examples: None, |
| 3539 | strict: None, |
| 3540 | cache_control: None, |
| 3541 | }, |
| 3542 | Tool { |
| 3543 | tool_type: Some("deepseek_read_url".to_string()), |
| 3544 | name: "deepseek_read_url".to_string(), |
| 3545 | description: String::new(), |
| 3546 | input_schema: json!({}), |
| 3547 | allowed_callers: None, |
| 3548 | defer_loading: None, |
| 3549 | input_examples: None, |
| 3550 | strict: None, |
| 3551 | cache_control: None, |
| 3552 | }, |
| 3553 | ]), |
| 3554 | tool_choice: Some(json!({ "type": "auto" })), |
| 3555 | metadata: None, |
| 3556 | thinking: None, |
| 3557 | reasoning_effort: None, |
| 3558 | stream: Some(true), |
| 3559 | temperature: None, |
| 3560 | top_p: None, |
| 3561 | safety_check: Some(codewhale_models::SafetyCheckConfig { |
| 3562 | level: "high".to_string(), |
| 3563 | }), |
| 3564 | title: Some(codewhale_models::ConversationTitleConfig { enabled: true }), |
| 3565 | }; |
| 3566 | |
| 3567 | let (body, warnings) = client |
| 3568 | .build_anthropic_wire_body(&request, true) |
| 3569 | .expect("deepseek messages body builds"); |
| 3570 | assert!(warnings.is_empty(), "{warnings:?}"); |
| 3571 | assert_eq!(body["safety_check"], json!({ "level": "high" })); |
| 3572 | assert_eq!(body["title"], json!({ "enabled": true })); |
| 3573 | assert_eq!( |
| 3574 | body["tools"], |
| 3575 | json!([ |
| 3576 | { "type": "deepseek_web_search", "name": "deepseek_web_search" }, |
| 3577 | { |
| 3578 | "type": "deepseek_read_url", |
| 3579 | "name": "deepseek_read_url", |
| 3580 | "cache_control": { "type": "ephemeral" } |
| 3581 | } |
| 3582 | ]) |
| 3583 | ); |
| 3584 | assert_eq!( |
| 3585 | body["messages"][0]["content"][1], |
| 3586 | json!({ "type": "document", "source": { "type": "file", "file_id": "file_doc_1" } }) |
| 3587 | ); |
| 3588 | assert_eq!(body["messages"][1]["content"][0]["kind"], "search"); |
| 3589 | assert_eq!(body["messages"][1]["content"][2]["signature"], "sig_fetch"); |
| 3590 | assert_eq!(body["messages"][2]["role"], "latest_reminder"); |
| 3591 | assert_eq!(body["messages"][3]["role"], "user"); |
| 3592 | |
| 3593 | let mut forced = request.clone(); |
| 3594 | forced.tool_choice = Some(json!({ "type": "tool", "name": "deepseek_web_search" })); |
| 3595 | assert!(client.build_anthropic_wire_body(&forced, true).is_err()); |
| 3596 | |
| 3597 | let mut required_choice = request.clone(); |
| 3598 | required_choice.tool_choice = Some(json!({ "type": "any" })); |
| 3599 | assert!( |
| 3600 | client |
| 3601 | .build_anthropic_wire_body(&required_choice, true) |
| 3602 | .is_err() |
| 3603 | ); |
| 3604 | |
| 3605 | let non_deepseek = anthropic_test_client(None); |
| 3606 | assert!( |
| 3607 | non_deepseek |
| 3608 | .build_anthropic_wire_body(&request, true) |
| 3609 | .is_err() |
| 3610 | ); |
| 3611 | |
| 3612 | let mut bad_domain = request; |
| 3613 | bad_domain.tools.as_mut().expect("tools")[0].input_schema = |
| 3614 | json!({ "allowed_domains": ["example.com"] }); |
| 3615 | assert!(client.build_anthropic_wire_body(&bad_domain, true).is_err()); |
| 3616 | } |
| 3617 | |
| 3618 | #[test] |
| 3619 | fn deepseek_anthropic_sse_decodes_web_results_title_citations_and_refusal() { |
| 3620 | let events = [ |
| 3621 | json!({ |
| 3622 | "type": "content_block_start", |
| 3623 | "index": 0, |
| 3624 | "content_block": { |
| 3625 | "type": "server_tool_use", |
| 3626 | "id": "srv_1", |
| 3627 | "name": "deepseek_web_search", |
| 3628 | "kind": "deep_search", |
| 3629 | "input": {} |
| 3630 | } |
| 3631 | }).to_string(), |
| 3632 | json!({ |
| 3633 | "type": "content_block_start", |
| 3634 | "index": 1, |
| 3635 | "content_block": { |
| 3636 | "type": "web_search_tool_result", |
| 3637 | "tool_use_id": "srv_1", |
| 3638 | "kind": "deep_search", |
| 3639 | "content": [{ "type": "web_search_result_location", "url": "https://example.com" }] |
| 3640 | } |
| 3641 | }).to_string(), |
| 3642 | json!({ |
| 3643 | "type": "content_block_delta", |
| 3644 | "index": 2, |
| 3645 | "delta": { |
| 3646 | "type": "citations_delta", |
| 3647 | "citation": { "type": "web_search_result_location", "url": "https://example.com" } |
| 3648 | } |
| 3649 | }).to_string(), |
| 3650 | json!({ |
| 3651 | "type": "message_delta", |
| 3652 | "delta": { |
| 3653 | "stop_reason": "refusal", |
| 3654 | "title": "DeepSeek Chat", |
| 3655 | "refusal": "Content filtered", |
| 3656 | "stop_details": { "category": "safety" } |
| 3657 | }, |
| 3658 | "usage": { |
| 3659 | "output_tokens": 18, |
| 3660 | "safety_tokens": 9, |
| 3661 | "server_tool_use": { |
| 3662 | "web_search_requests": 1, |
| 3663 | "web_fetch_requests": 0, |
| 3664 | "tool_search": 1, |
| 3665 | "tool_fetch": 0, |
| 3666 | "tool_image_search": 2 |
| 3667 | } |
| 3668 | } |
| 3669 | }).to_string(), |
| 3670 | ]; |
| 3671 | |
| 3672 | let decoded: Vec<StreamEvent> = events |
| 3673 | .iter() |
| 3674 | .map(|raw| { |
| 3675 | convert_anthropic_sse_data(raw) |
| 3676 | .expect("sse event succeeds") |
| 3677 | .expect("sse event decoded") |
| 3678 | }) |
| 3679 | .collect(); |
| 3680 | |
| 3681 | assert!(matches!( |
| 3682 | &decoded[0], |
| 3683 | StreamEvent::ContentBlockStart { |
| 3684 | content_block: codewhale_models::ContentBlockStart::ServerToolUse { |
| 3685 | kind: Some(k), .. |
| 3686 | }, .. |
| 3687 | } if k == "deep_search" |
| 3688 | )); |
| 3689 | assert!(matches!( |
| 3690 | &decoded[1], |
| 3691 | StreamEvent::ContentBlockStart { |
| 3692 | content_block: codewhale_models::ContentBlockStart::WebSearchToolResult { |
| 3693 | kind: Some(k), .. |
| 3694 | }, .. |
| 3695 | } if k == "deep_search" |
| 3696 | )); |
| 3697 | assert!(matches!( |
| 3698 | &decoded[2], |
| 3699 | StreamEvent::ContentBlockDelta { |
| 3700 | delta: codewhale_models::Delta::CitationsDelta { .. }, |
| 3701 | .. |
| 3702 | } |
| 3703 | )); |
| 3704 | let StreamEvent::MessageDelta { delta, usage } = &decoded[3] else { |
| 3705 | panic!("expected MessageDelta"); |
| 3706 | }; |
| 3707 | assert_eq!(delta.stop_reason.as_deref(), Some("refusal")); |
| 3708 | assert_eq!(delta.title.as_deref(), Some("DeepSeek Chat")); |
| 3709 | assert_eq!(delta.refusal.as_deref(), Some("Content filtered")); |
| 3710 | let usage = usage.as_ref().expect("usage present"); |
| 3711 | assert_eq!(usage.safety_tokens, Some(9)); |
| 3712 | let stu = usage.server_tool_use.as_ref().expect("server_tool_use"); |
| 3713 | assert_eq!(stu.tool_search, Some(1)); |
| 3714 | assert_eq!(stu.tool_image_search, Some(2)); |
| 3715 | } |
| 3716 | |
| 3717 | #[tokio::test] |
| 3718 | async fn deepseek_anthropic_sends_files_beta_header_and_surfaces_200_error_envelope() { |
| 3719 | use crate::core::model_client::ModelClient; |
| 3720 | use wiremock::matchers::{header, method, path}; |
| 3721 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 3722 | |
| 3723 | let server = MockServer::start().await; |
| 3724 | Mock::given(method("POST")) |
| 3725 | .and(path("/v1/messages")) |
| 3726 | .and(header("anthropic-beta", "files-api-2025-04-14")) |
| 3727 | .respond_with(ResponseTemplate::new(200).set_body_json(json!({ |
| 3728 | "type": "error", |
| 3729 | "error": { "type": "invalid_request_error", "message": "bad file" } |
| 3730 | }))) |
| 3731 | .mount(&server) |
| 3732 | .await; |
| 3733 | |
| 3734 | let client = deepseek_test_client(&server.uri()); |
| 3735 | let request = MessageRequest { |
| 3736 | model: "deepseek-v4".to_string(), |
| 3737 | messages: vec![Message { |
| 3738 | role: Role::User, |
| 3739 | content: vec![ContentBlock::File { |
| 3740 | file_id: "file_1".to_string(), |
| 3741 | }], |
| 3742 | }], |
| 3743 | max_tokens: 128, |
| 3744 | system: None, |
| 3745 | tools: None, |
| 3746 | tool_choice: None, |
| 3747 | metadata: None, |
| 3748 | thinking: None, |
| 3749 | reasoning_effort: None, |
| 3750 | stream: Some(false), |
| 3751 | temperature: None, |
| 3752 | top_p: None, |
| 3753 | safety_check: None, |
| 3754 | title: None, |
| 3755 | }; |
| 3756 | let err = client |
| 3757 | .create_message(request) |
| 3758 | .await |
| 3759 | .expect_err("200 error envelope must surface as Err"); |
| 3760 | assert!(err.to_string().contains("bad file"), "{err}"); |
| 3761 | } |
| 3762 | } |
| 3763 |