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