meerkat-core 0.8.1

Core agent logic for Meerkat (no I/O deps)
Documentation
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! Build the JSON Schema advertised for the provider-specific payload inside a
//! model's canonical `provider_params.provider_tag` from a [`ModelCapabilities`]
//! row. The outer `ProviderParamsOverride` envelope is owned by the public wire
//! contract; this builder describes only the selected provider variant's knobs.
//!
//! The schema here is the single source of truth for UI-facing param shapes.
//! It is pure mechanics over the capability vocabulary: the function maps a
//! capability row to a schema and consults no catalog data. The canonical
//! rows live in `meerkat-models`, whose tests pin the emitted schema for
//! every real model.

use crate::Provider;
use crate::model_profile::capabilities::{EffortLevel, ModelCapabilities, ThinkingSupport};
use serde_json::{Value, json};

/// Build the JSON Schema for a model's `provider_params`.
pub fn build_params_schema(caps: &ModelCapabilities) -> Value {
    match caps.provider {
        Provider::Anthropic => build_anthropic_schema(caps),
        Provider::OpenAI => build_openai_schema(caps),
        Provider::Gemini => build_gemini_schema(caps),
        _ => json!({
            "type": "object",
            "additionalProperties": false,
            "properties": {}
        }),
    }
}

// ---------------------------------------------------------------------------
// Anthropic
//
// Current hand-written shape (matched for parity):
// - thinking: oneOf
//     * { type: "adaptive" }                          (only when adaptive is supported)
//     * { type: "enabled", budget_tokens: integer }   (always supported where thinking != None)
// - thinking_budget: integer  (legacy flat alternative)
// - top_k: integer
// - effort: string enum       (only on models with effort_levels non-empty)
// - inference_geo: string     (only on models with supports_inference_geo)
// - compaction: object | "auto"  (only on models with supports_compaction)
// ---------------------------------------------------------------------------

fn build_anthropic_schema(caps: &ModelCapabilities) -> Value {
    let mut props = serde_json::Map::new();

    if let Some(thinking) = anthropic_thinking_schema(caps.thinking) {
        props.insert("thinking".into(), thinking);
    }
    if caps.supports_thinking_budget_legacy && caps.thinking != ThinkingSupport::None {
        props.insert("thinking_budget".into(), integer_nonneg_schema());
    }
    if caps.supports_top_k {
        props.insert("top_k".into(), integer_nonneg_schema());
    }
    if !caps.effort_levels.is_empty() {
        props.insert(
            "effort".into(),
            effort_enum_schema("Output effort level.", caps.effort_levels),
        );
    }
    if caps.supports_inference_geo {
        props.insert(
            "inference_geo".into(),
            json!({
                "description": "Data residency region (e.g., \"us\" or \"global\").",
                "type": "string"
            }),
        );
    }
    if caps.supports_compaction {
        props.insert(
            "compaction".into(),
            json!({
                "description": "Context compaction. \"auto\" or an object like {\"trigger\": 150000}.",
            }),
        );
    }

    object_schema(props)
}

fn anthropic_thinking_schema(mode: ThinkingSupport) -> Option<Value> {
    match mode {
        ThinkingSupport::None | ThinkingSupport::GeminiThinkingLevel => None,
        ThinkingSupport::AnthropicEnabledOnly => Some(json!({
            "description": "Extended thinking configuration. Format: {\"type\": \"enabled\", \"budget_tokens\": N}.",
            "type": "object",
            "required": ["type", "budget_tokens"],
            "properties": {
                "type": { "type": "string", "enum": ["enabled"] },
                "budget_tokens": { "type": "integer", "minimum": 0 }
            }
        })),
        ThinkingSupport::AnthropicAdaptiveOnly => Some(json!({
            "description": "Extended thinking configuration. Format: {\"type\": \"adaptive\"}.",
            "type": "object",
            "required": ["type"],
            "properties": {
                "type": { "type": "string", "enum": ["adaptive"] }
            }
        })),
        ThinkingSupport::AnthropicAdaptiveAndEnabled => Some(json!({
            "description": "Extended thinking configuration. Format: {\"type\": \"adaptive\"} or {\"type\": \"enabled\", \"budget_tokens\": N}.",
            "oneOf": [
                {
                    "type": "object",
                    "required": ["type"],
                    "properties": {
                        "type": { "type": "string", "enum": ["adaptive"] }
                    }
                },
                {
                    "type": "object",
                    "required": ["type", "budget_tokens"],
                    "properties": {
                        "type": { "type": "string", "enum": ["enabled"] },
                        "budget_tokens": { "type": "integer", "minimum": 0 }
                    }
                }
            ]
        })),
    }
}

// ---------------------------------------------------------------------------
// OpenAI
//
// Provider-tag payload shape:
// - reasoning_effort: string enum  (only on reasoning models)
// - reasoning_mode: string enum    (GPT-5.6 Responses)
// - reasoning_context: string enum (GPT-5.6 Responses)
// - text_verbosity: string enum    (GPT-5.6 Responses)
// - prompt_cache_options: object   (GPT-5.6 Responses)
// - seed: integer
// - frequency_penalty: number
// - presence_penalty: number
// ---------------------------------------------------------------------------

