1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! Model profile — projects a [`crate::capabilities::ModelCapabilities`] row
//! into the narrower [`ModelProfile`] surface consumed by the rest of the
//! platform.
//!
//! Before the per-model capability refactor, this module owned the full
//! capability definitions via hand-written struct-per-bucket types. That
//! lived in `anthropic.rs`, `openai.rs`, `gemini.rs` — each providing a
//! `profile(model)` function, a fixed set of JSON Schema buckets, and
//! heuristic helpers (`supports_adaptive_thinking`, `is_gpt5_family`, …).
//!
//! After the refactor, capability data lives in
//! [`crate::capabilities`] as a per-model table, and the JSON Schema is
//! derived from it by [`schema_builder::build_params_schema`]. The
//! per-provider modules now hold only request-shaping helpers that read the
//! same catalog. Uncatalogued model IDs do not receive synthesized semantic
//! capabilities.

pub mod anthropic;
pub mod capabilities;
pub mod catalog;
pub mod gemini;
pub mod openai;
pub mod schema_builder;

use crate::Provider;
use crate::model_profile::capabilities::{
    BetaHeader, ModelCapabilities, ThinkingSupport, capabilities_for,
};
use serde::{Deserialize, Serialize};

/// Runtime profile for a model, describing its capabilities and operational defaults.
///
/// This is a **capability-plus-operational-defaults catalog**: it owns both model
/// capability flags (vision, thinking, temperature) and authoritative model-specific
/// operational defaults (call timeout) that the factory composes into effective
/// runtime policy. This ownership expansion is deliberate — see dogma rule §11.
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
pub struct ModelProfile {
    /// Provider that serves this model.
    pub provider: Provider,
    /// Model family identifier (e.g., `"claude-opus-4"`, `"gpt-5"`, `"gemini-3"`).
    pub model_family: String,
    /// Whether the model accepts a `temperature` parameter.
    pub supports_temperature: bool,
    /// Whether the model supports extended thinking / reasoning budgets.
    pub supports_thinking: bool,
    /// Whether the model supports explicit reasoning effort control.
    pub supports_reasoning: bool,
    /// Whether the model accepts inline video content in user messages.
    pub inline_video: bool,
    /// Whether the model accepts image content in user messages.
    pub vision: bool,
    /// Whether user messages may include image input blocks.
    pub image_input: bool,
    /// Whether the model can process image blocks in tool results.
    /// When false, `view_image` is hidden from the tool list.
    pub image_tool_results: bool,
    /// Whether the model supports a realtime bidirectional streaming transport
    /// (e.g. OpenAI `*-realtime*` endpoints, Gemini `*-live*` endpoints). Drives
    /// capability-based realtime transport attach/detach in the runtime.
    pub realtime: bool,
    /// Whether the model supports provider-native web search tools.
    pub supports_web_search: bool,
    /// Whether the provider/model can use Meerkat image generation.
    pub image_generation: bool,
    /// JSON Schema describing accepted provider-specific parameters.
    pub params_schema: serde_json::Value,
    /// Beta headers authorized by the model capability catalog.
    #[serde(default)]
    pub beta_headers: Vec<ModelBetaHeader>,
    /// Authoritative default call timeout in seconds for this model family.
    ///
    /// `None` means the model family has no profiled default timeout.
    /// This is the canonical source for model-specific call timeout defaults,
    /// consumed by the factory/agent-loop resolver trait at call time.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub call_timeout_secs: Option<u64>,
}

/// Catalog-owned beta header metadata for a model.
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
pub struct ModelBetaHeader {
    pub feature: String,
    pub header_name: String,
    pub header_value: String,
}

impl From<&BetaHeader> for ModelBetaHeader {
    fn from(value: &BetaHeader) -> Self {
        Self {
            // Wire/display projection of the typed `BetaFeature` owner.
            feature: value.feature.as_wire_str().to_string(),
            header_name: value.header_name.to_string(),
            header_value: value.header_value.to_string(),
        }
    }
}

/// Look up the profile for a model by typed provider and model ID.
///
/// Catalog models project directly from their capability row. Uncatalogued
/// model IDs return `None`; semantic capability facts must come from the
/// capability catalog, not model-name prefixes.
///
/// Returns `None` if the provider/model pair has no catalog capability row.
pub fn profile_for(provider: Provider, model: &str) -> Option<ModelProfile> {
    capabilities_for(provider, model).map(project_to_profile)
}

