meerkat-contracts 0.4.2

Wire format contracts and capability registry for Meerkat
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
//! Composable request fragments.
//!
//! Protocol crates inline the fields they support and provide accessor
//! methods returning the fragment type. No `#[serde(flatten)]` —
//! explicit delegation to avoid known serde/schemars issues.

use serde::{Deserialize, Serialize};

use meerkat_core::{
    HookRunOverrides, OutputSchema, PeerMeta, Provider,
    skills::{SkillId, SkillKey, SkillRef, SourceIdentityRegistry},
};

/// Core session creation parameters.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CoreCreateParams {
    pub prompt: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provider: Option<Provider>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system_prompt: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub labels: Option<std::collections::BTreeMap<String, String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub additional_instructions: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub app_context: Option<serde_json::Value>,
}

/// Structured output parameters.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StructuredOutputParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_schema: Option<OutputSchema>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub structured_output_retries: Option<u32>,
}

/// Comms parameters.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CommsParams {
    #[serde(default)]
    pub host_mode: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub comms_name: Option<String>,
    /// Friendly metadata for peer discovery.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub peer_meta: Option<PeerMeta>,
}

/// Hook parameters.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct HookParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hooks_override: Option<HookRunOverrides>,
}

/// Skills parameters for session/turn requests.
///
/// `preload_skills`: Pre-load these skills at session creation.
/// `None` or empty = inventory-only mode (no pre-loading).
/// `Some([])` is normalized to `None` to prevent silent misconfiguration.
///
/// `skill_references`: Skill IDs to resolve and inject for this turn.
/// `None` or empty = no per-turn skill injection.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SkillsParams {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preload_skills: Option<Vec<String>>,
    /// Structured refs for Skills V2.1. Supports legacy strings via `SkillRef::Legacy`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub skill_refs: Option<Vec<SkillRef>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub skill_references: Option<Vec<String>>,
}

impl SkillsParams {
    /// Normalize: `Some([])` → `None` for both fields.
    pub fn normalize(&mut self) {
        if let Some(ref v) = self.preload_skills
            && v.is_empty()
        {
            self.preload_skills = None;
        }
        if let Some(ref v) = self.skill_refs
            && v.is_empty()
        {
            self.skill_refs = None;
        }
        if let Some(ref v) = self.skill_references
            && v.is_empty()
        {
            self.skill_references = None;
        }
    }

    /// Canonicalize boundary refs by merging structured `skill_refs` and
    /// compatibility `skill_references`.
    pub fn canonical_skill_refs(&self) -> Option<Vec<SkillRef>> {
        let mut refs = Vec::new();

        if let Some(structured) = &self.skill_refs {
            refs.extend(structured.iter().cloned());
        }
        if let Some(legacy) = &self.skill_references {
            refs.extend(legacy.iter().cloned().map(SkillRef::Legacy));
        }

        if refs.is_empty() { None } else { Some(refs) }
    }

    /// Canonicalize to typed `SkillId`s.
    pub fn canonical_skill_ids(&self) -> Option<Vec<SkillId>> {
        self.canonical_skill_refs().map(|refs| {
            refs.into_iter()
                .map(|r| match r {
                    SkillRef::Legacy(id) => SkillId(id),
                    SkillRef::Structured(key) => SourceIdentityRegistry::canonical_skill_id(&key),
                })
                .collect()
        })
    }

    /// Canonicalize through the source-identity resolver boundary, producing
    /// typed canonical `SkillKey` values.
    pub fn canonical_skill_keys_with_registry(
        &self,
        registry: &SourceIdentityRegistry,
    ) -> Result<Option<Vec<SkillKey>>, meerkat_core::skills::SkillError> {
        let Some(refs) = self.canonical_skill_refs() else {
            return Ok(None);
        };

        let mut keys = Vec::with_capacity(refs.len());
        for reference in refs {
            keys.push(registry.resolve_skill_ref(&reference)?);
        }

        Ok(Some(keys))
    }

