Skip to main content

codewhale_models/
lib.rs

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