/// Look up whether a model accepts inline video by typed provider and model ID.
///
/// Returns `None` when the provider/model pair has no capability row.
pub fn inline_video_support_for(provider: Provider, model: &str) -> Option<bool> {
    capabilities_for(provider, model).map(|caps| caps.inline_video)
}

/// Project a capability record into the [`ModelProfile`] surface.
pub(crate) fn project_to_profile(caps: &ModelCapabilities) -> ModelProfile {
    ModelProfile {
        provider: caps.provider,
        model_family: caps.model_family.to_string(),
        supports_temperature: caps.supports_temperature,
        supports_thinking: caps.thinking != ThinkingSupport::None,
        supports_reasoning: caps.supports_reasoning,
        supports_web_search: caps.supports_web_search,
        inline_video: caps.inline_video,
        vision: caps.vision,
        image_input: caps.vision,
        image_tool_results: caps.image_tool_results,
        realtime: caps.realtime,
        image_generation: caps.image_generation,
        params_schema: schema_builder::build_params_schema(caps),
        beta_headers: caps
            .beta_headers
            .iter()
            .map(ModelBetaHeader::from)
            .collect(),
        call_timeout_secs: caps.call_timeout_secs,
    }
}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)]
mod tests {
    use super::*;

    fn provider_from_catalog(provider: &str) -> Provider {
        Provider::parse_strict(provider)
            .unwrap_or_else(|| panic!("catalog provider '{provider}' must parse"))
    }

    /// Fields that `ModelProfile` must expose, mirrored by `WireModelProfile`
    /// in `meerkat-contracts::wire::models`. Adding a field here is a
    /// wire-contract change that needs parallel updates in `meerkat-contracts`
    /// and a schema regeneration. (Moved from the deleted `meerkat-models`
    /// shim crate's guard tests.)
    const EXPECTED_MODEL_PROFILE_FIELDS: &[&str] = &[
        "provider",
        "model_family",
        "supports_temperature",
        "supports_thinking",
        "supports_reasoning",
        "supports_web_search",
        "inline_video",
        "vision",
        "image_input",
        "image_tool_results",
        "realtime",
        "image_generation",
        "params_schema",
        "call_timeout_secs",
        "beta_headers",
    ];

    #[test]
    fn model_profile_wire_field_parity() {
        let schema = schemars::schema_for!(ModelProfile);
        let value = serde_json::to_value(&schema).expect("schema serializes to JSON");
        let props = value
            .get("properties")
            .and_then(|p| p.as_object())
            .expect("ModelProfile schema has a properties map")
            .keys()
            .cloned()
            .collect::<std::collections::BTreeSet<_>>();
        let expected: std::collections::BTreeSet<String> = EXPECTED_MODEL_PROFILE_FIELDS
            .iter()
            .map(|s| (*s).to_string())
            .collect();
        assert_eq!(
            props, expected,
            "ModelProfile field set drift — update meerkat-contracts::WireModelProfile \
             in lockstep, regenerate artifact schemas (make regen-schemas), and update \
             EXPECTED_MODEL_PROFILE_FIELDS if this change is intentional."
        );
    }

    #[test]
    fn profile_for_all_catalog_models() {
        for entry in crate::model_profile::catalog::catalog() {
            let profile = profile_for(provider_from_catalog(entry.provider), entry.id);
            assert!(
                profile.is_some(),
                "catalog model '{}' (provider '{}') must have a profile",
                entry.id,
                entry.provider
            );
        }
    }

    #[test]
    fn unknown_provider_returns_none() {
        assert!(profile_for(Provider::Other, "some-model").is_none());
    }

    #[test]
    fn uncatalogued_model_returns_none_for_known_provider() {
        assert!(profile_for(Provider::OpenAI, "gpt-5.9-future").is_none());
        assert!(profile_for(Provider::Anthropic, "claude-opus-4-8-20260501-preview").is_none());
        assert!(profile_for(Provider::Gemini, "gemini-4-future").is_none());
    }