fn build_openai_schema(caps: &ModelCapabilities) -> Value {
    let mut props = serde_json::Map::new();

    if caps.supports_reasoning && !caps.effort_levels.is_empty() {
        props.insert(
            "reasoning_effort".into(),
            effort_enum_schema("Reasoning effort level.", caps.effort_levels),
        );
    }
    if let Some(advanced) = caps.openai_responses_params {
        if !advanced.reasoning_modes.is_empty() {
            props.insert(
                "reasoning_mode".into(),
                string_enum_schema(
                    "Responses reasoning execution mode.",
                    advanced
                        .reasoning_modes
                        .iter()
                        .map(|mode| mode.as_wire_str()),
                ),
            );
        }
        if !advanced.reasoning_contexts.is_empty() {
            props.insert(
                "reasoning_context".into(),
                string_enum_schema(
                    "Reasoning items made available to the next sample.",
                    advanced
                        .reasoning_contexts
                        .iter()
                        .map(|context| context.as_wire_str()),
                ),
            );
        }
        if !advanced.text_verbosity_levels.is_empty() {
            props.insert(
                "text_verbosity".into(),
                string_enum_schema(
                    "Default detail level for text output.",
                    advanced
                        .text_verbosity_levels
                        .iter()
                        .map(|level| level.as_wire_str()),
                ),
            );
        }

        let mut cache_props = serde_json::Map::new();
        if !advanced.prompt_cache_modes.is_empty() {
            cache_props.insert(
                "mode".into(),
                string_enum_schema(
                    "Request-wide prompt-cache breakpoint policy.",
                    advanced
                        .prompt_cache_modes
                        .iter()
                        .map(|mode| mode.as_wire_str()),
                ),
            );
        }
        if !advanced.prompt_cache_ttls.is_empty() {
            cache_props.insert(
                "ttl".into(),
                string_enum_schema(
                    "Minimum lifetime for prompt-cache entries.",
                    advanced
                        .prompt_cache_ttls
                        .iter()
                        .map(|ttl| ttl.as_wire_str()),
                ),
            );
        }
        if !cache_props.is_empty() {
            props.insert(
                "prompt_cache_options".into(),
                json!({
                    "description": "GPT-5.6 prompt-cache controls.",
                    "type": "object",
                    "additionalProperties": false,
                    "properties": Value::Object(cache_props)
                }),
            );
        }
    }
    if caps.supports_legacy_penalties {
        props.insert(
            "seed".into(),
            json!({
                "description": "Random seed for reproducibility.",
                "type": "integer"
            }),
        );
        props.insert(
            "frequency_penalty".into(),
            json!({
                "description": "Frequency penalty (-2.0 to 2.0).",
                "type": "number"
            }),
        );
        props.insert(
            "presence_penalty".into(),
            json!({
                "description": "Presence penalty (-2.0 to 2.0).",
                "type": "number"
            }),
        );
    }

    object_schema(props)
}

// ---------------------------------------------------------------------------
// Gemini
//
// Current hand-written shape:
// - thinking: object { thinking_level, thinking_budget }
// - thinking_level: string enum                       (Gemini 3 authoritative knob)
// - thinking_budget: integer                          (legacy flat alternative)
// - top_k: integer
// - top_p: number
// ---------------------------------------------------------------------------