    /// Canonicalize through the source-identity resolver boundary and down-convert
    /// to canonical `SkillId` strings for legacy callers.
    pub fn canonical_skill_ids_with_registry(
        &self,
        registry: &SourceIdentityRegistry,
    ) -> Result<Option<Vec<SkillId>>, meerkat_core::skills::SkillError> {
        Ok(self
            .canonical_skill_keys_with_registry(registry)?
            .map(|keys| {
                keys.into_iter()
                    .map(|key| SourceIdentityRegistry::canonical_skill_id(&key))
                    .collect()
            }))
    }
}

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

    #[test]
    fn test_skills_params_none_serde() -> Result<(), serde_json::Error> {
        let params = SkillsParams {
            preload_skills: None,
            skill_refs: None,
            skill_references: None,
        };
        let json = serde_json::to_string(&params)?;
        assert_eq!(json, "{}");

        let parsed: SkillsParams = serde_json::from_str("{}")?;
        assert!(parsed.preload_skills.is_none());
        assert!(parsed.skill_refs.is_none());
        assert!(parsed.skill_references.is_none());
        Ok(())
    }

    #[test]
    fn test_skills_params_empty_normalizes() {
        let mut params = SkillsParams {
            preload_skills: Some(vec![]),
            skill_refs: Some(vec![]),
            skill_references: Some(vec![]),
        };
        params.normalize();
        assert!(params.preload_skills.is_none());
        assert!(params.skill_refs.is_none());
        assert!(params.skill_references.is_none());
    }

    #[test]
    fn test_skills_params_with_ids() -> Result<(), serde_json::Error> {
        let params = SkillsParams {
            preload_skills: Some(vec!["a/b".into()]),
            skill_refs: Some(vec![SkillRef::Legacy("a/b".to_string())]),
            skill_references: Some(vec!["c/d".into()]),
        };
        let json = serde_json::to_string(&params)?;
        let parsed: SkillsParams = serde_json::from_str(&json)?;
        assert_eq!(parsed.preload_skills, Some(vec!["a/b".to_string()]));
        assert_eq!(
            parsed.skill_refs,
            Some(vec![SkillRef::Legacy("a/b".to_string())])
        );
        assert_eq!(parsed.skill_references, Some(vec!["c/d".to_string()]));
        Ok(())
    }

    #[test]
    fn test_skill_refs_structured_and_legacy_equivalence() -> Result<(), serde_json::Error> {
        let structured_json = r#"{
            "skill_refs":[{"source_uuid":"dc256086-0d2f-4f61-a307-320d4148107f","skill_name":"email-extractor"}]
        }"#;
        let legacy_json =
            r#"{"skill_references":["dc256086-0d2f-4f61-a307-320d4148107f/email-extractor"]}"#;

        let structured: SkillsParams = serde_json::from_str(structured_json)?;
        let legacy: SkillsParams = serde_json::from_str(legacy_json)?;

        assert_eq!(
            structured.canonical_skill_ids(),
            Some(vec![SkillId(
                "dc256086-0d2f-4f61-a307-320d4148107f/email-extractor".to_string()
            )])
        );
        assert_eq!(
            structured.canonical_skill_ids(),
            legacy.canonical_skill_ids()
        );
        Ok(())
    }

    #[test]
    fn test_skill_refs_canonical_mixed_order_is_deterministic() -> Result<(), serde_json::Error> {
        let mixed_json = r#"{
            "skill_refs":[{"source_uuid":"dc256086-0d2f-4f61-a307-320d4148107f","skill_name":"email-extractor"}],
            "skill_references":["legacy/skill"]
        }"#;
        let parsed: SkillsParams = serde_json::from_str(mixed_json)?;
        let canonical = parsed.canonical_skill_refs().expect("canonical refs");

        assert_eq!(canonical.len(), 2);
        assert!(matches!(canonical[0], SkillRef::Structured(_)));
        assert_eq!(canonical[1], SkillRef::Legacy("legacy/skill".to_string()));
        Ok(())
    }

    #[test]
    fn test_skill_refs_canonicalized_via_registry_remap() {
        use meerkat_core::skills::{
            SkillAlias, SkillKey, SkillKeyRemap, SkillName, SourceIdentityLineage,
            SourceIdentityLineageEvent, SourceIdentityRecord, SourceIdentityStatus,
            SourceTransportKind, SourceUuid,
        };

        let source_old = SourceUuid::parse("dc256086-0d2f-4f61-a307-320d4148107f").expect("uuid");
        let source_new = SourceUuid::parse("a93d587d-8f44-438f-8189-6e8cf549f6e7").expect("uuid");
        let old_name = SkillName::parse("email-extractor").expect("slug");
        let new_name = SkillName::parse("mail-extractor").expect("slug");

        let registry = SourceIdentityRegistry::build(
            vec![
                SourceIdentityRecord {
                    source_uuid: source_old.clone(),
                    display_name: "old".to_string(),
                    transport_kind: SourceTransportKind::Filesystem,
                    fingerprint: "fp-a".to_string(),
                    status: SourceIdentityStatus::Active,
                },
                SourceIdentityRecord {
                    source_uuid: source_new.clone(),
                    display_name: "new".to_string(),
                    transport_kind: SourceTransportKind::Filesystem,
                    fingerprint: "fp-a".to_string(),
                    status: SourceIdentityStatus::Active,
                },
            ],
            vec![SourceIdentityLineage {
                event_id: "rotate-1".to_string(),
                recorded_at_unix_secs: 1,
                required_from_skills: vec![old_name.clone()],
                event: SourceIdentityLineageEvent::Rotate {
                    from: source_old.clone(),
                    to: source_new.clone(),
                },
            }],
            vec![SkillKeyRemap {
                from: SkillKey {
                    source_uuid: source_old.clone(),
                    skill_name: old_name.clone(),
                },
                to: SkillKey {
                    source_uuid: source_new.clone(),
                    skill_name: new_name.clone(),
                },
                reason: None,
            }],
            vec![SkillAlias {
                alias: "legacy/email".to_string(),
                to: SkillKey {
                    source_uuid: source_old.clone(),
                    skill_name: old_name,
                },
            }],
        )
        .expect("registry");

        let params = SkillsParams {
            preload_skills: None,
            skill_refs: Some(vec![SkillRef::Structured(SkillKey {
                source_uuid: source_old,
                skill_name: SkillName::parse("email-extractor").expect("slug"),
            })]),
            skill_references: Some(vec!["legacy/email".to_string()]),
        };

        let canonical = params
            .canonical_skill_ids_with_registry(&registry)
            .expect("canonicalization should succeed")
            .expect("ids");
        assert_eq!(
            canonical,
            vec![
                SkillId("a93d587d-8f44-438f-8189-6e8cf549f6e7/mail-extractor".to_string()),
                SkillId("a93d587d-8f44-438f-8189-6e8cf549f6e7/mail-extractor".to_string())
            ]
        );
    }

    #[test]
    fn test_core_create_params_all_fields_roundtrip() -> Result<(), serde_json::Error> {
        let mut labels = std::collections::BTreeMap::new();
        labels.insert("env".to_string(), "prod".to_string());
        labels.insert("team".to_string(), "infra".to_string());

        let params = CoreCreateParams {
            prompt: "hello".to_string(),
            model: Some("claude-opus-4-6".to_string()),
            provider: Some(Provider::Anthropic),
            max_tokens: Some(1024),
            system_prompt: Some("You are helpful.".to_string()),
            labels: Some(labels.clone()),
            additional_instructions: Some(vec![
                "Be concise.".to_string(),
                "Use JSON output.".to_string(),
            ]),
            app_context: Some(serde_json::json!({"org_id": "acme", "tier": "premium"})),
        };
        let json = serde_json::to_string(&params)?;
        let parsed: CoreCreateParams = serde_json::from_str(&json)?;
        assert_eq!(parsed.prompt, "hello");
        assert_eq!(parsed.labels, Some(labels));
        assert_eq!(
            parsed.additional_instructions,
            Some(vec![
                "Be concise.".to_string(),
                "Use JSON output.".to_string()
            ])
        );
        assert!(parsed.app_context.is_some());
        Ok(())
    }

    #[test]
    fn test_core_create_params_defaults_backward_compat() -> Result<(), serde_json::Error> {
        let json = r#"{"prompt": "hello"}"#;
        let parsed: CoreCreateParams = serde_json::from_str(json)?;
        assert_eq!(parsed.prompt, "hello");
        assert!(parsed.model.is_none());
        assert!(parsed.labels.is_none());
        assert!(parsed.additional_instructions.is_none());
        assert!(parsed.app_context.is_none());
        Ok(())
    }

    #[test]
    fn test_core_create_params_none_fields_omitted() -> Result<(), serde_json::Error> {
        let params = CoreCreateParams {
            prompt: "hello".to_string(),
            model: None,
            provider: None,
            max_tokens: None,
            system_prompt: None,
            labels: None,
            additional_instructions: None,
            app_context: None,
        };
        let json = serde_json::to_string(&params)?;
        assert!(!json.contains("\"labels\""));
        assert!(!json.contains("\"additional_instructions\""));
        assert!(!json.contains("\"app_context\""));
        Ok(())
    }
}