    #[test]
    fn wrong_typed_provider_for_known_model_returns_none() {
        assert!(profile_for(Provider::Anthropic, "gpt-5.4").is_none());
        assert!(profile_for(Provider::OpenAI, "gemini-3.5-flash").is_none());
    }

    #[test]
    fn unknown_provider_model_pairs_fail_closed_without_defaults() {
        assert!(profile_for(Provider::Other, "gpt-5.4").is_none());
        assert!(profile_for(Provider::Other, "uncatalogued-gpt-compatible").is_none());
        assert!(inline_video_support_for(Provider::Other, "gemini-3.5-flash").is_none());
    }

    #[test]
    fn display_provider_strings_cannot_select_capability_without_typed_provider() {
        let display_provider = Provider::parse_strict("Gemini").unwrap_or(Provider::Other);
        assert_eq!(display_provider, Provider::Other);
        assert_eq!(
            inline_video_support_for(display_provider, "gemini-3.5-flash"),
            None
        );
    }

    #[test]
    fn claude_profile_vision_and_image_tool_results_true() {
        let profile = profile_for(Provider::Anthropic, "claude-opus-4-8")
            .expect("claude-opus-4-8 must have a profile");
        assert!(profile.vision, "Anthropic models must support vision");
        assert!(
            profile.image_tool_results,
            "Anthropic models must support image tool results"
        );
        assert!(
            !profile.inline_video,
            "Anthropic models must NOT support inline video"
        );

        let profile = profile_for(Provider::Anthropic, "claude-sonnet-4-5")
            .expect("claude-sonnet-4-5 must have a profile");
        assert!(profile.vision);
        assert!(profile.image_tool_results);
    }

    #[test]
    fn gpt_profile_vision_true_image_tool_results_false() {
        let profile =
            profile_for(Provider::OpenAI, "gpt-5.4").expect("gpt-5.4 must have a profile");
        assert!(profile.vision, "OpenAI models must support vision");
        assert!(
            !profile.image_tool_results,
            "OpenAI models must NOT support image tool results"
        );
        assert!(
            !profile.inline_video,
            "OpenAI models must NOT support inline video"
        );
    }

    #[test]
    fn gemini_profile_vision_and_image_tool_results_true() {
        let profile = profile_for(Provider::Gemini, "gemini-3.5-flash")
            .expect("gemini-3.5-flash must have a profile");
        assert!(profile.vision, "Gemini models must support vision");
        assert!(
            profile.image_tool_results,
            "Gemini models must support image tool results"
        );
        assert!(
            profile.inline_video,
            "Gemini models must support inline video"
        );
    }

    #[test]
    fn all_gemini_profiles_preserve_inline_video_support() {
        for entry in catalog::catalog()
            .iter()
            .filter(|entry| entry.provider == "gemini")
        {
            assert!(
                profile_for(provider_from_catalog(entry.provider), entry.id)
                    .as_ref()
                    .is_some_and(|profile| profile.inline_video),
                "Gemini model '{}' must support inline video",
                entry.id
            );
        }
    }

    #[test]
    fn inline_video_support_for_reads_capability_truth() {
        assert_eq!(
            inline_video_support_for(Provider::Gemini, "gemini-3.5-flash"),
            Some(true)
        );
        assert_eq!(
            inline_video_support_for(Provider::OpenAI, "gpt-5.4"),
            Some(false)
        );
        assert_eq!(
            inline_video_support_for(Provider::Gemini, "gemini-4-future"),
            None
        );
    }

    #[test]
    fn params_schema_non_empty_for_all_profiles() {
        for entry in crate::model_profile::catalog::catalog() {
            let profile = profile_for(provider_from_catalog(entry.provider), entry.id);
            if let Some(p) = profile {
                assert!(
                    p.params_schema.is_object(),
                    "params_schema for '{}' must be a JSON object, got {:?}",
                    entry.id,
                    p.params_schema
                );
            }
        }
    }

    #[test]
    fn call_timeout_secs_populated_for_known_models() {
        for entry in crate::model_profile::catalog::catalog() {
            let profile = profile_for(provider_from_catalog(entry.provider), entry.id);
            if let Some(p) = profile {
                assert!(
                    p.call_timeout_secs.is_some(),
                    "catalog model '{}' (provider '{}', family '{}') must have call_timeout_secs",
                    entry.id,
                    entry.provider,
                    p.model_family
                );
            }
        }
    }

