| 1 | //! Chat Completions API helpers for DeepSeek's OpenAI-compatible endpoint. |
| 2 | //! |
| 3 | //! This is the production code path. Streaming (`create_message_stream`), |
| 4 | //! request building (`build_chat_messages*`), and SSE parsing |
| 5 | //! (`parse_sse_chunk_with_reasoning_style`) all live here. |
| 6 | |
| 7 | use std::collections::{HashMap, HashSet}; |
| 8 | use std::io::Write; |
| 9 | use std::pin::Pin; |
| 10 | use std::time::Duration; |
| 11 | |
| 12 | use anyhow::{Context, Result, bail}; |
| 13 | use serde::{Deserialize, Serialize}; |
| 14 | use serde_json::{Value, json}; |
| 15 | use tokio::time::timeout as tokio_timeout; |
| 16 | |
| 17 | use codewhale_config::catalog::reviewed::constants::TOGETHER_INKLING_MODEL; |
| 18 | use codewhale_runtime::config::{ |
| 19 | is_exact_direct_moonshot_k3_route, is_exact_kimi_code_k3_route, is_exact_zai_chat_route, |
| 20 | is_exact_zai_forced_thinking_route, is_exact_zai_tiered_effort_route, |
| 21 | is_kimi_code_membership_model, minimax_m3_route_uses_max_completion_tokens, |
| 22 | moonshot_base_url_is_exact_kimi_code, |
| 23 | }; |
| 24 | |
| 25 | use crate::llm_client::StreamEventBox; |
| 26 | use codewhale_config::ProviderKind; |
| 27 | use codewhale_models::tool_projection::{ |
| 28 | RouteToolProjection, ToolSchemaProjection, description_with_constraint_note, forced_tool_name, |
| 29 | project_tool_schema, |
| 30 | }; |
| 31 | use codewhale_models::{ |
| 32 | ContentBlock, ContentBlockStart, Delta, Message, MessageDelta, MessageRequest, MessageResponse, |
| 33 | StreamEvent, SystemPrompt, Tool, ToolCaller, Usage, is_openai_gpt_56_api_model, |
| 34 | model_is_openai_reasoning_family, model_supports_reasoning, |
| 35 | }; |
| 36 | use codewhale_runtime::logging; |
| 37 | |
| 38 | use super::CodewhaleClient; |
| 39 | use super::deepseek_tools::{ |
| 40 | deepseek_web_tool_kind, validate_and_apply_safety_check_and_title, |
| 41 | validate_deepseek_web_tool_choice, validate_deepseek_web_tools, |
| 42 | }; |
| 43 | use super::prepared::WireDialect; |
| 44 | use super::role_placement::{RolePlacement, role_placement}; |
| 45 | use super::wire::{ |
| 46 | ERROR_BODY_MAX_BYTES, SSE_BACKPRESSURE_HIGH_WATERMARK, SSE_BACKPRESSURE_SLEEP_MS, |
| 47 | SSE_MAX_LINES_PER_CHUNK, ToolNameWire, acquire_stream_buffer, bounded_error_text, |
| 48 | check_history_tool_names, documented_tool_name_limit, from_api_tool_name, |
| 49 | over_limit_tool_name_message, parse_usage, release_stream_buffer, system_to_instructions, |
| 50 | to_api_tool_name, tool_name_exceeds_limit, tool_name_limit, |
| 51 | }; |
| 52 | use super::wire::{extract_sse_data_value, flush_sse_line, push_sse_event_data, take_sse_line}; |
| 53 | use codewhale_config::route::RouteLimits; |
| 54 | use codewhale_models::Role; |
| 55 | |
| 56 | fn apply_provider_token_limit( |
| 57 | body: &mut Value, |
| 58 | provider: ProviderKind, |
| 59 | base_url: &str, |
| 60 | model: &str, |
| 61 | max_tokens: u32, |
| 62 | ) { |
| 63 | let use_max_completion_tokens = provider == ProviderKind::XiaomiMimo |
| 64 | || (provider == ProviderKind::Openai && model_is_openai_reasoning_family(model)) |
| 65 | || minimax_m3_route_uses_max_completion_tokens(provider, base_url, model) |
| 66 | || is_exact_direct_moonshot_k3_route(provider, base_url, model); |
| 67 | if !use_max_completion_tokens { |
| 68 | return; |
| 69 | } |
| 70 | |
| 71 | if let Some(object) = body.as_object_mut() { |
| 72 | object.remove("max_tokens"); |
| 73 | } |
| 74 | body["max_completion_tokens"] = json!(max_tokens); |
| 75 | } |
| 76 | |
| 77 | fn apply_openai_reasoning_effort( |
| 78 | body: &mut Value, |
| 79 | provider: ProviderKind, |
| 80 | model: &str, |
| 81 | effort: Option<&str>, |
| 82 | ) { |
| 83 | let model_lower = model.trim().to_ascii_lowercase(); |
| 84 | let is_gpt_56 = |
| 85 | provider == ProviderKind::Openai && is_openai_gpt_56_api_model(model_lower.as_str()); |
| 86 | let is_openai_reasoning = |
| 87 | provider == ProviderKind::Openai && model_is_openai_reasoning_family(model); |
| 88 | let is_muse_spark = provider == ProviderKind::Meta |
| 89 | && (model_lower == "muse-spark" || model_lower.starts_with("muse-spark-")); |
| 90 | if !is_openai_reasoning && !is_muse_spark { |
| 91 | return; |
| 92 | } |
| 93 | let Some(effort) = |
| 94 | effort.and_then(|value| openai_compatible_reasoning_effort(value, is_gpt_56, !is_gpt_56)) |
| 95 | else { |
| 96 | return; |
| 97 | }; |
| 98 | body["reasoning_effort"] = json!(clamp_openai_reasoning_effort(provider, model, effort)); |
| 99 | } |
| 100 | |
| 101 | /// xAI's first-party `reasoning_effort` ladder, driven by the bundled |
| 102 | /// catalog row for the exact model id: a row that documents an `effort` |
| 103 | /// option gets the field (`xhigh` only where the row lists it — grok-4.7 and |
| 104 | /// grok-4.6 do, grok-4.5 maps it to `high`); a row without one (grok-4.3, |
| 105 | /// grok-build) or no row at all sends nothing. Grok reasoning cannot be |
| 106 | /// disabled, so `off` is sent as the documented default `high` |
| 107 | /// (<https://docs.x.ai/docs/guides/reasoning>). |
| 108 | fn apply_xai_grok_reasoning_effort( |
| 109 | body: &mut Value, |
| 110 | provider: ProviderKind, |
| 111 | base_url: &str, |
| 112 | model: &str, |
| 113 | effort: Option<&str>, |
| 114 | ) { |
| 115 | if provider != ProviderKind::Xai |
| 116 | || !codewhale_config::provider::is_exact_xai_platform_route( |
| 117 | codewhale_config::ProviderKind::Xai, |
| 118 | base_url, |
| 119 | ) |
| 120 | { |
| 121 | return; |
| 122 | } |
| 123 | let Some(effort) = effort else { |
| 124 | return; |
| 125 | }; |
| 126 | let model = model.trim().to_ascii_lowercase(); |
| 127 | // The bundled row with Codewhale's corrections applied (#6396): the raw |
| 128 | // seed row carries Models.dev's ladder, which lists an effort control for |
| 129 | // grok-4.3 that xAI does not document. |
| 130 | let Some(row) = |
| 131 | crate::provider_lake::bundled_catalog_offering_for_model(ProviderKind::Xai, &model) |
| 132 | else { |
| 133 | return; |
| 134 | }; |
| 135 | let Some(documented) = row |
| 136 | .reasoning_options |
| 137 | .iter() |
| 138 | .find(|option| option["type"] == "effort") |
| 139 | .and_then(|option| option["values"].as_array()) |
| 140 | else { |
| 141 | return; |
| 142 | }; |
| 143 | let supports_xhigh = documented.iter().any(|value| value == "xhigh"); |
| 144 | let wire_effort = match effort.trim().to_ascii_lowercase().as_str() { |
| 145 | "auto" | "automatic" | "" => return, |
| 146 | "off" | "disabled" | "none" | "false" | "high" => "high", |
| 147 | "minimal" | "minimum" | "low" | "light" => "low", |
| 148 | "medium" | "mid" => "medium", |
| 149 | "xhigh" | "max" | "maximum" | "highest" | "ultra" | "ultracode" => { |
| 150 | if supports_xhigh { |
| 151 | "xhigh" |
| 152 | } else { |
| 153 | "high" |
| 154 | } |
| 155 | } |
| 156 | _ => return, |
| 157 | }; |
| 158 | body["reasoning_effort"] = json!(wire_effort); |
| 159 | } |
| 160 | |
| 161 | fn apply_inkling_reasoning_effort( |
| 162 | body: &mut Value, |
| 163 | provider: ProviderKind, |
| 164 | model: &str, |
| 165 | effort: Option<&str>, |
| 166 | ) { |
| 167 | if provider != ProviderKind::Together |
| 168 | || !model.trim().eq_ignore_ascii_case(TOGETHER_INKLING_MODEL) |
| 169 | { |
| 170 | return; |
| 171 | } |
| 172 | |
| 173 | // Inkling's official chat template accepts OpenAI's top-level |
| 174 | // `reasoning_effort` field with this exact vocabulary. It does not use |
| 175 | // Together's generic `thinking` extension or the `xhigh` wire value. |
| 176 | if let Some(object) = body.as_object_mut() { |
| 177 | object.remove("thinking"); |
| 178 | } |
| 179 | let Some(effort) = effort else { |
| 180 | return; |
| 181 | }; |
| 182 | let wire_effort = match effort.trim().to_ascii_lowercase().as_str() { |
| 183 | "off" | "disabled" | "none" | "false" => "none", |
| 184 | "minimal" => "minimal", |
| 185 | "low" => "low", |
| 186 | "medium" | "mid" | "" => "medium", |
| 187 | "high" => "high", |
| 188 | "max" | "xhigh" | "highest" | "ultra" | "ultracode" => "max", |
| 189 | _ => return, |
| 190 | }; |
| 191 | body["reasoning_effort"] = json!(wire_effort); |
| 192 | } |
| 193 | |
| 194 | /// Apply Kimi Code K3's route-specific nested thinking effort after the |
| 195 | /// generic Moonshot shaping. Other Moonshot and Kimi-compatible routes accept |
| 196 | /// only the generic enabled/disabled form, so the exact endpoint and bare |
| 197 | /// model identifier are both part of this guard. |
| 198 | fn apply_kimi_code_k3_reasoning_effort( |
| 199 | body: &mut Value, |
| 200 | provider: ProviderKind, |
| 201 | base_url: &str, |
| 202 | model: &str, |
| 203 | effort: Option<&str>, |
| 204 | ) { |
| 205 | if !is_exact_kimi_code_k3_route(provider, base_url, model) { |
| 206 | return; |
| 207 | } |
| 208 | let Some(effort) = effort else { |
| 209 | return; |
| 210 | }; |
| 211 | |
| 212 | let thinking = match effort.trim().to_ascii_lowercase().as_str() { |
| 213 | "off" | "none" | "disabled" | "false" | "low" | "minimum" | "minimal" | "light" => { |
| 214 | json!({ "type": "enabled", "effort": "low" }) |
| 215 | } |
| 216 | "medium" | "high" => json!({ "type": "enabled", "effort": "high" }), |
| 217 | "xhigh" | "ultra" | "max" => json!({ "type": "enabled", "effort": "max" }), |
| 218 | _ => return, |
| 219 | }; |
| 220 | |
| 221 | // K3 uses the nested `thinking.effort` dialect. Do not leave an |
| 222 | // OpenAI-style effort value behind if another shaping layer was added |
| 223 | // before this route-specific override. |
| 224 | if let Some(object) = body.as_object_mut() { |
| 225 | object.remove("reasoning_effort"); |
| 226 | } |
| 227 | body["thinking"] = thinking; |
| 228 | } |
| 229 | |
| 230 | /// Apply Moonshot's direct K3 reasoning dialect. |
| 231 | /// |
| 232 | /// The pay-as-you-go K3 endpoint is always-thinking and accepts only the |
| 233 | /// top-level `reasoning_effort` values low/high/max. In particular, a generic |
| 234 | /// Moonshot `thinking: {type: disabled}` payload is not truthful for this |
| 235 | /// route. Treat a legacy raw `off` as the lowest supported tier defensively; |
| 236 | /// route-aware callers normalize it before it reaches this layer. |
| 237 | fn apply_direct_moonshot_k3_reasoning_effort( |
| 238 | body: &mut Value, |
| 239 | provider: ProviderKind, |
| 240 | base_url: &str, |
| 241 | model: &str, |
| 242 | effort: Option<&str>, |
| 243 | ) { |
| 244 | if !is_exact_direct_moonshot_k3_route(provider, base_url, model) { |
| 245 | return; |
| 246 | } |
| 247 | |
| 248 | if let Some(object) = body.as_object_mut() { |
| 249 | object.remove("thinking"); |
| 250 | object.remove("reasoning_effort"); |
| 251 | } |
| 252 | let Some(effort) = effort else { |
| 253 | return; |
| 254 | }; |
| 255 | let wire_effort = match effort.trim().to_ascii_lowercase().as_str() { |
| 256 | "off" | "none" | "disabled" | "false" | "low" | "minimum" | "minimal" | "light" => "low", |
| 257 | "medium" | "mid" | "high" | "" => "high", |
| 258 | "xhigh" | "ultra" | "max" | "highest" | "ultracode" => "max", |
| 259 | // `auto` and unknown legacy values leave the field omitted so the |
| 260 | // direct API owns its documented default (`max`). |
| 261 | _ => return, |
| 262 | }; |
| 263 | body["reasoning_effort"] = json!(wire_effort); |
| 264 | } |
| 265 | |
| 266 | /// Keep Z.ai controls on exact first-party routes only. The tiered-effort GLM |
| 267 | /// models (5.2, and the forced-thinking 5.3 family) receive the documented |
| 268 | /// top-level effort, GLM-5.1 and GLM-5-Turbo keep only the generic thinking |
| 269 | /// toggle, and compatible gateways receive neither field because their |
| 270 | /// request dialect is not known from provider/model selection alone. |
| 271 | fn apply_zai_route_reasoning_controls( |
| 272 | body: &mut Value, |
| 273 | provider: ProviderKind, |
| 274 | base_url: &str, |
| 275 | model: &str, |
| 276 | effort: Option<&str>, |
| 277 | ) { |
| 278 | if provider != ProviderKind::Zai { |
| 279 | return; |
| 280 | } |
| 281 | |
| 282 | if let Some(object) = body.as_object_mut() { |
| 283 | object.remove("reasoning_effort"); |
| 284 | if !is_exact_zai_chat_route(provider, base_url) { |
| 285 | // A compatible gateway owns its own request dialect. Provider/model |
| 286 | // selection alone is not evidence that Z.ai's `thinking` object is |
| 287 | // supported there, so fail closed instead of leaking it. |
| 288 | object.remove("thinking"); |
| 289 | return; |
| 290 | } |
| 291 | } |
| 292 | if !codewhale_runtime::config::is_exact_known_zai_reasoning_route(provider, base_url, model) { |
| 293 | if let Some(object) = body.as_object_mut() { |
| 294 | object.remove("thinking"); |
| 295 | } |
| 296 | return; |
| 297 | } |
| 298 | if !is_exact_zai_tiered_effort_route(provider, base_url, model) { |
| 299 | // Exact first-party GLM-5-Turbo and GLM-5.1 keep only the generic |
| 300 | // enabled/disabled thinking control. |
| 301 | return; |
| 302 | } |
| 303 | if is_exact_zai_forced_thinking_route(provider, base_url, model) { |
| 304 | apply_zai_forced_thinking_effort(body, effort); |
| 305 | return; |
| 306 | } |
| 307 | match effort |
| 308 | .map(|value| value.trim().to_ascii_lowercase()) |
| 309 | .as_deref() |
| 310 | { |
| 311 | Some("high") => body["reasoning_effort"] = json!("high"), |
| 312 | Some("xhigh") | Some("max") | Some("highest") | Some("ultra") | Some("ultracode") => { |
| 313 | body["reasoning_effort"] = json!("max"); |
| 314 | } |
| 315 | // Off, lower tiers, omitted effort, and unknown legacy values retain |
| 316 | // only the generic Z.ai thinking control. |
| 317 | _ => {} |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | /// GLM-5.3 and GLM-5.3-Flash are forced-thinking on the exact first-party |
| 322 | /// Z.ai route: `thinking.type: "disabled"` is rejected with an error and |
| 323 | /// `reasoning_effort` accepts only low/high/max. The generic Z.ai layer emits |
| 324 | /// `disabled` for `off`, so a request that was valid for GLM-5.2 fails on |
| 325 | /// 5.3. Rewrite that payload the way the vendor migration note prescribes — |
| 326 | /// keep thinking enabled and send the lowest tier — and map the remaining |
| 327 | /// aliases onto the three documented values, leaving unknown legacy values |
| 328 | /// omitted so the API owns its documented default (`max`). |
| 329 | fn apply_zai_forced_thinking_effort(body: &mut Value, effort: Option<&str>) { |
| 330 | let thinking_disabled = body |
| 331 | .get("thinking") |
| 332 | .and_then(|thinking| thinking.get("type")) |
| 333 | .and_then(Value::as_str) |
| 334 | == Some("disabled"); |
| 335 | if thinking_disabled { |
| 336 | body["thinking"] = json!({ |
| 337 | "type": "enabled", |
| 338 | "clear_thinking": false, |
| 339 | }); |
| 340 | } |
| 341 | let Some(effort) = effort else { |
| 342 | return; |
| 343 | }; |
| 344 | let wire_effort = match effort.trim().to_ascii_lowercase().as_str() { |
| 345 | "off" | "none" | "disabled" | "false" | "low" | "minimum" | "minimal" | "light" => "low", |
| 346 | "medium" | "mid" | "high" => "high", |
| 347 | "xhigh" | "max" | "highest" | "ultra" | "ultracode" => "max", |
| 348 | _ => return, |
| 349 | }; |
| 350 | body["reasoning_effort"] = json!(wire_effort); |
| 351 | } |
| 352 | |
| 353 | /// Add MiniMax's Chat-only reasoning controls only when endpoint and model |
| 354 | /// prove the exact first-party M3 route. A provider label alone is not enough |
| 355 | /// to send MiniMax-specific fields to a compatible gateway or unknown model. |
| 356 | fn resolved_minimax_wire_effort( |
| 357 | effort: Option<&str>, |
| 358 | reasoning_options: Option<&[Value]>, |
| 359 | ) -> Option<&'static str> { |
| 360 | let effort = effort?.trim().to_ascii_lowercase(); |
| 361 | if matches!(effort.as_str(), "" | "off" | "disabled" | "none" | "false") { |
| 362 | return None; |
| 363 | } |
| 364 | let values = reasoning_options?.iter().find_map(|option| { |
| 365 | (option.get("type").and_then(Value::as_str) == Some("effort")) |
| 366 | .then(|| option.get("values").and_then(Value::as_array)) |
| 367 | .flatten() |
| 368 | })?; |
| 369 | let preferences: &[&str] = match effort.as_str() { |
| 370 | "low" | "minimal" => &["low", "minimal", "medium", "high"], |
| 371 | "medium" | "mid" => &["medium", "mid", "high", "low"], |
| 372 | "xhigh" => &["xhigh", "max", "high", "medium", "low"], |
| 373 | "max" | "highest" | "ultra" | "ultracode" => &["max", "xhigh", "high", "medium", "low"], |
| 374 | _ => &["high", "medium", "max", "xhigh", "low"], |
| 375 | }; |
| 376 | preferences.iter().copied().find(|candidate| { |
| 377 | values |
| 378 | .iter() |
| 379 | .any(|value| value.as_str() == Some(*candidate)) |
| 380 | }) |
| 381 | } |
| 382 | |
| 383 | fn apply_minimax_route_reasoning_controls( |
| 384 | body: &mut Value, |
| 385 | provider: ProviderKind, |
| 386 | base_url: &str, |
| 387 | model: &str, |
| 388 | effort: Option<&str>, |
| 389 | reasoning_options: Option<&[Value]>, |
| 390 | ) { |
| 391 | if provider != ProviderKind::Minimax { |
| 392 | return; |
| 393 | } |
| 394 | if let Some(object) = body.as_object_mut() { |
| 395 | object.remove("reasoning_split"); |
| 396 | object.remove("thinking"); |
| 397 | object.remove("reasoning_effort"); |
| 398 | } |
| 399 | let resolved_offering = reasoning_options.is_none().then(|| { |
| 400 | crate::provider_lake::catalog_offering_for_model(ProviderKind::Minimax, model.trim()) |
| 401 | }); |
| 402 | let offering = resolved_offering.as_ref().and_then(Option::as_ref); |
| 403 | let effective_options = |
| 404 | reasoning_options.or_else(|| offering.map(|row| row.reasoning_options.as_slice())); |
| 405 | let catalog_supported = |
| 406 | codewhale_config::provider::is_exact_minimax_chat_route(provider, base_url) |
| 407 | && effective_options.is_some_and(|options| !options.is_empty()) |
| 408 | && offering.is_none_or(|row| row.reasoning != Some(false)); |
| 409 | if !codewhale_runtime::config::is_exact_minimax_m3_route(provider, base_url, model) |
| 410 | && !catalog_supported |
| 411 | { |
| 412 | return; |
| 413 | } |
| 414 | |
| 415 | body["reasoning_split"] = json!(true); |
| 416 | match effort |
| 417 | .map(|value| value.trim().to_ascii_lowercase()) |
| 418 | .as_deref() |
| 419 | { |
| 420 | Some("off" | "disabled" | "none" | "false") => { |
| 421 | body["thinking"] = json!({ "type": "disabled" }); |
| 422 | } |
| 423 | Some( |
| 424 | "low" | "minimal" | "medium" | "mid" | "high" | "xhigh" | "max" | "highest" | "ultra" |
| 425 | | "ultracode" | "", |
| 426 | ) => { |
| 427 | body["thinking"] = json!({ "type": "adaptive" }); |
| 428 | if let Some(wire_effort) = resolved_minimax_wire_effort(effort, effective_options) { |
| 429 | body["reasoning_effort"] = json!(wire_effort); |
| 430 | } |
| 431 | } |
| 432 | _ => {} |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | /// Model Studio's OpenAI-compatible API uses its own top-level reasoning |
| 437 | /// controls. Keep them on verified Alibaba Chat Completions routes: a custom |
| 438 | /// `base_url` points the same provider identity at an arbitrary gateway, and |
| 439 | /// that gateway must not be handed Alibaba's dialect. |
| 440 | /// |
| 441 | /// This is the *sole* writer of Model Studio reasoning fields — |
| 442 | /// `apply_reasoning_effort` deliberately writes nothing for the `Modelstudio*` |
| 443 | /// identities — so the strip below runs for all four variants, including the |
| 444 | /// two Anthropic-dialect ones. Those normally reach the Messages adapter |
| 445 | /// instead, but `wire = "openai"` can route them here, and an unmatched |
| 446 | /// `enable_thinking` left in the body would then go out unguarded. |
| 447 | fn apply_modelstudio_route_reasoning_controls( |
| 448 | body: &mut Value, |
| 449 | provider: ProviderKind, |
| 450 | base_url: &str, |
| 451 | model: &str, |
| 452 | effort: Option<&str>, |
| 453 | ) { |
| 454 | if !matches!( |
| 455 | provider, |
| 456 | ProviderKind::ModelstudioTokenPlan |
| 457 | | ProviderKind::ModelstudioTokenPlanAnthropic |
| 458 | | ProviderKind::ModelstudioCodingPlan |
| 459 | | ProviderKind::ModelstudioCodingPlanAnthropic |
| 460 | ) { |
| 461 | return; |
| 462 | } |
| 463 | |
| 464 | if let Some(object) = body.as_object_mut() { |
| 465 | object.remove("thinking"); |
| 466 | object.remove("enable_thinking"); |
| 467 | object.remove("preserve_thinking"); |
| 468 | object.remove("reasoning_effort"); |
| 469 | } |
| 470 | if !is_exact_modelstudio_chat_route(provider, base_url) { |
| 471 | return; |
| 472 | } |
| 473 | |
| 474 | let thinking_only = modelstudio_model_is_thinking_only(model); |
| 475 | if !thinking_only && !modelstudio_model_is_hybrid(model) { |
| 476 | return; |
| 477 | } |
| 478 | |
| 479 | let thinking_enabled = !modelstudio_effort_disables_thinking(effort); |
| 480 | // Thinking-only models emit `reasoning_content` but reject an |
| 481 | // enable/disable control. Hybrid models use `enable_thinking`. |
| 482 | if !thinking_only { |
| 483 | body["enable_thinking"] = json!(thinking_enabled); |
| 484 | } |
| 485 | if modelstudio_model_supports_preserve_thinking(model) { |
| 486 | // Model Studio otherwise drops assistant `reasoning_content` from the |
| 487 | // next turn's context. This applies even when the provider default |
| 488 | // leaves thinking enabled and no explicit UI effort was selected. |
| 489 | body["preserve_thinking"] = json!(thinking_only || thinking_enabled); |
| 490 | } |
| 491 | if !thinking_only |
| 492 | && thinking_enabled |
| 493 | && let Some(effort) = effort.and_then(modelstudio_reasoning_effort_for_model) |
| 494 | && modelstudio_model_supports_reasoning_effort(model) |
| 495 | { |
| 496 | body["reasoning_effort"] = json!(effort); |
| 497 | } |
| 498 | } |
| 499 | |
| 500 | /// Fail-closed host guard: only Alibaba's own OpenAI-compatible Chat |
| 501 | /// Completions URL shapes count. Anything else (a proxy, a self-hosted |
| 502 | /// gateway, a typo) gets the Model Studio fields stripped and nothing added. |
| 503 | fn is_exact_modelstudio_chat_route(provider: ProviderKind, base_url: &str) -> bool { |
| 504 | let trimmed = base_url.trim().trim_end_matches('/').to_ascii_lowercase(); |
| 505 | let Some((host, path)) = trimmed |
| 506 | .strip_prefix("https://") |
| 507 | .and_then(|rest| rest.split_once('/')) |
| 508 | else { |
| 509 | return false; |
| 510 | }; |
| 511 | |
| 512 | // Includes Token Plan's default and workspace-scoped |
| 513 | // `{workspace}.<region>.maas.aliyuncs.com/compatible-mode/v1` hosts. |
| 514 | let token_plan_chat = host.ends_with(".maas.aliyuncs.com") && path == "compatible-mode/v1"; |
| 515 | let coding_plan_chat = host == "coding-intl.dashscope.aliyuncs.com" && path == "v1"; |
| 516 | // Alibaba's classic pay-as-you-go DashScope endpoints serve the same |
| 517 | // models and the same dialect; leaving them off the allowlist silently |
| 518 | // stripped every reasoning control on a genuine Alibaba host |
| 519 | // (2026-08-04 review). The intl spelling matches the repo's own |
| 520 | // provider defaults. |
| 521 | let classic_dashscope_chat = matches!( |
| 522 | host, |
| 523 | "dashscope.aliyuncs.com" | "dashscope-intl.aliyuncs.com" |
| 524 | ) && path == "compatible-mode/v1"; |
| 525 | |
| 526 | match provider { |
| 527 | // The primary Model Studio provider selects Coding Plan through |
| 528 | // `mode = "coding-plan"`, which resolves this base URL without |
| 529 | // changing the provider enum. Legacy Coding Plan identities remain |
| 530 | // supported as well, so recognize either official Chat route for the |
| 531 | // complete Model Studio OpenAI family. The `*Anthropic` identities |
| 532 | // speak the Messages dialect and are never verified here. |
| 533 | ProviderKind::ModelstudioTokenPlan | ProviderKind::ModelstudioCodingPlan => { |
| 534 | token_plan_chat || coding_plan_chat || classic_dashscope_chat |
| 535 | } |
| 536 | _ => false, |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | fn is_exact_modelstudio_thinking_only_route( |
| 541 | provider: ProviderKind, |
| 542 | base_url: &str, |
| 543 | model: &str, |
| 544 | ) -> bool { |
| 545 | is_exact_modelstudio_chat_route(provider, base_url) && modelstudio_model_is_thinking_only(model) |
| 546 | } |
| 547 | |
| 548 | fn modelstudio_effort_disables_thinking(effort: Option<&str>) -> bool { |
| 549 | effort.is_some_and(|value| { |
| 550 | matches!( |
| 551 | value.trim().to_ascii_lowercase().as_str(), |
| 552 | "off" | "disabled" | "none" | "false" |
| 553 | ) |
| 554 | }) |
| 555 | } |
| 556 | |
| 557 | /// Models with no enable/disable control at all. `models_dev.bundled.json` |
| 558 | /// lists `qwen3.8-max` as `thinking: always_on` and gives `qwen3.8-max-preview` |
| 559 | /// effort/budget options with no `toggle`, so sending `enable_thinking` to |
| 560 | /// either is at best ignored and at worst a 400. |
| 561 | fn modelstudio_model_is_thinking_only(model: &str) -> bool { |
| 562 | let model = model.trim().to_ascii_lowercase(); |
| 563 | matches!( |
| 564 | model.as_str(), |
| 565 | "qwen3.8-max" |
| 566 | | "qwen3.8-max-preview" |
| 567 | // Kimi K2.7 Code is always-thinking. Keep both Alibaba-hosted and |
| 568 | // Moonshot-supplied exact IDs separate from hybrid Kimi variants |
| 569 | // so we never send the unsupported enable_thinking switch. |
| 570 | | "kimi-k2.7-code" |
| 571 | | "kimi/kimi-k2.7-code" |
| 572 | | "kimi/kimi-k2.7-code-highspeed" |
| 573 | ) |
| 574 | } |
| 575 | |
| 576 | fn modelstudio_model_is_hybrid(model: &str) -> bool { |
| 577 | let model = model.trim().to_ascii_lowercase(); |
| 578 | model.starts_with("qwen3.7-") |
| 579 | || model.starts_with("qwen3.6-") |
| 580 | || model.starts_with("qwen3.5-") |
| 581 | || model.starts_with("qwen3-") |
| 582 | || model.starts_with("deepseek-v4") |
| 583 | || model.starts_with("deepseek-v3.2") |
| 584 | || model.starts_with("deepseek-v3.1") |
| 585 | || model.starts_with("kimi-k2.6") |
| 586 | || matches!(model.as_str(), "kimi/kimi-k2.6") |
| 587 | || model.starts_with("kimi-k2.5") |
| 588 | || model.starts_with("glm-") |
| 589 | } |
| 590 | |
| 591 | fn modelstudio_model_supports_preserve_thinking(model: &str) -> bool { |
| 592 | let model = model.trim().to_ascii_lowercase(); |
| 593 | matches!( |
| 594 | model.as_str(), |
| 595 | "qwen3.7-max" |
| 596 | | "qwen3.7-max-us" |
| 597 | | "qwen3.7-max-2026-05-17" |
| 598 | | "qwen3.7-max-2026-05-20" |
| 599 | | "qwen3.7-max-2026-06-08" |
| 600 | | "qwen3.7-max-preview" |
| 601 | | "qwen3.7-plus" |
| 602 | | "qwen3.7-plus-us" |
| 603 | | "qwen3.7-plus-2026-05-26" |
| 604 | | "qwen3.6-max-preview" |
| 605 | | "qwen3.6-plus" |
| 606 | | "qwen3.6-plus-2026-04-02" |
| 607 | | "qwen3.6-flash" |
| 608 | | "qwen3.6-flash-2026-04-16" |
| 609 | | "kimi-k2.6" |
| 610 | | "kimi-k2.7-code" |
| 611 | | "kimi/kimi-k2.6" |
| 612 | | "kimi/kimi-k2.7-code" |
| 613 | | "kimi/kimi-k2.7-code-highspeed" |
| 614 | ) |
| 615 | } |
| 616 | |
| 617 | fn modelstudio_model_supports_reasoning_effort(model: &str) -> bool { |
| 618 | let model = model.trim().to_ascii_lowercase(); |
| 619 | model.starts_with("deepseek-v4") || matches!(model.as_str(), "glm-5.2" | "glm-5.1" | "glm-5") |
| 620 | } |
| 621 | |
| 622 | fn modelstudio_reasoning_effort_for_model(effort: &str) -> Option<&'static str> { |
| 623 | match effort.trim().to_ascii_lowercase().as_str() { |
| 624 | // Model Studio documents low and medium as aliases for high. |
| 625 | "minimal" | "low" | "medium" | "mid" | "high" | "" => Some("high"), |
| 626 | "xhigh" | "max" | "highest" | "ultra" | "ultracode" => Some("max"), |
| 627 | _ => None, |
| 628 | } |
| 629 | } |
| 630 | |
| 631 | /// Whether `base_url` points at one of DeepSeek's own Chat Completions hosts. |
| 632 | /// |
| 633 | /// The decision is the host's, not the path's: `https://api.deepseek.com/openai` |
| 634 | /// is still DeepSeek, and treating a non-canonical path as a gateway would send |
| 635 | /// `reasoning_effort: "none"` to the real endpoint, which documents no such tier |
| 636 | /// on this wire. Scheme stays exact so an http downgrade cannot claim the |
| 637 | /// dialect. |
| 638 | /// |
| 639 | /// The host set deliberately includes the legacy typo host `api.deepseeki.com`, |
| 640 | /// which `docs/REBRAND.md` records as not an official endpoint and kept only for |
| 641 | /// existing configs (#1079). `deepseek_base_url_supports_strict_tools`, the beta |
| 642 | /// path guard, and the Responses dialect all accept it too; excluding it here |
| 643 | /// would make the same host DeepSeek for strict tools and Responses but not for |
| 644 | /// reasoning, silently dropping the toggle those configs rely on. |
| 645 | fn is_deepseek_chat_host(base_url: &str) -> bool { |
| 646 | reqwest::Url::parse(base_url.trim()).is_ok_and(|url| { |
| 647 | url.scheme() == "https" |
| 648 | && matches!( |
| 649 | url.host_str(), |
| 650 | Some("api.deepseek.com" | "api.deepseeki.com") |
| 651 | ) |
| 652 | }) |
| 653 | } |
| 654 | |
| 655 | /// Final reasoning-control pass shared by streaming and non-streaming Chat |
| 656 | /// Completions requests. Route-specific shapers run first so they can remove |
| 657 | /// fields that are invalid for their exact endpoint; the gateway cleanup below |
| 658 | /// runs last, so nothing in this function can re-add what it removes. |
| 659 | /// |
| 660 | /// Which dialect a route speaks is decided by the endpoint, not by the model id. |
| 661 | /// A route labeled `deepseek` speaks DeepSeek's, and so does a `custom` row |
| 662 | /// pointed at DeepSeek's own host. A `custom` row pointed anywhere else may |
| 663 | /// still carry a DeepSeek model id, but the endpoint's dialect is unknown: it |
| 664 | /// keeps the documented `reasoning_effort` spelling and loses the native |
| 665 | /// `thinking` object, which the gateway this was reproduced against rejects |
| 666 | /// outright on `/v1/chat/completions`. |
| 667 | /// |
| 668 | /// `off` is expressed as `reasoning_effort: "none"` on such a route, the OpenAI |
| 669 | /// compatibility spelling this repository already maps `off` to for other |
| 670 | /// compatible routes. On the gateway this was verified against, `none` stopped |
| 671 | /// thinking (`reasoning_tokens: 0`, no reasoning field) rather than merely |
| 672 | /// omitting the control. A gateway that validates the field fails loudly; one |
| 673 | /// that silently ignores unknown values would fall back to its own default |
| 674 | /// while the replay gate skips `reasoning_content` for `off` — which is why this |
| 675 | /// mapping is only self-consistent on gateways that implement `none`. |
| 676 | pub(super) fn apply_route_reasoning_controls( |
| 677 | body: &mut Value, |
| 678 | provider: ProviderKind, |
| 679 | base_url: &str, |
| 680 | model: &str, |
| 681 | effort: Option<&str>, |
| 682 | ) { |
| 683 | apply_route_reasoning_controls_with_options(body, provider, base_url, model, effort, None); |
| 684 | } |
| 685 | |
| 686 | pub(super) fn apply_route_reasoning_controls_with_options( |
| 687 | body: &mut Value, |
| 688 | provider: ProviderKind, |
| 689 | base_url: &str, |
| 690 | model: &str, |
| 691 | effort: Option<&str>, |
| 692 | reasoning_options: Option<&[Value]>, |
| 693 | ) { |
| 694 | let custom_claims_deepseek_model = |
| 695 | provider == ProviderKind::Custom && requires_reasoning_content(model); |
| 696 | let gateway_drops_deepseek_dialect = |
| 697 | custom_claims_deepseek_model && !is_deepseek_chat_host(base_url); |
| 698 | let reasoning_provider = if provider == ProviderKind::Deepseek || custom_claims_deepseek_model { |
| 699 | ProviderKind::Deepseek |
| 700 | } else { |
| 701 | provider |
| 702 | }; |
| 703 | super::reasoning_effort::apply_reasoning_effort_with_options( |
| 704 | body, |
| 705 | effort, |
| 706 | reasoning_provider, |
| 707 | reasoning_options, |
| 708 | ); |
| 709 | codewhale_config::local_reasoning::apply_local_reasoning_controls( |
| 710 | body, provider, model, effort, |
| 711 | ); |
| 712 | apply_modelstudio_route_reasoning_controls(body, provider, base_url, model, effort); |
| 713 | apply_minimax_route_reasoning_controls( |
| 714 | body, |
| 715 | provider, |
| 716 | base_url, |
| 717 | model, |
| 718 | effort, |
| 719 | reasoning_options, |
| 720 | ); |
| 721 | apply_inkling_reasoning_effort(body, provider, model, effort); |
| 722 | apply_openai_reasoning_effort(body, provider, model, effort); |
| 723 | apply_xai_grok_reasoning_effort(body, provider, base_url, model, effort); |
| 724 | apply_direct_moonshot_k3_reasoning_effort(body, provider, base_url, model, effort); |
| 725 | apply_kimi_code_k3_reasoning_effort(body, provider, base_url, model, effort); |
| 726 | apply_zai_route_reasoning_controls(body, provider, base_url, model, effort); |
| 727 | apply_mistral_route_reasoning_controls(body, provider, base_url, model, effort); |
| 728 | apply_google_reasoning_effort(body, base_url, model, effort); |
| 729 | if gateway_drops_deepseek_dialect { |
| 730 | if let Some(object) = body.as_object_mut() { |
| 731 | object.remove("thinking"); |
| 732 | } |
| 733 | if effort.is_some_and(|effort| !reasoning_effort_enables_thinking(Some(effort))) |
| 734 | && body.get("reasoning_effort").is_none() |
| 735 | { |
| 736 | body["reasoning_effort"] = json!("none"); |
| 737 | } |
| 738 | } |
| 739 | } |
| 740 | |
| 741 | /// Mistral's polymorphic reasoning-content contract is only proven on its |
| 742 | /// first-party Chat Completions endpoints. A configured `mistral` provider may |
| 743 | /// point at an arbitrary OpenAI-compatible gateway, so provider identity alone |
| 744 | /// is not enough to opt that route into Mistral's request or response dialect. |
| 745 | fn is_exact_mistral_chat_route(provider: ProviderKind, base_url: &str) -> bool { |
| 746 | if provider != ProviderKind::Mistral { |
| 747 | return false; |
| 748 | } |
| 749 | let trimmed = base_url.trim().trim_end_matches('/').to_ascii_lowercase(); |
| 750 | let Some((host, path)) = trimmed |
| 751 | .strip_prefix("https://") |
| 752 | .and_then(|rest| rest.split_once('/')) |
| 753 | else { |
| 754 | return false; |
| 755 | }; |
| 756 | matches!( |
| 757 | host, |
| 758 | "api.mistral.ai" | "api.eu.mistral.ai" | "api.us.mistral.ai" |
| 759 | ) && path == "v1" |
| 760 | } |
| 761 | |
| 762 | /// Google's OpenAI-compatibility route, identified by the **resolved base |
| 763 | /// URL** rather than by provider identity. Thought signatures are captured |
| 764 | /// from tool-call `extra_content.google.thought_signature` and replayed on |
| 765 | /// the assistant tool-call messages of later turns; thinking models fail |
| 766 | /// closed when a replayed call has no signature. |
| 767 | /// |
| 768 | /// The endpoint carries the signature contract, not the config row that |
| 769 | /// happens to name it: a manually configured `kind="openai-compatible"` |
| 770 | /// provider ([`ProviderKind::Custom`]) pointed at this exact host and path is |
| 771 | /// byte-for-byte the same endpoint as the built-in `google` row, so it must |
| 772 | /// preserve and replay signatures the same way. The converse still holds — |
| 773 | /// a `google` row pointed at some other gateway is not this route and never |
| 774 | /// carries Google-only fields off-endpoint. |
| 775 | fn is_google_openai_compat_chat_route(base_url: &str) -> bool { |
| 776 | let trimmed = base_url.trim().trim_end_matches('/').to_ascii_lowercase(); |
| 777 | let Some((host, path)) = trimmed |
| 778 | .strip_prefix("https://") |
| 779 | .and_then(|rest| rest.split_once('/')) |
| 780 | else { |
| 781 | return false; |
| 782 | }; |
| 783 | host == "generativelanguage.googleapis.com" && path == "v1beta/openai" |
| 784 | } |
| 785 | |
| 786 | fn resolve_google_route_model(model: &str) -> Option<String> { |
| 787 | codewhale_config::route::resolve_model(ProviderKind::Google, model, None) |
| 788 | .ok() |
| 789 | .filter(|resolved| !resolved.is_auto) |
| 790 | .map(|resolved| resolved.wire_id) |
| 791 | } |
| 792 | |
| 793 | fn google_model_requires_thought_signatures(model: &str) -> bool { |
| 794 | resolve_google_route_model(model) |
| 795 | .as_deref() |
| 796 | .is_some_and(codewhale_models::model_requires_thought_signatures) |
| 797 | } |
| 798 | |
| 799 | fn apply_google_reasoning_effort( |
| 800 | body: &mut serde_json::Value, |
| 801 | base_url: &str, |
| 802 | model: &str, |
| 803 | effort: Option<&str>, |
| 804 | ) { |
| 805 | if !is_google_openai_compat_chat_route(base_url) { |
| 806 | return; |
| 807 | } |
| 808 | let Some(effort) = effort else { |
| 809 | return; |
| 810 | }; |
| 811 | let resolved = resolve_google_route_model(model); |
| 812 | let can_disable = resolved |
| 813 | .as_deref() |
| 814 | .is_some_and(codewhale_models::model_can_disable_thinking); |
| 815 | let offering = resolved.as_deref().and_then(|wire_id| { |
| 816 | crate::provider_lake::bundled_catalog_offering_for_model(ProviderKind::Google, wire_id) |
| 817 | }); |
| 818 | let declared_efforts: Option<Vec<&str>> = offering.as_ref().and_then(|row| { |
| 819 | row.reasoning_options |
| 820 | .iter() |
| 821 | .find(|option| option["type"] == "effort") |
| 822 | .and_then(|option| option["values"].as_array()) |
| 823 | .map(|values| values.iter().filter_map(Value::as_str).collect()) |
| 824 | }); |
| 825 | let has_declared = |target: &str| { |
| 826 | declared_efforts |
| 827 | .as_ref() |
| 828 | .is_some_and(|efforts| efforts.contains(&target)) |
| 829 | }; |
| 830 | let normalized = effort.trim().to_ascii_lowercase(); |
| 831 | if matches!(normalized.as_str(), "auto" | "automatic") { |
| 832 | if let Some(object) = body.as_object_mut() { |
| 833 | object.remove("reasoning_effort"); |
| 834 | } |
| 835 | return; |
| 836 | } |
| 837 | let effort = match normalized.as_str() { |
| 838 | "off" | "disabled" | "none" | "false" if can_disable => "none", |
| 839 | "off" | "disabled" | "none" | "false" | "minimal" | "minimum" => { |
| 840 | if declared_efforts.is_some() && !has_declared("minimal") && has_declared("low") { |
| 841 | "low" |
| 842 | } else { |
| 843 | "minimal" |
| 844 | } |
| 845 | } |
| 846 | "low" | "light" => "low", |
| 847 | "medium" | "mid" | "" => { |
| 848 | if declared_efforts.is_some() && !has_declared("medium") { |
| 849 | if has_declared("high") { "high" } else { "low" } |
| 850 | } else { |
| 851 | "medium" |
| 852 | } |
| 853 | } |
| 854 | "high" => "high", |
| 855 | "xhigh" | "max" | "maximum" | "highest" | "ultra" | "ultracode" => { |
| 856 | if has_declared("xhigh") { |
| 857 | "xhigh" |
| 858 | } else { |
| 859 | "high" |
| 860 | } |
| 861 | } |
| 862 | _ => return, |
| 863 | }; |
| 864 | body["reasoning_effort"] = json!(effort); |
| 865 | } |
| 866 | |
| 867 | /// Fail closed before transport when Google's OpenAI-compat route would |
| 868 | /// replay tool calls without the thought signatures Google's thinking models |
| 869 | /// require. The error names the model and the tool call and tells the |
| 870 | /// operator how to recover instead of letting Google reject or corrupt the |
| 871 | /// tool loop. |
| 872 | /// |
| 873 | /// Models whose thinking is off by default (Gemini 2.5 Flash-Lite) degrade |
| 874 | /// instead of failing — but never silently: the unsigned replay is reported |
| 875 | /// through the same warning path the reasoning-replay sanitizer uses, so a |
| 876 | /// later tool-turn failure has a receipt. Only tool-call identifiers and the |
| 877 | /// model id are logged; signature bytes never are. |
| 878 | fn validate_google_thought_signature_replay( |
| 879 | base_url: &str, |
| 880 | model: &str, |
| 881 | messages: &[Value], |
| 882 | ) -> Result<()> { |
| 883 | if !is_google_openai_compat_chat_route(base_url) { |
| 884 | return Ok(()); |
| 885 | } |
| 886 | let requires_signatures = google_model_requires_thought_signatures(model); |
| 887 | let mut unsigned_call_ids: Vec<&str> = Vec::new(); |
| 888 | for message in messages { |
| 889 | let Some(tool_calls) = message.get("tool_calls").and_then(Value::as_array) else { |
| 890 | continue; |
| 891 | }; |
| 892 | let Some(call) = tool_calls.first() else { |
| 893 | continue; |
| 894 | }; |
| 895 | let missing = call |
| 896 | .pointer("/extra_content/google/thought_signature") |
| 897 | .and_then(Value::as_str) |
| 898 | .is_none_or(|signature| signature.is_empty()); |
| 899 | if missing { |
| 900 | let id = call.get("id").and_then(Value::as_str).unwrap_or("?"); |
| 901 | if requires_signatures { |
| 902 | anyhow::bail!( |
| 903 | "Gemini model `{model}` requires a thought signature to replay tool call \ |
| 904 | `{id}`, but none was captured (the turn predates signature capture, or \ |
| 905 | the provider omitted it). Start a new session before using tools on \ |
| 906 | this route." |
| 907 | ); |
| 908 | } |
| 909 | unsigned_call_ids.push(id); |
| 910 | } |
| 911 | } |
| 912 | if !unsigned_call_ids.is_empty() { |
| 913 | // Bounded: identifiers only, and only the first few of them. |
| 914 | let sample = unsigned_call_ids |
| 915 | .iter() |
| 916 | .take(3) |
| 917 | .copied() |
| 918 | .collect::<Vec<_>>() |
| 919 | .join(", "); |
| 920 | tracing::warn!( |
| 921 | model = %model, |
| 922 | unsigned_tool_calls = unsigned_call_ids.len(), |
| 923 | sample_tool_call_ids = %sample, |
| 924 | "replaying tool calls without Google thought signatures on the Gemini \ |
| 925 | OpenAI-compatible route; later signed tool turns may be rejected" |
| 926 | ); |
| 927 | } |
| 928 | Ok(()) |
| 929 | } |
| 930 | |
| 931 | /// Captured Google signatures ride on tool calls as |
| 932 | /// `extra_content.google.thought_signature`. Only Google's OpenAI-compat |
| 933 | /// endpoint may carry them on the wire; every other route gets them stripped |
| 934 | /// so a route switch never leaks Google-only fields to a foreign gateway. |
| 935 | /// |
| 936 | /// Returns how many tool calls lost a signature, so the caller can report a |
| 937 | /// route switch that silently drops signed history instead of dropping it |
| 938 | /// without a receipt. Never returns or logs the signature bytes. |
| 939 | fn strip_google_tool_call_extra_content(messages: &mut [Value]) -> usize { |
| 940 | let mut stripped = 0usize; |
| 941 | for message in messages { |
| 942 | let Some(tool_calls) = message.get_mut("tool_calls").and_then(Value::as_array_mut) else { |
| 943 | continue; |
| 944 | }; |
| 945 | for call in tool_calls { |
| 946 | if let Some(extra) = call.get_mut("extra_content") |
| 947 | && let Some(obj) = extra.as_object_mut() |
| 948 | { |
| 949 | if obj.remove("google").is_some() { |
| 950 | stripped += 1; |
| 951 | } |
| 952 | if obj.is_empty() { |
| 953 | call.as_object_mut().map(|c| c.remove("extra_content")); |
| 954 | } |
| 955 | } |
| 956 | } |
| 957 | } |
| 958 | stripped |
| 959 | } |
| 960 | |
| 961 | fn mistral_model_has_adjustable_reasoning(model: &str) -> bool { |
| 962 | let model = model.trim().to_ascii_lowercase(); |
| 963 | model.starts_with("mistral-medium") || model.starts_with("mistral-small") |
| 964 | } |
| 965 | |
| 966 | fn mistral_model_has_native_reasoning(model: &str) -> bool { |
| 967 | model.trim().to_ascii_lowercase().starts_with("magistral") |
| 968 | } |
| 969 | |
| 970 | fn mistral_model_supports_reasoning(model: &str) -> bool { |
| 971 | mistral_model_has_adjustable_reasoning(model) || mistral_model_has_native_reasoning(model) |
| 972 | } |
| 973 | |
| 974 | fn mistral_reasoning_effort_wire_value(effort: &str) -> Option<&'static str> { |
| 975 | match effort.trim().to_ascii_lowercase().as_str() { |
| 976 | "off" | "disabled" | "none" | "false" => Some("none"), |
| 977 | "high" | "xhigh" | "max" | "highest" | "ultra" | "ultracode" => Some("high"), |
| 978 | _ => None, |
| 979 | } |
| 980 | } |
| 981 | |
| 982 | /// Rewrite assistant messages that carry `reasoning_content` back into the |
| 983 | /// polymorphic `content: [{type: thinking, thinking: [{type: text, text: ...}], |
| 984 | /// closed: bool}, {type: text, text: ...}]` shape that Mistral la Plateforme |
| 985 | /// emits and accepts on replay. Mistral tolerates plain-string history in a |
| 986 | /// thinking-capable conversation, but replaying the original thinking trace |
| 987 | /// keeps multi-turn reasoning quality high per the official docs |
| 988 | /// (docs.mistral.ai/capabilities/reasoning). Non-assistant messages and |
| 989 | /// assistant messages without stored thinking are left untouched. |
| 990 | fn reshape_mistral_messages_for_reasoning_replay(messages: &mut [Value]) { |
| 991 | for message in messages.iter_mut() { |
| 992 | let Some(object) = message.as_object_mut() else { |
| 993 | continue; |
| 994 | }; |
| 995 | if object.get("role").and_then(Value::as_str) != Some("assistant") { |
| 996 | continue; |
| 997 | } |
| 998 | let Some(reasoning) = object.remove("reasoning_content") else { |
| 999 | continue; |
| 1000 | }; |
| 1001 | let reasoning_text = reasoning |
| 1002 | .as_str() |
| 1003 | .map(str::to_string) |
| 1004 | .filter(|s| !s.trim().is_empty()); |
| 1005 | let Some(reasoning_text) = reasoning_text else { |
| 1006 | continue; |
| 1007 | }; |
| 1008 | let text_content = object |
| 1009 | .get("content") |
| 1010 | .and_then(Value::as_str) |
| 1011 | .map(str::to_string); |
| 1012 | let mut blocks = vec![json!({ |
| 1013 | "type": "thinking", |
| 1014 | "thinking": [{"type": "text", "text": reasoning_text}], |
| 1015 | "closed": true, |
| 1016 | })]; |
| 1017 | if let Some(text) = text_content.filter(|s| !s.trim().is_empty()) { |
| 1018 | blocks.push(json!({"type": "text", "text": text})); |
| 1019 | } |
| 1020 | object.insert("content".to_string(), Value::Array(blocks)); |
| 1021 | } |
| 1022 | } |
| 1023 | |
| 1024 | /// Extract thinking and text content from a Mistral polymorphic `content` |
| 1025 | /// value. Mistral la Plateforme returns `content` as either a plain string |
| 1026 | /// (default) or an array of typed blocks (`{type: "thinking", thinking: |
| 1027 | /// [{type: "text", text: "..."}], closed: bool}` and `{type: "text", text: |
| 1028 | /// "..."}`). This helper flattens the thinking sub-array into a single |
| 1029 | /// string and returns any inline text separately. It ignores plain-string |
| 1030 | /// `content` (returns `(None, None)`) so the shared string fallback still |
| 1031 | /// runs for non-reasoning responses. |
| 1032 | fn extract_mistral_polymorphic_content(value: &Value) -> (Option<String>, Option<String>) { |
| 1033 | let Some(array) = value.get("content").and_then(Value::as_array) else { |
| 1034 | return (None, None); |
| 1035 | }; |
| 1036 | let mut thinking = String::new(); |
| 1037 | let mut text = String::new(); |
| 1038 | for block in array { |
| 1039 | let Some(kind) = block.get("type").and_then(Value::as_str) else { |
| 1040 | continue; |
| 1041 | }; |
| 1042 | match kind { |
| 1043 | "thinking" => { |
| 1044 | if let Some(inner) = block.get("thinking").and_then(Value::as_array) { |
| 1045 | for sub in inner { |
| 1046 | if let Some(sub_text) = sub |
| 1047 | .get("text") |
| 1048 | .and_then(Value::as_str) |
| 1049 | .filter(|s| !s.is_empty()) |
| 1050 | { |
| 1051 | thinking.push_str(sub_text); |
| 1052 | } |
| 1053 | } |
| 1054 | } else if let Some(inline) = block |
| 1055 | .get("thinking") |
| 1056 | .and_then(Value::as_str) |
| 1057 | .filter(|s| !s.is_empty()) |
| 1058 | { |
| 1059 | thinking.push_str(inline); |
| 1060 | } |
| 1061 | } |
| 1062 | "text" => { |
| 1063 | if let Some(sub_text) = block |
| 1064 | .get("text") |
| 1065 | .and_then(Value::as_str) |
| 1066 | .filter(|s| !s.is_empty()) |
| 1067 | { |
| 1068 | text.push_str(sub_text); |
| 1069 | } |
| 1070 | } |
| 1071 | _ => {} |
| 1072 | } |
| 1073 | } |
| 1074 | let thinking = (!thinking.is_empty()).then_some(thinking); |
| 1075 | let text = (!text.is_empty()).then_some(text); |
| 1076 | (thinking, text) |
| 1077 | } |
| 1078 | |
| 1079 | fn apply_mistral_route_reasoning_controls( |
| 1080 | body: &mut Value, |
| 1081 | provider: ProviderKind, |
| 1082 | base_url: &str, |
| 1083 | model: &str, |
| 1084 | effort: Option<&str>, |
| 1085 | ) { |
| 1086 | if provider != ProviderKind::Mistral { |
| 1087 | return; |
| 1088 | } |
| 1089 | if let Some(object) = body.as_object_mut() { |
| 1090 | object.remove("thinking"); |
| 1091 | object.remove("reasoning_effort"); |
| 1092 | } |
| 1093 | if !is_exact_mistral_chat_route(provider, base_url) |
| 1094 | || !mistral_model_has_adjustable_reasoning(model) |
| 1095 | { |
| 1096 | return; |
| 1097 | } |
| 1098 | let Some(effort) = effort else { |
| 1099 | return; |
| 1100 | }; |
| 1101 | if let Some(wire) = mistral_reasoning_effort_wire_value(effort) { |
| 1102 | body["reasoning_effort"] = json!(wire); |
| 1103 | } |
| 1104 | } |
| 1105 | |
| 1106 | /// The direct K3 Chat Completions schema exposes fixed sampling behavior and |
| 1107 | /// omits `temperature` and `top_p`. Strip legacy/generic values only from the |
| 1108 | /// exact first-party route so compatible gateways keep their own contract. |
| 1109 | /// Source: <https://platform.kimi.ai/docs/guide/kimi-k3-quickstart> (verified 2026-07-20). |
| 1110 | fn apply_direct_moonshot_k3_fixed_sampling( |
| 1111 | body: &mut Value, |
| 1112 | provider: ProviderKind, |
| 1113 | base_url: &str, |
| 1114 | model: &str, |
| 1115 | ) { |
| 1116 | if !is_exact_direct_moonshot_k3_route(provider, base_url, model) { |
| 1117 | return; |
| 1118 | } |
| 1119 | if let Some(object) = body.as_object_mut() { |
| 1120 | object.remove("temperature"); |
| 1121 | object.remove("top_p"); |
| 1122 | } |
| 1123 | } |
| 1124 | |
| 1125 | /// Kimi Code's documented membership models own their sampling behavior. |
| 1126 | /// Strip generic controls only on the exact first-party membership route; |
| 1127 | /// custom gateways and unknown model ids retain their own wire contract. |
| 1128 | /// Source: <https://www.kimi.com/code/docs/en/third-party-tools/codex.html> |
| 1129 | /// (verified 2026-08-26). |
| 1130 | fn apply_kimi_code_fixed_sampling( |
| 1131 | body: &mut Value, |
| 1132 | provider: ProviderKind, |
| 1133 | base_url: &str, |
| 1134 | model: &str, |
| 1135 | ) { |
| 1136 | if provider != ProviderKind::Moonshot |
| 1137 | || !moonshot_base_url_is_exact_kimi_code(base_url) |
| 1138 | || !is_kimi_code_membership_model(model) |
| 1139 | { |
| 1140 | return; |
| 1141 | } |
| 1142 | if let Some(object) = body.as_object_mut() { |
| 1143 | object.remove("temperature"); |
| 1144 | object.remove("top_p"); |
| 1145 | } |
| 1146 | } |
| 1147 | |
| 1148 | fn openai_compatible_reasoning_effort( |
| 1149 | effort: &str, |
| 1150 | supports_max: bool, |
| 1151 | supports_minimal: bool, |
| 1152 | ) -> Option<&'static str> { |
| 1153 | match effort.trim().to_ascii_lowercase().as_str() { |
| 1154 | "off" | "disabled" | "none" | "false" => Some("none"), |
| 1155 | "minimal" if supports_minimal => Some("minimal"), |
| 1156 | "minimal" => Some("low"), |
| 1157 | "low" => Some("low"), |
| 1158 | "medium" | "mid" | "" => Some("medium"), |
| 1159 | "high" => Some("high"), |
| 1160 | "xhigh" => Some("xhigh"), |
| 1161 | "max" | "highest" | "ultra" | "ultracode" if supports_max => Some("max"), |
| 1162 | "max" | "highest" | "ultra" | "ultracode" => Some("xhigh"), |
| 1163 | _ => None, |
| 1164 | } |
| 1165 | } |
| 1166 | |
| 1167 | const OPENAI_EFFORT_LADDER: [&str; 7] = |
| 1168 | ["none", "minimal", "low", "medium", "high", "xhigh", "max"]; |
| 1169 | |
| 1170 | fn clamp_openai_reasoning_effort( |
| 1171 | provider: ProviderKind, |
| 1172 | model: &str, |
| 1173 | effort: &'static str, |
| 1174 | ) -> &'static str { |
| 1175 | let Some(row) = |
| 1176 | crate::provider_lake::bundled_catalog_offering_for_model(provider, model.trim()) |
| 1177 | else { |
| 1178 | return effort; |
| 1179 | }; |
| 1180 | let Some(declared) = row |
| 1181 | .reasoning_options |
| 1182 | .iter() |
| 1183 | .find(|option| option["type"] == "effort") |
| 1184 | .and_then(|option| option["values"].as_array()) |
| 1185 | else { |
| 1186 | return effort; |
| 1187 | }; |
| 1188 | let declared: Vec<&str> = declared.iter().filter_map(Value::as_str).collect(); |
| 1189 | if declared.contains(&effort) { |
| 1190 | return effort; |
| 1191 | } |
| 1192 | let Some(requested) = OPENAI_EFFORT_LADDER |
| 1193 | .iter() |
| 1194 | .position(|value| *value == effort) |
| 1195 | else { |
| 1196 | return effort; |
| 1197 | }; |
| 1198 | let mut best: Option<(usize, &'static str)> = None; |
| 1199 | for (rank, value) in OPENAI_EFFORT_LADDER.iter().enumerate() { |
| 1200 | if !declared.contains(value) { |
| 1201 | continue; |
| 1202 | } |
| 1203 | let distance = rank.abs_diff(requested); |
| 1204 | let better = match best { |
| 1205 | None => true, |
| 1206 | Some((best_rank, _)) => { |
| 1207 | let best_distance = best_rank.abs_diff(requested); |
| 1208 | distance < best_distance || (distance == best_distance && rank > best_rank) |
| 1209 | } |
| 1210 | }; |
| 1211 | if better { |
| 1212 | best = Some((rank, value)); |
| 1213 | } |
| 1214 | } |
| 1215 | best.map_or(effort, |(_, value)| value) |
| 1216 | } |
| 1217 | |
| 1218 | fn mirror_minimax_reasoning_details_for_messages(messages: &mut [Value]) { |
| 1219 | for message in messages { |
| 1220 | if message.get("role").and_then(Value::as_str) != Some("assistant") { |
| 1221 | continue; |
| 1222 | } |
| 1223 | if message.get("reasoning_details").is_some() { |
| 1224 | continue; |
| 1225 | } |
| 1226 | let Some(reasoning) = message |
| 1227 | .get("reasoning_content") |
| 1228 | .and_then(Value::as_str) |
| 1229 | .filter(|reasoning| !reasoning.trim().is_empty()) |
| 1230 | .map(str::to_string) |
| 1231 | else { |
| 1232 | continue; |
| 1233 | }; |
| 1234 | message["reasoning_details"] = json!([ |
| 1235 | { |
| 1236 | "type": "text", |
| 1237 | "text": reasoning, |
| 1238 | } |
| 1239 | ]); |
| 1240 | } |
| 1241 | } |
| 1242 | |
| 1243 | fn mirror_minimax_reasoning_details_for_body(body: &mut Value, provider: ProviderKind) { |
| 1244 | if provider != ProviderKind::Minimax { |
| 1245 | return; |
| 1246 | } |
| 1247 | let Some(messages) = body.get_mut("messages").and_then(Value::as_array_mut) else { |
| 1248 | return; |
| 1249 | }; |
| 1250 | mirror_minimax_reasoning_details_for_messages(messages); |
| 1251 | } |
| 1252 | |
| 1253 | fn chat_route_tool_projection( |
| 1254 | provider: ProviderKind, |
| 1255 | base_url: &str, |
| 1256 | strict_tools_disabled: bool, |
| 1257 | ) -> RouteToolProjection { |
| 1258 | let strict_honored = |
| 1259 | !strict_tools_disabled && deepseek_base_url_supports_strict_tools(base_url); |
| 1260 | if matches!(provider, ProviderKind::Moonshot) { |
| 1261 | RouteToolProjection::Mfjs { strict_honored } |
| 1262 | } else if matches!(provider, ProviderKind::Xai) { |
| 1263 | RouteToolProjection::Relaxed { strict_honored } |
| 1264 | } else { |
| 1265 | RouteToolProjection::Exact { strict_honored } |
| 1266 | } |
| 1267 | } |
| 1268 | |
| 1269 | /// The final Chat Completions wire payload for one request. |
| 1270 | /// |
| 1271 | /// Produced by [`build_chat_wire_body`], the single place where a |
| 1272 | /// `MessageRequest` becomes Chat-shaped JSON. It is reached only through |
| 1273 | /// [`super::CodewhaleClient::prepare_outbound_request`], the shared outbound |
| 1274 | /// seam that the blocking transport, the streaming transport, and |
| 1275 | /// `/preview-request` all consume — so a preview cannot drift from what would |
| 1276 | /// be sent, and no other dialect is projected through this builder. |
| 1277 | /// |
| 1278 | /// Seam concept harvested from PR #1099 (`build_sanitized_chat_completion_body`) |
| 1279 | /// by TaoMu (GTC2080); re-implemented against the current client shape. |
| 1280 | pub struct ChatWireBody { |
| 1281 | /// Provider-shaped JSON body, post-sanitizers. |
| 1282 | pub body: Value, |
| 1283 | /// The model id actually placed on the wire (may differ from the |
| 1284 | /// configured/display model for routed providers). |
| 1285 | pub model: String, |
| 1286 | /// Tokens re-sent because thinking-mode replay substituted |
| 1287 | /// `reasoning_content`. Only computed on the streaming path, which is the |
| 1288 | /// only path that runs the replay sanitizer today. |
| 1289 | pub replay_input_tokens: Option<u32>, |
| 1290 | /// Wire-normalized tool names omitted because Moonshot's MFJS validator |
| 1291 | /// rejected their parameter schemas. Kept outside the wire body so the |
| 1292 | /// caller can surface one bounded diagnostic without leaking schema data. |
| 1293 | pub omitted_tool_names: Vec<String>, |
| 1294 | } |
| 1295 | |
| 1296 | /// Build the Chat Completions wire body for `request`. |
| 1297 | /// |
| 1298 | /// `stream` selects the streaming shape (`stream` + `stream_options`) and, to |
| 1299 | /// preserve historical behavior exactly, also gates the thinking-mode replay |
| 1300 | /// sanitizer — the blocking path has never run it. |
| 1301 | #[cfg(test)] |
| 1302 | pub fn build_chat_wire_body( |
| 1303 | request: &MessageRequest, |
| 1304 | provider: ProviderKind, |
| 1305 | base_url: &str, |
| 1306 | stream: bool, |
| 1307 | route_limits: Option<RouteLimits>, |
| 1308 | ) -> Result<ChatWireBody> { |
| 1309 | build_chat_wire_body_with_window_and_options( |
| 1310 | request, |
| 1311 | provider, |
| 1312 | base_url, |
| 1313 | stream, |
| 1314 | route_limits, |
| 1315 | None, |
| 1316 | false, |
| 1317 | None, |
| 1318 | ) |
| 1319 | } |
| 1320 | |
| 1321 | #[allow(clippy::too_many_arguments)] |
| 1322 | pub fn build_chat_wire_body_with_window_and_options( |
| 1323 | request: &MessageRequest, |
| 1324 | provider: ProviderKind, |
| 1325 | base_url: &str, |
| 1326 | stream: bool, |
| 1327 | route_limits: Option<RouteLimits>, |
| 1328 | effective_window: Option<u32>, |
| 1329 | strict_tools_disabled: bool, |
| 1330 | reasoning_options: Option<&[Value]>, |
| 1331 | ) -> Result<ChatWireBody> { |
| 1332 | let messages = PromptBuilder::for_request(request).build_for_provider_and_route( |
| 1333 | provider, |
| 1334 | base_url, |
| 1335 | route_limits, |
| 1336 | effective_window, |
| 1337 | ); |
| 1338 | let model = { |
| 1339 | let wire = codewhale_config::route::resolve_model(provider, &request.model, Some(base_url)) |
| 1340 | .map_or_else( |
| 1341 | |_| request.model.trim().to_string(), |
| 1342 | |resolved| resolved.wire_id, |
| 1343 | ); |
| 1344 | codewhale_models::effective_muse_wire_id(&wire).to_string() |
| 1345 | }; |
| 1346 | validate_google_thought_signature_replay(base_url, &model, &messages)?; |
| 1347 | let mut body = if stream { |
| 1348 | json!({ |
| 1349 | "model": model.clone(), |
| 1350 | "messages": messages, |
| 1351 | "max_tokens": request.max_tokens, |
| 1352 | "stream": true, |
| 1353 | "stream_options": { |
| 1354 | "include_usage": true |
| 1355 | }, |
| 1356 | }) |
| 1357 | } else { |
| 1358 | json!({ |
| 1359 | "model": model.clone(), |
| 1360 | "messages": messages, |
| 1361 | "max_tokens": request.max_tokens, |
| 1362 | }) |
| 1363 | }; |
| 1364 | apply_provider_token_limit(&mut body, provider, base_url, &model, request.max_tokens); |
| 1365 | |
| 1366 | if let Some(temperature) = request.temperature { |
| 1367 | body["temperature"] = json!(temperature); |
| 1368 | } |
| 1369 | if let Some(top_p) = request.top_p { |
| 1370 | body["top_p"] = json!(top_p); |
| 1371 | } |
| 1372 | super::role_placement::validate_latest_reminder_messages(&request.messages)?; |
| 1373 | validate_and_apply_safety_check_and_title( |
| 1374 | request, |
| 1375 | &mut body, |
| 1376 | matches!( |
| 1377 | provider, |
| 1378 | ProviderKind::Deepseek | ProviderKind::DeepseekAnthropic |
| 1379 | ), |
| 1380 | )?; |
| 1381 | let mut omitted_tool_names = Vec::new(); |
| 1382 | let mut has_deepseek_web_tools = false; |
| 1383 | let tool_name_limit = tool_name_limit(provider, ToolNameWire::OpenAiCompatible); |
| 1384 | check_history_tool_names( |
| 1385 | request, |
| 1386 | documented_tool_name_limit(provider, ToolNameWire::OpenAiCompatible), |
| 1387 | )?; |
| 1388 | if let Some(tools) = request.tools.as_ref() { |
| 1389 | has_deepseek_web_tools = validate_deepseek_web_tools(tools, WireDialect::ChatCompletions)?; |
| 1390 | if has_deepseek_web_tools |
| 1391 | && request |
| 1392 | .metadata |
| 1393 | .as_ref() |
| 1394 | .and_then(|m| m.get("web_search_options")) |
| 1395 | .is_some() |
| 1396 | { |
| 1397 | bail!( |
| 1398 | "web_search_options cannot be combined with deepseek_web_search or deepseek_read_url" |
| 1399 | ); |
| 1400 | } |
| 1401 | let route_projection = |
| 1402 | chat_route_tool_projection(provider, base_url, strict_tools_disabled); |
| 1403 | let mut chat_tools = Vec::new(); |
| 1404 | for tool in tools { |
| 1405 | if let Some(kind) = deepseek_web_tool_kind(tool) { |
| 1406 | chat_tools.push(json!({ "type": kind })); |
| 1407 | continue; |
| 1408 | } |
| 1409 | if tool_name_exceeds_limit(&tool.name, tool_name_limit) { |
| 1410 | omitted_tool_names.push(to_api_tool_name(&tool.name)); |
| 1411 | continue; |
| 1412 | } |
| 1413 | match project_tool_schema(route_projection, &tool.input_schema, tool.strict) { |
| 1414 | ToolSchemaProjection::Exact { |
| 1415 | parameters, |
| 1416 | strict, |
| 1417 | constraint_note, |
| 1418 | } |
| 1419 | | ToolSchemaProjection::Relaxed { |
| 1420 | parameters, |
| 1421 | strict, |
| 1422 | constraint_note, |
| 1423 | } => chat_tools.push(tool_to_chat_projected( |
| 1424 | tool, |
| 1425 | parameters, |
| 1426 | strict, |
| 1427 | constraint_note, |
| 1428 | )), |
| 1429 | ToolSchemaProjection::Omitted { .. } => { |
| 1430 | let name = to_api_tool_name(&tool.name); |
| 1431 | omitted_tool_names.push(name); |
| 1432 | } |
| 1433 | } |
| 1434 | } |
| 1435 | // When per-tool degradation (or the caller) left no tools, omit the |
| 1436 | // key entirely: an empty `tools` array — or a `tool_choice` pointing |
| 1437 | // at a dropped tool — is itself a fresh 400 on strict providers. |
| 1438 | if !chat_tools.is_empty() { |
| 1439 | body["tools"] = json!(chat_tools); |
| 1440 | } |
| 1441 | } |
| 1442 | if let Some(name) = request.tool_choice.as_ref().and_then(forced_tool_name) |
| 1443 | && omitted_tool_names |
| 1444 | .iter() |
| 1445 | .any(|omitted| omitted == name || *omitted == to_api_tool_name(name)) |
| 1446 | { |
| 1447 | if tool_name_exceeds_limit(name, tool_name_limit) { |
| 1448 | bail!(over_limit_tool_name_message(name, tool_name_limit)); |
| 1449 | } |
| 1450 | bail!( |
| 1451 | "cannot force an omitted tool because its input schema is incompatible with this route" |
| 1452 | ); |
| 1453 | } |
| 1454 | if let Some(choice) = request.tool_choice.as_ref() { |
| 1455 | validate_deepseek_web_tool_choice(choice, has_deepseek_web_tools)?; |
| 1456 | let mapped = map_tool_choice_for_chat(choice); |
| 1457 | if let Some(mapped) = mapped |
| 1458 | && should_send_tool_choice_for_chat( |
| 1459 | provider, |
| 1460 | request.reasoning_effort.as_deref(), |
| 1461 | &mapped, |
| 1462 | ) |
| 1463 | && body.get("tools").is_some() |
| 1464 | { |
| 1465 | body["tool_choice"] = mapped; |
| 1466 | } |
| 1467 | } |
| 1468 | apply_route_reasoning_controls_with_options( |
| 1469 | &mut body, |
| 1470 | provider, |
| 1471 | base_url, |
| 1472 | &model, |
| 1473 | request.reasoning_effort.as_deref(), |
| 1474 | reasoning_options, |
| 1475 | ); |
| 1476 | apply_direct_moonshot_k3_fixed_sampling(&mut body, provider, base_url, &model); |
| 1477 | apply_kimi_code_fixed_sampling(&mut body, provider, base_url, &model); |
| 1478 | |
| 1479 | // Bulletproof final sanitizer: walk the wire payload and force |
| 1480 | // `reasoning_content` onto any assistant message that has tool_calls |
| 1481 | // but no reasoning_content. DeepSeek's thinking-mode API rejects |
| 1482 | // such messages with a 400. This is the last line of defense after |
| 1483 | // engine-side and build-side substitution; if either upstream path |
| 1484 | // misses a case (e.g. a session restored from disk, a sub-agent |
| 1485 | // adding messages directly, or a cached prefix mismatch), this pass |
| 1486 | // still produces a valid request. |
| 1487 | let replay_input_tokens = if stream { |
| 1488 | sanitize_thinking_mode_messages_for_route( |
| 1489 | &mut body, |
| 1490 | &model, |
| 1491 | request.reasoning_effort.as_deref(), |
| 1492 | provider, |
| 1493 | base_url, |
| 1494 | ) |
| 1495 | } else { |
| 1496 | None |
| 1497 | }; |
| 1498 | mirror_minimax_reasoning_details_for_body(&mut body, provider); |
| 1499 | |
| 1500 | Ok(ChatWireBody { |
| 1501 | body, |
| 1502 | model, |
| 1503 | replay_input_tokens, |
| 1504 | omitted_tool_names, |
| 1505 | }) |
| 1506 | } |
| 1507 | |
| 1508 | impl CodewhaleClient { |
| 1509 | pub(super) async fn create_message_chat( |
| 1510 | &self, |
| 1511 | prepared: &super::PreparedOutboundRequest, |
| 1512 | cacheable: bool, |
| 1513 | ) -> Result<MessageResponse> { |
| 1514 | let body = &prepared.body; |
| 1515 | |
| 1516 | let response_cache_key = if cacheable && self.plugin_provider.is_none() { |
| 1517 | let wire_body = |
| 1518 | serde_json::to_vec(&body).context("Failed to serialize Chat API cache key")?; |
| 1519 | let key = codewhale_runtime::llm_response_cache::ResponseCache::make_key( |
| 1520 | self.api_provider.as_str(), |
| 1521 | &self.base_url, |
| 1522 | self.path_suffix.as_deref(), |
| 1523 | &self.api_key, |
| 1524 | &wire_body, |
| 1525 | ); |
| 1526 | if let Some(cached) = codewhale_runtime::llm_response_cache::response_cache().get(&key) |
| 1527 | { |
| 1528 | return Ok(cached); |
| 1529 | } |
| 1530 | Some(key) |
| 1531 | } else { |
| 1532 | None |
| 1533 | }; |
| 1534 | |
| 1535 | // The endpoint was resolved by the shared seam alongside the body, so |
| 1536 | // a route-shape decision (e.g. DeepSeek's strict-tools `/beta` path) |
| 1537 | // cannot be made twice with two different answers. |
| 1538 | let url = prepared.endpoint.url.as_str(); |
| 1539 | let response = self.send_json_with_retry(url, body).await?; |
| 1540 | |
| 1541 | let status = response.status(); |
| 1542 | crate::client::record_provider_response(self.api_provider, status.as_u16()); |
| 1543 | if !status.is_success() { |
| 1544 | let raw_error_text = bounded_error_text(response, ERROR_BODY_MAX_BYTES).await; |
| 1545 | let error_text = self.disclosed_http_error_body( |
| 1546 | &super::ErrorBodyDisclosure::Full, |
| 1547 | status.as_u16(), |
| 1548 | &raw_error_text, |
| 1549 | ); |
| 1550 | anyhow::bail!( |
| 1551 | "Failed to call {} Chat Completions API: HTTP {status}: {error_text}", |
| 1552 | self.api_provider.provider().display_name() |
| 1553 | ); |
| 1554 | } |
| 1555 | |
| 1556 | let response_text = response |
| 1557 | .text() |
| 1558 | .await |
| 1559 | .context("Failed to read Chat API response body")?; |
| 1560 | let value: Value = |
| 1561 | serde_json::from_str(&response_text).context("Failed to parse Chat API JSON")?; |
| 1562 | let parsed = parse_chat_message_for_route(&value, self.api_provider, &self.base_url)?; |
| 1563 | if let Some(key) = response_cache_key { |
| 1564 | codewhale_runtime::llm_response_cache::response_cache().put(key, parsed.clone()); |
| 1565 | } |
| 1566 | Ok(parsed) |
| 1567 | } |
| 1568 | } |
| 1569 | |
| 1570 | impl CodewhaleClient { |
| 1571 | async fn open_chat_stream_response( |
| 1572 | &self, |
| 1573 | url: &str, |
| 1574 | body: &Value, |
| 1575 | ) -> Result<(reqwest::Response, Duration)> { |
| 1576 | let request_body = |
| 1577 | serde_json::to_vec(body).context("Failed to serialize JSON request body")?; |
| 1578 | let open_req = self.stream_open_request(); |
| 1579 | let idle_timeout = open_req.idle_timeout; |
| 1580 | let response = self |
| 1581 | .send_stream_open_with_retry(|policy| { |
| 1582 | super::stream_entry::client_for_policy( |
| 1583 | &self.http_client, |
| 1584 | self.http1_fallback_client(), |
| 1585 | policy, |
| 1586 | ) |
| 1587 | .post(url) |
| 1588 | .header(reqwest::header::CONTENT_TYPE, "application/json") |
| 1589 | .body(request_body.clone()) |
| 1590 | }) |
| 1591 | .await?; |
| 1592 | Ok((response, idle_timeout)) |
| 1593 | } |
| 1594 | |
| 1595 | pub(super) async fn handle_chat_completion_stream( |
| 1596 | &self, |
| 1597 | prepared: &super::PreparedOutboundRequest, |
| 1598 | ) -> Result<StreamEventBox> { |
| 1599 | // Try true SSE streaming via chat completions (widely supported). |
| 1600 | // Body and endpoint both come from the shared prepared-request seam, |
| 1601 | // so a preview or a non-stream call can never diverge from the |
| 1602 | // streamed request. |
| 1603 | let body = &prepared.body; |
| 1604 | let model = prepared.wire_model.clone(); |
| 1605 | let replay_input_tokens = prepared.replay_input_tokens; |
| 1606 | let url = &prepared.endpoint.url; |
| 1607 | |
| 1608 | let (response, stream_idle_timeout) = match self.open_chat_stream_response(url, body).await |
| 1609 | { |
| 1610 | Ok(opened) => opened, |
| 1611 | Err(error) => { |
| 1612 | // If DeepSeek rejected for missing reasoning_content despite the |
| 1613 | // sanitizer, dump the offending indices so we can diagnose where |
| 1614 | // they came from on the next failure. |
| 1615 | if format!("{error:#}").contains("reasoning_content") { |
| 1616 | log_thinking_mode_violations(body); |
| 1617 | } |
| 1618 | return Err(error); |
| 1619 | } |
| 1620 | }; |
| 1621 | |
| 1622 | let status = response.status(); |
| 1623 | crate::client::record_provider_response(self.api_provider, status.as_u16()); |
| 1624 | if !status.is_success() { |
| 1625 | let raw_error_text = bounded_error_text(response, ERROR_BODY_MAX_BYTES).await; |
| 1626 | let error_text = self.disclosed_http_error_body( |
| 1627 | &super::ErrorBodyDisclosure::Full, |
| 1628 | status.as_u16(), |
| 1629 | &raw_error_text, |
| 1630 | ); |
| 1631 | return Err(crate::llm_client::LlmError::from_http_response( |
| 1632 | status.as_u16(), |
| 1633 | &error_text, |
| 1634 | ) |
| 1635 | .into()); |
| 1636 | } |
| 1637 | |
| 1638 | let api_provider = self.api_provider; |
| 1639 | let base_url = self.base_url.clone(); |
| 1640 | |
| 1641 | // Capture transport-shape headers before we consume `response` into |
| 1642 | // `bytes_stream()`. They are surfaced in the decode-error log path so |
| 1643 | // we can tell HTTP/2 RST_STREAM from chunked-encoding corruption from |
| 1644 | // gzip-compressor failure when investigating #103. |
| 1645 | let response_headers = format_stream_headers(response.headers()); |
| 1646 | let byte_stream = response.bytes_stream(); |
| 1647 | let configured_reasoning_stream_style = self.reasoning_stream_style.clone(); |
| 1648 | |
| 1649 | let stream = async_stream::stream! { |
| 1650 | use futures_util::StreamExt; |
| 1651 | |
| 1652 | // Emit a synthetic MessageStart |
| 1653 | yield Ok(StreamEvent::MessageStart { |
| 1654 | message: MessageResponse { |
| 1655 | tool_projection_warning: None, |
| 1656 | id: String::new(), |
| 1657 | r#type: "message".to_string(), |
| 1658 | role: "assistant".to_string(), |
| 1659 | content: Vec::new(), |
| 1660 | model: model.clone(), |
| 1661 | stop_reason: None, |
| 1662 | stop_sequence: None, |
| 1663 | container: None, |
| 1664 | title: None, |
| 1665 | stop_details: None, |
| 1666 | refusal: None, |
| 1667 | usage: Usage { |
| 1668 | input_tokens: 0, |
| 1669 | output_tokens: 0, |
| 1670 | ..Usage::default() |
| 1671 | } |
| 1672 | }, |
| 1673 | }); |
| 1674 | |
| 1675 | let mut line_buf = String::new(); |
| 1676 | let mut byte_buf = acquire_stream_buffer(); |
| 1677 | let mut content_index: u32 = 0; |
| 1678 | let mut text_started = false; |
| 1679 | let mut thinking_started = false; |
| 1680 | let mut tool_indices = ChatToolStream::for_base_url(&base_url); |
| 1681 | let mut reasoning_detail_buffers: std::collections::HashMap<u32, String> = std::collections::HashMap::new(); |
| 1682 | let mut inline_reasoning_tags = InlineReasoningTagState::default(); |
| 1683 | let reasoning_stream_style = reasoning_stream_style_for_route( |
| 1684 | api_provider, |
| 1685 | &base_url, |
| 1686 | &model, |
| 1687 | configured_reasoning_stream_style.as_deref(), |
| 1688 | ); |
| 1689 | |
| 1690 | let mut byte_stream = std::pin::pin!(byte_stream); |
| 1691 | let idle = stream_idle_timeout; |
| 1692 | |
| 1693 | // Telemetry for #103 stream-decode diagnostics: bytes received |
| 1694 | // since the start of this stream and last successful event time. |
| 1695 | // Surfaces in the error log when reqwest yields a chunk error so |
| 1696 | // we can tell HTTP/2 RST_STREAM from chunk-decode-failure from |
| 1697 | // gzip-corruption when investigating a flaky session. |
| 1698 | let stream_start = std::time::Instant::now(); |
| 1699 | let mut last_event_at = std::time::Instant::now(); |
| 1700 | let mut bytes_received: usize = 0; |
| 1701 | // Set when a `[DONE]` sentinel was seen, so the post-loop flush does |
| 1702 | // not re-process trailing post-DONE bytes. |
| 1703 | let mut saw_done = false; |
| 1704 | // A number of OpenAI-compatible providers omit `[DONE]` but send a |
| 1705 | // terminal `finish_reason`. Either is valid terminal proof. A raw |
| 1706 | // HTTP EOF with neither is not: treating that as MessageStop turns |
| 1707 | // a truncated provider response into a successful empty turn. |
| 1708 | let mut saw_finish_reason = false; |
| 1709 | // Once an error has been emitted, do not follow it with a synthetic |
| 1710 | // MessageStop (or a second, less-specific premature-EOF error). |
| 1711 | let mut stream_failed = false; |
| 1712 | // Set when a complete line or unterminated flush failed UTF-8. |
| 1713 | // Skip further data-frame parsing so U+FFFD cannot enter the transcript. |
| 1714 | let mut decode_failed = false; |
| 1715 | |
| 1716 | let first_byte = super::stream_entry::first_byte_timeout(idle); |
| 1717 | 'stream: loop { |
| 1718 | let wait = super::stream_entry::next_chunk_timeout(idle, first_byte, bytes_received); |
| 1719 | let chunk_result = match tokio_timeout(wait, byte_stream.next()).await { |
| 1720 | Ok(Some(result)) => result, |
| 1721 | Ok(None) => break, // Stream ended normally |
| 1722 | Err(_elapsed) => { |
| 1723 | stream_failed = true; |
| 1724 | yield Err(anyhow::anyhow!(super::stream_entry::body_timeout_message( |
| 1725 | wait, |
| 1726 | bytes_received, |
| 1727 | stream_start.elapsed(), |
| 1728 | last_event_at.elapsed(), |
| 1729 | api_provider.provider().display_name(), |
| 1730 | ))); |
| 1731 | break; |
| 1732 | } |
| 1733 | }; |
| 1734 | let chunk = match chunk_result { |
| 1735 | Ok(bytes) => bytes, |
| 1736 | Err(e) => { |
| 1737 | stream_failed = true; |
| 1738 | // Walk the error source chain so reqwest's underlying |
| 1739 | // hyper / h2 / io error is visible — without this the |
| 1740 | // outer "error decoding response body" message tells |
| 1741 | // us nothing about WHY the stream died. |
| 1742 | let mut error_chain = format!("{e}"); |
| 1743 | let mut current: Option<&(dyn std::error::Error + 'static)> = |
| 1744 | std::error::Error::source(&e); |
| 1745 | while let Some(source) = current { |
| 1746 | error_chain.push_str(&format!(" -> {source}")); |
| 1747 | current = std::error::Error::source(source); |
| 1748 | } |
| 1749 | codewhale_runtime::logging::warn(format!( |
| 1750 | "Stream read error: {error_chain} \ |
| 1751 | (elapsed: {}ms, bytes_received: {}, ms_since_last_event: {}, headers: {})", |
| 1752 | stream_start.elapsed().as_millis(), |
| 1753 | bytes_received, |
| 1754 | last_event_at.elapsed().as_millis(), |
| 1755 | response_headers, |
| 1756 | )); |
| 1757 | yield Err(anyhow::anyhow!("Stream read error: {e}")); |
| 1758 | break; |
| 1759 | } |
| 1760 | }; |
| 1761 | |
| 1762 | bytes_received = bytes_received.saturating_add(chunk.len()); |
| 1763 | last_event_at = std::time::Instant::now(); |
| 1764 | byte_buf.extend_from_slice(&chunk); |
| 1765 | |
| 1766 | // Guard against unbounded buffer growth (e.g., malformed stream without newlines) |
| 1767 | const MAX_SSE_BUF: usize = 10 * 1024 * 1024; // 10 MB |
| 1768 | if byte_buf.len() > MAX_SSE_BUF { |
| 1769 | stream_failed = true; |
| 1770 | yield Err(anyhow::anyhow!("SSE buffer exceeded {MAX_SSE_BUF} bytes — aborting stream")); |
| 1771 | break; |
| 1772 | } |
| 1773 | |
| 1774 | if byte_buf.len() > SSE_BACKPRESSURE_HIGH_WATERMARK { |
| 1775 | tokio::time::sleep(Duration::from_millis(SSE_BACKPRESSURE_SLEEP_MS)).await; |
| 1776 | } |
| 1777 | |
| 1778 | // Process complete SSE lines from the buffer. Decode only after |
| 1779 | // a `\n` so an HTTP/2 DATA split mid-character cannot become |
| 1780 | // U+FFFD; genuine invalid bytes fail closed. |
| 1781 | let mut lines_processed = 0usize; |
| 1782 | loop { |
| 1783 | let line = match take_sse_line(&mut byte_buf) { |
| 1784 | Ok(Some(line)) => line, |
| 1785 | Ok(None) => break, |
| 1786 | Err(err) => { |
| 1787 | decode_failed = true; |
| 1788 | stream_failed = true; |
| 1789 | yield Err(anyhow::anyhow!("{err}")); |
| 1790 | break 'stream; |
| 1791 | } |
| 1792 | }; |
| 1793 | |
| 1794 | if line.is_empty() { |
| 1795 | // Empty line = event boundary, process accumulated data |
| 1796 | if !line_buf.is_empty() { |
| 1797 | let data = std::mem::take(&mut line_buf); |
| 1798 | match parse_sse_data_frame( |
| 1799 | &data, |
| 1800 | &mut content_index, |
| 1801 | &mut text_started, |
| 1802 | &mut thinking_started, |
| 1803 | &mut tool_indices, |
| 1804 | &mut reasoning_detail_buffers, |
| 1805 | &mut inline_reasoning_tags, |
| 1806 | reasoning_stream_style, |
| 1807 | ) { |
| 1808 | SseDataFrame::Done => { |
| 1809 | saw_done = true; |
| 1810 | break 'stream; |
| 1811 | } |
| 1812 | SseDataFrame::Events(events) => { |
| 1813 | for mut event in events { |
| 1814 | saw_finish_reason |= matches!( |
| 1815 | &event, |
| 1816 | StreamEvent::MessageDelta { delta, .. } |
| 1817 | if delta.stop_reason.as_deref().is_some_and(|reason| !reason.trim().is_empty()) |
| 1818 | ); |
| 1819 | // Stamp the client-side replay-token estimate |
| 1820 | // onto the final usage so the UI can surface |
| 1821 | // it (#30). We compute it pre-request and |
| 1822 | // overlay it on the server-reported usage at |
| 1823 | // stream completion. |
| 1824 | if let Some(tokens) = replay_input_tokens |
| 1825 | && let StreamEvent::MessageDelta { |
| 1826 | usage: Some(usage), |
| 1827 | .. |
| 1828 | } = &mut event |
| 1829 | { |
| 1830 | usage.reasoning_replay_tokens = Some(tokens); |
| 1831 | } |
| 1832 | yield Ok(event); |
| 1833 | } |
| 1834 | } |
| 1835 | } |
| 1836 | } |
| 1837 | continue; |
| 1838 | } |
| 1839 | |
| 1840 | if line.starts_with(':') { |
| 1841 | // SSE comment (`: keep-alive`, `: OPENROUTER PROCESSING`). |
| 1842 | // Surface it as a ping so the engine counts a provider |
| 1843 | // that is alive but queued/thinking as progress |
| 1844 | // (#6184) instead of timing out on a live stream. |
| 1845 | yield Ok(StreamEvent::Ping); |
| 1846 | continue; |
| 1847 | } |
| 1848 | |
| 1849 | if let Some(data) = extract_sse_data_value(&line) |
| 1850 | && let Err(err) = push_sse_event_data(&mut line_buf, data) |
| 1851 | { |
| 1852 | decode_failed = true; |
| 1853 | stream_failed = true; |
| 1854 | yield Err(anyhow::anyhow!("{err}")); |
| 1855 | break 'stream; |
| 1856 | } |
| 1857 | // Ignore other SSE fields (event:, id:, retry:) |
| 1858 | |
| 1859 | lines_processed = lines_processed.saturating_add(1); |
| 1860 | if lines_processed >= SSE_MAX_LINES_PER_CHUNK { |
| 1861 | // Backpressure relief: hand the executor a turn so a |
| 1862 | // slow consumer is not starved. Keep draining after |
| 1863 | // that — leaving complete lines buffered would strand |
| 1864 | // them, because the outer loop only resumes draining |
| 1865 | // once ANOTHER chunk arrives and the end-of-stream |
| 1866 | // flush treats the whole remainder as a single |
| 1867 | // unterminated line. |
| 1868 | lines_processed = 0; |
| 1869 | tokio::task::yield_now().await; |
| 1870 | } |
| 1871 | } |
| 1872 | } |
| 1873 | |
| 1874 | // Flush a final SSE frame that arrived without a terminating blank |
| 1875 | // line (the stream closed straight after the last `data:` line, or |
| 1876 | // that line lacked a trailing newline). Without this the final delta |
| 1877 | // — last tokens, finish_reason, and usage — is silently dropped. |
| 1878 | // Skipped after `[DONE]`, whose frame was already processed, and |
| 1879 | // after a fail-closed UTF-8 error. |
| 1880 | if !saw_done && !decode_failed { |
| 1881 | match flush_sse_line(&mut byte_buf) { |
| 1882 | Ok(Some(line)) => { |
| 1883 | if let Some(data) = extract_sse_data_value(&line) |
| 1884 | && let Err(err) = push_sse_event_data(&mut line_buf, data) |
| 1885 | { |
| 1886 | decode_failed = true; |
| 1887 | stream_failed = true; |
| 1888 | yield Err(anyhow::anyhow!("{err}")); |
| 1889 | } |
| 1890 | } |
| 1891 | Ok(None) => {} |
| 1892 | Err(err) => { |
| 1893 | decode_failed = true; |
| 1894 | stream_failed = true; |
| 1895 | yield Err(anyhow::anyhow!("{err}")); |
| 1896 | } |
| 1897 | } |
| 1898 | if !decode_failed && !line_buf.is_empty() { |
| 1899 | let data = std::mem::take(&mut line_buf); |
| 1900 | match parse_sse_data_frame( |
| 1901 | &data, |
| 1902 | &mut content_index, |
| 1903 | &mut text_started, |
| 1904 | &mut thinking_started, |
| 1905 | &mut tool_indices, |
| 1906 | &mut reasoning_detail_buffers, |
| 1907 | &mut inline_reasoning_tags, |
| 1908 | reasoning_stream_style, |
| 1909 | ) { |
| 1910 | SseDataFrame::Done => saw_done = true, |
| 1911 | SseDataFrame::Events(events) => { |
| 1912 | for mut event in events { |
| 1913 | saw_finish_reason |= matches!( |
| 1914 | &event, |
| 1915 | StreamEvent::MessageDelta { delta, .. } |
| 1916 | if delta.stop_reason.as_deref().is_some_and(|reason| !reason.trim().is_empty()) |
| 1917 | ); |
| 1918 | if let Some(tokens) = replay_input_tokens |
| 1919 | && let StreamEvent::MessageDelta { |
| 1920 | usage: Some(usage), .. |
| 1921 | } = &mut event |
| 1922 | { |
| 1923 | usage.reasoning_replay_tokens = Some(tokens); |
| 1924 | } |
| 1925 | yield Ok(event); |
| 1926 | } |
| 1927 | } |
| 1928 | } |
| 1929 | } |
| 1930 | } |
| 1931 | |
| 1932 | // Close any open blocks — content_index points to the |
| 1933 | // currently active open block (it is only incremented |
| 1934 | // *after* a block is closed, not when opened). |
| 1935 | if thinking_started || text_started { |
| 1936 | yield Ok(StreamEvent::ContentBlockStop { index: content_index }); |
| 1937 | } |
| 1938 | |
| 1939 | release_stream_buffer(byte_buf); |
| 1940 | if !stream_failed && (saw_done || saw_finish_reason) { |
| 1941 | for event in tool_indices.finish() { |
| 1942 | yield Ok(event); |
| 1943 | } |
| 1944 | yield Ok(StreamEvent::MessageStop); |
| 1945 | } else if !stream_failed { |
| 1946 | yield Err(anyhow::anyhow!( |
| 1947 | "Chat Completions stream closed before [DONE] or finish_reason" |
| 1948 | )); |
| 1949 | } |
| 1950 | }; |
| 1951 | |
| 1952 | Ok(Pin::from(Box::new(stream) |
| 1953 | as Box< |
| 1954 | dyn futures_util::Stream<Item = Result<StreamEvent>> + Send, |
| 1955 | >)) |
| 1956 | } |
| 1957 | } |
| 1958 | |
| 1959 | // === Chat Completions Helpers === |
| 1960 | |
| 1961 | #[cfg(any(test, feature = "test-support"))] |
| 1962 | pub(super) fn build_chat_messages( |
| 1963 | system: Option<&SystemPrompt>, |
| 1964 | messages: &[Message], |
| 1965 | model: &str, |
| 1966 | ) -> Vec<Value> { |
| 1967 | build_chat_messages_with_reasoning( |
| 1968 | system, |
| 1969 | messages, |
| 1970 | tool_result_sent_char_budget(model), |
| 1971 | should_replay_reasoning_content(model, None), |
| 1972 | false, |
| 1973 | ) |
| 1974 | } |
| 1975 | |
| 1976 | #[cfg(test)] |
| 1977 | pub(super) fn build_chat_messages_for_request(request: &MessageRequest) -> Vec<Value> { |
| 1978 | PromptBuilder::for_request(request).build() |
| 1979 | } |
| 1980 | |
| 1981 | #[cfg(test)] |
| 1982 | pub(super) fn build_chat_messages_for_request_and_provider( |
| 1983 | request: &MessageRequest, |
| 1984 | provider: ProviderKind, |
| 1985 | ) -> Vec<Value> { |
| 1986 | build_chat_messages_for_request_and_provider_and_route(request, provider, "") |
| 1987 | } |
| 1988 | |
| 1989 | /// Build a wire prompt for one fully resolved provider route. |
| 1990 | /// |
| 1991 | /// Most provider behavior is keyed only by the provider kind and model. Kimi |
| 1992 | /// Code K3 is deliberately narrower: the bare `k3` model owns reasoning |
| 1993 | /// replay only on its official membership-plan endpoint, so callers that have |
| 1994 | /// a concrete base URL must retain it through prompt construction. |
| 1995 | #[cfg(test)] |
| 1996 | pub(super) fn build_chat_messages_for_request_and_provider_and_route( |
| 1997 | request: &MessageRequest, |
| 1998 | provider: ProviderKind, |
| 1999 | base_url: &str, |
| 2000 | ) -> Vec<Value> { |
| 2001 | PromptBuilder::for_request(request).build_for_provider_and_route(provider, base_url, None, None) |
| 2002 | } |
| 2003 | |
| 2004 | pub fn inspect_prompt_for_request(request: &MessageRequest) -> PromptInspection { |
| 2005 | PromptBuilder::for_request(request).inspect() |
| 2006 | } |
| 2007 | |
| 2008 | pub fn build_cache_warmup_request(request: &MessageRequest) -> MessageRequest { |
| 2009 | PromptBuilder::for_request(request).build_cache_warmup_request() |
| 2010 | } |
| 2011 | |
| 2012 | struct PromptBuilder<'a> { |
| 2013 | system: Option<&'a SystemPrompt>, |
| 2014 | messages: &'a [Message], |
| 2015 | tools: Option<&'a [Tool]>, |
| 2016 | model: &'a str, |
| 2017 | reasoning_effort: Option<&'a str>, |
| 2018 | } |
| 2019 | |
| 2020 | impl<'a> PromptBuilder<'a> { |
| 2021 | fn for_request(request: &'a MessageRequest) -> Self { |
| 2022 | Self { |
| 2023 | system: request.system.as_ref(), |
| 2024 | messages: &request.messages, |
| 2025 | tools: request.tools.as_deref(), |
| 2026 | model: &request.model, |
| 2027 | reasoning_effort: request.reasoning_effort.as_deref(), |
| 2028 | } |
| 2029 | } |
| 2030 | |
| 2031 | #[cfg(test)] |
| 2032 | fn build(self) -> Vec<Value> { |
| 2033 | build_chat_messages_with_reasoning( |
| 2034 | self.system, |
| 2035 | self.messages, |
| 2036 | tool_result_sent_char_budget(self.model), |
| 2037 | should_replay_reasoning_content(self.model, self.reasoning_effort), |
| 2038 | false, |
| 2039 | ) |
| 2040 | } |
| 2041 | |
| 2042 | fn build_for_provider_and_route( |
| 2043 | self, |
| 2044 | provider: ProviderKind, |
| 2045 | base_url: &str, |
| 2046 | route_limits: Option<RouteLimits>, |
| 2047 | effective_window: Option<u32>, |
| 2048 | ) -> Vec<Value> { |
| 2049 | let mut messages = build_chat_messages_with_reasoning( |
| 2050 | self.system, |
| 2051 | self.messages, |
| 2052 | crate::route_budget::route_inline_char_budget(Some(effective_window.unwrap_or_else( |
| 2053 | || { |
| 2054 | crate::route_budget::route_context_window_tokens( |
| 2055 | provider, |
| 2056 | self.model, |
| 2057 | route_limits, |
| 2058 | ) |
| 2059 | }, |
| 2060 | ))), |
| 2061 | should_replay_reasoning_content_for_provider_on_route( |
| 2062 | provider, |
| 2063 | base_url, |
| 2064 | self.model, |
| 2065 | self.reasoning_effort, |
| 2066 | ), |
| 2067 | false, |
| 2068 | ); |
| 2069 | dump_system_prompt_if_requested(&messages); |
| 2070 | if provider == ProviderKind::Arcee { |
| 2071 | apply_arcee_waf_safe_message_encoding(&mut messages); |
| 2072 | } |
| 2073 | if provider == ProviderKind::Minimax { |
| 2074 | mirror_minimax_reasoning_details_for_messages(&mut messages); |
| 2075 | } |
| 2076 | if is_exact_mistral_chat_route(provider, base_url) { |
| 2077 | reshape_mistral_messages_for_reasoning_replay(&mut messages); |
| 2078 | } |
| 2079 | if !is_google_openai_compat_chat_route(base_url) { |
| 2080 | // A signature captured on Google's endpoint is meaningless — and |
| 2081 | // potentially a leak — anywhere else, so it is stripped. Say so: |
| 2082 | // the model will behave differently on the replayed tool history, |
| 2083 | // and a silent strip is exactly what made this defect invisible. |
| 2084 | let stripped = strip_google_tool_call_extra_content(&mut messages); |
| 2085 | if stripped > 0 { |
| 2086 | tracing::warn!( |
| 2087 | provider = ?provider, |
| 2088 | stripped_tool_calls = stripped, |
| 2089 | "dropping captured Google thought signatures: this route is not Google's \ |
| 2090 | OpenAI-compatible endpoint, so the replayed tool history is unsigned" |
| 2091 | ); |
| 2092 | } |
| 2093 | } |
| 2094 | messages |
| 2095 | } |
| 2096 | |
| 2097 | fn inspect(self) -> PromptInspection { |
| 2098 | let messages = build_chat_messages_with_reasoning( |
| 2099 | self.system, |
| 2100 | self.messages, |
| 2101 | tool_result_sent_char_budget(self.model), |
| 2102 | should_replay_reasoning_content(self.model, self.reasoning_effort), |
| 2103 | true, |
| 2104 | ); |
| 2105 | inspect_wire_request(self.tools, &messages) |
| 2106 | } |
| 2107 | |
| 2108 | fn build_cache_warmup_request(self) -> MessageRequest { |
| 2109 | let system = stable_system_prompt(self.system); |
| 2110 | let mut messages = stable_history_messages(self.messages); |
| 2111 | let tools = self |
| 2112 | .tools |
| 2113 | .filter(|tools| !tools.is_empty()) |
| 2114 | .map(<[Tool]>::to_vec); |
| 2115 | let tool_choice = tools.as_ref().map(|_| json!("none")); |
| 2116 | messages.push(Message { |
| 2117 | role: Role::User, |
| 2118 | content: vec![ContentBlock::Text { |
| 2119 | text: CACHE_WARMUP_USER_TAIL.to_string(), |
| 2120 | cache_control: None, |
| 2121 | }], |
| 2122 | }); |
| 2123 | |
| 2124 | MessageRequest { |
| 2125 | model: self.model.to_string(), |
| 2126 | messages, |
| 2127 | max_tokens: CACHE_WARMUP_MAX_TOKENS, |
| 2128 | system, |
| 2129 | tools, |
| 2130 | tool_choice, |
| 2131 | metadata: None, |
| 2132 | thinking: None, |
| 2133 | // Warmup has an intentionally tiny answer contract ("OK"). Do not |
| 2134 | // let hidden reasoning consume that allowance before the cacheable |
| 2135 | // prefix is accepted by the provider. |
| 2136 | reasoning_effort: Some("off".to_string()), |
| 2137 | stream: None, |
| 2138 | temperature: None, |
| 2139 | top_p: None, |
| 2140 | safety_check: None, |
| 2141 | title: None, |
| 2142 | } |
| 2143 | } |
| 2144 | } |
| 2145 | |
| 2146 | const SYSTEM_PROMPT_DUMP_ENV: &str = "CODEWHALE_DUMP_SYSTEM_PROMPT"; |
| 2147 | const SYSTEM_PROMPT_DUMP_BEGIN: &str = "<<<CODEWHALE_SYSTEM_PROMPT_BEGIN>>>"; |
| 2148 | const SYSTEM_PROMPT_DUMP_END: &str = "<<<CODEWHALE_SYSTEM_PROMPT_END>>>"; |
| 2149 | const ARCEE_WAF_TEXT_SPLIT_TRIGGERS: &[(&str, &str, &str)] = &[("python -c", "python ", "-c")]; |
| 2150 | |
| 2151 | fn dump_system_prompt_if_requested(messages: &[Value]) { |
| 2152 | let Ok(flag) = std::env::var(SYSTEM_PROMPT_DUMP_ENV) else { |
| 2153 | return; |
| 2154 | }; |
| 2155 | if !matches!(flag.trim(), "1" | "true" | "TRUE" | "yes" | "YES") { |
| 2156 | return; |
| 2157 | } |
| 2158 | let Some(prompt) = messages.iter().find_map(system_message_text) else { |
| 2159 | return; |
| 2160 | }; |
| 2161 | let mut stderr = std::io::stderr().lock(); |
| 2162 | let _ = writeln!(stderr, "{SYSTEM_PROMPT_DUMP_BEGIN}"); |
| 2163 | let _ = writeln!(stderr, "{prompt}"); |
| 2164 | let _ = writeln!(stderr, "{SYSTEM_PROMPT_DUMP_END}"); |
| 2165 | } |
| 2166 | |
| 2167 | fn system_message_text(message: &Value) -> Option<String> { |
| 2168 | if message.get("role").and_then(Value::as_str) != Some("system") { |
| 2169 | return None; |
| 2170 | } |
| 2171 | match message.get("content")? { |
| 2172 | Value::String(text) => Some(text.clone()), |
| 2173 | Value::Array(parts) => { |
| 2174 | let text = parts |
| 2175 | .iter() |
| 2176 | .filter_map(|part| part.get("text").and_then(Value::as_str)) |
| 2177 | .collect::<Vec<_>>() |
| 2178 | .join(""); |
| 2179 | (!text.is_empty()).then_some(text) |
| 2180 | } |
| 2181 | _ => None, |
| 2182 | } |
| 2183 | } |
| 2184 | |
| 2185 | fn apply_arcee_waf_safe_message_encoding(messages: &mut [Value]) { |
| 2186 | for message in messages { |
| 2187 | if message.get("role").and_then(Value::as_str) != Some("system") { |
| 2188 | continue; |
| 2189 | } |
| 2190 | let Some(content) = message.get("content").and_then(Value::as_str) else { |
| 2191 | continue; |
| 2192 | }; |
| 2193 | let Some(parts) = arcee_waf_safe_text_parts(content) else { |
| 2194 | continue; |
| 2195 | }; |
| 2196 | message["content"] = json!(parts); |
| 2197 | } |
| 2198 | } |
| 2199 | |
| 2200 | fn arcee_waf_safe_text_parts(content: &str) -> Option<Vec<Value>> { |
| 2201 | let mut parts = Vec::new(); |
| 2202 | let mut cursor = 0usize; |
| 2203 | let mut split_any = false; |
| 2204 | |
| 2205 | while cursor < content.len() { |
| 2206 | let Some((trigger_start, trigger, left, right)) = next_arcee_waf_trigger(content, cursor) |
| 2207 | else { |
| 2208 | push_text_part(&mut parts, &content[cursor..]); |
| 2209 | break; |
| 2210 | }; |
| 2211 | |
| 2212 | push_text_part(&mut parts, &content[cursor..trigger_start]); |
| 2213 | push_text_part(&mut parts, left); |
| 2214 | push_text_part(&mut parts, right); |
| 2215 | cursor = trigger_start + trigger.len(); |
| 2216 | split_any = true; |
| 2217 | } |
| 2218 | |
| 2219 | split_any.then_some(parts) |
| 2220 | } |
| 2221 | |
| 2222 | fn next_arcee_waf_trigger(content: &str, cursor: usize) -> Option<(usize, &str, &str, &str)> { |
| 2223 | ARCEE_WAF_TEXT_SPLIT_TRIGGERS |
| 2224 | .iter() |
| 2225 | .filter_map(|(trigger, left, right)| { |
| 2226 | content[cursor..] |
| 2227 | .find(trigger) |
| 2228 | .map(|offset| (cursor + offset, *trigger, *left, *right)) |
| 2229 | }) |
| 2230 | .min_by_key(|(start, _, _, _)| *start) |
| 2231 | } |
| 2232 | |
| 2233 | fn push_text_part(parts: &mut Vec<Value>, text: &str) { |
| 2234 | if !text.is_empty() { |
| 2235 | parts.push(json!({ |
| 2236 | "type": "text", |
| 2237 | "text": text, |
| 2238 | })); |
| 2239 | } |
| 2240 | } |
| 2241 | |
| 2242 | pub const CACHE_WARMUP_USER_TAIL: &str = "请只回复 OK"; |
| 2243 | pub const CACHE_WARMUP_MAX_TOKENS: u32 = 8; |
| 2244 | /// Wire backstop for tool results (#6508). The engine already fits every |
| 2245 | /// result it gives the model to the route's inline budget, and marks any cut |
| 2246 | /// with a recovery footer. This pass only catches history that never went |
| 2247 | /// through the engine (legacy or restored raw results). Model-only inspection |
| 2248 | /// uses the catalog window; outbound requests pass their resolved route budget. |
| 2249 | /// Results with an engine recovery footer remain intact. |
| 2250 | fn tool_result_sent_char_budget(model: &str) -> usize { |
| 2251 | crate::route_budget::route_inline_char_budget(codewhale_models::context_window_for_model(model)) |
| 2252 | } |
| 2253 | /// Characters of an excerpted wire result spent on its labelled header. |
| 2254 | const TOOL_RESULT_EXCERPT_FRAME_CHARS: usize = 1_024; |
| 2255 | /// Tool results shorter than this stay inline even when repeated. The |
| 2256 | /// extra prompt bytes are cheaper than adding an earlier-message reference |
| 2257 | /// for tiny command outputs. |
| 2258 | const TOOL_RESULT_DEDUP_MIN_CHARS: usize = 1_024; |
| 2259 | |
| 2260 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 2261 | pub struct PromptInspection { |
| 2262 | pub base_static_prefix_hash: String, |
| 2263 | pub full_request_prefix_hash: String, |
| 2264 | /// Hash of the rendered tool catalog JSON, or empty when no tools were supplied. |
| 2265 | pub tool_catalog_hash: String, |
| 2266 | pub layers: Vec<PromptLayerInspection>, |
| 2267 | } |
| 2268 | |
| 2269 | /// Identifies the stable prefix that a cache warmup primes. |
| 2270 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 2271 | pub struct CacheWarmupKey { |
| 2272 | pub provider: String, |
| 2273 | pub model: String, |
| 2274 | pub base_url: String, |
| 2275 | pub static_prefix_hash: String, |
| 2276 | pub tool_catalog_hash: String, |
| 2277 | pub project_pack_hash: String, |
| 2278 | pub skills_hash: String, |
| 2279 | } |
| 2280 | |
| 2281 | impl CacheWarmupKey { |
| 2282 | pub fn from_inspection( |
| 2283 | provider: &str, |
| 2284 | model: &str, |
| 2285 | base_url: &str, |
| 2286 | inspection: &PromptInspection, |
| 2287 | ) -> Self { |
| 2288 | Self { |
| 2289 | provider: provider.to_string(), |
| 2290 | model: model.to_string(), |
| 2291 | base_url: base_url.to_string(), |
| 2292 | static_prefix_hash: inspection.base_static_prefix_hash.clone(), |
| 2293 | tool_catalog_hash: inspection.tool_catalog_hash.clone(), |
| 2294 | project_pack_hash: layer_hash(inspection, "Project context pack"), |
| 2295 | skills_hash: layer_hash(inspection, "Skills"), |
| 2296 | } |
| 2297 | } |
| 2298 | |
| 2299 | pub fn hash_short(&self) -> String { |
| 2300 | let json = serde_json::to_string(self).unwrap_or_default(); |
| 2301 | let hash = sha256_hex(json.as_bytes()); |
| 2302 | hash[..hash.len().min(12)].to_string() |
| 2303 | } |
| 2304 | } |
| 2305 | |
| 2306 | fn layer_hash(inspection: &PromptInspection, name: &str) -> String { |
| 2307 | inspection |
| 2308 | .layers |
| 2309 | .iter() |
| 2310 | .find(|layer| layer.name == name) |
| 2311 | .map(|layer| layer.sha256.clone()) |
| 2312 | .unwrap_or_default() |
| 2313 | } |
| 2314 | |
| 2315 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 2316 | pub struct PromptLayerInspection { |
| 2317 | pub name: String, |
| 2318 | pub stability: PromptLayerStability, |
| 2319 | pub char_len: usize, |
| 2320 | pub byte_len: usize, |
| 2321 | /// Rough token estimate for quick before/after cache-hit reports. |
| 2322 | pub token_estimate: usize, |
| 2323 | pub sha256: String, |
| 2324 | pub tool_result: Option<ToolResultInspection>, |
| 2325 | pub turn_meta: Option<TurnMetaInspection>, |
| 2326 | } |
| 2327 | |
| 2328 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 2329 | pub struct ToolResultInspection { |
| 2330 | pub original_chars: usize, |
| 2331 | pub sent_chars: usize, |
| 2332 | pub truncated: bool, |
| 2333 | pub deduplicated: bool, |
| 2334 | } |
| 2335 | |
| 2336 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 2337 | pub struct TurnMetaInspection { |
| 2338 | pub original_chars: usize, |
| 2339 | pub sent_chars: usize, |
| 2340 | pub deduplicated: bool, |
| 2341 | pub sha256: String, |
| 2342 | } |
| 2343 | |
| 2344 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 2345 | pub enum PromptLayerStability { |
| 2346 | Static, |
| 2347 | History, |
| 2348 | Dynamic, |
| 2349 | } |
| 2350 | |
| 2351 | #[cfg(any(test, feature = "test-support"))] |
| 2352 | impl PromptLayerStability { |
| 2353 | pub fn label(self) -> &'static str { |
| 2354 | match self { |
| 2355 | Self::Static => "static", |
| 2356 | Self::History => "history", |
| 2357 | Self::Dynamic => "dynamic", |
| 2358 | } |
| 2359 | } |
| 2360 | } |
| 2361 | |
| 2362 | fn inspect_wire_request(tools: Option<&[Tool]>, messages: &[Value]) -> PromptInspection { |
| 2363 | let mut layers = Vec::new(); |
| 2364 | let mut base_static_prefix_parts = Vec::new(); |
| 2365 | let mut full_request_prefix_parts = Vec::new(); |
| 2366 | let mut tool_catalog_hash = String::new(); |
| 2367 | let mut start_index = 0; |
| 2368 | |
| 2369 | if let Some(message) = messages.first() { |
| 2370 | let role = message |
| 2371 | .get("role") |
| 2372 | .and_then(Value::as_str) |
| 2373 | .unwrap_or("unknown"); |
| 2374 | let content = message_content_for_inspect(message); |
| 2375 | if role == "system" { |
| 2376 | for (name, stability, body) in split_system_layers(&content) { |
| 2377 | if stability == PromptLayerStability::Static { |
| 2378 | base_static_prefix_parts.push(body.to_string()); |
| 2379 | } |
| 2380 | if stability != PromptLayerStability::Dynamic { |
| 2381 | full_request_prefix_parts.push(body.to_string()); |
| 2382 | } |
| 2383 | layers.push(prompt_layer(name, stability, body)); |
| 2384 | } |
| 2385 | start_index = 1; |
| 2386 | } |
| 2387 | } |
| 2388 | |
| 2389 | if let Some(tool_catalog) = logical_tool_catalog_for_inspect(tools) { |
| 2390 | tool_catalog_hash = sha256_hex(tool_catalog.as_bytes()); |
| 2391 | base_static_prefix_parts.push(tool_catalog.clone()); |
| 2392 | full_request_prefix_parts.push(tool_catalog.clone()); |
| 2393 | layers.push(prompt_layer( |
| 2394 | "Tool catalog".to_string(), |
| 2395 | PromptLayerStability::Static, |
| 2396 | &tool_catalog, |
| 2397 | )); |
| 2398 | } |
| 2399 | |
| 2400 | for (index, message) in messages.iter().enumerate().skip(start_index) { |
| 2401 | let role = message |
| 2402 | .get("role") |
| 2403 | .and_then(Value::as_str) |
| 2404 | .unwrap_or("unknown"); |
| 2405 | let content = message_content_for_inspect(message); |
| 2406 | let is_last = index + 1 == messages.len(); |
| 2407 | let stability = if (is_last && role == "user") || role == "tool" { |
| 2408 | PromptLayerStability::Dynamic |
| 2409 | } else { |
| 2410 | PromptLayerStability::History |
| 2411 | }; |
| 2412 | let name = if is_last && role == "user" { |
| 2413 | "User task".to_string() |
| 2414 | } else { |
| 2415 | format!("Message #{index} {role}") |
| 2416 | }; |
| 2417 | if stability != PromptLayerStability::Dynamic { |
| 2418 | full_request_prefix_parts.push(content.clone()); |
| 2419 | } |
| 2420 | let mut layer = prompt_layer(name, stability, &content); |
| 2421 | layer.tool_result = tool_result_inspection_for_message(message); |
| 2422 | layer.turn_meta = turn_meta_inspection_for_message(message); |
| 2423 | layers.push(layer); |
| 2424 | } |
| 2425 | |
| 2426 | let base_static_prefix = base_static_prefix_parts.join("\n"); |
| 2427 | let full_request_prefix = full_request_prefix_parts.join("\n"); |
| 2428 | |
| 2429 | PromptInspection { |
| 2430 | base_static_prefix_hash: sha256_hex(base_static_prefix.as_bytes()), |
| 2431 | full_request_prefix_hash: sha256_hex(full_request_prefix.as_bytes()), |
| 2432 | tool_catalog_hash, |
| 2433 | layers, |
| 2434 | } |
| 2435 | } |
| 2436 | |
| 2437 | fn logical_tool_catalog_for_inspect(tools: Option<&[Tool]>) -> Option<String> { |
| 2438 | let tools = tools.filter(|tools| !tools.is_empty())?; |
| 2439 | serde_json::to_string( |
| 2440 | &tools |
| 2441 | .iter() |
| 2442 | .map(logical_tool_for_inspect) |
| 2443 | .collect::<Vec<_>>(), |
| 2444 | ) |
| 2445 | .ok() |
| 2446 | } |
| 2447 | |
| 2448 | fn message_content_for_inspect(message: &Value) -> String { |
| 2449 | let mut parts = Vec::new(); |
| 2450 | if let Some(content) = message.get("content").and_then(Value::as_str) |
| 2451 | && !content.is_empty() |
| 2452 | { |
| 2453 | parts.push(content.to_string()); |
| 2454 | } |
| 2455 | if let Some(content) = message.get("content").and_then(Value::as_array) { |
| 2456 | for part in content { |
| 2457 | match part.get("type").and_then(Value::as_str) { |
| 2458 | Some("text") => { |
| 2459 | if let Some(text) = part.get("text").and_then(Value::as_str) |
| 2460 | && !text.is_empty() |
| 2461 | { |
| 2462 | parts.push(text.to_string()); |
| 2463 | } |
| 2464 | } |
| 2465 | Some("image_url") => { |
| 2466 | let url = part |
| 2467 | .get("image_url") |
| 2468 | .and_then(|image_url| image_url.get("url")) |
| 2469 | .and_then(Value::as_str) |
| 2470 | .unwrap_or(""); |
| 2471 | parts.push(format!( |
| 2472 | "[image_url:{}]", |
| 2473 | summarize_image_url_for_inspect(url) |
| 2474 | )); |
| 2475 | } |
| 2476 | _ => {} |
| 2477 | } |
| 2478 | } |
| 2479 | } |
| 2480 | if let Some(reasoning) = message.get("reasoning_content").and_then(Value::as_str) |
| 2481 | && !reasoning.is_empty() |
| 2482 | { |
| 2483 | parts.push(reasoning.to_string()); |
| 2484 | } |
| 2485 | if let Some(tool_calls) = message.get("tool_calls") { |
| 2486 | parts.push(tool_calls.to_string()); |
| 2487 | } |
| 2488 | parts.join("\n") |
| 2489 | } |
| 2490 | |
| 2491 | fn summarize_image_url_for_inspect(url: &str) -> String { |
| 2492 | let Some((prefix, encoded)) = url.split_once(";base64,") else { |
| 2493 | return first_chars(url, 96); |
| 2494 | }; |
| 2495 | format!("{prefix};base64,<{} chars>", encoded.len()) |
| 2496 | } |
| 2497 | |
| 2498 | fn tool_result_inspection_for_message(message: &Value) -> Option<ToolResultInspection> { |
| 2499 | if message.get("role").and_then(Value::as_str) != Some("tool") { |
| 2500 | return None; |
| 2501 | } |
| 2502 | let budget = message.get("_tool_result_budget")?; |
| 2503 | Some(ToolResultInspection { |
| 2504 | original_chars: budget |
| 2505 | .get("original_chars") |
| 2506 | .and_then(Value::as_u64) |
| 2507 | .and_then(|n| usize::try_from(n).ok())?, |
| 2508 | sent_chars: budget |
| 2509 | .get("sent_chars") |
| 2510 | .and_then(Value::as_u64) |
| 2511 | .and_then(|n| usize::try_from(n).ok())?, |
| 2512 | truncated: budget |
| 2513 | .get("truncated") |
| 2514 | .and_then(Value::as_bool) |
| 2515 | .unwrap_or(false), |
| 2516 | deduplicated: budget |
| 2517 | .get("deduplicated") |
| 2518 | .and_then(Value::as_bool) |
| 2519 | .unwrap_or(false), |
| 2520 | }) |
| 2521 | } |
| 2522 | |
| 2523 | fn turn_meta_inspection_for_message(message: &Value) -> Option<TurnMetaInspection> { |
| 2524 | let budget = message.get("_turn_meta_budget")?; |
| 2525 | Some(TurnMetaInspection { |
| 2526 | original_chars: budget |
| 2527 | .get("original_chars") |
| 2528 | .and_then(Value::as_u64) |
| 2529 | .and_then(|n| usize::try_from(n).ok())?, |
| 2530 | sent_chars: budget |
| 2531 | .get("sent_chars") |
| 2532 | .and_then(Value::as_u64) |
| 2533 | .and_then(|n| usize::try_from(n).ok())?, |
| 2534 | deduplicated: budget |
| 2535 | .get("deduplicated") |
| 2536 | .and_then(Value::as_bool) |
| 2537 | .unwrap_or(false), |
| 2538 | sha256: budget |
| 2539 | .get("sha256") |
| 2540 | .and_then(Value::as_str) |
| 2541 | .map(str::to_string)?, |
| 2542 | }) |
| 2543 | } |
| 2544 | |
| 2545 | fn split_system_layers(content: &str) -> Vec<(String, PromptLayerStability, &str)> { |
| 2546 | let markers = [ |
| 2547 | ("Project context", "<project_instructions"), |
| 2548 | ("Project context pack", "## Project Context Pack"), |
| 2549 | ("Environment", "## Environment"), |
| 2550 | ("Configured instructions", "<instructions "), |
| 2551 | ("User memory", "## User Memory"), |
| 2552 | ("Current session goal", "## Current Session Goal"), |
| 2553 | ("Skills", "## Skills"), |
| 2554 | ("Core execution", "## Core Execution"), |
| 2555 | ("Compact template", "## Compact"), |
| 2556 | ("Previous session relay", "## Previous Session Relay"), |
| 2557 | ]; |
| 2558 | |
| 2559 | let mut starts: Vec<(usize, &str)> = markers |
| 2560 | .iter() |
| 2561 | .filter_map(|(name, marker)| content.find(marker).map(|idx| (idx, *name))) |
| 2562 | .collect(); |
| 2563 | starts.sort_by_key(|(idx, _)| *idx); |
| 2564 | |
| 2565 | let mut layers = Vec::new(); |
| 2566 | let first_marker = starts.first().map_or(content.len(), |(idx, _)| *idx); |
| 2567 | if first_marker > 0 { |
| 2568 | layers.push(( |
| 2569 | "Global system prefix".to_string(), |
| 2570 | PromptLayerStability::Static, |
| 2571 | content[..first_marker].trim(), |
| 2572 | )); |
| 2573 | } |
| 2574 | |
| 2575 | for (i, (start, name)) in starts.iter().enumerate() { |
| 2576 | let end = starts.get(i + 1).map_or(content.len(), |(idx, _)| *idx); |
| 2577 | let stability = if *name == "Previous session relay" { |
| 2578 | PromptLayerStability::Dynamic |
| 2579 | } else if is_static_base_layer(name) { |
| 2580 | PromptLayerStability::Static |
| 2581 | } else { |
| 2582 | PromptLayerStability::History |
| 2583 | }; |
| 2584 | layers.push(((*name).to_string(), stability, content[*start..end].trim())); |
| 2585 | } |
| 2586 | |
| 2587 | if layers.is_empty() { |
| 2588 | layers.push(( |
| 2589 | "Global system prefix".to_string(), |
| 2590 | PromptLayerStability::Static, |
| 2591 | content.trim(), |
| 2592 | )); |
| 2593 | } |
| 2594 | layers |
| 2595 | } |
| 2596 | |
| 2597 | fn is_static_base_layer(name: &str) -> bool { |
| 2598 | matches!( |
| 2599 | name, |
| 2600 | "Global system prefix" |
| 2601 | | "Environment" |
| 2602 | | "Skills" |
| 2603 | | "Project context" |
| 2604 | | "Project context pack" |
| 2605 | | "Core execution" |
| 2606 | | "Compact template" |
| 2607 | ) |
| 2608 | } |
| 2609 | |
| 2610 | fn stable_system_prompt(system: Option<&SystemPrompt>) -> Option<SystemPrompt> { |
| 2611 | let instructions = system_to_instructions(system.cloned())?; |
| 2612 | let stable = split_system_layers(&instructions) |
| 2613 | .into_iter() |
| 2614 | .filter_map(|(_, stability, body)| { |
| 2615 | (stability == PromptLayerStability::Static).then_some(body) |
| 2616 | }) |
| 2617 | .collect::<Vec<_>>() |
| 2618 | .join("\n\n"); |
| 2619 | if stable.trim().is_empty() { |
| 2620 | None |
| 2621 | } else { |
| 2622 | Some(SystemPrompt::Text(stable)) |
| 2623 | } |
| 2624 | } |
| 2625 | |
| 2626 | fn stable_history_messages(messages: &[Message]) -> Vec<Message> { |
| 2627 | let mut end = messages.len(); |
| 2628 | if messages |
| 2629 | .last() |
| 2630 | .is_some_and(|message| message.role.as_str() == "user") |
| 2631 | { |
| 2632 | end = end.saturating_sub(1); |
| 2633 | } |
| 2634 | messages[..end].to_vec() |
| 2635 | } |
| 2636 | |
| 2637 | fn prompt_layer( |
| 2638 | name: String, |
| 2639 | stability: PromptLayerStability, |
| 2640 | content: &str, |
| 2641 | ) -> PromptLayerInspection { |
| 2642 | let char_len = content.chars().count(); |
| 2643 | let token_estimate = if char_len == 0 { |
| 2644 | 0 |
| 2645 | } else if content.is_ascii() { |
| 2646 | (char_len / 4).max(1) |
| 2647 | } else { |
| 2648 | char_len.max(1) |
| 2649 | }; |
| 2650 | PromptLayerInspection { |
| 2651 | name, |
| 2652 | stability, |
| 2653 | char_len, |
| 2654 | byte_len: content.len(), |
| 2655 | token_estimate, |
| 2656 | sha256: sha256_hex(content.as_bytes()), |
| 2657 | tool_result: None, |
| 2658 | turn_meta: None, |
| 2659 | } |
| 2660 | } |
| 2661 | |
| 2662 | fn sha256_hex(bytes: &[u8]) -> String { |
| 2663 | codewhale_runtime::hashing::sha256_hex(bytes) |
| 2664 | } |
| 2665 | |
| 2666 | #[derive(Clone)] |
| 2667 | struct PendingToolCallInfo { |
| 2668 | tool_name: String, |
| 2669 | input: Value, |
| 2670 | } |
| 2671 | |
| 2672 | struct SeenToolResult { |
| 2673 | message_label: String, |
| 2674 | original_chars: usize, |
| 2675 | } |
| 2676 | |
| 2677 | struct WireToolResult { |
| 2678 | content: String, |
| 2679 | original_chars: usize, |
| 2680 | sent_chars: usize, |
| 2681 | truncated: bool, |
| 2682 | deduplicated: bool, |
| 2683 | } |
| 2684 | |
| 2685 | #[derive(Clone)] |
| 2686 | struct TurnMetaBudget { |
| 2687 | original_chars: usize, |
| 2688 | sent_chars: usize, |
| 2689 | deduplicated: bool, |
| 2690 | sha256: String, |
| 2691 | } |
| 2692 | |
| 2693 | struct LastFullTurnMeta { |
| 2694 | sha256: String, |
| 2695 | } |
| 2696 | |
| 2697 | fn render_turn_meta_for_wire( |
| 2698 | text: &str, |
| 2699 | last_full_turn_meta: &mut Option<LastFullTurnMeta>, |
| 2700 | ) -> (String, TurnMetaBudget) { |
| 2701 | let original_chars = text.chars().count(); |
| 2702 | let sha = sha256_hex(text.as_bytes()); |
| 2703 | |
| 2704 | if last_full_turn_meta |
| 2705 | .as_ref() |
| 2706 | .is_some_and(|previous| previous.sha256 == sha) |
| 2707 | { |
| 2708 | // Keep the repeated metadata slot short without surfacing an |
| 2709 | // opaque hash the model cannot resolve. |
| 2710 | let rendered = "<turn_meta_unchanged />".to_string(); |
| 2711 | let budget = TurnMetaBudget { |
| 2712 | original_chars, |
| 2713 | sent_chars: rendered.chars().count(), |
| 2714 | deduplicated: true, |
| 2715 | sha256: sha, |
| 2716 | }; |
| 2717 | return (rendered, budget); |
| 2718 | } |
| 2719 | |
| 2720 | *last_full_turn_meta = Some(LastFullTurnMeta { |
| 2721 | sha256: sha.clone(), |
| 2722 | }); |
| 2723 | ( |
| 2724 | text.to_string(), |
| 2725 | TurnMetaBudget { |
| 2726 | original_chars, |
| 2727 | sent_chars: original_chars, |
| 2728 | deduplicated: false, |
| 2729 | sha256: sha, |
| 2730 | }, |
| 2731 | ) |
| 2732 | } |
| 2733 | |
| 2734 | fn is_turn_meta_text(text: &str) -> bool { |
| 2735 | text.trim_start().starts_with("<turn_meta>") |
| 2736 | } |
| 2737 | |
| 2738 | fn turn_meta_budget_json(turn_meta: &TurnMetaBudget) -> Value { |
| 2739 | json!({ |
| 2740 | "original_chars": turn_meta.original_chars, |
| 2741 | "sent_chars": turn_meta.sent_chars, |
| 2742 | "deduplicated": turn_meta.deduplicated, |
| 2743 | "sha256": turn_meta.sha256, |
| 2744 | }) |
| 2745 | } |
| 2746 | |
| 2747 | /// Mutating/write tools whose result body is a *confirmation* (it embeds |
| 2748 | /// the unified diff + summary of what was just written), not retrievable |
| 2749 | /// reference data. Two identical large `write_file` calls must each keep |
| 2750 | /// their full confirmation inline: collapsing the later one to a |
| 2751 | /// `<TOOL_RESULT_REF sha="..." />` makes the model lose the write-success |
| 2752 | /// context and behave as if the file is missing (issue #1695). Read-style |
| 2753 | /// tools (`read_file`, `grep_files`, `exec_shell`, …) may deduplicate medium |
| 2754 | /// outputs by pointing at an earlier full message in the same request. They |
| 2755 | /// never advertise a process-wide SHA as retrievable: that store cannot prove |
| 2756 | /// session ownership. |
| 2757 | fn is_mutation_tool(tool_name: &str) -> bool { |
| 2758 | matches!( |
| 2759 | tool_name, |
| 2760 | "write" | "edit" | "write_file" | "edit_file" | "apply_patch" |
| 2761 | ) |
| 2762 | } |
| 2763 | |
| 2764 | fn compact_tool_result_for_wire( |
| 2765 | tool_name: &str, |
| 2766 | input: &Value, |
| 2767 | content: &str, |
| 2768 | message_label: &str, |
| 2769 | sent_budget: usize, |
| 2770 | seen_tool_results: &mut HashMap<String, SeenToolResult>, |
| 2771 | ) -> WireToolResult { |
| 2772 | let original_chars = content.chars().count(); |
| 2773 | let sha = sha256_hex(content.as_bytes()); |
| 2774 | |
| 2775 | // Only medium, non-mutation results can point back to a full earlier |
| 2776 | // message in this one request. Oversized results are already excerpts, so |
| 2777 | // a back-reference would falsely imply the exact bytes remain available. |
| 2778 | let dedup_eligible = (TOOL_RESULT_DEDUP_MIN_CHARS..=sent_budget).contains(&original_chars) |
| 2779 | && !is_mutation_tool(tool_name); |
| 2780 | |
| 2781 | if dedup_eligible && let Some(previous) = seen_tool_results.get(&sha) { |
| 2782 | let content = format!( |
| 2783 | "<TOOL_RESULT_REF sha=\"{sha}\" original_message=\"{label}\" chars=\"{chars}\">\n\ |
| 2784 | source: full content appears in {label} earlier in this request\n\ |
| 2785 | </TOOL_RESULT_REF>", |
| 2786 | label = previous.message_label, |
| 2787 | chars = previous.original_chars, |
| 2788 | ); |
| 2789 | return WireToolResult { |
| 2790 | sent_chars: content.chars().count(), |
| 2791 | content, |
| 2792 | original_chars, |
| 2793 | truncated: false, |
| 2794 | deduplicated: true, |
| 2795 | }; |
| 2796 | } |
| 2797 | |
| 2798 | if dedup_eligible { |
| 2799 | seen_tool_results.insert( |
| 2800 | sha.clone(), |
| 2801 | SeenToolResult { |
| 2802 | message_label: message_label.to_string(), |
| 2803 | original_chars, |
| 2804 | }, |
| 2805 | ); |
| 2806 | } |
| 2807 | |
| 2808 | if original_chars <= sent_budget { |
| 2809 | return WireToolResult { |
| 2810 | content: content.to_string(), |
| 2811 | original_chars, |
| 2812 | sent_chars: original_chars, |
| 2813 | truncated: false, |
| 2814 | deduplicated: false, |
| 2815 | }; |
| 2816 | } |
| 2817 | |
| 2818 | // Content already bounded by the adaptive evidence envelope carries its |
| 2819 | // own honest footer: the omitted count, the on-disk artifact path, and a |
| 2820 | // recovery instruction. Truncating it again here would destroy that |
| 2821 | // recovery contract and falsely report that no session-owned artifact |
| 2822 | // was recorded, so pass it through untouched. |
| 2823 | if content.contains(codewhale_tools::names::SPILLOVER_RECOVERY_HINT) { |
| 2824 | return WireToolResult { |
| 2825 | content: content.to_string(), |
| 2826 | original_chars, |
| 2827 | sent_chars: original_chars, |
| 2828 | truncated: false, |
| 2829 | deduplicated: false, |
| 2830 | }; |
| 2831 | } |
| 2832 | |
| 2833 | let excerpt_chars = sent_budget.saturating_sub(TOOL_RESULT_EXCERPT_FRAME_CHARS); |
| 2834 | let head_chars = excerpt_chars * 2 / 3; |
| 2835 | let head = first_chars(content, head_chars); |
| 2836 | let tail = last_chars(content, excerpt_chars - head_chars); |
| 2837 | let kept = head.chars().count() + tail.chars().count(); |
| 2838 | let omitted = original_chars.saturating_sub(kept); |
| 2839 | let compacted = format!( |
| 2840 | "[TOOL_RESULT_TRUNCATED]\n\ |
| 2841 | tool_name: {tool_name}\n\ |
| 2842 | command_or_query: {}\n\ |
| 2843 | exit_status: {}\n\ |
| 2844 | original_chars: {original_chars}\n\ |
| 2845 | sha256: {sha}\n\ |
| 2846 | exact_detail: unavailable; no session-owned artifact was recorded\n\ |
| 2847 | first_chars:\n\ |
| 2848 | {head}\n\n\ |
| 2849 | [... truncated {omitted} chars from middle ...]\n\n\ |
| 2850 | last_chars:\n\ |
| 2851 | {tail}", |
| 2852 | tool_command_or_query(input), |
| 2853 | tool_exit_status(content) |
| 2854 | ); |
| 2855 | |
| 2856 | WireToolResult { |
| 2857 | sent_chars: compacted.chars().count(), |
| 2858 | content: compacted, |
| 2859 | original_chars, |
| 2860 | truncated: true, |
| 2861 | deduplicated: false, |
| 2862 | } |
| 2863 | } |
| 2864 | |
| 2865 | fn tool_command_or_query(input: &Value) -> String { |
| 2866 | for key in ["command", "cmd", "query", "q", "pattern", "path", "url"] { |
| 2867 | if let Some(value) = input.get(key) { |
| 2868 | return summarize_for_metadata(value, 500); |
| 2869 | } |
| 2870 | } |
| 2871 | summarize_for_metadata(input, 500) |
| 2872 | } |
| 2873 | |
| 2874 | fn tool_exit_status(content: &str) -> String { |
| 2875 | if let Ok(value) = serde_json::from_str::<Value>(content) { |
| 2876 | for key in ["exit_code", "exit_status", "status", "code"] { |
| 2877 | if let Some(value) = value.get(key) { |
| 2878 | return summarize_for_metadata(value, 120); |
| 2879 | } |
| 2880 | } |
| 2881 | } |
| 2882 | |
| 2883 | for line in content.lines().take(20) { |
| 2884 | let trimmed = line.trim(); |
| 2885 | for prefix in ["Exit code:", "exit code:", "Exit status:", "exit status:"] { |
| 2886 | if let Some(value) = trimmed.strip_prefix(prefix) { |
| 2887 | return value.trim().to_string(); |
| 2888 | } |
| 2889 | } |
| 2890 | } |
| 2891 | "unknown".to_string() |
| 2892 | } |
| 2893 | |
| 2894 | fn summarize_for_metadata(value: &Value, max_chars: usize) -> String { |
| 2895 | let raw = value |
| 2896 | .as_str() |
| 2897 | .map(str::to_string) |
| 2898 | .unwrap_or_else(|| value.to_string()); |
| 2899 | let mut summarized = first_chars(&raw.replace('\n', "\\n"), max_chars); |
| 2900 | if raw.chars().count() > max_chars { |
| 2901 | summarized.push_str("..."); |
| 2902 | } |
| 2903 | summarized |
| 2904 | } |
| 2905 | |
| 2906 | fn first_chars(value: &str, count: usize) -> String { |
| 2907 | value.chars().take(count).collect() |
| 2908 | } |
| 2909 | |
| 2910 | fn last_chars(value: &str, count: usize) -> String { |
| 2911 | let mut chars: Vec<char> = value.chars().rev().take(count).collect(); |
| 2912 | chars.reverse(); |
| 2913 | chars.into_iter().collect() |
| 2914 | } |
| 2915 | |
| 2916 | fn merge_adjacent_user_content(previous: Value, current: Value) -> Value { |
| 2917 | match (previous, current) { |
| 2918 | (Value::String(left), Value::String(right)) => json!(format!("{left}\n\n{right}")), |
| 2919 | (left, right) => { |
| 2920 | let mut parts = Vec::new(); |
| 2921 | for content in [left, right] { |
| 2922 | match content { |
| 2923 | Value::Array(items) => parts.extend(items), |
| 2924 | Value::String(text) => parts.push(json!({"type": "text", "text": text})), |
| 2925 | other => parts.push(other), |
| 2926 | } |
| 2927 | } |
| 2928 | Value::Array(parts) |
| 2929 | } |
| 2930 | } |
| 2931 | } |
| 2932 | |
| 2933 | fn build_chat_messages_with_reasoning( |
| 2934 | system: Option<&SystemPrompt>, |
| 2935 | messages: &[Message], |
| 2936 | tool_result_budget: usize, |
| 2937 | include_reasoning: bool, |
| 2938 | include_tool_budget_metadata: bool, |
| 2939 | ) -> Vec<Value> { |
| 2940 | let mut out = Vec::new(); |
| 2941 | let mut pending_tool_calls: HashMap<String, PendingToolCallInfo> = HashMap::new(); |
| 2942 | // Chat Completions requires every result for one assistant tool-call batch |
| 2943 | // to be contiguous. Keep tool-result media aside until the complete batch |
| 2944 | // has been emitted as `role: tool` messages. |
| 2945 | let mut deferred_tool_result_images = Vec::new(); |
| 2946 | let mut seen_tool_results: HashMap<String, SeenToolResult> = HashMap::new(); |
| 2947 | let mut last_full_turn_meta: Option<LastFullTurnMeta> = None; |
| 2948 | |
| 2949 | if let Some(instructions) = system_to_instructions(system.cloned()) |
| 2950 | && !instructions.trim().is_empty() |
| 2951 | { |
| 2952 | out.push(json!({ |
| 2953 | "role": "system", |
| 2954 | "content": instructions, |
| 2955 | })); |
| 2956 | } |
| 2957 | |
| 2958 | // Persisted compaction keeps its summary after the bounded last round. |
| 2959 | // On strict paired chat templates a user message after a tool result is |
| 2960 | // invalid. Reorder only a generated summary immediately after a tool |
| 2961 | // result; its independent provenance block rules out quoted user text. |
| 2962 | // The session log retains every original message and tool ID. |
| 2963 | // Limitation: this normalization applies to Chat Completions only. |
| 2964 | let summary_index = messages |
| 2965 | .iter() |
| 2966 | .enumerate() |
| 2967 | .rev() |
| 2968 | .find_map(|(index, message)| { |
| 2969 | (index > 0 |
| 2970 | && codewhale_models::turn_classify::is_wire_compaction_checkpoint_message(message) |
| 2971 | && messages[index - 1] |
| 2972 | .content |
| 2973 | .iter() |
| 2974 | .any(|block| matches!(block, ContentBlock::ToolResult { .. }))) |
| 2975 | .then_some(index) |
| 2976 | }); |
| 2977 | let summary_target = summary_index.and_then(|summary_index| { |
| 2978 | messages[..summary_index] |
| 2979 | .iter() |
| 2980 | .rposition(|message| { |
| 2981 | codewhale_models::turn_classify::classify_user_turn_prompt(message) |
| 2982 | != codewhale_models::turn_classify::UserTurnPromptKind::NotPrompt |
| 2983 | }) |
| 2984 | .or_else(|| { |
| 2985 | messages[..summary_index] |
| 2986 | .iter() |
| 2987 | .position(|message| message.role.is_assistant_like()) |
| 2988 | }) |
| 2989 | }); |
| 2990 | let wire_messages = (0..messages.len()) |
| 2991 | .filter(|index| Some(*index) != summary_index || summary_target.is_none()) |
| 2992 | .flat_map(|index| { |
| 2993 | if Some(index) == summary_target { |
| 2994 | [summary_index, Some(index)] |
| 2995 | .into_iter() |
| 2996 | .flatten() |
| 2997 | .collect::<Vec<_>>() |
| 2998 | } else { |
| 2999 | vec![index] |
| 3000 | } |
| 3001 | }); |
| 3002 | |
| 3003 | for message_index in wire_messages { |
| 3004 | let message = &messages[message_index]; |
| 3005 | // Which wire channel this message belongs in is decided by the shared |
| 3006 | // placement table, not by an `if` chain local to this adapter. |
| 3007 | let placement = role_placement(&message.role, WireDialect::ChatCompletions); |
| 3008 | let mut text_parts = Vec::new(); |
| 3009 | let mut image_parts = Vec::new(); |
| 3010 | let mut file_parts = Vec::new(); |
| 3011 | let mut thinking_parts = Vec::new(); |
| 3012 | let mut tool_calls = Vec::new(); |
| 3013 | let mut server_tool_calls: Vec<Value> = Vec::new(); |
| 3014 | let mut tool_call_infos = Vec::new(); |
| 3015 | let mut tool_results: Vec<(String, String, String, Vec<Value>)> = Vec::new(); |
| 3016 | let mut turn_meta_budget: Option<TurnMetaBudget> = None; |
| 3017 | |
| 3018 | for block in &message.content { |
| 3019 | match block { |
| 3020 | ContentBlock::Text { text, .. } => { |
| 3021 | if is_turn_meta_text(text) { |
| 3022 | let (rendered, budget) = |
| 3023 | render_turn_meta_for_wire(text, &mut last_full_turn_meta); |
| 3024 | text_parts.push(rendered); |
| 3025 | turn_meta_budget = Some(budget); |
| 3026 | } else { |
| 3027 | text_parts.push(text.clone()); |
| 3028 | } |
| 3029 | } |
| 3030 | ContentBlock::ImageUrl { image_url } => { |
| 3031 | image_parts.push(json!({ |
| 3032 | "type": "image_url", |
| 3033 | "image_url": { |
| 3034 | "url": image_url.url.clone(), |
| 3035 | }, |
| 3036 | })); |
| 3037 | } |
| 3038 | ContentBlock::File { file_id } => { |
| 3039 | file_parts.push(json!({ |
| 3040 | "type": "file", |
| 3041 | "file_id": file_id.clone(), |
| 3042 | })); |
| 3043 | } |
| 3044 | ContentBlock::Thinking { thinking, .. } => thinking_parts.push(thinking.clone()), |
| 3045 | ContentBlock::ToolUse { |
| 3046 | id, |
| 3047 | name, |
| 3048 | input, |
| 3049 | caller, |
| 3050 | thought_signature, |
| 3051 | .. |
| 3052 | } => { |
| 3053 | let args = serde_json::to_string(input).unwrap_or_else(|_| input.to_string()); |
| 3054 | let mut call = json!({ |
| 3055 | "id": id, |
| 3056 | "type": "function", |
| 3057 | "function": { |
| 3058 | "name": to_api_tool_name(name), |
| 3059 | "arguments": args, |
| 3060 | } |
| 3061 | }); |
| 3062 | if let Some(signature) = thought_signature { |
| 3063 | call["extra_content"]["google"]["thought_signature"] = json!(signature); |
| 3064 | } |
| 3065 | if let Some(caller) = caller { |
| 3066 | call["caller"] = json!({ |
| 3067 | "type": caller.caller_type, |
| 3068 | "tool_id": caller.tool_id, |
| 3069 | }); |
| 3070 | } |
| 3071 | tool_calls.push(call); |
| 3072 | tool_call_infos.push(( |
| 3073 | id.clone(), |
| 3074 | PendingToolCallInfo { |
| 3075 | tool_name: name.clone(), |
| 3076 | input: input.clone(), |
| 3077 | }, |
| 3078 | )); |
| 3079 | } |
| 3080 | ContentBlock::ToolResult { |
| 3081 | tool_use_id, |
| 3082 | content, |
| 3083 | content_blocks, |
| 3084 | .. |
| 3085 | } => { |
| 3086 | let message_label = format!("Message #{message_index}"); |
| 3087 | tool_results.push(( |
| 3088 | tool_use_id.clone(), |
| 3089 | content.clone(), |
| 3090 | message_label, |
| 3091 | content_blocks.clone().unwrap_or_default(), |
| 3092 | )); |
| 3093 | } |
| 3094 | ContentBlock::ServerToolCalls { steps } => { |
| 3095 | server_tool_calls.extend(steps.iter().cloned()); |
| 3096 | } |
| 3097 | ContentBlock::ServerToolUse { .. } |
| 3098 | | ContentBlock::ToolSearchToolResult { .. } |
| 3099 | | ContentBlock::CodeExecutionToolResult { .. } |
| 3100 | | ContentBlock::WebSearchToolResult { .. } |
| 3101 | | ContentBlock::WebFetchToolResult { .. } |
| 3102 | | ContentBlock::WebSearchCall { .. } => {} |
| 3103 | } |
| 3104 | } |
| 3105 | |
| 3106 | let out_len_before_role_projection = out.len(); |
| 3107 | if placement.is_assistant_channel() { |
| 3108 | let content = if placement == RolePlacement::InterruptedAssistant { |
| 3109 | format!( |
| 3110 | "{}{}", |
| 3111 | codewhale_models::INTERRUPTED_ASSISTANT_CONTEXT_PREFIX, |
| 3112 | text_parts.join("\n") |
| 3113 | ) |
| 3114 | } else { |
| 3115 | text_parts.join("\n") |
| 3116 | }; |
| 3117 | let mut reasoning_content = thinking_parts.join("\n"); |
| 3118 | let has_text = !content.trim().is_empty(); |
| 3119 | let has_tool_calls = !tool_calls.is_empty(); |
| 3120 | let has_server_tool_calls = !server_tool_calls.is_empty(); |
| 3121 | // Reasoning replay must be a function of the stored message ONLY, |
| 3122 | // never of later history. DeepSeek's prefix cache hashes the raw |
| 3123 | // bytes of every message; flipping `reasoning_content` on/off |
| 3124 | // depending on whether a follow-up user turn exists rewrites a |
| 3125 | // historical message between turns and busts the cache from that |
| 3126 | // point onwards. Always emit `reasoning_content` when the model |
| 3127 | // requires replay AND the stored message carries thinking text. |
| 3128 | // Tool-call messages with empty thinking still need a placeholder |
| 3129 | // (DeepSeek 400s without it), but text-only assistant messages |
| 3130 | // simply omit the field when there's nothing to replay. |
| 3131 | let mut has_reasoning = include_reasoning && !reasoning_content.trim().is_empty(); |
| 3132 | if include_reasoning && has_tool_calls && !has_reasoning { |
| 3133 | logging::warn( |
| 3134 | "Substituting placeholder reasoning_content for DeepSeek tool-call assistant message", |
| 3135 | ); |
| 3136 | reasoning_content = String::from(REASONING_REPLAY_PLACEHOLDER); |
| 3137 | has_reasoning = true; |
| 3138 | } |
| 3139 | |
| 3140 | // DeepSeek rejects assistant messages where both `content` and |
| 3141 | // `tool_calls` are missing/null. Skip such entries even if they |
| 3142 | // carry reasoning-only metadata unless we can send a non-null |
| 3143 | // placeholder content field. |
| 3144 | if !has_text && !has_tool_calls && !has_reasoning && !has_server_tool_calls { |
| 3145 | pending_tool_calls.clear(); |
| 3146 | deferred_tool_result_images.clear(); |
| 3147 | continue; |
| 3148 | } |
| 3149 | |
| 3150 | let mut msg = json!({ |
| 3151 | "role": "assistant", |
| 3152 | "content": if has_text { |
| 3153 | json!(content) |
| 3154 | } else if has_reasoning { |
| 3155 | json!("") |
| 3156 | } else { |
| 3157 | Value::Null |
| 3158 | }, |
| 3159 | }); |
| 3160 | if has_reasoning { |
| 3161 | msg["reasoning_content"] = json!(reasoning_content); |
| 3162 | } |
| 3163 | if has_server_tool_calls { |
| 3164 | msg["server_tool_calls"] = json!(server_tool_calls); |
| 3165 | } |
| 3166 | if has_tool_calls { |
| 3167 | msg["tool_calls"] = json!(tool_calls); |
| 3168 | let expected_tool_result_count = tool_call_infos.len(); |
| 3169 | pending_tool_calls = tool_call_infos.into_iter().collect(); |
| 3170 | deferred_tool_result_images.clear(); |
| 3171 | if pending_tool_calls.len() != expected_tool_result_count { |
| 3172 | logging::warn( |
| 3173 | "Rejecting assistant tool-call batch with duplicate tool_call IDs", |
| 3174 | ); |
| 3175 | pending_tool_calls.clear(); |
| 3176 | } |
| 3177 | } else { |
| 3178 | pending_tool_calls.clear(); |
| 3179 | deferred_tool_result_images.clear(); |
| 3180 | } |
| 3181 | out.push(msg); |
| 3182 | } else if matches!(placement, RolePlacement::System | RolePlacement::Developer) { |
| 3183 | let content = text_parts.join("\n"); |
| 3184 | if !content.trim().is_empty() { |
| 3185 | let mut msg = json!({ |
| 3186 | "role": if placement == RolePlacement::Developer { |
| 3187 | "developer" |
| 3188 | } else { |
| 3189 | "system" |
| 3190 | }, |
| 3191 | "content": content, |
| 3192 | }); |
| 3193 | if include_tool_budget_metadata && let Some(turn_meta) = &turn_meta_budget { |
| 3194 | msg["_turn_meta_budget"] = turn_meta_budget_json(turn_meta); |
| 3195 | } |
| 3196 | out.push(msg); |
| 3197 | } |
| 3198 | } else if placement == RolePlacement::LatestReminder { |
| 3199 | let content = text_parts.join("\n"); |
| 3200 | if !content.trim().is_empty() { |
| 3201 | out.push(json!({ |
| 3202 | "role": "latest_reminder", |
| 3203 | "content": content, |
| 3204 | })); |
| 3205 | } |
| 3206 | } else if placement == RolePlacement::User { |
| 3207 | let content = text_parts.join("\n"); |
| 3208 | let has_text = !content.trim().is_empty(); |
| 3209 | let has_images = !image_parts.is_empty(); |
| 3210 | let has_files = !file_parts.is_empty(); |
| 3211 | if has_text || has_images || has_files { |
| 3212 | let wire_content = if has_images || has_files { |
| 3213 | let mut parts = Vec::new(); |
| 3214 | if has_text { |
| 3215 | parts.push(json!({ |
| 3216 | "type": "text", |
| 3217 | "text": content, |
| 3218 | })); |
| 3219 | } |
| 3220 | parts.extend(image_parts); |
| 3221 | parts.extend(file_parts); |
| 3222 | json!(parts) |
| 3223 | } else { |
| 3224 | json!(content) |
| 3225 | }; |
| 3226 | let mut msg = json!({ |
| 3227 | "role": "user", |
| 3228 | "content": wire_content, |
| 3229 | }); |
| 3230 | if include_tool_budget_metadata && let Some(turn_meta) = &turn_meta_budget { |
| 3231 | msg["_turn_meta_budget"] = turn_meta_budget_json(turn_meta); |
| 3232 | } |
| 3233 | if summary_target.is_some() |
| 3234 | && summary_index.is_some_and(|checkpoint| message_index == checkpoint + 1) |
| 3235 | && pending_tool_calls.is_empty() |
| 3236 | && out.last().is_some_and(|entry| entry["role"] == "tool") |
| 3237 | { |
| 3238 | out.push(json!({"role": "assistant", "content": " "})); |
| 3239 | } |
| 3240 | if (Some(message_index) == summary_index |
| 3241 | || Some(message_index) == summary_target |
| 3242 | || codewhale_models::turn_classify::is_wire_compaction_checkpoint_message( |
| 3243 | message, |
| 3244 | ) |
| 3245 | || crate::runtime_handoff::is_agent_topology_checkpoint(message) |
| 3246 | || crate::runtime_handoff::is_restored_agent_topology_checkpoint(message)) |
| 3247 | && let Some(previous) = out.last_mut() |
| 3248 | && previous.get("role").and_then(Value::as_str) == Some("user") |
| 3249 | { |
| 3250 | let previous_content = previous["content"].take(); |
| 3251 | let current_content = msg["content"].take(); |
| 3252 | previous["content"] = |
| 3253 | merge_adjacent_user_content(previous_content, current_content); |
| 3254 | if previous.get("_turn_meta_budget").is_none() |
| 3255 | && let Some(meta) = msg.get("_turn_meta_budget") |
| 3256 | { |
| 3257 | previous["_turn_meta_budget"] = meta.clone(); |
| 3258 | } |
| 3259 | } else { |
| 3260 | out.push(msg); |
| 3261 | } |
| 3262 | } |
| 3263 | } |
| 3264 | |
| 3265 | // A user/system/developer wire message closes the contiguous run that |
| 3266 | // must follow an assistant tool-call message. If the same stored |
| 3267 | // message also carries a later tool result, reject it here instead of |
| 3268 | // briefly accepting the result and letting any synthesized media |
| 3269 | // escape after the safety pass strips the malformed batch. |
| 3270 | if out.len() > out_len_before_role_projection |
| 3271 | && !placement.is_assistant_channel() |
| 3272 | && !pending_tool_calls.is_empty() |
| 3273 | { |
| 3274 | logging::warn("Dropping tool-call batch interrupted by non-tool content"); |
| 3275 | pending_tool_calls.clear(); |
| 3276 | deferred_tool_result_images.clear(); |
| 3277 | } |
| 3278 | |
| 3279 | if !tool_results.is_empty() { |
| 3280 | if pending_tool_calls.is_empty() { |
| 3281 | logging::warn("Dropping tool results without matching tool_calls"); |
| 3282 | } else { |
| 3283 | for (tool_id, content, message_label, content_blocks) in tool_results { |
| 3284 | if let Some(tool_info) = pending_tool_calls.remove(&tool_id) { |
| 3285 | let (image, omitted) = crate::image_attach::provider_tool_result_image_refs( |
| 3286 | Some(&content_blocks), |
| 3287 | ); |
| 3288 | let content = |
| 3289 | codewhale_models::image_window::tool_result_text_with_omission( |
| 3290 | &content, omitted, |
| 3291 | ); |
| 3292 | let wire_result = compact_tool_result_for_wire( |
| 3293 | &tool_info.tool_name, |
| 3294 | &tool_info.input, |
| 3295 | &content, |
| 3296 | &message_label, |
| 3297 | tool_result_budget, |
| 3298 | &mut seen_tool_results, |
| 3299 | ); |
| 3300 | let mut tool_msg = json!({ |
| 3301 | "role": "tool", |
| 3302 | "tool_call_id": tool_id, |
| 3303 | "content": wire_result.content, |
| 3304 | }); |
| 3305 | if include_tool_budget_metadata { |
| 3306 | tool_msg["_tool_result_budget"] = json!({ |
| 3307 | "original_chars": wire_result.original_chars, |
| 3308 | "sent_chars": wire_result.sent_chars, |
| 3309 | "truncated": wire_result.truncated, |
| 3310 | "deduplicated": wire_result.deduplicated, |
| 3311 | }); |
| 3312 | } |
| 3313 | out.push(tool_msg); |
| 3314 | if let Some((mime_type, data)) = image { |
| 3315 | deferred_tool_result_images.push(json!({ |
| 3316 | "type": "text", |
| 3317 | "text": format!( |
| 3318 | "Image returned by tool `{}` (call `{tool_id}`):", |
| 3319 | tool_info.tool_name, |
| 3320 | ), |
| 3321 | })); |
| 3322 | deferred_tool_result_images.push(json!({ |
| 3323 | "type": "image_url", |
| 3324 | "image_url": { |
| 3325 | "url": format!("data:{mime_type};base64,{data}") |
| 3326 | }, |
| 3327 | })); |
| 3328 | } |
| 3329 | } else { |
| 3330 | logging::warn(format!( |
| 3331 | "Dropping tool result for unknown tool_call_id: {tool_id}" |
| 3332 | )); |
| 3333 | } |
| 3334 | } |
| 3335 | if pending_tool_calls.is_empty() && !deferred_tool_result_images.is_empty() { |
| 3336 | out.push(json!({ |
| 3337 | "role": "user", |
| 3338 | "content": std::mem::take(&mut deferred_tool_result_images), |
| 3339 | })); |
| 3340 | } |
| 3341 | } |
| 3342 | } else if !placement.is_assistant_channel() { |
| 3343 | pending_tool_calls.clear(); |
| 3344 | deferred_tool_result_images.clear(); |
| 3345 | } |
| 3346 | } |
| 3347 | |
| 3348 | // Safety net: after compaction, an assistant message may have tool_calls |
| 3349 | // whose results were summarized away. The API rejects these, so strip |
| 3350 | // the tool_calls (downgrading to a plain assistant message) and remove |
| 3351 | // the now-orphaned tool result messages. |
| 3352 | let mut i = 0; |
| 3353 | while i < out.len() { |
| 3354 | let is_assistant_with_tools = out[i].get("role").and_then(Value::as_str) |
| 3355 | == Some("assistant") |
| 3356 | && out[i].get("tool_calls").is_some(); |
| 3357 | |
| 3358 | if is_assistant_with_tools { |
| 3359 | let expected_ids: Vec<String> = out[i] |
| 3360 | .get("tool_calls") |
| 3361 | .and_then(Value::as_array) |
| 3362 | .map(|calls| { |
| 3363 | calls |
| 3364 | .iter() |
| 3365 | .filter_map(|c| c.get("id").and_then(Value::as_str).map(String::from)) |
| 3366 | .collect() |
| 3367 | }) |
| 3368 | .unwrap_or_default(); |
| 3369 | |
| 3370 | // Collect tool result IDs immediately following this assistant message. |
| 3371 | let mut found_ids = Vec::new(); |
| 3372 | let mut tool_result_end = i + 1; |
| 3373 | while tool_result_end < out.len() { |
| 3374 | if out[tool_result_end].get("role").and_then(Value::as_str) == Some("tool") { |
| 3375 | if let Some(id) = out[tool_result_end] |
| 3376 | .get("tool_call_id") |
| 3377 | .and_then(Value::as_str) |
| 3378 | { |
| 3379 | found_ids.push(id.to_string()); |
| 3380 | } |
| 3381 | tool_result_end += 1; |
| 3382 | } else { |
| 3383 | break; |
| 3384 | } |
| 3385 | } |
| 3386 | |
| 3387 | // Chat Completions accepts only the immediately contiguous tool |
| 3388 | // run after its assistant tool-call message. Do not accept a |
| 3389 | // later tool result after user/system content has intervened. |
| 3390 | let results_match = expected_ids.len() == found_ids.len() |
| 3391 | && expected_ids.iter().all(|id| found_ids.contains(id)); |
| 3392 | if !results_match { |
| 3393 | let missing: Vec<_> = expected_ids |
| 3394 | .iter() |
| 3395 | .filter(|id| !found_ids.contains(*id)) |
| 3396 | .collect(); |
| 3397 | logging::warn(format!( |
| 3398 | "Stripping orphaned tool_calls from assistant message \ |
| 3399 | (expected {} tool results, found {}, missing: {:?})", |
| 3400 | expected_ids.len(), |
| 3401 | found_ids.len(), |
| 3402 | missing |
| 3403 | )); |
| 3404 | if let Some(obj) = out[i].as_object_mut() { |
| 3405 | obj.remove("tool_calls"); |
| 3406 | } |
| 3407 | // If tool_calls were the only assistant content, remove the now-invalid |
| 3408 | // assistant message entirely (DeepSeek requires content or tool_calls). |
| 3409 | let assistant_content_empty = out[i] |
| 3410 | .get("content") |
| 3411 | .is_none_or(|v| v.is_null() || v.as_str().is_some_and(str::is_empty)); |
| 3412 | if assistant_content_empty { |
| 3413 | // Remove orphaned tool results tied to this stripped assistant call set. |
| 3414 | let mut j = out.len(); |
| 3415 | while j > i + 1 { |
| 3416 | j -= 1; |
| 3417 | if out[j].get("role").and_then(Value::as_str) == Some("tool") |
| 3418 | && let Some(id) = out[j].get("tool_call_id").and_then(Value::as_str) |
| 3419 | && expected_ids.iter().any(|expected| expected == id) |
| 3420 | { |
| 3421 | out.remove(j); |
| 3422 | } |
| 3423 | } |
| 3424 | out.remove(i); |
| 3425 | i = i.saturating_sub(1); |
| 3426 | continue; |
| 3427 | } |
| 3428 | // Remove contiguous tool results first |
| 3429 | if tool_result_end > i + 1 { |
| 3430 | out.drain((i + 1)..tool_result_end); |
| 3431 | } |
| 3432 | // Remove any remaining non-contiguous tool results referencing expected_ids |
| 3433 | // (scan backward to avoid index shifting issues) |
| 3434 | let mut j = out.len(); |
| 3435 | while j > i + 1 { |
| 3436 | j -= 1; |
| 3437 | if out[j].get("role").and_then(Value::as_str) == Some("tool") |
| 3438 | && let Some(id) = out[j].get("tool_call_id").and_then(Value::as_str) |
| 3439 | && expected_ids.iter().any(|expected| expected == id) |
| 3440 | { |
| 3441 | out.remove(j); |
| 3442 | } |
| 3443 | } |
| 3444 | } |
| 3445 | } |
| 3446 | i += 1; |
| 3447 | } |
| 3448 | |
| 3449 | out |
| 3450 | } |
| 3451 | |
| 3452 | fn chat_tool_envelope( |
| 3453 | tool: &Tool, |
| 3454 | description: String, |
| 3455 | parameters: Value, |
| 3456 | strict: Option<bool>, |
| 3457 | ) -> Value { |
| 3458 | let mut value = json!({ |
| 3459 | "type": "function", |
| 3460 | "function": { |
| 3461 | "name": to_api_tool_name(&tool.name), |
| 3462 | "description": description, |
| 3463 | "parameters": parameters, |
| 3464 | } |
| 3465 | }); |
| 3466 | if let Some(strict) = strict |
| 3467 | && let Some(function) = value.get_mut("function") |
| 3468 | { |
| 3469 | function["strict"] = json!(strict); |
| 3470 | } |
| 3471 | value |
| 3472 | } |
| 3473 | |
| 3474 | fn logical_tool_for_inspect(tool: &Tool) -> Value { |
| 3475 | chat_tool_envelope( |
| 3476 | tool, |
| 3477 | tool.description.clone(), |
| 3478 | tool.input_schema.clone(), |
| 3479 | tool.strict, |
| 3480 | ) |
| 3481 | } |
| 3482 | |
| 3483 | fn tool_to_chat_projected( |
| 3484 | tool: &Tool, |
| 3485 | parameters: Value, |
| 3486 | strict: Option<bool>, |
| 3487 | constraint_note: Option<String>, |
| 3488 | ) -> Value { |
| 3489 | chat_tool_envelope( |
| 3490 | tool, |
| 3491 | description_with_constraint_note(&tool.description, constraint_note), |
| 3492 | parameters, |
| 3493 | strict, |
| 3494 | ) |
| 3495 | } |
| 3496 | |
| 3497 | fn deepseek_base_url_supports_strict_tools(base_url: &str) -> bool { |
| 3498 | let trimmed = base_url.trim_end_matches('/').to_ascii_lowercase(); |
| 3499 | let is_deepseek = trimmed == "https://api.deepseek.com" |
| 3500 | || trimmed == "https://api.deepseek.com/v1" |
| 3501 | || trimmed == "https://api.deepseek.com/beta" |
| 3502 | || trimmed == "https://api.deepseeki.com" |
| 3503 | || trimmed == "https://api.deepseeki.com/v1" |
| 3504 | || trimmed == "https://api.deepseeki.com/beta"; |
| 3505 | !is_deepseek || trimmed.ends_with("/beta") |
| 3506 | } |
| 3507 | |
| 3508 | fn map_tool_choice_for_chat(choice: &Value) -> Option<Value> { |
| 3509 | if let Some(choice_str) = choice.as_str() { |
| 3510 | return Some(match forced_tool_name(choice) { |
| 3511 | Some(name) => json!({ |
| 3512 | "type": "function", |
| 3513 | "function": { "name": to_api_tool_name(name) } |
| 3514 | }), |
| 3515 | None => json!(choice_str), |
| 3516 | }); |
| 3517 | } |
| 3518 | let Some(choice_type) = choice.get("type").and_then(Value::as_str) else { |
| 3519 | return Some(choice.clone()); |
| 3520 | }; |
| 3521 | if choice_type == "function" |
| 3522 | && let Some(name) = forced_tool_name(choice) |
| 3523 | { |
| 3524 | return Some(json!({ |
| 3525 | "type": "function", |
| 3526 | "function": { "name": to_api_tool_name(name) } |
| 3527 | })); |
| 3528 | } |
| 3529 | |
| 3530 | match choice_type { |
| 3531 | "auto" | "none" => Some(json!(choice_type)), |
| 3532 | "any" => Some(json!("auto")), |
| 3533 | "tool" => choice.get("name").and_then(Value::as_str).map(|name| { |
| 3534 | json!({ |
| 3535 | "type": "function", |
| 3536 | "function": { "name": to_api_tool_name(name) } |
| 3537 | }) |
| 3538 | }), |
| 3539 | _ => Some(choice.clone()), |
| 3540 | } |
| 3541 | } |
| 3542 | |
| 3543 | fn should_send_tool_choice_for_chat( |
| 3544 | provider: ProviderKind, |
| 3545 | effort: Option<&str>, |
| 3546 | choice: &Value, |
| 3547 | ) -> bool { |
| 3548 | if !matches!(provider, ProviderKind::Deepseek) { |
| 3549 | return true; |
| 3550 | } |
| 3551 | !reasoning_effort_enables_thinking(effort) || choice.as_str() == Some("none") |
| 3552 | } |
| 3553 | |
| 3554 | fn reasoning_effort_enables_thinking(effort: Option<&str>) -> bool { |
| 3555 | let Some(effort) = effort else { |
| 3556 | return false; |
| 3557 | }; |
| 3558 | !matches!( |
| 3559 | effort.trim().to_ascii_lowercase().as_str(), |
| 3560 | "off" | "disabled" | "none" | "false" |
| 3561 | ) |
| 3562 | } |
| 3563 | |
| 3564 | /// Final-pass sanitizer over the outgoing chat-completions JSON payload. |
| 3565 | /// Forces a non-empty `reasoning_content` onto assistant messages that carry |
| 3566 | /// `tool_calls`, when the model + effort combination requires it. DeepSeek's |
| 3567 | /// thinking-mode API rejects such messages with a 400 error; substituting a |
| 3568 | /// placeholder keeps the conversation chain intact. Non-tool assistant |
| 3569 | /// reasoning can stay omitted once a later user text turn begins. |
| 3570 | /// |
| 3571 | /// Also tallies the size of all replayed `reasoning_content` and logs it, so |
| 3572 | /// users on `RUST_LOG=codewhale_tui=debug` can see how much of their input |
| 3573 | /// budget is being spent re-sending prior thinking traces. |
| 3574 | #[cfg(test)] |
| 3575 | pub(super) fn sanitize_thinking_mode_messages( |
| 3576 | body: &mut Value, |
| 3577 | model: &str, |
| 3578 | effort: Option<&str>, |
| 3579 | provider: ProviderKind, |
| 3580 | ) -> Option<u32> { |
| 3581 | sanitize_thinking_mode_messages_for_route(body, model, effort, provider, "") |
| 3582 | } |
| 3583 | |
| 3584 | /// Route-aware variant of `sanitize_thinking_mode_messages`. |
| 3585 | /// |
| 3586 | /// The wrapper above remains intentionally route-agnostic for existing test |
| 3587 | /// helpers and generic callers. Production chat requests call this version so |
| 3588 | /// exact Kimi Code K3 assistant tool turns retain the reasoning trace that |
| 3589 | /// K3 expects on the next request. |
| 3590 | pub(super) fn sanitize_thinking_mode_messages_for_route( |
| 3591 | body: &mut Value, |
| 3592 | model: &str, |
| 3593 | effort: Option<&str>, |
| 3594 | provider: ProviderKind, |
| 3595 | base_url: &str, |
| 3596 | ) -> Option<u32> { |
| 3597 | // Mistral replay is encoded inside polymorphic `content` blocks, not the |
| 3598 | // DeepSeek `reasoning_content` field. Running the DeepSeek placeholder |
| 3599 | // sanitizer after reshaping would add a second, invalid reasoning dialect |
| 3600 | // to assistant tool-call turns. |
| 3601 | if is_exact_mistral_chat_route(provider, base_url) { |
| 3602 | return None; |
| 3603 | } |
| 3604 | if !should_replay_reasoning_content_for_provider_on_route(provider, base_url, model, effort) { |
| 3605 | return None; |
| 3606 | } |
| 3607 | let messages = body.get_mut("messages").and_then(Value::as_array_mut)?; |
| 3608 | let mut substitutions: u32 = 0; |
| 3609 | let mut replay_chars: u64 = 0; |
| 3610 | let mut replay_messages: u32 = 0; |
| 3611 | for (idx, msg) in messages.iter_mut().enumerate() { |
| 3612 | if msg.get("role").and_then(Value::as_str) != Some("assistant") { |
| 3613 | continue; |
| 3614 | } |
| 3615 | let has_tool_calls = msg.get("tool_calls").is_some(); |
| 3616 | let needs_placeholder = msg |
| 3617 | .get("reasoning_content") |
| 3618 | .and_then(Value::as_str) |
| 3619 | .is_none_or(|s| s.trim().is_empty()); |
| 3620 | if has_tool_calls && needs_placeholder { |
| 3621 | msg["reasoning_content"] = json!(REASONING_REPLAY_PLACEHOLDER); |
| 3622 | substitutions = substitutions.saturating_add(1); |
| 3623 | logging::warn(format!( |
| 3624 | "Final sanitizer: forced reasoning_content placeholder on assistant[{idx}]", |
| 3625 | )); |
| 3626 | } |
| 3627 | if let Some(reasoning) = msg.get("reasoning_content").and_then(Value::as_str) { |
| 3628 | let len = reasoning.len() as u64; |
| 3629 | if len > 0 { |
| 3630 | replay_chars = replay_chars.saturating_add(len); |
| 3631 | replay_messages = replay_messages.saturating_add(1); |
| 3632 | } |
| 3633 | } |
| 3634 | } |
| 3635 | if substitutions > 0 { |
| 3636 | logging::warn(format!( |
| 3637 | "Final sanitizer: {substitutions} assistant message(s) needed reasoning_content placeholder", |
| 3638 | )); |
| 3639 | } |
| 3640 | if replay_messages == 0 { |
| 3641 | return None; |
| 3642 | } |
| 3643 | // ~4 chars/token is the standard rough estimate; DeepSeek tokens skew |
| 3644 | // a touch shorter on Chinese/code but this is order-of-magnitude info. |
| 3645 | let approx_tokens = (replay_chars / 4).min(u64::from(u32::MAX)) as u32; |
| 3646 | logging::info(format!( |
| 3647 | "Reasoning-content replay: {replay_messages} assistant message(s), ~{approx_tokens} input tokens ({replay_chars} chars) being re-sent in this request", |
| 3648 | )); |
| 3649 | Some(approx_tokens) |
| 3650 | } |
| 3651 | |
| 3652 | /// Sums the byte length of `reasoning_content` across all assistant messages in |
| 3653 | /// an outgoing chat-completions body. Used by tests; the production sanitizer |
| 3654 | /// computes the same number inline and logs it. |
| 3655 | #[cfg(test)] |
| 3656 | pub(super) fn count_reasoning_replay_chars(body: &Value) -> u64 { |
| 3657 | let Some(messages) = body.get("messages").and_then(Value::as_array) else { |
| 3658 | return 0; |
| 3659 | }; |
| 3660 | messages |
| 3661 | .iter() |
| 3662 | .filter(|m| m.get("role").and_then(Value::as_str) == Some("assistant")) |
| 3663 | .filter_map(|m| m.get("reasoning_content").and_then(Value::as_str)) |
| 3664 | .map(|s| s.len() as u64) |
| 3665 | .sum() |
| 3666 | } |
| 3667 | |
| 3668 | /// Render the transport-shape headers we care about for #103 diagnostics. |
| 3669 | /// Always returns SOMETHING printable so the decode-error log line is parseable |
| 3670 | /// even when the server stripped a header we expected. |
| 3671 | fn format_stream_headers(headers: &reqwest::header::HeaderMap) -> String { |
| 3672 | const FIELDS: &[&str] = &[ |
| 3673 | "content-encoding", |
| 3674 | "transfer-encoding", |
| 3675 | "connection", |
| 3676 | "server", |
| 3677 | ]; |
| 3678 | let mut parts: Vec<String> = Vec::with_capacity(FIELDS.len()); |
| 3679 | for field in FIELDS { |
| 3680 | let rendered = headers |
| 3681 | .get(*field) |
| 3682 | .and_then(|v| v.to_str().ok()) |
| 3683 | .unwrap_or("(absent)"); |
| 3684 | parts.push(format!("{field}={rendered}")); |
| 3685 | } |
| 3686 | parts.join(", ") |
| 3687 | } |
| 3688 | |
| 3689 | /// Diagnostic logger fired when DeepSeek rejects the request despite the |
| 3690 | /// sanitizer. Walks the body and logs which assistant messages have tool_calls |
| 3691 | /// but no `reasoning_content` — useful to track down a code path that bypasses |
| 3692 | /// the sanitizer entirely. |
| 3693 | fn log_thinking_mode_violations(body: &Value) { |
| 3694 | let Some(messages) = body.get("messages").and_then(Value::as_array) else { |
| 3695 | logging::warn("400-after-sanitizer: body has no `messages` array"); |
| 3696 | return; |
| 3697 | }; |
| 3698 | let mut violations: Vec<String> = Vec::new(); |
| 3699 | for (idx, msg) in messages.iter().enumerate() { |
| 3700 | if msg.get("role").and_then(Value::as_str) != Some("assistant") { |
| 3701 | continue; |
| 3702 | } |
| 3703 | let reasoning = msg |
| 3704 | .get("reasoning_content") |
| 3705 | .and_then(Value::as_str) |
| 3706 | .unwrap_or(""); |
| 3707 | let has_tc = msg.get("tool_calls").is_some(); |
| 3708 | if reasoning.trim().is_empty() { |
| 3709 | violations.push(format!( |
| 3710 | "assistant[{idx}] (reasoning_content missing, tool_calls={has_tc})" |
| 3711 | )); |
| 3712 | } |
| 3713 | } |
| 3714 | if violations.is_empty() { |
| 3715 | logging::warn( |
| 3716 | "400-after-sanitizer: all assistant messages have reasoning_content — DeepSeek rejected for a different reason", |
| 3717 | ); |
| 3718 | } else { |
| 3719 | logging::warn(format!( |
| 3720 | "400-after-sanitizer: {} assistant message(s) lack reasoning_content despite sanitizer: {}", |
| 3721 | violations.len(), |
| 3722 | violations.join(", ") |
| 3723 | )); |
| 3724 | } |
| 3725 | } |
| 3726 | |
| 3727 | fn requires_reasoning_content(model: &str) -> bool { |
| 3728 | let lower = model.to_lowercase(); |
| 3729 | // V4-family direct model IDs. |
| 3730 | lower.contains("deepseek-v4") |
| 3731 | // Public DeepSeek API aliases routed server-side to the V4 family. |
| 3732 | // `deepseek-chat` resolves to `deepseek-v4-flash` and `deepseek-reasoner` |
| 3733 | // resolves to `deepseek-v4-pro`; both have thinking mode enabled by |
| 3734 | // default, so any assistant message carrying tool_calls must replay |
| 3735 | // `reasoning_content` on subsequent turns or the API returns 400. |
| 3736 | || lower.starts_with("deepseek-chat") |
| 3737 | || lower.starts_with("deepseek-reasoner") |
| 3738 | || has_deepseek_r_series_marker(&lower) |
| 3739 | // #6044: the V4.1 official id dropped the version number entirely |
| 3740 | // (`deepseek-flash`), so the literal arms above cannot see it and |
| 3741 | // the decode/replay classifiers depended on a later catalog fallback |
| 3742 | // to catch it. The catalog owns the capability — consult it here so |
| 3743 | // every caller (stream style, wire replay, prompt inspection) agrees |
| 3744 | // without another hardcoded id. |
| 3745 | || (lower.starts_with("deepseek-") && model_supports_reasoning(model)) |
| 3746 | } |
| 3747 | |
| 3748 | fn should_replay_reasoning_content(model: &str, effort: Option<&str>) -> bool { |
| 3749 | if effort |
| 3750 | .map(|value| { |
| 3751 | matches!( |
| 3752 | value.trim().to_ascii_lowercase().as_str(), |
| 3753 | "off" | "disabled" | "none" | "false" |
| 3754 | ) |
| 3755 | }) |
| 3756 | .unwrap_or(false) |
| 3757 | { |
| 3758 | return false; |
| 3759 | } |
| 3760 | |
| 3761 | requires_reasoning_content(model) |
| 3762 | } |
| 3763 | |
| 3764 | #[cfg(test)] |
| 3765 | fn should_replay_reasoning_content_for_provider( |
| 3766 | provider: ProviderKind, |
| 3767 | model: &str, |
| 3768 | effort: Option<&str>, |
| 3769 | ) -> bool { |
| 3770 | should_replay_reasoning_content_for_provider_on_route(provider, "", model, effort) |
| 3771 | } |
| 3772 | |
| 3773 | /// Route-aware reasoning replay policy. |
| 3774 | /// |
| 3775 | /// Keep the bare K3 identifier out of the global model catalog: direct |
| 3776 | /// Moonshot and arbitrary OpenAI-compatible routes can also expose a `k3` |
| 3777 | /// model name, but only Kimi Code's exact membership-plan endpoint has this |
| 3778 | /// replay contract. |
| 3779 | fn should_replay_reasoning_content_for_provider_on_route( |
| 3780 | provider: ProviderKind, |
| 3781 | base_url: &str, |
| 3782 | model: &str, |
| 3783 | effort: Option<&str>, |
| 3784 | ) -> bool { |
| 3785 | // Exact always-thinking routes replay their reasoning trace regardless of |
| 3786 | // a stale caller effort: the API contract requires the assistant |
| 3787 | // reasoning field on later tool turns for multi-turn continuity. |
| 3788 | if is_exact_direct_moonshot_k3_route(provider, base_url, model) |
| 3789 | || is_exact_kimi_code_k3_route(provider, base_url, model) |
| 3790 | || (is_exact_mistral_chat_route(provider, base_url) |
| 3791 | && mistral_model_has_native_reasoning(model)) |
| 3792 | { |
| 3793 | return true; |
| 3794 | } |
| 3795 | |
| 3796 | // The exact Model Studio route policy evaluates BEFORE any generic |
| 3797 | // model-name heuristic. Only models Alibaba documents as accepting |
| 3798 | // `preserve_thinking` replay historical `reasoning_content`, plus the |
| 3799 | // concrete DeepSeek V4 family ids whose own API contract requires the |
| 3800 | // reasoning field on tool turns. A model named `foo-thinking` or |
| 3801 | // `foo-reasoner` proves nothing about DashScope's request dialect and |
| 3802 | // must not gain replay here — replaying stale Thinking blocks feeds the |
| 3803 | // model its own past reasoning and re-triggers it every turn (observed |
| 3804 | // as a repeated handoff loop with the always-thinking qwen3.8 family). |
| 3805 | // Pi does not replay those either. |
| 3806 | if is_exact_modelstudio_chat_route(provider, base_url) { |
| 3807 | if modelstudio_model_supports_preserve_thinking(model) { |
| 3808 | // Thinking-only preserve models (kimi-k2.7-code) are |
| 3809 | // always-thinking and replay even with a stale `off`; hybrid |
| 3810 | // preserve models defer to the effort gate like every other |
| 3811 | // hybrid. |
| 3812 | if is_exact_modelstudio_thinking_only_route(provider, base_url, model) |
| 3813 | || !modelstudio_effort_disables_thinking(effort) |
| 3814 | { |
| 3815 | return true; |
| 3816 | } |
| 3817 | return false; |
| 3818 | } |
| 3819 | let lower = model.trim().to_ascii_lowercase(); |
| 3820 | return lower.contains("deepseek-v4") |
| 3821 | || lower.starts_with("deepseek-chat") |
| 3822 | || lower.starts_with("deepseek-reasoner"); |
| 3823 | } |
| 3824 | |
| 3825 | if effort |
| 3826 | .map(|value| { |
| 3827 | matches!( |
| 3828 | value.trim().to_ascii_lowercase().as_str(), |
| 3829 | "off" | "disabled" | "none" | "false" |
| 3830 | ) |
| 3831 | }) |
| 3832 | .unwrap_or(false) |
| 3833 | { |
| 3834 | return false; |
| 3835 | } |
| 3836 | |
| 3837 | if requires_reasoning_content(model) { |
| 3838 | return true; |
| 3839 | } |
| 3840 | |
| 3841 | // Xiaomi MiMo's API requires the assistant `reasoning_content` back on |
| 3842 | // tool-call turns (omitting it is a 400), for every MiMo chat model, not |
| 3843 | // only the ids the offline catalog marks as reasoning (#6501). A turn |
| 3844 | // that produced no reasoning replays nothing. |
| 3845 | if provider == ProviderKind::XiaomiMimo { |
| 3846 | return true; |
| 3847 | } |
| 3848 | |
| 3849 | if is_exact_mistral_chat_route(provider, base_url) |
| 3850 | && mistral_model_has_adjustable_reasoning(model) |
| 3851 | { |
| 3852 | return true; |
| 3853 | } |
| 3854 | |
| 3855 | if !provider_accepts_reasoning_content(provider) { |
| 3856 | // Generic non-DeepSeek model on a provider that rejects the field: |
| 3857 | // keep stripping it (preserves the #1542 fix). But a known DeepSeek |
| 3858 | // reasoning model pointed at a DeepSeek-compatible endpoint via the |
| 3859 | // generic `openai` provider still requires reasoning_content replay, |
| 3860 | // or the thinking-mode API returns 400 (#1739 / #1694). |
| 3861 | return false; |
| 3862 | } |
| 3863 | |
| 3864 | model_supports_reasoning(model) |
| 3865 | } |
| 3866 | |
| 3867 | /// Test shorthand: does this route surface `reasoning_content` / |
| 3868 | /// `reasoning` / `reasoning_details` deltas as Thinking by default? |
| 3869 | #[cfg(test)] |
| 3870 | fn is_reasoning_model_for_stream(provider: ProviderKind, model: &str) -> bool { |
| 3871 | reasoning_stream_style_for_stream(provider, model, None) == ReasoningStreamStyle::SeparateField |
| 3872 | } |
| 3873 | |
| 3874 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 3875 | pub(super) enum ReasoningStreamStyle { |
| 3876 | SeparateField, |
| 3877 | InlineTags, |
| 3878 | MistralBlocks, |
| 3879 | None, |
| 3880 | } |
| 3881 | |
| 3882 | #[cfg(test)] |
| 3883 | fn reasoning_stream_style_for_stream( |
| 3884 | provider: ProviderKind, |
| 3885 | model: &str, |
| 3886 | configured: Option<&str>, |
| 3887 | ) -> ReasoningStreamStyle { |
| 3888 | reasoning_stream_style_for_route(provider, "", model, configured) |
| 3889 | } |
| 3890 | |
| 3891 | /// Choose stream decoding semantics for a fully resolved provider route. |
| 3892 | fn reasoning_stream_style_for_route( |
| 3893 | provider: ProviderKind, |
| 3894 | base_url: &str, |
| 3895 | model: &str, |
| 3896 | configured: Option<&str>, |
| 3897 | ) -> ReasoningStreamStyle { |
| 3898 | if is_exact_mistral_chat_route(provider, base_url) && mistral_model_supports_reasoning(model) { |
| 3899 | return ReasoningStreamStyle::MistralBlocks; |
| 3900 | } |
| 3901 | if let Some(configured) = configured { |
| 3902 | if let Some(style) = parse_reasoning_stream_style(configured) { |
| 3903 | return style; |
| 3904 | } |
| 3905 | logging::warn(format!( |
| 3906 | "Ignoring unrecognized reasoning_stream_style `{configured}`; expected separate_field, inline_tags, or none" |
| 3907 | )); |
| 3908 | } |
| 3909 | // #6501: the dedicated reasoning fields are reasoning on every |
| 3910 | // Chat Completions route that sends them (DeepSeek, xAI, Xiaomi MiMo, |
| 3911 | // Kimi, GLM, MiniMax, DashScope, vLLM/SGLang reasoning parsers, OpenRouter, |
| 3912 | // Ollama, ...), and the non-streaming parser already treats them that way |
| 3913 | // unconditionally. Gating the stream on a provider allowlist AND a |
| 3914 | // per-model catalog row meant every unlisted provider (xAI, StepFun, |
| 3915 | // Together, Ollama, the Codewhale gateway, ...) and every model id newer |
| 3916 | // than the offline catalog (grok-4.7, a fresh MiMo id) rendered its |
| 3917 | // reasoning as answer prose. Surfacing a field that never arrives costs |
| 3918 | // nothing; a gateway that really puts its answer in `reasoning_content` |
| 3919 | // opts out with `reasoning_stream_style = "none"`. Replay of reasoning in |
| 3920 | // request history stays separately gated by |
| 3921 | // `should_replay_reasoning_content_for_provider_on_route`. |
| 3922 | ReasoningStreamStyle::SeparateField |
| 3923 | } |
| 3924 | |
| 3925 | fn parse_reasoning_stream_style(value: &str) -> Option<ReasoningStreamStyle> { |
| 3926 | match value.trim().to_ascii_lowercase().replace('-', "_").as_str() { |
| 3927 | "separate_field" | "separate" | "field" => Some(ReasoningStreamStyle::SeparateField), |
| 3928 | "inline_tags" | "inline" | "think_tags" | "thinking_tags" => { |
| 3929 | Some(ReasoningStreamStyle::InlineTags) |
| 3930 | } |
| 3931 | "none" | "text" | "disabled" | "off" => Some(ReasoningStreamStyle::None), |
| 3932 | _ => None, |
| 3933 | } |
| 3934 | } |
| 3935 | |
| 3936 | /// Providers whose chat-completions API both returns and accepts a dedicated |
| 3937 | /// `reasoning_content` field on assistant messages. |
| 3938 | /// |
| 3939 | /// Arcee is intentionally included. Trinity-Large-Thinking natively emits |
| 3940 | /// `<think>...</think>` traces, but Arcee's hosted API serves it through vLLM |
| 3941 | /// with `--reasoning-parser deepseek_r1`, which parses those blocks into a |
| 3942 | /// `reasoning_content` field (verified live against `api.arcee.ai`: thinking |
| 3943 | /// streams as `delta.reasoning_content`, the answer as `delta.content`, with no |
| 3944 | /// `<think>` tags on the wire). Arcee's docs require replaying `reasoning_content` |
| 3945 | /// on assistant tool-call turns; dropping it makes the model emit tool calls as |
| 3946 | /// raw XML inside its thinking ("xml_in_reasoning" pitfall). Do not remove Arcee |
| 3947 | /// here without new live evidence — see docs.arcee.ai/capabilities/reasoning-traces. |
| 3948 | fn provider_accepts_reasoning_content(provider: ProviderKind) -> bool { |
| 3949 | matches!( |
| 3950 | provider, |
| 3951 | ProviderKind::Deepseek |
| 3952 | | ProviderKind::NvidiaNim |
| 3953 | | ProviderKind::Openrouter |
| 3954 | | ProviderKind::XiaomiMimo |
| 3955 | | ProviderKind::Novita |
| 3956 | | ProviderKind::Fireworks |
| 3957 | | ProviderKind::Siliconflow |
| 3958 | | ProviderKind::SiliconflowCN |
| 3959 | | ProviderKind::Volcengine |
| 3960 | | ProviderKind::Arcee |
| 3961 | | ProviderKind::Minimax |
| 3962 | | ProviderKind::Sglang |
| 3963 | | ProviderKind::Zai |
| 3964 | | ProviderKind::Moonshot // #3016: Kimi thinking traces use reasoning_content |
| 3965 | ) |
| 3966 | } |
| 3967 | |
| 3968 | fn has_deepseek_r_series_marker(model_lower: &str) -> bool { |
| 3969 | const PREFIX: &str = "deepseek-r"; |
| 3970 | model_lower.match_indices(PREFIX).any(|(idx, _)| { |
| 3971 | model_lower[idx + PREFIX.len()..] |
| 3972 | .chars() |
| 3973 | .next() |
| 3974 | .is_some_and(|ch| ch.is_ascii_digit()) |
| 3975 | }) |
| 3976 | } |
| 3977 | |
| 3978 | /// Transport-only reasoning replay placeholder. DeepSeek-family chat wires |
| 3979 | /// reject assistant tool-call messages with an empty `reasoning_content`, so |
| 3980 | /// the request serializer substitutes this string for replay only. Providers |
| 3981 | /// that mirror assistant history (GLM-5.x) stream the substituted field back |
| 3982 | /// as a live reasoning delta; ingest must drop that exact echo so a wire-only |
| 3983 | /// placeholder never becomes a persisted or displayed thinking block. |
| 3984 | pub const REASONING_REPLAY_PLACEHOLDER: &str = "(reasoning omitted)"; |
| 3985 | |
| 3986 | #[must_use] |
| 3987 | pub fn is_reasoning_replay_placeholder(text: &str) -> bool { |
| 3988 | text.trim() == REASONING_REPLAY_PLACEHOLDER |
| 3989 | } |
| 3990 | |
| 3991 | fn reasoning_delta( |
| 3992 | value: &Value, |
| 3993 | choice_index: u32, |
| 3994 | reasoning_detail_buffers: &mut std::collections::HashMap<u32, String>, |
| 3995 | ) -> Option<String> { |
| 3996 | if let Some(reasoning) = value |
| 3997 | .get("reasoning_content") |
| 3998 | .or_else(|| value.get("reasoning")) |
| 3999 | .and_then(Value::as_str) |
| 4000 | { |
| 4001 | if is_reasoning_replay_placeholder(reasoning) { |
| 4002 | return None; |
| 4003 | } |
| 4004 | return Some(reasoning.to_string()); |
| 4005 | } |
| 4006 | |
| 4007 | let details = value.get("reasoning_details").and_then(Value::as_array)?; |
| 4008 | let full_text = details |
| 4009 | .iter() |
| 4010 | .filter_map(|detail| detail.get("text").and_then(Value::as_str)) |
| 4011 | .collect::<String>(); |
| 4012 | if full_text.is_empty() { |
| 4013 | return None; |
| 4014 | } |
| 4015 | |
| 4016 | let previous = reasoning_detail_buffers.entry(choice_index).or_default(); |
| 4017 | let delta = full_text |
| 4018 | .strip_prefix(previous.as_str()) |
| 4019 | .unwrap_or(&full_text) |
| 4020 | .to_string(); |
| 4021 | *previous = full_text; |
| 4022 | Some(delta) |
| 4023 | } |
| 4024 | |
| 4025 | fn reasoning_message_text(value: &Value) -> Option<String> { |
| 4026 | if let Some(reasoning) = value |
| 4027 | .get("reasoning_content") |
| 4028 | .or_else(|| value.get("reasoning")) |
| 4029 | .and_then(Value::as_str) |
| 4030 | { |
| 4031 | if is_reasoning_replay_placeholder(reasoning) { |
| 4032 | return None; |
| 4033 | } |
| 4034 | return Some(reasoning.to_string()); |
| 4035 | } |
| 4036 | value |
| 4037 | .get("reasoning_details") |
| 4038 | .and_then(Value::as_array) |
| 4039 | .map(|details| { |
| 4040 | details |
| 4041 | .iter() |
| 4042 | .filter_map(|detail| detail.get("text").and_then(Value::as_str)) |
| 4043 | .collect::<String>() |
| 4044 | }) |
| 4045 | } |
| 4046 | |
| 4047 | #[cfg(test)] |
| 4048 | pub(super) fn parse_chat_message(payload: &Value) -> Result<MessageResponse> { |
| 4049 | parse_chat_message_for_route(payload, ProviderKind::Openai, "") |
| 4050 | } |
| 4051 | |
| 4052 | fn parse_chat_message_for_route( |
| 4053 | payload: &Value, |
| 4054 | provider: ProviderKind, |
| 4055 | base_url: &str, |
| 4056 | ) -> Result<MessageResponse> { |
| 4057 | let payload = match ( |
| 4058 | payload.get("choices"), |
| 4059 | payload.get("success"), |
| 4060 | payload.get("data"), |
| 4061 | ) { |
| 4062 | (None, Some(Value::Bool(true)), Some(data)) |
| 4063 | if data.get("choices").is_some_and(Value::is_array) => |
| 4064 | { |
| 4065 | data |
| 4066 | } |
| 4067 | _ => payload, |
| 4068 | }; |
| 4069 | let id = payload |
| 4070 | .get("id") |
| 4071 | .and_then(Value::as_str) |
| 4072 | .unwrap_or("chatcmpl") |
| 4073 | .to_string(); |
| 4074 | let model = payload |
| 4075 | .get("model") |
| 4076 | .and_then(Value::as_str) |
| 4077 | .unwrap_or("unknown") |
| 4078 | .to_string(); |
| 4079 | |
| 4080 | let choices = payload |
| 4081 | .get("choices") |
| 4082 | .and_then(Value::as_array) |
| 4083 | .context("Chat API response missing choices")?; |
| 4084 | let choice = choices |
| 4085 | .first() |
| 4086 | .context("Chat API response missing first choice")?; |
| 4087 | let message = choice |
| 4088 | .get("message") |
| 4089 | .context("Chat API response missing message")?; |
| 4090 | |
| 4091 | let mut content_blocks = Vec::new(); |
| 4092 | if let Some(reasoning) = |
| 4093 | reasoning_message_text(message).filter(|reasoning| !reasoning.trim().is_empty()) |
| 4094 | { |
| 4095 | content_blocks.push(ContentBlock::Thinking { |
| 4096 | signature: None, |
| 4097 | state: None, |
| 4098 | redacted_data: None, |
| 4099 | thinking: reasoning.to_string(), |
| 4100 | }); |
| 4101 | } |
| 4102 | let (mistral_thinking, mistral_text) = if is_exact_mistral_chat_route(provider, base_url) { |
| 4103 | extract_mistral_polymorphic_content(message) |
| 4104 | } else { |
| 4105 | (None, None) |
| 4106 | }; |
| 4107 | if let Some(thinking) = mistral_thinking.filter(|s| !s.trim().is_empty()) { |
| 4108 | content_blocks.push(ContentBlock::Thinking { |
| 4109 | signature: None, |
| 4110 | state: None, |
| 4111 | thinking, |
| 4112 | redacted_data: None, |
| 4113 | }); |
| 4114 | } |
| 4115 | if let Some(text) = mistral_text.filter(|s| !s.trim().is_empty()) { |
| 4116 | content_blocks.push(ContentBlock::Text { |
| 4117 | text, |
| 4118 | cache_control: None, |
| 4119 | }); |
| 4120 | } else if let Some(text) = message.get("content").and_then(Value::as_str) |
| 4121 | && !text.trim().is_empty() |
| 4122 | { |
| 4123 | content_blocks.push(ContentBlock::Text { |
| 4124 | text: text.to_string(), |
| 4125 | cache_control: None, |
| 4126 | }); |
| 4127 | } |
| 4128 | |
| 4129 | if let Some(tool_calls) = message.get("tool_calls").and_then(Value::as_array) { |
| 4130 | let mut assigned_ids = tool_calls |
| 4131 | .iter() |
| 4132 | .filter_map(|call| call.get("id").and_then(Value::as_str).map(str::to_owned)) |
| 4133 | .collect(); |
| 4134 | for (call_index, call) in tool_calls.iter().enumerate() { |
| 4135 | let id = call |
| 4136 | .get("id") |
| 4137 | .and_then(Value::as_str) |
| 4138 | .map(str::to_string) |
| 4139 | .unwrap_or_else(|| synthesize_chat_call_id(call_index, &mut assigned_ids)); |
| 4140 | let function = call.get("function"); |
| 4141 | let name = tool_name_or_fallback( |
| 4142 | function.and_then(|f| f.get("name")).and_then(Value::as_str), |
| 4143 | &id, |
| 4144 | "Non-streaming response", |
| 4145 | ); |
| 4146 | let arguments = function |
| 4147 | .and_then(|f| f.get("arguments")) |
| 4148 | .and_then(Value::as_str) |
| 4149 | .map(|raw| serde_json::from_str(raw).unwrap_or(Value::String(raw.to_string()))) |
| 4150 | .unwrap_or(Value::Null); |
| 4151 | let caller = call.get("caller").and_then(|v| { |
| 4152 | v.get("type") |
| 4153 | .and_then(Value::as_str) |
| 4154 | .map(|caller_type| ToolCaller { |
| 4155 | caller_type: caller_type.to_string(), |
| 4156 | tool_id: v |
| 4157 | .get("tool_id") |
| 4158 | .and_then(Value::as_str) |
| 4159 | .map(std::string::ToString::to_string), |
| 4160 | }) |
| 4161 | }); |
| 4162 | |
| 4163 | let thought_signature = call |
| 4164 | .pointer("/extra_content/google/thought_signature") |
| 4165 | .and_then(Value::as_str) |
| 4166 | .map(str::to_string); |
| 4167 | content_blocks.push(ContentBlock::ToolUse { |
| 4168 | execution_id: None, |
| 4169 | id, |
| 4170 | name: from_api_tool_name(&name), |
| 4171 | input: arguments, |
| 4172 | caller, |
| 4173 | thought_signature, |
| 4174 | }); |
| 4175 | } |
| 4176 | } |
| 4177 | |
| 4178 | if let Some(steps) = message |
| 4179 | .get("server_tool_calls") |
| 4180 | .and_then(Value::as_array) |
| 4181 | .filter(|s| !s.is_empty()) |
| 4182 | { |
| 4183 | content_blocks.push(ContentBlock::ServerToolCalls { |
| 4184 | steps: steps.clone(), |
| 4185 | }); |
| 4186 | } |
| 4187 | |
| 4188 | let usage = parse_usage(payload.get("usage")); |
| 4189 | let title = message |
| 4190 | .get("title") |
| 4191 | .or_else(|| choice.get("title")) |
| 4192 | .or_else(|| payload.get("title")) |
| 4193 | .and_then(Value::as_str) |
| 4194 | .map(str::to_string); |
| 4195 | let refusal = message |
| 4196 | .get("refusal") |
| 4197 | .and_then(Value::as_str) |
| 4198 | .filter(|s| !s.is_empty()) |
| 4199 | .map(str::to_string); |
| 4200 | |
| 4201 | Ok(MessageResponse { |
| 4202 | tool_projection_warning: None, |
| 4203 | id, |
| 4204 | r#type: "message".to_string(), |
| 4205 | role: "assistant".to_string(), |
| 4206 | content: content_blocks, |
| 4207 | model, |
| 4208 | stop_reason: choice |
| 4209 | .get("finish_reason") |
| 4210 | .and_then(Value::as_str) |
| 4211 | .map(str::to_string), |
| 4212 | stop_sequence: None, |
| 4213 | container: None, |
| 4214 | usage, |
| 4215 | title, |
| 4216 | stop_details: None, |
| 4217 | refusal, |
| 4218 | }) |
| 4219 | } |
| 4220 | |
| 4221 | #[derive(Debug, Default)] |
| 4222 | struct InlineReasoningTagState { |
| 4223 | inside_think: bool, |
| 4224 | pending: String, |
| 4225 | } |
| 4226 | |
| 4227 | #[derive(Debug, PartialEq, Eq)] |
| 4228 | enum ReasoningSegment { |
| 4229 | Text(String), |
| 4230 | Thinking(String), |
| 4231 | } |
| 4232 | |
| 4233 | fn inline_reasoning_segments( |
| 4234 | content: &str, |
| 4235 | state: &mut InlineReasoningTagState, |
| 4236 | flush: bool, |
| 4237 | ) -> Vec<ReasoningSegment> { |
| 4238 | state.pending.push_str(content); |
| 4239 | let mut segments = Vec::new(); |
| 4240 | |
| 4241 | loop { |
| 4242 | if state.pending.is_empty() { |
| 4243 | break; |
| 4244 | } |
| 4245 | |
| 4246 | if state.inside_think { |
| 4247 | if let Some(close_at) = state.pending.find("</think>") { |
| 4248 | push_reasoning_segment( |
| 4249 | &mut segments, |
| 4250 | ReasoningSegment::Thinking(state.pending[..close_at].to_string()), |
| 4251 | ); |
| 4252 | state.pending.drain(..close_at + "</think>".len()); |
| 4253 | state.inside_think = false; |
| 4254 | continue; |
| 4255 | } |
| 4256 | |
| 4257 | let hold_len = if flush { |
| 4258 | 0 |
| 4259 | } else { |
| 4260 | trailing_tag_prefix_len(&state.pending, "</think>") |
| 4261 | }; |
| 4262 | let emit_len = state.pending.len().saturating_sub(hold_len); |
| 4263 | if emit_len > 0 { |
| 4264 | push_reasoning_segment( |
| 4265 | &mut segments, |
| 4266 | ReasoningSegment::Thinking(state.pending[..emit_len].to_string()), |
| 4267 | ); |
| 4268 | state.pending.drain(..emit_len); |
| 4269 | } |
| 4270 | break; |
| 4271 | } |
| 4272 | |
| 4273 | if let Some(open_at) = state.pending.find("<think>") { |
| 4274 | push_reasoning_segment( |
| 4275 | &mut segments, |
| 4276 | ReasoningSegment::Text(state.pending[..open_at].to_string()), |
| 4277 | ); |
| 4278 | state.pending.drain(..open_at + "<think>".len()); |
| 4279 | state.inside_think = true; |
| 4280 | continue; |
| 4281 | } |
| 4282 | |
| 4283 | let hold_len = if flush { |
| 4284 | 0 |
| 4285 | } else { |
| 4286 | trailing_tag_prefix_len(&state.pending, "<think>") |
| 4287 | }; |
| 4288 | let emit_len = state.pending.len().saturating_sub(hold_len); |
| 4289 | if emit_len > 0 { |
| 4290 | push_reasoning_segment( |
| 4291 | &mut segments, |
| 4292 | ReasoningSegment::Text(state.pending[..emit_len].to_string()), |
| 4293 | ); |
| 4294 | state.pending.drain(..emit_len); |
| 4295 | } |
| 4296 | break; |
| 4297 | } |
| 4298 | |
| 4299 | segments |
| 4300 | } |
| 4301 | |
| 4302 | fn trailing_tag_prefix_len(content: &str, tag: &str) -> usize { |
| 4303 | let max_len = tag.len().min(content.len()); |
| 4304 | for len in (1..=max_len).rev() { |
| 4305 | let start = content.len() - len; |
| 4306 | if content.is_char_boundary(start) && tag.starts_with(&content[start..]) { |
| 4307 | return len; |
| 4308 | } |
| 4309 | } |
| 4310 | 0 |
| 4311 | } |
| 4312 | |
| 4313 | fn push_reasoning_segment(segments: &mut Vec<ReasoningSegment>, segment: ReasoningSegment) { |
| 4314 | match &segment { |
| 4315 | ReasoningSegment::Text(text) | ReasoningSegment::Thinking(text) if text.is_empty() => {} |
| 4316 | _ => segments.push(segment), |
| 4317 | } |
| 4318 | } |
| 4319 | |
| 4320 | fn push_text_delta( |
| 4321 | events: &mut Vec<StreamEvent>, |
| 4322 | content_index: &mut u32, |
| 4323 | text_started: &mut bool, |
| 4324 | thinking_started: &mut bool, |
| 4325 | text: String, |
| 4326 | ) { |
| 4327 | if *thinking_started { |
| 4328 | events.push(StreamEvent::ContentBlockStop { |
| 4329 | index: *content_index, |
| 4330 | }); |
| 4331 | *content_index += 1; |
| 4332 | *thinking_started = false; |
| 4333 | } |
| 4334 | if !*text_started { |
| 4335 | events.push(StreamEvent::ContentBlockStart { |
| 4336 | index: *content_index, |
| 4337 | content_block: ContentBlockStart::Text { |
| 4338 | text: String::new(), |
| 4339 | }, |
| 4340 | }); |
| 4341 | *text_started = true; |
| 4342 | } |
| 4343 | events.push(StreamEvent::ContentBlockDelta { |
| 4344 | index: *content_index, |
| 4345 | delta: Delta::TextDelta { text }, |
| 4346 | }); |
| 4347 | } |
| 4348 | |
| 4349 | fn push_thinking_delta( |
| 4350 | events: &mut Vec<StreamEvent>, |
| 4351 | content_index: &mut u32, |
| 4352 | text_started: &mut bool, |
| 4353 | thinking_started: &mut bool, |
| 4354 | thinking: String, |
| 4355 | ) { |
| 4356 | if *text_started { |
| 4357 | events.push(StreamEvent::ContentBlockStop { |
| 4358 | index: *content_index, |
| 4359 | }); |
| 4360 | *content_index += 1; |
| 4361 | *text_started = false; |
| 4362 | } |
| 4363 | if !*thinking_started { |
| 4364 | events.push(StreamEvent::ContentBlockStart { |
| 4365 | index: *content_index, |
| 4366 | content_block: ContentBlockStart::Thinking { |
| 4367 | thinking: String::new(), |
| 4368 | }, |
| 4369 | }); |
| 4370 | *thinking_started = true; |
| 4371 | } |
| 4372 | events.push(StreamEvent::ContentBlockDelta { |
| 4373 | index: *content_index, |
| 4374 | delta: Delta::ThinkingDelta { thinking }, |
| 4375 | }); |
| 4376 | } |
| 4377 | |
| 4378 | // === SSE Chunk Parser === |
| 4379 | |
| 4380 | enum SseDataFrame { |
| 4381 | Done, |
| 4382 | Events(Vec<StreamEvent>), |
| 4383 | } |
| 4384 | |
| 4385 | #[derive(Default)] |
| 4386 | pub(super) struct ChatToolStream { |
| 4387 | google: bool, |
| 4388 | calls: Vec<ChatToolSlot>, |
| 4389 | by_index: HashMap<u64, usize>, |
| 4390 | by_id: HashMap<String, usize>, |
| 4391 | previous_batch: Vec<usize>, |
| 4392 | } |
| 4393 | |
| 4394 | struct ChatToolSlot { |
| 4395 | block: u32, |
| 4396 | wire_index: Option<u64>, |
| 4397 | id: Option<String>, |
| 4398 | } |
| 4399 | |
| 4400 | impl ChatToolStream { |
| 4401 | fn for_base_url(base_url: &str) -> Self { |
| 4402 | Self { |
| 4403 | google: is_google_openai_compat_chat_route(base_url), |
| 4404 | ..Self::default() |
| 4405 | } |
| 4406 | } |
| 4407 | |
| 4408 | fn slot( |
| 4409 | &self, |
| 4410 | index: Option<u64>, |
| 4411 | id: Option<&str>, |
| 4412 | has_name: bool, |
| 4413 | position: usize, |
| 4414 | batch_len: usize, |
| 4415 | ) -> Result<Option<usize>, &'static str> { |
| 4416 | let by_index = index.and_then(|i| self.by_index.get(&i).copied()); |
| 4417 | if !self.google { |
| 4418 | if by_index |
| 4419 | .and_then(|slot| self.calls[slot].id.as_deref()) |
| 4420 | .zip(id) |
| 4421 | .is_some_and(|(previous, current)| previous != current) |
| 4422 | { |
| 4423 | return Err("Conflicting tool call identities in provider stream"); |
| 4424 | } |
| 4425 | return Ok(by_index); |
| 4426 | } |
| 4427 | let by_id = id.and_then(|id| self.by_id.get(id).copied()); |
| 4428 | if let Some(slot) = by_index.or(by_id) { |
| 4429 | let call = &self.calls[slot]; |
| 4430 | if by_index.zip(by_id).is_some_and(|(a, b)| a != b) |
| 4431 | || index.zip(call.wire_index).is_some_and(|(a, b)| a != b) |
| 4432 | || id.zip(call.id.as_deref()).is_some_and(|(a, b)| a != b) |
| 4433 | { |
| 4434 | return Err("Conflicting tool call identities in provider stream"); |
| 4435 | } |
| 4436 | return Ok(Some(slot)); |
| 4437 | } |
| 4438 | if has_name { |
| 4439 | return Ok(None); |
| 4440 | } |
| 4441 | if index.is_none() && id.is_none() && self.previous_batch.len() == batch_len { |
| 4442 | return Ok(self.previous_batch.get(position).copied()); |
| 4443 | } |
| 4444 | Err("Cannot match a tool call delta to its provider stream block") |
| 4445 | } |
| 4446 | |
| 4447 | fn record_identity(&mut self, slot: usize, index: Option<u64>, id: Option<&str>) -> bool { |
| 4448 | let call = &mut self.calls[slot]; |
| 4449 | if call.wire_index.is_none() |
| 4450 | && let Some(index) = index |
| 4451 | { |
| 4452 | self.by_index.insert(index, slot); |
| 4453 | call.wire_index = Some(index); |
| 4454 | } |
| 4455 | if call.id.is_none() |
| 4456 | && let Some(id) = id |
| 4457 | { |
| 4458 | if self.google { |
| 4459 | self.by_id.insert(id.to_owned(), slot); |
| 4460 | } |
| 4461 | call.id = Some(id.to_owned()); |
| 4462 | return true; |
| 4463 | } |
| 4464 | false |
| 4465 | } |
| 4466 | |
| 4467 | fn finish(&mut self) -> Vec<StreamEvent> { |
| 4468 | self.previous_batch.clear(); |
| 4469 | self.by_index.clear(); |
| 4470 | self.by_id.clear(); |
| 4471 | finish_chat_tool_calls(self.calls.drain(..).map(|call| (call.block, call.id))).collect() |
| 4472 | } |
| 4473 | } |
| 4474 | |
| 4475 | fn synthesize_chat_call_id(ordinal: usize, assigned: &mut HashSet<String>) -> String { |
| 4476 | let base = format!("call_missing_{ordinal}"); |
| 4477 | let mut id = base.clone(); |
| 4478 | let mut suffix = 0usize; |
| 4479 | while !assigned.insert(id.clone()) { |
| 4480 | suffix += 1; |
| 4481 | id = format!("{base}_{suffix}"); |
| 4482 | } |
| 4483 | id |
| 4484 | } |
| 4485 | |
| 4486 | fn finish_chat_tool_calls( |
| 4487 | calls: impl Iterator<Item = (u32, Option<String>)>, |
| 4488 | ) -> impl Iterator<Item = StreamEvent> { |
| 4489 | let mut calls: Vec<_> = calls.collect(); |
| 4490 | calls.sort_unstable_by_key(|(block, _)| *block); |
| 4491 | let mut assigned = calls.iter().filter_map(|(_, id)| id.clone()).collect(); |
| 4492 | calls |
| 4493 | .into_iter() |
| 4494 | .enumerate() |
| 4495 | .flat_map(move |(ordinal, (index, id))| { |
| 4496 | let pairing = id.is_none().then(|| StreamEvent::ContentBlockDelta { |
| 4497 | index, |
| 4498 | delta: Delta::ToolCallIdDelta { |
| 4499 | id: synthesize_chat_call_id(ordinal, &mut assigned), |
| 4500 | }, |
| 4501 | }); |
| 4502 | pairing |
| 4503 | .into_iter() |
| 4504 | .chain([StreamEvent::ContentBlockStop { index }]) |
| 4505 | }) |
| 4506 | } |
| 4507 | |
| 4508 | // The six `&mut` streaming-state fields plus the style flag are a deliberate, |
| 4509 | // shared parser-state set (mirrored by `parse_sse_chunk*`); bundling them into a |
| 4510 | // struct would only add reborrow noise on this hot SSE path. |
| 4511 | #[allow(clippy::too_many_arguments)] |
| 4512 | fn parse_sse_data_frame( |
| 4513 | data: &str, |
| 4514 | content_index: &mut u32, |
| 4515 | text_started: &mut bool, |
| 4516 | thinking_started: &mut bool, |
| 4517 | tool_indices: &mut ChatToolStream, |
| 4518 | reasoning_detail_buffers: &mut std::collections::HashMap<u32, String>, |
| 4519 | inline_reasoning_tags: &mut InlineReasoningTagState, |
| 4520 | reasoning_stream_style: ReasoningStreamStyle, |
| 4521 | ) -> SseDataFrame { |
| 4522 | if data.trim() == "[DONE]" { |
| 4523 | return SseDataFrame::Done; |
| 4524 | } |
| 4525 | let events = serde_json::from_str::<Value>(data).map_or_else( |
| 4526 | |_| Vec::new(), |
| 4527 | |chunk_json| { |
| 4528 | parse_sse_chunk_with_reasoning_style( |
| 4529 | &chunk_json, |
| 4530 | content_index, |
| 4531 | text_started, |
| 4532 | thinking_started, |
| 4533 | tool_indices, |
| 4534 | reasoning_detail_buffers, |
| 4535 | inline_reasoning_tags, |
| 4536 | reasoning_stream_style, |
| 4537 | ) |
| 4538 | }, |
| 4539 | ); |
| 4540 | SseDataFrame::Events(events) |
| 4541 | } |
| 4542 | |
| 4543 | /// Parse a single SSE chunk from the Chat Completions streaming API into |
| 4544 | /// our internal `StreamEvent` representation. |
| 4545 | #[cfg(test)] |
| 4546 | pub(super) fn parse_sse_chunk( |
| 4547 | chunk: &Value, |
| 4548 | content_index: &mut u32, |
| 4549 | text_started: &mut bool, |
| 4550 | thinking_started: &mut bool, |
| 4551 | tool_indices: &mut ChatToolStream, |
| 4552 | reasoning_detail_buffers: &mut std::collections::HashMap<u32, String>, |
| 4553 | is_reasoning_model: bool, |
| 4554 | ) -> Vec<StreamEvent> { |
| 4555 | let mut inline_reasoning_tags = InlineReasoningTagState::default(); |
| 4556 | let reasoning_stream_style = if is_reasoning_model { |
| 4557 | ReasoningStreamStyle::SeparateField |
| 4558 | } else { |
| 4559 | ReasoningStreamStyle::None |
| 4560 | }; |
| 4561 | parse_sse_chunk_with_reasoning_style( |
| 4562 | chunk, |
| 4563 | content_index, |
| 4564 | text_started, |
| 4565 | thinking_started, |
| 4566 | tool_indices, |
| 4567 | reasoning_detail_buffers, |
| 4568 | &mut inline_reasoning_tags, |
| 4569 | reasoning_stream_style, |
| 4570 | ) |
| 4571 | } |
| 4572 | |
| 4573 | // Same deliberate shared parser-state set as `parse_sse_data_frame`. |
| 4574 | #[allow(clippy::too_many_arguments)] |
| 4575 | fn parse_sse_chunk_with_reasoning_style( |
| 4576 | chunk: &Value, |
| 4577 | content_index: &mut u32, |
| 4578 | text_started: &mut bool, |
| 4579 | thinking_started: &mut bool, |
| 4580 | tool_indices: &mut ChatToolStream, |
| 4581 | reasoning_detail_buffers: &mut std::collections::HashMap<u32, String>, |
| 4582 | inline_reasoning_tags: &mut InlineReasoningTagState, |
| 4583 | reasoning_stream_style: ReasoningStreamStyle, |
| 4584 | ) -> Vec<StreamEvent> { |
| 4585 | let mut events = Vec::new(); |
| 4586 | |
| 4587 | // OpenAI-compatible providers surface mid-stream failures as a chunk-level |
| 4588 | // `error` object (sometimes with `type: "error"`), delivered before |
| 4589 | // `[DONE]`. Silently dropping it turned rate-limit / context-length / |
| 4590 | // server errors into a truncated turn that looked successful — the frame |
| 4591 | // is now surfaced through the same `StreamEvent::Error` contract the |
| 4592 | // Anthropic path uses (#3014, ops R3). |
| 4593 | if let Some(error) = chunk.get("error") { |
| 4594 | let error = match error { |
| 4595 | Value::Object(_) => error.clone(), |
| 4596 | Value::String(message) => serde_json::json!({ "message": message }), |
| 4597 | _ => serde_json::json!({ "message": "provider stream error" }), |
| 4598 | }; |
| 4599 | events.push(StreamEvent::Error { error }); |
| 4600 | return events; |
| 4601 | } |
| 4602 | |
| 4603 | let Some(choices) = chunk.get("choices").and_then(Value::as_array) else { |
| 4604 | // Usage-only chunk (sent at end with stream_options) |
| 4605 | let title = chunk |
| 4606 | .get("title") |
| 4607 | .and_then(Value::as_str) |
| 4608 | .map(str::to_string); |
| 4609 | if let Some(usage_val) = chunk.get("usage") { |
| 4610 | let usage = parse_usage(Some(usage_val)); |
| 4611 | events.push(StreamEvent::MessageDelta { |
| 4612 | delta: MessageDelta { |
| 4613 | stop_reason: None, |
| 4614 | stop_sequence: None, |
| 4615 | title, |
| 4616 | stop_details: None, |
| 4617 | refusal: None, |
| 4618 | }, |
| 4619 | usage: Some(usage), |
| 4620 | }); |
| 4621 | } else if title.is_some() { |
| 4622 | events.push(StreamEvent::MessageDelta { |
| 4623 | delta: MessageDelta { |
| 4624 | stop_reason: None, |
| 4625 | stop_sequence: None, |
| 4626 | title, |
| 4627 | stop_details: None, |
| 4628 | refusal: None, |
| 4629 | }, |
| 4630 | usage: None, |
| 4631 | }); |
| 4632 | } |
| 4633 | return events; |
| 4634 | }; |
| 4635 | |
| 4636 | if choices.is_empty() { |
| 4637 | let title = chunk |
| 4638 | .get("title") |
| 4639 | .and_then(Value::as_str) |
| 4640 | .map(str::to_string); |
| 4641 | if let Some(usage_val) = chunk.get("usage") { |
| 4642 | let usage = parse_usage(Some(usage_val)); |
| 4643 | events.push(StreamEvent::MessageDelta { |
| 4644 | delta: MessageDelta { |
| 4645 | stop_reason: None, |
| 4646 | stop_sequence: None, |
| 4647 | title, |
| 4648 | stop_details: None, |
| 4649 | refusal: None, |
| 4650 | }, |
| 4651 | usage: Some(usage), |
| 4652 | }); |
| 4653 | } else if title.is_some() { |
| 4654 | events.push(StreamEvent::MessageDelta { |
| 4655 | delta: MessageDelta { |
| 4656 | stop_reason: None, |
| 4657 | stop_sequence: None, |
| 4658 | title, |
| 4659 | stop_details: None, |
| 4660 | refusal: None, |
| 4661 | }, |
| 4662 | usage: None, |
| 4663 | }); |
| 4664 | } |
| 4665 | return events; |
| 4666 | } |
| 4667 | |
| 4668 | for choice in choices { |
| 4669 | let choice_index = choice.get("index").and_then(Value::as_u64).unwrap_or(0) as u32; |
| 4670 | let delta = choice.get("delta"); |
| 4671 | let finish_reason = choice |
| 4672 | .get("finish_reason") |
| 4673 | .and_then(Value::as_str) |
| 4674 | .map(str::to_string); |
| 4675 | |
| 4676 | if let Some(delta) = delta { |
| 4677 | let reasoning_text = reasoning_delta(delta, choice_index, reasoning_detail_buffers) |
| 4678 | .filter(|s| !s.is_empty()); |
| 4679 | // Mistral la Plateforme streams reasoning as a polymorphic |
| 4680 | // `delta.content` value: an array of typed {type: thinking|text} |
| 4681 | // blocks while thinking, then a plain string once the final |
| 4682 | // answer starts. Flatten thinking sub-blocks into a single |
| 4683 | // reasoning delta and treat text sub-blocks as normal content |
| 4684 | // before the shared string fallback below. |
| 4685 | let (mistral_thinking, mistral_text) = |
| 4686 | if reasoning_stream_style == ReasoningStreamStyle::MistralBlocks { |
| 4687 | extract_mistral_polymorphic_content(delta) |
| 4688 | } else { |
| 4689 | (None, None) |
| 4690 | }; |
| 4691 | if let Some(reasoning) = mistral_thinking.as_deref() { |
| 4692 | push_thinking_delta( |
| 4693 | &mut events, |
| 4694 | content_index, |
| 4695 | text_started, |
| 4696 | thinking_started, |
| 4697 | reasoning.to_string(), |
| 4698 | ); |
| 4699 | } |
| 4700 | let content_text = mistral_text.or_else(|| { |
| 4701 | delta |
| 4702 | .get("content") |
| 4703 | .and_then(Value::as_str) |
| 4704 | .filter(|s| !s.is_empty()) |
| 4705 | .map(str::to_string) |
| 4706 | }); |
| 4707 | |
| 4708 | // Handle reasoning_content / reasoning thinking deltas. |
| 4709 | if reasoning_stream_style == ReasoningStreamStyle::SeparateField |
| 4710 | && let Some(reasoning) = reasoning_text.as_deref() |
| 4711 | { |
| 4712 | push_thinking_delta( |
| 4713 | &mut events, |
| 4714 | content_index, |
| 4715 | text_started, |
| 4716 | thinking_started, |
| 4717 | reasoning.to_string(), |
| 4718 | ); |
| 4719 | } |
| 4720 | |
| 4721 | // Generic OpenAI-compatible proxies sometimes stream answer text |
| 4722 | // in `reasoning_content`. If this route is configured with no |
| 4723 | // reasoning semantics, render that field as normal text when no |
| 4724 | // `content` delta is present. |
| 4725 | match (content_text, reasoning_stream_style) { |
| 4726 | (Some(content), ReasoningStreamStyle::InlineTags) => { |
| 4727 | for segment in inline_reasoning_segments(&content, inline_reasoning_tags, false) |
| 4728 | { |
| 4729 | match segment { |
| 4730 | ReasoningSegment::Text(text) => push_text_delta( |
| 4731 | &mut events, |
| 4732 | content_index, |
| 4733 | text_started, |
| 4734 | thinking_started, |
| 4735 | text, |
| 4736 | ), |
| 4737 | ReasoningSegment::Thinking(thinking) => push_thinking_delta( |
| 4738 | &mut events, |
| 4739 | content_index, |
| 4740 | text_started, |
| 4741 | thinking_started, |
| 4742 | thinking, |
| 4743 | ), |
| 4744 | } |
| 4745 | } |
| 4746 | } |
| 4747 | (Some(content), _) => push_text_delta( |
| 4748 | &mut events, |
| 4749 | content_index, |
| 4750 | text_started, |
| 4751 | thinking_started, |
| 4752 | content, |
| 4753 | ), |
| 4754 | (None, ReasoningStreamStyle::None) => { |
| 4755 | if let Some(content) = reasoning_text { |
| 4756 | push_text_delta( |
| 4757 | &mut events, |
| 4758 | content_index, |
| 4759 | text_started, |
| 4760 | thinking_started, |
| 4761 | content, |
| 4762 | ); |
| 4763 | } |
| 4764 | } |
| 4765 | (None, _) => {} |
| 4766 | } |
| 4767 | |
| 4768 | if let Some(annotations) = delta.get("annotations").and_then(Value::as_array) { |
| 4769 | for citation in annotations { |
| 4770 | if !*text_started { |
| 4771 | if *thinking_started { |
| 4772 | events.push(StreamEvent::ContentBlockStop { |
| 4773 | index: *content_index, |
| 4774 | }); |
| 4775 | *content_index += 1; |
| 4776 | *thinking_started = false; |
| 4777 | } |
| 4778 | events.push(StreamEvent::ContentBlockStart { |
| 4779 | index: *content_index, |
| 4780 | content_block: ContentBlockStart::Text { |
| 4781 | text: String::new(), |
| 4782 | }, |
| 4783 | }); |
| 4784 | *text_started = true; |
| 4785 | } |
| 4786 | events.push(StreamEvent::ContentBlockDelta { |
| 4787 | index: *content_index, |
| 4788 | delta: Delta::CitationsDelta { |
| 4789 | citation: citation.clone(), |
| 4790 | }, |
| 4791 | }); |
| 4792 | } |
| 4793 | } |
| 4794 | |
| 4795 | if let Some(refusal) = delta |
| 4796 | .get("refusal") |
| 4797 | .and_then(Value::as_str) |
| 4798 | .filter(|s| !s.is_empty()) |
| 4799 | { |
| 4800 | events.push(StreamEvent::ContentBlockDelta { |
| 4801 | index: *content_index, |
| 4802 | delta: Delta::RefusalDelta { |
| 4803 | refusal: refusal.to_string(), |
| 4804 | }, |
| 4805 | }); |
| 4806 | } |
| 4807 | |
| 4808 | if let Some(steps) = delta |
| 4809 | .get("server_tool_calls") |
| 4810 | .and_then(Value::as_array) |
| 4811 | .filter(|s| !s.is_empty()) |
| 4812 | { |
| 4813 | if *text_started { |
| 4814 | events.push(StreamEvent::ContentBlockStop { |
| 4815 | index: *content_index, |
| 4816 | }); |
| 4817 | *content_index += 1; |
| 4818 | *text_started = false; |
| 4819 | } |
| 4820 | if *thinking_started { |
| 4821 | events.push(StreamEvent::ContentBlockStop { |
| 4822 | index: *content_index, |
| 4823 | }); |
| 4824 | *content_index += 1; |
| 4825 | *thinking_started = false; |
| 4826 | } |
| 4827 | let block_index = *content_index; |
| 4828 | *content_index += 1; |
| 4829 | events.push(StreamEvent::ContentBlockStart { |
| 4830 | index: block_index, |
| 4831 | content_block: ContentBlockStart::ServerToolCalls { |
| 4832 | steps: steps.clone(), |
| 4833 | }, |
| 4834 | }); |
| 4835 | events.push(StreamEvent::ContentBlockStop { index: block_index }); |
| 4836 | } |
| 4837 | |
| 4838 | // Handle tool calls |
| 4839 | if let Some(tool_calls) = delta |
| 4840 | .get("tool_calls") |
| 4841 | .and_then(Value::as_array) |
| 4842 | .filter(|calls| !calls.is_empty()) |
| 4843 | { |
| 4844 | let mut batch = if tool_indices.google { |
| 4845 | Vec::with_capacity(tool_calls.len()) |
| 4846 | } else { |
| 4847 | Vec::new() |
| 4848 | }; |
| 4849 | let mut batch_slots = HashSet::new(); |
| 4850 | let mut inferred_positions = 0; |
| 4851 | let mut changed_positions = false; |
| 4852 | let mut carries_call_data = false; |
| 4853 | for (tc_pos, tc) in tool_calls.iter().enumerate() { |
| 4854 | let wire_index = tc.get("index").and_then(Value::as_u64); |
| 4855 | let wire_index = if tool_indices.google { |
| 4856 | wire_index |
| 4857 | } else { |
| 4858 | Some(u64::from(wire_index.unwrap_or(0) as u32)) |
| 4859 | }; |
| 4860 | let id = tc |
| 4861 | .get("id") |
| 4862 | .and_then(Value::as_str) |
| 4863 | .filter(|id| !tool_indices.google || !id.is_empty()); |
| 4864 | let name = tc.pointer("/function/name").and_then(Value::as_str); |
| 4865 | let has_name = name.is_some_and(|name| !name.trim().is_empty()); |
| 4866 | let args = tc |
| 4867 | .pointer("/function/arguments") |
| 4868 | .and_then(Value::as_str) |
| 4869 | .filter(|args| !args.is_empty()); |
| 4870 | let slot = |
| 4871 | match tool_indices.slot(wire_index, id, has_name, tc_pos, tool_calls.len()) |
| 4872 | { |
| 4873 | Ok(slot) => slot, |
| 4874 | Err(message) => { |
| 4875 | return vec![StreamEvent::Error { |
| 4876 | error: json!({ "message": message }), |
| 4877 | }]; |
| 4878 | } |
| 4879 | }; |
| 4880 | let (slot, tool_block_index) = match slot { |
| 4881 | Some(slot) => { |
| 4882 | if tool_indices.google && !batch_slots.insert(slot) { |
| 4883 | return vec![StreamEvent::Error { |
| 4884 | error: json!({ "message": "Duplicate tool call in provider stream batch" }), |
| 4885 | }]; |
| 4886 | } |
| 4887 | let accepted_id = tool_indices.record_identity(slot, wire_index, id); |
| 4888 | let call = &tool_indices.calls[slot]; |
| 4889 | if accepted_id && let Some(id) = call.id.as_ref() { |
| 4890 | events.push(StreamEvent::ContentBlockDelta { |
| 4891 | index: call.block, |
| 4892 | delta: Delta::ToolCallIdDelta { id: id.clone() }, |
| 4893 | }); |
| 4894 | } |
| 4895 | if tool_indices.google |
| 4896 | && let Some(sig) = tc |
| 4897 | .pointer("/extra_content/google/thought_signature") |
| 4898 | .and_then(Value::as_str) |
| 4899 | .filter(|s| !s.is_empty()) |
| 4900 | { |
| 4901 | events.push(StreamEvent::ContentBlockDelta { |
| 4902 | index: call.block, |
| 4903 | delta: Delta::ThoughtSignatureDelta { |
| 4904 | thought_signature: sig.to_string(), |
| 4905 | }, |
| 4906 | }); |
| 4907 | } |
| 4908 | (slot, call.block) |
| 4909 | } |
| 4910 | None => { |
| 4911 | // Close text block if transitioning to tool use |
| 4912 | if *text_started { |
| 4913 | events.push(StreamEvent::ContentBlockStop { |
| 4914 | index: *content_index, |
| 4915 | }); |
| 4916 | *content_index += 1; |
| 4917 | *text_started = false; |
| 4918 | } |
| 4919 | if *thinking_started { |
| 4920 | events.push(StreamEvent::ContentBlockStop { |
| 4921 | index: *content_index, |
| 4922 | }); |
| 4923 | *content_index += 1; |
| 4924 | *thinking_started = false; |
| 4925 | } |
| 4926 | |
| 4927 | let block_index = *content_index; |
| 4928 | let block_id = id.unwrap_or_default().to_owned(); |
| 4929 | let name = |
| 4930 | tool_name_or_fallback(name, &block_id, "Streaming response chunk"); |
| 4931 | let caller = tc.get("caller").and_then(|v| { |
| 4932 | v.get("type").and_then(Value::as_str).map(|caller_type| { |
| 4933 | ToolCaller { |
| 4934 | caller_type: caller_type.to_string(), |
| 4935 | tool_id: v |
| 4936 | .get("tool_id") |
| 4937 | .and_then(Value::as_str) |
| 4938 | .map(std::string::ToString::to_string), |
| 4939 | } |
| 4940 | }) |
| 4941 | }); |
| 4942 | |
| 4943 | let thought_signature = tc |
| 4944 | .pointer("/extra_content/google/thought_signature") |
| 4945 | .and_then(Value::as_str) |
| 4946 | .map(str::to_string); |
| 4947 | events.push(StreamEvent::ContentBlockStart { |
| 4948 | index: block_index, |
| 4949 | content_block: ContentBlockStart::ToolUse { |
| 4950 | id: block_id, |
| 4951 | name: from_api_tool_name(&name), |
| 4952 | input: json!({}), |
| 4953 | caller, |
| 4954 | thought_signature, |
| 4955 | }, |
| 4956 | }); |
| 4957 | *content_index = (*content_index).saturating_add(1); |
| 4958 | let slot = tool_indices.calls.len(); |
| 4959 | tool_indices.calls.push(ChatToolSlot { |
| 4960 | block: block_index, |
| 4961 | wire_index: None, |
| 4962 | id: None, |
| 4963 | }); |
| 4964 | tool_indices.record_identity(slot, wire_index, id); |
| 4965 | if tool_indices.google { |
| 4966 | batch_slots.insert(slot); |
| 4967 | } |
| 4968 | (slot, block_index) |
| 4969 | } |
| 4970 | }; |
| 4971 | if tool_indices.google { |
| 4972 | inferred_positions += |
| 4973 | usize::from(wire_index.is_none() && id.is_none() && !has_name); |
| 4974 | changed_positions |= tool_indices.previous_batch.get(tc_pos) != Some(&slot); |
| 4975 | carries_call_data |= has_name || args.is_some(); |
| 4976 | batch.push(slot); |
| 4977 | } |
| 4978 | |
| 4979 | // Stream tool call arguments |
| 4980 | if let Some(args) = args { |
| 4981 | events.push(StreamEvent::ContentBlockDelta { |
| 4982 | index: tool_block_index, |
| 4983 | delta: Delta::InputJsonDelta { |
| 4984 | partial_json: args.to_string(), |
| 4985 | }, |
| 4986 | }); |
| 4987 | } |
| 4988 | } |
| 4989 | if inferred_positions > 1 || (inferred_positions == 1 && changed_positions) { |
| 4990 | return vec![StreamEvent::Error { |
| 4991 | error: json!({ "message": "Cannot infer positions in an ambiguous tool call batch" }), |
| 4992 | }]; |
| 4993 | } |
| 4994 | if carries_call_data { |
| 4995 | tool_indices.previous_batch = batch; |
| 4996 | } |
| 4997 | } |
| 4998 | } |
| 4999 | |
| 5000 | if let Some(server_tool_event) = choice.get("server_tool_event") |
| 5001 | && !server_tool_event.is_null() |
| 5002 | { |
| 5003 | if *text_started { |
| 5004 | events.push(StreamEvent::ContentBlockStop { |
| 5005 | index: *content_index, |
| 5006 | }); |
| 5007 | *content_index += 1; |
| 5008 | *text_started = false; |
| 5009 | } |
| 5010 | if *thinking_started { |
| 5011 | events.push(StreamEvent::ContentBlockStop { |
| 5012 | index: *content_index, |
| 5013 | }); |
| 5014 | *content_index += 1; |
| 5015 | *thinking_started = false; |
| 5016 | } |
| 5017 | let block_index = *content_index; |
| 5018 | *content_index += 1; |
| 5019 | events.push(StreamEvent::ContentBlockStart { |
| 5020 | index: block_index, |
| 5021 | content_block: ContentBlockStart::ServerToolCalls { |
| 5022 | steps: vec![server_tool_event.clone()], |
| 5023 | }, |
| 5024 | }); |
| 5025 | events.push(StreamEvent::ContentBlockStop { index: block_index }); |
| 5026 | } |
| 5027 | |
| 5028 | let chunk_title = delta |
| 5029 | .and_then(|d| d.get("title")) |
| 5030 | .or_else(|| choice.get("title")) |
| 5031 | .or_else(|| chunk.get("title")) |
| 5032 | .and_then(Value::as_str) |
| 5033 | .map(str::to_string); |
| 5034 | let chunk_refusal = delta |
| 5035 | .and_then(|d| d.get("refusal")) |
| 5036 | .and_then(Value::as_str) |
| 5037 | .filter(|s| !s.is_empty()) |
| 5038 | .map(str::to_string); |
| 5039 | |
| 5040 | // Handle finish reason |
| 5041 | if let Some(reason) = finish_reason { |
| 5042 | if reasoning_stream_style == ReasoningStreamStyle::InlineTags { |
| 5043 | for segment in inline_reasoning_segments("", inline_reasoning_tags, true) { |
| 5044 | match segment { |
| 5045 | ReasoningSegment::Text(text) => push_text_delta( |
| 5046 | &mut events, |
| 5047 | content_index, |
| 5048 | text_started, |
| 5049 | thinking_started, |
| 5050 | text, |
| 5051 | ), |
| 5052 | ReasoningSegment::Thinking(thinking) => push_thinking_delta( |
| 5053 | &mut events, |
| 5054 | content_index, |
| 5055 | text_started, |
| 5056 | thinking_started, |
| 5057 | thinking, |
| 5058 | ), |
| 5059 | } |
| 5060 | } |
| 5061 | } |
| 5062 | // Close any open blocks |
| 5063 | if *text_started { |
| 5064 | events.push(StreamEvent::ContentBlockStop { |
| 5065 | index: *content_index, |
| 5066 | }); |
| 5067 | *text_started = false; |
| 5068 | } |
| 5069 | if *thinking_started { |
| 5070 | events.push(StreamEvent::ContentBlockStop { |
| 5071 | index: *content_index, |
| 5072 | }); |
| 5073 | *thinking_started = false; |
| 5074 | } |
| 5075 | // Close tool blocks |
| 5076 | events.extend(tool_indices.finish()); |
| 5077 | |
| 5078 | // Emit usage from the chunk if available |
| 5079 | let chunk_usage = chunk.get("usage").map(|u| parse_usage(Some(u))); |
| 5080 | events.push(StreamEvent::MessageDelta { |
| 5081 | delta: MessageDelta { |
| 5082 | stop_reason: Some(reason), |
| 5083 | stop_sequence: None, |
| 5084 | title: chunk_title, |
| 5085 | stop_details: None, |
| 5086 | refusal: chunk_refusal, |
| 5087 | }, |
| 5088 | usage: chunk_usage, |
| 5089 | }); |
| 5090 | } else if chunk_title.is_some() { |
| 5091 | events.push(StreamEvent::MessageDelta { |
| 5092 | delta: MessageDelta { |
| 5093 | stop_reason: None, |
| 5094 | stop_sequence: None, |
| 5095 | title: chunk_title, |
| 5096 | stop_details: None, |
| 5097 | refusal: None, |
| 5098 | }, |
| 5099 | usage: None, |
| 5100 | }); |
| 5101 | } |
| 5102 | } |
| 5103 | |
| 5104 | events |
| 5105 | } |
| 5106 | |
| 5107 | fn tool_name_or_fallback(name: Option<&str>, id: &str, source: &str) -> String { |
| 5108 | let trimmed = name.unwrap_or("").trim(); |
| 5109 | if trimmed.is_empty() { |
| 5110 | logging::warn(format!( |
| 5111 | "{source} returned an empty tool name for call {id}; using unknown_tool" |
| 5112 | )); |
| 5113 | "unknown_tool".to_string() |
| 5114 | } else { |
| 5115 | trimmed.to_string() |
| 5116 | } |
| 5117 | } |
| 5118 | |
| 5119 | // === #103 Phase 1: stream-decode diagnostics =================================== |
| 5120 | |
| 5121 | #[cfg(test)] |
| 5122 | mod stream_diagnostics_tests { |
| 5123 | use super::*; |
| 5124 | use reqwest::header::{HeaderMap, HeaderValue}; |
| 5125 | |
| 5126 | #[test] |
| 5127 | fn stream_idle_timeout_reports_progress_and_timing() { |
| 5128 | let message = super::super::stream_entry::idle_timeout_message( |
| 5129 | Duration::from_secs(240), |
| 5130 | 8192, |
| 5131 | Duration::from_millis(73_500), |
| 5132 | Duration::from_millis(41_250), |
| 5133 | ); |
| 5134 | |
| 5135 | assert_eq!( |
| 5136 | message, |
| 5137 | "SSE stream idle timeout after 240s — no data received \ |
| 5138 | (bytes_received=8192, stream_age_ms=73500, ms_since_last_chunk=41250)" |
| 5139 | ); |
| 5140 | } |
| 5141 | |
| 5142 | #[test] |
| 5143 | fn chat_completions_error_frames_surface_as_stream_events() { |
| 5144 | let mut content_index = 0u32; |
| 5145 | let mut text_started = false; |
| 5146 | let mut thinking_started = false; |
| 5147 | let mut tool_indices = ChatToolStream::default(); |
| 5148 | let mut reasoning_buffers = std::collections::HashMap::new(); |
| 5149 | for chunk in [ |
| 5150 | json!({ "error": { "message": "rate limit exceeded", "type": "rate_limit_error" } }), |
| 5151 | json!({ "type": "error", "error": { "message": "context length exceeded" } }), |
| 5152 | json!({ "error": "server error" }), |
| 5153 | ] { |
| 5154 | let events = parse_sse_chunk( |
| 5155 | &chunk, |
| 5156 | &mut content_index, |
| 5157 | &mut text_started, |
| 5158 | &mut thinking_started, |
| 5159 | &mut tool_indices, |
| 5160 | &mut reasoning_buffers, |
| 5161 | false, |
| 5162 | ); |
| 5163 | assert_eq!( |
| 5164 | events.len(), |
| 5165 | 1, |
| 5166 | "a chunk-level error frame must not be swallowed ({chunk})" |
| 5167 | ); |
| 5168 | match &events[0] { |
| 5169 | StreamEvent::Error { error } => assert!( |
| 5170 | !error.is_null() |
| 5171 | && (error.get("message").and_then(Value::as_str).is_some() |
| 5172 | || error.is_string()), |
| 5173 | "the provider error message must survive parsing: {error}" |
| 5174 | ), |
| 5175 | other => panic!("expected StreamEvent::Error, got {other:?}"), |
| 5176 | } |
| 5177 | } |
| 5178 | // A normal content chunk still parses as a delta after the error path. |
| 5179 | let deltas = parse_sse_chunk( |
| 5180 | &json!({"choices": [{"index": 0, "delta": {"content": "ok"}}]}), |
| 5181 | &mut content_index, |
| 5182 | &mut text_started, |
| 5183 | &mut thinking_started, |
| 5184 | &mut tool_indices, |
| 5185 | &mut reasoning_buffers, |
| 5186 | false, |
| 5187 | ); |
| 5188 | assert!( |
| 5189 | deltas.iter().any(|event| { |
| 5190 | matches!( |
| 5191 | event, |
| 5192 | StreamEvent::ContentBlockDelta { |
| 5193 | delta: Delta::TextDelta { text }, .. |
| 5194 | } if text == "ok" |
| 5195 | ) |
| 5196 | }), |
| 5197 | "content deltas still parse: {deltas:?}" |
| 5198 | ); |
| 5199 | } |
| 5200 | |
| 5201 | #[test] |
| 5202 | fn deepseek_thinking_sends_only_none_tool_choice() { |
| 5203 | let required = json!("required"); |
| 5204 | let named = json!({ |
| 5205 | "type": "function", |
| 5206 | "function": { "name": "read_file" } |
| 5207 | }); |
| 5208 | for effort in [Some("high"), Some("max"), Some("medium"), Some("")] { |
| 5209 | assert!( |
| 5210 | !should_send_tool_choice_for_chat(ProviderKind::Deepseek, effort, &required), |
| 5211 | "DeepSeek thinking rejects required tool_choice for {effort:?}" |
| 5212 | ); |
| 5213 | assert!( |
| 5214 | !should_send_tool_choice_for_chat(ProviderKind::Deepseek, effort, &named), |
| 5215 | "DeepSeek thinking rejects named tool_choice for {effort:?}" |
| 5216 | ); |
| 5217 | assert!( |
| 5218 | should_send_tool_choice_for_chat(ProviderKind::Deepseek, effort, &json!("none")), |
| 5219 | "DeepSeek thinking accepts tool_choice none for {effort:?}" |
| 5220 | ); |
| 5221 | } |
| 5222 | |
| 5223 | for effort in [ |
| 5224 | None, |
| 5225 | Some("off"), |
| 5226 | Some("disabled"), |
| 5227 | Some("none"), |
| 5228 | Some("false"), |
| 5229 | ] { |
| 5230 | assert!(should_send_tool_choice_for_chat( |
| 5231 | ProviderKind::Deepseek, |
| 5232 | effort, |
| 5233 | &required |
| 5234 | )); |
| 5235 | } |
| 5236 | assert!(should_send_tool_choice_for_chat( |
| 5237 | ProviderKind::Openrouter, |
| 5238 | Some("high"), |
| 5239 | &required |
| 5240 | )); |
| 5241 | } |
| 5242 | |
| 5243 | #[test] |
| 5244 | fn format_stream_headers_renders_all_fields_when_present() { |
| 5245 | let mut headers = HeaderMap::new(); |
| 5246 | headers.insert("content-encoding", HeaderValue::from_static("gzip")); |
| 5247 | headers.insert("transfer-encoding", HeaderValue::from_static("chunked")); |
| 5248 | headers.insert("connection", HeaderValue::from_static("keep-alive")); |
| 5249 | headers.insert("server", HeaderValue::from_static("openresty/1.25.3.1")); |
| 5250 | |
| 5251 | let rendered = format_stream_headers(&headers); |
| 5252 | // Order is fixed by FIELDS in the helper; assert each field appears. |
| 5253 | assert!( |
| 5254 | rendered.contains("content-encoding=gzip"), |
| 5255 | "got: {rendered}" |
| 5256 | ); |
| 5257 | assert!( |
| 5258 | rendered.contains("transfer-encoding=chunked"), |
| 5259 | "got: {rendered}" |
| 5260 | ); |
| 5261 | assert!( |
| 5262 | rendered.contains("connection=keep-alive"), |
| 5263 | "got: {rendered}" |
| 5264 | ); |
| 5265 | assert!( |
| 5266 | rendered.contains("server=openresty/1.25.3.1"), |
| 5267 | "got: {rendered}" |
| 5268 | ); |
| 5269 | } |
| 5270 | |
| 5271 | #[test] |
| 5272 | fn format_stream_headers_marks_missing_fields_as_absent() { |
| 5273 | // DeepSeek frequently omits content-encoding when not compressing. |
| 5274 | // The diagnostic must still produce a parseable line so log scrapers |
| 5275 | // don't lose the slot. |
| 5276 | let headers = HeaderMap::new(); |
| 5277 | let rendered = format_stream_headers(&headers); |
| 5278 | assert!( |
| 5279 | rendered.contains("content-encoding=(absent)"), |
| 5280 | "missing field must be explicitly marked; got: {rendered}" |
| 5281 | ); |
| 5282 | assert!( |
| 5283 | rendered.contains("transfer-encoding=(absent)"), |
| 5284 | "missing field must be explicitly marked; got: {rendered}" |
| 5285 | ); |
| 5286 | } |
| 5287 | |
| 5288 | #[test] |
| 5289 | fn format_stream_headers_handles_non_ascii_value_gracefully() { |
| 5290 | // If a header value isn't UTF-8, `.to_str()` fails — we must not panic |
| 5291 | // and should still produce a parseable line. |
| 5292 | let mut headers = HeaderMap::new(); |
| 5293 | // 0xFF is a valid byte but invalid UTF-8 start byte. |
| 5294 | headers.insert( |
| 5295 | "server", |
| 5296 | HeaderValue::from_bytes(b"\xff\xfemystery").expect("header value"), |
| 5297 | ); |
| 5298 | let rendered = format_stream_headers(&headers); |
| 5299 | assert!( |
| 5300 | rendered.contains("server=(absent)"), |
| 5301 | "non-UTF8 header values fall back to (absent); got: {rendered}" |
| 5302 | ); |
| 5303 | } |
| 5304 | } |
| 5305 | |
| 5306 | #[cfg(test)] |
| 5307 | mod arcee_waf_message_encoding_tests { |
| 5308 | use super::build_chat_messages_for_request_and_provider; |
| 5309 | use codewhale_config::ProviderKind; |
| 5310 | use codewhale_models::{MessageRequest, SystemPrompt}; |
| 5311 | use serde_json::Value; |
| 5312 | |
| 5313 | fn request_with_system(system: &str) -> MessageRequest { |
| 5314 | MessageRequest { |
| 5315 | model: "trinity-large-thinking".to_string(), |
| 5316 | messages: Vec::new(), |
| 5317 | max_tokens: 16, |
| 5318 | system: Some(SystemPrompt::Text(system.to_string())), |
| 5319 | tools: None, |
| 5320 | tool_choice: None, |
| 5321 | metadata: None, |
| 5322 | thinking: None, |
| 5323 | reasoning_effort: None, |
| 5324 | stream: None, |
| 5325 | temperature: None, |
| 5326 | top_p: None, |
| 5327 | safety_check: None, |
| 5328 | title: None, |
| 5329 | } |
| 5330 | } |
| 5331 | |
| 5332 | fn decoded_content(content: &Value) -> String { |
| 5333 | if let Some(text) = content.as_str() { |
| 5334 | return text.to_string(); |
| 5335 | } |
| 5336 | content |
| 5337 | .as_array() |
| 5338 | .expect("content parts") |
| 5339 | .iter() |
| 5340 | .map(|part| part.get("text").and_then(Value::as_str).expect("text part")) |
| 5341 | .collect() |
| 5342 | } |
| 5343 | |
| 5344 | #[test] |
| 5345 | fn arcee_splits_waf_trigger_without_changing_decoded_system_prompt() { |
| 5346 | let system = "Run calculations with `python -c 'print(1)'` when a tool is available."; |
| 5347 | let request = request_with_system(system); |
| 5348 | |
| 5349 | let messages = build_chat_messages_for_request_and_provider(&request, ProviderKind::Arcee); |
| 5350 | let content = &messages[0]["content"]; |
| 5351 | |
| 5352 | assert!( |
| 5353 | content.is_array(), |
| 5354 | "Arcee system content with a WAF trigger should be encoded as text parts" |
| 5355 | ); |
| 5356 | assert_eq!(decoded_content(content), system); |
| 5357 | let serialized = serde_json::to_string(&messages).expect("serialize messages"); |
| 5358 | assert!( |
| 5359 | !serialized.contains("python -c"), |
| 5360 | "wire JSON should not contain the Cloudflare trigger contiguously: {serialized}" |
| 5361 | ); |
| 5362 | } |
| 5363 | |
| 5364 | #[test] |
| 5365 | fn non_arcee_providers_keep_system_prompt_as_string() { |
| 5366 | let system = "Run calculations with `python -c 'print(1)'` when a tool is available."; |
| 5367 | let request = request_with_system(system); |
| 5368 | |
| 5369 | let messages = build_chat_messages_for_request_and_provider(&request, ProviderKind::Openai); |
| 5370 | |
| 5371 | assert_eq!(messages[0]["content"].as_str(), Some(system)); |
| 5372 | } |
| 5373 | |
| 5374 | #[test] |
| 5375 | fn arcee_keeps_non_triggering_system_prompt_as_string() { |
| 5376 | let system = "Use read-only tools to inspect files before reporting results."; |
| 5377 | let request = request_with_system(system); |
| 5378 | |
| 5379 | let messages = build_chat_messages_for_request_and_provider(&request, ProviderKind::Arcee); |
| 5380 | |
| 5381 | assert_eq!(messages[0]["content"].as_str(), Some(system)); |
| 5382 | } |
| 5383 | } |
| 5384 | |
| 5385 | #[cfg(test)] |
| 5386 | mod minimax_reasoning_replay_tests { |
| 5387 | use super::{ |
| 5388 | build_chat_messages_for_request_and_provider, |
| 5389 | build_chat_messages_for_request_and_provider_and_route, |
| 5390 | }; |
| 5391 | use codewhale_config::ProviderKind; |
| 5392 | use codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL; |
| 5393 | use codewhale_config::descriptors::defaults::{ |
| 5394 | DEFAULT_KIMI_CODE_BASE_URL, DEFAULT_MINIMAX_MODEL, DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL, |
| 5395 | DEFAULT_MOONSHOT_BASE_URL, |
| 5396 | }; |
| 5397 | use codewhale_models::Role; |
| 5398 | use codewhale_models::{ContentBlock, Message, MessageRequest}; |
| 5399 | |
| 5400 | fn request_with_assistant_thinking() -> MessageRequest { |
| 5401 | MessageRequest { |
| 5402 | model: DEFAULT_MINIMAX_MODEL.to_string(), |
| 5403 | messages: vec![Message { |
| 5404 | role: Role::Assistant, |
| 5405 | content: vec![ |
| 5406 | ContentBlock::Thinking { |
| 5407 | thinking: "Inspect tool state".to_string(), |
| 5408 | signature: None, |
| 5409 | state: None, |
| 5410 | redacted_data: None, |
| 5411 | }, |
| 5412 | ContentBlock::Text { |
| 5413 | text: "Done.".to_string(), |
| 5414 | cache_control: None, |
| 5415 | }, |
| 5416 | ], |
| 5417 | }], |
| 5418 | max_tokens: 16, |
| 5419 | system: None, |
| 5420 | tools: None, |
| 5421 | tool_choice: None, |
| 5422 | metadata: None, |
| 5423 | thinking: None, |
| 5424 | reasoning_effort: None, |
| 5425 | stream: None, |
| 5426 | temperature: None, |
| 5427 | top_p: None, |
| 5428 | safety_check: None, |
| 5429 | title: None, |
| 5430 | } |
| 5431 | } |
| 5432 | |
| 5433 | #[test] |
| 5434 | fn minimax_history_replays_thinking_as_reasoning_details() { |
| 5435 | let request = request_with_assistant_thinking(); |
| 5436 | |
| 5437 | let messages = |
| 5438 | build_chat_messages_for_request_and_provider(&request, ProviderKind::Minimax); |
| 5439 | let assistant = &messages[0]; |
| 5440 | |
| 5441 | assert_eq!( |
| 5442 | assistant |
| 5443 | .get("reasoning_content") |
| 5444 | .and_then(|value| value.as_str()), |
| 5445 | Some("Inspect tool state") |
| 5446 | ); |
| 5447 | assert_eq!( |
| 5448 | assistant |
| 5449 | .pointer("/reasoning_details/0/type") |
| 5450 | .and_then(|value| value.as_str()), |
| 5451 | Some("text") |
| 5452 | ); |
| 5453 | assert_eq!( |
| 5454 | assistant |
| 5455 | .pointer("/reasoning_details/0/text") |
| 5456 | .and_then(|value| value.as_str()), |
| 5457 | Some("Inspect tool state") |
| 5458 | ); |
| 5459 | } |
| 5460 | |
| 5461 | #[test] |
| 5462 | fn kimi_code_k3_replays_thinking_only_on_the_exact_membership_route() { |
| 5463 | let mut request = request_with_assistant_thinking(); |
| 5464 | request.model = KIMI_CODE_K3_MODEL.to_string(); |
| 5465 | |
| 5466 | let exact = build_chat_messages_for_request_and_provider_and_route( |
| 5467 | &request, |
| 5468 | ProviderKind::Moonshot, |
| 5469 | DEFAULT_KIMI_CODE_BASE_URL, |
| 5470 | ); |
| 5471 | assert_eq!( |
| 5472 | exact[0] |
| 5473 | .get("reasoning_content") |
| 5474 | .and_then(serde_json::Value::as_str), |
| 5475 | Some("Inspect tool state") |
| 5476 | ); |
| 5477 | |
| 5478 | let neighbor = build_chat_messages_for_request_and_provider_and_route( |
| 5479 | &request, |
| 5480 | ProviderKind::Moonshot, |
| 5481 | DEFAULT_MOONSHOT_BASE_URL, |
| 5482 | ); |
| 5483 | assert!( |
| 5484 | neighbor[0].get("reasoning_content").is_none(), |
| 5485 | "a generic Moonshot k3 identifier must not inherit Kimi Code replay" |
| 5486 | ); |
| 5487 | } |
| 5488 | |
| 5489 | #[test] |
| 5490 | fn modelstudio_qwen38_wire_body_replays_no_historical_reasoning_across_tool_loop() { |
| 5491 | // One user handoff, one assistant Thinking + Text + ToolUse turn, and |
| 5492 | // its matching ToolResult. On the exact Model Studio route the |
| 5493 | // always-thinking qwen3.8 family must not receive historical |
| 5494 | // `reasoning_content`, while the handoff occurs exactly once and the |
| 5495 | // tool call id, arguments, and result stay intact. |
| 5496 | let mut request = request_with_assistant_thinking(); |
| 5497 | request.model = "qwen3.8-max".to_string(); |
| 5498 | request.messages = vec![ |
| 5499 | Message { |
| 5500 | role: Role::User, |
| 5501 | content: vec![ContentBlock::Text { |
| 5502 | text: "HANDOFF-SENTINEL: fix the widget.".to_string(), |
| 5503 | cache_control: None, |
| 5504 | }], |
| 5505 | }, |
| 5506 | Message { |
| 5507 | role: Role::Assistant, |
| 5508 | content: vec![ |
| 5509 | ContentBlock::Thinking { |
| 5510 | thinking: "stale thinking from the prior turn".to_string(), |
| 5511 | signature: None, |
| 5512 | state: None, |
| 5513 | redacted_data: None, |
| 5514 | }, |
| 5515 | ContentBlock::Text { |
| 5516 | text: "I'll read the widget first.".to_string(), |
| 5517 | cache_control: None, |
| 5518 | }, |
| 5519 | ContentBlock::ToolUse { |
| 5520 | execution_id: None, |
| 5521 | id: "call_qwen38_001".to_string(), |
| 5522 | name: "read".to_string(), |
| 5523 | input: serde_json::json!({ "path": "widget.rs" }), |
| 5524 | caller: None, |
| 5525 | thought_signature: None, |
| 5526 | }, |
| 5527 | ], |
| 5528 | }, |
| 5529 | Message { |
| 5530 | role: Role::User, |
| 5531 | content: vec![ContentBlock::ToolResult { |
| 5532 | execution_id: None, |
| 5533 | tool_use_id: "call_qwen38_001".to_string(), |
| 5534 | content: "widget.rs: struct Widget { .. }".to_string(), |
| 5535 | is_error: None, |
| 5536 | content_blocks: None, |
| 5537 | }], |
| 5538 | }, |
| 5539 | ]; |
| 5540 | |
| 5541 | let messages = build_chat_messages_for_request_and_provider_and_route( |
| 5542 | &request, |
| 5543 | ProviderKind::ModelstudioTokenPlan, |
| 5544 | DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL, |
| 5545 | ); |
| 5546 | |
| 5547 | // The handoff occurs exactly once, as a plain user text message. |
| 5548 | let handoff_carriers: Vec<&serde_json::Value> = messages |
| 5549 | .iter() |
| 5550 | .filter(|message| { |
| 5551 | message.get("role").and_then(serde_json::Value::as_str) == Some("user") |
| 5552 | && message |
| 5553 | .get("content") |
| 5554 | .and_then(serde_json::Value::as_str) |
| 5555 | .is_some_and(|content| content.contains("HANDOFF-SENTINEL")) |
| 5556 | }) |
| 5557 | .collect(); |
| 5558 | assert_eq!( |
| 5559 | handoff_carriers.len(), |
| 5560 | 1, |
| 5561 | "the handoff must appear in exactly one user message: {messages:?}" |
| 5562 | ); |
| 5563 | |
| 5564 | // The assistant turn keeps its text and tool call, but no historical |
| 5565 | // reasoning_content for qwen3.8. |
| 5566 | let assistant = messages |
| 5567 | .iter() |
| 5568 | .find(|message| { |
| 5569 | message.get("role").and_then(serde_json::Value::as_str) == Some("assistant") |
| 5570 | }) |
| 5571 | .expect("assistant message"); |
| 5572 | assert_eq!( |
| 5573 | assistant.get("content").and_then(serde_json::Value::as_str), |
| 5574 | Some("I'll read the widget first.") |
| 5575 | ); |
| 5576 | assert!( |
| 5577 | assistant.get("reasoning_content").is_none(), |
| 5578 | "qwen3.8 must not receive historical reasoning_content: {assistant:?}" |
| 5579 | ); |
| 5580 | let tool_calls = assistant |
| 5581 | .get("tool_calls") |
| 5582 | .and_then(serde_json::Value::as_array) |
| 5583 | .expect("tool_calls array"); |
| 5584 | assert_eq!(tool_calls.len(), 1); |
| 5585 | assert_eq!(tool_calls[0]["id"], serde_json::json!("call_qwen38_001")); |
| 5586 | assert_eq!( |
| 5587 | tool_calls[0].pointer("/function/name"), |
| 5588 | Some(&serde_json::json!("read")) |
| 5589 | ); |
| 5590 | assert_eq!( |
| 5591 | tool_calls[0].pointer("/function/arguments"), |
| 5592 | Some(&serde_json::json!(r#"{"path":"widget.rs"}"#)) |
| 5593 | ); |
| 5594 | |
| 5595 | // The matching tool result rides along under its original id. |
| 5596 | let tool_result = messages |
| 5597 | .iter() |
| 5598 | .find(|message| message.get("role").and_then(serde_json::Value::as_str) == Some("tool")) |
| 5599 | .expect("tool result message"); |
| 5600 | assert_eq!( |
| 5601 | tool_result.get("tool_call_id"), |
| 5602 | Some(&serde_json::json!("call_qwen38_001")) |
| 5603 | ); |
| 5604 | assert_eq!( |
| 5605 | tool_result |
| 5606 | .get("content") |
| 5607 | .and_then(serde_json::Value::as_str), |
| 5608 | Some("widget.rs: struct Widget { .. }") |
| 5609 | ); |
| 5610 | |
| 5611 | // Control: the same handoff/tool loop with a documented |
| 5612 | // preserve-thinking model replays its historical reasoning, proving |
| 5613 | // the strip above is model-gated, not route-gated. |
| 5614 | let mut preserve_request = request; |
| 5615 | preserve_request.model = "qwen3.7-plus".to_string(); |
| 5616 | let preserve_messages = build_chat_messages_for_request_and_provider_and_route( |
| 5617 | &preserve_request, |
| 5618 | ProviderKind::ModelstudioTokenPlan, |
| 5619 | DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL, |
| 5620 | ); |
| 5621 | let preserve_assistant = preserve_messages |
| 5622 | .iter() |
| 5623 | .find(|message| { |
| 5624 | message.get("role").and_then(serde_json::Value::as_str) == Some("assistant") |
| 5625 | }) |
| 5626 | .expect("assistant message"); |
| 5627 | assert_eq!( |
| 5628 | preserve_assistant |
| 5629 | .get("reasoning_content") |
| 5630 | .and_then(serde_json::Value::as_str), |
| 5631 | Some("stale thinking from the prior turn"), |
| 5632 | "documented preserve-thinking models keep replaying history" |
| 5633 | ); |
| 5634 | } |
| 5635 | } |
| 5636 | |
| 5637 | // === #103 Phase 4: SSE decoder behavior on canned chunk sequences ============ |
| 5638 | |
| 5639 | #[cfg(test)] |
| 5640 | #[path = "chat/tests/stream_decoder.rs"] |
| 5641 | mod stream_decoder_tests; |
| 5642 | |
| 5643 | #[cfg(test)] |
| 5644 | mod alias_thinking_detection_tests { |
| 5645 | //! Regression coverage for the DeepSeek public model aliases. |
| 5646 | //! |
| 5647 | //! `deepseek-chat` and `deepseek-reasoner` are the canonical alias names |
| 5648 | //! published in DeepSeek's API docs. Server-side they resolve to V4-flash |
| 5649 | //! and V4-pro respectively, both of which have thinking mode enabled by |
| 5650 | //! default. If the TUI does not classify those aliases as reasoning |
| 5651 | //! models, the sanitizer skips replaying `reasoning_content` on tool-call |
| 5652 | //! assistant messages and DeepSeek returns a 400 ("the `reasoning_content` |
| 5653 | //! in the thinking mode must be passed back to the API") on the second |
| 5654 | //! turn. See upstream API docs: |
| 5655 | //! <https://api-docs.deepseek.com/guides/thinking_mode> |
| 5656 | use super::{ |
| 5657 | ReasoningStreamStyle, apply_direct_moonshot_k3_fixed_sampling, |
| 5658 | apply_inkling_reasoning_effort, apply_kimi_code_fixed_sampling, |
| 5659 | apply_kimi_code_k3_reasoning_effort, apply_openai_reasoning_effort, |
| 5660 | apply_provider_token_limit, apply_route_reasoning_controls, is_reasoning_model_for_stream, |
| 5661 | provider_accepts_reasoning_content, reasoning_stream_style_for_route, |
| 5662 | requires_reasoning_content, should_replay_reasoning_content, |
| 5663 | should_replay_reasoning_content_for_provider, |
| 5664 | should_replay_reasoning_content_for_provider_on_route, |
| 5665 | }; |
| 5666 | use codewhale_config::ProviderKind; |
| 5667 | use serde_json::json; |
| 5668 | |
| 5669 | #[test] |
| 5670 | fn aliases_routed_to_v4_require_reasoning_content() { |
| 5671 | // Documented public aliases. |
| 5672 | assert!(requires_reasoning_content("deepseek-chat")); |
| 5673 | assert!(requires_reasoning_content("deepseek-reasoner")); |
| 5674 | // Case-insensitive: users sometimes copy/paste with capitalisation. |
| 5675 | assert!(requires_reasoning_content("DeepSeek-Chat")); |
| 5676 | assert!(requires_reasoning_content("DEEPSEEK-REASONER")); |
| 5677 | } |
| 5678 | |
| 5679 | #[test] |
| 5680 | fn explicit_v4_ids_still_require_reasoning_content() { |
| 5681 | // Direct V4 IDs continue to match (regression guard for the existing |
| 5682 | // `lower.contains("deepseek-v4")` branch). |
| 5683 | assert!(requires_reasoning_content("deepseek-v4-flash")); |
| 5684 | assert!(requires_reasoning_content("deepseek-v4-pro")); |
| 5685 | } |
| 5686 | |
| 5687 | #[test] |
| 5688 | fn non_thinking_aliases_remain_excluded() { |
| 5689 | // Legacy non-thinking IDs and unrelated provider models must not be |
| 5690 | // misclassified, otherwise we would force a placeholder |
| 5691 | // `reasoning_content` on providers that reject the field. |
| 5692 | assert!(!requires_reasoning_content("deepseek-v3")); |
| 5693 | assert!(!requires_reasoning_content("deepseek-coder")); |
| 5694 | assert!(!requires_reasoning_content("qwen3-coder")); |
| 5695 | assert!(!requires_reasoning_content("claude-sonnet-4-6")); |
| 5696 | } |
| 5697 | |
| 5698 | #[test] |
| 5699 | fn alias_prefix_handles_suffixed_variants() { |
| 5700 | // OpenRouter / proxy deployments occasionally suffix the canonical |
| 5701 | // alias (e.g. `deepseek-chat:free`). Those routes still hit V4 |
| 5702 | // server-side, so they must continue to require reasoning_content. |
| 5703 | assert!(requires_reasoning_content("deepseek-chat:free")); |
| 5704 | assert!(requires_reasoning_content("deepseek-reasoner-2025-05")); |
| 5705 | } |
| 5706 | |
| 5707 | #[test] |
| 5708 | fn explicit_reasoning_off_overrides_alias_detection() { |
| 5709 | // `reasoning_effort = "off"` is the documented escape hatch: even when |
| 5710 | // the model is in the thinking family, the user can opt out and the |
| 5711 | // sanitizer must respect that choice. |
| 5712 | assert!(!should_replay_reasoning_content( |
| 5713 | "deepseek-chat", |
| 5714 | Some("off") |
| 5715 | )); |
| 5716 | assert!(!should_replay_reasoning_content( |
| 5717 | "deepseek-reasoner", |
| 5718 | Some("disabled") |
| 5719 | )); |
| 5720 | // Without an explicit override, alias models still trigger replay. |
| 5721 | assert!(should_replay_reasoning_content("deepseek-chat", None)); |
| 5722 | assert!(should_replay_reasoning_content( |
| 5723 | "deepseek-reasoner", |
| 5724 | Some("medium") |
| 5725 | )); |
| 5726 | } |
| 5727 | |
| 5728 | #[test] |
| 5729 | fn generic_openai_provider_does_not_accept_reasoning_content_semantics() { |
| 5730 | assert!(!provider_accepts_reasoning_content(ProviderKind::Openai)); |
| 5731 | assert!(provider_accepts_reasoning_content(ProviderKind::Deepseek)); |
| 5732 | assert!(provider_accepts_reasoning_content(ProviderKind::NvidiaNim)); |
| 5733 | assert!(provider_accepts_reasoning_content(ProviderKind::XiaomiMimo)); |
| 5734 | assert!(provider_accepts_reasoning_content(ProviderKind::Arcee)); |
| 5735 | assert!(provider_accepts_reasoning_content(ProviderKind::Minimax)); |
| 5736 | assert!(provider_accepts_reasoning_content(ProviderKind::Zai)); |
| 5737 | // #3016: Moonshot's native endpoint streams Kimi thinking as |
| 5738 | // reasoning_content. |
| 5739 | assert!(provider_accepts_reasoning_content(ProviderKind::Moonshot)); |
| 5740 | } |
| 5741 | |
| 5742 | /// Alibaba's classic pay-as-you-go DashScope endpoints are genuine |
| 5743 | /// Alibaba Chat Completions hosts serving the same models; before |
| 5744 | /// 2026-08-04 they were missing from the verifier allowlist, so every |
| 5745 | /// reasoning control was silently stripped there (fail-closed feature |
| 5746 | /// loss, not a leak). The intl spelling matches provider_defaults. |
| 5747 | #[test] |
| 5748 | fn classic_dashscope_hosts_are_verified_modelstudio_chat_routes() { |
| 5749 | for base_url in [ |
| 5750 | "https://dashscope.aliyuncs.com/compatible-mode/v1", |
| 5751 | "https://dashscope-intl.aliyuncs.com/compatible-mode/v1", |
| 5752 | "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/", |
| 5753 | ] { |
| 5754 | assert!( |
| 5755 | super::is_exact_modelstudio_chat_route( |
| 5756 | ProviderKind::ModelstudioTokenPlan, |
| 5757 | base_url |
| 5758 | ), |
| 5759 | "{base_url}" |
| 5760 | ); |
| 5761 | let mut body = json!({}); |
| 5762 | apply_route_reasoning_controls( |
| 5763 | &mut body, |
| 5764 | ProviderKind::ModelstudioTokenPlan, |
| 5765 | base_url, |
| 5766 | "qwen3.7-plus", |
| 5767 | Some("off"), |
| 5768 | ); |
| 5769 | assert_eq!(body["enable_thinking"], json!(false), "{base_url}: {body}"); |
| 5770 | } |
| 5771 | // Lookalike hosts stay unverified — fail closed. |
| 5772 | for base_url in [ |
| 5773 | "https://dashscope.aliyuncs.com.evil.example/compatible-mode/v1", |
| 5774 | "https://notdashscope.aliyuncs.com/compatible-mode/v1", |
| 5775 | "https://dashscope.aliyuncs.com/other-path/v1", |
| 5776 | ] { |
| 5777 | assert!( |
| 5778 | !super::is_exact_modelstudio_chat_route( |
| 5779 | ProviderKind::ModelstudioTokenPlan, |
| 5780 | base_url |
| 5781 | ), |
| 5782 | "{base_url}" |
| 5783 | ); |
| 5784 | } |
| 5785 | } |
| 5786 | |
| 5787 | #[test] |
| 5788 | fn modelstudio_hybrid_routes_send_documented_thinking_controls() { |
| 5789 | let base_url = |
| 5790 | codewhale_config::descriptors::defaults::DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL; |
| 5791 | for (effort, enabled) in [ |
| 5792 | (None, true), |
| 5793 | (Some("low"), true), |
| 5794 | (Some("high"), true), |
| 5795 | (Some("xhigh"), true), |
| 5796 | (Some("off"), false), |
| 5797 | ] { |
| 5798 | let mut body = json!({}); |
| 5799 | apply_route_reasoning_controls( |
| 5800 | &mut body, |
| 5801 | ProviderKind::ModelstudioTokenPlan, |
| 5802 | base_url, |
| 5803 | "qwen3.7-plus", |
| 5804 | effort, |
| 5805 | ); |
| 5806 | |
| 5807 | assert_eq!(body["enable_thinking"], json!(enabled), "{effort:?}"); |
| 5808 | assert_eq!(body["preserve_thinking"], json!(enabled), "{effort:?}"); |
| 5809 | assert!(body.get("thinking").is_none(), "{effort:?}: {body}"); |
| 5810 | assert!(body.get("reasoning_effort").is_none(), "{effort:?}: {body}"); |
| 5811 | } |
| 5812 | } |
| 5813 | |
| 5814 | #[test] |
| 5815 | fn modelstudio_deepseek_v4_maps_effort_to_documented_values() { |
| 5816 | let base_url = |
| 5817 | codewhale_config::descriptors::defaults::DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL; |
| 5818 | for (requested, expected) in [("low", "high"), ("high", "high"), ("xhigh", "max")] { |
| 5819 | let mut body = json!({}); |
| 5820 | apply_route_reasoning_controls( |
| 5821 | &mut body, |
| 5822 | ProviderKind::ModelstudioTokenPlan, |
| 5823 | base_url, |
| 5824 | "deepseek-v4-pro", |
| 5825 | Some(requested), |
| 5826 | ); |
| 5827 | |
| 5828 | assert_eq!(body["enable_thinking"], json!(true), "{requested}"); |
| 5829 | assert_eq!(body["reasoning_effort"], json!(expected), "{requested}"); |
| 5830 | } |
| 5831 | } |
| 5832 | |
| 5833 | #[test] |
| 5834 | fn modelstudio_reasoning_controls_fail_closed_on_custom_gateways() { |
| 5835 | let mut body = json!({ |
| 5836 | "enable_thinking": true, |
| 5837 | "preserve_thinking": true, |
| 5838 | "reasoning_effort": "high", |
| 5839 | }); |
| 5840 | apply_route_reasoning_controls( |
| 5841 | &mut body, |
| 5842 | ProviderKind::ModelstudioTokenPlan, |
| 5843 | "https://proxy.example/v1", |
| 5844 | "qwen3.7-plus", |
| 5845 | Some("high"), |
| 5846 | ); |
| 5847 | |
| 5848 | assert!(body.get("enable_thinking").is_none()); |
| 5849 | assert!(body.get("preserve_thinking").is_none()); |
| 5850 | assert!(body.get("reasoning_effort").is_none()); |
| 5851 | } |
| 5852 | |
| 5853 | #[test] |
| 5854 | fn modelstudio_anthropic_identities_write_nothing_on_the_chat_path() { |
| 5855 | // The Messages adapter owns these two. If `wire = "openai"` ever routes |
| 5856 | // them through Chat Completions, the shaper must strip rather than |
| 5857 | // inherit the OpenAI-dialect fields — there is no provider-enum writer |
| 5858 | // left to re-add them. |
| 5859 | for provider in [ |
| 5860 | ProviderKind::ModelstudioTokenPlanAnthropic, |
| 5861 | ProviderKind::ModelstudioCodingPlanAnthropic, |
| 5862 | ] { |
| 5863 | for base_url in [ |
| 5864 | codewhale_config::descriptors::defaults::DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL, |
| 5865 | codewhale_config::descriptors::defaults::MODELSTUDIO_TOKEN_PLAN_ANTHROPIC_BASE_URL, |
| 5866 | ] { |
| 5867 | let mut body = json!({ "enable_thinking": true }); |
| 5868 | apply_route_reasoning_controls( |
| 5869 | &mut body, |
| 5870 | provider, |
| 5871 | base_url, |
| 5872 | "qwen3.7-plus", |
| 5873 | Some("high"), |
| 5874 | ); |
| 5875 | assert_eq!(body, json!({}), "{provider:?} {base_url}"); |
| 5876 | } |
| 5877 | } |
| 5878 | } |
| 5879 | |
| 5880 | #[test] |
| 5881 | fn modelstudio_qwen38_route_streams_reasoning_without_replaying_history() { |
| 5882 | let base_url = |
| 5883 | codewhale_config::descriptors::defaults::DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL; |
| 5884 | for model in ["qwen3.8-max", "qwen3.8-max-preview"] { |
| 5885 | // qwen3.8 is thinking-only. Effort selection must never hide its |
| 5886 | // separate reasoning stream, including the stale `off` state |
| 5887 | // that can arrive before route normalization. |
| 5888 | assert_eq!( |
| 5889 | reasoning_stream_style_for_route( |
| 5890 | ProviderKind::ModelstudioTokenPlan, |
| 5891 | base_url, |
| 5892 | model, |
| 5893 | None, |
| 5894 | ), |
| 5895 | ReasoningStreamStyle::SeparateField, |
| 5896 | "{model}" |
| 5897 | ); |
| 5898 | // ...but Alibaba does not document `preserve_thinking` for the |
| 5899 | // qwen3.8 family, so no historical `reasoning_content` may be |
| 5900 | // replayed — even when a stale effort claims thinking is off. |
| 5901 | // Replaying it feeds the model its own past Thinking blocks and |
| 5902 | // re-triggers them every turn (observed handoff loop). |
| 5903 | for effort in [None, Some("off"), Some("high"), Some("xhigh")] { |
| 5904 | assert!( |
| 5905 | !should_replay_reasoning_content_for_provider_on_route( |
| 5906 | ProviderKind::ModelstudioTokenPlan, |
| 5907 | base_url, |
| 5908 | model, |
| 5909 | effort, |
| 5910 | ), |
| 5911 | "{model} {effort:?}" |
| 5912 | ); |
| 5913 | } |
| 5914 | // ...and no enable/disable or preserve switch is ever sent for |
| 5915 | // them. |
| 5916 | for effort in [None, Some("off"), Some("high")] { |
| 5917 | let mut body = json!({}); |
| 5918 | apply_route_reasoning_controls( |
| 5919 | &mut body, |
| 5920 | ProviderKind::ModelstudioTokenPlan, |
| 5921 | base_url, |
| 5922 | model, |
| 5923 | effort, |
| 5924 | ); |
| 5925 | assert!(body.get("enable_thinking").is_none(), "{model}: {body}"); |
| 5926 | assert!( |
| 5927 | body.get("preserve_thinking").is_none(), |
| 5928 | "{model} {effort:?}: {body}" |
| 5929 | ); |
| 5930 | assert!(body.get("reasoning_effort").is_none(), "{model}: {body}"); |
| 5931 | } |
| 5932 | } |
| 5933 | } |
| 5934 | |
| 5935 | #[test] |
| 5936 | fn modelstudio_hybrid_route_classifies_reasoning_and_replays_history() { |
| 5937 | let base_url = |
| 5938 | codewhale_config::descriptors::defaults::DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL; |
| 5939 | assert_eq!( |
| 5940 | reasoning_stream_style_for_route( |
| 5941 | ProviderKind::ModelstudioTokenPlan, |
| 5942 | base_url, |
| 5943 | "qwen3.7-plus", |
| 5944 | None, |
| 5945 | ), |
| 5946 | ReasoningStreamStyle::SeparateField, |
| 5947 | ); |
| 5948 | assert!(should_replay_reasoning_content_for_provider_on_route( |
| 5949 | ProviderKind::ModelstudioTokenPlan, |
| 5950 | base_url, |
| 5951 | "qwen3.7-plus", |
| 5952 | None, |
| 5953 | )); |
| 5954 | assert!(!should_replay_reasoning_content_for_provider_on_route( |
| 5955 | ProviderKind::ModelstudioTokenPlan, |
| 5956 | base_url, |
| 5957 | "qwen3.7-plus", |
| 5958 | Some("off"), |
| 5959 | )); |
| 5960 | } |
| 5961 | |
| 5962 | #[test] |
| 5963 | fn modelstudio_replay_stays_narrow_until_a_live_key_confirms_it() { |
| 5964 | // Deliberately narrower than PR #5233: only `preserve_thinking` models |
| 5965 | // replay. GLM and DeepSeek-V3.x on Model Studio stay stripped until |
| 5966 | // someone with a key confirms DashScope accepts `reasoning_content` in |
| 5967 | // input messages. deepseek-v4* is unaffected — it replays through |
| 5968 | // `requires_reasoning_content` on every provider. |
| 5969 | let base_url = |
| 5970 | codewhale_config::descriptors::defaults::DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL; |
| 5971 | for model in ["glm-5.2", "deepseek-v3.2", "deepseek-v3.1"] { |
| 5972 | assert!( |
| 5973 | !should_replay_reasoning_content_for_provider_on_route( |
| 5974 | ProviderKind::ModelstudioTokenPlan, |
| 5975 | base_url, |
| 5976 | model, |
| 5977 | None, |
| 5978 | ), |
| 5979 | "{model}" |
| 5980 | ); |
| 5981 | } |
| 5982 | assert!(should_replay_reasoning_content_for_provider_on_route( |
| 5983 | ProviderKind::ModelstudioTokenPlan, |
| 5984 | base_url, |
| 5985 | "deepseek-v4-pro", |
| 5986 | None, |
| 5987 | )); |
| 5988 | } |
| 5989 | |
| 5990 | #[test] |
| 5991 | fn modelstudio_coding_plan_chat_route_is_classified_for_all_supported_identities() { |
| 5992 | // The picker represents Coding Plan as mode = "coding-plan" under |
| 5993 | // the primary provider id, so the chat client receives |
| 5994 | // ModelstudioTokenPlan with the Coding Plan URL. Direct configuration |
| 5995 | // also retains the legacy ModelstudioCodingPlan identity. |
| 5996 | let base_url = |
| 5997 | codewhale_config::descriptors::defaults::DEFAULT_MODELSTUDIO_CODING_PLAN_BASE_URL; |
| 5998 | for provider in [ |
| 5999 | ProviderKind::ModelstudioTokenPlan, |
| 6000 | ProviderKind::ModelstudioCodingPlan, |
| 6001 | ] { |
| 6002 | let mut body = json!({}); |
| 6003 | apply_route_reasoning_controls( |
| 6004 | &mut body, |
| 6005 | provider, |
| 6006 | base_url, |
| 6007 | "qwen3.7-plus", |
| 6008 | Some("high"), |
| 6009 | ); |
| 6010 | |
| 6011 | assert_eq!(body["enable_thinking"], json!(true), "{provider:?}"); |
| 6012 | assert_eq!(body["preserve_thinking"], json!(true), "{provider:?}"); |
| 6013 | assert_eq!( |
| 6014 | reasoning_stream_style_for_route(provider, base_url, "qwen3.7-plus", None), |
| 6015 | ReasoningStreamStyle::SeparateField, |
| 6016 | "{provider:?}", |
| 6017 | ); |
| 6018 | assert!(should_replay_reasoning_content_for_provider_on_route( |
| 6019 | provider, |
| 6020 | base_url, |
| 6021 | "qwen3.7-plus", |
| 6022 | None, |
| 6023 | )); |
| 6024 | } |
| 6025 | } |
| 6026 | |
| 6027 | #[test] |
| 6028 | fn modelstudio_workspace_scoped_token_plan_route_is_recognized() { |
| 6029 | let workspace_url = |
| 6030 | "https://workspace-123.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"; |
| 6031 | // Stream classification works on the workspace-scoped host... |
| 6032 | assert_eq!( |
| 6033 | reasoning_stream_style_for_route( |
| 6034 | ProviderKind::ModelstudioTokenPlan, |
| 6035 | workspace_url, |
| 6036 | "qwen3.8-max", |
| 6037 | None, |
| 6038 | ), |
| 6039 | ReasoningStreamStyle::SeparateField, |
| 6040 | ); |
| 6041 | assert_eq!( |
| 6042 | reasoning_stream_style_for_route( |
| 6043 | ProviderKind::ModelstudioTokenPlan, |
| 6044 | workspace_url, |
| 6045 | "qwen3.7-plus", |
| 6046 | None, |
| 6047 | ), |
| 6048 | ReasoningStreamStyle::SeparateField, |
| 6049 | ); |
| 6050 | // ...and the route gate decides replay the same way it does on the |
| 6051 | // default host: qwen3.8 never replays, documented preserve models do. |
| 6052 | assert!(!should_replay_reasoning_content_for_provider_on_route( |
| 6053 | ProviderKind::ModelstudioTokenPlan, |
| 6054 | workspace_url, |
| 6055 | "qwen3.8-max", |
| 6056 | None, |
| 6057 | )); |
| 6058 | assert!(should_replay_reasoning_content_for_provider_on_route( |
| 6059 | ProviderKind::ModelstudioTokenPlan, |
| 6060 | workspace_url, |
| 6061 | "qwen3.7-plus", |
| 6062 | None, |
| 6063 | )); |
| 6064 | let mut body = json!({}); |
| 6065 | apply_route_reasoning_controls( |
| 6066 | &mut body, |
| 6067 | ProviderKind::ModelstudioTokenPlan, |
| 6068 | workspace_url, |
| 6069 | "qwen3.7-plus", |
| 6070 | Some("high"), |
| 6071 | ); |
| 6072 | assert_eq!(body["preserve_thinking"], json!(true), "{body}"); |
| 6073 | } |
| 6074 | |
| 6075 | #[test] |
| 6076 | fn modelstudio_thinking_named_unknown_model_cannot_bypass_the_route_gate() { |
| 6077 | // An unknown Model Studio model whose *name* suggests reasoning must |
| 6078 | // not gain replay: only the documented `preserve_thinking` list (plus |
| 6079 | // the concrete DeepSeek V4 family ids) authorizes historical |
| 6080 | // `reasoning_content` on exact Model Studio routes. The generic |
| 6081 | // `-thinking`/`reasoner` heuristics prove nothing about DashScope's |
| 6082 | // request dialect. |
| 6083 | let base_url = |
| 6084 | codewhale_config::descriptors::defaults::DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL; |
| 6085 | for model in [ |
| 6086 | "foo-thinking", |
| 6087 | "foo-reasoner", |
| 6088 | "new-model-reasoning", |
| 6089 | "acme-reasoner-v2", |
| 6090 | "qwen4-max-preview", |
| 6091 | ] { |
| 6092 | assert!( |
| 6093 | !should_replay_reasoning_content_for_provider_on_route( |
| 6094 | ProviderKind::ModelstudioTokenPlan, |
| 6095 | base_url, |
| 6096 | model, |
| 6097 | None, |
| 6098 | ), |
| 6099 | "{model}" |
| 6100 | ); |
| 6101 | // The shaper writes no reasoning controls for it either — fail |
| 6102 | // closed on the wire. |
| 6103 | let mut body = json!({ "enable_thinking": true, "preserve_thinking": true }); |
| 6104 | apply_route_reasoning_controls( |
| 6105 | &mut body, |
| 6106 | ProviderKind::ModelstudioTokenPlan, |
| 6107 | base_url, |
| 6108 | model, |
| 6109 | Some("high"), |
| 6110 | ); |
| 6111 | assert!(body.get("enable_thinking").is_none(), "{model}: {body}"); |
| 6112 | assert!(body.get("preserve_thinking").is_none(), "{model}: {body}"); |
| 6113 | } |
| 6114 | // A suggestive name is not a replay contract on any route. |
| 6115 | assert!(!requires_reasoning_content("foo-thinking")); |
| 6116 | assert!(!requires_reasoning_content("foo-reasoner")); |
| 6117 | } |
| 6118 | |
| 6119 | #[test] |
| 6120 | fn modelstudio_qwen36_flash_preserves_thinking_per_current_documentation() { |
| 6121 | // Current Alibaba documentation explicitly includes qwen3.6-flash |
| 6122 | // (and its documented snapshots) among the `preserve_thinking` |
| 6123 | // models. Keep positive coverage so any future narrowing of the |
| 6124 | // preserve list has to remove it deliberately. |
| 6125 | let base_url = |
| 6126 | codewhale_config::descriptors::defaults::DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL; |
| 6127 | for model in ["qwen3.6-flash", "qwen3.6-flash-2026-04-16"] { |
| 6128 | assert!(should_replay_reasoning_content_for_provider_on_route( |
| 6129 | ProviderKind::ModelstudioTokenPlan, |
| 6130 | base_url, |
| 6131 | model, |
| 6132 | None, |
| 6133 | )); |
| 6134 | let mut body = json!({}); |
| 6135 | apply_route_reasoning_controls( |
| 6136 | &mut body, |
| 6137 | ProviderKind::ModelstudioTokenPlan, |
| 6138 | base_url, |
| 6139 | model, |
| 6140 | Some("high"), |
| 6141 | ); |
| 6142 | assert_eq!(body["enable_thinking"], json!(true), "{model}"); |
| 6143 | assert_eq!(body["preserve_thinking"], json!(true), "{model}: {body}"); |
| 6144 | // Hybrid semantics: an explicit off disables both, and replay |
| 6145 | // follows the effort gate. |
| 6146 | assert!(!should_replay_reasoning_content_for_provider_on_route( |
| 6147 | ProviderKind::ModelstudioTokenPlan, |
| 6148 | base_url, |
| 6149 | model, |
| 6150 | Some("off"), |
| 6151 | )); |
| 6152 | let mut off_body = json!({}); |
| 6153 | apply_route_reasoning_controls( |
| 6154 | &mut off_body, |
| 6155 | ProviderKind::ModelstudioTokenPlan, |
| 6156 | base_url, |
| 6157 | model, |
| 6158 | Some("off"), |
| 6159 | ); |
| 6160 | assert_eq!(off_body["enable_thinking"], json!(false), "{model}"); |
| 6161 | assert_eq!(off_body["preserve_thinking"], json!(false), "{model}"); |
| 6162 | } |
| 6163 | |
| 6164 | for invented in [ |
| 6165 | "qwen3.6-flash-future", |
| 6166 | "qwen3.7-plus-proxy", |
| 6167 | "kimi-k2.7-code-unverified", |
| 6168 | ] { |
| 6169 | assert!( |
| 6170 | !should_replay_reasoning_content_for_provider_on_route( |
| 6171 | ProviderKind::ModelstudioTokenPlan, |
| 6172 | base_url, |
| 6173 | invented, |
| 6174 | None, |
| 6175 | ), |
| 6176 | "prefix lookalikes must fail closed: {invented}" |
| 6177 | ); |
| 6178 | } |
| 6179 | } |
| 6180 | |
| 6181 | #[test] |
| 6182 | fn modelstudio_kimi_k27_code_is_thinking_only_and_preserves_trace() { |
| 6183 | // NOTE: unlike the qwen3.8 pair, this classification is asserted by |
| 6184 | // PR #5233 rather than corroborated by models_dev.bundled.json, which |
| 6185 | // lists kimi-k2.7-code with `reasoning: true` and no `always_on`. |
| 6186 | let base_url = |
| 6187 | codewhale_config::descriptors::defaults::DEFAULT_MODELSTUDIO_TOKEN_PLAN_BASE_URL; |
| 6188 | for model in [ |
| 6189 | "kimi-k2.7-code", |
| 6190 | "kimi/kimi-k2.7-code", |
| 6191 | "kimi/kimi-k2.7-code-highspeed", |
| 6192 | ] { |
| 6193 | let mut body = json!({}); |
| 6194 | apply_route_reasoning_controls( |
| 6195 | &mut body, |
| 6196 | ProviderKind::ModelstudioTokenPlan, |
| 6197 | base_url, |
| 6198 | model, |
| 6199 | Some("off"), |
| 6200 | ); |
| 6201 | |
| 6202 | assert!(body.get("enable_thinking").is_none(), "{model}: {body}"); |
| 6203 | assert_eq!(body["preserve_thinking"], json!(true), "{model}"); |
| 6204 | assert_eq!( |
| 6205 | reasoning_stream_style_for_route( |
| 6206 | ProviderKind::ModelstudioTokenPlan, |
| 6207 | base_url, |
| 6208 | model, |
| 6209 | None, |
| 6210 | ), |
| 6211 | ReasoningStreamStyle::SeparateField, |
| 6212 | "{model}", |
| 6213 | ); |
| 6214 | assert!(should_replay_reasoning_content_for_provider_on_route( |
| 6215 | ProviderKind::ModelstudioTokenPlan, |
| 6216 | base_url, |
| 6217 | model, |
| 6218 | Some("off"), |
| 6219 | )); |
| 6220 | } |
| 6221 | } |
| 6222 | |
| 6223 | #[test] |
| 6224 | fn stream_classifies_moonshot_kimi_as_reasoning() { |
| 6225 | // #3016: without this, Kimi thinking leaked into answer text. |
| 6226 | assert!(is_reasoning_model_for_stream( |
| 6227 | ProviderKind::Moonshot, |
| 6228 | "kimi-k2.6" |
| 6229 | )); |
| 6230 | assert!( |
| 6231 | is_reasoning_model_for_stream(ProviderKind::Moonshot, "kimi-for-coding"), |
| 6232 | "Kimi Code's stable model id now maps to K2.7 Code and streams reasoning_content" |
| 6233 | ); |
| 6234 | } |
| 6235 | |
| 6236 | #[test] |
| 6237 | fn moonshot_and_minimax_replay_reasoning_content_for_supported_models() { |
| 6238 | assert!(should_replay_reasoning_content_for_provider( |
| 6239 | ProviderKind::Moonshot, |
| 6240 | "kimi-k2.7-code", |
| 6241 | None, |
| 6242 | )); |
| 6243 | assert!(should_replay_reasoning_content_for_provider( |
| 6244 | ProviderKind::Moonshot, |
| 6245 | "kimi-for-coding", |
| 6246 | None, |
| 6247 | )); |
| 6248 | assert!(should_replay_reasoning_content_for_provider( |
| 6249 | ProviderKind::Minimax, |
| 6250 | "MiniMax-M3", |
| 6251 | None, |
| 6252 | )); |
| 6253 | assert!(should_replay_reasoning_content_for_provider( |
| 6254 | ProviderKind::Zai, |
| 6255 | "GLM-5.2", |
| 6256 | None, |
| 6257 | )); |
| 6258 | assert!(should_replay_reasoning_content_for_provider( |
| 6259 | ProviderKind::Zai, |
| 6260 | "GLM-5.3", |
| 6261 | None, |
| 6262 | )); |
| 6263 | assert!(!should_replay_reasoning_content_for_provider( |
| 6264 | ProviderKind::Moonshot, |
| 6265 | "kimi-for-coding", |
| 6266 | Some("off"), |
| 6267 | )); |
| 6268 | } |
| 6269 | |
| 6270 | #[test] |
| 6271 | fn bare_k3_reasoning_semantics_are_scoped_to_exact_kimi_code_route() { |
| 6272 | let kimi_code = codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL; |
| 6273 | let direct_moonshot = codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL; |
| 6274 | |
| 6275 | assert!(should_replay_reasoning_content_for_provider_on_route( |
| 6276 | ProviderKind::Moonshot, |
| 6277 | kimi_code, |
| 6278 | codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL, |
| 6279 | Some("high"), |
| 6280 | )); |
| 6281 | assert_eq!( |
| 6282 | reasoning_stream_style_for_route( |
| 6283 | ProviderKind::Moonshot, |
| 6284 | kimi_code, |
| 6285 | codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL, |
| 6286 | None, |
| 6287 | ), |
| 6288 | ReasoningStreamStyle::SeparateField |
| 6289 | ); |
| 6290 | |
| 6291 | assert!(!should_replay_reasoning_content_for_provider_on_route( |
| 6292 | ProviderKind::Moonshot, |
| 6293 | direct_moonshot, |
| 6294 | codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL, |
| 6295 | Some("high"), |
| 6296 | )); |
| 6297 | // Display is not replay: a reasoning field that arrives on the |
| 6298 | // neighboring route still renders as Thinking (#6501), while the |
| 6299 | // replay contract above stays scoped to the exact membership route. |
| 6300 | assert_eq!( |
| 6301 | reasoning_stream_style_for_route( |
| 6302 | ProviderKind::Moonshot, |
| 6303 | direct_moonshot, |
| 6304 | codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL, |
| 6305 | None, |
| 6306 | ), |
| 6307 | ReasoningStreamStyle::SeparateField |
| 6308 | ); |
| 6309 | assert!( |
| 6310 | should_replay_reasoning_content_for_provider_on_route( |
| 6311 | ProviderKind::Moonshot, |
| 6312 | kimi_code, |
| 6313 | codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL, |
| 6314 | Some("off"), |
| 6315 | ), |
| 6316 | "exact membership K3 stays always-thinking even for a stale raw Off caller" |
| 6317 | ); |
| 6318 | } |
| 6319 | |
| 6320 | #[test] |
| 6321 | fn direct_moonshot_k3_is_always_thinking_and_replays_reasoning() { |
| 6322 | let direct = codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL; |
| 6323 | let model = codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL; |
| 6324 | |
| 6325 | for effort in [Some("off"), Some("low"), Some("high"), Some("max"), None] { |
| 6326 | assert!(should_replay_reasoning_content_for_provider_on_route( |
| 6327 | ProviderKind::Moonshot, |
| 6328 | direct, |
| 6329 | model, |
| 6330 | effort, |
| 6331 | )); |
| 6332 | } |
| 6333 | assert_eq!( |
| 6334 | reasoning_stream_style_for_route(ProviderKind::Moonshot, direct, model, None), |
| 6335 | ReasoningStreamStyle::SeparateField |
| 6336 | ); |
| 6337 | } |
| 6338 | |
| 6339 | #[test] |
| 6340 | fn xiaomi_mimo_uses_max_completion_tokens_payload_key() { |
| 6341 | let mut body = json!({ |
| 6342 | "model": "mimo-v2.5-pro", |
| 6343 | "messages": [], |
| 6344 | "max_tokens": 8192, |
| 6345 | }); |
| 6346 | |
| 6347 | apply_provider_token_limit( |
| 6348 | &mut body, |
| 6349 | ProviderKind::XiaomiMimo, |
| 6350 | "https://api.xiaomimimo.com/v1", |
| 6351 | "mimo-v2.5-pro", |
| 6352 | 8192, |
| 6353 | ); |
| 6354 | |
| 6355 | assert!(body.get("max_tokens").is_none()); |
| 6356 | assert_eq!( |
| 6357 | body.get("max_completion_tokens") |
| 6358 | .and_then(serde_json::Value::as_u64), |
| 6359 | Some(8192) |
| 6360 | ); |
| 6361 | } |
| 6362 | |
| 6363 | #[test] |
| 6364 | fn openai_reasoning_model_uses_completion_token_limit_and_effort_field() { |
| 6365 | let mut body = json!({ |
| 6366 | "model": "gpt-5.5", |
| 6367 | "messages": [], |
| 6368 | "max_tokens": 4096, |
| 6369 | }); |
| 6370 | |
| 6371 | apply_provider_token_limit( |
| 6372 | &mut body, |
| 6373 | ProviderKind::Openai, |
| 6374 | "https://api.openai.com/v1", |
| 6375 | "gpt-5.5", |
| 6376 | 4096, |
| 6377 | ); |
| 6378 | apply_openai_reasoning_effort(&mut body, ProviderKind::Openai, "gpt-5.5", Some("high")); |
| 6379 | |
| 6380 | assert!(body.get("max_tokens").is_none()); |
| 6381 | assert_eq!( |
| 6382 | body.get("max_completion_tokens") |
| 6383 | .and_then(serde_json::Value::as_u64), |
| 6384 | Some(4096) |
| 6385 | ); |
| 6386 | assert_eq!( |
| 6387 | body.get("reasoning_effort") |
| 6388 | .and_then(serde_json::Value::as_str), |
| 6389 | Some("high") |
| 6390 | ); |
| 6391 | } |
| 6392 | |
| 6393 | #[test] |
| 6394 | fn gpt_56_uses_documented_max_reasoning_effort() { |
| 6395 | let mut body = json!({ |
| 6396 | "model": "gpt-5.6-sol", |
| 6397 | "messages": [], |
| 6398 | "max_tokens": 8192, |
| 6399 | }); |
| 6400 | |
| 6401 | apply_provider_token_limit( |
| 6402 | &mut body, |
| 6403 | ProviderKind::Openai, |
| 6404 | "https://api.openai.com/v1", |
| 6405 | "gpt-5.6-sol", |
| 6406 | 8192, |
| 6407 | ); |
| 6408 | apply_openai_reasoning_effort(&mut body, ProviderKind::Openai, "gpt-5.6-sol", Some("max")); |
| 6409 | |
| 6410 | assert!(body.get("max_tokens").is_none()); |
| 6411 | assert_eq!(body["max_completion_tokens"], json!(8192)); |
| 6412 | assert_eq!(body["reasoning_effort"], json!("max")); |
| 6413 | } |
| 6414 | |
| 6415 | #[test] |
| 6416 | fn grok_47_and_46_use_exact_first_party_reasoning_effort_ladder() { |
| 6417 | // Both catalog rows document low/medium/high/xhigh; reasoning cannot |
| 6418 | // be disabled, so `off` is the documented default `high`. |
| 6419 | for model in [ |
| 6420 | codewhale_config::catalog::reviewed::constants::XAI_GROK_4_7_MODEL, |
| 6421 | codewhale_config::catalog::reviewed::constants::XAI_GROK_4_6_MODEL, |
| 6422 | ] { |
| 6423 | for (requested, expected) in [ |
| 6424 | ("off", "high"), |
| 6425 | ("low", "low"), |
| 6426 | ("medium", "medium"), |
| 6427 | ("high", "high"), |
| 6428 | ("xhigh", "xhigh"), |
| 6429 | ("max", "xhigh"), |
| 6430 | ] { |
| 6431 | let mut body = json!({}); |
| 6432 | apply_route_reasoning_controls( |
| 6433 | &mut body, |
| 6434 | ProviderKind::Xai, |
| 6435 | codewhale_config::descriptors::defaults::DEFAULT_XAI_BASE_URL, |
| 6436 | model, |
| 6437 | Some(requested), |
| 6438 | ); |
| 6439 | assert_eq!( |
| 6440 | body, |
| 6441 | json!({ "reasoning_effort": expected }), |
| 6442 | "{model} {requested}" |
| 6443 | ); |
| 6444 | } |
| 6445 | } |
| 6446 | |
| 6447 | // A row without a documented effort option (grok-4.3) and an id the |
| 6448 | // catalog does not know send nothing. |
| 6449 | for model in [ |
| 6450 | codewhale_config::catalog::reviewed::constants::XAI_GROK_4_3_MODEL, |
| 6451 | "grok-9-unknown", |
| 6452 | ] { |
| 6453 | let mut body = json!({}); |
| 6454 | apply_route_reasoning_controls( |
| 6455 | &mut body, |
| 6456 | ProviderKind::Xai, |
| 6457 | codewhale_config::descriptors::defaults::DEFAULT_XAI_BASE_URL, |
| 6458 | model, |
| 6459 | Some("medium"), |
| 6460 | ); |
| 6461 | assert_eq!(body, json!({}), "{model}"); |
| 6462 | } |
| 6463 | |
| 6464 | let mut provider_default = json!({}); |
| 6465 | apply_route_reasoning_controls( |
| 6466 | &mut provider_default, |
| 6467 | ProviderKind::Xai, |
| 6468 | codewhale_config::descriptors::defaults::DEFAULT_XAI_BASE_URL, |
| 6469 | codewhale_config::catalog::reviewed::constants::XAI_GROK_4_6_MODEL, |
| 6470 | Some("auto"), |
| 6471 | ); |
| 6472 | assert_eq!(provider_default, json!({})); |
| 6473 | |
| 6474 | let mut custom = json!({}); |
| 6475 | apply_route_reasoning_controls( |
| 6476 | &mut custom, |
| 6477 | ProviderKind::Xai, |
| 6478 | "https://gateway.example/v1", |
| 6479 | codewhale_config::catalog::reviewed::constants::XAI_GROK_4_6_MODEL, |
| 6480 | Some("medium"), |
| 6481 | ); |
| 6482 | assert_eq!(custom, json!({})); |
| 6483 | } |
| 6484 | |
| 6485 | #[test] |
| 6486 | fn grok_45_uses_first_party_ladder_and_maps_xhigh_to_high() { |
| 6487 | for (requested, expected) in [ |
| 6488 | ("off", "high"), |
| 6489 | ("low", "low"), |
| 6490 | ("medium", "medium"), |
| 6491 | ("high", "high"), |
| 6492 | ("xhigh", "high"), |
| 6493 | ("max", "high"), |
| 6494 | ] { |
| 6495 | let mut body = json!({}); |
| 6496 | apply_route_reasoning_controls( |
| 6497 | &mut body, |
| 6498 | ProviderKind::Xai, |
| 6499 | codewhale_config::descriptors::defaults::DEFAULT_XAI_BASE_URL, |
| 6500 | codewhale_config::catalog::reviewed::constants::XAI_GROK_4_5_MODEL, |
| 6501 | Some(requested), |
| 6502 | ); |
| 6503 | assert_eq!(body, json!({ "reasoning_effort": expected }), "{requested}"); |
| 6504 | } |
| 6505 | } |
| 6506 | |
| 6507 | #[test] |
| 6508 | fn inkling_uses_its_exact_reasoning_vocabulary_without_thinking_extension() { |
| 6509 | for (requested, expected) in [ |
| 6510 | ("off", "none"), |
| 6511 | ("minimal", "minimal"), |
| 6512 | ("low", "low"), |
| 6513 | ("medium", "medium"), |
| 6514 | ("high", "high"), |
| 6515 | ("max", "max"), |
| 6516 | ("xhigh", "max"), |
| 6517 | ] { |
| 6518 | let mut body = json!({ |
| 6519 | "thinking": { "type": "enabled" }, |
| 6520 | "reasoning_effort": "xhigh", |
| 6521 | }); |
| 6522 | |
| 6523 | apply_inkling_reasoning_effort( |
| 6524 | &mut body, |
| 6525 | ProviderKind::Together, |
| 6526 | "thinkingmachines/inkling", |
| 6527 | Some(requested), |
| 6528 | ); |
| 6529 | |
| 6530 | assert_eq!(body["reasoning_effort"], json!(expected)); |
| 6531 | assert!(body.get("thinking").is_none()); |
| 6532 | } |
| 6533 | } |
| 6534 | |
| 6535 | #[test] |
| 6536 | fn inkling_reasoning_override_is_scoped_to_the_exact_together_route() { |
| 6537 | let mut other_model = json!({ "thinking": { "type": "enabled" } }); |
| 6538 | apply_inkling_reasoning_effort( |
| 6539 | &mut other_model, |
| 6540 | ProviderKind::Together, |
| 6541 | "deepseek-ai/DeepSeek-V4-Pro", |
| 6542 | Some("max"), |
| 6543 | ); |
| 6544 | assert_eq!(other_model["thinking"]["type"], json!("enabled")); |
| 6545 | assert!(other_model.get("reasoning_effort").is_none()); |
| 6546 | |
| 6547 | let mut other_provider = json!({ "thinking": { "type": "enabled" } }); |
| 6548 | apply_inkling_reasoning_effort( |
| 6549 | &mut other_provider, |
| 6550 | ProviderKind::Openrouter, |
| 6551 | "thinkingmachines/inkling", |
| 6552 | Some("max"), |
| 6553 | ); |
| 6554 | assert_eq!(other_provider["thinking"]["type"], json!("enabled")); |
| 6555 | assert!(other_provider.get("reasoning_effort").is_none()); |
| 6556 | } |
| 6557 | |
| 6558 | #[test] |
| 6559 | fn kimi_code_k3_uses_documented_nested_thinking_effort() { |
| 6560 | for (requested, expected) in [ |
| 6561 | ("low", json!({ "type": "enabled", "effort": "low" })), |
| 6562 | ("minimum", json!({ "type": "enabled", "effort": "low" })), |
| 6563 | ("light", json!({ "type": "enabled", "effort": "low" })), |
| 6564 | ("medium", json!({ "type": "enabled", "effort": "high" })), |
| 6565 | ("high", json!({ "type": "enabled", "effort": "high" })), |
| 6566 | ("xhigh", json!({ "type": "enabled", "effort": "max" })), |
| 6567 | ("ultra", json!({ "type": "enabled", "effort": "max" })), |
| 6568 | ("max", json!({ "type": "enabled", "effort": "max" })), |
| 6569 | ("none", json!({ "type": "enabled", "effort": "low" })), |
| 6570 | ("off", json!({ "type": "enabled", "effort": "low" })), |
| 6571 | ] { |
| 6572 | let mut body = json!({ "reasoning_effort": "stale" }); |
| 6573 | apply_kimi_code_k3_reasoning_effort( |
| 6574 | &mut body, |
| 6575 | ProviderKind::Moonshot, |
| 6576 | codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL, |
| 6577 | codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL, |
| 6578 | Some(requested), |
| 6579 | ); |
| 6580 | |
| 6581 | assert_eq!(body["thinking"], expected, "requested {requested}"); |
| 6582 | assert!(body.get("reasoning_effort").is_none()); |
| 6583 | } |
| 6584 | } |
| 6585 | |
| 6586 | #[test] |
| 6587 | fn kimi_code_k3_256k_uses_k3_reasoning_and_membership_sampling_contracts() { |
| 6588 | let mut body = json!({ |
| 6589 | "reasoning_effort": "stale", |
| 6590 | "temperature": 0.3, |
| 6591 | "top_p": 0.8, |
| 6592 | }); |
| 6593 | apply_kimi_code_k3_reasoning_effort( |
| 6594 | &mut body, |
| 6595 | ProviderKind::Moonshot, |
| 6596 | codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL, |
| 6597 | codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_256K_MODEL, |
| 6598 | Some("max"), |
| 6599 | ); |
| 6600 | apply_kimi_code_fixed_sampling( |
| 6601 | &mut body, |
| 6602 | ProviderKind::Moonshot, |
| 6603 | codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL, |
| 6604 | codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_256K_MODEL, |
| 6605 | ); |
| 6606 | |
| 6607 | assert_eq!( |
| 6608 | body["thinking"], |
| 6609 | json!({ "type": "enabled", "effort": "max" }) |
| 6610 | ); |
| 6611 | assert!(body.get("reasoning_effort").is_none()); |
| 6612 | assert!(body.get("temperature").is_none()); |
| 6613 | assert!(body.get("top_p").is_none()); |
| 6614 | } |
| 6615 | |
| 6616 | #[test] |
| 6617 | fn kimi_code_fixed_sampling_does_not_leak_to_neighbor_routes() { |
| 6618 | for (provider, base_url, model) in [ |
| 6619 | ( |
| 6620 | ProviderKind::Moonshot, |
| 6621 | codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL, |
| 6622 | codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_256K_MODEL, |
| 6623 | ), |
| 6624 | ( |
| 6625 | ProviderKind::Openrouter, |
| 6626 | codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL, |
| 6627 | codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_256K_MODEL, |
| 6628 | ), |
| 6629 | ( |
| 6630 | ProviderKind::Moonshot, |
| 6631 | codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL, |
| 6632 | "k3-256k-preview", |
| 6633 | ), |
| 6634 | ] { |
| 6635 | let mut body = json!({ "temperature": 0.3, "top_p": 0.8 }); |
| 6636 | apply_kimi_code_fixed_sampling(&mut body, provider, base_url, model); |
| 6637 | assert_eq!(body["temperature"], json!(0.3)); |
| 6638 | assert_eq!(body["top_p"], json!(0.8)); |
| 6639 | } |
| 6640 | } |
| 6641 | |
| 6642 | #[test] |
| 6643 | fn direct_moonshot_k3_uses_top_level_effort_and_never_disables_thinking() { |
| 6644 | for (requested, expected) in [ |
| 6645 | ("off", "low"), |
| 6646 | ("none", "low"), |
| 6647 | ("low", "low"), |
| 6648 | ("medium", "high"), |
| 6649 | ("high", "high"), |
| 6650 | ("xhigh", "max"), |
| 6651 | ("max", "max"), |
| 6652 | ] { |
| 6653 | let mut body = json!({ |
| 6654 | "model": codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL, |
| 6655 | "thinking": { "type": "disabled" }, |
| 6656 | }); |
| 6657 | apply_route_reasoning_controls( |
| 6658 | &mut body, |
| 6659 | ProviderKind::Moonshot, |
| 6660 | codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL, |
| 6661 | codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL, |
| 6662 | Some(requested), |
| 6663 | ); |
| 6664 | |
| 6665 | assert_eq!(body["reasoning_effort"], json!(expected), "{requested}"); |
| 6666 | assert!(body.get("thinking").is_none(), "{requested}: {body}"); |
| 6667 | } |
| 6668 | |
| 6669 | let mut provider_default = json!({ "thinking": { "type": "enabled" } }); |
| 6670 | apply_route_reasoning_controls( |
| 6671 | &mut provider_default, |
| 6672 | ProviderKind::Moonshot, |
| 6673 | codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL, |
| 6674 | codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL, |
| 6675 | Some("auto"), |
| 6676 | ); |
| 6677 | assert!(provider_default.get("thinking").is_none()); |
| 6678 | assert!(provider_default.get("reasoning_effort").is_none()); |
| 6679 | } |
| 6680 | |
| 6681 | #[test] |
| 6682 | fn direct_moonshot_k3_uses_modern_token_field_and_fixed_sampling_only_on_exact_route() { |
| 6683 | let mut direct = json!({ |
| 6684 | "max_tokens": 64, |
| 6685 | "temperature": 0.2, |
| 6686 | "top_p": 0.9, |
| 6687 | }); |
| 6688 | apply_provider_token_limit( |
| 6689 | &mut direct, |
| 6690 | ProviderKind::Moonshot, |
| 6691 | codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL, |
| 6692 | codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL, |
| 6693 | 64, |
| 6694 | ); |
| 6695 | apply_direct_moonshot_k3_fixed_sampling( |
| 6696 | &mut direct, |
| 6697 | ProviderKind::Moonshot, |
| 6698 | codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL, |
| 6699 | codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL, |
| 6700 | ); |
| 6701 | assert_eq!(direct["max_completion_tokens"], json!(64)); |
| 6702 | assert!(direct.get("max_tokens").is_none()); |
| 6703 | assert!(direct.get("temperature").is_none()); |
| 6704 | assert!(direct.get("top_p").is_none()); |
| 6705 | |
| 6706 | let mut neighbor = json!({ |
| 6707 | "max_tokens": 64, |
| 6708 | "temperature": 0.2, |
| 6709 | "top_p": 0.9, |
| 6710 | }); |
| 6711 | apply_provider_token_limit( |
| 6712 | &mut neighbor, |
| 6713 | ProviderKind::Moonshot, |
| 6714 | "https://proxy.example/v1", |
| 6715 | codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL, |
| 6716 | 64, |
| 6717 | ); |
| 6718 | apply_direct_moonshot_k3_fixed_sampling( |
| 6719 | &mut neighbor, |
| 6720 | ProviderKind::Moonshot, |
| 6721 | "https://proxy.example/v1", |
| 6722 | codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL, |
| 6723 | ); |
| 6724 | assert_eq!(neighbor["max_tokens"], json!(64)); |
| 6725 | assert!(neighbor.get("max_completion_tokens").is_none()); |
| 6726 | assert_eq!(neighbor["temperature"], json!(0.2)); |
| 6727 | assert_eq!(neighbor["top_p"], json!(0.9)); |
| 6728 | } |
| 6729 | |
| 6730 | #[test] |
| 6731 | fn direct_and_membership_k3_reasoning_dialects_do_not_cross_routes() { |
| 6732 | let mut membership = json!({}); |
| 6733 | apply_route_reasoning_controls( |
| 6734 | &mut membership, |
| 6735 | ProviderKind::Moonshot, |
| 6736 | codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL, |
| 6737 | codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL, |
| 6738 | Some("max"), |
| 6739 | ); |
| 6740 | assert_eq!( |
| 6741 | membership["thinking"], |
| 6742 | json!({ "type": "enabled", "effort": "max" }) |
| 6743 | ); |
| 6744 | assert!(membership.get("reasoning_effort").is_none()); |
| 6745 | |
| 6746 | for (base_url, model) in [ |
| 6747 | ( |
| 6748 | codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL, |
| 6749 | codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL, |
| 6750 | ), |
| 6751 | ( |
| 6752 | codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL, |
| 6753 | codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL, |
| 6754 | ), |
| 6755 | ( |
| 6756 | "https://proxy.example/v1", |
| 6757 | codewhale_config::catalog::reviewed::constants::MOONSHOT_KIMI_K3_MODEL, |
| 6758 | ), |
| 6759 | ] { |
| 6760 | let mut neighbor = json!({}); |
| 6761 | apply_route_reasoning_controls( |
| 6762 | &mut neighbor, |
| 6763 | ProviderKind::Moonshot, |
| 6764 | base_url, |
| 6765 | model, |
| 6766 | Some("max"), |
| 6767 | ); |
| 6768 | assert_eq!( |
| 6769 | neighbor["thinking"], |
| 6770 | json!({ "type": "enabled" }), |
| 6771 | "{base_url} / {model}" |
| 6772 | ); |
| 6773 | assert!(neighbor.get("reasoning_effort").is_none()); |
| 6774 | assert!(neighbor.pointer("/thinking/effort").is_none()); |
| 6775 | } |
| 6776 | } |
| 6777 | |
| 6778 | #[test] |
| 6779 | fn kimi_code_k3_effort_override_never_leaks_to_neighbor_routes() { |
| 6780 | for (base_url, model) in [ |
| 6781 | ( |
| 6782 | codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL, |
| 6783 | "kimi-k3", |
| 6784 | ), |
| 6785 | ( |
| 6786 | codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL, |
| 6787 | codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_MODEL, |
| 6788 | ), |
| 6789 | ( |
| 6790 | codewhale_config::descriptors::defaults::DEFAULT_MOONSHOT_BASE_URL, |
| 6791 | "k3", |
| 6792 | ), |
| 6793 | ] { |
| 6794 | let mut body = json!({ "thinking": { "type": "enabled" } }); |
| 6795 | apply_kimi_code_k3_reasoning_effort( |
| 6796 | &mut body, |
| 6797 | ProviderKind::Moonshot, |
| 6798 | base_url, |
| 6799 | model, |
| 6800 | Some("max"), |
| 6801 | ); |
| 6802 | |
| 6803 | assert_eq!(body["thinking"], json!({ "type": "enabled" })); |
| 6804 | assert!( |
| 6805 | body.pointer("/thinking/effort").is_none(), |
| 6806 | "{base_url} / {model}" |
| 6807 | ); |
| 6808 | assert!(body.get("reasoning_effort").is_none()); |
| 6809 | } |
| 6810 | } |
| 6811 | |
| 6812 | #[test] |
| 6813 | fn muse_spark_uses_meta_reasoning_effort_without_openai_token_rewrite() { |
| 6814 | let mut body = json!({ |
| 6815 | "model": "muse-spark-1.1", |
| 6816 | "messages": [], |
| 6817 | "max_tokens": 8192, |
| 6818 | }); |
| 6819 | |
| 6820 | apply_provider_token_limit( |
| 6821 | &mut body, |
| 6822 | ProviderKind::Meta, |
| 6823 | "https://api.meta.ai/v1", |
| 6824 | "muse-spark-1.1", |
| 6825 | 8192, |
| 6826 | ); |
| 6827 | apply_openai_reasoning_effort(&mut body, ProviderKind::Meta, "muse-spark-1.1", Some("max")); |
| 6828 | |
| 6829 | assert_eq!(body["max_tokens"], json!(8192)); |
| 6830 | assert!(body.get("max_completion_tokens").is_none()); |
| 6831 | assert_eq!(body["reasoning_effort"], json!("xhigh")); |
| 6832 | } |
| 6833 | |
| 6834 | #[test] |
| 6835 | fn provider_regression_5853_muse_family_preserves_reasoning_effort() { |
| 6836 | for model in [ |
| 6837 | "muse-spark-1.2", |
| 6838 | "muse-spark-1.3", |
| 6839 | "muse-spark-1.3-contributor", |
| 6840 | " MUSE-SPARK-1.3 ", |
| 6841 | ] { |
| 6842 | for (effort, wire) in [ |
| 6843 | ("low", "low"), |
| 6844 | ("medium", "medium"), |
| 6845 | ("high", "high"), |
| 6846 | ("xhigh", "xhigh"), |
| 6847 | ("max", "xhigh"), |
| 6848 | ("ultra", "xhigh"), |
| 6849 | ] { |
| 6850 | let mut body = json!({"model": model}); |
| 6851 | apply_openai_reasoning_effort(&mut body, ProviderKind::Meta, model, Some(effort)); |
| 6852 | assert_eq!(body["reasoning_effort"], wire, "{model}, effort={effort}"); |
| 6853 | } |
| 6854 | } |
| 6855 | for (provider, model, effort) in [ |
| 6856 | (ProviderKind::Openai, "muse-spark-1.3", Some("high")), |
| 6857 | (ProviderKind::Meta, "muse-glimmer-fixture", Some("high")), |
| 6858 | (ProviderKind::Meta, "muse-sparks-fixture", Some("high")), |
| 6859 | (ProviderKind::Meta, "muse-spark-1.3", None), |
| 6860 | ] { |
| 6861 | let mut body = json!({"model": model}); |
| 6862 | apply_openai_reasoning_effort(&mut body, provider, model, effort); |
| 6863 | assert!( |
| 6864 | body.get("reasoning_effort").is_none(), |
| 6865 | "{provider:?}, {model}" |
| 6866 | ); |
| 6867 | } |
| 6868 | } |
| 6869 | |
| 6870 | #[test] |
| 6871 | fn openai_non_reasoning_model_omits_reasoning_only_fields() { |
| 6872 | let mut body = json!({ |
| 6873 | "model": "gpt-4o", |
| 6874 | "messages": [], |
| 6875 | "max_tokens": 4096, |
| 6876 | }); |
| 6877 | |
| 6878 | apply_provider_token_limit( |
| 6879 | &mut body, |
| 6880 | ProviderKind::Openai, |
| 6881 | "https://api.openai.com/v1", |
| 6882 | "gpt-4o", |
| 6883 | 4096, |
| 6884 | ); |
| 6885 | apply_openai_reasoning_effort(&mut body, ProviderKind::Openai, "gpt-4o", Some("high")); |
| 6886 | |
| 6887 | assert_eq!( |
| 6888 | body.get("max_tokens").and_then(serde_json::Value::as_u64), |
| 6889 | Some(4096) |
| 6890 | ); |
| 6891 | assert!(body.get("max_completion_tokens").is_none()); |
| 6892 | assert!(body.get("reasoning_effort").is_none()); |
| 6893 | } |
| 6894 | |
| 6895 | #[test] |
| 6896 | fn openai_provider_deepseek_compatible_model_keeps_chat_token_field() { |
| 6897 | let mut body = json!({ |
| 6898 | "model": "deepseek-v4-pro", |
| 6899 | "messages": [], |
| 6900 | "max_tokens": 4096, |
| 6901 | }); |
| 6902 | |
| 6903 | apply_provider_token_limit( |
| 6904 | &mut body, |
| 6905 | ProviderKind::Openai, |
| 6906 | "https://api.openai.com/v1", |
| 6907 | "deepseek-v4-pro", |
| 6908 | 4096, |
| 6909 | ); |
| 6910 | apply_openai_reasoning_effort( |
| 6911 | &mut body, |
| 6912 | ProviderKind::Openai, |
| 6913 | "deepseek-v4-pro", |
| 6914 | Some("high"), |
| 6915 | ); |
| 6916 | |
| 6917 | assert_eq!( |
| 6918 | body.get("max_tokens").and_then(serde_json::Value::as_u64), |
| 6919 | Some(4096) |
| 6920 | ); |
| 6921 | assert!(body.get("max_completion_tokens").is_none()); |
| 6922 | assert!(body.get("reasoning_effort").is_none()); |
| 6923 | } |
| 6924 | |
| 6925 | #[test] |
| 6926 | fn deepseek_model_on_openai_provider_still_replays_reasoning_content() { |
| 6927 | // #1739 / #1694: a DeepSeek thinking model pointed at a |
| 6928 | // DeepSeek-compatible endpoint via the generic `openai` provider must |
| 6929 | // still replay reasoning_content, even though the provider itself does |
| 6930 | // not accept the field. Otherwise the thinking-mode API returns 400. |
| 6931 | assert!(should_replay_reasoning_content_for_provider( |
| 6932 | ProviderKind::Openai, |
| 6933 | "deepseek-v4-flash", |
| 6934 | None, |
| 6935 | )); |
| 6936 | assert!(should_replay_reasoning_content_for_provider( |
| 6937 | ProviderKind::Openai, |
| 6938 | "deepseek-v4-pro", |
| 6939 | None, |
| 6940 | )); |
| 6941 | assert!(should_replay_reasoning_content_for_provider( |
| 6942 | ProviderKind::Openai, |
| 6943 | "deepseek-reasoner", |
| 6944 | Some("medium"), |
| 6945 | )); |
| 6946 | // The documented escape hatch still wins over model detection. |
| 6947 | assert!(!should_replay_reasoning_content_for_provider( |
| 6948 | ProviderKind::Openai, |
| 6949 | "deepseek-v4-flash", |
| 6950 | Some("off"), |
| 6951 | )); |
| 6952 | } |
| 6953 | |
| 6954 | #[test] |
| 6955 | fn generic_model_on_openai_provider_still_strips_reasoning_content() { |
| 6956 | // #1542 no-regression guard: a genuine non-DeepSeek model on the |
| 6957 | // openai provider must continue to have reasoning_content stripped. |
| 6958 | assert!(!should_replay_reasoning_content_for_provider( |
| 6959 | ProviderKind::Openai, |
| 6960 | "qwen3-coder", |
| 6961 | None, |
| 6962 | )); |
| 6963 | assert!(!should_replay_reasoning_content_for_provider( |
| 6964 | ProviderKind::Openai, |
| 6965 | "claude-sonnet-4-6", |
| 6966 | None, |
| 6967 | )); |
| 6968 | } |
| 6969 | |
| 6970 | #[test] |
| 6971 | fn suggestive_unknown_model_names_never_authorize_reasoning_replay() { |
| 6972 | for provider in [ |
| 6973 | ProviderKind::Openai, |
| 6974 | ProviderKind::Deepseek, |
| 6975 | ProviderKind::Openrouter, |
| 6976 | ProviderKind::Moonshot, |
| 6977 | ProviderKind::Zai, |
| 6978 | ] { |
| 6979 | for model in [ |
| 6980 | "foo-thinking", |
| 6981 | "foo-reasoner", |
| 6982 | "acme-reasoning", |
| 6983 | "future-reasoner-v9", |
| 6984 | ] { |
| 6985 | assert!( |
| 6986 | !should_replay_reasoning_content_for_provider(provider, model, None), |
| 6987 | "{provider:?} {model}" |
| 6988 | ); |
| 6989 | } |
| 6990 | } |
| 6991 | } |
| 6992 | |
| 6993 | #[test] |
| 6994 | fn stream_classifies_deepseek_model_on_openai_provider_as_reasoning() { |
| 6995 | // #1739: the SSE parser must treat a DeepSeek thinking model on the |
| 6996 | // generic `openai` provider (DeepSeek-compatible endpoint) as a |
| 6997 | // reasoning model, or incoming `reasoning_content` tokens are stored |
| 6998 | // as answer text and the subsequent replay still 400s. |
| 6999 | assert!(is_reasoning_model_for_stream( |
| 7000 | ProviderKind::Openai, |
| 7001 | "deepseek-v4-flash" |
| 7002 | )); |
| 7003 | assert!(is_reasoning_model_for_stream( |
| 7004 | ProviderKind::Openai, |
| 7005 | "deepseek-v4-pro" |
| 7006 | )); |
| 7007 | assert!(is_reasoning_model_for_stream( |
| 7008 | ProviderKind::Openai, |
| 7009 | "deepseek-reasoner" |
| 7010 | )); |
| 7011 | // Native DeepSeek provider was already correct; stays correct. |
| 7012 | assert!(is_reasoning_model_for_stream( |
| 7013 | ProviderKind::Deepseek, |
| 7014 | "deepseek-v4-pro" |
| 7015 | )); |
| 7016 | } |
| 7017 | |
| 7018 | #[test] |
| 7019 | fn zai_tiered_effort_applies_to_glm_5_2_and_glm_5_3_but_not_5_1() { |
| 7020 | let zai = codewhale_config::descriptors::defaults::DEFAULT_ZAI_BASE_URL; |
| 7021 | // GLM-5.3 and GLM-5.3-Flash inherit GLM-5.2's reasoning_options |
| 7022 | // (effort high/max), so they must take the same tiered wire path. |
| 7023 | for base_url in [zai, "https://open.bigmodel.cn/api/coding/paas/v4"] { |
| 7024 | for model in [ |
| 7025 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL, |
| 7026 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_3_MODEL, |
| 7027 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_3_FLASH_MODEL, |
| 7028 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_4_MODEL, |
| 7029 | ] { |
| 7030 | let mut body = json!({}); |
| 7031 | apply_route_reasoning_controls( |
| 7032 | &mut body, |
| 7033 | ProviderKind::Zai, |
| 7034 | base_url, |
| 7035 | model, |
| 7036 | Some("max"), |
| 7037 | ); |
| 7038 | assert_eq!(body["reasoning_effort"], json!("max"), "{model} at max"); |
| 7039 | |
| 7040 | let mut body = json!({}); |
| 7041 | apply_route_reasoning_controls( |
| 7042 | &mut body, |
| 7043 | ProviderKind::Zai, |
| 7044 | base_url, |
| 7045 | model, |
| 7046 | Some("high"), |
| 7047 | ); |
| 7048 | assert_eq!(body["reasoning_effort"], json!("high"), "{model} at high"); |
| 7049 | } |
| 7050 | } |
| 7051 | let mut glm54_off = json!({"thinking": {"type": "disabled"}}); |
| 7052 | apply_route_reasoning_controls( |
| 7053 | &mut glm54_off, |
| 7054 | ProviderKind::Zai, |
| 7055 | "https://open.bigmodel.cn/api/coding/paas/v4", |
| 7056 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_4_MODEL, |
| 7057 | Some("off"), |
| 7058 | ); |
| 7059 | assert_eq!(glm54_off["thinking"]["type"], json!("disabled")); |
| 7060 | assert!(glm54_off.get("reasoning_effort").is_none()); |
| 7061 | |
| 7062 | // GLM-5.1 and GLM-5-Turbo keep only the generic thinking control. |
| 7063 | for model in [ |
| 7064 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_1_MODEL, |
| 7065 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_TURBO_MODEL, |
| 7066 | ] { |
| 7067 | let mut body = json!({}); |
| 7068 | apply_route_reasoning_controls(&mut body, ProviderKind::Zai, zai, model, Some("max")); |
| 7069 | assert!( |
| 7070 | body.get("reasoning_effort").is_none(), |
| 7071 | "{model} must not receive tiered effort" |
| 7072 | ); |
| 7073 | } |
| 7074 | |
| 7075 | // A compatible gateway is not evidence of the Z.ai dialect, for 5.3 |
| 7076 | // exactly as for 5.2. |
| 7077 | let mut body = json!({"thinking": {"type": "enabled"}}); |
| 7078 | apply_route_reasoning_controls( |
| 7079 | &mut body, |
| 7080 | ProviderKind::Zai, |
| 7081 | "https://gateway.example.com/v1", |
| 7082 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_3_MODEL, |
| 7083 | Some("max"), |
| 7084 | ); |
| 7085 | assert!(body.get("reasoning_effort").is_none()); |
| 7086 | assert!(body.get("thinking").is_none()); |
| 7087 | } |
| 7088 | |
| 7089 | #[test] |
| 7090 | fn zai_forced_thinking_models_never_send_thinking_disabled() { |
| 7091 | // BigModel and Z.ai document GLM-5.3 / GLM-5.3-Flash as forced-thinking: |
| 7092 | // `thinking.type: "disabled"` errors, effort accepts only low/high/max, |
| 7093 | // and the migration note for a former `disabled` payload is |
| 7094 | // `enabled` + `reasoning_effort: "low"`. Both hosts of the first-party |
| 7095 | // open platform — api.z.ai and open.bigmodel.cn — get the rewrite. |
| 7096 | for zai in [ |
| 7097 | codewhale_config::descriptors::defaults::DEFAULT_ZAI_BASE_URL, |
| 7098 | "https://open.bigmodel.cn/api/paas/v4", |
| 7099 | ] { |
| 7100 | for model in [ |
| 7101 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_3_MODEL, |
| 7102 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_3_FLASH_MODEL, |
| 7103 | ] { |
| 7104 | let mut body = json!({}); |
| 7105 | apply_route_reasoning_controls( |
| 7106 | &mut body, |
| 7107 | ProviderKind::Zai, |
| 7108 | zai, |
| 7109 | model, |
| 7110 | Some("off"), |
| 7111 | ); |
| 7112 | assert_eq!( |
| 7113 | body["thinking"]["type"], |
| 7114 | json!("enabled"), |
| 7115 | "{model} must not send the rejected disabled toggle" |
| 7116 | ); |
| 7117 | assert_eq!( |
| 7118 | body["reasoning_effort"], |
| 7119 | json!("low"), |
| 7120 | "{model} off becomes low" |
| 7121 | ); |
| 7122 | |
| 7123 | let mut body = json!({}); |
| 7124 | apply_route_reasoning_controls( |
| 7125 | &mut body, |
| 7126 | ProviderKind::Zai, |
| 7127 | zai, |
| 7128 | model, |
| 7129 | Some("low"), |
| 7130 | ); |
| 7131 | assert_eq!( |
| 7132 | body["reasoning_effort"], |
| 7133 | json!("low"), |
| 7134 | "{model} low is native" |
| 7135 | ); |
| 7136 | |
| 7137 | let mut body = json!({}); |
| 7138 | apply_route_reasoning_controls( |
| 7139 | &mut body, |
| 7140 | ProviderKind::Zai, |
| 7141 | zai, |
| 7142 | model, |
| 7143 | Some("medium"), |
| 7144 | ); |
| 7145 | assert_eq!( |
| 7146 | body["reasoning_effort"], |
| 7147 | json!("high"), |
| 7148 | "{model} medium maps to high" |
| 7149 | ); |
| 7150 | |
| 7151 | let mut body = json!({}); |
| 7152 | apply_route_reasoning_controls( |
| 7153 | &mut body, |
| 7154 | ProviderKind::Zai, |
| 7155 | zai, |
| 7156 | model, |
| 7157 | Some("max"), |
| 7158 | ); |
| 7159 | assert_eq!( |
| 7160 | body["reasoning_effort"], |
| 7161 | json!("max"), |
| 7162 | "{model} max stays max" |
| 7163 | ); |
| 7164 | |
| 7165 | // Unknown legacy values leave the field omitted so the API keeps |
| 7166 | // its documented default; nothing may reintroduce `disabled`. |
| 7167 | let mut body = json!({}); |
| 7168 | apply_route_reasoning_controls( |
| 7169 | &mut body, |
| 7170 | ProviderKind::Zai, |
| 7171 | zai, |
| 7172 | model, |
| 7173 | Some("auto"), |
| 7174 | ); |
| 7175 | assert!( |
| 7176 | body.get("reasoning_effort").is_none(), |
| 7177 | "{model} auto stays omitted" |
| 7178 | ); |
| 7179 | assert_ne!(body["thinking"]["type"], json!("disabled")); |
| 7180 | } |
| 7181 | |
| 7182 | // GLM-5.2 honours the generic disabled toggle on both hosts. On |
| 7183 | // BigModel that toggle now reaches the API (its docs still list |
| 7184 | // `disabled` for GLM-5.2) instead of being stripped by the |
| 7185 | // fail-closed gateway path. |
| 7186 | let mut body = json!({}); |
| 7187 | apply_route_reasoning_controls( |
| 7188 | &mut body, |
| 7189 | ProviderKind::Zai, |
| 7190 | zai, |
| 7191 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL, |
| 7192 | Some("off"), |
| 7193 | ); |
| 7194 | assert_eq!(body["thinking"]["type"], json!("disabled")); |
| 7195 | assert!(body.get("reasoning_effort").is_none()); |
| 7196 | } |
| 7197 | } |
| 7198 | |
| 7199 | #[test] |
| 7200 | fn zai_bigmodel_adjacent_routes_stay_fail_closed() { |
| 7201 | // BigModel's `/preview` product and a plain-http neighbor are not the |
| 7202 | // documented Chat dialect, so they keep the gateway treatment: no |
| 7203 | // Z.ai reasoning fields, including on a forced-thinking model. |
| 7204 | for neighboring_route in [ |
| 7205 | "https://open.bigmodel.cn/api/paas/v4/preview", |
| 7206 | "http://open.bigmodel.cn/api/paas/v4", |
| 7207 | ] { |
| 7208 | let mut body = json!({"thinking": {"type": "enabled"}}); |
| 7209 | apply_route_reasoning_controls( |
| 7210 | &mut body, |
| 7211 | ProviderKind::Zai, |
| 7212 | neighboring_route, |
| 7213 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_3_MODEL, |
| 7214 | Some("max"), |
| 7215 | ); |
| 7216 | assert!( |
| 7217 | body.get("reasoning_effort").is_none(), |
| 7218 | "{neighboring_route} must not gain tiered effort" |
| 7219 | ); |
| 7220 | assert!( |
| 7221 | body.get("thinking").is_none(), |
| 7222 | "{neighboring_route} must not keep the Z.ai thinking object" |
| 7223 | ); |
| 7224 | } |
| 7225 | } |
| 7226 | |
| 7227 | #[test] |
| 7228 | fn stream_classifies_known_large_reasoning_models_as_reasoning() { |
| 7229 | // Xiaomi MiMo and OpenRouter/Qwen/Trinity can stream private reasoning through a |
| 7230 | // `reasoning` delta without using a DeepSeek-looking model name. The |
| 7231 | // renderer must still route that field into Thinking cells instead |
| 7232 | // of plain assistant prose. |
| 7233 | assert!( |
| 7234 | is_reasoning_model_for_stream(ProviderKind::XiaomiMimo, "mimo-v2.5-pro"), |
| 7235 | "mimo-v2.5-pro should stream reasoning as thinking on Xiaomi MiMo" |
| 7236 | ); |
| 7237 | assert!( |
| 7238 | is_reasoning_model_for_stream(ProviderKind::Arcee, "trinity-large-thinking"), |
| 7239 | "trinity-large-thinking should stream reasoning as thinking on direct Arcee" |
| 7240 | ); |
| 7241 | assert!( |
| 7242 | is_reasoning_model_for_stream(ProviderKind::Zai, "GLM-5.2"), |
| 7243 | "GLM-5.2 should stream reasoning_content as thinking on direct Z.ai" |
| 7244 | ); |
| 7245 | assert!( |
| 7246 | is_reasoning_model_for_stream(ProviderKind::Zai, "GLM-5.3"), |
| 7247 | "GLM-5.3 inherits GLM-5.2's reasoning capability on direct Z.ai" |
| 7248 | ); |
| 7249 | for model in [ |
| 7250 | "arcee-ai/trinity-large-thinking", |
| 7251 | "minimax/minimax-m3", |
| 7252 | "xiaomi/mimo-v2.5-pro", |
| 7253 | ] { |
| 7254 | assert!( |
| 7255 | is_reasoning_model_for_stream(ProviderKind::Openrouter, model), |
| 7256 | "{model} should stream reasoning as thinking on OpenRouter" |
| 7257 | ); |
| 7258 | } |
| 7259 | } |
| 7260 | |
| 7261 | #[test] |
| 7262 | fn stream_surfaces_reasoning_fields_on_every_unconfigured_route() { |
| 7263 | // #6501: grok-4.7 on xAI and a MiMo id newer than the offline catalog |
| 7264 | // streamed their reasoning as answer prose because the stream gate |
| 7265 | // required a provider allowlist AND a catalog row. The reasoning |
| 7266 | // fields are reasoning on every route that sends them; only an |
| 7267 | // explicit `reasoning_stream_style = "none"` restores pass-through. |
| 7268 | for (provider, model) in [ |
| 7269 | (ProviderKind::Xai, "grok-4.7"), |
| 7270 | (ProviderKind::Xai, "grok-4.6"), |
| 7271 | (ProviderKind::XiaomiMimo, "mimo-v2.7-pro-unreleased"), |
| 7272 | (ProviderKind::XiaomiMimo, "mimo-v2.6-pro"), |
| 7273 | (ProviderKind::Openai, "qwen3-coder"), |
| 7274 | (ProviderKind::Deepseek, "qwen3-coder"), |
| 7275 | (ProviderKind::Stepfun, "step-3.5"), |
| 7276 | (ProviderKind::Together, "any/model"), |
| 7277 | (ProviderKind::Ollama, "gpt-oss:20b"), |
| 7278 | (ProviderKind::Codewhale, "grok-4.7"), |
| 7279 | ] { |
| 7280 | assert!( |
| 7281 | is_reasoning_model_for_stream(provider, model), |
| 7282 | "{provider:?} {model} must surface reasoning fields as Thinking" |
| 7283 | ); |
| 7284 | } |
| 7285 | assert_eq!( |
| 7286 | super::reasoning_stream_style_for_stream(ProviderKind::Xai, "grok-4.7", Some("none")), |
| 7287 | ReasoningStreamStyle::None, |
| 7288 | "an explicit route override still wins" |
| 7289 | ); |
| 7290 | } |
| 7291 | |
| 7292 | #[test] |
| 7293 | fn xiaomi_mimo_replays_reasoning_for_every_model_id() { |
| 7294 | // #6501: MiMo returns 400 when a tool-call turn omits the assistant |
| 7295 | // `reasoning_content`, including ids newer than the offline catalog. |
| 7296 | for model in ["mimo-v2.5-pro", "mimo-v2.6-pro", "mimo-v2.7-pro-unreleased"] { |
| 7297 | assert!( |
| 7298 | should_replay_reasoning_content_for_provider(ProviderKind::XiaomiMimo, model, None), |
| 7299 | "{model}" |
| 7300 | ); |
| 7301 | } |
| 7302 | assert!(!should_replay_reasoning_content_for_provider( |
| 7303 | ProviderKind::XiaomiMimo, |
| 7304 | "mimo-v2.6-pro", |
| 7305 | Some("off"), |
| 7306 | )); |
| 7307 | } |
| 7308 | |
| 7309 | #[test] |
| 7310 | fn stream_display_does_not_authorize_reasoning_replay() { |
| 7311 | // #1542 stays fixed: rendering a reasoning delta as Thinking must not |
| 7312 | // make a provider that rejects `reasoning_content` receive it back. |
| 7313 | for (provider, model) in [ |
| 7314 | (ProviderKind::Openai, "qwen3-coder"), |
| 7315 | (ProviderKind::Openai, "claude-sonnet-4-6"), |
| 7316 | (ProviderKind::Xai, "grok-4.7"), |
| 7317 | ] { |
| 7318 | assert!(is_reasoning_model_for_stream(provider, model)); |
| 7319 | assert!( |
| 7320 | !should_replay_reasoning_content_for_provider(provider, model, None), |
| 7321 | "{provider:?} {model}" |
| 7322 | ); |
| 7323 | } |
| 7324 | } |
| 7325 | } |
| 7326 | |
| 7327 | #[cfg(test)] |
| 7328 | mod image_block_wire_tests { |
| 7329 | //! The OpenAI-compatible projection of [`ContentBlock::ImageUrl`]. |
| 7330 | //! |
| 7331 | //! Chat Completions is the wire format behind the large majority of |
| 7332 | //! CodeWhale's provider routes, so a regression here is a regression for |
| 7333 | //! most of them at once. The shape is fixed by OpenAI's spec: a `user` |
| 7334 | //! message whose `content` is an array of parts, with the image as |
| 7335 | //! `{"type":"image_url","image_url":{"url":…}}`. |
| 7336 | use super::{ |
| 7337 | ChatWireBody, ProviderKind, build_chat_messages, build_chat_wire_body, |
| 7338 | map_tool_choice_for_chat, to_api_tool_name, |
| 7339 | }; |
| 7340 | use codewhale_models::Role; |
| 7341 | use codewhale_models::{ContentBlock, ImageUrlContent, Message, MessageRequest, Tool}; |
| 7342 | use serde_json::{Value, json}; |
| 7343 | |
| 7344 | const DATA_URL: &str = "data:image/png;base64,QUJD"; |
| 7345 | |
| 7346 | #[test] |
| 7347 | fn compaction_checkpoint_keeps_complete_tool_round_on_wire() { |
| 7348 | let mut messages: Vec<Message> = serde_json::from_value(serde_json::json!([ |
| 7349 | {"role":"user","content":[{"type":"text","text":"Analyze the data"}]}, |
| 7350 | {"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"read","input":{"path":"a.txt"}}]}, |
| 7351 | {"role":"user","content":[{"type":"tool_result","tool_use_id":"call_1","content":"ready"}]}, |
| 7352 | {"role":"assistant","content":[{"type":"tool_use","id":"call_2","name":"read","input":{"path":"b.txt"}}]}, |
| 7353 | {"role":"user","content":[{"type":"tool_result","tool_use_id":"call_2","content":"done"}]} |
| 7354 | ])).unwrap(); |
| 7355 | let summary = codewhale_models::SystemPrompt::Text( |
| 7356 | crate::compaction::build_compaction_summary_block_text("Compacted summary", ""), |
| 7357 | ); |
| 7358 | messages.push(crate::compaction::compaction_checkpoint_message(&summary)); |
| 7359 | crate::runtime_handoff::replace_agent_topology_checkpoint(&mut messages, &[]); |
| 7360 | let stored = messages.clone(); |
| 7361 | let wire = build_chat_messages(None, &messages, "gpt-4o"); |
| 7362 | assert_eq!( |
| 7363 | messages, stored, |
| 7364 | "request construction must not alter saved history" |
| 7365 | ); |
| 7366 | let roles: Vec<&str> = wire |
| 7367 | .iter() |
| 7368 | .map(|message| message["role"].as_str().unwrap()) |
| 7369 | .collect(); |
| 7370 | assert_eq!(roles, ["user", "assistant", "tool", "assistant", "tool"]); |
| 7371 | let prompt = wire[0]["content"].as_str().unwrap(); |
| 7372 | assert!(prompt.contains("Compacted summary")); |
| 7373 | assert!(prompt.contains("Analyze the data")); |
| 7374 | assert!(prompt.contains("codewhale.agent_topology.v1")); |
| 7375 | assert_eq!(wire[1]["tool_calls"][0]["id"], "call_1"); |
| 7376 | assert_eq!(wire[2]["tool_call_id"], "call_1"); |
| 7377 | assert_eq!(wire[3]["tool_calls"][0]["id"], "call_2"); |
| 7378 | assert_eq!(wire[4]["tool_call_id"], "call_2"); |
| 7379 | |
| 7380 | messages.push( |
| 7381 | serde_json::from_value(serde_json::json!({ |
| 7382 | "role":"assistant","content":[{"type":"text","text":"Analysis complete"}] |
| 7383 | })) |
| 7384 | .unwrap(), |
| 7385 | ); |
| 7386 | messages.push( |
| 7387 | serde_json::from_value(serde_json::json!({ |
| 7388 | "role":"user","content":[{"type":"text","text":"What happened next?"}] |
| 7389 | })) |
| 7390 | .unwrap(), |
| 7391 | ); |
| 7392 | let later_wire = build_chat_messages(None, &messages, "gpt-4o"); |
| 7393 | let later_roles: Vec<&str> = later_wire |
| 7394 | .iter() |
| 7395 | .map(|message| message["role"].as_str().unwrap()) |
| 7396 | .collect(); |
| 7397 | assert_eq!( |
| 7398 | later_roles, |
| 7399 | [ |
| 7400 | "user", |
| 7401 | "assistant", |
| 7402 | "tool", |
| 7403 | "assistant", |
| 7404 | "tool", |
| 7405 | "assistant", |
| 7406 | "user" |
| 7407 | ] |
| 7408 | ); |
| 7409 | assert_eq!(later_wire[6]["content"], "What happened next?"); |
| 7410 | |
| 7411 | let restored = crate::compaction::restore_compaction_checkpoint( |
| 7412 | crate::runtime_handoff::project_owned_messages_for_restore(messages.clone()), |
| 7413 | Some(&summary), |
| 7414 | ); |
| 7415 | let restored_wire = build_chat_messages(None, &restored, "gpt-4o"); |
| 7416 | let restored_roles: Vec<&str> = restored_wire |
| 7417 | .iter() |
| 7418 | .map(|message| message["role"].as_str().unwrap()) |
| 7419 | .collect(); |
| 7420 | assert_eq!(restored_roles, later_roles); |
| 7421 | assert!( |
| 7422 | restored_wire[0]["content"] |
| 7423 | .as_str() |
| 7424 | .unwrap() |
| 7425 | .contains("restored Agent topology checkpoint") |
| 7426 | ); |
| 7427 | assert_eq!(restored_wire[6]["content"], "What happened next?"); |
| 7428 | } |
| 7429 | |
| 7430 | #[test] |
| 7431 | fn restore_repairs_pre_anchor_topology_sidecar_wire() { |
| 7432 | // Sessions saved before the placement anchor appended the topology |
| 7433 | // sidecar to the end of the replacement history, so a session |
| 7434 | // compacted with live agents carries `tool result, summary, sidecar`. |
| 7435 | // Request-time rewriting moves only the summary, so a sidecar left in |
| 7436 | // place reaches the wire as `tool -> user` — the shape strict paired |
| 7437 | // chat templates reject with HTTP 400. Restore relocates the sidecar |
| 7438 | // to its placement anchor, and the first request is wire-legal again. |
| 7439 | let summary = codewhale_models::SystemPrompt::Text( |
| 7440 | crate::compaction::build_compaction_summary_block_text("Compacted summary", ""), |
| 7441 | ); |
| 7442 | let mut messages: Vec<Message> = serde_json::from_value(serde_json::json!([ |
| 7443 | {"role":"user","content":[{"type":"text","text":"Analyze the data"}]}, |
| 7444 | {"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"read","input":{"path":"a.txt"}}]}, |
| 7445 | {"role":"user","content":[{"type":"tool_result","tool_use_id":"call_1","content":"ready"}]}, |
| 7446 | // The v0.9.12-era bare summary carrier: legacy marker text, no |
| 7447 | // provenance block. |
| 7448 | {"role":"user","content":[{"type":"text","text":"Another language model started to solve this problem and produced a summary of the earlier turns."}]} |
| 7449 | ])).unwrap(); |
| 7450 | let mut holder: Vec<Message> = Vec::new(); |
| 7451 | crate::runtime_handoff::replace_agent_topology_checkpoint(&mut holder, &[]); |
| 7452 | messages.push(holder.remove(0)); |
| 7453 | |
| 7454 | let restored = crate::compaction::restore_compaction_checkpoint( |
| 7455 | crate::runtime_handoff::project_owned_messages_for_restore(messages), |
| 7456 | Some(&summary), |
| 7457 | ); |
| 7458 | let wire = build_chat_messages(None, &restored, "gpt-4o"); |
| 7459 | for pair in wire.windows(2) { |
| 7460 | assert!( |
| 7461 | !(pair[0]["role"] == "tool" && pair[1]["role"] == "user"), |
| 7462 | "no user message may follow a tool result on the wire: {wire:?}" |
| 7463 | ); |
| 7464 | } |
| 7465 | let roles: Vec<&str> = wire |
| 7466 | .iter() |
| 7467 | .map(|message| message["role"].as_str().unwrap()) |
| 7468 | .collect(); |
| 7469 | assert_eq!( |
| 7470 | roles, |
| 7471 | ["user", "assistant", "tool", "assistant", "user"], |
| 7472 | "{wire:?}" |
| 7473 | ); |
| 7474 | assert_eq!(wire[3]["content"], " "); |
| 7475 | assert_eq!( |
| 7476 | wire[4]["content"], |
| 7477 | "Another language model started to solve this problem and produced a summary of the earlier turns." |
| 7478 | ); |
| 7479 | let prompt = wire[0]["content"].as_str().unwrap(); |
| 7480 | assert!(prompt.contains("Compacted summary")); |
| 7481 | assert!(prompt.contains("Analyze the data")); |
| 7482 | assert!(prompt.contains("restored Agent topology checkpoint")); |
| 7483 | |
| 7484 | let mut saved_again = restored; |
| 7485 | crate::runtime_handoff::replace_agent_topology_checkpoint(&mut saved_again, &[]); |
| 7486 | let restored_again = crate::compaction::restore_compaction_checkpoint( |
| 7487 | crate::runtime_handoff::project_owned_messages_for_restore(saved_again), |
| 7488 | Some(&summary), |
| 7489 | ); |
| 7490 | let second_wire = build_chat_messages(None, &restored_again, "gpt-4o"); |
| 7491 | assert_eq!( |
| 7492 | second_wire |
| 7493 | .iter() |
| 7494 | .map(|m| m["role"].as_str().unwrap()) |
| 7495 | .collect::<Vec<_>>(), |
| 7496 | roles |
| 7497 | ); |
| 7498 | let final_prompt = second_wire[4]["content"].as_str().unwrap(); |
| 7499 | assert!(final_prompt.starts_with(wire[4]["content"].as_str().unwrap())); |
| 7500 | assert!(final_prompt.contains("restored Agent topology checkpoint")); |
| 7501 | } |
| 7502 | |
| 7503 | #[test] |
| 7504 | fn quoted_compaction_marker_does_not_reorder_user_wire_messages() { |
| 7505 | // The current marker, and the legacy one older sessions still carry. |
| 7506 | for marker in [ |
| 7507 | codewhale_models::turn_classify::COMPACTION_SUMMARY_MARKER, |
| 7508 | codewhale_models::turn_classify::LEGACY_V2_COMPACTION_SUMMARY_MARKER, |
| 7509 | ] { |
| 7510 | let quote = format!("Please explain: {marker}"); |
| 7511 | let messages: Vec<Message> = serde_json::from_value(serde_json::json!([ |
| 7512 | {"role":"user","content":[{"type":"text","text":"First question"}]}, |
| 7513 | {"role":"assistant","content":[{"type":"text","text":"First answer"}]}, |
| 7514 | {"role":"user","content":[{"type":"text","text":quote}]}, |
| 7515 | {"role":"assistant","content":[{"type":"text","text":"It introduces a summary."}]}, |
| 7516 | {"role":"user","content":[{"type":"text","text":"Follow-up question"}]} |
| 7517 | ])) |
| 7518 | .unwrap(); |
| 7519 | let wire = build_chat_messages(None, &messages, "gpt-4o"); |
| 7520 | let roles: Vec<&str> = wire |
| 7521 | .iter() |
| 7522 | .map(|message| message["role"].as_str().unwrap()) |
| 7523 | .collect(); |
| 7524 | assert_eq!(roles, ["user", "assistant", "user", "assistant", "user"]); |
| 7525 | assert_eq!(wire[0]["content"], "First question"); |
| 7526 | assert_eq!(wire[2]["content"], quote); |
| 7527 | assert_eq!(wire[4]["content"], "Follow-up question"); |
| 7528 | } |
| 7529 | let messages: Vec<Message> = serde_json::from_value(serde_json::json!([ |
| 7530 | {"role":"user","content":[{"type":"text","text":"First question"}]}, |
| 7531 | {"role":"assistant","content":[{"type":"text","text":"First answer"}]}, |
| 7532 | {"role":"user","content":[{"type":"text","text":"placeholder"}]}, |
| 7533 | {"role":"assistant","content":[{"type":"text","text":"It introduces a summary."}]}, |
| 7534 | {"role":"user","content":[{"type":"text","text":"Follow-up question"}]} |
| 7535 | ])) |
| 7536 | .unwrap(); |
| 7537 | let roles = ["user", "assistant", "user", "assistant", "user"]; |
| 7538 | |
| 7539 | let quoted_exact_header = crate::compaction::build_compaction_summary_block_text( |
| 7540 | "This text was pasted by a user", |
| 7541 | "", |
| 7542 | ); |
| 7543 | let mut with_exact_quote = messages.clone(); |
| 7544 | with_exact_quote[2] = Message { |
| 7545 | role: Role::User, |
| 7546 | content: vec![ContentBlock::Text { |
| 7547 | text: quoted_exact_header.clone(), |
| 7548 | cache_control: None, |
| 7549 | }], |
| 7550 | }; |
| 7551 | let exact_wire = build_chat_messages(None, &with_exact_quote, "gpt-4o"); |
| 7552 | let exact_roles: Vec<&str> = exact_wire |
| 7553 | .iter() |
| 7554 | .map(|message| message["role"].as_str().unwrap()) |
| 7555 | .collect(); |
| 7556 | assert_eq!(exact_roles, roles); |
| 7557 | assert_eq!(exact_wire[2]["content"], quoted_exact_header); |
| 7558 | |
| 7559 | let mut after_tool: Vec<Message> = serde_json::from_value(serde_json::json!([ |
| 7560 | {"role":"user","content":[{"type":"text","text":"Read first"}]}, |
| 7561 | {"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"read","input":{"path":"a.txt"}}]}, |
| 7562 | {"role":"user","content":[{"type":"tool_result","tool_use_id":"call_1","content":"contents"}]}, |
| 7563 | {"role":"user","content":[{"type":"text","text":"placeholder"}]}, |
| 7564 | {"role":"assistant","content":[{"type":"text","text":"Answer"}]} |
| 7565 | ])).unwrap(); |
| 7566 | after_tool[3] = Message { |
| 7567 | role: Role::User, |
| 7568 | content: vec![ContentBlock::Text { |
| 7569 | text: quoted_exact_header.clone(), |
| 7570 | cache_control: None, |
| 7571 | }], |
| 7572 | }; |
| 7573 | let after_tool_wire = build_chat_messages(None, &after_tool, "gpt-4o"); |
| 7574 | let after_tool_roles: Vec<&str> = after_tool_wire |
| 7575 | .iter() |
| 7576 | .map(|message| message["role"].as_str().unwrap()) |
| 7577 | .collect(); |
| 7578 | assert_eq!( |
| 7579 | after_tool_roles, |
| 7580 | ["user", "assistant", "tool", "user", "assistant"] |
| 7581 | ); |
| 7582 | assert_eq!(after_tool_wire[3]["content"], quoted_exact_header); |
| 7583 | } |
| 7584 | |
| 7585 | #[test] |
| 7586 | fn topology_checkpoint_after_tool_result_keeps_wire_tool_pair() { |
| 7587 | let mut messages: Vec<Message> = serde_json::from_value(serde_json::json!([ |
| 7588 | {"role":"user","content":[{"type":"text","text":"Read the file"}]}, |
| 7589 | {"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"read","input":{"path":"a.txt"}}]}, |
| 7590 | {"role":"user","content":[{"type":"tool_result","tool_use_id":"call_1","content":"contents"}]} |
| 7591 | ])).unwrap(); |
| 7592 | crate::runtime_handoff::replace_agent_topology_checkpoint(&mut messages, &[]); |
| 7593 | let wire = build_chat_messages(None, &messages, "gpt-4o"); |
| 7594 | let roles: Vec<&str> = wire |
| 7595 | .iter() |
| 7596 | .map(|message| message["role"].as_str().unwrap()) |
| 7597 | .collect(); |
| 7598 | assert_eq!(roles, ["user", "assistant", "tool"]); |
| 7599 | assert!( |
| 7600 | wire[0]["content"] |
| 7601 | .as_str() |
| 7602 | .unwrap() |
| 7603 | .contains("agent_topology_v1") |
| 7604 | ); |
| 7605 | assert_eq!(wire[1]["tool_calls"][0]["id"], "call_1"); |
| 7606 | assert_eq!(wire[2]["tool_call_id"], "call_1"); |
| 7607 | } |
| 7608 | |
| 7609 | #[test] |
| 7610 | fn compaction_without_retained_user_has_one_wire_user_before_tools() { |
| 7611 | let mut messages: Vec<Message> = serde_json::from_value(serde_json::json!([ |
| 7612 | {"role":"assistant","content":[{"type":"tool_use","id":"call_1","name":"read","input":{"path":"a.txt"}}]}, |
| 7613 | {"role":"user","content":[{"type":"tool_result","tool_use_id":"call_1","content":"contents"}]} |
| 7614 | ])).unwrap(); |
| 7615 | let summary = codewhale_models::SystemPrompt::Text( |
| 7616 | crate::compaction::build_compaction_summary_block_text("Summary", ""), |
| 7617 | ); |
| 7618 | messages.push(crate::compaction::compaction_checkpoint_message(&summary)); |
| 7619 | crate::runtime_handoff::replace_agent_topology_checkpoint(&mut messages, &[]); |
| 7620 | let wire = build_chat_messages(None, &messages, "gpt-4o"); |
| 7621 | let roles: Vec<&str> = wire |
| 7622 | .iter() |
| 7623 | .map(|message| message["role"].as_str().unwrap()) |
| 7624 | .collect(); |
| 7625 | assert_eq!(roles, ["user", "assistant", "tool"]); |
| 7626 | let prompt = wire[0]["content"].as_str().unwrap(); |
| 7627 | assert!(prompt.contains("Summary")); |
| 7628 | assert!(prompt.contains("agent_topology_v1")); |
| 7629 | assert_eq!(wire[2]["tool_call_id"], "call_1"); |
| 7630 | } |
| 7631 | |
| 7632 | #[test] |
| 7633 | fn compaction_after_unanswered_user_prompt_has_one_wire_user() { |
| 7634 | let mut messages: Vec<Message> = serde_json::from_value(serde_json::json!([ |
| 7635 | {"role":"user","content":[{"type":"text","text":"Please continue"}]} |
| 7636 | ])) |
| 7637 | .unwrap(); |
| 7638 | let summary = codewhale_models::SystemPrompt::Text( |
| 7639 | crate::compaction::build_compaction_summary_block_text("Earlier work", ""), |
| 7640 | ); |
| 7641 | messages.push(crate::compaction::compaction_checkpoint_message(&summary)); |
| 7642 | crate::runtime_handoff::replace_agent_topology_checkpoint(&mut messages, &[]); |
| 7643 | let wire = build_chat_messages(None, &messages, "gpt-4o"); |
| 7644 | assert_eq!(wire.len(), 1); |
| 7645 | assert_eq!(wire[0]["role"], "user"); |
| 7646 | let prompt = wire[0]["content"].as_str().unwrap(); |
| 7647 | assert!(prompt.contains("Please continue")); |
| 7648 | assert!(prompt.contains("Earlier work")); |
| 7649 | assert!(prompt.contains("agent_topology_v1")); |
| 7650 | } |
| 7651 | |
| 7652 | fn fixture_tool_use(id: &str) -> ContentBlock { |
| 7653 | ContentBlock::ToolUse { |
| 7654 | execution_id: None, |
| 7655 | id: id.to_string(), |
| 7656 | name: "read".to_string(), |
| 7657 | input: serde_json::json!({"path": format!("{id}.txt")}), |
| 7658 | caller: None, |
| 7659 | thought_signature: None, |
| 7660 | } |
| 7661 | } |
| 7662 | |
| 7663 | fn fixture_tool_result(id: &str) -> Message { |
| 7664 | Message { |
| 7665 | role: Role::User, |
| 7666 | content: vec![ContentBlock::ToolResult { |
| 7667 | execution_id: None, |
| 7668 | tool_use_id: id.to_string(), |
| 7669 | content: format!("result for {id}"), |
| 7670 | is_error: Some(false), |
| 7671 | content_blocks: None, |
| 7672 | }], |
| 7673 | } |
| 7674 | } |
| 7675 | |
| 7676 | fn named_tool(name: &str) -> Tool { |
| 7677 | Tool { |
| 7678 | tool_type: None, |
| 7679 | name: name.to_string(), |
| 7680 | description: "d".to_string(), |
| 7681 | input_schema: json!({"type": "object", "additionalProperties": false}), |
| 7682 | allowed_callers: None, |
| 7683 | defer_loading: None, |
| 7684 | input_examples: None, |
| 7685 | strict: None, |
| 7686 | cache_control: None, |
| 7687 | } |
| 7688 | } |
| 7689 | |
| 7690 | #[test] |
| 7691 | fn function_object_tool_choice_encodes_the_tool_name() { |
| 7692 | let encoded = to_api_tool_name("web.run"); |
| 7693 | assert_eq!(encoded, "web-x00002E-run"); |
| 7694 | let expected = json!({"type": "function", "function": {"name": encoded}}); |
| 7695 | for choice in [ |
| 7696 | json!({"type": "function", "function": {"name": "web.run"}}), |
| 7697 | json!({"type": "function", "name": "web.run"}), |
| 7698 | json!({"type": "tool", "name": "web.run"}), |
| 7699 | json!("web.run"), |
| 7700 | ] { |
| 7701 | assert_eq!( |
| 7702 | map_tool_choice_for_chat(&choice), |
| 7703 | Some(expected.clone()), |
| 7704 | "{choice}" |
| 7705 | ); |
| 7706 | } |
| 7707 | assert_eq!( |
| 7708 | map_tool_choice_for_chat(&json!("required")), |
| 7709 | Some(json!("required")) |
| 7710 | ); |
| 7711 | |
| 7712 | let mut request = request_with_image(); |
| 7713 | request.tools = Some(vec![named_tool("read_file"), named_tool("web.run")]); |
| 7714 | request.tool_choice = Some(json!({"type": "function", "function": {"name": "web.run"}})); |
| 7715 | let body = build_chat_wire_body( |
| 7716 | &request, |
| 7717 | ProviderKind::Openai, |
| 7718 | "https://api.openai.com/v1", |
| 7719 | false, |
| 7720 | None, |
| 7721 | ) |
| 7722 | .expect("wire body"); |
| 7723 | assert_eq!(body.body["tool_choice"], expected); |
| 7724 | let declared: Vec<&str> = body.body["tools"] |
| 7725 | .as_array() |
| 7726 | .expect("tools") |
| 7727 | .iter() |
| 7728 | .filter_map(|tool| tool.pointer("/function/name").and_then(Value::as_str)) |
| 7729 | .collect(); |
| 7730 | assert!(declared.contains(&"web-x00002E-run")); |
| 7731 | } |
| 7732 | |
| 7733 | #[test] |
| 7734 | fn over_long_encoded_tool_names_are_withheld_by_provider_limit() { |
| 7735 | let mid = "mcp__tracker__projects.v2.issues.list-by-assignee"; |
| 7736 | let long = format!( |
| 7737 | "mcp__tracker__{}.v2.issues.list-by-assignee", |
| 7738 | "a".repeat(70) |
| 7739 | ); |
| 7740 | let mid_len = to_api_tool_name(mid).len(); |
| 7741 | assert!(mid_len > 64 && mid_len <= 128, "{mid_len}"); |
| 7742 | assert!(to_api_tool_name(&long).len() > 128); |
| 7743 | |
| 7744 | let build = |provider, base_url: &str, choice: Option<Value>| { |
| 7745 | let mut request = request_with_image(); |
| 7746 | request.tools = Some(vec![ |
| 7747 | named_tool("read_file"), |
| 7748 | named_tool(mid), |
| 7749 | named_tool(&long), |
| 7750 | ]); |
| 7751 | request.tool_choice = choice; |
| 7752 | build_chat_wire_body(&request, provider, base_url, false, None) |
| 7753 | }; |
| 7754 | let declared = |body: &ChatWireBody| -> Vec<String> { |
| 7755 | body.body["tools"] |
| 7756 | .as_array() |
| 7757 | .expect("tools") |
| 7758 | .iter() |
| 7759 | .filter_map(|tool| tool.pointer("/function/name").and_then(Value::as_str)) |
| 7760 | .map(str::to_string) |
| 7761 | .collect() |
| 7762 | }; |
| 7763 | |
| 7764 | let openai = build(ProviderKind::Openai, "https://api.openai.com/v1", None).expect("body"); |
| 7765 | assert_eq!(declared(&openai), vec!["read_file".to_string()]); |
| 7766 | assert_eq!( |
| 7767 | openai.omitted_tool_names, |
| 7768 | vec![to_api_tool_name(mid), to_api_tool_name(&long)] |
| 7769 | ); |
| 7770 | |
| 7771 | let deepseek = |
| 7772 | build(ProviderKind::Deepseek, "https://api.deepseek.com", None).expect("body"); |
| 7773 | assert_eq!( |
| 7774 | declared(&deepseek), |
| 7775 | vec!["read_file".to_string(), to_api_tool_name(mid)] |
| 7776 | ); |
| 7777 | assert_eq!(deepseek.omitted_tool_names, vec![to_api_tool_name(&long)]); |
| 7778 | |
| 7779 | let forced = json!({"type": "function", "function": {"name": mid}}); |
| 7780 | let error = build( |
| 7781 | ProviderKind::Openai, |
| 7782 | "https://api.openai.com/v1", |
| 7783 | Some(forced), |
| 7784 | ) |
| 7785 | .err() |
| 7786 | .expect("forcing a withheld tool is refused"); |
| 7787 | let message = error.to_string(); |
| 7788 | assert!( |
| 7789 | message.contains(&format!("{mid_len} characters")), |
| 7790 | "{message}" |
| 7791 | ); |
| 7792 | assert!(message.contains("at most 64"), "{message}"); |
| 7793 | } |
| 7794 | |
| 7795 | #[test] |
| 7796 | fn over_long_tool_name_in_history_is_refused_with_the_limit() { |
| 7797 | let long = "mcp__tracker__projects.v2.issues.list-by-assignee"; |
| 7798 | let mut request = request_with_image(); |
| 7799 | request.messages.push(Message { |
| 7800 | role: Role::Assistant, |
| 7801 | content: vec![ContentBlock::ToolUse { |
| 7802 | execution_id: None, |
| 7803 | id: "call_1".to_string(), |
| 7804 | name: long.to_string(), |
| 7805 | input: json!({}), |
| 7806 | caller: None, |
| 7807 | thought_signature: None, |
| 7808 | }], |
| 7809 | }); |
| 7810 | let error = build_chat_wire_body( |
| 7811 | &request, |
| 7812 | ProviderKind::Openai, |
| 7813 | "https://api.openai.com/v1", |
| 7814 | false, |
| 7815 | None, |
| 7816 | ) |
| 7817 | .err() |
| 7818 | .expect("history name over the limit is refused"); |
| 7819 | let message = error.to_string(); |
| 7820 | assert!( |
| 7821 | message.contains("at most 64") && message.contains(long), |
| 7822 | "{message}" |
| 7823 | ); |
| 7824 | build_chat_wire_body( |
| 7825 | &request, |
| 7826 | ProviderKind::Deepseek, |
| 7827 | "https://api.deepseek.com", |
| 7828 | false, |
| 7829 | None, |
| 7830 | ) |
| 7831 | .expect("the same history fits a 128-character route"); |
| 7832 | } |
| 7833 | |
| 7834 | #[test] |
| 7835 | fn history_name_of_65_to_128_characters_is_sent_unchanged_on_undocumented_routes() { |
| 7836 | let long = "mcp__tracker__projects.v2.issues.list-by-assignee"; |
| 7837 | assert!(to_api_tool_name(long).len() > 64); |
| 7838 | let mut request = request_with_image(); |
| 7839 | request.messages.push(Message { |
| 7840 | role: Role::Assistant, |
| 7841 | content: vec![ContentBlock::ToolUse { |
| 7842 | execution_id: None, |
| 7843 | id: "call_1".to_string(), |
| 7844 | name: long.to_string(), |
| 7845 | input: json!({}), |
| 7846 | caller: None, |
| 7847 | thought_signature: None, |
| 7848 | }], |
| 7849 | }); |
| 7850 | for (provider, base_url) in [ |
| 7851 | (ProviderKind::Ollama, "http://localhost:11434/v1"), |
| 7852 | (ProviderKind::Custom, "http://localhost:8000/v1"), |
| 7853 | (ProviderKind::Minimax, "https://api.minimax.io/v1"), |
| 7854 | ] { |
| 7855 | build_chat_wire_body(&request, provider, base_url, false, None) |
| 7856 | .unwrap_or_else(|error| panic!("{provider:?}: {error}")); |
| 7857 | } |
| 7858 | let error = build_chat_wire_body( |
| 7859 | &request, |
| 7860 | ProviderKind::Openai, |
| 7861 | "https://api.openai.com/v1", |
| 7862 | false, |
| 7863 | None, |
| 7864 | ) |
| 7865 | .err() |
| 7866 | .expect("documented 64-character route refuses the history name"); |
| 7867 | assert!( |
| 7868 | error.to_string().contains("earlier in this session"), |
| 7869 | "{error}" |
| 7870 | ); |
| 7871 | } |
| 7872 | |
| 7873 | #[test] |
| 7874 | fn a_100_character_encoded_name_is_withheld_on_a_chat_wire_route() { |
| 7875 | let name = "a".repeat(100); |
| 7876 | let mut request = request_with_image(); |
| 7877 | request.tools = Some(vec![named_tool("read_file"), named_tool(&name)]); |
| 7878 | let body = build_chat_wire_body( |
| 7879 | &request, |
| 7880 | ProviderKind::Minimax, |
| 7881 | "https://api.minimax.io/v1", |
| 7882 | false, |
| 7883 | None, |
| 7884 | ) |
| 7885 | .expect("wire body"); |
| 7886 | assert_eq!(body.omitted_tool_names, vec![name]); |
| 7887 | assert_eq!(body.body["tools"].as_array().expect("tools").len(), 1); |
| 7888 | } |
| 7889 | |
| 7890 | fn request_with_image() -> MessageRequest { |
| 7891 | MessageRequest { |
| 7892 | model: "gpt-4o".to_string(), |
| 7893 | messages: vec![Message { |
| 7894 | role: Role::User, |
| 7895 | content: vec![ |
| 7896 | ContentBlock::Text { |
| 7897 | text: "what is in this screenshot?".to_string(), |
| 7898 | cache_control: None, |
| 7899 | }, |
| 7900 | ContentBlock::ImageUrl { |
| 7901 | image_url: ImageUrlContent { |
| 7902 | url: DATA_URL.to_string(), |
| 7903 | }, |
| 7904 | }, |
| 7905 | ], |
| 7906 | }], |
| 7907 | max_tokens: 128, |
| 7908 | system: None, |
| 7909 | tools: None, |
| 7910 | tool_choice: None, |
| 7911 | metadata: None, |
| 7912 | thinking: None, |
| 7913 | reasoning_effort: None, |
| 7914 | stream: None, |
| 7915 | temperature: None, |
| 7916 | top_p: None, |
| 7917 | safety_check: None, |
| 7918 | title: None, |
| 7919 | } |
| 7920 | } |
| 7921 | |
| 7922 | #[test] |
| 7923 | fn user_image_becomes_a_multimodal_parts_array() { |
| 7924 | let body = build_chat_wire_body( |
| 7925 | &request_with_image(), |
| 7926 | ProviderKind::Openai, |
| 7927 | "https://api.openai.com/v1", |
| 7928 | false, |
| 7929 | None, |
| 7930 | ) |
| 7931 | .expect("wire body"); |
| 7932 | |
| 7933 | let messages = body.body["messages"].as_array().expect("messages"); |
| 7934 | let user = messages |
| 7935 | .iter() |
| 7936 | .find(|message| message["role"] == "user") |
| 7937 | .expect("a user message"); |
| 7938 | let parts = user["content"] |
| 7939 | .as_array() |
| 7940 | .expect("content must be a parts array once an image is present, not a bare string"); |
| 7941 | |
| 7942 | let image = parts |
| 7943 | .iter() |
| 7944 | .find(|part| part["type"] == "image_url") |
| 7945 | .expect("an image_url part"); |
| 7946 | assert_eq!(image["image_url"]["url"], DATA_URL); |
| 7947 | |
| 7948 | let text = parts |
| 7949 | .iter() |
| 7950 | .find(|part| part["type"] == "text") |
| 7951 | .expect("the accompanying text part"); |
| 7952 | assert!( |
| 7953 | text["text"] |
| 7954 | .as_str() |
| 7955 | .expect("text") |
| 7956 | .contains("what is in this screenshot?"), |
| 7957 | "the question must survive alongside the image: {user}" |
| 7958 | ); |
| 7959 | } |
| 7960 | |
| 7961 | #[test] |
| 7962 | fn deepseek_vision_exp_uses_chat_image_url_request_shape() { |
| 7963 | let mut request = request_with_image(); |
| 7964 | request.model = "deepseek-v4-flash-vision-exp".to_string(); |
| 7965 | |
| 7966 | let body = build_chat_wire_body( |
| 7967 | &request, |
| 7968 | ProviderKind::Deepseek, |
| 7969 | "https://api.deepseek.com/beta", |
| 7970 | false, |
| 7971 | None, |
| 7972 | ) |
| 7973 | .expect("DeepSeek vision wire body"); |
| 7974 | |
| 7975 | assert_eq!(body.body["model"], "deepseek-v4-flash-vision-exp"); |
| 7976 | let messages = body.body["messages"].as_array().expect("messages"); |
| 7977 | let user = messages |
| 7978 | .iter() |
| 7979 | .find(|message| message["role"] == "user") |
| 7980 | .expect("a user message"); |
| 7981 | let parts = user["content"] |
| 7982 | .as_array() |
| 7983 | .expect("DeepSeek vision content must use multimodal parts"); |
| 7984 | |
| 7985 | assert!(parts.iter().any(|part| { |
| 7986 | part["type"] == "text" && part["text"] == "what is in this screenshot?" |
| 7987 | })); |
| 7988 | assert!( |
| 7989 | parts.iter().any(|part| { |
| 7990 | part["type"] == "image_url" && part["image_url"]["url"] == DATA_URL |
| 7991 | }) |
| 7992 | ); |
| 7993 | } |
| 7994 | |
| 7995 | #[test] |
| 7996 | fn a_message_with_no_image_keeps_its_plain_string_content() { |
| 7997 | // Promoting every user turn to a parts array would change the request |
| 7998 | // bytes for every text-only route, and with them the prompt-cache |
| 7999 | // prefix. Images must be the only thing that triggers the array form. |
| 8000 | let mut request = request_with_image(); |
| 8001 | request.messages[0] |
| 8002 | .content |
| 8003 | .retain(|block| !matches!(block, ContentBlock::ImageUrl { .. })); |
| 8004 | |
| 8005 | let body = build_chat_wire_body( |
| 8006 | &request, |
| 8007 | ProviderKind::Openai, |
| 8008 | "https://api.openai.com/v1", |
| 8009 | false, |
| 8010 | None, |
| 8011 | ) |
| 8012 | .expect("wire body"); |
| 8013 | |
| 8014 | let messages = body.body["messages"].as_array().expect("messages"); |
| 8015 | let user = messages |
| 8016 | .iter() |
| 8017 | .find(|message| message["role"] == "user") |
| 8018 | .expect("a user message"); |
| 8019 | assert!( |
| 8020 | user["content"].is_string(), |
| 8021 | "text-only turns must stay a plain string: {user}" |
| 8022 | ); |
| 8023 | } |
| 8024 | |
| 8025 | #[test] |
| 8026 | fn tool_result_image_follows_its_tool_message_as_multimodal_user_content() { |
| 8027 | let mut request = request_with_image(); |
| 8028 | request.messages = vec![ |
| 8029 | Message { |
| 8030 | role: Role::Assistant, |
| 8031 | content: vec![ContentBlock::ToolUse { |
| 8032 | execution_id: None, |
| 8033 | id: "call_image_1".to_string(), |
| 8034 | name: "read".to_string(), |
| 8035 | input: serde_json::json!({"path": "shot.png"}), |
| 8036 | caller: None, |
| 8037 | thought_signature: None, |
| 8038 | }], |
| 8039 | }, |
| 8040 | Message { |
| 8041 | role: Role::User, |
| 8042 | content: vec![ContentBlock::ToolResult { |
| 8043 | execution_id: None, |
| 8044 | tool_use_id: "call_image_1".to_string(), |
| 8045 | content: "screenshot captured".to_string(), |
| 8046 | is_error: Some(false), |
| 8047 | content_blocks: Some(vec![serde_json::json!({ |
| 8048 | "type": "image", |
| 8049 | "mime_type": "image/png", |
| 8050 | "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==", |
| 8051 | })]), |
| 8052 | }], |
| 8053 | }, |
| 8054 | ]; |
| 8055 | |
| 8056 | let body = build_chat_wire_body( |
| 8057 | &request, |
| 8058 | ProviderKind::Openai, |
| 8059 | "https://api.openai.com/v1", |
| 8060 | false, |
| 8061 | None, |
| 8062 | ) |
| 8063 | .expect("wire body"); |
| 8064 | let messages = body.body["messages"].as_array().expect("messages"); |
| 8065 | let tool_index = messages |
| 8066 | .iter() |
| 8067 | .position(|message| message["role"] == "tool") |
| 8068 | .expect("tool result"); |
| 8069 | assert_eq!(messages[tool_index]["tool_call_id"], "call_image_1"); |
| 8070 | assert_eq!(messages[tool_index]["content"], "screenshot captured"); |
| 8071 | |
| 8072 | let image_message = &messages[tool_index + 1]; |
| 8073 | assert_eq!(image_message["role"], "user"); |
| 8074 | let parts = image_message["content"].as_array().expect("image parts"); |
| 8075 | assert_eq!(parts[1]["type"], "image_url"); |
| 8076 | assert_eq!( |
| 8077 | parts[1]["image_url"]["url"], |
| 8078 | "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==" |
| 8079 | ); |
| 8080 | assert!( |
| 8081 | parts[0]["text"] |
| 8082 | .as_str() |
| 8083 | .is_some_and(|text| text.contains("read") && text.contains("call_image_1")) |
| 8084 | ); |
| 8085 | } |
| 8086 | |
| 8087 | #[test] |
| 8088 | fn tool_result_images_follow_the_entire_tool_call_batch() { |
| 8089 | let mut request = request_with_image(); |
| 8090 | request.messages = vec![ |
| 8091 | Message { |
| 8092 | role: Role::Assistant, |
| 8093 | content: vec![ |
| 8094 | ContentBlock::ToolUse { |
| 8095 | execution_id: None, |
| 8096 | id: "call_image_1".to_string(), |
| 8097 | name: "read".to_string(), |
| 8098 | input: serde_json::json!({"path": "first.png"}), |
| 8099 | caller: None, |
| 8100 | thought_signature: None, |
| 8101 | }, |
| 8102 | ContentBlock::ToolUse { |
| 8103 | execution_id: None, |
| 8104 | id: "call_image_2".to_string(), |
| 8105 | name: "read".to_string(), |
| 8106 | input: serde_json::json!({"path": "second.png"}), |
| 8107 | caller: None, |
| 8108 | thought_signature: None, |
| 8109 | }, |
| 8110 | ], |
| 8111 | }, |
| 8112 | Message { |
| 8113 | role: Role::User, |
| 8114 | content: vec![ContentBlock::ToolResult { |
| 8115 | execution_id: None, |
| 8116 | tool_use_id: "call_image_1".to_string(), |
| 8117 | content: "first screenshot captured".to_string(), |
| 8118 | is_error: Some(false), |
| 8119 | content_blocks: Some(vec![serde_json::json!({ |
| 8120 | "type": "image", |
| 8121 | "mime_type": "image/png", |
| 8122 | "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==", |
| 8123 | })]), |
| 8124 | }], |
| 8125 | }, |
| 8126 | Message { |
| 8127 | role: Role::User, |
| 8128 | content: vec![ContentBlock::ToolResult { |
| 8129 | execution_id: None, |
| 8130 | tool_use_id: "call_image_2".to_string(), |
| 8131 | content: "second screenshot captured".to_string(), |
| 8132 | is_error: Some(false), |
| 8133 | content_blocks: Some(vec![serde_json::json!({ |
| 8134 | "type": "image", |
| 8135 | "mime_type": "image/png", |
| 8136 | "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYPj/HwADAgH/5ncLrgAAAABJRU5ErkJggg==", |
| 8137 | })]), |
| 8138 | }], |
| 8139 | }, |
| 8140 | ]; |
| 8141 | |
| 8142 | let body = build_chat_wire_body( |
| 8143 | &request, |
| 8144 | ProviderKind::Openai, |
| 8145 | "https://api.openai.com/v1", |
| 8146 | false, |
| 8147 | None, |
| 8148 | ) |
| 8149 | .expect("wire body"); |
| 8150 | let messages = body.body["messages"].as_array().expect("messages"); |
| 8151 | let roles: Vec<_> = messages |
| 8152 | .iter() |
| 8153 | .map(|message| message["role"].as_str().expect("role")) |
| 8154 | .collect(); |
| 8155 | assert_eq!(roles, ["assistant", "tool", "tool", "user"]); |
| 8156 | assert_eq!(messages[1]["tool_call_id"], "call_image_1"); |
| 8157 | assert_eq!(messages[2]["tool_call_id"], "call_image_2"); |
| 8158 | |
| 8159 | let image_parts = messages[3]["content"].as_array().expect("image parts"); |
| 8160 | assert_eq!(image_parts.len(), 4); |
| 8161 | assert_eq!( |
| 8162 | image_parts[1]["image_url"]["url"], |
| 8163 | "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==" |
| 8164 | ); |
| 8165 | assert_eq!( |
| 8166 | image_parts[3]["image_url"]["url"], |
| 8167 | "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYPj/HwADAgH/5ncLrgAAAABJRU5ErkJggg==" |
| 8168 | ); |
| 8169 | } |
| 8170 | |
| 8171 | #[test] |
| 8172 | fn out_of_order_tool_results_remain_a_contiguous_complete_batch() { |
| 8173 | let messages = vec![ |
| 8174 | Message { |
| 8175 | role: Role::Assistant, |
| 8176 | content: vec![fixture_tool_use("call_one"), fixture_tool_use("call_two")], |
| 8177 | }, |
| 8178 | fixture_tool_result("call_two"), |
| 8179 | fixture_tool_result("call_one"), |
| 8180 | ]; |
| 8181 | |
| 8182 | let wire = build_chat_messages(None, &messages, "gpt-4o"); |
| 8183 | let roles: Vec<_> = wire |
| 8184 | .iter() |
| 8185 | .map(|message| message["role"].as_str().expect("role")) |
| 8186 | .collect(); |
| 8187 | assert_eq!(roles, ["assistant", "tool", "tool"]); |
| 8188 | assert_eq!(wire[1]["tool_call_id"], "call_two"); |
| 8189 | assert_eq!(wire[2]["tool_call_id"], "call_one"); |
| 8190 | } |
| 8191 | |
| 8192 | #[test] |
| 8193 | fn incomplete_tool_result_batch_is_downgraded_before_serialization() { |
| 8194 | let messages = vec![ |
| 8195 | Message { |
| 8196 | role: Role::Assistant, |
| 8197 | content: vec![fixture_tool_use("call_one"), fixture_tool_use("call_two")], |
| 8198 | }, |
| 8199 | fixture_tool_result("call_one"), |
| 8200 | ]; |
| 8201 | |
| 8202 | let wire = build_chat_messages(None, &messages, "gpt-4o"); |
| 8203 | assert!( |
| 8204 | !wire |
| 8205 | .iter() |
| 8206 | .any(|message| message.get("tool_calls").is_some()), |
| 8207 | "an incomplete tool batch must not reach the provider: {wire:?}" |
| 8208 | ); |
| 8209 | assert!( |
| 8210 | !wire |
| 8211 | .iter() |
| 8212 | .any(|message| message["role"].as_str() == Some("tool")), |
| 8213 | "the partial result must be removed with its incomplete call batch: {wire:?}" |
| 8214 | ); |
| 8215 | } |
| 8216 | |
| 8217 | #[test] |
| 8218 | fn interleaved_tool_result_batch_is_downgraded_before_serialization() { |
| 8219 | let messages = vec![ |
| 8220 | Message { |
| 8221 | role: Role::Assistant, |
| 8222 | content: vec![ |
| 8223 | ContentBlock::ToolUse { |
| 8224 | execution_id: None, |
| 8225 | id: "call_one".to_string(), |
| 8226 | name: "read".to_string(), |
| 8227 | input: serde_json::json!({"path": "first.png"}), |
| 8228 | caller: None, |
| 8229 | thought_signature: None, |
| 8230 | }, |
| 8231 | ContentBlock::ToolUse { |
| 8232 | execution_id: None, |
| 8233 | id: "call_two".to_string(), |
| 8234 | name: "read".to_string(), |
| 8235 | input: serde_json::json!({"path": "second.png"}), |
| 8236 | caller: None, |
| 8237 | thought_signature: None, |
| 8238 | }, |
| 8239 | ], |
| 8240 | }, |
| 8241 | Message { |
| 8242 | role: Role::User, |
| 8243 | content: vec![ContentBlock::ToolResult { |
| 8244 | execution_id: None, |
| 8245 | tool_use_id: "call_one".to_string(), |
| 8246 | content: "first screenshot captured".to_string(), |
| 8247 | is_error: Some(false), |
| 8248 | content_blocks: Some(vec![serde_json::json!({ |
| 8249 | "type": "image", |
| 8250 | "mime_type": "image/png", |
| 8251 | "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==", |
| 8252 | })]), |
| 8253 | }], |
| 8254 | }, |
| 8255 | Message { |
| 8256 | role: Role::User, |
| 8257 | content: vec![ |
| 8258 | ContentBlock::Text { |
| 8259 | text: "interloper".to_string(), |
| 8260 | cache_control: None, |
| 8261 | }, |
| 8262 | ContentBlock::ToolResult { |
| 8263 | execution_id: None, |
| 8264 | tool_use_id: "call_two".to_string(), |
| 8265 | content: "second screenshot captured".to_string(), |
| 8266 | is_error: Some(false), |
| 8267 | content_blocks: Some(vec![serde_json::json!({ |
| 8268 | "type": "image", |
| 8269 | "mime_type": "image/png", |
| 8270 | "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==", |
| 8271 | })]), |
| 8272 | }, |
| 8273 | ], |
| 8274 | }, |
| 8275 | ]; |
| 8276 | |
| 8277 | let wire = build_chat_messages(None, &messages, "gpt-4o"); |
| 8278 | assert!( |
| 8279 | !wire |
| 8280 | .iter() |
| 8281 | .any(|message| message.get("tool_calls").is_some()), |
| 8282 | "a non-contiguous tool batch must not reach the provider: {wire:?}" |
| 8283 | ); |
| 8284 | assert!( |
| 8285 | !wire |
| 8286 | .iter() |
| 8287 | .any(|message| message["role"].as_str() == Some("tool")), |
| 8288 | "orphaned tool replies must be removed with their stripped call batch: {wire:?}" |
| 8289 | ); |
| 8290 | assert!( |
| 8291 | !wire.iter().any(|message| { |
| 8292 | message["content"].as_array().is_some_and(|parts| { |
| 8293 | parts |
| 8294 | .iter() |
| 8295 | .any(|part| part["type"].as_str() == Some("image_url")) |
| 8296 | }) |
| 8297 | }), |
| 8298 | "images from a stripped tool batch must not survive as user input: {wire:?}" |
| 8299 | ); |
| 8300 | } |
| 8301 | |
| 8302 | #[test] |
| 8303 | fn duplicate_tool_call_ids_are_downgraded_before_serialization() { |
| 8304 | let messages = vec![ |
| 8305 | Message { |
| 8306 | role: Role::Assistant, |
| 8307 | content: vec![ |
| 8308 | ContentBlock::ToolUse { |
| 8309 | execution_id: None, |
| 8310 | id: "duplicate".to_string(), |
| 8311 | name: "read".to_string(), |
| 8312 | input: serde_json::json!({"path": "first.png"}), |
| 8313 | caller: None, |
| 8314 | thought_signature: None, |
| 8315 | }, |
| 8316 | ContentBlock::ToolUse { |
| 8317 | execution_id: None, |
| 8318 | id: "duplicate".to_string(), |
| 8319 | name: "read".to_string(), |
| 8320 | input: serde_json::json!({"path": "second.png"}), |
| 8321 | caller: None, |
| 8322 | thought_signature: None, |
| 8323 | }, |
| 8324 | ], |
| 8325 | }, |
| 8326 | Message { |
| 8327 | role: Role::User, |
| 8328 | content: vec![ContentBlock::ToolResult { |
| 8329 | execution_id: None, |
| 8330 | tool_use_id: "duplicate".to_string(), |
| 8331 | content: "one result for two calls".to_string(), |
| 8332 | is_error: Some(false), |
| 8333 | content_blocks: Some(vec![serde_json::json!({ |
| 8334 | "type": "image", |
| 8335 | "mime_type": "image/png", |
| 8336 | "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==", |
| 8337 | })]), |
| 8338 | }], |
| 8339 | }, |
| 8340 | ]; |
| 8341 | |
| 8342 | let wire = build_chat_messages(None, &messages, "gpt-4o"); |
| 8343 | assert!( |
| 8344 | !wire |
| 8345 | .iter() |
| 8346 | .any(|message| message.get("tool_calls").is_some()), |
| 8347 | "duplicate call IDs cannot satisfy two tool calls: {wire:?}" |
| 8348 | ); |
| 8349 | assert!( |
| 8350 | !wire |
| 8351 | .iter() |
| 8352 | .any(|message| message["role"].as_str() == Some("tool")), |
| 8353 | "the ambiguous tool result must be removed with the stripped batch: {wire:?}" |
| 8354 | ); |
| 8355 | assert!( |
| 8356 | !wire.iter().any(|message| { |
| 8357 | message["content"].as_array().is_some_and(|parts| { |
| 8358 | parts |
| 8359 | .iter() |
| 8360 | .any(|part| part["type"].as_str() == Some("image_url")) |
| 8361 | }) |
| 8362 | }), |
| 8363 | "media from an ambiguous duplicate-ID batch must not survive: {wire:?}" |
| 8364 | ); |
| 8365 | } |
| 8366 | } |
| 8367 | |
| 8368 | #[cfg(test)] |
| 8369 | mod mistral_reasoning_tests { |
| 8370 | use super::*; |
| 8371 | |
| 8372 | fn request_with_assistant_thinking_and_tool() -> MessageRequest { |
| 8373 | MessageRequest { |
| 8374 | model: "mistral-medium-latest".to_string(), |
| 8375 | messages: vec![ |
| 8376 | Message { |
| 8377 | role: Role::Assistant, |
| 8378 | content: vec![ |
| 8379 | ContentBlock::Thinking { |
| 8380 | thinking: "Inspect the current state before calling the tool." |
| 8381 | .to_string(), |
| 8382 | signature: None, |
| 8383 | state: None, |
| 8384 | redacted_data: None, |
| 8385 | }, |
| 8386 | ContentBlock::Text { |
| 8387 | text: "I will inspect it now.".to_string(), |
| 8388 | cache_control: None, |
| 8389 | }, |
| 8390 | ContentBlock::ToolUse { |
| 8391 | execution_id: None, |
| 8392 | id: "call-1".to_string(), |
| 8393 | name: "read_file".to_string(), |
| 8394 | input: json!({"path": "README.md"}), |
| 8395 | caller: None, |
| 8396 | thought_signature: None, |
| 8397 | }, |
| 8398 | ], |
| 8399 | }, |
| 8400 | Message { |
| 8401 | role: Role::User, |
| 8402 | content: vec![ContentBlock::ToolResult { |
| 8403 | execution_id: None, |
| 8404 | tool_use_id: "call-1".to_string(), |
| 8405 | content: "contents".to_string(), |
| 8406 | is_error: None, |
| 8407 | content_blocks: None, |
| 8408 | }], |
| 8409 | }, |
| 8410 | ], |
| 8411 | max_tokens: 64, |
| 8412 | system: None, |
| 8413 | tools: None, |
| 8414 | tool_choice: None, |
| 8415 | metadata: None, |
| 8416 | thinking: None, |
| 8417 | reasoning_effort: Some("high".to_string()), |
| 8418 | stream: None, |
| 8419 | temperature: None, |
| 8420 | top_p: None, |
| 8421 | safety_check: None, |
| 8422 | title: None, |
| 8423 | } |
| 8424 | } |
| 8425 | |
| 8426 | #[test] |
| 8427 | fn mistral_effort_wire_value_covers_codewhale_tiers() { |
| 8428 | assert_eq!(mistral_reasoning_effort_wire_value("off"), Some("none")); |
| 8429 | assert_eq!( |
| 8430 | mistral_reasoning_effort_wire_value("disabled"), |
| 8431 | Some("none") |
| 8432 | ); |
| 8433 | assert_eq!(mistral_reasoning_effort_wire_value("none"), Some("none")); |
| 8434 | assert_eq!(mistral_reasoning_effort_wire_value("false"), Some("none")); |
| 8435 | assert_eq!(mistral_reasoning_effort_wire_value("high"), Some("high")); |
| 8436 | assert_eq!(mistral_reasoning_effort_wire_value("xhigh"), Some("high")); |
| 8437 | assert_eq!(mistral_reasoning_effort_wire_value("max"), Some("high")); |
| 8438 | assert_eq!(mistral_reasoning_effort_wire_value("ultra"), Some("high")); |
| 8439 | assert_eq!( |
| 8440 | mistral_reasoning_effort_wire_value("ultracode"), |
| 8441 | Some("high") |
| 8442 | ); |
| 8443 | // Intermediate tiers must be omitted so the request falls back to |
| 8444 | // Mistral's own default rather than 400 code 3051 on unsupported |
| 8445 | // values like "low"/"medium" that the server does not accept today. |
| 8446 | assert_eq!(mistral_reasoning_effort_wire_value("low"), None); |
| 8447 | assert_eq!(mistral_reasoning_effort_wire_value("medium"), None); |
| 8448 | assert_eq!(mistral_reasoning_effort_wire_value("mid"), None); |
| 8449 | assert_eq!(mistral_reasoning_effort_wire_value("minimal"), None); |
| 8450 | } |
| 8451 | |
| 8452 | #[test] |
| 8453 | fn mistral_model_gate_only_matches_reasoning_capable_families() { |
| 8454 | assert!(mistral_model_supports_reasoning("mistral-medium-latest")); |
| 8455 | assert!(mistral_model_supports_reasoning("mistral-medium-3-5")); |
| 8456 | assert!(mistral_model_supports_reasoning("mistral-small-latest")); |
| 8457 | assert!(mistral_model_supports_reasoning("mistral-small-2603")); |
| 8458 | assert!(mistral_model_supports_reasoning("magistral-small-latest")); |
| 8459 | assert!(mistral_model_supports_reasoning("MISTRAL-MEDIUM-LATEST")); |
| 8460 | assert!(!mistral_model_supports_reasoning("mistral-code-latest")); |
| 8461 | assert!(!mistral_model_supports_reasoning("codestral-latest")); |
| 8462 | assert!(!mistral_model_supports_reasoning("mistral-large-latest")); |
| 8463 | assert!(!mistral_model_supports_reasoning("mistral-nemo-2407")); |
| 8464 | } |
| 8465 | |
| 8466 | #[test] |
| 8467 | fn mistral_route_shaper_writes_reasoning_only_for_supported_models() { |
| 8468 | let mut body = json!({"model": "mistral-medium-latest"}); |
| 8469 | apply_mistral_route_reasoning_controls( |
| 8470 | &mut body, |
| 8471 | ProviderKind::Mistral, |
| 8472 | codewhale_config::descriptors::defaults::DEFAULT_MISTRAL_BASE_URL, |
| 8473 | "mistral-medium-latest", |
| 8474 | Some("high"), |
| 8475 | ); |
| 8476 | assert_eq!(body["reasoning_effort"], json!("high")); |
| 8477 | |
| 8478 | let mut body = json!({"model": "mistral-code-latest"}); |
| 8479 | apply_mistral_route_reasoning_controls( |
| 8480 | &mut body, |
| 8481 | ProviderKind::Mistral, |
| 8482 | codewhale_config::descriptors::defaults::DEFAULT_MISTRAL_BASE_URL, |
| 8483 | "mistral-code-latest", |
| 8484 | Some("high"), |
| 8485 | ); |
| 8486 | assert!( |
| 8487 | body.get("reasoning_effort").is_none(), |
| 8488 | "non-reasoning models must never see reasoning_effort (Mistral 400s on 3051): {body}" |
| 8489 | ); |
| 8490 | |
| 8491 | let mut body = json!({"model": "mistral-medium-latest", "reasoning_effort": "stale"}); |
| 8492 | apply_mistral_route_reasoning_controls( |
| 8493 | &mut body, |
| 8494 | ProviderKind::Mistral, |
| 8495 | codewhale_config::descriptors::defaults::DEFAULT_MISTRAL_BASE_URL, |
| 8496 | "mistral-medium-latest", |
| 8497 | Some("low"), |
| 8498 | ); |
| 8499 | assert!( |
| 8500 | body.get("reasoning_effort").is_none(), |
| 8501 | "intermediate tiers must be stripped rather than sent unsupported: {body}" |
| 8502 | ); |
| 8503 | |
| 8504 | // Non-Mistral providers must not be touched by this shaper. |
| 8505 | let mut body = json!({"model": "deepseek-v4-pro", "reasoning_effort": "high"}); |
| 8506 | apply_mistral_route_reasoning_controls( |
| 8507 | &mut body, |
| 8508 | ProviderKind::Deepseek, |
| 8509 | codewhale_config::descriptors::defaults::DEFAULT_MISTRAL_BASE_URL, |
| 8510 | "deepseek-v4-pro", |
| 8511 | Some("high"), |
| 8512 | ); |
| 8513 | assert_eq!(body["reasoning_effort"], json!("high")); |
| 8514 | |
| 8515 | let mut body = json!({ |
| 8516 | "model": "mistral-medium-latest", |
| 8517 | "thinking": {"type": "enabled"}, |
| 8518 | "reasoning_effort": "stale", |
| 8519 | }); |
| 8520 | apply_mistral_route_reasoning_controls( |
| 8521 | &mut body, |
| 8522 | ProviderKind::Mistral, |
| 8523 | "https://gateway.example.test/v1", |
| 8524 | "mistral-medium-latest", |
| 8525 | Some("high"), |
| 8526 | ); |
| 8527 | assert!(body.get("thinking").is_none()); |
| 8528 | assert!(body.get("reasoning_effort").is_none()); |
| 8529 | |
| 8530 | let mut native = json!({"model": "magistral-small-latest"}); |
| 8531 | apply_mistral_route_reasoning_controls( |
| 8532 | &mut native, |
| 8533 | ProviderKind::Mistral, |
| 8534 | codewhale_config::descriptors::defaults::DEFAULT_MISTRAL_BASE_URL, |
| 8535 | "magistral-small-latest", |
| 8536 | Some("off"), |
| 8537 | ); |
| 8538 | assert!( |
| 8539 | native.get("reasoning_effort").is_none(), |
| 8540 | "legacy native Magistral is always-reasoning and does not use the adjustable effort field" |
| 8541 | ); |
| 8542 | } |
| 8543 | |
| 8544 | #[test] |
| 8545 | fn mistral_wire_dialect_is_limited_to_exact_first_party_routes() { |
| 8546 | for official in [ |
| 8547 | "https://api.mistral.ai/v1", |
| 8548 | "https://api.eu.mistral.ai/v1/", |
| 8549 | "https://api.us.mistral.ai/v1", |
| 8550 | ] { |
| 8551 | assert!(is_exact_mistral_chat_route(ProviderKind::Mistral, official)); |
| 8552 | } |
| 8553 | for neighbor in [ |
| 8554 | "http://api.mistral.ai/v1", |
| 8555 | "https://api.mistral.ai/v2", |
| 8556 | "https://proxy.example.test/v1", |
| 8557 | "https://api.mistral.ai.evil.test/v1", |
| 8558 | ] { |
| 8559 | assert!(!is_exact_mistral_chat_route( |
| 8560 | ProviderKind::Mistral, |
| 8561 | neighbor |
| 8562 | )); |
| 8563 | } |
| 8564 | assert!(!is_exact_mistral_chat_route( |
| 8565 | ProviderKind::Openai, |
| 8566 | codewhale_config::descriptors::defaults::DEFAULT_MISTRAL_BASE_URL, |
| 8567 | )); |
| 8568 | assert_eq!( |
| 8569 | reasoning_stream_style_for_route( |
| 8570 | ProviderKind::Mistral, |
| 8571 | codewhale_config::descriptors::defaults::DEFAULT_MISTRAL_BASE_URL, |
| 8572 | "mistral-medium-latest", |
| 8573 | None, |
| 8574 | ), |
| 8575 | ReasoningStreamStyle::MistralBlocks |
| 8576 | ); |
| 8577 | assert_eq!( |
| 8578 | reasoning_stream_style_for_route( |
| 8579 | ProviderKind::Mistral, |
| 8580 | "https://gateway.example.test/v1", |
| 8581 | "mistral-medium-latest", |
| 8582 | None, |
| 8583 | ), |
| 8584 | ReasoningStreamStyle::SeparateField |
| 8585 | ); |
| 8586 | } |
| 8587 | |
| 8588 | #[test] |
| 8589 | fn extract_mistral_polymorphic_content_flattens_thinking_and_text() { |
| 8590 | // Non-reasoning response: plain string content. Extractor returns |
| 8591 | // (None, None) so the shared string fallback still runs. |
| 8592 | let plain = json!({"content": "Hello world"}); |
| 8593 | assert_eq!(extract_mistral_polymorphic_content(&plain), (None, None)); |
| 8594 | |
| 8595 | // Missing content: no panic, returns (None, None). |
| 8596 | let empty = json!({}); |
| 8597 | assert_eq!(extract_mistral_polymorphic_content(&empty), (None, None)); |
| 8598 | |
| 8599 | // Reasoning response: nested thinking array + text block. |
| 8600 | let reasoning = json!({"content": [ |
| 8601 | {"type": "thinking", "thinking": [ |
| 8602 | {"type": "text", "text": "First "}, |
| 8603 | {"type": "text", "text": "second."}, |
| 8604 | ], "closed": true}, |
| 8605 | {"type": "text", "text": "Final answer."}, |
| 8606 | ]}); |
| 8607 | let (thinking, text) = extract_mistral_polymorphic_content(&reasoning); |
| 8608 | assert_eq!(thinking.as_deref(), Some("First second.")); |
| 8609 | assert_eq!(text.as_deref(), Some("Final answer.")); |
| 8610 | |
| 8611 | // Thinking-only chunk (mid-stream) with no closing text yet. |
| 8612 | let thinking_only = json!({"content": [ |
| 8613 | {"type": "thinking", "thinking": [{"type": "text", "text": "still thinking"}]}, |
| 8614 | ]}); |
| 8615 | let (thinking, text) = extract_mistral_polymorphic_content(&thinking_only); |
| 8616 | assert_eq!(thinking.as_deref(), Some("still thinking")); |
| 8617 | assert_eq!(text, None); |
| 8618 | } |
| 8619 | |
| 8620 | #[test] |
| 8621 | fn reshape_mistral_messages_reconstructs_polymorphic_shape_for_assistant_replay() { |
| 8622 | // Assistant message with stored reasoning_content is reshaped into |
| 8623 | // Mistral's polymorphic content-as-array shape. |
| 8624 | let mut messages = vec![ |
| 8625 | json!({"role": "user", "content": "compute 3+4"}), |
| 8626 | json!({ |
| 8627 | "role": "assistant", |
| 8628 | "content": "The answer is 7.", |
| 8629 | "reasoning_content": "Let me add 3 and 4 to get 7.", |
| 8630 | }), |
| 8631 | json!({"role": "user", "content": "now multiply by 2"}), |
| 8632 | ]; |
| 8633 | reshape_mistral_messages_for_reasoning_replay(&mut messages); |
| 8634 | |
| 8635 | assert_eq!(messages[0]["role"], "user"); |
| 8636 | assert!( |
| 8637 | messages[0]["content"].is_string(), |
| 8638 | "user turns are left untouched: {}", |
| 8639 | messages[0] |
| 8640 | ); |
| 8641 | |
| 8642 | assert_eq!(messages[1]["role"], "assistant"); |
| 8643 | assert!( |
| 8644 | messages[1].get("reasoning_content").is_none(), |
| 8645 | "reasoning_content field must be removed after reshape: {}", |
| 8646 | messages[1] |
| 8647 | ); |
| 8648 | let content = messages[1]["content"] |
| 8649 | .as_array() |
| 8650 | .expect("assistant content is now an array"); |
| 8651 | assert_eq!(content.len(), 2); |
| 8652 | assert_eq!(content[0]["type"], "thinking"); |
| 8653 | assert_eq!(content[0]["closed"], true); |
| 8654 | assert_eq!(content[0]["thinking"][0]["type"], "text"); |
| 8655 | assert_eq!( |
| 8656 | content[0]["thinking"][0]["text"], |
| 8657 | "Let me add 3 and 4 to get 7." |
| 8658 | ); |
| 8659 | assert_eq!(content[1]["type"], "text"); |
| 8660 | assert_eq!(content[1]["text"], "The answer is 7."); |
| 8661 | |
| 8662 | // Assistant with no reasoning stays as-is (plain string content). |
| 8663 | let mut plain = vec![json!({"role": "assistant", "content": "hi"})]; |
| 8664 | reshape_mistral_messages_for_reasoning_replay(&mut plain); |
| 8665 | assert_eq!(plain[0]["content"], "hi"); |
| 8666 | |
| 8667 | // Empty reasoning is treated as absent — no reshape. |
| 8668 | let mut empty = vec![json!({ |
| 8669 | "role": "assistant", |
| 8670 | "content": "hi", |
| 8671 | "reasoning_content": " ", |
| 8672 | })]; |
| 8673 | reshape_mistral_messages_for_reasoning_replay(&mut empty); |
| 8674 | assert_eq!(empty[0]["content"], "hi"); |
| 8675 | } |
| 8676 | |
| 8677 | #[test] |
| 8678 | fn mistral_prompt_builder_replays_stored_thinking_as_polymorphic_content() { |
| 8679 | let request = request_with_assistant_thinking_and_tool(); |
| 8680 | let exact = build_chat_messages_for_request_and_provider_and_route( |
| 8681 | &request, |
| 8682 | ProviderKind::Mistral, |
| 8683 | codewhale_config::descriptors::defaults::DEFAULT_MISTRAL_BASE_URL, |
| 8684 | ); |
| 8685 | let assistant = &exact[0]; |
| 8686 | assert!(assistant.get("reasoning_content").is_none()); |
| 8687 | assert!(assistant.get("tool_calls").is_some()); |
| 8688 | let content = assistant["content"] |
| 8689 | .as_array() |
| 8690 | .expect("exact Mistral history uses polymorphic content"); |
| 8691 | assert_eq!(content[0]["type"], "thinking"); |
| 8692 | assert_eq!( |
| 8693 | content[0]["thinking"][0]["text"], |
| 8694 | "Inspect the current state before calling the tool." |
| 8695 | ); |
| 8696 | assert_eq!(content[1]["type"], "text"); |
| 8697 | assert_eq!(content[1]["text"], "I will inspect it now."); |
| 8698 | |
| 8699 | for (provider, base_url) in [ |
| 8700 | (ProviderKind::Mistral, "https://gateway.example.test/v1"), |
| 8701 | ( |
| 8702 | ProviderKind::Openai, |
| 8703 | codewhale_config::descriptors::defaults::DEFAULT_MISTRAL_BASE_URL, |
| 8704 | ), |
| 8705 | ] { |
| 8706 | let neighbor = build_chat_messages_for_request_and_provider_and_route( |
| 8707 | &request, provider, base_url, |
| 8708 | ); |
| 8709 | assert!(neighbor[0].get("reasoning_content").is_none()); |
| 8710 | assert!( |
| 8711 | neighbor[0]["content"].is_string(), |
| 8712 | "unproven routes must not inherit Mistral's polymorphic dialect: {}", |
| 8713 | neighbor[0] |
| 8714 | ); |
| 8715 | } |
| 8716 | } |
| 8717 | |
| 8718 | #[test] |
| 8719 | fn mistral_stream_tool_call_replay_does_not_gain_reasoning_content() { |
| 8720 | let request = request_with_assistant_thinking_and_tool(); |
| 8721 | let wire = build_chat_wire_body( |
| 8722 | &request, |
| 8723 | ProviderKind::Mistral, |
| 8724 | codewhale_config::descriptors::defaults::DEFAULT_MISTRAL_BASE_URL, |
| 8725 | true, |
| 8726 | None, |
| 8727 | ) |
| 8728 | .expect("Mistral stream wire body"); |
| 8729 | let assistant = &wire.body["messages"][0]; |
| 8730 | assert!(assistant["content"].is_array()); |
| 8731 | assert!(assistant.get("reasoning_content").is_none()); |
| 8732 | assert!(assistant.get("tool_calls").is_some()); |
| 8733 | assert_eq!(wire.body["reasoning_effort"], "high"); |
| 8734 | assert_eq!(wire.replay_input_tokens, None); |
| 8735 | } |
| 8736 | |
| 8737 | #[test] |
| 8738 | fn mistral_nonstream_parser_is_route_isolated() { |
| 8739 | let payload = json!({ |
| 8740 | "id": "chatcmpl-mistral", |
| 8741 | "model": "mistral-medium-latest", |
| 8742 | "choices": [{ |
| 8743 | "finish_reason": "stop", |
| 8744 | "message": {"role": "assistant", "content": [ |
| 8745 | {"type": "thinking", "thinking": [ |
| 8746 | {"type": "text", "text": "private trace"} |
| 8747 | ], "closed": true}, |
| 8748 | {"type": "text", "text": "public answer"} |
| 8749 | ]} |
| 8750 | }], |
| 8751 | "usage": {"prompt_tokens": 5, "completion_tokens": 2} |
| 8752 | }); |
| 8753 | let mistral = parse_chat_message_for_route( |
| 8754 | &payload, |
| 8755 | ProviderKind::Mistral, |
| 8756 | codewhale_config::descriptors::defaults::DEFAULT_MISTRAL_BASE_URL, |
| 8757 | ) |
| 8758 | .expect("Mistral payload parses"); |
| 8759 | assert!(matches!( |
| 8760 | &mistral.content[0], |
| 8761 | ContentBlock::Thinking { thinking, .. } if thinking == "private trace" |
| 8762 | )); |
| 8763 | assert!(matches!( |
| 8764 | &mistral.content[1], |
| 8765 | ContentBlock::Text { text, .. } if text == "public answer" |
| 8766 | )); |
| 8767 | |
| 8768 | let generic = parse_chat_message(&payload).expect("generic payload parses"); |
| 8769 | assert!( |
| 8770 | !generic |
| 8771 | .content |
| 8772 | .iter() |
| 8773 | .any(|block| matches!(block, ContentBlock::Thinking { .. })), |
| 8774 | "typed arrays from another provider must not be reinterpreted as Mistral thinking" |
| 8775 | ); |
| 8776 | } |
| 8777 | |
| 8778 | #[test] |
| 8779 | fn mistral_shared_capability_matches_wire_contract() { |
| 8780 | for model in [ |
| 8781 | "mistral-medium-latest", |
| 8782 | "mistral-small-latest", |
| 8783 | "magistral-small-latest", |
| 8784 | ] { |
| 8785 | assert!(codewhale_models::model_supports_reasoning(model), "{model}"); |
| 8786 | } |
| 8787 | for model in ["mistral-code-latest", "mistral-large-latest"] { |
| 8788 | assert!( |
| 8789 | !codewhale_models::model_supports_reasoning(model), |
| 8790 | "{model}" |
| 8791 | ); |
| 8792 | } |
| 8793 | } |
| 8794 | } |
| 8795 | |
| 8796 | #[cfg(test)] |
| 8797 | mod google_thought_signature_tests { |
| 8798 | use super::*; |
| 8799 | |
| 8800 | // ── Google thought signatures (#v0.9.8 Google backend) ────────────── |
| 8801 | use codewhale_config::descriptors::defaults::DEFAULT_OPENAI_BASE_URL; |
| 8802 | const DEFAULT_GOOGLE_BASE_URL: &str = |
| 8803 | "https://generativelanguage.googleapis.com/v1beta/openai/"; |
| 8804 | |
| 8805 | /// One signed tool turn. `paired` false is the restart shape: the process |
| 8806 | /// died between the tool call and its result, so the terminal |
| 8807 | /// `tool_result` never reached durable history. |
| 8808 | fn signed_history(signature: Option<&str>, paired: bool) -> Vec<Message> { |
| 8809 | let mut messages = vec![ |
| 8810 | Message { |
| 8811 | role: Role::User, |
| 8812 | content: vec![ContentBlock::Text { |
| 8813 | text: "Read the config.".to_string(), |
| 8814 | cache_control: None, |
| 8815 | }], |
| 8816 | }, |
| 8817 | Message { |
| 8818 | role: Role::Assistant, |
| 8819 | content: vec![ |
| 8820 | ContentBlock::Text { |
| 8821 | text: "Reading now.".to_string(), |
| 8822 | cache_control: None, |
| 8823 | }, |
| 8824 | ContentBlock::ToolUse { |
| 8825 | execution_id: None, |
| 8826 | id: "call-g-1".to_string(), |
| 8827 | name: "read".to_string(), |
| 8828 | input: json!({"path": "config.toml"}), |
| 8829 | caller: None, |
| 8830 | thought_signature: signature.map(str::to_string), |
| 8831 | }, |
| 8832 | ], |
| 8833 | }, |
| 8834 | ]; |
| 8835 | if paired { |
| 8836 | messages.push(Message { |
| 8837 | role: Role::User, |
| 8838 | content: vec![ContentBlock::ToolResult { |
| 8839 | execution_id: None, |
| 8840 | tool_use_id: "call-g-1".to_string(), |
| 8841 | content: "key = \"value\"".to_string(), |
| 8842 | is_error: None, |
| 8843 | content_blocks: None, |
| 8844 | }], |
| 8845 | }); |
| 8846 | } |
| 8847 | messages |
| 8848 | } |
| 8849 | |
| 8850 | fn request_from(messages: Vec<Message>) -> MessageRequest { |
| 8851 | MessageRequest { |
| 8852 | model: "gemini-3.1-pro-preview".to_string(), |
| 8853 | messages, |
| 8854 | max_tokens: 64, |
| 8855 | system: None, |
| 8856 | tools: None, |
| 8857 | tool_choice: None, |
| 8858 | metadata: None, |
| 8859 | thinking: None, |
| 8860 | reasoning_effort: Some("high".to_string()), |
| 8861 | stream: None, |
| 8862 | temperature: None, |
| 8863 | top_p: None, |
| 8864 | safety_check: None, |
| 8865 | title: None, |
| 8866 | } |
| 8867 | } |
| 8868 | |
| 8869 | fn google_request_with_signed_tool(signature: Option<&str>) -> MessageRequest { |
| 8870 | request_from(signed_history(signature, true)) |
| 8871 | } |
| 8872 | |
| 8873 | #[tokio::test] |
| 8874 | async fn gateway_thought_signature_rejection_explains_recovery_after_transport() { |
| 8875 | use crate::llm_client::LlmClient; |
| 8876 | use wiremock::matchers::{method, path}; |
| 8877 | use wiremock::{Mock, MockServer, ResponseTemplate}; |
| 8878 | |
| 8879 | let _ = rustls::crypto::ring::default_provider().install_default(); |
| 8880 | // An unsigned replay must reach the gateway: it may manage Google's |
| 8881 | // signatures itself. Only an actual rejection warrants recovery advice. |
| 8882 | for streaming in [false, true] { |
| 8883 | for status in [200, 400] { |
| 8884 | let server = MockServer::start().await; |
| 8885 | let response = if status == 400 { |
| 8886 | ResponseTemplate::new(status).set_body_json(json!({ |
| 8887 | "error": { |
| 8888 | "code": 400, |
| 8889 | "message": "Function call is missing a thought_signature in functionCall parts." |
| 8890 | } |
| 8891 | })) |
| 8892 | } else if streaming { |
| 8893 | ResponseTemplate::new(status) |
| 8894 | .insert_header("content-type", "text/event-stream") |
| 8895 | .set_body_string("data: [DONE]\n\n") |
| 8896 | } else { |
| 8897 | ResponseTemplate::new(status).set_body_json(json!({ |
| 8898 | "id": "gateway-replay", |
| 8899 | "model": "gemini-3.1-pro-preview", |
| 8900 | "choices": [{ |
| 8901 | "message": {"role": "assistant", "content": "Done."}, |
| 8902 | "finish_reason": "stop" |
| 8903 | }] |
| 8904 | })) |
| 8905 | }; |
| 8906 | Mock::given(method("POST")) |
| 8907 | .and(path("/v1/chat/completions")) |
| 8908 | .respond_with(response) |
| 8909 | .expect(1) |
| 8910 | .mount(&server) |
| 8911 | .await; |
| 8912 | |
| 8913 | let mut client = CodewhaleClient::new(&{ |
| 8914 | let __cw_config_init_0_0 = Some("openai".to_string()); |
| 8915 | let __cw_config_init_0_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 8916 | openai: codewhale_runtime::config::ProviderConfig { |
| 8917 | api_key: Some("gateway-test-key".to_string()), |
| 8918 | base_url: Some(format!("{}/v1", server.uri())), |
| 8919 | model: Some("gemini-3.1-pro-preview".to_string()), |
| 8920 | ..codewhale_runtime::config::ProviderConfig::default() |
| 8921 | }, |
| 8922 | ..codewhale_runtime::config::ProvidersConfig::default() |
| 8923 | }); |
| 8924 | let mut __cw_config_init_0_value: codewhale_runtime::config::Config = |
| 8925 | codewhale_runtime::config::Config::default(); |
| 8926 | __cw_config_init_0_value.provider = __cw_config_init_0_0; |
| 8927 | __cw_config_init_0_value.providers = __cw_config_init_0_1; |
| 8928 | __cw_config_init_0_value |
| 8929 | }) |
| 8930 | .expect("gateway client"); |
| 8931 | client.isolated_request_state = true; |
| 8932 | let request = google_request_with_signed_tool(None); |
| 8933 | let result = if streaming { |
| 8934 | client.create_message_stream(request).await.map(|_| ()) |
| 8935 | } else { |
| 8936 | client |
| 8937 | .create_message_without_response_cache( |
| 8938 | request, |
| 8939 | crate::llm_client::RequestRetryObservation::isolated(), |
| 8940 | ) |
| 8941 | .await |
| 8942 | .map(|_| ()) |
| 8943 | }; |
| 8944 | if status == 400 { |
| 8945 | let error = result.expect_err("gateway rejects unsigned replay"); |
| 8946 | let message = error.to_string(); |
| 8947 | assert!(message.contains("built-in `google` provider"), "{message}"); |
| 8948 | assert!(message.contains("start a new session"), "{message}"); |
| 8949 | assert!(matches!( |
| 8950 | error.downcast_ref::<crate::llm_client::LlmError>(), |
| 8951 | Some(crate::llm_client::LlmError::InvalidRequest { status: 400, .. }) |
| 8952 | )); |
| 8953 | } else { |
| 8954 | result.expect("gateway-managed signatures must still work"); |
| 8955 | } |
| 8956 | server.verify().await; |
| 8957 | } |
| 8958 | } |
| 8959 | } |
| 8960 | |
| 8961 | #[test] |
| 8962 | fn google_route_round_trips_thought_signatures_on_replayed_tool_calls() { |
| 8963 | let request = google_request_with_signed_tool(Some("SIG-abc123")); |
| 8964 | let messages = build_chat_messages_for_request_and_provider_and_route( |
| 8965 | &request, |
| 8966 | ProviderKind::Google, |
| 8967 | DEFAULT_GOOGLE_BASE_URL, |
| 8968 | ); |
| 8969 | let assistant = messages |
| 8970 | .iter() |
| 8971 | .find(|m| m.get("role") == Some(&json!("assistant"))) |
| 8972 | .expect("assistant replay message"); |
| 8973 | let signature = assistant |
| 8974 | .pointer("/tool_calls/0/extra_content/google/thought_signature") |
| 8975 | .and_then(serde_json::Value::as_str); |
| 8976 | assert_eq!(signature, Some("SIG-abc123")); |
| 8977 | } |
| 8978 | |
| 8979 | #[test] |
| 8980 | fn google_route_fails_closed_when_replayed_signature_is_missing() { |
| 8981 | let request = google_request_with_signed_tool(None); |
| 8982 | let error = build_chat_wire_body( |
| 8983 | &request, |
| 8984 | ProviderKind::Google, |
| 8985 | DEFAULT_GOOGLE_BASE_URL, |
| 8986 | false, |
| 8987 | None, |
| 8988 | ) |
| 8989 | .err() |
| 8990 | .expect("missing signature must fail closed before transport"); |
| 8991 | assert!( |
| 8992 | error.to_string().contains("thought signature"), |
| 8993 | "error must name the missing signature: {error}" |
| 8994 | ); |
| 8995 | } |
| 8996 | |
| 8997 | /// Google names the same model `gemini-3-pro` and `models/gemini-3-pro` on |
| 8998 | /// this endpoint. The prefixed spelling used to match none of the thinking |
| 8999 | /// families, so the model that most needs a signature was treated as one |
| 9000 | /// that needs none and the replay reached Google unsigned (#6018). |
| 9001 | #[test] |
| 9002 | fn google_route_fails_closed_for_a_models_prefixed_thinking_id() { |
| 9003 | for model in [ |
| 9004 | "models/gemini-3-pro-preview", |
| 9005 | "gemini-4-hydrogen", |
| 9006 | "models/gemini-4-hydrogen", |
| 9007 | ] { |
| 9008 | let mut request = google_request_with_signed_tool(None); |
| 9009 | request.model = model.to_string(); |
| 9010 | let error = build_chat_wire_body( |
| 9011 | &request, |
| 9012 | ProviderKind::Google, |
| 9013 | DEFAULT_GOOGLE_BASE_URL, |
| 9014 | false, |
| 9015 | None, |
| 9016 | ) |
| 9017 | .err() |
| 9018 | .expect("a thinking id must fail closed across bare and models/-prefixed spellings"); |
| 9019 | assert!( |
| 9020 | error.to_string().contains("thought signature"), |
| 9021 | "error must name the missing signature for {model}: {error}" |
| 9022 | ); |
| 9023 | } |
| 9024 | } |
| 9025 | |
| 9026 | #[test] |
| 9027 | fn google_missing_signature_is_a_warning_not_an_error_for_flash_lite() { |
| 9028 | // 2.5 Flash-Lite ships thinking off; Google may legitimately omit |
| 9029 | // signatures there, so replay proceeds. |
| 9030 | let mut request = google_request_with_signed_tool(None); |
| 9031 | request.model = "gemini-2.5-flash-lite".to_string(); |
| 9032 | build_chat_wire_body( |
| 9033 | &request, |
| 9034 | ProviderKind::Google, |
| 9035 | DEFAULT_GOOGLE_BASE_URL, |
| 9036 | false, |
| 9037 | None, |
| 9038 | ) |
| 9039 | .expect("flash-lite replay must not require a signature"); |
| 9040 | } |
| 9041 | |
| 9042 | #[test] |
| 9043 | fn non_google_routes_never_see_google_extra_content() { |
| 9044 | let request = google_request_with_signed_tool(Some("SIG-abc123")); |
| 9045 | let messages = build_chat_messages_for_request_and_provider_and_route( |
| 9046 | &request, |
| 9047 | ProviderKind::Openai, |
| 9048 | DEFAULT_OPENAI_BASE_URL, |
| 9049 | ); |
| 9050 | for message in &messages { |
| 9051 | if let Some(tool_calls) = message.get("tool_calls").and_then(|v| v.as_array()) { |
| 9052 | for call in tool_calls { |
| 9053 | assert!( |
| 9054 | call.get("extra_content").is_none(), |
| 9055 | "Google-only fields must not leak to other providers" |
| 9056 | ); |
| 9057 | } |
| 9058 | } |
| 9059 | } |
| 9060 | } |
| 9061 | |
| 9062 | #[test] |
| 9063 | fn google_neighbor_base_url_does_not_get_google_dialect() { |
| 9064 | // A Google provider row pointed at some other gateway must not |
| 9065 | // carry signatures or fail closed: the dialect binds to the exact |
| 9066 | // official route, not to provider identity alone. |
| 9067 | let request = google_request_with_signed_tool(None); |
| 9068 | build_chat_wire_body( |
| 9069 | &request, |
| 9070 | ProviderKind::Google, |
| 9071 | "https://gateway.example.com/v1", |
| 9072 | false, |
| 9073 | None, |
| 9074 | ) |
| 9075 | .expect("non-official Google base URL must not require signatures"); |
| 9076 | let messages = build_chat_messages_for_request_and_provider_and_route( |
| 9077 | &google_request_with_signed_tool(Some("SIG")), |
| 9078 | ProviderKind::Google, |
| 9079 | "https://gateway.example.com/v1", |
| 9080 | ); |
| 9081 | assert!( |
| 9082 | messages |
| 9083 | .iter() |
| 9084 | .all(|m| m.pointer("/tool_calls/0/extra_content").is_none()), |
| 9085 | "signatures must not be sent to a non-Google endpoint" |
| 9086 | ); |
| 9087 | } |
| 9088 | |
| 9089 | /// The manually configured OpenAI-compatible row (#1519, |
| 9090 | /// `ProviderKind::Custom`) pointed at Google's OpenAI-compat endpoint is |
| 9091 | /// byte-for-byte the same endpoint as the built-in `google` row. C22: it |
| 9092 | /// used to fail the `provider == Google` half of the route gate, so its |
| 9093 | /// signatures were stripped on replay with no warning and later signed |
| 9094 | /// tool turns failed. The gate now binds to the endpoint. |
| 9095 | #[test] |
| 9096 | fn manually_configured_openai_compatible_google_endpoint_replays_signatures() { |
| 9097 | let request = google_request_with_signed_tool(Some("SIG-abc123")); |
| 9098 | for base_url in [ |
| 9099 | DEFAULT_GOOGLE_BASE_URL, |
| 9100 | "https://generativelanguage.googleapis.com/v1beta/openai", |
| 9101 | "https://GenerativeLanguage.googleapis.com/v1beta/openai/", |
| 9102 | ] { |
| 9103 | let messages = build_chat_messages_for_request_and_provider_and_route( |
| 9104 | &request, |
| 9105 | ProviderKind::Custom, |
| 9106 | base_url, |
| 9107 | ); |
| 9108 | let assistant = messages |
| 9109 | .iter() |
| 9110 | .find(|m| m.get("role") == Some(&json!("assistant"))) |
| 9111 | .expect("assistant replay message"); |
| 9112 | assert_eq!( |
| 9113 | assistant |
| 9114 | .pointer("/tool_calls/0/extra_content/google/thought_signature") |
| 9115 | .and_then(serde_json::Value::as_str), |
| 9116 | Some("SIG-abc123"), |
| 9117 | "custom row at Google's endpoint must replay the signature ({base_url})" |
| 9118 | ); |
| 9119 | } |
| 9120 | } |
| 9121 | |
| 9122 | /// Signature preservation is a property of the endpoint, never of the |
| 9123 | /// reasoning setting: an operator who turns reasoning off (or whose |
| 9124 | /// effort is simply absent) still has to replay signed tool history. |
| 9125 | #[test] |
| 9126 | fn signatures_survive_replay_regardless_of_the_reasoning_setting() { |
| 9127 | for effort in [None, Some("off"), Some("low"), Some("high")] { |
| 9128 | for (provider, base_url) in [ |
| 9129 | (ProviderKind::Google, DEFAULT_GOOGLE_BASE_URL), |
| 9130 | ( |
| 9131 | ProviderKind::Custom, |
| 9132 | "https://generativelanguage.googleapis.com/v1beta/openai", |
| 9133 | ), |
| 9134 | ] { |
| 9135 | let mut request = google_request_with_signed_tool(Some("SIG-abc123")); |
| 9136 | request.reasoning_effort = effort.map(str::to_string); |
| 9137 | let body = build_chat_wire_body(&request, provider, base_url, true, None) |
| 9138 | .expect("signed replay builds on a signature-bearing route"); |
| 9139 | let assistant = body.body["messages"] |
| 9140 | .as_array() |
| 9141 | .expect("messages") |
| 9142 | .iter() |
| 9143 | .find(|m| m.get("role") == Some(&json!("assistant"))) |
| 9144 | .expect("assistant replay message"); |
| 9145 | assert_eq!( |
| 9146 | assistant |
| 9147 | .pointer("/tool_calls/0/extra_content/google/thought_signature") |
| 9148 | .and_then(serde_json::Value::as_str), |
| 9149 | Some("SIG-abc123"), |
| 9150 | "reasoning={effort:?} must not govern signature replay ({base_url})" |
| 9151 | ); |
| 9152 | } |
| 9153 | } |
| 9154 | } |
| 9155 | |
| 9156 | /// Fail closed on the manually configured row too — the missing-signature |
| 9157 | /// error is the useful feedback that replaces a silent strip. |
| 9158 | #[test] |
| 9159 | fn custom_row_at_google_endpoint_fails_closed_without_a_signature() { |
| 9160 | let request = google_request_with_signed_tool(None); |
| 9161 | let error = build_chat_wire_body( |
| 9162 | &request, |
| 9163 | ProviderKind::Custom, |
| 9164 | "https://generativelanguage.googleapis.com/v1beta/openai", |
| 9165 | false, |
| 9166 | None, |
| 9167 | ) |
| 9168 | .err() |
| 9169 | .expect("missing signature must fail closed before transport"); |
| 9170 | let rendered = error.to_string(); |
| 9171 | assert!( |
| 9172 | rendered.contains("thought signature") && rendered.contains("call-g-1"), |
| 9173 | "error must name the missing signature and the tool call: {rendered}" |
| 9174 | ); |
| 9175 | } |
| 9176 | |
| 9177 | /// A custom row pointed somewhere else is still a foreign gateway: the |
| 9178 | /// signature is stripped, and the strip reports how much it removed so |
| 9179 | /// the drop is never silent. |
| 9180 | #[test] |
| 9181 | fn custom_row_off_google_endpoint_strips_and_reports_signatures() { |
| 9182 | let request = google_request_with_signed_tool(Some("SIG-abc123")); |
| 9183 | let mut messages = build_chat_messages_for_request_and_provider_and_route( |
| 9184 | &request, |
| 9185 | ProviderKind::Google, |
| 9186 | DEFAULT_GOOGLE_BASE_URL, |
| 9187 | ); |
| 9188 | assert_eq!( |
| 9189 | strip_google_tool_call_extra_content(&mut messages), |
| 9190 | 1, |
| 9191 | "the strip must report the signatures it dropped" |
| 9192 | ); |
| 9193 | assert!( |
| 9194 | messages |
| 9195 | .iter() |
| 9196 | .all(|m| m.pointer("/tool_calls/0/extra_content").is_none()), |
| 9197 | "stripped history must carry no Google-only fields" |
| 9198 | ); |
| 9199 | let via_route = build_chat_messages_for_request_and_provider_and_route( |
| 9200 | &request, |
| 9201 | ProviderKind::Custom, |
| 9202 | "https://gateway.example.com/v1", |
| 9203 | ); |
| 9204 | assert!( |
| 9205 | via_route |
| 9206 | .iter() |
| 9207 | .all(|m| m.pointer("/tool_calls/0/extra_content").is_none()), |
| 9208 | "signatures must not reach a non-Google endpoint" |
| 9209 | ); |
| 9210 | } |
| 9211 | |
| 9212 | #[test] |
| 9213 | fn google_reasoning_uses_compatible_effort_without_rejected_native_fields() { |
| 9214 | // Wire examples and model limits from Google's compatibility docs. |
| 9215 | // Cover the actual request builder, both transport modes and both |
| 9216 | // ways a fresh install can configure the official endpoint (#6018). |
| 9217 | for (model, effort, expected) in [ |
| 9218 | ("gemini-3.1-pro-preview", Some("low"), Some("low")), |
| 9219 | ("gemini-3.1-pro-preview", Some("medium"), Some("medium")), |
| 9220 | ("gemini-3.1-pro-preview", Some("high"), Some("high")), |
| 9221 | ("gemini-3.1-pro-preview", Some("max"), Some("high")), |
| 9222 | ("gemini-3.5-flash-lite", Some("off"), Some("minimal")), |
| 9223 | ("gemini-2.5-flash", Some("off"), Some("none")), |
| 9224 | ("models/gemini-2.5-flash-lite", Some("off"), Some("none")), |
| 9225 | ("gemini-2.5-pro", Some("off"), Some("minimal")), |
| 9226 | ("gemini-3.1-pro-preview", None, None), |
| 9227 | ] { |
| 9228 | for provider in [ProviderKind::Google, ProviderKind::Custom] { |
| 9229 | for streaming in [false, true] { |
| 9230 | let mut request = google_request_with_signed_tool(Some("SIG")); |
| 9231 | request.model = model.to_string(); |
| 9232 | request.reasoning_effort = effort.map(str::to_string); |
| 9233 | let wire = build_chat_wire_body( |
| 9234 | &request, |
| 9235 | provider, |
| 9236 | DEFAULT_GOOGLE_BASE_URL, |
| 9237 | streaming, |
| 9238 | None, |
| 9239 | ) |
| 9240 | .expect("valid signed Google request"); |
| 9241 | assert_eq!( |
| 9242 | wire.body.get("reasoning_effort").and_then(Value::as_str), |
| 9243 | expected, |
| 9244 | "{model}: {effort:?}, {provider:?}, streaming={streaming}" |
| 9245 | ); |
| 9246 | assert!(wire.body.get("google").is_none()); |
| 9247 | assert!(wire.body.get("extra_body").is_none()); |
| 9248 | assert!(wire.body.get("thinking").is_none()); |
| 9249 | } |
| 9250 | } |
| 9251 | } |
| 9252 | } |
| 9253 | |
| 9254 | #[test] |
| 9255 | fn google_reasoning_control_does_not_rewrite_other_endpoints() { |
| 9256 | for provider in [ProviderKind::Google, ProviderKind::Custom] { |
| 9257 | let request = google_request_with_signed_tool(Some("SIG")); |
| 9258 | let wire = build_chat_wire_body( |
| 9259 | &request, |
| 9260 | provider, |
| 9261 | "https://gateway.example.com/v1", |
| 9262 | false, |
| 9263 | None, |
| 9264 | ) |
| 9265 | .expect("valid gateway request"); |
| 9266 | assert!(wire.body.get("reasoning_effort").is_none()); |
| 9267 | assert!(wire.body.get("google").is_none()); |
| 9268 | assert!(wire.body.get("extra_body").is_none()); |
| 9269 | } |
| 9270 | } |
| 9271 | |
| 9272 | #[test] |
| 9273 | fn google_signature_captured_from_non_streaming_tool_call() { |
| 9274 | let payload = json!({ |
| 9275 | "id": "resp-1", |
| 9276 | "model": "gemini-3.1-pro-preview", |
| 9277 | "choices": [{ |
| 9278 | "index": 0, |
| 9279 | "finish_reason": "tool_calls", |
| 9280 | "message": { |
| 9281 | "role": "assistant", |
| 9282 | "content": null, |
| 9283 | "tool_calls": [{ |
| 9284 | "id": "call-g-9", |
| 9285 | "type": "function", |
| 9286 | "function": { |
| 9287 | "name": "read", |
| 9288 | "arguments": "{\"path\":\"x\"}" |
| 9289 | }, |
| 9290 | "extra_content": { |
| 9291 | "google": { "thought_signature": "SIG-stream" } |
| 9292 | } |
| 9293 | }] |
| 9294 | } |
| 9295 | }], |
| 9296 | "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2} |
| 9297 | }); |
| 9298 | let response = parse_chat_message(&payload).expect("parses"); |
| 9299 | let signature = response.content.iter().find_map(|block| match block { |
| 9300 | ContentBlock::ToolUse { |
| 9301 | thought_signature, .. |
| 9302 | } => thought_signature.clone(), |
| 9303 | _ => None, |
| 9304 | }); |
| 9305 | assert_eq!(signature.as_deref(), Some("SIG-stream")); |
| 9306 | } |
| 9307 | |
| 9308 | #[test] |
| 9309 | fn google_signature_captured_from_streaming_first_chunk() { |
| 9310 | let chunk = json!({ |
| 9311 | "choices": [{ |
| 9312 | "index": 0, |
| 9313 | "delta": { |
| 9314 | "tool_calls": [{ |
| 9315 | "index": 0, |
| 9316 | "id": "call-g-7", |
| 9317 | "type": "function", |
| 9318 | "function": { "name": "read", "arguments": "{}" }, |
| 9319 | "extra_content": { |
| 9320 | "google": { "thought_signature": "SIG-delta" } |
| 9321 | } |
| 9322 | }] |
| 9323 | } |
| 9324 | }] |
| 9325 | }); |
| 9326 | let mut content_index = 0u32; |
| 9327 | let mut text_started = false; |
| 9328 | let mut thinking_started = false; |
| 9329 | let mut tool_indices = ChatToolStream::default(); |
| 9330 | let mut reasoning_buffers = std::collections::HashMap::new(); |
| 9331 | let mut inline_tags = InlineReasoningTagState::default(); |
| 9332 | let events = parse_sse_chunk_with_reasoning_style( |
| 9333 | &chunk, |
| 9334 | &mut content_index, |
| 9335 | &mut text_started, |
| 9336 | &mut thinking_started, |
| 9337 | &mut tool_indices, |
| 9338 | &mut reasoning_buffers, |
| 9339 | &mut inline_tags, |
| 9340 | ReasoningStreamStyle::None, |
| 9341 | ); |
| 9342 | let signature = events.iter().find_map(|event| match event { |
| 9343 | StreamEvent::ContentBlockStart { |
| 9344 | content_block: |
| 9345 | ContentBlockStart::ToolUse { |
| 9346 | thought_signature, .. |
| 9347 | }, |
| 9348 | .. |
| 9349 | } => thought_signature.clone(), |
| 9350 | _ => None, |
| 9351 | }); |
| 9352 | assert_eq!(signature.as_deref(), Some("SIG-delta")); |
| 9353 | } |
| 9354 | |
| 9355 | /// Run the production restart/resume chain over a message history: |
| 9356 | /// persist to disk, reload, repair crashed tool pairs, then project for |
| 9357 | /// restore exactly as `apply.rs` does before assigning `api_messages`. |
| 9358 | /// Returns the recovery receipt, the restored messages, and the raw |
| 9359 | /// session JSON as it actually sits on disk. |
| 9360 | fn resumed( |
| 9361 | messages: &[Message], |
| 9362 | ) -> ( |
| 9363 | crate::session_manager::SessionRecovery, |
| 9364 | Vec<Message>, |
| 9365 | String, |
| 9366 | ) { |
| 9367 | let dir = tempfile::tempdir().expect("tempdir"); |
| 9368 | let manager = crate::session_manager::SessionManager::new(dir.path().join("sessions")) |
| 9369 | .expect("session manager"); |
| 9370 | let session = crate::session_manager::create_saved_session( |
| 9371 | messages, |
| 9372 | "gemini-3.1-pro-preview", |
| 9373 | dir.path(), |
| 9374 | 0, |
| 9375 | None, |
| 9376 | ); |
| 9377 | let id = session.metadata.id.clone(); |
| 9378 | let path = manager.save_session(&session).expect("save session"); |
| 9379 | let on_disk = std::fs::read_to_string(&path).expect("read persisted session"); |
| 9380 | let recovery = manager |
| 9381 | .recover_session_for_resume(&id) |
| 9382 | .expect("recover session for resume"); |
| 9383 | let restored = crate::runtime_handoff::project_owned_messages_for_restore( |
| 9384 | recovery.session.messages.clone(), |
| 9385 | ); |
| 9386 | (recovery, restored, on_disk) |
| 9387 | } |
| 9388 | |
| 9389 | fn replayed_signature(body: &serde_json::Value) -> Option<String> { |
| 9390 | body["messages"] |
| 9391 | .as_array() |
| 9392 | .expect("wire messages") |
| 9393 | .iter() |
| 9394 | // The crash repair appends a trailing assistant text receipt, so |
| 9395 | // find the tool-call message by shape, never by index. |
| 9396 | .find(|message| message.get("tool_calls").is_some()) |
| 9397 | .expect("assistant tool-call message") |
| 9398 | .pointer("/tool_calls/0/extra_content/google/thought_signature") |
| 9399 | .and_then(serde_json::Value::as_str) |
| 9400 | .map(str::to_string) |
| 9401 | } |
| 9402 | |
| 9403 | /// C22 done-evidence item 3: restarting and resuming must continue the |
| 9404 | /// signed history. This walks the whole persistence chain — durable JSON, |
| 9405 | /// reload, restore projection, wire body — because the signature can be |
| 9406 | /// lost at any of them, and a serde round-trip alone would prove none of |
| 9407 | /// it. Local unit evidence only: it does not exercise a real Gemini call. |
| 9408 | #[test] |
| 9409 | fn resumed_google_session_replays_signed_tool_calls() { |
| 9410 | let original = signed_history(Some("SIG-abc123"), true); |
| 9411 | let (recovery, restored, on_disk) = resumed(&original); |
| 9412 | |
| 9413 | assert!( |
| 9414 | !recovery.changed, |
| 9415 | "a fully paired history needs no repair on resume" |
| 9416 | ); |
| 9417 | assert_eq!( |
| 9418 | recovery.session.messages, original, |
| 9419 | "reload must return the signed history unchanged" |
| 9420 | ); |
| 9421 | assert_eq!( |
| 9422 | restored, original, |
| 9423 | "the restore projection must not touch signed tool history" |
| 9424 | ); |
| 9425 | assert!( |
| 9426 | on_disk.contains("\"thought_signature\"") && on_disk.contains("SIG-abc123"), |
| 9427 | "the signature must reach durable storage, not just live memory" |
| 9428 | ); |
| 9429 | |
| 9430 | for (provider, base_url) in [ |
| 9431 | (ProviderKind::Google, DEFAULT_GOOGLE_BASE_URL), |
| 9432 | ( |
| 9433 | ProviderKind::Custom, |
| 9434 | "https://generativelanguage.googleapis.com/v1beta/openai", |
| 9435 | ), |
| 9436 | ] { |
| 9437 | let body = build_chat_wire_body( |
| 9438 | &request_from(restored.clone()), |
| 9439 | provider, |
| 9440 | base_url, |
| 9441 | true, |
| 9442 | None, |
| 9443 | ) |
| 9444 | .expect("a resumed signed history must build, not fail closed"); |
| 9445 | assert_eq!( |
| 9446 | replayed_signature(&body.body).as_deref(), |
| 9447 | Some("SIG-abc123"), |
| 9448 | "resumed history must still replay the signature ({base_url})" |
| 9449 | ); |
| 9450 | } |
| 9451 | } |
| 9452 | |
| 9453 | /// The real restart shape: the process died between the tool call and its |
| 9454 | /// result, so resume runs `repair_tool_call_pairs`, which rebuilds every |
| 9455 | /// message. That rebuild must not strip `ToolUse` fields — if it did, the |
| 9456 | /// repaired history would fail closed on Gemini 3 forever after. |
| 9457 | #[test] |
| 9458 | fn crash_repaired_resume_keeps_the_signature_on_the_repaired_tool_call() { |
| 9459 | let (recovery, restored, on_disk) = resumed(&signed_history(Some("SIG-abc123"), false)); |
| 9460 | |
| 9461 | assert!(recovery.changed, "a dangling tool call must be repaired"); |
| 9462 | assert_eq!(recovery.repaired_call_count, 1); |
| 9463 | assert_eq!(recovery.duplicate_result_count, 0); |
| 9464 | assert_eq!(recovery.orphan_result_count, 0); |
| 9465 | assert!( |
| 9466 | on_disk.contains("\"thought_signature\"") && on_disk.contains("SIG-abc123"), |
| 9467 | "the signature must reach durable storage, not just live memory" |
| 9468 | ); |
| 9469 | assert!( |
| 9470 | restored |
| 9471 | .iter() |
| 9472 | .any(|message| message.content.iter().any(|block| matches!( |
| 9473 | block, |
| 9474 | ContentBlock::ToolResult { tool_use_id, content, .. } |
| 9475 | if tool_use_id == "call-g-1" && content.contains("crashed_and_repaired") |
| 9476 | ))), |
| 9477 | "the repair must pair the dangling call with a terminal result" |
| 9478 | ); |
| 9479 | |
| 9480 | let body = build_chat_wire_body( |
| 9481 | &request_from(restored), |
| 9482 | ProviderKind::Google, |
| 9483 | DEFAULT_GOOGLE_BASE_URL, |
| 9484 | true, |
| 9485 | None, |
| 9486 | ) |
| 9487 | .expect("a crash-repaired signed history must build, not fail closed"); |
| 9488 | assert_eq!( |
| 9489 | replayed_signature(&body.body).as_deref(), |
| 9490 | Some("SIG-abc123"), |
| 9491 | "crash repair must not strip the thought signature" |
| 9492 | ); |
| 9493 | } |
| 9494 | } |
| 9495 | |
| 9496 | #[cfg(test)] |
| 9497 | mod local_template_regression { |
| 9498 | use super::*; |
| 9499 | |
| 9500 | #[test] |
| 9501 | fn vllm_model_template_effort_survives_route_shaping() { |
| 9502 | for model in ["Qwen3.8-27B-NVFP4", "nvidia/Qwen3.8-Flash-Next-NVFP4"] { |
| 9503 | let mut body = json!({"model":model,"messages":[],"max_tokens":99}); |
| 9504 | apply_route_reasoning_controls( |
| 9505 | &mut body, |
| 9506 | ProviderKind::Vllm, |
| 9507 | "http://localhost:8000/v1", |
| 9508 | model, |
| 9509 | Some("high"), |
| 9510 | ); |
| 9511 | assert!(body.get("reasoning_effort").is_none()); |
| 9512 | assert_eq!(body["chat_template_kwargs"]["reasoning_effort"], "xhigh"); |
| 9513 | assert_eq!(body["model"], model); |
| 9514 | assert_eq!(body["max_tokens"], 99); |
| 9515 | } |
| 9516 | } |
| 9517 | } |
| 9518 |