fn build_gemini_schema(caps: &ModelCapabilities) -> Value {
    let mut props = serde_json::Map::new();

    if caps.thinking != ThinkingSupport::None {
        let thinking_props = match caps.thinking {
            ThinkingSupport::GeminiThinkingLevel => json!({
                "thinking_level": gemini_thinking_level_schema(),
                "thinking_budget": { "type": "integer", "minimum": 0 }
            }),
            _ => json!({
                "thinking_budget": { "type": "integer", "minimum": 0 }
            }),
        };
        props.insert(
            "thinking".into(),
            json!({
                "description": "Thinking configuration.",
                "type": "object",
                "additionalProperties": false,
                "properties": thinking_props
            }),
        );
        if caps.thinking == ThinkingSupport::GeminiThinkingLevel {
            props.insert("thinking_level".into(), gemini_thinking_level_schema());
        }
        if caps.supports_thinking_budget_legacy {
            props.insert(
                "thinking_budget".into(),
                json!({
                    "description": "Legacy flat thinking budget (alternative to thinking.thinking_budget).",
                    "type": "integer",
                    "minimum": 0
                }),
            );
        }
    }
    if caps.supports_top_k {
        props.insert("top_k".into(), integer_nonneg_schema());
    }
    if caps.supports_top_p {
        props.insert(
            "top_p".into(),
            json!({
                "type": "number",
                "minimum": 0.0,
                "maximum": 1.0
            }),
        );
    }

    object_schema(props)
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn object_schema(properties: serde_json::Map<String, Value>) -> Value {
    json!({
        "type": "object",
        "additionalProperties": false,
        "properties": Value::Object(properties)
    })
}

fn integer_nonneg_schema() -> Value {
    json!({ "type": "integer", "minimum": 0 })
}

fn gemini_thinking_level_schema() -> Value {
    json!({
        "description": "Gemini 3 reasoning level.",
        "type": "string",
        "enum": ["minimal", "low", "medium", "high"]
    })
}

/// Project a typed [`EffortLevel`] set into a JSON Schema string-enum.
///
/// The enum values derive from the typed vocabulary via
/// [`EffortLevel::as_wire_str`], not from inline string literals, so the
/// advertised schema cannot drift from the catalog's declared levels.
fn effort_enum_schema(description: &str, levels: &[EffortLevel]) -> Value {
    let vs: Vec<Value> = levels
        .iter()
        .map(|level| Value::String(level.as_wire_str().into()))
        .collect();
    json!({
        "description": description,
        "type": "string",
        "enum": vs
    })
}

fn string_enum_schema(description: &str, values: impl Iterator<Item = &'static str>) -> Value {
    let values: Vec<Value> = values.map(|value| Value::String(value.into())).collect();
    json!({
        "description": description,
        "type": "string",
        "enum": values
    })
}

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

    /// Extract the set of property names from a params schema.
    fn property_keys(schema: &Value) -> std::collections::BTreeSet<String> {
        schema
            .get("properties")
            .and_then(|p| p.as_object())
            .map(|m| m.keys().cloned().collect())
            .unwrap_or_default()
    }

    /// Extract the set of enum values for a top-level string-enum property.
    fn enum_values_for(schema: &Value, prop: &str) -> Option<std::collections::BTreeSet<String>> {
        let val = schema
            .get("properties")
            .and_then(|p| p.get(prop))
            .and_then(|v| v.get("enum"))
            .and_then(|e| e.as_array())?;
        Some(
            val.iter()
                .filter_map(|v| v.as_str().map(|s| s.to_string()))
                .collect(),
        )
    }

    #[test]
    fn builder_emits_object_schema_for_every_capability_row() {
        for caps in TEST_CATALOG.capabilities {
            let schema = build_params_schema(caps);
            assert_eq!(
                schema.get("type").and_then(|t| t.as_str()),
                Some("object"),
                "schema for {} must be type=object",
                caps.id
            );
            assert!(
                schema.get("properties").is_some(),
                "schema for {} must have a properties map",
                caps.id
            );
        }
    }

    #[test]
    fn effort_enum_values_derive_from_typed_effort_levels() {
        use crate::model_profile::capabilities::{EffortLevel, ModelCapabilities, ThinkingSupport};

        let base = TEST_CATALOG
            .capabilities_for(crate::Provider::Anthropic, "test-anthropic-default")
            .expect("test anthropic row");
        let caps = ModelCapabilities {
            thinking: ThinkingSupport::AnthropicAdaptiveAndEnabled,
            effort_levels: &[EffortLevel::Low, EffortLevel::High, EffortLevel::Max],
            ..*base
        };
        let schema = build_params_schema(&caps);
        let values = enum_values_for(&schema, "effort").expect("effort enum");
        let declared: std::collections::BTreeSet<String> = caps
            .effort_levels
            .iter()
            .map(|level| level.as_wire_str().to_string())
            .collect();
        assert_eq!(
            values, declared,
            "effort enum must equal the row's typed effort_levels"
        );
    }

    #[test]
    fn empty_effort_levels_emit_no_effort_property() {
        let caps = TEST_CATALOG
            .capabilities_for(crate::Provider::Anthropic, "test-anthropic-default")
            .expect("test anthropic row");
        assert!(caps.effort_levels.is_empty());
        let schema = build_params_schema(caps);
        assert!(!property_keys(&schema).contains("effort"));
    }

    #[test]
    fn gemini_thinking_level_rows_expose_thinking_level() {
        let caps = TEST_CATALOG
            .capabilities_for(crate::Provider::Gemini, "test-gemini-video")
            .expect("test gemini row");
        let schema = build_params_schema(caps);
        let keys = property_keys(&schema);
        assert!(
            keys.contains("thinking_level"),
            "GeminiThinkingLevel rows must advertise thinking_level"
        );
        let values = enum_values_for(&schema, "thinking_level").expect("thinking_level enum");
        let expected: std::collections::BTreeSet<String> = ["high", "low", "medium", "minimal"]
            .into_iter()
            .map(str::to_string)
            .collect();
        assert_eq!(values, expected);
    }

    #[test]
    fn gemini_rows_have_no_include_thoughts() {
        let caps = TEST_CATALOG
            .capabilities_for(crate::Provider::Gemini, "test-gemini-video")
            .expect("test gemini row");
        let schema = build_params_schema(caps);
        assert!(!property_keys(&schema).contains("include_thoughts"));
        let thinking = schema.get("properties").and_then(|p| p.get("thinking"));
        if let Some(inner_props) = thinking.and_then(|t| t.get("properties")) {
            let obj = inner_props.as_object().expect("inner properties");
            assert!(!obj.contains_key("include_thoughts"));
        }
    }
}