| 1 | //! API request/response models for `DeepSeek` and OpenAI-compatible endpoints. |
| 2 | |
| 3 | use serde::{Deserialize, Serialize}; |
| 4 | |
| 5 | pub mod auto_route_evidence; |
| 6 | pub mod hand_pricing; |
| 7 | pub mod image_window; |
| 8 | pub mod reasoning_effort_tier; |
| 9 | pub mod schema_canonicalize; |
| 10 | pub mod schema_sanitize; |
| 11 | pub mod tool_projection; |
| 12 | pub mod turn_classify; |
| 13 | |
| 14 | /// Context window used only for legacy DeepSeek model IDs that do not name a |
| 15 | /// newer V4 alias and do not carry an explicit `*k` suffix. |
| 16 | pub const LEGACY_DEEPSEEK_CONTEXT_WINDOW_TOKENS: u32 = 128_000; |
| 17 | pub use codewhale_config::catalog::reviewed::constants::DEEPSEEK_V4_CONTEXT_WINDOW_TOKENS; |
| 18 | /// Conservative Kimi Code K3 context baseline. The membership route's real |
| 19 | /// context is plan-tier dependent (verified 2026-07-20 from |
| 20 | /// <https://www.kimi.com/code/docs/en/kimi-code/models>): Moderato gets 256K, |
| 21 | /// while Allegretto and above get up to 1M. Bare `k3` therefore keeps this |
| 22 | /// safe floor everywhere; higher plan entitlements must come from an explicit |
| 23 | /// provider `context_window` configuration or fresh provider facts while |
| 24 | /// preserving the `k3` wire id. |
| 25 | pub const KIMI_CODE_K3_CONTEXT_WINDOW_TOKENS: u32 = 262_144; |
| 26 | /// Kimi K3 context window on the open platform (`kimi-k3` pay-as-you-go). |
| 27 | /// Verified 2026-07-20 from <https://platform.kimi.ai/docs/guide/kimi-k3-quickstart> |
| 28 | /// (1,048,576 tokens). Max output is a separate fact below and must never be |
| 29 | /// conflated with this window. |
| 30 | pub use codewhale_config::catalog::reviewed::constants::KIMI_K3_CONTEXT_WINDOW_TOKENS; |
| 31 | /// Conservative K3 default generation ceiling. The direct Kimi API defaults |
| 32 | /// `max_completion_tokens` to 131,072, while its documented route maximum is |
| 33 | /// a separate exact-route fact below. Membership and neighboring routes do |
| 34 | /// not inherit that direct-platform maximum. |
| 35 | pub use codewhale_config::catalog::reviewed::constants::KIMI_K3_DEFAULT_MAX_COMPLETION_TOKENS; |
| 36 | /// Documented maximum output for the exact direct Kimi K3 API route. |
| 37 | /// |
| 38 | /// Source: <https://platform.kimi.ai/docs/guide/kimi-k3-quickstart> (verified 2026-07-20). |
| 39 | pub const DIRECT_KIMI_K3_MAX_OUTPUT_TOKENS: u32 = 1_048_576; |
| 40 | /// Last-resort compaction trigger when [`context_window_for_model`] returns |
| 41 | /// `None` (an unrecognised model id). v0.8.11 raised this from `50_000` to |
| 42 | /// `102_400` (80% of [`LEGACY_DEEPSEEK_CONTEXT_WINDOW_TOKENS`]) so unknown |
| 43 | /// models inherit the same late-trigger discipline as V4 instead of paying |
| 44 | /// the prefix-cache hit at 5% of the V4 window. Known DeepSeek / Claude |
| 45 | /// models resolve to their own scaled value via |
| 46 | /// `compaction_threshold_for_model` (#664). |
| 47 | pub const DEFAULT_COMPACTION_TOKEN_THRESHOLD: usize = 102_400; |
| 48 | pub fn canonical_official_deepseek_model_id(model: &str) -> Option<&'static str> { |
| 49 | codewhale_config::catalog::reviewed::official_deepseek_model_id(model) |
| 50 | } |
| 51 | |
| 52 | #[cfg(any(test, feature = "test-support"))] |
| 53 | const COMPACTION_THRESHOLD_PERCENT: u32 = 80; |
| 54 | |
| 55 | // === Core Message Types === |
| 56 | |
| 57 | // Keep the historical TUI path stable while the production request DTOs are |
| 58 | // owned by `codewhale-core`. Existing transports and response decoders do not |
| 59 | // need a flag day, and headless callers can depend on core directly. |
| 60 | // Some process-test crates include this module privately and exercise only a |
| 61 | // subset of the compatibility surface, so their crate-local dead-import view |
| 62 | // is not evidence that a re-export can be removed. |
| 63 | #[allow(unused_imports)] |
| 64 | pub use codewhale_core::request::{ |
| 65 | CacheControl, ContentBlock, ConversationTitleConfig, INTERRUPTED_ASSISTANT_CONTEXT_PREFIX, |
| 66 | INTERRUPTED_ASSISTANT_ROLE, ImageUrlContent, Message, MessageRequest, OpaqueReasoningState, |
| 67 | SafetyCheckConfig, SystemBlock, SystemPrompt, Tool, ToolCallKey, ToolCaller, |
| 68 | }; |
| 69 | #[allow(unused_imports)] |
| 70 | pub use codewhale_core::role::Role; |
| 71 | |
| 72 | /// Container metadata for code-execution style server tools. |
| 73 | #[derive(Debug, Serialize, Deserialize, Clone)] |
| 74 | pub struct ContainerInfo { |
| 75 | pub id: String, |
| 76 | #[serde(skip_serializing_if = "Option::is_none")] |
| 77 | pub expires_at: Option<String>, |
| 78 | } |
| 79 | |
| 80 | /// Server-side tool usage counters. |
| 81 | #[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, Eq)] |
| 82 | pub struct ServerToolUsage { |
| 83 | #[serde(skip_serializing_if = "Option::is_none")] |
| 84 | pub code_execution_requests: Option<u32>, |
| 85 | #[serde(skip_serializing_if = "Option::is_none")] |
| 86 | pub tool_search_requests: Option<u32>, |
| 87 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 88 | pub web_search_requests: Option<u32>, |
| 89 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 90 | pub web_fetch_requests: Option<u32>, |
| 91 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 92 | pub tool_search: Option<u32>, |
| 93 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 94 | pub tool_fetch: Option<u32>, |
| 95 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 96 | pub tool_image_search: Option<u32>, |
| 97 | } |
| 98 | |
| 99 | #[derive(Debug, Serialize, Clone)] |
| 100 | pub struct ToolProjectionWarning { |
| 101 | pub provider: String, |
| 102 | pub omitted_tool_names: Vec<String>, |
| 103 | pub omitted_tool_count: usize, |
| 104 | } |
| 105 | |
| 106 | /// Response payload for a message request. |
| 107 | #[derive(Debug, Serialize, Deserialize, Clone)] |
| 108 | pub struct MessageResponse { |
| 109 | #[serde(skip_deserializing, skip_serializing_if = "Option::is_none")] |
| 110 | pub tool_projection_warning: Option<ToolProjectionWarning>, |
| 111 | pub id: String, |
| 112 | pub r#type: String, |
| 113 | pub role: String, |
| 114 | pub content: Vec<ContentBlock>, |
| 115 | pub model: String, |
| 116 | pub stop_reason: Option<String>, |
| 117 | pub stop_sequence: Option<String>, |
| 118 | #[serde(skip_serializing_if = "Option::is_none")] |
| 119 | pub container: Option<ContainerInfo>, |
| 120 | pub usage: Usage, |
| 121 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 122 | pub title: Option<String>, |
| 123 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 124 | pub stop_details: Option<serde_json::Value>, |
| 125 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 126 | pub refusal: Option<String>, |
| 127 | } |
| 128 | |
| 129 | /// True when the provider ended generation because its output allowance was |
| 130 | /// exhausted. Providers use several wire spellings for the same condition. |
| 131 | #[must_use] |
| 132 | pub fn is_output_limit_stop_reason(reason: Option<&str>) -> bool { |
| 133 | reason.is_some_and(|reason| { |
| 134 | let reason = reason |
| 135 | .trim() |
| 136 | .strip_prefix("incomplete:") |
| 137 | .unwrap_or_else(|| reason.trim()); |
| 138 | matches!( |
| 139 | reason.to_ascii_lowercase().as_str(), |
| 140 | "length" |
| 141 | | "max_tokens" |
| 142 | | "max_output_tokens" |
| 143 | | "model_length" |
| 144 | | "output_limit" |
| 145 | | "max_completion_tokens" |
| 146 | ) |
| 147 | }) |
| 148 | } |
| 149 | |
| 150 | /// Stop reason recorded for a response that reported `stop` while its own usage |
| 151 | /// shows it ran to the requested output ceiling (#6889). The Chat Completions |
| 152 | /// spelling, so every existing output-limit path treats it as a `length` stop. |
| 153 | pub const OUTPUT_CEILING_STOP_REASON: &str = "length"; |
| 154 | |
| 155 | /// True when a Chat Completions `stop` is contradicted by the provider's own |
| 156 | /// usage: the completion tokens it reported equal the output ceiling the |
| 157 | /// request asked for (#6889). A finished answer leaves the allowance unfilled, |
| 158 | /// so this response was cut at the ceiling, typically by reasoning that used |
| 159 | /// the allowance before or during the answer. |
| 160 | /// |
| 161 | /// `reported_output_tokens` is `None` when the provider reported no usage; no |
| 162 | /// inference is made then. The match is exact: a provider that does not count |
| 163 | /// reasoning against the cap can report more than the ceiling on a finished |
| 164 | /// answer. Only `stop` is second-guessed. The Anthropic and Responses wires |
| 165 | /// report a limit stop through typed fields of their own, and one Responses |
| 166 | /// route sends no ceiling at all. |
| 167 | #[must_use] |
| 168 | pub fn stop_contradicts_output_ceiling( |
| 169 | reason: Option<&str>, |
| 170 | reported_output_tokens: Option<u32>, |
| 171 | requested_max_tokens: u32, |
| 172 | ) -> bool { |
| 173 | requested_max_tokens > 0 |
| 174 | && reported_output_tokens == Some(requested_max_tokens) |
| 175 | && reason.is_some_and(|reason| reason.trim().eq_ignore_ascii_case("stop")) |
| 176 | } |
| 177 | |
| 178 | #[must_use] |
| 179 | pub fn is_refusal_stop_reason(reason: Option<&str>) -> bool { |
| 180 | reason.is_some_and(|reason| { |
| 181 | matches!( |
| 182 | reason.trim().to_ascii_lowercase().as_str(), |
| 183 | "refusal" | "content_filter" | "incomplete:content_filter" |
| 184 | ) |
| 185 | }) |
| 186 | } |
| 187 | |
| 188 | /// True when the provider explicitly reported that it did not complete the |
| 189 | /// response. Responses API reasons carry an `incomplete:` prefix so unknown |
| 190 | /// future reasons cannot accidentally be accepted as a finished answer. |
| 191 | #[must_use] |
| 192 | pub fn is_incomplete_stop_reason(reason: Option<&str>) -> bool { |
| 193 | is_output_limit_stop_reason(reason) |
| 194 | || is_refusal_stop_reason(reason) |
| 195 | || reason.is_some_and(|reason| { |
| 196 | let reason = reason.trim().to_ascii_lowercase(); |
| 197 | reason.starts_with("incomplete:") |
| 198 | || matches!( |
| 199 | reason.as_str(), |
| 200 | "content_filter" |
| 201 | | "refusal" |
| 202 | | "model_context_window_exceeded" |
| 203 | | "insufficient_system_resource" |
| 204 | | "aborted" |
| 205 | ) |
| 206 | }) |
| 207 | } |
| 208 | |
| 209 | #[must_use] |
| 210 | pub fn stop_reason_detail(reason: Option<&str>) -> &str { |
| 211 | reason |
| 212 | .map(str::trim) |
| 213 | .and_then(|reason| reason.strip_prefix("incomplete:").or(Some(reason))) |
| 214 | .filter(|reason| !reason.is_empty()) |
| 215 | .unwrap_or("unknown") |
| 216 | } |
| 217 | |
| 218 | /// Token usage metadata for a response. |
| 219 | #[derive(Debug, Serialize, Deserialize, Clone, Default, PartialEq, Eq)] |
| 220 | pub struct Usage { |
| 221 | pub input_tokens: u32, |
| 222 | pub output_tokens: u32, |
| 223 | #[serde(skip_serializing_if = "Option::is_none")] |
| 224 | pub prompt_cache_hit_tokens: Option<u32>, |
| 225 | #[serde(skip_serializing_if = "Option::is_none")] |
| 226 | pub prompt_cache_miss_tokens: Option<u32>, |
| 227 | /// Cache-creation / cache-write tokens (Anthropic `cache_creation_input_tokens`). |
| 228 | /// Billed at the cache-write rate when the pricing row publishes one (#4318). |
| 229 | #[serde(skip_serializing_if = "Option::is_none")] |
| 230 | pub prompt_cache_write_tokens: Option<u32>, |
| 231 | #[serde(skip_serializing_if = "Option::is_none")] |
| 232 | pub reasoning_tokens: Option<u32>, |
| 233 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 234 | pub input_audio_tokens: Option<u32>, |
| 235 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 236 | pub output_audio_tokens: Option<u32>, |
| 237 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 238 | pub request_usages: Vec<Usage>, |
| 239 | /// Approximate input tokens spent re-sending prior `reasoning_content` |
| 240 | /// across user-message boundaries in DeepSeek V4 thinking-mode tool-calling |
| 241 | /// turns (V4 §5.1.1 "Interleaved Thinking"). Estimated client-side at |
| 242 | /// ~4 chars/token from the outgoing request body, before the model sees it. |
| 243 | #[serde(skip_serializing_if = "Option::is_none")] |
| 244 | pub reasoning_replay_tokens: Option<u32>, |
| 245 | #[serde(skip_serializing_if = "Option::is_none")] |
| 246 | pub server_tool_use: Option<ServerToolUsage>, |
| 247 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 248 | pub safety_tokens: Option<u32>, |
| 249 | } |
| 250 | |
| 251 | /// Map known models to their approximate context window sizes. |
| 252 | /// |
| 253 | /// Exact catalog and recognized model facts take precedence. Otherwise an |
| 254 | /// explicit `_Nk` suffix supplies an unverified hint for self-hosted models. |
| 255 | /// Unrecognized DeepSeek family names remain unknown. |
| 256 | #[must_use] |
| 257 | pub fn context_window_for_model(model: &str) -> Option<u32> { |
| 258 | reviewed_model_limit(model, |row| row.context_window) |
| 259 | .or_else(|| explicit_context_window_hint(&model.to_ascii_lowercase())) |
| 260 | } |
| 261 | |
| 262 | fn reviewed_model_limit( |
| 263 | model: &str, |
| 264 | limit: impl Fn(codewhale_config::catalog::reviewed::IntrinsicModel) -> Option<u32>, |
| 265 | ) -> Option<u32> { |
| 266 | codewhale_config::catalog::reviewed::intrinsic_model(model) |
| 267 | .and_then(&limit) |
| 268 | .or_else(|| { |
| 269 | reviewed_snapshot_model(model) |
| 270 | .and_then(codewhale_config::catalog::reviewed::intrinsic_model) |
| 271 | .and_then(limit) |
| 272 | }) |
| 273 | } |
| 274 | |
| 275 | #[must_use] |
| 276 | pub fn generation_default_for_model(model: &str) -> Option<u32> { |
| 277 | reviewed_model_limit(model, |row| row.generation_default) |
| 278 | } |
| 279 | |
| 280 | #[must_use] |
| 281 | pub fn max_output_tokens_for_model(model: &str) -> Option<u32> { |
| 282 | reviewed_model_limit(model, |row| row.generation_default.or(row.max_output)) |
| 283 | } |
| 284 | |
| 285 | fn reviewed_model_flag( |
| 286 | model: &str, |
| 287 | flag: impl Fn(codewhale_config::catalog::reviewed::IntrinsicModel) -> Option<bool>, |
| 288 | ) -> Option<bool> { |
| 289 | codewhale_config::catalog::reviewed::intrinsic_model(model) |
| 290 | .and_then(&flag) |
| 291 | .or_else(|| { |
| 292 | reviewed_snapshot_model(model) |
| 293 | .and_then(codewhale_config::catalog::reviewed::intrinsic_model) |
| 294 | .and_then(flag) |
| 295 | }) |
| 296 | } |
| 297 | |
| 298 | /// Catalog-first reasoning capability. `None` means no catalog row and no |
| 299 | /// remaining cited fallback — unknown, not "not a reasoning model". |
| 300 | /// |
| 301 | /// Prefer this over [`model_supports_reasoning`] when the caller can surface |
| 302 | /// unknown the way unknown cost already is. The bool wrapper still defaults |
| 303 | /// unknown to `false` for existing stream/UI gates. |
| 304 | #[must_use] |
| 305 | pub fn model_reasoning_capability(model: &str) -> Option<bool> { |
| 306 | reviewed_model_flag(model, |row| row.reasoning) |
| 307 | } |
| 308 | |
| 309 | #[must_use] |
| 310 | pub fn model_supports_reasoning(model: &str) -> bool { |
| 311 | model_reasoning_capability(model).unwrap_or(false) |
| 312 | } |
| 313 | |
| 314 | #[must_use] |
| 315 | pub fn model_requires_thought_signatures(model: &str) -> bool { |
| 316 | reviewed_model_flag(model, |row| row.thought_signatures_required).unwrap_or(false) |
| 317 | } |
| 318 | |
| 319 | #[must_use] |
| 320 | pub fn model_can_disable_thinking(model: &str) -> bool { |
| 321 | reviewed_model_flag(model, |row| row.thinking_can_disable).unwrap_or(false) |
| 322 | } |
| 323 | |
| 324 | /// Contributor tier of Muse Spark 1.2 is a distinct selectable id with |
| 325 | /// its own wire model (`muse-spark-1.2-contributor`) and cheaper billing in |
| 326 | /// exchange for training-data opt-in. Do not collapse it to the standard tier. |
| 327 | #[must_use] |
| 328 | pub fn effective_muse_wire_id(model: &str) -> &str { |
| 329 | model |
| 330 | } |
| 331 | |
| 332 | #[must_use] |
| 333 | pub fn model_is_openai_reasoning_family(model: &str) -> bool { |
| 334 | let lower = model.to_ascii_lowercase(); |
| 335 | let reviewed = codewhale_config::catalog::reviewed::bundled_reviewed(); |
| 336 | reviewed.openai_reasoning_ids.contains_key(&lower) |
| 337 | // Snapshot resolution spans every reviewed family; the resolved |
| 338 | // target must itself be an OpenAI reasoning row, or a DeepSeek |
| 339 | // snapshot would be relabelled as one. |
| 340 | || reviewed_snapshot_model(&lower) |
| 341 | .is_some_and(|target| reviewed.openai_reasoning_ids.contains_key(target)) |
| 342 | } |
| 343 | |
| 344 | pub fn is_openai_gpt_56_api_model(model_lower: &str) -> bool { |
| 345 | codewhale_config::catalog::reviewed::bundled_reviewed() |
| 346 | .openai_reasoning_ids |
| 347 | .get(model_lower) |
| 348 | .is_some_and(|kind| kind == "gpt_56") |
| 349 | } |
| 350 | |
| 351 | pub fn has_date_snapshot_suffix(model_lower: &str, prefix: &str) -> bool { |
| 352 | let Some(rest) = model_lower.strip_prefix(prefix) else { |
| 353 | return false; |
| 354 | }; |
| 355 | let bytes = rest.as_bytes(); |
| 356 | bytes.len() == 10 |
| 357 | && bytes[4] == b'-' |
| 358 | && bytes[7] == b'-' |
| 359 | && bytes |
| 360 | .iter() |
| 361 | .enumerate() |
| 362 | .all(|(idx, byte)| idx == 4 || idx == 7 || byte.is_ascii_digit()) |
| 363 | } |
| 364 | |
| 365 | /// Resolve a snapshot or variant model id to the reviewed intrinsic row it |
| 366 | /// denotes, without inventing facts for names the catalog does not own. |
| 367 | /// |
| 368 | /// Two documented contracts, applied in order: |
| 369 | /// - the authored `snapshot_prefixes` rows (`gpt-5.5-<YYYY-MM-DD>`); |
| 370 | /// - a trailing date stamp (`-YYYY-MM-DD` or `-MMDD`) or an explicit variant |
| 371 | /// marker (`-vision-exp`, `-vision`, `-exp`), accepted only when stripping |
| 372 | /// it leaves the exact id of a reviewed intrinsic row |
| 373 | /// (`deepseek-v4-pro-0813` denotes `deepseek-v4-pro`; |
| 374 | /// `deepseek-v4-flash-vision` denotes `deepseek-v4-flash`). |
| 375 | /// The compact `-YYYYMMDD` shape is deliberately not inferred: the |
| 376 | /// sibling-metadata contract rejects it. |
| 377 | /// |
| 378 | /// Every layer is resolved against the bundled reviewed catalog only. An |
| 379 | /// unrecognized name still returns `None`: the unknown stays observable. |
| 380 | fn reviewed_snapshot_model(model: &str) -> Option<&'static str> { |
| 381 | let reviewed = codewhale_config::catalog::reviewed::bundled_reviewed(); |
| 382 | let via_authored_contract = |candidate: &str| { |
| 383 | reviewed |
| 384 | .snapshot_prefixes |
| 385 | .iter() |
| 386 | .find_map(|(prefix, target)| { |
| 387 | has_date_snapshot_suffix(candidate, prefix).then_some(target.as_str()) |
| 388 | }) |
| 389 | }; |
| 390 | let mut candidate = model.to_ascii_lowercase(); |
| 391 | for _ in 0..3 { |
| 392 | if let Some(target) = via_authored_contract(&candidate) { |
| 393 | return Some(target); |
| 394 | } |
| 395 | let stripped = strip_snapshot_or_variant_suffix(&candidate)?; |
| 396 | if let Some((key, _)) = reviewed.intrinsic.get_key_value(&stripped) { |
| 397 | return Some(key.as_str()); |
| 398 | } |
| 399 | candidate = stripped; |
| 400 | } |
| 401 | None |
| 402 | } |
| 403 | |
| 404 | /// One snapshot/variant normalization layer, longest marker first. The |
| 405 | /// caller re-resolves the shortened id against the reviewed catalog and |
| 406 | /// never accepts a shortening on its own. |
| 407 | fn strip_snapshot_or_variant_suffix(id: &str) -> Option<String> { |
| 408 | for marker in ["-vision-exp", "-vision", "-exp"] { |
| 409 | if let Some(base) = id.strip_suffix(marker) |
| 410 | && !base.is_empty() |
| 411 | { |
| 412 | return Some(base.to_string()); |
| 413 | } |
| 414 | } |
| 415 | strip_date_stamp(id) |
| 416 | } |
| 417 | |
| 418 | /// Strip one trailing date stamp: `-YYYY-MM-DD` or `-MMDD` (the reviewed |
| 419 | /// snapshot conventions). The compact `-YYYYMMDD` form is deliberately not |
| 420 | /// inferred: the sibling-metadata contract rejects that shape (see |
| 421 | /// `unrecognized_deepseek_models_do_not_inherit_sibling_metadata`). |
| 422 | fn strip_date_stamp(id: &str) -> Option<String> { |
| 423 | // `-YYYY-MM-DD`: a ten-character tail preceded by its own dash. The split |
| 424 | // index is a byte offset, so it must land on a char boundary: a multi-byte |
| 425 | // model id would panic in `split_at` otherwise. |
| 426 | if id.len() > 11 && id.is_char_boundary(id.len() - 10) { |
| 427 | let (head, tail) = id.split_at(id.len() - 10); |
| 428 | if let Some(head) = head.strip_suffix('-') |
| 429 | && !head.is_empty() |
| 430 | && has_date_snapshot_suffix(tail, "") |
| 431 | { |
| 432 | return Some(head.to_string()); |
| 433 | } |
| 434 | } |
| 435 | let (head, tail) = id.rsplit_once('-')?; |
| 436 | if head.is_empty() || tail.is_empty() { |
| 437 | return None; |
| 438 | } |
| 439 | let digits = tail.as_bytes(); |
| 440 | if digits.len() == 4 |
| 441 | && digits.iter().all(u8::is_ascii_digit) |
| 442 | && valid_month_day(&digits[0..2], &digits[2..4]) |
| 443 | { |
| 444 | return Some(head.to_string()); |
| 445 | } |
| 446 | None |
| 447 | } |
| 448 | |
| 449 | /// Validate a two-digit month/day pair (ranges only, no calendar math). |
| 450 | fn valid_month_day(month_digits: &[u8], day_digits: &[u8]) -> bool { |
| 451 | let two = |bytes: &[u8]| -> Option<u32> { |
| 452 | (bytes.len() == 2 && bytes.iter().all(u8::is_ascii_digit)) |
| 453 | .then(|| u32::from(bytes[0] - b'0') * 10 + u32::from(bytes[1] - b'0')) |
| 454 | }; |
| 455 | match (two(month_digits), two(day_digits)) { |
| 456 | (Some(month), Some(day)) => (1..=12).contains(&month) && (1..=31).contains(&day), |
| 457 | _ => false, |
| 458 | } |
| 459 | } |
| 460 | |
| 461 | /// The context window a model name's `_Nk` suffix advertises, when the |
| 462 | /// catalog does not already describe the model (#5441). |
| 463 | /// |
| 464 | /// Exposed separately from `explicit_context_window_hint` because the |
| 465 | /// honesty surfaces need to know *whether the number they are holding came |
| 466 | /// from the name* — a naming convention the serving engine may ignore is not |
| 467 | /// a fact about the route, and every surface that shows such a window must |
| 468 | /// mark it unverified. |
| 469 | #[must_use] |
| 470 | pub fn name_suffix_context_window_hint(model: &str) -> Option<u32> { |
| 471 | if codewhale_config::catalog::reviewed::intrinsic_model(model) |
| 472 | .and_then(|row| row.context_window) |
| 473 | .is_some() |
| 474 | || reviewed_snapshot_model(model).is_some() |
| 475 | { |
| 476 | return None; |
| 477 | } |
| 478 | explicit_context_window_hint(&model.to_ascii_lowercase()) |
| 479 | } |
| 480 | |
| 481 | /// Parse an explicit `_Nk` context-window hint from a model name (vendor |
| 482 | /// agnostic). Returns the window in tokens for `N` in `8..=1024`. |
| 483 | fn explicit_context_window_hint(model_lower: &str) -> Option<u32> { |
| 484 | let bytes = model_lower.as_bytes(); |
| 485 | let mut i = 0usize; |
| 486 | while i < bytes.len() { |
| 487 | if bytes[i].is_ascii_digit() { |
| 488 | let start = i; |
| 489 | while i < bytes.len() && bytes[i].is_ascii_digit() { |
| 490 | i += 1; |
| 491 | } |
| 492 | if i >= bytes.len() || bytes[i] != b'k' { |
| 493 | continue; |
| 494 | } |
| 495 | |
| 496 | let before_ok = start == 0 || !bytes[start - 1].is_ascii_alphanumeric(); |
| 497 | let after_ok = i + 1 >= bytes.len() || !bytes[i + 1].is_ascii_alphanumeric(); |
| 498 | if !before_ok || !after_ok { |
| 499 | continue; |
| 500 | } |
| 501 | |
| 502 | if let Ok(kilo_tokens) = model_lower[start..i].parse::<u32>() |
| 503 | && (8..=1024).contains(&kilo_tokens) |
| 504 | { |
| 505 | return Some(kilo_tokens.saturating_mul(1000)); |
| 506 | } |
| 507 | } else { |
| 508 | i += 1; |
| 509 | } |
| 510 | } |
| 511 | None |
| 512 | } |
| 513 | |
| 514 | /// Derive a compaction token threshold from model context and a caller-supplied |
| 515 | /// percentage. |
| 516 | #[must_use] |
| 517 | #[cfg(any(test, feature = "test-support"))] |
| 518 | pub fn compaction_threshold_for_model_at_percent(model: &str, percent: f64) -> usize { |
| 519 | let Some(window) = context_window_for_model(model) else { |
| 520 | return DEFAULT_COMPACTION_TOKEN_THRESHOLD; |
| 521 | }; |
| 522 | |
| 523 | let percent = percent.clamp(10.0, 100.0); |
| 524 | let threshold = (f64::from(window) * percent / 100.0).round(); |
| 525 | let threshold = if threshold.is_finite() && threshold > 0.0 { |
| 526 | threshold as u64 |
| 527 | } else { |
| 528 | u64::from(window) * u64::from(COMPACTION_THRESHOLD_PERCENT) / 100 |
| 529 | }; |
| 530 | usize::try_from(threshold).unwrap_or(DEFAULT_COMPACTION_TOKEN_THRESHOLD) |
| 531 | } |
| 532 | |
| 533 | /// Whether auto-compaction should be enabled when the user did not explicitly |
| 534 | /// configure it. Known model windows default automatic continuity on; an |
| 535 | /// explicit `auto_compact = false` remains authoritative at the call sites. |
| 536 | #[must_use] |
| 537 | #[cfg(test)] |
| 538 | pub fn auto_compact_default_for_model(model: &str) -> bool { |
| 539 | context_window_for_model(model).is_some() |
| 540 | } |
| 541 | |
| 542 | // === Streaming Structures === |
| 543 | |
| 544 | /// Decode the `redacted_thinking` start-event payload, tolerating the |
| 545 | /// missing-key shape (`#[serde(default)]`) and an explicit `"data": null` |
| 546 | /// from nonconforming gateways. Both decode to the empty payload that the |
| 547 | /// capture site warns about, instead of failing the whole SSE event. |
| 548 | fn deserialize_redacted_data<'de, D>(deserializer: D) -> Result<String, D::Error> |
| 549 | where |
| 550 | D: serde::Deserializer<'de>, |
| 551 | { |
| 552 | Ok(Option::<String>::deserialize(deserializer)?.unwrap_or_default()) |
| 553 | } |
| 554 | |
| 555 | #[derive(Debug, Deserialize, Clone)] |
| 556 | #[serde(tag = "type")] |
| 557 | /// Streaming event types for SSE responses. |
| 558 | pub enum StreamEvent { |
| 559 | /// Local pre-stream receipt: the provider request was sent with a reduced |
| 560 | /// tool surface. This is not provider SSE and must not count as content. |
| 561 | #[serde(rename = "tool_projection_warning")] |
| 562 | ToolProjectionWarning { |
| 563 | provider: String, |
| 564 | omitted_tool_names: Vec<String>, |
| 565 | omitted_tool_count: usize, |
| 566 | }, |
| 567 | #[serde(rename = "message_start")] |
| 568 | MessageStart { message: MessageResponse }, |
| 569 | #[serde(rename = "content_block_start")] |
| 570 | ContentBlockStart { |
| 571 | index: u32, |
| 572 | content_block: ContentBlockStart, |
| 573 | }, |
| 574 | #[serde(rename = "content_block_delta")] |
| 575 | ContentBlockDelta { index: u32, delta: Delta }, |
| 576 | #[serde(rename = "content_block_stop")] |
| 577 | ContentBlockStop { index: u32 }, |
| 578 | #[serde(rename = "message_delta")] |
| 579 | MessageDelta { |
| 580 | delta: MessageDelta, |
| 581 | usage: Option<Usage>, |
| 582 | }, |
| 583 | #[serde(rename = "message_stop")] |
| 584 | MessageStop, |
| 585 | #[serde(rename = "ping")] |
| 586 | Ping, |
| 587 | /// Anthropic SSE error event (#3014). |
| 588 | #[serde(rename = "error")] |
| 589 | Error { error: serde_json::Value }, |
| 590 | } |
| 591 | |
| 592 | #[derive(Debug, Deserialize, Clone)] |
| 593 | #[serde(tag = "type")] |
| 594 | /// Content block types used in streaming starts. |
| 595 | pub enum ContentBlockStart { |
| 596 | #[serde(rename = "text")] |
| 597 | Text { text: String }, |
| 598 | #[serde(rename = "thinking")] |
| 599 | Thinking { thinking: String }, |
| 600 | /// Anthropic `redacted_thinking`: the provider withheld the whole block |
| 601 | /// for safety and replaced it with an encrypted payload that arrives |
| 602 | /// complete on the start event (no deltas). It must be captured and |
| 603 | /// replayed byte-exact — the API decrypts it to restore the turn's |
| 604 | /// reasoning, and dropping it makes the next tool-loop request fail with |
| 605 | /// "Expected `thinking` or `redacted_thinking`, but found `tool_use`". |
| 606 | #[serde(rename = "redacted_thinking")] |
| 607 | RedactedThinking { |
| 608 | /// Tolerant of both a missing and an explicit-null `data` |
| 609 | /// (`deserialize_redacted_data` + default): a contract-violating |
| 610 | /// start event still decodes (empty payload + capture warn) instead |
| 611 | /// of failing the whole event and silently losing the turn. Note |
| 612 | /// that `#[serde(default)]` alone only covers the missing key — an |
| 613 | /// explicit `"data": null` would still fail `String` decoding. |
| 614 | #[serde(default, deserialize_with = "deserialize_redacted_data")] |
| 615 | data: String, |
| 616 | }, |
| 617 | #[serde(rename = "tool_use")] |
| 618 | ToolUse { |
| 619 | id: String, |
| 620 | name: String, |
| 621 | input: serde_json::Value, // usually empty or partial |
| 622 | #[serde(skip_serializing_if = "Option::is_none")] |
| 623 | caller: Option<ToolCaller>, |
| 624 | /// Google thought signature, when the first streaming chunk of this |
| 625 | /// tool call carried `extra_content.google.thought_signature`. |
| 626 | #[serde(skip_serializing_if = "Option::is_none")] |
| 627 | thought_signature: Option<String>, |
| 628 | }, |
| 629 | #[serde(rename = "server_tool_use")] |
| 630 | ServerToolUse { |
| 631 | id: String, |
| 632 | name: String, |
| 633 | input: serde_json::Value, |
| 634 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 635 | kind: Option<String>, |
| 636 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 637 | caller: Option<ToolCaller>, |
| 638 | }, |
| 639 | #[serde(rename = "web_search_tool_result")] |
| 640 | WebSearchToolResult { |
| 641 | tool_use_id: String, |
| 642 | content: serde_json::Value, |
| 643 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 644 | kind: Option<String>, |
| 645 | }, |
| 646 | #[serde(rename = "web_fetch_tool_result")] |
| 647 | WebFetchToolResult { |
| 648 | tool_use_id: String, |
| 649 | content: serde_json::Value, |
| 650 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 651 | kind: Option<String>, |
| 652 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 653 | signature: Option<String>, |
| 654 | }, |
| 655 | #[serde(rename = "web_search_call")] |
| 656 | WebSearchCall { |
| 657 | id: String, |
| 658 | status: String, |
| 659 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 660 | kind: Option<String>, |
| 661 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 662 | action: Option<serde_json::Value>, |
| 663 | }, |
| 664 | #[serde(rename = "server_tool_calls")] |
| 665 | ServerToolCalls { steps: Vec<serde_json::Value> }, |
| 666 | } |
| 667 | |
| 668 | // Variant names match legacy streaming spec, suppressing style warning |
| 669 | #[allow(clippy::enum_variant_names, clippy::large_enum_variant)] |
| 670 | #[derive(Debug, Deserialize, Clone)] |
| 671 | #[serde(tag = "type")] |
| 672 | /// Delta events emitted during streaming responses. |
| 673 | pub enum Delta { |
| 674 | #[serde(rename = "text_delta")] |
| 675 | TextDelta { text: String }, |
| 676 | #[serde(rename = "thinking_delta")] |
| 677 | ThinkingDelta { thinking: String }, |
| 678 | #[serde(rename = "input_json_delta")] |
| 679 | InputJsonDelta { partial_json: String }, |
| 680 | #[serde(skip)] |
| 681 | ToolCallIdDelta { id: String }, |
| 682 | /// Anthropic signed-thinking signature delta (#3014); arrives at the end |
| 683 | /// of a thinking block on the native Messages stream. |
| 684 | #[serde(rename = "signature_delta")] |
| 685 | SignatureDelta { signature: String }, |
| 686 | #[serde(rename = "thought_signature_delta")] |
| 687 | ThoughtSignatureDelta { thought_signature: String }, |
| 688 | /// Opaque Responses reasoning continuity, attached only when the provider |
| 689 | /// returns an encrypted item on the exact originating route. |
| 690 | #[serde(rename = "reasoning_state_delta")] |
| 691 | ReasoningStateDelta { state: OpaqueReasoningState }, |
| 692 | #[serde(rename = "citations_delta")] |
| 693 | CitationsDelta { citation: serde_json::Value }, |
| 694 | #[serde(rename = "refusal_delta")] |
| 695 | RefusalDelta { refusal: String }, |
| 696 | #[serde(rename = "web_search_call_delta")] |
| 697 | WebSearchCallDelta { |
| 698 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 699 | status: Option<String>, |
| 700 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 701 | kind: Option<String>, |
| 702 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 703 | action: Option<serde_json::Value>, |
| 704 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 705 | sources: Option<serde_json::Value>, |
| 706 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 707 | page: Option<serde_json::Value>, |
| 708 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 709 | signature: Option<String>, |
| 710 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 711 | error: Option<serde_json::Value>, |
| 712 | }, |
| 713 | #[serde(rename = "server_tool_calls_delta")] |
| 714 | ServerToolCallsDelta { steps: Vec<serde_json::Value> }, |
| 715 | } |
| 716 | |
| 717 | #[derive(Debug, Deserialize, Clone, Default)] |
| 718 | /// Delta payload for message-level updates. |
| 719 | pub struct MessageDelta { |
| 720 | pub stop_reason: Option<String>, |
| 721 | pub stop_sequence: Option<String>, |
| 722 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 723 | pub title: Option<String>, |
| 724 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 725 | pub stop_details: Option<serde_json::Value>, |
| 726 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 727 | pub refusal: Option<String>, |
| 728 | } |
| 729 | |
| 730 | #[cfg(test)] |
| 731 | mod tests { |
| 732 | use super::*; |
| 733 | use std::any::TypeId; |
| 734 | |
| 735 | #[test] |
| 736 | fn redacted_thinking_stream_start_decodes_with_its_payload() { |
| 737 | // A safeguard-triggered redacted block arrives complete on the start |
| 738 | // event. Before the variant existed this line failed the whole SSE |
| 739 | // event decode and lost the turn. |
| 740 | let block: ContentBlockStart = serde_json::from_value(serde_json::json!({ |
| 741 | "type": "redacted_thinking", |
| 742 | "data": "ENC_REDACTED_PAYLOAD", |
| 743 | })) |
| 744 | .expect("redacted_thinking must decode"); |
| 745 | match block { |
| 746 | ContentBlockStart::RedactedThinking { data } => { |
| 747 | assert_eq!(data, "ENC_REDACTED_PAYLOAD"); |
| 748 | } |
| 749 | other => panic!("expected RedactedThinking, got {other:?}"), |
| 750 | } |
| 751 | } |
| 752 | |
| 753 | #[test] |
| 754 | fn redacted_thinking_start_tolerates_an_explicit_null_payload() { |
| 755 | // `#[serde(default)]` covers a missing key only; a nonconforming |
| 756 | // gateway sending `"data": null` must still decode to the empty |
| 757 | // payload (capture warn downstream) instead of failing the whole |
| 758 | // SSE event and silently losing the turn's redacted block. |
| 759 | let block: ContentBlockStart = serde_json::from_value(serde_json::json!({ |
| 760 | "type": "redacted_thinking", |
| 761 | "data": null, |
| 762 | })) |
| 763 | .expect("an explicit null payload must not fail the event decode"); |
| 764 | match block { |
| 765 | ContentBlockStart::RedactedThinking { data } => { |
| 766 | assert_eq!(data, ""); |
| 767 | } |
| 768 | other => panic!("expected RedactedThinking, got {other:?}"), |
| 769 | } |
| 770 | } |
| 771 | |
| 772 | /// #6032: `model_supports_reasoning` consults the catalog before its |
| 773 | /// hand-maintained pile, so a literal arm that duplicates a catalog row is |
| 774 | /// unreachable. These 27 arms were exactly that and were deleted. They must |
| 775 | /// keep answering `true` from the catalog *alone* — if a row is ever |
| 776 | /// dropped, this fails loudly here rather than silently reverting them to |
| 777 | /// "reasoning not expected", which leaks their `reasoning_content` into |
| 778 | /// ordinary prose (#6044). |
| 779 | #[test] |
| 780 | fn unknown_reasoning_capability_is_observable() { |
| 781 | assert_eq!( |
| 782 | model_reasoning_capability("not-a-real-model-xyz"), |
| 783 | None, |
| 784 | "unknown must not collapse to false at this layer" |
| 785 | ); |
| 786 | assert!( |
| 787 | !model_supports_reasoning("not-a-real-model-xyz"), |
| 788 | "legacy bool wrapper still defaults unknown to false" |
| 789 | ); |
| 790 | assert_eq!(model_reasoning_capability("kimi-for-coding"), Some(true)); |
| 791 | } |
| 792 | |
| 793 | #[test] |
| 794 | fn catalog_alone_covers_the_models_removed_from_the_heuristic_pile() { |
| 795 | let removed = [ |
| 796 | "claude-opus-4-8", |
| 797 | "claude-opus-5", |
| 798 | "claude-sonnet-4-6", |
| 799 | "claude-sonnet-5", |
| 800 | "claude-fable-5", |
| 801 | "gpt-5-codex", |
| 802 | "gpt-5.3-codex", |
| 803 | "trinity-mini", |
| 804 | "trinity-large-thinking", |
| 805 | "moonshotai/kimi-k2.7-code", |
| 806 | "kimi-k2.7-code", |
| 807 | "minimax/minimax-m3", |
| 808 | "minimax/minimax-m2.7", |
| 809 | "minimax-m2.7", |
| 810 | "qwen/qwen3.6-flash", |
| 811 | "mimo-v2.5", |
| 812 | "mimo-v2.5-pro", |
| 813 | "mimo-v2.5-pro-ultraspeed", |
| 814 | "z-ai/glm-5.2", |
| 815 | "z-ai/glm-5.3", |
| 816 | "z-ai/glm-5.3-flash", |
| 817 | "glm-5.2", |
| 818 | "glm-5.3", |
| 819 | "glm-5.3-flash", |
| 820 | "muse-spark-1.1", |
| 821 | "muse-spark-1.2", |
| 822 | "muse-spark-1.2-contributor", |
| 823 | // Part 2: cited qwen3.x / Kimi coding-route arms moved into the |
| 824 | // bundled catalog (Alibaba Cloud Model Studio deep-thinking docs; |
| 825 | // #3016 plus the 2026 K2.7 update). |
| 826 | "kimi-for-coding", |
| 827 | "kimi-for-coding-highspeed", |
| 828 | "kimi-k2.5", |
| 829 | "kimi-k2.6", |
| 830 | "qwen3.5-flash", |
| 831 | "qwen3.5-plus", |
| 832 | "qwen3.6-flash", |
| 833 | "qwen3.6-plus", |
| 834 | "qwen3.7-max", |
| 835 | "qwen3.7-plus", |
| 836 | "qwen3.8-flash", |
| 837 | "qwen3.8-max", |
| 838 | "qwen3.8-max-preview", |
| 839 | ]; |
| 840 | for model in removed { |
| 841 | assert_eq!( |
| 842 | codewhale_config::catalog::reviewed::intrinsic_model(model) |
| 843 | .and_then(|row| row.reasoning), |
| 844 | Some(true), |
| 845 | "{model} no longer has a catalog row, but its heuristic arm was \ |
| 846 | deleted in #6032 — restore the row, or put the arm back" |
| 847 | ); |
| 848 | assert!( |
| 849 | model_supports_reasoning(model), |
| 850 | "{model} must still classify as reasoning-capable" |
| 851 | ); |
| 852 | } |
| 853 | } |
| 854 | |
| 855 | /// #6032 part 3: the eight literal arms deleted in favor of the bundled |
| 856 | /// Models.dev snapshot. Each id's `reasoning` bool is sourced there (all |
| 857 | /// `true`), so they must keep answering without a heuristic arm — if a |
| 858 | /// row is dropped from the asset, this fails loudly instead of silently |
| 859 | /// reverting them to "reasoning not expected" (#6044). |
| 860 | #[test] |
| 861 | fn models_dev_bundled_asset_covers_the_arms_deleted_from_the_heuristic_pile() { |
| 862 | let catalog = codewhale_config::catalog::bundled_models_dev_catalog(); |
| 863 | let deleted = [ |
| 864 | "qwen/qwen3.8-flash", |
| 865 | "qwen/qwen3.6-35b-a3b", |
| 866 | "qwen/qwen3.6-plus", |
| 867 | "qwen/qwen3.7-plus", |
| 868 | "glm-5.1", |
| 869 | "grok-4.6", |
| 870 | "grok-4.5", |
| 871 | "grok-4.3", |
| 872 | ]; |
| 873 | for model in deleted { |
| 874 | assert_eq!( |
| 875 | catalog.reasoning_support(model), |
| 876 | Some(true), |
| 877 | "{model} lost its bundled Models.dev row — restore its reviewed \ |
| 878 | source row (#6032)" |
| 879 | ); |
| 880 | assert!( |
| 881 | model_supports_reasoning(model), |
| 882 | "{model} must still classify as reasoning-capable" |
| 883 | ); |
| 884 | } |
| 885 | } |
| 886 | |
| 887 | /// #6032 coverage guard: exact reviewed facts and documented snapshot |
| 888 | /// contracts classify known models. Mistral's documented latest IDs now |
| 889 | /// have explicit reviewed reasoning facts; their family names and private |
| 890 | /// model names do not inherit those facts through a prefix heuristic. |
| 891 | #[test] |
| 892 | fn remaining_reasoning_heuristic_arms_are_unsourced_in_models_dev_bundled_asset() { |
| 893 | // Known facts are explicit data. Family resemblance is not a sourced |
| 894 | // capability, while the documented date-snapshot contract remains exact. |
| 895 | for model in [ |
| 896 | "kimi-k2.9", |
| 897 | "magistral-medium", |
| 898 | "claude-private-server", |
| 899 | "gpt-5.6-private", |
| 900 | ] { |
| 901 | assert_eq!(model_reasoning_capability(model), None, "{model}"); |
| 902 | } |
| 903 | for model in [ |
| 904 | "mistral-medium-latest", |
| 905 | "mistral-small-latest", |
| 906 | "gpt-5.5-2026-06-01", |
| 907 | "gpt-5.1-codex-max", |
| 908 | "codex-gpt-5.5-preview", |
| 909 | "chatgpt-gpt-5.5", |
| 910 | ] { |
| 911 | assert_eq!(model_reasoning_capability(model), Some(true), "{model}"); |
| 912 | } |
| 913 | } |
| 914 | |
| 915 | #[test] |
| 916 | fn output_limit_stop_reason_accepts_provider_aliases_only() { |
| 917 | for reason in [ |
| 918 | "length", |
| 919 | "max_tokens", |
| 920 | "max_output_tokens", |
| 921 | " MAX_TOKENS ", |
| 922 | "incomplete:max_output_tokens", |
| 923 | ] { |
| 924 | assert!(is_output_limit_stop_reason(Some(reason)), "{reason}"); |
| 925 | } |
| 926 | for reason in [None, Some("end_turn"), Some("tool_use"), Some("")] { |
| 927 | assert!(!is_output_limit_stop_reason(reason), "{reason:?}"); |
| 928 | } |
| 929 | } |
| 930 | |
| 931 | #[test] |
| 932 | fn stop_at_the_requested_ceiling_is_an_output_limit_stop() { |
| 933 | // #6889: 16000 requested, 16000 reported, `finish_reason: stop`. |
| 934 | assert!(stop_contradicts_output_ceiling( |
| 935 | Some("stop"), |
| 936 | Some(16_000), |
| 937 | 16_000 |
| 938 | )); |
| 939 | assert!(stop_contradicts_output_ceiling( |
| 940 | Some(" STOP "), |
| 941 | Some(50), |
| 942 | 50 |
| 943 | )); |
| 944 | assert!(is_output_limit_stop_reason(Some( |
| 945 | OUTPUT_CEILING_STOP_REASON |
| 946 | ))); |
| 947 | assert!(is_incomplete_stop_reason(Some(OUTPUT_CEILING_STOP_REASON))); |
| 948 | |
| 949 | // A finished answer leaves the allowance unfilled. |
| 950 | assert!(!stop_contradicts_output_ceiling( |
| 951 | Some("stop"), |
| 952 | Some(15_999), |
| 953 | 16_000 |
| 954 | )); |
| 955 | // Reasoning the provider does not count against the cap. |
| 956 | assert!(!stop_contradicts_output_ceiling( |
| 957 | Some("stop"), |
| 958 | Some(20_000), |
| 959 | 16_000 |
| 960 | )); |
| 961 | // No usage reported: nothing to compare. |
| 962 | assert!(!stop_contradicts_output_ceiling(Some("stop"), None, 16_000)); |
| 963 | // No ceiling requested. |
| 964 | assert!(!stop_contradicts_output_ceiling(Some("stop"), Some(0), 0)); |
| 965 | // Other wires and other stops keep their own reporting. |
| 966 | for reason in [None, Some("end_turn"), Some("tool_calls"), Some("length")] { |
| 967 | assert!( |
| 968 | !stop_contradicts_output_ceiling(reason, Some(16_000), 16_000), |
| 969 | "{reason:?}" |
| 970 | ); |
| 971 | } |
| 972 | } |
| 973 | |
| 974 | #[test] |
| 975 | fn incomplete_stop_reason_never_accepts_unknown_responses_failures() { |
| 976 | assert!(is_incomplete_stop_reason(Some("incomplete:content_filter"))); |
| 977 | assert!(is_incomplete_stop_reason(Some("content_filter"))); |
| 978 | assert!(is_incomplete_stop_reason(Some( |
| 979 | "model_context_window_exceeded" |
| 980 | ))); |
| 981 | assert!(is_incomplete_stop_reason(Some("max_tokens"))); |
| 982 | assert!(!is_incomplete_stop_reason(Some("end_turn"))); |
| 983 | assert_eq!( |
| 984 | stop_reason_detail(Some("incomplete:content_filter")), |
| 985 | "content_filter" |
| 986 | ); |
| 987 | } |
| 988 | |
| 989 | #[test] |
| 990 | fn historical_tui_request_path_is_the_core_request_type() { |
| 991 | assert_eq!( |
| 992 | TypeId::of::<MessageRequest>(), |
| 993 | TypeId::of::<codewhale_core::request::MessageRequest>() |
| 994 | ); |
| 995 | |
| 996 | let via_tui_path = MessageRequest { |
| 997 | model: "model".to_string(), |
| 998 | messages: vec![], |
| 999 | max_tokens: 1024, |
| 1000 | system: None, |
| 1001 | tools: None, |
| 1002 | tool_choice: None, |
| 1003 | metadata: None, |
| 1004 | thinking: None, |
| 1005 | reasoning_effort: None, |
| 1006 | stream: Some(true), |
| 1007 | temperature: None, |
| 1008 | top_p: None, |
| 1009 | safety_check: None, |
| 1010 | title: None, |
| 1011 | }; |
| 1012 | let via_core_path: codewhale_core::request::MessageRequest = via_tui_path.clone(); |
| 1013 | assert_eq!( |
| 1014 | serde_json::to_vec(&via_tui_path).expect("serialize TUI path"), |
| 1015 | serde_json::to_vec(&via_core_path).expect("serialize core path") |
| 1016 | ); |
| 1017 | } |
| 1018 | |
| 1019 | #[test] |
| 1020 | fn interrupted_assistant_role_round_trips_as_distinct_session_item() { |
| 1021 | let message = Message { |
| 1022 | role: Role::InterruptedAssistant, |
| 1023 | content: vec![ContentBlock::Text { |
| 1024 | text: "partial output".to_string(), |
| 1025 | cache_control: None, |
| 1026 | }], |
| 1027 | }; |
| 1028 | let encoded = serde_json::to_string(&message).expect("message should serialize"); |
| 1029 | let decoded: Message = serde_json::from_str(&encoded).expect("message should deserialize"); |
| 1030 | assert_eq!(decoded, message); |
| 1031 | assert_ne!(decoded.role, "assistant"); |
| 1032 | } |
| 1033 | |
| 1034 | #[test] |
| 1035 | fn unrecognized_deepseek_models_do_not_inherit_sibling_metadata() { |
| 1036 | for model in [ |
| 1037 | "deepseek-v4-flash-20260423", |
| 1038 | "deepseek-v4-pro-20260423", |
| 1039 | "deepseek-coder", |
| 1040 | "deepseek-v3.2-0324", |
| 1041 | "deepseek-v4.1-flash-expires-on-0910", |
| 1042 | ] { |
| 1043 | assert_eq!(context_window_for_model(model), None, "{model}"); |
| 1044 | } |
| 1045 | assert!(!model_supports_reasoning( |
| 1046 | "deepseek-v4.1-flash-expires-on-0910" |
| 1047 | )); |
| 1048 | } |
| 1049 | |
| 1050 | #[test] |
| 1051 | fn deepseek_v4_models_map_to_1m_context_window() { |
| 1052 | assert_eq!( |
| 1053 | context_window_for_model("deepseek-v4-pro"), |
| 1054 | Some(DEEPSEEK_V4_CONTEXT_WINDOW_TOKENS) |
| 1055 | ); |
| 1056 | assert_eq!( |
| 1057 | context_window_for_model("deepseek-v4-flash"), |
| 1058 | Some(DEEPSEEK_V4_CONTEXT_WINDOW_TOKENS) |
| 1059 | ); |
| 1060 | assert_eq!( |
| 1061 | context_window_for_model("deepseek-ai/deepseek-v4-pro"), |
| 1062 | Some(DEEPSEEK_V4_CONTEXT_WINDOW_TOKENS) |
| 1063 | ); |
| 1064 | } |
| 1065 | |
| 1066 | #[test] |
| 1067 | fn deepseek_v4_output_caps_require_exact_catalog_metadata() { |
| 1068 | // `deepseek-v4.1-flash` used to sit in this list: it had no model-only |
| 1069 | // row, so its output ceiling came only from a provider offering, and a |
| 1070 | // custom endpoint that names the model without a vendor prefix fell |
| 1071 | // through to the 128K window. It now carries an exact row of its own |
| 1072 | // (see `bundled_catalog_resolves_the_bare_deepseek_v41_flash_spelling` |
| 1073 | // in `codewhale-config`), so it moved to the resolved list below. The |
| 1074 | // near-miss spellings stay unresolved — an exact row documents one |
| 1075 | // identifier, never a family. |
| 1076 | for model in [ |
| 1077 | "deepseek-v4.1-flash-expires-on-0910", |
| 1078 | "deepseek-v4.1-pro", |
| 1079 | "vendor/deepseek-v4.1-flash", |
| 1080 | "deepseek-v4-flash-vendor", |
| 1081 | ] { |
| 1082 | assert!( |
| 1083 | codewhale_config::catalog::reviewed::intrinsic_model(model).is_none(), |
| 1084 | "{model}" |
| 1085 | ); |
| 1086 | assert_eq!(max_output_tokens_for_model(model), None, "{model}"); |
| 1087 | } |
| 1088 | |
| 1089 | for model in [ |
| 1090 | "deepseek-v4-flash", |
| 1091 | "deepseek-v4-pro", |
| 1092 | "deepseek-v4-flash-vision-exp", |
| 1093 | "deepseek-v4.1-flash", |
| 1094 | "DEEPSEEK-V4-FLASH", |
| 1095 | ] { |
| 1096 | assert_eq!(max_output_tokens_for_model(model), Some(384_000), "{model}"); |
| 1097 | } |
| 1098 | } |
| 1099 | |
| 1100 | #[test] |
| 1101 | fn recent_openrouter_large_models_have_static_windows() { |
| 1102 | for (model, expected_window) in [ |
| 1103 | ("arcee-ai/trinity-large-thinking", 262_144), |
| 1104 | ("trinity-large-thinking", 262_144), |
| 1105 | (concat!("qwen/", "qwen3.8-flash"), 1_000_000), |
| 1106 | (concat!("qwen/", "qwen3.6-flash"), 1_000_000), |
| 1107 | (concat!("qwen/", "qwen3.6-35b-a3b"), 262_144), |
| 1108 | (concat!("qwen/", "qwen3.6-max-preview"), 262_144), |
| 1109 | (concat!("qwen/", "qwen3.6-plus"), 1_000_000), |
| 1110 | (concat!("xiaomi/", "mimo-v2.5-pro"), 1_000_000), |
| 1111 | ("mimo-v2.5-pro", 1_000_000), |
| 1112 | ("mimo-v2.5-pro-ultraspeed", 1_000_000), |
| 1113 | ("mimo-v2.5", 1_000_000), |
| 1114 | ("minimax/minimax-m3", 1_000_000), |
| 1115 | ("minimax/minimax-m2.7", 204_800), |
| 1116 | ("moonshotai/kimi-k2.7-code", 262_144), |
| 1117 | ("moonshotai/kimi-k2.6", 262_144), |
| 1118 | ("google/gemma-4-31b-it", 262_144), |
| 1119 | ("z-ai/glm-5.1", 202_752), |
| 1120 | ("z-ai/glm-5.2", 1_000_000), |
| 1121 | ("z-ai/glm-5.3", 1_000_000), |
| 1122 | ("z-ai/glm-5.3-flash", 1_000_000), |
| 1123 | ] { |
| 1124 | assert_eq!(context_window_for_model(model), Some(expected_window)); |
| 1125 | assert!(model_supports_reasoning(model)); |
| 1126 | } |
| 1127 | } |
| 1128 | |
| 1129 | #[test] |
| 1130 | fn openai_api_and_codex_models_have_verified_context_metadata() { |
| 1131 | for model in ["gpt-5.6", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna"] { |
| 1132 | assert_eq!(context_window_for_model(model), Some(1_050_000)); |
| 1133 | assert_eq!(max_output_tokens_for_model(model), Some(128_000)); |
| 1134 | assert!(model_supports_reasoning(model)); |
| 1135 | assert_eq!( |
| 1136 | compaction_threshold_for_model_at_percent(model, 80.0), |
| 1137 | 840_000 |
| 1138 | ); |
| 1139 | } |
| 1140 | |
| 1141 | for model in [ |
| 1142 | "gpt-5.5", |
| 1143 | "gpt-5.5-pro", |
| 1144 | "gpt-5.5-2026-04-23", |
| 1145 | "gpt-5.5-pro-2026-04-23", |
| 1146 | ] { |
| 1147 | assert_eq!(context_window_for_model(model), Some(1_050_000)); |
| 1148 | assert_eq!(max_output_tokens_for_model(model), Some(128_000)); |
| 1149 | assert!(model_supports_reasoning(model)); |
| 1150 | assert_eq!( |
| 1151 | compaction_threshold_for_model_at_percent(model, 80.0), |
| 1152 | 840_000 |
| 1153 | ); |
| 1154 | } |
| 1155 | |
| 1156 | for model in [ |
| 1157 | "gpt-5-codex", |
| 1158 | "gpt-5.1-codex", |
| 1159 | "gpt-5.1-codex-mini", |
| 1160 | "gpt-5.1-codex-max", |
| 1161 | "gpt-5.2-codex", |
| 1162 | "gpt-5.3-codex", |
| 1163 | "codex-gpt-5.5", |
| 1164 | "chatgpt-gpt-5.5", |
| 1165 | "gpt-5.5-codex", |
| 1166 | "gpt-5.5-codex-preview", |
| 1167 | ] { |
| 1168 | assert_eq!(context_window_for_model(model), Some(400_000)); |
| 1169 | assert_eq!(max_output_tokens_for_model(model), Some(128_000)); |
| 1170 | assert!(model_supports_reasoning(model)); |
| 1171 | assert_eq!( |
| 1172 | compaction_threshold_for_model_at_percent(model, 80.0), |
| 1173 | 320_000 |
| 1174 | ); |
| 1175 | } |
| 1176 | |
| 1177 | assert_eq!(context_window_for_model("gpt-5.5-nano"), None); |
| 1178 | assert_eq!(max_output_tokens_for_model("gpt-5.5-nano"), None); |
| 1179 | assert!(!model_supports_reasoning("gpt-5.5-nano")); |
| 1180 | } |
| 1181 | |
| 1182 | #[test] |
| 1183 | fn anthropic_stepfun_and_sakana_limits_match_2026_07_09_audit() { |
| 1184 | // Sonnet 4.6 output cap raised 64K -> 128K per |
| 1185 | // https://platform.claude.com/docs/en/about-claude/models/overview; |
| 1186 | // Haiku stays at 64K. |
| 1187 | assert_eq!( |
| 1188 | max_output_tokens_for_model("claude-sonnet-4-6"), |
| 1189 | Some(128_000) |
| 1190 | ); |
| 1191 | assert_eq!( |
| 1192 | max_output_tokens_for_model("claude-haiku-4-5"), |
| 1193 | Some(64_000) |
| 1194 | ); |
| 1195 | // step-3.7-flash max output is third-party sourced (models.dev + |
| 1196 | // Artificial Analysis; the official StepFun page is silent): |
| 1197 | // https://models.dev/models/stepfun/step-3.7-flash/ |
| 1198 | assert_eq!(max_output_tokens_for_model("step-3.7-flash"), Some(256_000)); |
| 1199 | assert_eq!(context_window_for_model("step-3.7-flash"), Some(256_000)); |
| 1200 | // fugu-ultra limits are third-party sourced (Requesty; Sakana's own |
| 1201 | // >272K price tier at https://console.sakana.ai/pricing confirms the |
| 1202 | // context window exceeds 272K). |
| 1203 | for model in ["fugu-ultra", "fugu-ultra-20260615"] { |
| 1204 | assert_eq!(context_window_for_model(model), Some(1_000_000), "{model}"); |
| 1205 | assert_eq!(max_output_tokens_for_model(model), Some(131_000), "{model}"); |
| 1206 | } |
| 1207 | } |
| 1208 | |
| 1209 | #[test] |
| 1210 | fn stepfun_current_coding_models_have_verified_metadata() { |
| 1211 | assert_eq!(context_window_for_model("step-5"), Some(1_000_000)); |
| 1212 | assert_eq!(max_output_tokens_for_model("step-5"), Some(65_536)); |
| 1213 | assert_eq!(context_window_for_model("step-5-preview"), Some(1_000_000)); |
| 1214 | assert_eq!( |
| 1215 | max_output_tokens_for_model("step-5-preview"), |
| 1216 | Some(1_000_000) |
| 1217 | ); |
| 1218 | for model in [ |
| 1219 | "step-5", |
| 1220 | "step-5-preview", |
| 1221 | "step-3.7-flash", |
| 1222 | "step-3.5-flash", |
| 1223 | "step-3.5-flash-2603", |
| 1224 | ] { |
| 1225 | assert!(model_supports_reasoning(model), "{model}"); |
| 1226 | } |
| 1227 | for model in ["step-3.5-flash", "step-3.5-flash-2603"] { |
| 1228 | assert_eq!(context_window_for_model(model), Some(256_000)); |
| 1229 | assert_eq!(max_output_tokens_for_model(model), None); |
| 1230 | } |
| 1231 | } |
| 1232 | |
| 1233 | #[test] |
| 1234 | fn claude_fable_5_and_sonnet_5_have_verified_metadata() { |
| 1235 | // 1M context / 128K output per |
| 1236 | // https://platform.claude.com/docs/en/about-claude/pricing (2026-07-09). |
| 1237 | for model in ["claude-fable-5", "claude-sonnet-5"] { |
| 1238 | assert_eq!(context_window_for_model(model), Some(1_000_000), "{model}"); |
| 1239 | assert_eq!(max_output_tokens_for_model(model), Some(128_000), "{model}"); |
| 1240 | assert!(model_supports_reasoning(model), "{model}"); |
| 1241 | } |
| 1242 | } |
| 1243 | |
| 1244 | #[test] |
| 1245 | fn claude_opus_5_has_verified_metadata() { |
| 1246 | // 1M context / 128K output, adaptive thinking, per |
| 1247 | // https://platform.claude.com/docs/en/about-claude/models/overview |
| 1248 | // (2026-08-17). |
| 1249 | assert_eq!(context_window_for_model("claude-opus-5"), Some(1_000_000)); |
| 1250 | assert_eq!(max_output_tokens_for_model("claude-opus-5"), Some(128_000)); |
| 1251 | assert!(model_supports_reasoning("claude-opus-5")); |
| 1252 | } |
| 1253 | |
| 1254 | #[test] |
| 1255 | fn kimi_k2_7_code_highspeed_shares_the_k2_7_code_limits() { |
| 1256 | // https://platform.kimi.ai/docs/pricing/chat-k27-code (2026-08-17): |
| 1257 | // same model as kimi-k2.7-code, 262,144 context. |
| 1258 | for model in [ |
| 1259 | "kimi-k2.7-code-highspeed", |
| 1260 | "moonshotai/kimi-k2.7-code-highspeed", |
| 1261 | ] { |
| 1262 | assert_eq!(context_window_for_model(model), Some(262_144), "{model}"); |
| 1263 | assert_eq!(max_output_tokens_for_model(model), Some(32_768), "{model}"); |
| 1264 | assert!(model_supports_reasoning(model), "{model}"); |
| 1265 | } |
| 1266 | } |
| 1267 | |
| 1268 | #[test] |
| 1269 | fn gemini_api_models_have_documented_token_limits() { |
| 1270 | // Every current Gemini API text model page lists 1,048,576 input / |
| 1271 | // 65,536 output (verified 2026-08-17, see |
| 1272 | // `known_context_window_for_model`). |
| 1273 | for model in [ |
| 1274 | "gemini-4-carbon", |
| 1275 | "gemini-4-argon", |
| 1276 | "gemini-3.7-flash", |
| 1277 | "gemini-3.6-flash", |
| 1278 | "gemini-3.5-flash", |
| 1279 | "gemini-3.5-flash-lite", |
| 1280 | "gemini-3.1-pro-preview", |
| 1281 | "gemini-3-pro-preview", |
| 1282 | "gemini-2.5-pro", |
| 1283 | "gemini-2.5-flash", |
| 1284 | ] { |
| 1285 | assert_eq!(context_window_for_model(model), Some(1_048_576), "{model}"); |
| 1286 | assert_eq!(max_output_tokens_for_model(model), Some(65_536), "{model}"); |
| 1287 | } |
| 1288 | } |
| 1289 | |
| 1290 | #[test] |
| 1291 | fn muse_spark_has_verified_context_and_reasoning_metadata() { |
| 1292 | assert_eq!(context_window_for_model("muse-spark-1.1"), Some(1_000_000)); |
| 1293 | assert_eq!(max_output_tokens_for_model("muse-spark-1.1"), Some(32_000)); |
| 1294 | assert!(model_supports_reasoning("muse-spark-1.1")); |
| 1295 | // Muse Spark 1.2 standard: 1M context, $1.25/$4.25 + $0.15 cache (Artificial Analysis). |
| 1296 | assert_eq!(context_window_for_model("muse-spark-1.2"), Some(1_000_000)); |
| 1297 | assert_eq!(max_output_tokens_for_model("muse-spark-1.2"), Some(32_000)); |
| 1298 | assert!(model_supports_reasoning("muse-spark-1.2")); |
| 1299 | // Contributor tier: same model/limits, ~12×/21× cheaper in exchange for training-data opt-in. |
| 1300 | assert_eq!( |
| 1301 | context_window_for_model("muse-spark-1.2-contributor"), |
| 1302 | Some(1_000_000) |
| 1303 | ); |
| 1304 | assert_eq!( |
| 1305 | max_output_tokens_for_model("muse-spark-1.2-contributor"), |
| 1306 | Some(32_000) |
| 1307 | ); |
| 1308 | assert!(model_supports_reasoning("muse-spark-1.2-contributor")); |
| 1309 | } |
| 1310 | |
| 1311 | #[test] |
| 1312 | fn modelstudio_qwen38_max_is_1m_context_not_128k() { |
| 1313 | // Owner Token Plan console + curated catalog (2026-08-03). The 128K |
| 1314 | // figure is max output, not the window — never collapse them. |
| 1315 | for model in ["qwen3.8-max", "qwen3.8-max-preview"] { |
| 1316 | assert_eq!(context_window_for_model(model), Some(1_000_000), "{model}"); |
| 1317 | assert_eq!(max_output_tokens_for_model(model), Some(131_072), "{model}"); |
| 1318 | } |
| 1319 | } |
| 1320 | |
| 1321 | #[test] |
| 1322 | fn openrouter_qwen38_flash_is_1m_context_with_128k_output() { |
| 1323 | // models.dev OpenRouter listing 2026-08-26: 1,000,000 / 131,072. |
| 1324 | // Both the namespaced wire id and the bare short id must resolve. |
| 1325 | for model in ["qwen/qwen3.8-flash", "qwen3.8-flash"] { |
| 1326 | assert_eq!(context_window_for_model(model), Some(1_000_000), "{model}"); |
| 1327 | assert_eq!(max_output_tokens_for_model(model), Some(131_072), "{model}"); |
| 1328 | assert!(model_supports_reasoning(model), "{model}"); |
| 1329 | } |
| 1330 | } |
| 1331 | |
| 1332 | #[test] |
| 1333 | fn modelstudio_bare_qwen_models_support_reasoning() { |
| 1334 | // Model Studio's deep-thinking docs: every qwen3.x family the Token / |
| 1335 | // Coding Plan catalogs carry is hybrid-thinking (reasoning_content on |
| 1336 | // the OpenAI dialect, thinking blocks on the Anthropic dialect). |
| 1337 | for model in [ |
| 1338 | "qwen3.8-max", |
| 1339 | "qwen3.8-max-preview", |
| 1340 | "qwen3.7-max", |
| 1341 | "qwen3.7-plus", |
| 1342 | "qwen3.6-plus", |
| 1343 | "qwen3.6-flash", |
| 1344 | "qwen3.5-plus", |
| 1345 | "qwen3.5-flash", |
| 1346 | ] { |
| 1347 | assert!(model_supports_reasoning(model), "{model}"); |
| 1348 | } |
| 1349 | } |
| 1350 | |
| 1351 | #[test] |
| 1352 | fn model_metadata_catalog_override_flows_through_models_chokepoint() { |
| 1353 | let private=codewhale_config::models_dev::ModelsDevCatalog::parse_json(r#"{"providers":{"private":{"models":{"catalog-only-model":{"limit":{"context":777000,"output":55000},"reasoning":true}}}}}"#).unwrap(); |
| 1354 | assert!( |
| 1355 | codewhale_config::catalog::reviewed::intrinsic_model_in(&private, "catalog-only-model") |
| 1356 | .is_none() |
| 1357 | ); |
| 1358 | assert_eq!(context_window_for_model("catalog-only-model"), None); |
| 1359 | assert_eq!(max_output_tokens_for_model("catalog-only-model"), None); |
| 1360 | assert_eq!(model_reasoning_capability("catalog-only-model"), None); |
| 1361 | } |
| 1362 | |
| 1363 | #[test] |
| 1364 | fn moonshot_native_kimi_ids_support_reasoning_including_coding_route() { |
| 1365 | // #3016: bare Moonshot ids (no moonshotai/ prefix) emit |
| 1366 | // reasoning_content; kimi-for-coding currently rides the K2.7 Code path. |
| 1367 | assert!(model_supports_reasoning("kimi-k2.7-code")); |
| 1368 | assert!(model_supports_reasoning("kimi-k2.6")); |
| 1369 | assert!(model_supports_reasoning("kimi-for-coding")); |
| 1370 | assert!(model_supports_reasoning("kimi-for-coding-highspeed")); |
| 1371 | assert!(model_supports_reasoning("kimi-k2.5")); |
| 1372 | } |
| 1373 | |
| 1374 | #[test] |
| 1375 | fn xai_grok_models_have_static_context_metadata() { |
| 1376 | for (model, expected_window, supports_reasoning) in [ |
| 1377 | ("grok-4.6", 500_000, true), |
| 1378 | ("grok-4.5", 500_000, true), |
| 1379 | ("grok-4.3", 1_000_000, true), |
| 1380 | ("grok-build", 512_000, true), |
| 1381 | ("grok-composer-2.5-fast", 200_000, false), |
| 1382 | ("grok-4.20-0309-reasoning", 2_000_000, true), |
| 1383 | ("grok-4.20-0309-non-reasoning", 2_000_000, false), |
| 1384 | ] { |
| 1385 | assert_eq!(context_window_for_model(model), Some(expected_window)); |
| 1386 | assert_eq!(max_output_tokens_for_model(model), None); |
| 1387 | assert_eq!(model_supports_reasoning(model), supports_reasoning); |
| 1388 | } |
| 1389 | } |
| 1390 | |
| 1391 | #[test] |
| 1392 | fn arcee_direct_models_preserve_verified_capabilities_only() { |
| 1393 | assert_eq!( |
| 1394 | context_window_for_model("trinity-large-preview"), |
| 1395 | Some(262_144) |
| 1396 | ); |
| 1397 | assert!(!model_supports_reasoning("trinity-large-preview")); |
| 1398 | assert_eq!(context_window_for_model("trinity-mini"), Some(128_000)); |
| 1399 | assert_eq!(max_output_tokens_for_model("trinity-mini"), None); |
| 1400 | assert!(model_supports_reasoning("trinity-mini")); |
| 1401 | } |
| 1402 | |
| 1403 | #[test] |
| 1404 | fn qwen37_plus_and_inkling_reasoning_do_not_invent_limits() { |
| 1405 | for model in ["qwen/qwen3.7-plus", "thinkingmachines/inkling"] { |
| 1406 | assert_eq!(context_window_for_model(model), None, "{model}"); |
| 1407 | assert_eq!(max_output_tokens_for_model(model), None, "{model}"); |
| 1408 | assert!(model_supports_reasoning(model), "{model}"); |
| 1409 | } |
| 1410 | } |
| 1411 | |
| 1412 | #[test] |
| 1413 | fn recent_openrouter_large_models_have_known_output_caps() { |
| 1414 | assert_eq!( |
| 1415 | max_output_tokens_for_model("arcee-ai/trinity-large-thinking"), |
| 1416 | Some(262_144) |
| 1417 | ); |
| 1418 | assert_eq!( |
| 1419 | max_output_tokens_for_model("trinity-large-thinking"), |
| 1420 | Some(262_144) |
| 1421 | ); |
| 1422 | assert_eq!( |
| 1423 | max_output_tokens_for_model(concat!("qwen/", "qwen3.8-flash")), |
| 1424 | Some(131_072) |
| 1425 | ); |
| 1426 | assert_eq!( |
| 1427 | max_output_tokens_for_model(concat!("qwen/", "qwen3.6-flash")), |
| 1428 | Some(65_536) |
| 1429 | ); |
| 1430 | assert_eq!( |
| 1431 | max_output_tokens_for_model(concat!("qwen/", "qwen3.6-max-preview")), |
| 1432 | Some(65_536) |
| 1433 | ); |
| 1434 | assert_eq!( |
| 1435 | max_output_tokens_for_model(concat!("qwen/", "qwen3.6-plus")), |
| 1436 | Some(65_536) |
| 1437 | ); |
| 1438 | assert_eq!( |
| 1439 | max_output_tokens_for_model(concat!("xiaomi/", "mimo-v2.5-pro")), |
| 1440 | Some(131_072) |
| 1441 | ); |
| 1442 | assert_eq!(max_output_tokens_for_model("mimo-v2.5-pro"), Some(131_072)); |
| 1443 | assert_eq!( |
| 1444 | max_output_tokens_for_model("mimo-v2.5-pro-ultraspeed"), |
| 1445 | Some(131_072) |
| 1446 | ); |
| 1447 | assert_eq!(max_output_tokens_for_model("mimo-v2.5"), Some(131_072)); |
| 1448 | assert_eq!( |
| 1449 | max_output_tokens_for_model("minimax/minimax-m3"), |
| 1450 | Some(524_288) |
| 1451 | ); |
| 1452 | assert_eq!(max_output_tokens_for_model("z-ai/glm-5.1"), Some(131_072)); |
| 1453 | assert_eq!(max_output_tokens_for_model("z-ai/glm-5.2"), Some(131_072)); |
| 1454 | assert_eq!(max_output_tokens_for_model("z-ai/glm-5.3"), Some(131_072)); |
| 1455 | assert_eq!( |
| 1456 | max_output_tokens_for_model("z-ai/glm-5-turbo"), |
| 1457 | Some(131_072) |
| 1458 | ); |
| 1459 | assert_eq!(max_output_tokens_for_model("glm-5-turbo"), Some(131_072)); |
| 1460 | } |
| 1461 | |
| 1462 | #[test] |
| 1463 | fn k3_route_ids_use_verified_contracts_not_legacy_128k() { |
| 1464 | // Open-platform K3 carries the verified 1M contract. |
| 1465 | assert_eq!(context_window_for_model("kimi-k3"), Some(1_048_576)); |
| 1466 | assert_eq!( |
| 1467 | context_window_for_model("opencode-go/kimi-k3"), |
| 1468 | Some(1_048_576) |
| 1469 | ); |
| 1470 | // Bare `k3` (Kimi Code membership) is plan-tier dependent, so it |
| 1471 | // keeps the documented safe floor — and must never fall through to |
| 1472 | // the 128K legacy default. |
| 1473 | assert_eq!(context_window_for_model("k3"), Some(262_144)); |
| 1474 | assert_eq!(context_window_for_model("k3-256k"), Some(262_144)); |
| 1475 | assert_eq!(max_output_tokens_for_model("k3"), Some(131_072)); |
| 1476 | assert_eq!(max_output_tokens_for_model("k3-256k"), Some(131_072)); |
| 1477 | assert_eq!(max_output_tokens_for_model("kimi-k3"), Some(131_072)); |
| 1478 | // Never project max output as the context window. |
| 1479 | assert_ne!( |
| 1480 | context_window_for_model("k3"), |
| 1481 | max_output_tokens_for_model("k3") |
| 1482 | ); |
| 1483 | assert_ne!( |
| 1484 | context_window_for_model("kimi-k3"), |
| 1485 | max_output_tokens_for_model("kimi-k3") |
| 1486 | ); |
| 1487 | } |
| 1488 | |
| 1489 | #[test] |
| 1490 | fn kimi_code_membership_ids_mirror_their_family_facts() { |
| 1491 | // The high-speed membership id rides the kimi-for-coding family |
| 1492 | // context fact (256K) and reasoning support via the same `kimi-` |
| 1493 | // native-id rule as `kimi-for-coding`. No client-side output ceiling |
| 1494 | // is claimed for the membership ids — the membership catalog is the |
| 1495 | // source of truth, so the generic lookup returns None. |
| 1496 | assert_eq!( |
| 1497 | context_window_for_model("kimi-for-coding-highspeed"), |
| 1498 | Some(262_144) |
| 1499 | ); |
| 1500 | assert_eq!( |
| 1501 | max_output_tokens_for_model("kimi-for-coding-highspeed"), |
| 1502 | None |
| 1503 | ); |
| 1504 | assert_eq!(max_output_tokens_for_model("kimi-for-coding"), None); |
| 1505 | assert!(model_supports_reasoning("kimi-for-coding-highspeed")); |
| 1506 | } |
| 1507 | |
| 1508 | #[test] |
| 1509 | fn bare_provider_model_ids_mirror_vendor_prefixed_rows() { |
| 1510 | // Direct-provider routes (Moonshot, MiniMax, Z.ai) serve bare model |
| 1511 | // ids without the OpenRouter vendor prefix; both spellings must |
| 1512 | // resolve identical metadata (#1310 ride-along on #3023). |
| 1513 | for (model, expected_window) in [ |
| 1514 | ("kimi-k3", 1_048_576), |
| 1515 | ("kimi-k2.7-code", 262_144), |
| 1516 | ("kimi-k2.6", 262_144), |
| 1517 | ("minimax-m3", 1_000_000), |
| 1518 | ("minimax-m2.7", 204_800), |
| 1519 | ("minimax-m2.5-highspeed", 204_800), |
| 1520 | ("minimax-m2", 204_800), |
| 1521 | ("glm-5.1", 202_752), |
| 1522 | ("glm-5.2", 1_000_000), |
| 1523 | // Inherited from glm-5.2 pending official Z.ai release metadata. |
| 1524 | ("glm-5.3", 1_000_000), |
| 1525 | ("glm-5.3-flash", 1_000_000), |
| 1526 | ("glm-5-turbo", 202_752), |
| 1527 | ] { |
| 1528 | assert_eq!(context_window_for_model(model), Some(expected_window)); |
| 1529 | assert!(model_supports_reasoning(model)); |
| 1530 | } |
| 1531 | assert_eq!(context_window_for_model("kimi-for-coding"), Some(262_144)); |
| 1532 | assert!(model_supports_reasoning("kimi-for-coding")); |
| 1533 | assert_eq!(context_window_for_model("glm-5v-turbo"), Some(202_752)); |
| 1534 | assert!(!model_supports_reasoning("glm-5v-turbo")); |
| 1535 | // GLM-5-Turbo is a fast text sibling (distinct from the glm-5v-turbo |
| 1536 | // vision model): same compact window as 5.1 but reasoning-capable. |
| 1537 | assert_eq!(context_window_for_model("z-ai/glm-5-turbo"), Some(202_752)); |
| 1538 | assert!(model_supports_reasoning("z-ai/glm-5-turbo")); |
| 1539 | assert_eq!( |
| 1540 | codewhale_config::catalog::reviewed::intrinsic_model("kimi-k2.7-code") |
| 1541 | .and_then(|row| row.generation_default.or(row.max_output)), |
| 1542 | Some(32_768) |
| 1543 | ); |
| 1544 | assert_eq!(max_output_tokens_for_model("kimi-k2.7-code"), Some(32_768)); |
| 1545 | assert_eq!(max_output_tokens_for_model("kimi-k2.6"), Some(32_768)); |
| 1546 | assert_eq!(max_output_tokens_for_model("kimi-for-coding"), None); |
| 1547 | assert_eq!(max_output_tokens_for_model("kimi-k3"), Some(131_072)); |
| 1548 | assert_eq!(max_output_tokens_for_model("minimax-m3"), Some(524_288)); |
| 1549 | assert_eq!(max_output_tokens_for_model("glm-5.1"), Some(131_072)); |
| 1550 | assert_eq!(max_output_tokens_for_model("glm-5.2"), Some(131_072)); |
| 1551 | assert_eq!(max_output_tokens_for_model("glm-5.3"), Some(131_072)); |
| 1552 | assert_eq!(max_output_tokens_for_model("glm-5.3-flash"), Some(131_072)); |
| 1553 | } |
| 1554 | |
| 1555 | #[test] |
| 1556 | fn deepseek_models_with_k_suffix_use_hint() { |
| 1557 | assert_eq!(context_window_for_model("deepseek-v3.2-32k"), Some(32_000)); |
| 1558 | assert_eq!( |
| 1559 | context_window_for_model("deepseek-v3.2-256k-preview"), |
| 1560 | Some(256_000) |
| 1561 | ); |
| 1562 | assert_eq!(context_window_for_model("deepseek-v3.2-2k-preview"), None); |
| 1563 | } |
| 1564 | |
| 1565 | /// 2026-10-05: custom gateways serve V4 under snapshot and variant ids |
| 1566 | /// the reviewed catalog does not enumerate (`deepseek-v4-pro-0813`, |
| 1567 | /// `deepseek-v4-flash-vision`). They denote the same rows as their base |
| 1568 | /// ids and must inherit the base facts instead of falling back to the |
| 1569 | /// 128K unknown shape. |
| 1570 | #[test] |
| 1571 | fn deepseek_v4_snapshot_and_variant_ids_inherit_reviewed_facts() { |
| 1572 | for model in [ |
| 1573 | "deepseek-v4-pro-0813", |
| 1574 | "DeepSeek-V4-Pro-0813", |
| 1575 | "deepseek-v4-pro-2025-08-13", |
| 1576 | "deepseek-v4-flash-vision", |
| 1577 | "deepseek-v4-flash-vision-0813", |
| 1578 | ] { |
| 1579 | assert_eq!(context_window_for_model(model), Some(1_000_000), "{model}"); |
| 1580 | assert_eq!(max_output_tokens_for_model(model), Some(384_000), "{model}"); |
| 1581 | assert!(model_supports_reasoning(model), "{model}"); |
| 1582 | } |
| 1583 | // A trailing number that is not a recognized date stamp, an |
| 1584 | // eight-digit compact stamp, or an unknown base, stays unknown: the |
| 1585 | // resolver never invents a row. |
| 1586 | for model in [ |
| 1587 | "not-a-model-0813", |
| 1588 | "deepseek-v4-pro-9913", |
| 1589 | "deepseek-v4-pro-08130", |
| 1590 | "deepseek-v4-pro-x0813", |
| 1591 | "deepseek-v4-pro-20250813", |
| 1592 | ] { |
| 1593 | assert_eq!(context_window_for_model(model), None, "{model}"); |
| 1594 | assert_eq!(model_reasoning_capability(model), None, "{model}"); |
| 1595 | } |
| 1596 | // Snapshot resolution must not relabel a DeepSeek row as an OpenAI |
| 1597 | // reasoning model, while the OpenAI snapshot contract keeps working. |
| 1598 | assert!(!model_is_openai_reasoning_family("deepseek-v4-pro-0813")); |
| 1599 | assert!(model_is_openai_reasoning_family("gpt-5.5-2026-06-01")); |
| 1600 | } |
| 1601 | |
| 1602 | /// Multi-byte model ids must not panic the byte-indexed date scan: the |
| 1603 | /// `-YYYY-MM-DD` layer splits at `len - 10`, which need not be a UTF-8 |
| 1604 | /// char boundary (review finding from the PR #6 review). |
| 1605 | #[test] |
| 1606 | fn non_ascii_ids_do_not_panic_the_snapshot_scan() { |
| 1607 | for model in ["模型模型模型模型", "ローカルモデル-2026", "モデル-0813"] { |
| 1608 | assert_eq!(context_window_for_model(model), None, "{model}"); |
| 1609 | assert_eq!(model_reasoning_capability(model), None, "{model}"); |
| 1610 | } |
| 1611 | } |
| 1612 | |
| 1613 | #[test] |
| 1614 | fn compaction_threshold_scales_with_context_window() { |
| 1615 | assert_eq!( |
| 1616 | compaction_threshold_for_model_at_percent("deepseek-v3.2-128k", 80.0), |
| 1617 | 102_400 |
| 1618 | ); |
| 1619 | // v0.8.11 (#664): unknown-model fallback also resolves to 80% of |
| 1620 | // `LEGACY_DEEPSEEK_CONTEXT_WINDOW_TOKENS` (128K legacy DeepSeek |
| 1621 | // fallback) — same late-trigger discipline as the V4 path. Was |
| 1622 | // `50_000` pre-v0.8.11; that hardcoded value compacted at ~5% of a |
| 1623 | // 1M window when model detection silently fell through, which is |
| 1624 | // exactly the prefix-cache-burning behaviour we're getting away from. |
| 1625 | assert_eq!( |
| 1626 | compaction_threshold_for_model_at_percent("unknown-model", 80.0), |
| 1627 | 102_400 |
| 1628 | ); |
| 1629 | } |
| 1630 | |
| 1631 | #[test] |
| 1632 | fn compaction_scales_for_deepseek_v4_1m_context() { |
| 1633 | assert_eq!( |
| 1634 | compaction_threshold_for_model_at_percent("deepseek-v4-pro", 80.0), |
| 1635 | 800_000 |
| 1636 | ); |
| 1637 | } |
| 1638 | |
| 1639 | #[test] |
| 1640 | fn compaction_threshold_honors_configured_percent() { |
| 1641 | assert_eq!( |
| 1642 | compaction_threshold_for_model_at_percent("deepseek-v4-pro", 75.0), |
| 1643 | 750_000 |
| 1644 | ); |
| 1645 | assert_eq!( |
| 1646 | compaction_threshold_for_model_at_percent("trinity-large-thinking", 80.0), |
| 1647 | 209_715 |
| 1648 | ); |
| 1649 | } |
| 1650 | |
| 1651 | #[test] |
| 1652 | fn auto_compaction_defaults_on_for_known_supported_model_windows() { |
| 1653 | assert!(auto_compact_default_for_model("trinity-large-thinking")); |
| 1654 | assert!(auto_compact_default_for_model("deepseek-v3.2-128k")); |
| 1655 | assert!(auto_compact_default_for_model("deepseek-v4-pro")); |
| 1656 | assert!(auto_compact_default_for_model("mimo-v2.5-pro")); |
| 1657 | assert!(!auto_compact_default_for_model("unknown-model")); |
| 1658 | } |
| 1659 | |
| 1660 | #[test] |
| 1661 | fn deepseek_chatbot_models_usage_and_refusal_helpers() { |
| 1662 | assert!(is_refusal_stop_reason(Some("refusal"))); |
| 1663 | assert!(is_refusal_stop_reason(Some("content_filter"))); |
| 1664 | assert!(!is_refusal_stop_reason(Some("end_turn"))); |
| 1665 | assert!(is_incomplete_stop_reason(Some("refusal"))); |
| 1666 | |
| 1667 | let usage: Usage = serde_json::from_value(serde_json::json!({ |
| 1668 | "input_tokens": 120, |
| 1669 | "output_tokens": 45, |
| 1670 | "safety_tokens": 12, |
| 1671 | "server_tool_use": { |
| 1672 | "web_search_requests": 2, |
| 1673 | "web_fetch_requests": 1, |
| 1674 | "tool_search": 2, |
| 1675 | "tool_fetch": 1, |
| 1676 | "tool_image_search": 3 |
| 1677 | } |
| 1678 | })) |
| 1679 | .expect("usage deserializes"); |
| 1680 | assert_eq!(usage.safety_tokens, Some(12)); |
| 1681 | let server_tool_use = usage.server_tool_use.expect("server_tool_use present"); |
| 1682 | assert_eq!(server_tool_use.web_search_requests, Some(2)); |
| 1683 | assert_eq!(server_tool_use.web_fetch_requests, Some(1)); |
| 1684 | assert_eq!(server_tool_use.tool_search, Some(2)); |
| 1685 | assert_eq!(server_tool_use.tool_fetch, Some(1)); |
| 1686 | assert_eq!(server_tool_use.tool_image_search, Some(3)); |
| 1687 | |
| 1688 | let delta: MessageDelta = serde_json::from_value(serde_json::json!({ |
| 1689 | "stop_reason": "refusal", |
| 1690 | "title": "Rust 2024 Summary", |
| 1691 | "refusal": "Policy blocked output", |
| 1692 | "stop_details": {"reason": "safety"} |
| 1693 | })) |
| 1694 | .expect("delta deserializes"); |
| 1695 | assert_eq!(delta.title.as_deref(), Some("Rust 2024 Summary")); |
| 1696 | assert_eq!(delta.refusal.as_deref(), Some("Policy blocked output")); |
| 1697 | assert!(delta.stop_details.is_some()); |
| 1698 | } |
| 1699 | |
| 1700 | #[test] |
| 1701 | fn offline_seed_models_resolve_limits_and_reasoning() { |
| 1702 | for (model, context, output) in [ |
| 1703 | ("gemini-4-neon", 1_048_576, 65_536), |
| 1704 | ("gpt-6.2-astra", 1_050_000, 128_000), |
| 1705 | ("gpt-6.2-sol", 1_050_000, 128_000), |
| 1706 | ("muse-ember-1.0", 1_048_576, 524_288), |
| 1707 | ] { |
| 1708 | assert_eq!(context_window_for_model(model), Some(context), "{model}"); |
| 1709 | assert_eq!(max_output_tokens_for_model(model), Some(output), "{model}"); |
| 1710 | assert!(model_supports_reasoning(model), "{model}"); |
| 1711 | } |
| 1712 | assert!(!model_can_disable_thinking("gemini-4-neon")); |
| 1713 | } |
| 1714 | } |
| 1715 |