    #[test]
    fn anthropic_opus_has_longer_timeout_than_haiku() {
        let opus = profile_for(Provider::Anthropic, "claude-opus-4-8").unwrap();
        let haiku = profile_for(Provider::Anthropic, "claude-haiku-4-5-20251001").unwrap();
        assert!(
            opus.call_timeout_secs.unwrap() > haiku.call_timeout_secs.unwrap(),
            "Opus should have a longer default timeout than Haiku"
        );
    }

    #[test]
    fn openai_pro_has_longer_timeout_than_standard_gpt5() {
        let pro = profile_for(Provider::OpenAI, "gpt-5.5-pro").unwrap();
        let standard = profile_for(Provider::OpenAI, "gpt-5.5").unwrap();
        assert!(
            pro.call_timeout_secs.unwrap() > standard.call_timeout_secs.unwrap(),
            "gpt-5.5-pro ({}) should have a much longer timeout than gpt-5.5 ({})",
            pro.call_timeout_secs.unwrap(),
            standard.call_timeout_secs.unwrap(),
        );
    }

    #[test]
    fn gemini_flash_has_shorter_timeout_than_pro() {
        let flash = profile_for(Provider::Gemini, "gemini-3.1-flash-lite-preview").unwrap();
        let pro = profile_for(Provider::Gemini, "gemini-3.1-pro-preview").unwrap();
        assert!(
            flash.call_timeout_secs.unwrap() < pro.call_timeout_secs.unwrap(),
            "gemini flash ({}) should have shorter timeout than gemini pro ({})",
            flash.call_timeout_secs.unwrap(),
            pro.call_timeout_secs.unwrap(),
        );
    }

    #[test]
    fn unknown_provider_call_timeout_is_none() {
        assert!(profile_for(Provider::Other, "model").is_none());
    }

    #[test]
    fn web_search_flag_populated_for_all_catalog_models() {
        for entry in crate::model_profile::catalog::catalog() {
            let profile = profile_for(provider_from_catalog(entry.provider), entry.id);
            assert!(
                profile.is_some(),
                "catalog model '{}' (provider '{}') must have a profile",
                entry.id,
                entry.provider
            );
        }
    }

    /// Gate (row #92): `image_generation` is a model-owned catalog fact, not a
    /// per-provider derivation. A Gemini text model's provider (Gemini) HAS an
    /// image-generation default model, yet the text row itself declares
    /// `image_generation = false` and the projected profile must report false —
    /// proving the fact comes from the model row, not a provider lookup.
    #[test]
    fn image_generation_is_model_owned_not_provider_derived() {
        // Gemini provider has an image-gen default, but the text model row does
        // not itself generate images.
        assert!(
            catalog::default_image_generation_model(Provider::Gemini).is_some(),
            "Gemini provider must have an image-generation default model"
        );
        let gemini_text = profile_for(Provider::Gemini, "gemini-3.5-flash")
            .expect("gemini-3.5-flash must have a profile");
        assert!(
            !gemini_text.image_generation,
            "Gemini text model must report image_generation=false despite the \
             provider having an image-gen default"
        );

        // OpenAI text rows route through the hosted image tool: model-owned true.
        let gpt = profile_for(Provider::OpenAI, "gpt-5.4").expect("gpt-5.4 must have a profile");
        assert!(gpt.image_generation);

        // Anthropic has no image-gen route: model-owned false.
        let claude = profile_for(Provider::Anthropic, "claude-opus-4-8")
            .expect("claude-opus-4-8 must have a profile");
        assert!(!claude.image_generation);
    }

    #[test]
    fn anthropic_supports_web_search() {
        let profile = profile_for(Provider::Anthropic, "claude-opus-4-8").unwrap();
        assert!(profile.supports_web_search);
    }

    #[test]
    fn openai_supports_web_search() {
        let profile = profile_for(Provider::OpenAI, "gpt-5.4").unwrap();
        assert!(profile.supports_web_search);
    }

    #[test]
    fn gemini_supports_web_search() {
        let profile = profile_for(Provider::Gemini, "gemini-3.5-flash").unwrap();
        assert!(profile.supports_web_search);
    }
}