Skip to main content

codewhale_models/
schema_sanitize.rs

1//! Schema sanitizer for tool `input_schema` before sending to provider APIs.
2//!
3//! DeepSeek's `/beta/chat/completions` strict tool mode is harsh. MCP tool
4//! schemas frequently arrive with Pydantic-style `anyOf:[{type:"string"},
5//! {type:"null"}]` unions, bare `{type:"object"}` with no `properties`, or
6//! `required` entries that don't appear in `properties`. These dirty schemas
7//! cause silent 400s that users can't diagnose.
8//!
9//! The default sanitizer runs in-place on every schema returned by
10//! `ToolRegistry::tools_for_api()` before the registry hands them off.
11//! Provider-specific helpers below add stricter DeepSeek and OpenAI Responses
12//! compatibility passes where their request shapes need it.
13
14use std::collections::HashSet;
15
16use serde_json::{Map, Value};
17
18/// Sanitize a JSON Schema in-place for DeepSeek strict-tool compatibility.
19///
20/// Applies a sequence of normalisations chosen to be semantics-preserving:
21/// - Collapse `{"anyOf":[X, {"type":"null"}]}` → `X ∪ {"nullable": true}`
22/// - Inject `"properties": {}` on bare-object schemas
23/// - Prune dangling `required` entries
24/// - Collapse single-element `oneOf` / `allOf`
25/// - Walk recursively through all subschemas
26pub fn sanitize(schema: &mut Value) {
27    collapse_nullable_unions(schema);
28    inject_properties_on_bare_objects(schema);
29    prune_dangling_required(schema);
30    collapse_single_element_unions(schema);
31    // Recurse into all sub-schemas
32    if let Some(obj) = schema.as_object_mut() {
33        for (_, v) in obj.iter_mut() {
34            sanitize(v);
35        }
36    } else if let Some(arr) = schema.as_array_mut() {
37        for v in arr.iter_mut() {
38            sanitize(v);
39        }
40    }
41}
42
43/// Sanitize a schema for DeepSeek strict function-calling.
44///
45/// This extends the general sanitizer with the official strict-mode object
46/// rules: every object must set `additionalProperties: false`, and every
47/// property must be listed in `required`.
48pub fn sanitize_for_strict(schema: &mut Value) {
49    sanitize(schema);
50    enforce_strict_subset(schema);
51}
52
53/// Sanitize a tool `parameters` schema for xAI chat completions.
54///
55/// xAI validates that the parameters root is an object schema and rejects a
56/// root-level `anyOf`/`oneOf` union with any non-object branch
57/// ("tool parameter root must be an object type"). The built-in `apply_patch`
58/// schema's `oneOf: [{required:["patch"]}, {required:["changes"]}]` trips this
59/// with a 400 on the first tool-bearing request. The Responses-API pass
60/// performs exactly the required normalization — merge root composition
61/// properties, force `type: object`, drop root-only composition keywords —
62/// so reuse it and surface the dropped constraint as a description note.
63pub fn sanitize_for_xai_parameters(parameters: &mut Value) -> Option<String> {
64    sanitize_for_responses(parameters)
65}
66
67/// Sanitize a schema for OpenAI Responses function tools.
68///
69/// The Responses API requires the top-level `parameters` schema to be an object
70/// and rejects top-level `oneOf` / `anyOf` / `allOf` / `enum` / `not`. Keep the
71/// schema permissive rather than changing tool semantics: merge any root
72/// alternative properties we can see, then remove the root-only composition
73/// keywords while preserving nested schemas.
74///
75/// Returns a short description note when root composition constraints with
76/// meaningful `required` groups are dropped.
77pub fn sanitize_for_responses(schema: &mut Value) -> Option<String> {
78    let constraint_note = schema
79        .as_object()
80        .and_then(root_composition_constraint_note);
81    let dependent_note = drop_dependent_keywords(schema);
82
83    sanitize(schema);
84
85    if !schema.is_object() {
86        *schema = Value::Object(Map::new());
87    }
88
89    let Some(obj) = schema.as_object_mut() else {
90        return combine_constraint_notes(constraint_note, dependent_note);
91    };
92
93    merge_root_composition_properties(obj);
94    obj.insert("type".into(), Value::String("object".to_string()));
95    obj.remove("oneOf");
96    obj.remove("anyOf");
97    obj.remove("allOf");
98    obj.remove("enum");
99    obj.remove("not");
100    ensure_properties_object(obj);
101    prune_dangling_required(schema);
102    combine_constraint_notes(constraint_note, dependent_note)
103}
104
105pub fn strict_schema_supported(schema: &Value) -> bool {
106    let mut normalized = schema.clone();
107    sanitize(&mut normalized);
108    !has_strict_incompatible_composition(&normalized, true)
109}
110
111fn has_strict_incompatible_composition(schema: &Value, is_root: bool) -> bool {
112    if let Some(obj) = schema.as_object() {
113        if obj.contains_key("oneOf")
114            || obj.contains_key("allOf")
115            || obj.contains_key("dependentSchemas")
116        {
117            return true;
118        }
119        if is_root && obj.contains_key("anyOf") {
120            return true;
121        }
122        return obj
123            .values()
124            .any(|value| has_strict_incompatible_composition(value, false));
125    }
126    schema.as_array().is_some_and(|arr| {
127        arr.iter()
128            .any(|value| has_strict_incompatible_composition(value, false))
129    })
130}
131
132/// Collapse `{"anyOf":[X, {"type":"null"}]}` → `X ∪ {"nullable": true}`.
133///
134/// Same treatment for `oneOf`. Only collapses when exactly one non-null
135/// member and exactly one null-type member are present.
136fn collapse_nullable_unions(schema: &mut Value) {
137    let Some(obj) = schema.as_object_mut() else {
138        return;
139    };
140    for key in ["anyOf", "oneOf"] {
141        let members: Vec<Value> = match obj.get(key).and_then(|v| v.as_array()) {
142            Some(arr) => arr.clone(),
143            None => continue,
144        };
145        let (nulls, nons): (Vec<_>, Vec<_>) = members.into_iter().partition(is_null_type);
146        if nulls.len() == 1 && nons.len() == 1 {
147            // `nullable` is only meaningful when it annotates a concrete
148            // schema type. Collapsing `$ref | null` or another untyped branch
149            // would manufacture an annotation-only schema and lose the
150            // terminating union needed by MFJS reference validation.
151            let has_concrete_non_null_type = nons[0]
152                .as_object()
153                .and_then(|branch| branch.get("type"))
154                .and_then(Value::as_str)
155                .is_some_and(|schema_type| schema_type != "null");
156            if !has_concrete_non_null_type {
157                continue;
158            }
159            obj.remove(key);
160            if let Value::Object(non_obj) = nons.into_iter().next().unwrap() {
161                for (k, v) in non_obj {
162                    if k != "type" || v != "null" {
163                        obj.insert(k, v);
164                    }
165                }
166            }
167            obj.insert("nullable".into(), Value::Bool(true));
168        }
169    }
170}
171
172fn is_null_type(v: &Value) -> bool {
173    v.as_object()
174        .and_then(|o| o.get("type"))
175        .and_then(|t| t.as_str())
176        == Some("null")
177}
178
179/// Bare `{"type": "object"}` (no `properties`, no `additionalProperties`)
180/// → inject `"properties": {}` so DeepSeek's strict validator doesn't 400.
181fn inject_properties_on_bare_objects(schema: &mut Value) {
182    let Some(obj) = schema.as_object_mut() else {
183        return;
184    };
185    if obj.get("type").and_then(|t| t.as_str()) != Some("object") {
186        return;
187    }
188    if obj.contains_key("properties") || obj.contains_key("additionalProperties") {
189        return;
190    }
191    obj.insert("properties".into(), Value::Object(Map::new()));
192}
193
194/// Remove entries from `required` that aren't keys in `properties`.
195///
196/// A schema with neither `properties` nor `type` is a composition branch
197/// whose `required` names properties declared by the enclosing schema —
198/// `oneOf: [{"required": ["patch"]}, ...]` (#6561 D04-11). Its list is kept:
199/// pruning emptied every branch, turning apply_patch's "exactly one of"
200/// into an unsatisfiable `oneOf` of three `{}` and the finance tool's
201/// "ticker or symbol" into no constraint.
202///
203/// Known limitation: a `type: "object"` schema without `properties` still
204/// loses `required` entries (a bare object gets `properties: {}` injected
205/// first). Strict validators (DeepSeek strict, MFJS) reject `required`
206/// names absent from local `properties`, and this provider-neutral pass
207/// cannot invent their property types.
208fn prune_dangling_required(schema: &mut Value) {
209    let Some(obj) = schema.as_object_mut() else {
210        return;
211    };
212    if !obj.contains_key("properties") && !obj.contains_key("type") {
213        return;
214    }
215    // Collect known property names first (immutable borrow), then prune.
216    let known_keys: Vec<String> = obj
217        .get("properties")
218        .and_then(|v| v.as_object())
219        .map(|props| props.keys().cloned().collect())
220        .unwrap_or_default();
221    let Some(required) = obj.get_mut("required").and_then(|v| v.as_array_mut()) else {
222        return;
223    };
224    required.retain(|entry| {
225        entry
226            .as_str()
227            .is_some_and(|k| known_keys.iter().any(|known| known == k))
228    });
229    if required.is_empty() {
230        obj.remove("required");
231    }
232}
233
234/// Collapse `{"oneOf": [X]}` → X, same for `allOf`.
235///
236/// Single-element unions are semantically equivalent to the element itself;
237/// DeepSeek's strict validator doesn't always flatten them.
238fn collapse_single_element_unions(schema: &mut Value) {
239    let Some(obj) = schema.as_object_mut() else {
240        return;
241    };
242    for key in ["oneOf", "allOf", "anyOf"] {
243        let single = match obj.get(key).and_then(|v| v.as_array()) {
244            Some(arr) if arr.len() == 1 => arr[0].clone(),
245            _ => continue,
246        };
247        obj.remove(key);
248        if let Value::Object(inner) = single {
249            for (k, v) in inner {
250                if !obj.contains_key(&k) {
251                    obj.insert(k, v);
252                }
253            }
254        }
255    }
256}
257
258fn enforce_strict_subset(schema: &mut Value) {
259    if let Some(obj) = schema.as_object_mut() {
260        strip_unsupported_strict_keywords(obj);
261        if is_object_schema(obj) {
262            let originally_required = required_names(obj);
263            let properties = ensure_properties_object(obj);
264            let mut property_names: Vec<String> = properties.keys().cloned().collect();
265            property_names.sort();
266            for property_name in &property_names {
267                if !originally_required
268                    .iter()
269                    .any(|required| required == property_name)
270                    && let Some(property_schema) = properties.get_mut(property_name)
271                {
272                    mark_nullable(property_schema);
273                }
274            }
275            obj.insert(
276                "required".into(),
277                Value::Array(property_names.into_iter().map(Value::String).collect()),
278            );
279            obj.insert("additionalProperties".into(), Value::Bool(false));
280        }
281
282        for value in obj.values_mut() {
283            enforce_strict_subset(value);
284        }
285    } else if let Some(arr) = schema.as_array_mut() {
286        for value in arr {
287            enforce_strict_subset(value);
288        }
289    }
290}
291
292fn strip_unsupported_strict_keywords(obj: &mut Map<String, Value>) {
293    obj.remove("patternProperties");
294    match obj.get("type").and_then(Value::as_str) {
295        Some("string") => {
296            obj.remove("minLength");
297            obj.remove("maxLength");
298        }
299        Some("array") => {
300            obj.remove("minItems");
301            obj.remove("maxItems");
302        }
303        _ => {}
304    }
305}
306
307fn is_object_schema(obj: &Map<String, Value>) -> bool {
308    obj.get("type").and_then(Value::as_str) == Some("object") || obj.contains_key("properties")
309}
310
311fn ensure_properties_object(obj: &mut Map<String, Value>) -> &mut Map<String, Value> {
312    let needs_replacement = !matches!(obj.get("properties"), Some(Value::Object(_)));
313    if needs_replacement {
314        obj.insert("properties".into(), Value::Object(Map::new()));
315    }
316    obj.get_mut("properties")
317        .and_then(Value::as_object_mut)
318        .expect("properties was just ensured as object")
319}
320
321fn required_names(obj: &Map<String, Value>) -> Vec<String> {
322    obj.get("required")
323        .and_then(Value::as_array)
324        .map(|required| {
325            required
326                .iter()
327                .filter_map(Value::as_str)
328                .map(ToOwned::to_owned)
329                .collect()
330        })
331        .unwrap_or_default()
332}
333
334fn mark_nullable(schema: &mut Value) {
335    if let Some(obj) = schema.as_object_mut() {
336        obj.insert("nullable".into(), Value::Bool(true));
337    }
338}
339
340fn merge_root_composition_properties(obj: &mut Map<String, Value>) {
341    let mut merged = Map::new();
342    for key in ["oneOf", "anyOf", "allOf"] {
343        let Some(items) = obj.get(key).and_then(Value::as_array) else {
344            continue;
345        };
346        for item in items {
347            let Some(properties) = item.get("properties").and_then(Value::as_object) else {
348                continue;
349            };
350            for (name, schema) in properties {
351                merged.entry(name.clone()).or_insert_with(|| schema.clone());
352            }
353        }
354    }
355
356    if merged.is_empty() {
357        return;
358    }
359
360    let properties = ensure_properties_object(obj);
361    for (name, schema) in merged {
362        properties.entry(name).or_insert(schema);
363    }
364}
365
366fn root_composition_constraint_note(obj: &Map<String, Value>) -> Option<String> {
367    for (key, prefix) in [
368        ("oneOf", "Exactly one"),
369        ("anyOf", "At least one"),
370        ("allOf", "All"),
371    ] {
372        let Some(items) = obj.get(key).and_then(Value::as_array) else {
373            continue;
374        };
375        let mut groups: Vec<String> = items.iter().filter_map(required_group_label).collect();
376        groups.sort();
377        groups.dedup();
378        if groups.len() >= 2 {
379            return Some(format!(
380                "{prefix} of these parameter groups must be provided: {}.",
381                groups.join(" | ")
382            ));
383        }
384    }
385    None
386}
387
388/// Strip `dependentSchemas` / `dependentRequired` from every node.
389///
390/// MFJS validates each node against a closed keyword allow-list, so a schema
391/// carrying either keyword would otherwise be omitted by route projection.
392/// Keep the remaining schema and disclose the lost conditional constraints.
393fn drop_dependent_keywords(schema: &mut Value) -> Option<String> {
394    strip_dependent_keywords(schema).then(|| {
395        "This provider cannot express conditional requirements from the original schema. \
396         Honor any such requirements documented by the tool when calling it."
397            .to_string()
398    })
399}
400
401fn combine_constraint_notes(first: Option<String>, second: Option<String>) -> Option<String> {
402    match (first, second) {
403        (Some(first), Some(second)) => Some(format!("{first} {second}")),
404        (Some(note), None) | (None, Some(note)) => Some(note),
405        (None, None) => None,
406    }
407}
408
409fn strip_dependent_keywords(schema: &mut Value) -> bool {
410    match schema {
411        Value::Object(obj) => {
412            let mut dropped = obj.remove("dependentRequired").is_some();
413            dropped |= obj.remove("dependentSchemas").is_some();
414            for value in obj.values_mut() {
415                dropped |= strip_dependent_keywords(value);
416            }
417            dropped
418        }
419        Value::Array(items) => {
420            let mut dropped = false;
421            for item in items {
422                dropped |= strip_dependent_keywords(item);
423            }
424            dropped
425        }
426        _ => false,
427    }
428}
429
430fn required_group_label(item: &Value) -> Option<String> {
431    let mut names: Vec<String> = item
432        .get("required")?
433        .as_array()?
434        .iter()
435        .filter_map(Value::as_str)
436        .map(|name| format!("`{name}`"))
437        .collect();
438    if names.is_empty() {
439        None
440    } else {
441        names.sort();
442        names.dedup();
443        Some(names.join(" + "))
444    }
445}
446
447#[cfg(test)]
448mod tests {
449    use super::*;
450    use serde_json::json;
451
452    #[test]
453    fn collapses_nullable_anyof() {
454        let mut schema = json!({
455            "anyOf": [
456                {"type": "string"},
457                {"type": "null"}
458            ]
459        });
460        sanitize(&mut schema);
461        assert_eq!(schema["type"], "string");
462        assert_eq!(schema["nullable"], true);
463        assert!(schema.get("anyOf").is_none());
464    }
465
466    #[test]
467    fn collapses_nullable_oneof() {
468        let mut schema = json!({
469            "oneOf": [
470                {"type": "null"},
471                {"type": "integer", "minimum": 0}
472            ]
473        });
474        sanitize(&mut schema);
475        assert_eq!(schema["type"], "integer");
476        assert_eq!(schema["minimum"], 0);
477        assert_eq!(schema["nullable"], true);
478    }
479
480    #[test]
481    fn preserves_non_null_anyof() {
482        let original = json!({
483            "anyOf": [
484                {"type": "string"},
485                {"type": "integer"}
486            ]
487        });
488        let mut schema = original.clone();
489        sanitize(&mut schema);
490        // Multi-typed anyOf should collapse to single element after
491        // recursive walk — but here neither is null so the collapse
492        // doesn't trigger. The anyOf array itself remains.
493        assert!(schema.get("anyOf").is_some());
494    }
495
496    #[test]
497    fn injects_properties_on_bare_object() {
498        let mut schema = json!({"type": "object"});
499        sanitize(&mut schema);
500        assert!(schema.get("properties").is_some());
501        assert_eq!(schema["properties"], json!({}));
502    }
503
504    #[test]
505    fn does_not_inject_properties_when_present() {
506        let mut schema = json!({
507            "type": "object",
508            "properties": {"name": {"type": "string"}}
509        });
510        let expected = schema.clone();
511        sanitize(&mut schema);
512        assert_eq!(schema, expected);
513    }
514
515    #[test]
516    fn prunes_dangling_required() {
517        let mut schema = json!({
518            "type": "object",
519            "properties": {"name": {"type": "string"}},
520            "required": ["name", "email"]
521        });
522        sanitize(&mut schema);
523        let required = schema["required"].as_array().unwrap();
524        assert_eq!(required.len(), 1);
525        assert_eq!(required[0], "name");
526    }
527
528    #[test]
529    fn removes_required_when_all_pruned() {
530        let mut schema = json!({
531            "type": "object",
532            "properties": {},
533            "required": ["ghost"]
534        });
535        sanitize(&mut schema);
536        assert!(schema.get("required").is_none());
537    }
538
539    /// #6561 D04-11: composition branches name the parent's properties.
540    #[test]
541    fn keeps_required_groups_of_composition_branches() {
542        let mut schema = json!({
543            "type": "object",
544            "properties": {
545                "patch": {"type": "string"},
546                "replace": {"type": "array"},
547                "changes": {"type": "array"}
548            },
549            "oneOf": [
550                {"required": ["patch"]},
551                {"required": ["replace"]},
552                {"required": ["changes"]}
553            ]
554        });
555        sanitize(&mut schema);
556        assert_eq!(
557            schema["oneOf"],
558            json!([
559                {"required": ["patch"]},
560                {"required": ["replace"]},
561                {"required": ["changes"]}
562            ])
563        );
564        // A typed object still has its dangling names pruned.
565        let mut typed = json!({
566            "type": "object",
567            "properties": {"name": {"type": "string"}},
568            "required": ["name", "ghost"]
569        });
570        sanitize(&mut typed);
571        assert_eq!(typed["required"], json!(["name"]));
572    }
573
574    #[test]
575    fn collapses_single_element_oneof() {
576        let mut schema = json!({
577            "oneOf": [{"type": "string", "minLength": 1}]
578        });
579        sanitize(&mut schema);
580        assert!(schema.get("oneOf").is_none());
581        assert_eq!(schema["type"], "string");
582        assert_eq!(schema["minLength"], 1);
583    }
584
585    #[test]
586    fn collapses_single_element_anyof() {
587        let mut schema = json!({
588            "anyOf": [{"type": "boolean"}]
589        });
590        sanitize(&mut schema);
591        assert!(schema.get("anyOf").is_none());
592        assert_eq!(schema["type"], "boolean");
593    }
594
595    #[test]
596    fn recursive_walk_into_properties() {
597        let mut schema = json!({
598            "type": "object",
599            "properties": {
600                "opt_name": {
601                    "anyOf": [
602                        {"type": "string"},
603                        {"type": "null"}
604                    ]
605                }
606            }
607        });
608        sanitize(&mut schema);
609        let prop = &schema["properties"]["opt_name"];
610        assert_eq!(prop["type"], "string");
611        assert_eq!(prop["nullable"], true);
612    }
613
614    #[test]
615    fn recursive_walk_into_items() {
616        let mut schema = json!({
617            "type": "array",
618            "items": {
619                "anyOf": [
620                    {"type": "integer"},
621                    {"type": "null"}
622                ]
623            }
624        });
625        sanitize(&mut schema);
626        let items = &schema["items"];
627        assert_eq!(items["type"], "integer");
628        assert_eq!(items["nullable"], true);
629    }
630
631    #[test]
632    fn nested_anyof_in_nullable_union_stays_structural() {
633        // Pydantic can nest unions: Optional[Union[str, int]].
634        let mut schema = json!({
635            "anyOf": [
636                {
637                    "anyOf": [
638                        {"type": "string"},
639                        {"type": "integer"}
640                    ]
641                },
642                {"type": "null"}
643            ]
644        });
645        sanitize(&mut schema);
646        // The non-null branch has no concrete type of its own. Collapsing the
647        // outer union would manufacture an annotation-only `nullable` schema,
648        // so retain both levels and their explicit null termination.
649        assert!(schema.get("nullable").is_none());
650        assert_eq!(schema["anyOf"][1], json!({"type": "null"}));
651        assert_eq!(
652            schema["anyOf"][0]["anyOf"],
653            json!([{"type": "string"}, {"type": "integer"}])
654        );
655    }
656
657    #[test]
658    fn idempotent() {
659        let mut schema = json!({
660            "type": "object",
661            "properties": {
662                "name": {"type": "string"},
663                "maybe": {
664                    "anyOf": [{"type": "integer"}, {"type": "null"}]
665                }
666            },
667            "required": ["name", "missing_field"]
668        });
669        sanitize(&mut schema);
670        let after_first = schema.clone();
671        sanitize(&mut schema);
672        assert_eq!(schema, after_first, "sanitize must be idempotent");
673    }
674
675    #[test]
676    fn strict_sanitize_requires_all_object_properties_and_closes_extra_keys() {
677        let mut schema = json!({
678            "type": "object",
679            "properties": {
680                "name": {"type": "string"},
681                "count": {"type": "integer"}
682            },
683            "required": ["name"],
684            "additionalProperties": {"type": "string"}
685        });
686
687        sanitize_for_strict(&mut schema);
688
689        assert_eq!(schema["additionalProperties"], false);
690        assert_eq!(schema["required"], json!(["count", "name"]));
691        assert_eq!(schema["properties"]["count"]["nullable"], true);
692        assert!(schema["properties"]["name"].get("nullable").is_none());
693    }
694
695    #[test]
696    fn strict_sanitize_preserves_optional_properties_as_nullable() {
697        let mut schema = json!({
698            "type": "object",
699            "properties": {
700                "path": {"type": "string"},
701                "start_line": {"type": "integer"},
702                "max_lines": {"type": "integer"},
703                "options": {
704                    "type": "object",
705                    "properties": {
706                        "encoding": {"type": "string"},
707                        "trim": {"type": "boolean"}
708                    },
709                    "required": ["encoding"]
710                }
711            },
712            "required": ["path", "options"]
713        });
714
715        sanitize_for_strict(&mut schema);
716
717        assert_eq!(
718            schema["required"],
719            json!(["max_lines", "options", "path", "start_line"])
720        );
721        assert!(schema["properties"]["path"].get("nullable").is_none());
722        assert!(schema["properties"]["options"].get("nullable").is_none());
723        assert_eq!(schema["properties"]["start_line"]["nullable"], true);
724        assert_eq!(schema["properties"]["max_lines"]["nullable"], true);
725        assert_eq!(
726            schema["properties"]["options"]["required"],
727            json!(["encoding", "trim"])
728        );
729        assert!(
730            schema["properties"]["options"]["properties"]["encoding"]
731                .get("nullable")
732                .is_none()
733        );
734        assert_eq!(
735            schema["properties"]["options"]["properties"]["trim"]["nullable"],
736            true
737        );
738    }
739
740    #[test]
741    fn strict_sanitize_applies_object_rules_recursively() {
742        let mut schema = json!({
743            "type": "object",
744            "properties": {
745                "outer": {
746                    "type": "object",
747                    "properties": {
748                        "inner": {"type": "string"}
749                    },
750                    "required": []
751                }
752            },
753            "required": []
754        });
755
756        sanitize_for_strict(&mut schema);
757
758        assert_eq!(schema["required"], json!(["outer"]));
759        assert_eq!(schema["additionalProperties"], false);
760        assert_eq!(schema["properties"]["outer"]["required"], json!(["inner"]));
761        assert_eq!(schema["properties"]["outer"]["additionalProperties"], false);
762    }
763
764    #[test]
765    fn strict_sanitize_removes_unsupported_string_and_array_bounds() {
766        let mut schema = json!({
767            "type": "object",
768            "properties": {
769                "name": {
770                    "type": "string",
771                    "minLength": 1,
772                    "maxLength": 64,
773                    "pattern": "^[a-z]+$"
774                },
775                "items": {
776                    "type": "array",
777                    "minItems": 1,
778                    "maxItems": 5,
779                    "items": {"type": "string"}
780                },
781                "score": {
782                    "type": "integer",
783                    "minimum": 1,
784                    "maximum": 5
785                }
786            }
787        });
788
789        sanitize_for_strict(&mut schema);
790
791        let name = &schema["properties"]["name"];
792        assert!(name.get("minLength").is_none());
793        assert!(name.get("maxLength").is_none());
794        assert_eq!(name["pattern"], "^[a-z]+$");
795
796        let items = &schema["properties"]["items"];
797        assert!(items.get("minItems").is_none());
798        assert!(items.get("maxItems").is_none());
799
800        let score = &schema["properties"]["score"];
801        assert_eq!(score["minimum"], 1);
802        assert_eq!(score["maximum"], 5);
803    }
804
805    #[test]
806    fn responses_sanitize_removes_root_composition_from_apply_patch_shape() {
807        let mut schema = json!({
808            "type": "object",
809            "properties": {
810                "path": {"type": "string"},
811                "patch": {"type": "string"},
812                "replace": {
813                    "type": "array",
814                    "items": {
815                        "type": "object",
816                        "properties": {
817                            "path": {"type": "string"},
818                            "content": {"type": "string"}
819                        },
820                        "required": ["path", "content"]
821                    }
822                },
823                "changes": {
824                    "type": "array",
825                    "items": {
826                        "type": "object",
827                        "properties": {
828                            "path": {"type": "string"},
829                            "content": {"type": "string"}
830                        },
831                        "required": ["path", "content"]
832                    }
833                }
834            },
835            "oneOf": [
836                {"required": ["patch"]},
837                {"required": ["replace"]},
838                {"required": ["changes"]}
839            ]
840        });
841
842        let note = sanitize_for_responses(&mut schema);
843
844        assert_eq!(schema["type"], "object");
845        assert!(schema.get("oneOf").is_none());
846        assert!(schema.get("anyOf").is_none());
847        assert!(schema.get("allOf").is_none());
848        assert!(schema.get("enum").is_none());
849        assert!(schema.get("not").is_none());
850        assert!(schema["properties"].get("patch").is_some());
851        assert!(schema["properties"].get("replace").is_some());
852        assert!(schema["properties"].get("changes").is_some());
853        assert_eq!(
854            note.as_deref(),
855            Some(
856                "Exactly one of these parameter groups must be provided: `changes` | `patch` | `replace`."
857            )
858        );
859    }
860
861    #[test]
862    fn responses_sanitize_merges_root_alternative_properties() {
863        let mut schema = json!({
864            "anyOf": [
865                {
866                    "type": "object",
867                    "properties": {
868                        "path": {"type": "string"}
869                    },
870                    "required": ["path"]
871                },
872                {
873                    "type": "object",
874                    "properties": {
875                        "url": {"type": "string"}
876                    },
877                    "required": ["url"]
878                }
879            ]
880        });
881
882        let note = sanitize_for_responses(&mut schema);
883
884        assert_eq!(schema["type"], "object");
885        assert!(schema.get("anyOf").is_none());
886        assert!(schema["properties"].get("path").is_some());
887        assert!(schema["properties"].get("url").is_some());
888        assert!(schema.get("required").is_none());
889        assert_eq!(
890            note.as_deref(),
891            Some("At least one of these parameter groups must be provided: `path` | `url`.")
892        );
893    }
894
895    #[test]
896    fn responses_sanitize_preserves_nested_alternatives() {
897        let mut schema = json!({
898            "type": "object",
899            "properties": {
900                "value": {
901                    "anyOf": [
902                        {"type": "string"},
903                        {"type": "integer"}
904                    ]
905                }
906            }
907        });
908
909        let note = sanitize_for_responses(&mut schema);
910
911        assert_eq!(schema["type"], "object");
912        assert!(schema.get("anyOf").is_none());
913        assert!(schema["properties"]["value"].get("anyOf").is_some());
914        assert_eq!(note, None);
915    }
916
917    #[test]
918    fn responses_sanitize_plain_object_has_no_constraint_note() {
919        let mut schema = json!({
920            "type": "object",
921            "properties": {
922                "query": {"type": "string"}
923            }
924        });
925
926        let note = sanitize_for_responses(&mut schema);
927
928        assert_eq!(schema["type"], "object");
929        assert_eq!(note, None);
930    }
931
932    #[test]
933    fn responses_constraint_note_is_sorted_and_deduped() {
934        let mut schema = json!({
935            "type": "object",
936            "properties": {
937                "a": {"type": "string"},
938                "b": {"type": "string"},
939                "c": {"type": "string"}
940            },
941            "oneOf": [
942                {"required": ["b", "a", "a"]},
943                {"required": ["c"]},
944                {"required": ["a", "b"]}
945            ]
946        });
947
948        let note = sanitize_for_responses(&mut schema);
949
950        assert_eq!(
951            note.as_deref(),
952            Some("Exactly one of these parameter groups must be provided: `a` + `b` | `c`.")
953        );
954    }
955}
956
957/// Normalize a tool's function schema for Kimi / Moonshot API compatibility.
958///
959/// Kimi's API enforces stricter JSON Schema validation: when a schema uses
960/// `anyOf` / `oneOf`, the `type` field must be placed inside each item rather
961/// than on the parent object.  This function walks the schema root and any
962/// nested objects, pushing `"type": "object"` down into `anyOf` / `oneOf`
963/// items when present.
964///
965/// Invariant: only mutates objects that carry a top-level `type` + an
966/// `anyOf` or `oneOf` array — pure schemas without conditional alternatives
967/// are left untouched.
968pub fn sanitize_for_kimi(schema: &mut serde_json::Value) {
969    if let Some(obj) = schema.as_object_mut() {
970        // Recurse first so a type injected into this object's alternatives is
971        // not immediately removed again by processing that freshly-mutated item.
972        for map_key in ["properties", "$defs"] {
973            if let Some(children) = obj.get_mut(map_key).and_then(Value::as_object_mut) {
974                for child in children.values_mut() {
975                    sanitize_for_kimi(child);
976                }
977            }
978        }
979        if let Some(items) = obj.get_mut("items") {
980            sanitize_for_kimi(items);
981        }
982        if let Some(additional) = obj.get_mut("additionalProperties")
983            && additional.is_object()
984        {
985            sanitize_for_kimi(additional);
986        }
987        for union_key in ["anyOf", "oneOf"] {
988            if let Some(branches) = obj.get_mut(union_key).and_then(Value::as_array_mut) {
989                for branch in branches {
990                    sanitize_for_kimi(branch);
991                }
992            }
993        }
994
995        // If this object has `type` + `anyOf`/`oneOf`, push `type` into
996        // each item and remove it from the parent. Otherwise leave it alone.
997        let should_push =
998            obj.contains_key("type") && (obj.contains_key("anyOf") || obj.contains_key("oneOf"));
999        if should_push && let Some(type_val) = obj.remove("type") {
1000            for key in ["anyOf", "oneOf"] {
1001                if let Some(items) = obj.get_mut(key).and_then(|v| v.as_array_mut()) {
1002                    for item in items {
1003                        if let Some(item_obj) = item.as_object_mut()
1004                            && !item_obj.contains_key("type")
1005                        {
1006                            item_obj.insert("type".to_string(), type_val.clone());
1007                        }
1008                    }
1009                }
1010            }
1011            // The provider-neutral sanitizer injects an empty `properties`
1012            // map on every bare object before this provider pass. MFJS permits
1013            // only annotations beside `anyOf`, so remove that semantic no-op
1014            // after moving the object type into each branch.
1015            if obj
1016                .get("properties")
1017                .and_then(Value::as_object)
1018                .is_some_and(Map::is_empty)
1019            {
1020                obj.remove("properties");
1021            }
1022        }
1023    }
1024}
1025
1026/// A safe, provider-facing reason that Kimi parameters could not be emitted.
1027///
1028/// These diagnostics deliberately never include the schema or `$ref` value:
1029/// tool schemas can be supplied by MCP servers and may contain private data.
1030#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
1031pub enum KimiParameterSchemaError {
1032    #[error("Moonshot function parameters root must be a JSON object schema")]
1033    RootMustBeObject,
1034    #[error("Moonshot function parameters contain an unsupported root reference")]
1035    UnsupportedRootReference,
1036    #[error("Moonshot function parameters contain an unresolved internal root reference")]
1037    UnresolvedRootReference,
1038    #[error("Moonshot function parameters contain a cyclic internal root reference")]
1039    CyclicRootReference,
1040    #[error("Moonshot function parameters root reference must resolve to an object schema")]
1041    ReferencedRootMustBeObject,
1042    #[error("Moonshot function parameters contain unsupported nested allOf composition")]
1043    UnsupportedNestedAllOf,
1044    #[error("Moonshot function parameters contain conflicting nested union composition")]
1045    ConflictingNestedUnion,
1046    #[error("Moonshot function parameters contain an unsupported const literal")]
1047    UnsupportedConstLiteral,
1048    #[error("Moonshot function parameters contain conflicting literal constraints")]
1049    ConflictingLiteralConstraint,
1050    #[error("Moonshot function parameters contain an invalid nullable marker")]
1051    InvalidNullable,
1052    #[error("Moonshot function parameters contain an unsupported MFJS keyword")]
1053    UnsupportedKeyword,
1054    #[error("Moonshot function parameters contain an invalid MFJS schema node")]
1055    InvalidSchemaNode,
1056    #[error("Moonshot function parameters contain an invalid MFJS keyword value")]
1057    InvalidKeywordValue,
1058    #[error("Moonshot function parameters contain an invalid MFJS reference")]
1059    InvalidReference,
1060    #[error("Moonshot function parameters contain an MFJS schema without a concrete type")]
1061    MissingType,
1062    #[error("Moonshot function parameters exceed an MFJS resource limit")]
1063    ResourceLimitExceeded,
1064    #[error("Moonshot function parameters contain a non-terminating MFJS reference")]
1065    NonTerminatingReference,
1066    #[error("Moonshot function parameters contain an invalid MFJS default")]
1067    InvalidDefault,
1068    #[error("Moonshot function parameters contain an invalid MFJS range")]
1069    InvalidRange,
1070}
1071
1072/// Normalize a complete Kimi / Moonshot `function.parameters` object.
1073///
1074/// Function parameters have an additional MFJS constraint: the root must end
1075/// as a plain `type: "object"` schema. Root composition is flattened using the
1076/// same compatibility pass as Responses and xAI, while supported nested
1077/// `anyOf` branches remain nested. Internal root `$ref` values are resolved and
1078/// inlined before normalization so we never manufacture the invalid
1079/// `type + allOf($ref)` shape rejected by MFJS.
1080///
1081/// Unsupported, unresolved, cyclic, and non-object root references fail
1082/// closed with a non-secret diagnostic instead of being sent to Moonshot.
1083///
1084/// MFJS differences from JSON Schema:
1085/// <https://github.com/MoonshotAI/walle/blob/main/docs/mfjs-walle-vs-draft-2020-12.md>
1086pub fn sanitize_for_kimi_parameters(
1087    parameters: &mut Value,
1088) -> Result<Option<String>, KimiParameterSchemaError> {
1089    // Work on a clone so a rejected schema remains byte-for-byte unchanged for
1090    // callers that retain the catalog and retry against another provider.
1091    let mut candidate = parameters.clone();
1092    let constraint_note = sanitize_kimi_parameters_candidate(&mut candidate)?;
1093    validate_mfjs_parameters(&candidate)?;
1094    *parameters = candidate;
1095    Ok(constraint_note)
1096}
1097
1098fn sanitize_kimi_parameters_candidate(
1099    parameters: &mut Value,
1100) -> Result<Option<String>, KimiParameterSchemaError> {
1101    let Some(root) = parameters.as_object() else {
1102        return Err(KimiParameterSchemaError::RootMustBeObject);
1103    };
1104    if root
1105        .get("type")
1106        .is_some_and(|schema_type| schema_type != "object")
1107    {
1108        return Err(KimiParameterSchemaError::RootMustBeObject);
1109    }
1110
1111    inline_internal_kimi_root_ref(parameters)?;
1112
1113    // A function schema's root cannot carry MFJS composition because it must
1114    // simultaneously be `type: object`. Flatten the actual root shape used by
1115    // apply_patch and retain its dropped required-group contract as a prompt
1116    // note for the model.
1117    // MFJS has no conditional keywords. The shared compatibility pass drops
1118    // them with a bounded description note instead of failing the whole turn.
1119    let constraint_note = sanitize_for_responses(parameters);
1120
1121    // Restore nullable unions collapsed by the registry's provider-neutral
1122    // sanitizer, translate MFJS-safe scalar const values, and normalize nested
1123    // composition. This changes model-facing schema guidance only; each tool
1124    // keeps responsibility for validating its own arguments. allOf fails closed.
1125    normalize_kimi_compatibility(parameters, true)?;
1126
1127    // MFJS requires `type` to live inside each anyOf branch, never alongside
1128    // the union keyword. The root is composition-free at this point, so this
1129    // only adjusts valid nested unions.
1130    sanitize_for_kimi(parameters);
1131
1132    // JSON Schema reads an empty `items` schema as "items are unconstrained",
1133    // which is exactly the MFJS-legal shape with the keyword absent. MFJS
1134    // itself has no empty schema node and fails the whole tool with
1135    // MissingType, so repair the equivalent shape instead of dropping the
1136    // tool from the request.
1137    remove_empty_mfjs_items_schemas(parameters);
1138
1139    let Some(root) = parameters.as_object() else {
1140        return Err(KimiParameterSchemaError::RootMustBeObject);
1141    };
1142    if root.get("type").and_then(Value::as_str) != Some("object")
1143        || root.contains_key("anyOf")
1144        || root.contains_key("oneOf")
1145        || root.contains_key("allOf")
1146        || root.contains_key("$ref")
1147    {
1148        return Err(KimiParameterSchemaError::RootMustBeObject);
1149    }
1150
1151    Ok(constraint_note)
1152}
1153
1154/// Drop every empty `items` schema node (`"items": {}`) from a Kimi
1155/// parameters document.
1156///
1157/// Empty-schema nodes sit exactly where schema values live: property values,
1158/// `items`, object-form `additionalProperties`, `anyOf` branches, and `$defs`
1159/// entries. `properties` itself is a name map, so its own emptiness is legal
1160/// and only its values are visited. `oneOf` needs no visit: this runs after
1161/// `normalize_kimi_compatibility` has converted every non-root `oneOf` to
1162/// `anyOf`, and root composition was already flattened before that.
1163///
1164/// Children are visited before the node's own `items` check so a nested
1165/// repair can empty the parent (`"items": {"items": {}}` is vacuously true
1166/// once the inner keyword is gone, so dropping the outer keyword is still
1167/// semantics-preserving). Every removal keeps the document equivalent: an
1168/// absent `items` keyword already means unconstrained items, so a legal
1169/// document passes through unchanged.
1170fn remove_empty_mfjs_items_schemas(value: &mut Value) {
1171    let Some(obj) = value.as_object_mut() else {
1172        return;
1173    };
1174    if let Some(properties) = obj.get_mut("properties").and_then(Value::as_object_mut) {
1175        for child in properties.values_mut() {
1176            remove_empty_mfjs_items_schemas(child);
1177        }
1178    }
1179    if let Some(definitions) = obj.get_mut("$defs").and_then(Value::as_object_mut) {
1180        for child in definitions.values_mut() {
1181            remove_empty_mfjs_items_schemas(child);
1182        }
1183    }
1184    if let Some(branches) = obj.get_mut("anyOf").and_then(Value::as_array_mut) {
1185        for branch in branches.iter_mut() {
1186            remove_empty_mfjs_items_schemas(branch);
1187        }
1188    }
1189    if let Some(additional) = obj.get_mut("additionalProperties")
1190        && additional.is_object()
1191    {
1192        remove_empty_mfjs_items_schemas(additional);
1193    }
1194    if let Some(items) = obj.get_mut("items") {
1195        remove_empty_mfjs_items_schemas(items);
1196    }
1197    if obj
1198        .get("items")
1199        .is_some_and(|items| items.as_object().is_some_and(Map::is_empty))
1200    {
1201        obj.shift_remove("items");
1202    }
1203}
1204
1205fn inline_internal_kimi_root_ref(parameters: &mut Value) -> Result<(), KimiParameterSchemaError> {
1206    let document = parameters.clone();
1207    let Some(document_root) = document.as_object() else {
1208        return Err(KimiParameterSchemaError::RootMustBeObject);
1209    };
1210    let Some(root_ref) = document_root.get("$ref") else {
1211        return Ok(());
1212    };
1213    let Some(mut reference) = root_ref.as_str() else {
1214        return Err(KimiParameterSchemaError::UnsupportedRootReference);
1215    };
1216
1217    let mut visited = HashSet::new();
1218    let resolved = loop {
1219        if !reference.starts_with("#/") {
1220            return Err(KimiParameterSchemaError::UnsupportedRootReference);
1221        }
1222        if !visited.insert(reference.to_string()) {
1223            return Err(KimiParameterSchemaError::CyclicRootReference);
1224        }
1225        let target = document
1226            .pointer(&reference[1..])
1227            .ok_or(KimiParameterSchemaError::UnresolvedRootReference)?;
1228        let target = target
1229            .as_object()
1230            .ok_or(KimiParameterSchemaError::ReferencedRootMustBeObject)?;
1231        if let Some(next_ref) = target.get("$ref") {
1232            reference = next_ref
1233                .as_str()
1234                .ok_or(KimiParameterSchemaError::UnsupportedRootReference)?;
1235            continue;
1236        }
1237        if target.get("type").and_then(Value::as_str) != Some("object") {
1238            return Err(KimiParameterSchemaError::ReferencedRootMustBeObject);
1239        }
1240        break target.clone();
1241    };
1242
1243    let mut inlined = resolved;
1244    for (key, value) in document_root {
1245        if key != "$ref" {
1246            inlined.insert(key.clone(), value.clone());
1247        }
1248    }
1249    *parameters = Value::Object(inlined);
1250    Ok(())
1251}
1252
1253fn normalize_kimi_compatibility(
1254    schema: &mut Value,
1255    is_root: bool,
1256) -> Result<(), KimiParameterSchemaError> {
1257    let Some(obj) = schema.as_object_mut() else {
1258        return Err(KimiParameterSchemaError::InvalidSchemaNode);
1259    };
1260
1261    if !is_root {
1262        if obj.contains_key("allOf") {
1263            return Err(KimiParameterSchemaError::UnsupportedNestedAllOf);
1264        }
1265        if let Some(one_of) = obj.remove("oneOf") {
1266            if obj.contains_key("anyOf") {
1267                return Err(KimiParameterSchemaError::ConflictingNestedUnion);
1268            }
1269            obj.insert("anyOf".to_string(), one_of);
1270        }
1271    }
1272
1273    if let Some(constant) = obj.remove("const") {
1274        if !is_mfjs_enum_literal(&constant) {
1275            return Err(KimiParameterSchemaError::UnsupportedConstLiteral);
1276        }
1277        if !obj.contains_key("type") {
1278            let inferred = mfjs_literal_kind(&constant)
1279                .ok_or(KimiParameterSchemaError::UnsupportedConstLiteral)?;
1280            let schema_type = match inferred {
1281                MfjsLiteralKind::Integer => "integer",
1282                MfjsLiteralKind::Number => "number",
1283                MfjsLiteralKind::String => "string",
1284            };
1285            obj.insert("type".to_string(), Value::String(schema_type.to_string()));
1286        }
1287        if let Some(existing) = obj.get("enum") {
1288            let agrees = existing
1289                .as_array()
1290                .is_some_and(|values| values.as_slice() == [constant.clone()]);
1291            if !agrees {
1292                return Err(KimiParameterSchemaError::ConflictingLiteralConstraint);
1293            }
1294        } else {
1295            obj.insert("enum".to_string(), Value::Array(vec![constant]));
1296        }
1297    }
1298
1299    let nullable = obj.remove("nullable");
1300    let admits_null = nullable == Some(Value::Bool(true))
1301        || obj
1302            .get("anyOf")
1303            .and_then(Value::as_array)
1304            .is_some_and(|branches| branches.iter().any(is_null_type));
1305    if admits_null && obj.get("default").is_some_and(Value::is_null) {
1306        obj.remove("default");
1307    }
1308    if nullable.is_some()
1309        && !obj
1310            .get("type")
1311            .is_some_and(|schema_type| schema_type.as_str().is_some_and(is_mfjs_concrete_type))
1312    {
1313        return Err(KimiParameterSchemaError::InvalidNullable);
1314    }
1315    match nullable.as_ref().map(Value::as_bool) {
1316        None => {}
1317        Some(Some(false)) => {}
1318        Some(Some(true)) if is_root => {
1319            // Function parameters are required to be an object at the root;
1320            // null was never a valid wire instance there.
1321        }
1322        Some(Some(true)) => {
1323            let non_null = Value::Object(std::mem::take(obj));
1324            *schema = serde_json::json!({
1325                "anyOf": [non_null, {"type": "null"}]
1326            });
1327        }
1328        Some(None) => return Err(KimiParameterSchemaError::InvalidNullable),
1329    }
1330
1331    normalize_kimi_child_schemas(schema)?;
1332    Ok(())
1333}
1334
1335fn normalize_kimi_child_schemas(schema: &mut Value) -> Result<(), KimiParameterSchemaError> {
1336    let Some(obj) = schema.as_object_mut() else {
1337        return Err(KimiParameterSchemaError::InvalidSchemaNode);
1338    };
1339
1340    for map_key in ["properties", "$defs"] {
1341        if let Some(children) = obj.get_mut(map_key).and_then(Value::as_object_mut) {
1342            for child in children.values_mut() {
1343                normalize_kimi_compatibility(child, false)?;
1344            }
1345        }
1346    }
1347
1348    if let Some(items) = obj.get_mut("items") {
1349        normalize_kimi_compatibility(items, false)?;
1350    }
1351    if let Some(additional) = obj.get_mut("additionalProperties")
1352        && additional.is_object()
1353    {
1354        normalize_kimi_compatibility(additional, false)?;
1355    }
1356    if let Some(branches) = obj.get_mut("anyOf").and_then(Value::as_array_mut) {
1357        for branch in branches {
1358            normalize_kimi_compatibility(branch, false)?;
1359        }
1360    }
1361    Ok(())
1362}
1363
1364fn is_mfjs_enum_literal(value: &Value) -> bool {
1365    value.is_string() || value.is_number()
1366}
1367
1368/// Validate one fully normalized MFJS function-parameters schema.
1369///
1370/// Every error is a fixed enum variant: schemas can originate in MCP or
1371/// runtime tools and may contain private names or values, so diagnostics must
1372/// never echo a keyword, property, reference, or literal from the document.
1373pub fn validate_mfjs_parameters(parameters: &Value) -> Result<(), KimiParameterSchemaError> {
1374    let root = parameters
1375        .as_object()
1376        .ok_or(KimiParameterSchemaError::RootMustBeObject)?;
1377    if root.get("type").and_then(Value::as_str) != Some("object")
1378        || root.contains_key("anyOf")
1379        || root.contains_key("oneOf")
1380        || root.contains_key("allOf")
1381        || root.contains_key("$ref")
1382    {
1383        return Err(KimiParameterSchemaError::RootMustBeObject);
1384    }
1385    if serde_json::to_vec(parameters)
1386        .map(|encoded| encoded.len() > MFJS_MAX_SCHEMA_BYTES)
1387        .unwrap_or(true)
1388    {
1389        return Err(KimiParameterSchemaError::ResourceLimitExceeded);
1390    }
1391
1392    let mut state = MfjsValidationState::new(parameters);
1393    state.validate_schema(parameters, true, false, 0, 0)?;
1394
1395    let mut visiting_refs = HashSet::new();
1396    if !mfjs_schema_can_terminate(parameters, parameters, &mut visiting_refs, 0)? {
1397        return Err(KimiParameterSchemaError::NonTerminatingReference);
1398    }
1399
1400    validate_mfjs_expanded_depth(parameters, parameters, 0, &mut HashSet::new(), 0)?;
1401    if let Some(definitions) = root.get("$defs").and_then(Value::as_object) {
1402        for definition in definitions.values() {
1403            validate_mfjs_expanded_depth(definition, parameters, 0, &mut HashSet::new(), 0)?;
1404        }
1405    }
1406    Ok(())
1407}
1408
1409const MFJS_MAX_ANY_OF_ITEMS: usize = 10;
1410const MFJS_MAX_OBJECT_DEPTH: usize = 5;
1411const MFJS_MAX_TOTAL_PROPERTIES: usize = 100;
1412const MFJS_MAX_TOTAL_ENUM_VALUES: usize = 500;
1413const MFJS_ENUM_LENGTH_CHECK_THRESHOLD: usize = 250;
1414const MFJS_MAX_ENUM_STRING_LENGTH: usize = 7_500;
1415const MFJS_MAX_SCHEMA_BYTES: usize = 120_000;
1416const MFJS_MAX_STRUCTURAL_DEPTH: usize = 64;
1417const MFJS_MAX_SAFE_INTEGER: f64 = 9_007_199_254_740_991.0;
1418
1419struct MfjsValidationState<'a> {
1420    document: &'a Value,
1421    total_properties: usize,
1422    total_enum_values: usize,
1423}
1424
1425impl<'a> MfjsValidationState<'a> {
1426    fn new(document: &'a Value) -> Self {
1427        Self {
1428            document,
1429            total_properties: 0,
1430            total_enum_values: 0,
1431        }
1432    }
1433
1434    fn validate_schema(
1435        &mut self,
1436        schema: &Value,
1437        is_root: bool,
1438        allow_empty: bool,
1439        property_depth: usize,
1440        structural_depth: usize,
1441    ) -> Result<(), KimiParameterSchemaError> {
1442        if structural_depth > MFJS_MAX_STRUCTURAL_DEPTH {
1443            return Err(KimiParameterSchemaError::ResourceLimitExceeded);
1444        }
1445        let obj = schema
1446            .as_object()
1447            .ok_or(KimiParameterSchemaError::InvalidSchemaNode)?;
1448        if obj.is_empty() {
1449            return if allow_empty {
1450                Ok(())
1451            } else {
1452                Err(KimiParameterSchemaError::MissingType)
1453            };
1454        }
1455
1456        const ALLOWED_KEYWORDS: &[&str] = &[
1457            "$id",
1458            "$ref",
1459            "$defs",
1460            "anyOf",
1461            "properties",
1462            "additionalProperties",
1463            "items",
1464            "type",
1465            "enum",
1466            "required",
1467            "maxLength",
1468            "minLength",
1469            "maximum",
1470            "minimum",
1471            "maxItems",
1472            "minItems",
1473            "title",
1474            "description",
1475            "default",
1476        ];
1477        if obj
1478            .keys()
1479            .any(|keyword| !ALLOWED_KEYWORDS.contains(&keyword.as_str()))
1480        {
1481            return Err(KimiParameterSchemaError::UnsupportedKeyword);
1482        }
1483
1484        for annotation in ["title", "description"] {
1485            if obj.get(annotation).is_some_and(|value| !value.is_string()) {
1486                return Err(KimiParameterSchemaError::InvalidKeywordValue);
1487            }
1488        }
1489        if obj.get("$id").is_some_and(|value| !value.is_string())
1490            || (!is_root && obj.contains_key("$id"))
1491        {
1492            return Err(KimiParameterSchemaError::InvalidKeywordValue);
1493        }
1494
1495        if let Some(definitions) = obj.get("$defs") {
1496            if !is_root {
1497                return Err(KimiParameterSchemaError::InvalidKeywordValue);
1498            }
1499            let definitions = definitions
1500                .as_object()
1501                .ok_or(KimiParameterSchemaError::InvalidKeywordValue)?;
1502            for (name, definition) in definitions {
1503                if name.is_empty() || name.contains('/') {
1504                    return Err(KimiParameterSchemaError::InvalidKeywordValue);
1505                }
1506                self.validate_schema(definition, false, false, 0, structural_depth + 1)?;
1507            }
1508        }
1509
1510        if let Some(reference) = obj.get("$ref") {
1511            let reference = reference
1512                .as_str()
1513                .ok_or(KimiParameterSchemaError::InvalidReference)?;
1514            if resolve_mfjs_reference(self.document, reference).is_none() {
1515                return Err(KimiParameterSchemaError::InvalidReference);
1516            }
1517            let allowed_ref_sibling = |key: &str| {
1518                matches!(key, "$ref" | "title" | "description")
1519                    || (is_root && matches!(key, "$defs" | "$id"))
1520            };
1521            if obj.keys().any(|key| !allowed_ref_sibling(key)) {
1522                return Err(KimiParameterSchemaError::InvalidReference);
1523            }
1524            return Ok(());
1525        }
1526
1527        if let Some(any_of) = obj.get("anyOf") {
1528            let branches = any_of
1529                .as_array()
1530                .filter(|branches| !branches.is_empty() && branches.len() <= MFJS_MAX_ANY_OF_ITEMS)
1531                .ok_or(KimiParameterSchemaError::ResourceLimitExceeded)?;
1532            let allowed_union_sibling = |key: &str| {
1533                matches!(key, "anyOf" | "title" | "description")
1534                    || (is_root && matches!(key, "$defs" | "$id"))
1535            };
1536            if obj.keys().any(|key| !allowed_union_sibling(key)) {
1537                return Err(KimiParameterSchemaError::InvalidKeywordValue);
1538            }
1539            for branch in branches {
1540                self.validate_schema(branch, false, false, property_depth, structural_depth + 1)?;
1541            }
1542            return Ok(());
1543        }
1544
1545        let schema_type = obj
1546            .get("type")
1547            .and_then(Value::as_str)
1548            .filter(|schema_type| is_mfjs_concrete_type(schema_type))
1549            .ok_or(KimiParameterSchemaError::MissingType)?;
1550        if obj
1551            .keys()
1552            .any(|keyword| !mfjs_keyword_allowed_for_type(keyword, schema_type, is_root))
1553        {
1554            return Err(KimiParameterSchemaError::InvalidKeywordValue);
1555        }
1556
1557        if let Some(values) = obj.get("enum") {
1558            validate_mfjs_enum(values, schema_type, self)?;
1559        }
1560        if let Some(default) = obj.get("default") {
1561            validate_mfjs_default(default, schema_type)?;
1562        }
1563
1564        if let Some(properties) = obj.get("properties") {
1565            let properties = properties
1566                .as_object()
1567                .ok_or(KimiParameterSchemaError::InvalidKeywordValue)?;
1568            self.total_properties = self
1569                .total_properties
1570                .checked_add(properties.len())
1571                .ok_or(KimiParameterSchemaError::ResourceLimitExceeded)?;
1572            if self.total_properties > MFJS_MAX_TOTAL_PROPERTIES {
1573                return Err(KimiParameterSchemaError::ResourceLimitExceeded);
1574            }
1575            for (name, property) in properties {
1576                if name.is_empty()
1577                    || matches!(
1578                        name.as_str(),
1579                        "$defs" | "$ref" | "anyOf" | "required" | "additionalProperties"
1580                    )
1581                {
1582                    return Err(KimiParameterSchemaError::InvalidKeywordValue);
1583                }
1584                let child_depth = property_depth
1585                    .checked_add(1)
1586                    .ok_or(KimiParameterSchemaError::ResourceLimitExceeded)?;
1587                if child_depth > MFJS_MAX_OBJECT_DEPTH {
1588                    return Err(KimiParameterSchemaError::ResourceLimitExceeded);
1589                }
1590                self.validate_schema(property, false, false, child_depth, structural_depth + 1)?;
1591            }
1592        }
1593
1594        if let Some(required) = obj.get("required") {
1595            let required = required
1596                .as_array()
1597                .ok_or(KimiParameterSchemaError::InvalidKeywordValue)?;
1598            let properties = obj
1599                .get("properties")
1600                .and_then(Value::as_object)
1601                .ok_or(KimiParameterSchemaError::InvalidKeywordValue)?;
1602            let mut seen = HashSet::new();
1603            for name in required {
1604                let name = name
1605                    .as_str()
1606                    .ok_or(KimiParameterSchemaError::InvalidKeywordValue)?;
1607                if name.is_empty() || !properties.contains_key(name) || !seen.insert(name) {
1608                    return Err(KimiParameterSchemaError::InvalidKeywordValue);
1609                }
1610            }
1611        }
1612
1613        if let Some(additional) = obj.get("additionalProperties") {
1614            match additional {
1615                Value::Bool(_) => {}
1616                Value::Object(_) => self.validate_schema(
1617                    additional,
1618                    false,
1619                    true,
1620                    property_depth,
1621                    structural_depth + 1,
1622                )?,
1623                _ => return Err(KimiParameterSchemaError::InvalidKeywordValue),
1624            }
1625        }
1626
1627        if let Some(items) = obj.get("items") {
1628            self.validate_schema(items, false, false, property_depth, structural_depth + 1)?;
1629        }
1630
1631        validate_mfjs_bounds(obj, schema_type)?;
1632        Ok(())
1633    }
1634}
1635
1636fn is_mfjs_concrete_type(schema_type: &str) -> bool {
1637    matches!(
1638        schema_type,
1639        "null" | "boolean" | "object" | "array" | "number" | "integer" | "string"
1640    )
1641}
1642
1643fn mfjs_keyword_allowed_for_type(keyword: &str, schema_type: &str, is_root: bool) -> bool {
1644    if is_root && matches!(keyword, "$defs" | "$id") {
1645        return true;
1646    }
1647    if matches!(keyword, "type" | "title" | "description") {
1648        return true;
1649    }
1650    match schema_type {
1651        "object" => matches!(keyword, "properties" | "required" | "additionalProperties"),
1652        "array" => matches!(keyword, "items" | "minItems" | "maxItems"),
1653        "string" => matches!(keyword, "enum" | "default" | "minLength" | "maxLength"),
1654        "number" | "integer" => {
1655            matches!(keyword, "enum" | "default" | "minimum" | "maximum")
1656        }
1657        "boolean" | "null" => keyword == "default",
1658        _ => false,
1659    }
1660}
1661
1662#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1663enum MfjsLiteralKind {
1664    Integer,
1665    Number,
1666    String,
1667}
1668
1669fn mfjs_literal_kind(value: &Value) -> Option<MfjsLiteralKind> {
1670    if value.is_string() {
1671        return Some(MfjsLiteralKind::String);
1672    }
1673    let number = value.as_number()?;
1674    if number.is_i64() || number.is_u64() {
1675        Some(MfjsLiteralKind::Integer)
1676    } else {
1677        Some(MfjsLiteralKind::Number)
1678    }
1679}
1680
1681fn validate_mfjs_enum(
1682    value: &Value,
1683    schema_type: &str,
1684    state: &mut MfjsValidationState<'_>,
1685) -> Result<(), KimiParameterSchemaError> {
1686    let values = value
1687        .as_array()
1688        .filter(|values| !values.is_empty())
1689        .ok_or(KimiParameterSchemaError::InvalidKeywordValue)?;
1690    state.total_enum_values = state
1691        .total_enum_values
1692        .checked_add(values.len())
1693        .ok_or(KimiParameterSchemaError::ResourceLimitExceeded)?;
1694    if state.total_enum_values > MFJS_MAX_TOTAL_ENUM_VALUES {
1695        return Err(KimiParameterSchemaError::ResourceLimitExceeded);
1696    }
1697
1698    let values_match_type = match schema_type {
1699        "string" => values.iter().all(Value::is_string),
1700        "integer" => values
1701            .iter()
1702            .all(|value| mfjs_integer_value(value).is_some()),
1703        "number" => values.iter().all(Value::is_number),
1704        _ => false,
1705    };
1706    if !values_match_type {
1707        return Err(KimiParameterSchemaError::InvalidKeywordValue);
1708    }
1709
1710    if values.len() > MFJS_ENUM_LENGTH_CHECK_THRESHOLD {
1711        let encoded_length = values.iter().try_fold(0usize, |total, value| {
1712            let literal_length = value
1713                .as_str()
1714                .map(str::len)
1715                .unwrap_or_else(|| value.to_string().len());
1716            total.checked_add(literal_length)
1717        });
1718        if encoded_length.is_none_or(|length| length > MFJS_MAX_ENUM_STRING_LENGTH) {
1719            return Err(KimiParameterSchemaError::ResourceLimitExceeded);
1720        }
1721    }
1722    Ok(())
1723}
1724
1725fn validate_mfjs_default(value: &Value, schema_type: &str) -> Result<(), KimiParameterSchemaError> {
1726    let valid = match schema_type {
1727        "boolean" => value.is_boolean(),
1728        "number" => value.is_number(),
1729        "integer" => mfjs_integer_value(value).is_some(),
1730        "string" => value.is_string(),
1731        "null" => value.is_null(),
1732        _ => false,
1733    };
1734    if valid {
1735        Ok(())
1736    } else {
1737        Err(KimiParameterSchemaError::InvalidDefault)
1738    }
1739}
1740
1741fn mfjs_integer_value(value: &Value) -> Option<f64> {
1742    let value = value.as_number()?.as_f64()?;
1743    (value.is_finite() && value.fract() == 0.0 && value.abs() <= MFJS_MAX_SAFE_INTEGER)
1744        .then_some(value)
1745}
1746
1747fn validate_mfjs_bounds(
1748    obj: &Map<String, Value>,
1749    schema_type: &str,
1750) -> Result<(), KimiParameterSchemaError> {
1751    validate_mfjs_unsigned_range(obj, schema_type, "string", "minLength", "maxLength")?;
1752    validate_mfjs_unsigned_range(obj, schema_type, "array", "minItems", "maxItems")?;
1753
1754    let minimum = obj.get("minimum");
1755    let maximum = obj.get("maximum");
1756    if minimum.is_some() || maximum.is_some() {
1757        let parse_bound = |value: &Value| match schema_type {
1758            "integer" => mfjs_integer_value(value),
1759            "number" => value.as_number().and_then(serde_json::Number::as_f64),
1760            _ => None,
1761        };
1762        let minimum = minimum
1763            .map(|value| parse_bound(value).ok_or(KimiParameterSchemaError::InvalidRange))
1764            .transpose()?;
1765        let maximum = maximum
1766            .map(|value| parse_bound(value).ok_or(KimiParameterSchemaError::InvalidRange))
1767            .transpose()?;
1768        if minimum.zip(maximum).is_some_and(|(min, max)| min > max) {
1769            return Err(KimiParameterSchemaError::InvalidRange);
1770        }
1771    }
1772    Ok(())
1773}
1774
1775fn validate_mfjs_unsigned_range(
1776    obj: &Map<String, Value>,
1777    schema_type: &str,
1778    expected_type: &str,
1779    minimum_keyword: &str,
1780    maximum_keyword: &str,
1781) -> Result<(), KimiParameterSchemaError> {
1782    let minimum = obj.get(minimum_keyword);
1783    let maximum = obj.get(maximum_keyword);
1784    if minimum.is_none() && maximum.is_none() {
1785        return Ok(());
1786    }
1787    if schema_type != expected_type {
1788        return Err(KimiParameterSchemaError::InvalidRange);
1789    }
1790    let minimum = minimum
1791        .map(|value| value.as_u64().ok_or(KimiParameterSchemaError::InvalidRange))
1792        .transpose()?;
1793    let maximum = maximum
1794        .map(|value| value.as_u64().ok_or(KimiParameterSchemaError::InvalidRange))
1795        .transpose()?;
1796    if minimum.zip(maximum).is_some_and(|(min, max)| min > max) {
1797        return Err(KimiParameterSchemaError::InvalidRange);
1798    }
1799    Ok(())
1800}
1801
1802fn resolve_mfjs_reference<'a>(document: &'a Value, reference: &str) -> Option<&'a Value> {
1803    if reference == "#" {
1804        return Some(document);
1805    }
1806    let name = reference.strip_prefix("#/$defs/")?;
1807    if name.is_empty() || name.contains('/') {
1808        return None;
1809    }
1810    document
1811        .pointer(&reference[1..])
1812        .filter(|target| target.is_object())
1813}
1814
1815fn mfjs_schema_can_terminate(
1816    schema: &Value,
1817    document: &Value,
1818    visiting_refs: &mut HashSet<String>,
1819    structural_depth: usize,
1820) -> Result<bool, KimiParameterSchemaError> {
1821    if structural_depth > MFJS_MAX_STRUCTURAL_DEPTH {
1822        return Err(KimiParameterSchemaError::ResourceLimitExceeded);
1823    }
1824    let obj = schema
1825        .as_object()
1826        .ok_or(KimiParameterSchemaError::InvalidSchemaNode)?;
1827
1828    if let Some(reference) = obj.get("$ref").and_then(Value::as_str) {
1829        if !visiting_refs.insert(reference.to_string()) {
1830            return Ok(false);
1831        }
1832        let target = resolve_mfjs_reference(document, reference)
1833            .ok_or(KimiParameterSchemaError::InvalidReference)?;
1834        let terminates =
1835            mfjs_schema_can_terminate(target, document, visiting_refs, structural_depth + 1)?;
1836        visiting_refs.remove(reference);
1837        return Ok(terminates);
1838    }
1839
1840    if let Some(branches) = obj.get("anyOf").and_then(Value::as_array) {
1841        for branch in branches {
1842            let mut branch_refs = visiting_refs.clone();
1843            if mfjs_schema_can_terminate(branch, document, &mut branch_refs, structural_depth + 1)?
1844            {
1845                return Ok(true);
1846            }
1847        }
1848        return Ok(false);
1849    }
1850
1851    match obj.get("type").and_then(Value::as_str) {
1852        Some("object") => {
1853            let Some(required) = obj.get("required").and_then(Value::as_array) else {
1854                return Ok(true);
1855            };
1856            if required.is_empty() {
1857                return Ok(true);
1858            }
1859            let properties = obj
1860                .get("properties")
1861                .and_then(Value::as_object)
1862                .ok_or(KimiParameterSchemaError::InvalidKeywordValue)?;
1863            for name in required {
1864                let property = name
1865                    .as_str()
1866                    .and_then(|name| properties.get(name))
1867                    .ok_or(KimiParameterSchemaError::InvalidKeywordValue)?;
1868                let mut property_refs = visiting_refs.clone();
1869                if !mfjs_schema_can_terminate(
1870                    property,
1871                    document,
1872                    &mut property_refs,
1873                    structural_depth + 1,
1874                )? {
1875                    return Ok(false);
1876                }
1877            }
1878            Ok(true)
1879        }
1880        Some("array") => {
1881            if obj.get("minItems").and_then(Value::as_u64).unwrap_or(0) == 0 {
1882                return Ok(true);
1883            }
1884            let Some(items) = obj.get("items") else {
1885                return Ok(true);
1886            };
1887            mfjs_schema_can_terminate(items, document, visiting_refs, structural_depth + 1)
1888        }
1889        Some(schema_type) if is_mfjs_concrete_type(schema_type) => Ok(true),
1890        _ => Err(KimiParameterSchemaError::MissingType),
1891    }
1892}
1893
1894fn validate_mfjs_expanded_depth(
1895    schema: &Value,
1896    document: &Value,
1897    property_depth: usize,
1898    visiting_refs: &mut HashSet<String>,
1899    structural_depth: usize,
1900) -> Result<(), KimiParameterSchemaError> {
1901    if property_depth > MFJS_MAX_OBJECT_DEPTH || structural_depth > MFJS_MAX_STRUCTURAL_DEPTH {
1902        return Err(KimiParameterSchemaError::ResourceLimitExceeded);
1903    }
1904    let obj = schema
1905        .as_object()
1906        .ok_or(KimiParameterSchemaError::InvalidSchemaNode)?;
1907
1908    if let Some(reference) = obj.get("$ref").and_then(Value::as_str) {
1909        if !visiting_refs.insert(reference.to_string()) {
1910            return Ok(());
1911        }
1912        let target = resolve_mfjs_reference(document, reference)
1913            .ok_or(KimiParameterSchemaError::InvalidReference)?;
1914        let result = validate_mfjs_expanded_depth(
1915            target,
1916            document,
1917            property_depth,
1918            visiting_refs,
1919            structural_depth + 1,
1920        );
1921        visiting_refs.remove(reference);
1922        return result;
1923    }
1924
1925    if let Some(properties) = obj.get("properties").and_then(Value::as_object) {
1926        for property in properties.values() {
1927            validate_mfjs_expanded_depth(
1928                property,
1929                document,
1930                property_depth + 1,
1931                visiting_refs,
1932                structural_depth + 1,
1933            )?;
1934        }
1935    }
1936    if let Some(items) = obj.get("items") {
1937        validate_mfjs_expanded_depth(
1938            items,
1939            document,
1940            property_depth,
1941            visiting_refs,
1942            structural_depth + 1,
1943        )?;
1944    }
1945    if let Some(additional) = obj
1946        .get("additionalProperties")
1947        .filter(|additional| additional.is_object())
1948    {
1949        validate_mfjs_expanded_depth(
1950            additional,
1951            document,
1952            property_depth,
1953            visiting_refs,
1954            structural_depth + 1,
1955        )?;
1956    }
1957    if let Some(branches) = obj.get("anyOf").and_then(Value::as_array) {
1958        for branch in branches {
1959            validate_mfjs_expanded_depth(
1960                branch,
1961                document,
1962                property_depth,
1963                visiting_refs,
1964                structural_depth + 1,
1965            )?;
1966        }
1967    }
1968    Ok(())
1969}
1970
1971#[cfg(test)]
1972mod kimi_tests {
1973    use super::*;
1974    use serde_json::json;
1975
1976    #[test]
1977    fn kimi_parameters_repairs_empty_items_as_unconstrained() {
1978        // A browser-automation MCP tool ships
1979        // `args: {"type": "array", "items": {}}`. JSON Schema reads the empty
1980        // items schema as unconstrained, but MFJS fails it with MissingType
1981        // and the request builder silently dropped the whole tool — the
1982        // model kept seeing a tool_search reference it could never call. The
1983        // MFJS-legal equivalent shape drops the keyword instead.
1984        let mut schema = json!({
1985            "type": "object",
1986            "properties": {
1987                "function": {"type": "string"},
1988                "args": {"type": "array", "items": {}}
1989            },
1990            "required": ["function"],
1991            "additionalProperties": true
1992        });
1993        sanitize_for_kimi_parameters(&mut schema)
1994            .expect("empty items must repair to the keyword being absent");
1995        assert_eq!(schema["properties"]["args"], json!({"type": "array"}));
1996
1997        // Nested occurrences repair too; other untyped schema nodes still
1998        // fail closed because no semantics-preserving MFJS shape exists.
1999        let mut nested = json!({
2000            "type": "object",
2001            "properties": {
2002                "outer": {
2003                    "type": "object",
2004                    "properties": {
2005                        "inner": {"type": "array", "items": {}}
2006                    },
2007                    "required": ["inner"]
2008                }
2009            }
2010        });
2011        sanitize_for_kimi_parameters(&mut nested).expect("nested empty items repair");
2012        assert_eq!(
2013            nested["properties"]["outer"]["properties"]["inner"],
2014            json!({"type": "array"})
2015        );
2016
2017        let mut described_only = json!({
2018            "type": "object",
2019            "properties": {
2020                "args": {"type": "array", "items": {"description": "anything"}}
2021            }
2022        });
2023        assert_eq!(
2024            sanitize_for_kimi_parameters(&mut described_only).unwrap_err(),
2025            KimiParameterSchemaError::MissingType
2026        );
2027    }
2028
2029    #[test]
2030    fn kimi_parameters_repairs_nested_and_sibling_empty_items() {
2031        // items-in-items: the inner keyword repairs to nothing, which empties
2032        // the outer node; `{"items": X}` is vacuously true for non-arrays and
2033        // `{"items": {}}` accepts everything, so dropping the outer keyword
2034        // preserves the accepted set. The emptiness check must run after the
2035        // recursion or the parent is stranded as `{}` and fails MissingType.
2036        let mut grid = json!({
2037            "type": "object",
2038            "properties": {
2039                "grid": {"type": "array", "items": {"items": {}}}
2040            }
2041        });
2042        sanitize_for_kimi_parameters(&mut grid).expect("items-in-items repair");
2043        assert_eq!(grid["properties"]["grid"], json!({"type": "array"}));
2044
2045        // A root `items` keyword beside `$defs`: the repair must visit every
2046        // schema-value sibling of the root node, not just the removed key's
2047        // own subtree, or `$defs` stays unrepaired and fails the whole tool.
2048        let mut with_defs = json!({
2049            "type": "object",
2050            "items": {},
2051            "$defs": {"rows": {"type": "array", "items": {}}},
2052            "properties": {"rows": {"$ref": "#/$defs/rows"}}
2053        });
2054        sanitize_for_kimi_parameters(&mut with_defs).expect("root items beside $defs repair");
2055        assert!(with_defs.get("items").is_none());
2056        assert_eq!(with_defs["$defs"]["rows"], json!({"type": "array"}));
2057
2058        // Every schema-value position the validator recurses into must be
2059        // visited: an empty `items` inside an object-form
2060        // `additionalProperties` or an `anyOf` branch repairs too, and a
2061        // walker that skips either position would strand the node and fail
2062        // the whole tool with MissingType.
2063        let mut nested_positions = json!({
2064            "type": "object",
2065            "properties": {
2066                "map": {
2067                    "type": "object",
2068                    "additionalProperties": {"type": "array", "items": {}}
2069                },
2070                "choice": {
2071                    "anyOf": [
2072                        {"type": "string"},
2073                        {"type": "array", "items": {}}
2074                    ]
2075                }
2076            }
2077        });
2078        sanitize_for_kimi_parameters(&mut nested_positions)
2079            .expect("additionalProperties and anyOf empty items repair");
2080        assert_eq!(
2081            nested_positions["properties"]["map"]["additionalProperties"],
2082            json!({"type": "array"})
2083        );
2084        assert_eq!(
2085            nested_positions["properties"]["choice"]["anyOf"][1],
2086            json!({"type": "array"})
2087        );
2088    }
2089
2090    #[test]
2091    fn kimi_sanitize_pushes_type_into_anyof_items() {
2092        let mut schema = json!({
2093            "type": "object",
2094            "properties": {
2095                "handle": {
2096                    "type": "object",
2097                    "anyOf": [
2098                        {"type": "string"},
2099                        {"type": "null"}
2100                    ]
2101                }
2102            }
2103        });
2104        sanitize_for_kimi(&mut schema);
2105        let handle = &schema["properties"]["handle"];
2106        assert!(
2107            !handle.as_object().unwrap().contains_key("type"),
2108            "root type should be removed"
2109        );
2110        let any_of = handle["anyOf"].as_array().unwrap();
2111        assert_eq!(any_of[0]["type"], "string");
2112        assert_eq!(any_of[1]["type"], "null");
2113    }
2114
2115    #[test]
2116    fn kimi_sanitize_injects_missing_anyof_item_types() {
2117        let mut schema = json!({
2118            "type": "object",
2119            "anyOf": [
2120                {"properties": {"path": {"type": "string"}}},
2121                {"required": ["url"], "properties": {"url": {"type": "string"}}}
2122            ]
2123        });
2124
2125        sanitize_for_kimi(&mut schema);
2126
2127        assert!(
2128            !schema.as_object().unwrap().contains_key("type"),
2129            "parent type should be removed"
2130        );
2131        let any_of = schema["anyOf"].as_array().unwrap();
2132        assert_eq!(any_of[0]["type"], "object");
2133        assert_eq!(any_of[1]["type"], "object");
2134    }
2135
2136    #[test]
2137    fn kimi_sanitize_preserves_type_injected_into_nested_anyof_item() {
2138        let mut schema = json!({
2139            "type": "object",
2140            "anyOf": [
2141                {
2142                    "anyOf": [
2143                        {"properties": {"path": {"type": "string"}}}
2144                    ]
2145                }
2146            ]
2147        });
2148
2149        sanitize_for_kimi(&mut schema);
2150
2151        let outer_item = &schema["anyOf"][0];
2152        assert_eq!(outer_item["type"], "object");
2153        assert!(
2154            !schema.as_object().unwrap().contains_key("type"),
2155            "outer parent type should be removed"
2156        );
2157    }
2158
2159    #[test]
2160    fn kimi_sanitize_leaves_pure_object_untouched() {
2161        let original = json!({
2162            "type": "object",
2163            "properties": {"x": {"type": "string"}},
2164            "required": ["x"]
2165        });
2166        let mut schema = original.clone();
2167        sanitize_for_kimi(&mut schema);
2168        assert_eq!(schema, original);
2169    }
2170
2171    #[test]
2172    fn kimi_parameters_add_type_to_empty_root() {
2173        let mut schema = json!({});
2174        sanitize_for_kimi_parameters(&mut schema).unwrap();
2175        assert_eq!(schema, json!({"type": "object", "properties": {}}));
2176    }
2177
2178    #[test]
2179    fn kimi_parameters_add_type_to_properties_root_without_corrupting_properties_map() {
2180        let mut schema = json!({
2181            "properties": {
2182                "path": {"type": "string"}
2183            },
2184            "required": ["path"]
2185        });
2186
2187        sanitize_for_kimi_parameters(&mut schema).unwrap();
2188
2189        assert_eq!(schema["type"], "object");
2190        assert_eq!(schema["properties"]["path"]["type"], "string");
2191        assert!(schema["properties"].get("type").is_none());
2192    }
2193
2194    // Function parameters must end as a plain object root. Composition stays
2195    // available only in valid nested anyOf positions.
2196
2197    #[test]
2198    fn kimi_parameters_add_type_to_anyof_root() {
2199        let mut schema = json!({
2200            "anyOf": [
2201                {"type": "object", "properties": {"path": {"type": "string"}}},
2202                {"type": "null"}
2203            ]
2204        });
2205        sanitize_for_kimi_parameters(&mut schema).unwrap();
2206        assert_eq!(schema["type"], "object");
2207        assert!(schema.get("anyOf").is_none());
2208        assert_eq!(schema["properties"]["path"]["type"], "string");
2209    }
2210
2211    #[test]
2212    fn kimi_parameters_add_type_to_allof_root() {
2213        let mut schema = json!({
2214            "allOf": [
2215                {"type": "object", "properties": {"name": {"type": "string"}}}
2216            ]
2217        });
2218        sanitize_for_kimi_parameters(&mut schema).unwrap();
2219        assert_eq!(schema["type"], "object");
2220        assert!(schema.get("allOf").is_none());
2221        assert_eq!(schema["properties"]["name"]["type"], "string");
2222    }
2223
2224    #[test]
2225    fn kimi_parameters_add_type_to_oneof_root() {
2226        let mut schema = json!({
2227            "oneOf": [
2228                {"type": "object", "properties": {"id": {"type": "integer"}}},
2229                {"type": "object", "properties": {"name": {"type": "string"}}}
2230            ]
2231        });
2232        sanitize_for_kimi_parameters(&mut schema).unwrap();
2233        assert_eq!(schema["type"], "object");
2234        assert!(schema.get("oneOf").is_none());
2235        assert_eq!(schema["properties"]["id"]["type"], "integer");
2236        assert_eq!(schema["properties"]["name"]["type"], "string");
2237    }
2238
2239    #[test]
2240    fn kimi_parameters_preserves_nested_anyof_branches() {
2241        let mut schema = json!({
2242            "type": "object",
2243            "properties": {
2244                "selector": {
2245                    "type": "object",
2246                    "anyOf": [
2247                        {"properties": {"path": {"type": "string"}}},
2248                        {"properties": {"id": {"type": "integer"}}}
2249                    ]
2250                }
2251            }
2252        });
2253
2254        sanitize_for_kimi_parameters(&mut schema).unwrap();
2255
2256        assert_eq!(schema["type"], "object");
2257        let selector = &schema["properties"]["selector"];
2258        assert!(selector.get("type").is_none());
2259        let branches = selector["anyOf"].as_array().unwrap();
2260        assert_eq!(branches.len(), 2);
2261        assert!(branches.iter().all(|branch| branch["type"] == "object"));
2262    }
2263
2264    #[test]
2265    fn kimi_parameters_converts_nested_oneof_to_supported_anyof() {
2266        let mut schema = json!({
2267            "type": "object",
2268            "properties": {
2269                "selector": {
2270                    "type": "object",
2271                    "oneOf": [
2272                        {"properties": {"path": {"type": "string"}}},
2273                        {"properties": {"id": {"type": "integer"}}}
2274                    ]
2275                }
2276            }
2277        });
2278
2279        sanitize_for_kimi_parameters(&mut schema).unwrap();
2280
2281        let selector = &schema["properties"]["selector"];
2282        assert!(selector.get("oneOf").is_none());
2283        assert!(selector["anyOf"].is_array());
2284        assert!(selector.get("type").is_none());
2285    }
2286
2287    #[test]
2288    fn kimi_parameters_restores_registry_collapsed_nullable_anyof() {
2289        let mut schema = json!({
2290            "type": "object",
2291            "properties": {
2292                "query": {
2293                    "anyOf": [
2294                        {"type": "string"},
2295                        {"type": "null"}
2296                    ]
2297                }
2298            }
2299        });
2300
2301        // Exercise the exact two-stage production path: ToolRegistry applies
2302        // the provider-neutral pass before the Moonshot request adapter sees
2303        // the schema.
2304        sanitize(&mut schema);
2305        assert_eq!(schema["properties"]["query"]["nullable"], true);
2306        assert!(schema["properties"]["query"].get("anyOf").is_none());
2307
2308        sanitize_for_kimi_parameters(&mut schema).unwrap();
2309
2310        let query = &schema["properties"]["query"];
2311        assert!(query.get("nullable").is_none(), "{query}");
2312        assert_eq!(
2313            query["anyOf"],
2314            json!([{"type": "string"}, {"type": "null"}])
2315        );
2316        validate_mfjs_parameters(&schema).unwrap();
2317    }
2318
2319    #[test]
2320    fn kimi_parameters_accepts_pydantic_optional_with_null_default() {
2321        let mut schema = json!({
2322            "type": "object",
2323            "$defs": {
2324                "Filters": {
2325                    "type": "object",
2326                    "properties": {"state": {"type": "string"}}
2327                }
2328            },
2329            "properties": {
2330                "limit": {
2331                    "anyOf": [{"type": "integer"}, {"type": "null"}],
2332                    "default": null
2333                },
2334                "filters": {
2335                    "anyOf": [{"$ref": "#/$defs/Filters"}, {"type": "null"}],
2336                    "default": null
2337                }
2338            }
2339        });
2340
2341        sanitize(&mut schema);
2342        sanitize_for_kimi_parameters(&mut schema).unwrap();
2343
2344        validate_mfjs_parameters(&schema).unwrap();
2345    }
2346
2347    #[test]
2348    fn kimi_parameters_recursively_translates_safe_const_to_enum() {
2349        let mut schema = json!({
2350            "type": "object",
2351            "properties": {
2352                "envelope": {
2353                    "type": "object",
2354                    "properties": {
2355                        "items": {
2356                            "type": "array",
2357                            "items": {
2358                                "type": "object",
2359                                "properties": {
2360                                    "kind": {"type": "string", "const": "var_handle"}
2361                                },
2362                                "required": ["kind"]
2363                            }
2364                        }
2365                    }
2366                }
2367            }
2368        });
2369
2370        sanitize_for_kimi_parameters(&mut schema).unwrap();
2371
2372        let kind = schema
2373            .pointer("/properties/envelope/properties/items/items/properties/kind")
2374            .expect("nested kind schema");
2375        assert!(kind.get("const").is_none(), "{kind}");
2376        assert_eq!(kind["enum"], json!(["var_handle"]));
2377    }
2378
2379    #[test]
2380    fn kimi_parameters_rejects_unsafe_const_without_mutating_or_leaking() {
2381        let mut schema = json!({
2382            "type": "object",
2383            "properties": {
2384                "private-toggle-8172": {"type": "boolean", "const": true}
2385            }
2386        });
2387        let original = schema.clone();
2388
2389        let error = sanitize_for_kimi_parameters(&mut schema).unwrap_err();
2390
2391        assert_eq!(error, KimiParameterSchemaError::UnsupportedConstLiteral);
2392        assert!(!error.to_string().contains("private-toggle-8172"));
2393        assert_eq!(schema, original, "a rejected schema must remain reusable");
2394    }
2395
2396    #[test]
2397    fn kimi_parameters_validator_fails_closed_without_echoing_schema_values() {
2398        let mut schema = json!({
2399            "type": "object",
2400            "properties": {
2401                "private-field-4921": {
2402                    "type": "string",
2403                    "pattern": "private-pattern-value-7395"
2404                }
2405            }
2406        });
2407        let original = schema.clone();
2408
2409        let error = sanitize_for_kimi_parameters(&mut schema).unwrap_err();
2410        let diagnostic = error.to_string();
2411
2412        assert_eq!(error, KimiParameterSchemaError::UnsupportedKeyword);
2413        assert!(!diagnostic.contains("private-field-4921"));
2414        assert!(!diagnostic.contains("private-pattern-value-7395"));
2415        assert_eq!(schema, original, "failed validation must be transactional");
2416    }
2417
2418    #[test]
2419    fn kimi_parameters_rejects_untyped_schema_and_nullable_transactionally() {
2420        for (mut schema, expected, sentinels) in [
2421            (
2422                json!({
2423                    "type": "object",
2424                    "properties": {
2425                        "private-missing-type-1207": {
2426                            "description": "private-description-1208"
2427                        }
2428                    }
2429                }),
2430                KimiParameterSchemaError::MissingType,
2431                ["private-missing-type-1207", "private-description-1208"],
2432            ),
2433            (
2434                json!({
2435                    "type": "object",
2436                    "properties": {
2437                        "private-nullable-1209": {
2438                            "nullable": true,
2439                            "description": "private-nullable-description-1210"
2440                        }
2441                    }
2442                }),
2443                KimiParameterSchemaError::InvalidNullable,
2444                ["private-nullable-1209", "private-nullable-description-1210"],
2445            ),
2446        ] {
2447            let original = schema.clone();
2448            let error = sanitize_for_kimi_parameters(&mut schema).unwrap_err();
2449            assert_eq!(error, expected);
2450            for sentinel in sentinels {
2451                assert!(!error.to_string().contains(sentinel));
2452            }
2453            assert_eq!(schema, original, "rejection must be transactional");
2454        }
2455    }
2456
2457    #[test]
2458    fn kimi_parameters_infers_safe_types_for_untyped_const() {
2459        let mut schema = json!({
2460            "type": "object",
2461            "properties": {
2462                "kind": {"const": "var_handle"},
2463                "count": {"const": 7},
2464                "ratio": {"const": 1.25}
2465            }
2466        });
2467
2468        sanitize_for_kimi_parameters(&mut schema).unwrap();
2469
2470        assert_eq!(schema["properties"]["kind"]["type"], "string");
2471        assert_eq!(schema["properties"]["kind"]["enum"], json!(["var_handle"]));
2472        assert_eq!(schema["properties"]["count"]["type"], "integer");
2473        assert_eq!(schema["properties"]["count"]["enum"], json!([7]));
2474        assert_eq!(schema["properties"]["ratio"]["type"], "number");
2475        assert_eq!(schema["properties"]["ratio"]["enum"], json!([1.25]));
2476    }
2477
2478    #[test]
2479    fn kimi_parameters_allows_only_the_documented_empty_schema_exception() {
2480        let mut schema = json!({
2481            "type": "object",
2482            "additionalProperties": {}
2483        });
2484        sanitize_for_kimi_parameters(&mut schema).unwrap();
2485        assert_eq!(schema["additionalProperties"], json!({}));
2486
2487        let mut invalid = json!({
2488            "type": "object",
2489            "properties": {"value": {}}
2490        });
2491        assert_eq!(
2492            sanitize_for_kimi_parameters(&mut invalid).unwrap_err(),
2493            KimiParameterSchemaError::MissingType
2494        );
2495    }
2496
2497    #[test]
2498    fn kimi_parameters_rejects_required_direct_and_mutual_recursion() {
2499        let fixtures = [
2500            json!({
2501                "type": "object",
2502                "properties": {
2503                    "private-root-node-2201": {"$ref": "#/$defs/private-node-2202"}
2504                },
2505                "required": ["private-root-node-2201"],
2506                "$defs": {
2507                    "private-node-2202": {
2508                        "type": "object",
2509                        "properties": {
2510                            "private-next-2203": {"$ref": "#/$defs/private-node-2202"}
2511                        },
2512                        "required": ["private-next-2203"]
2513                    }
2514                }
2515            }),
2516            json!({
2517                "type": "object",
2518                "properties": {
2519                    "private-root-a-2204": {"$ref": "#/$defs/private-a-2205"}
2520                },
2521                "required": ["private-root-a-2204"],
2522                "$defs": {
2523                    "private-a-2205": {
2524                        "type": "object",
2525                        "properties": {
2526                            "private-to-b-2206": {"$ref": "#/$defs/private-b-2207"}
2527                        },
2528                        "required": ["private-to-b-2206"]
2529                    },
2530                    "private-b-2207": {
2531                        "type": "object",
2532                        "properties": {
2533                            "private-to-a-2208": {"$ref": "#/$defs/private-a-2205"}
2534                        },
2535                        "required": ["private-to-a-2208"]
2536                    }
2537                }
2538            }),
2539        ];
2540
2541        for mut schema in fixtures {
2542            let original = schema.clone();
2543            let error = sanitize_for_kimi_parameters(&mut schema).unwrap_err();
2544            assert_eq!(error, KimiParameterSchemaError::NonTerminatingReference);
2545            for sentinel in ["private-root", "private-node", "private-to"] {
2546                assert!(!error.to_string().contains(sentinel));
2547            }
2548            assert_eq!(schema, original, "recursive rejection must be atomic");
2549        }
2550    }
2551
2552    #[test]
2553    fn kimi_parameters_preserves_optional_and_nullable_recursive_termination() {
2554        let mut optional = json!({
2555            "type": "object",
2556            "properties": {
2557                "node": {"$ref": "#/$defs/Node"}
2558            },
2559            "$defs": {
2560                "Node": {
2561                    "type": "object",
2562                    "properties": {
2563                        "next": {"$ref": "#/$defs/Node"}
2564                    },
2565                    "required": ["next"]
2566                }
2567            }
2568        });
2569        sanitize_for_kimi_parameters(&mut optional).unwrap();
2570
2571        let mut nullable = json!({
2572            "type": "object",
2573            "properties": {
2574                "node": {
2575                    "anyOf": [
2576                        {"$ref": "#/$defs/Node"},
2577                        {"type": "null"}
2578                    ]
2579                }
2580            },
2581            "required": ["node"],
2582            "$defs": {
2583                "Node": {
2584                    "type": "object",
2585                    "properties": {
2586                        "next": {
2587                            "anyOf": [
2588                                {"$ref": "#/$defs/Node"},
2589                                {"type": "null"}
2590                            ]
2591                        }
2592                    },
2593                    "required": ["next"]
2594                }
2595            }
2596        });
2597        sanitize_for_kimi_parameters(&mut nullable).unwrap();
2598    }
2599
2600    #[test]
2601    fn kimi_parameters_enforces_anyof_and_aggregate_resource_limits() {
2602        let mut too_many_branches = json!({
2603            "type": "object",
2604            "properties": {
2605                "choice": {
2606                    "anyOf": (0..11)
2607                        .map(|_| json!({"type": "string"}))
2608                        .collect::<Vec<_>>()
2609                }
2610            }
2611        });
2612        assert_eq!(
2613            sanitize_for_kimi_parameters(&mut too_many_branches).unwrap_err(),
2614            KimiParameterSchemaError::ResourceLimitExceeded
2615        );
2616
2617        let string_property = || json!({"type": "string"});
2618        let mut root_properties = Map::new();
2619        for index in 0..51 {
2620            root_properties.insert(format!("root_{index}"), string_property());
2621        }
2622        let mut definition_properties = Map::new();
2623        for index in 0..50 {
2624            definition_properties.insert(format!("definition_{index}"), string_property());
2625        }
2626        let mut too_many_properties = json!({
2627            "type": "object",
2628            "properties": Value::Object(root_properties),
2629            "$defs": {
2630                "Holder": {
2631                    "type": "object",
2632                    "properties": Value::Object(definition_properties)
2633                }
2634            }
2635        });
2636        assert_eq!(
2637            sanitize_for_kimi_parameters(&mut too_many_properties).unwrap_err(),
2638            KimiParameterSchemaError::ResourceLimitExceeded
2639        );
2640
2641        let enum_values = |start: usize, count: usize| {
2642            Value::Array((start..start + count).map(|value| json!(value)).collect())
2643        };
2644        let mut too_many_enum_values = json!({
2645            "type": "object",
2646            "properties": {
2647                "first": {"type": "integer", "enum": enum_values(0, 250)},
2648                "second": {"type": "integer", "enum": enum_values(250, 251)}
2649            }
2650        });
2651        assert_eq!(
2652            sanitize_for_kimi_parameters(&mut too_many_enum_values).unwrap_err(),
2653            KimiParameterSchemaError::ResourceLimitExceeded
2654        );
2655    }
2656
2657    #[test]
2658    fn kimi_parameters_enforces_depth_and_enum_text_limits() {
2659        let mut too_deep = json!({"type": "string"});
2660        for index in (0..6).rev() {
2661            let mut properties = Map::new();
2662            properties.insert(format!("level_{index}"), too_deep);
2663            too_deep = json!({
2664                "type": "object",
2665                "properties": Value::Object(properties)
2666            });
2667        }
2668        assert_eq!(
2669            sanitize_for_kimi_parameters(&mut too_deep).unwrap_err(),
2670            KimiParameterSchemaError::ResourceLimitExceeded
2671        );
2672
2673        let long_values = Value::Array(
2674            (0..251)
2675                .map(|index| Value::String(format!("private-enum-{index:04}-xxxxxxxxxxxxxx")))
2676                .collect(),
2677        );
2678        let mut too_much_enum_text = json!({
2679            "type": "object",
2680            "properties": {
2681                "choice": {"type": "string", "enum": long_values}
2682            }
2683        });
2684        assert_eq!(
2685            sanitize_for_kimi_parameters(&mut too_much_enum_text).unwrap_err(),
2686            KimiParameterSchemaError::ResourceLimitExceeded
2687        );
2688    }
2689
2690    #[test]
2691    fn kimi_parameters_validates_default_type_and_placement_without_leaks() {
2692        let mut valid = json!({
2693            "type": "object",
2694            "properties": {
2695                "enabled": {"type": "boolean", "default": true},
2696                "count": {"type": "integer", "default": 3},
2697                "ratio": {"type": "number", "default": 1.5},
2698                "label": {"type": "string", "default": "default-label"},
2699                "empty": {"type": "null", "default": null}
2700            }
2701        });
2702        sanitize_for_kimi_parameters(&mut valid).unwrap();
2703
2704        for (mut invalid, expected) in [
2705            (
2706                json!({
2707                    "type": "object",
2708                    "properties": {
2709                        "private-default-3301": {
2710                            "type": "integer",
2711                            "default": "private-default-value-3302"
2712                        }
2713                    }
2714                }),
2715                KimiParameterSchemaError::InvalidDefault,
2716            ),
2717            (
2718                json!({
2719                    "type": "object",
2720                    "properties": {
2721                        "private-untyped-default-3303": {"default": 1}
2722                    }
2723                }),
2724                KimiParameterSchemaError::MissingType,
2725            ),
2726            (
2727                json!({
2728                    "type": "object",
2729                    "properties": {
2730                        "private-object-default-3304": {
2731                            "type": "object",
2732                            "default": {}
2733                        }
2734                    }
2735                }),
2736                KimiParameterSchemaError::InvalidKeywordValue,
2737            ),
2738        ] {
2739            let original = invalid.clone();
2740            let error = sanitize_for_kimi_parameters(&mut invalid).unwrap_err();
2741            assert_eq!(error, expected);
2742            assert!(!error.to_string().contains("private-default"));
2743            assert_eq!(invalid, original);
2744        }
2745    }
2746
2747    #[test]
2748    fn kimi_parameters_rejects_inverted_and_fractional_integer_bounds() {
2749        for mut schema in [
2750            json!({
2751                "type": "object",
2752                "properties": {
2753                    "value": {"type": "string", "minLength": 5, "maxLength": 4}
2754                }
2755            }),
2756            json!({
2757                "type": "object",
2758                "properties": {
2759                    "value": {"type": "array", "minItems": 3, "maxItems": 2}
2760                }
2761            }),
2762            json!({
2763                "type": "object",
2764                "properties": {
2765                    "value": {"type": "number", "minimum": 10, "maximum": 9}
2766                }
2767            }),
2768            json!({
2769                "type": "object",
2770                "properties": {
2771                    "value": {"type": "integer", "minimum": 1.5}
2772                }
2773            }),
2774            json!({
2775                "type": "object",
2776                "properties": {
2777                    "value": {"type": "integer", "maximum": 2.5}
2778                }
2779            }),
2780        ] {
2781            assert_eq!(
2782                sanitize_for_kimi_parameters(&mut schema).unwrap_err(),
2783                KimiParameterSchemaError::InvalidRange
2784            );
2785        }
2786    }
2787
2788    #[test]
2789    fn kimi_parameters_inlines_valid_internal_object_root_ref() {
2790        let mut schema = json!({
2791            "$ref": "#/$defs/FileArgs",
2792            "$defs": {
2793                "FileArgs": {
2794                    "type": "object",
2795                    "properties": {"path": {"type": "string"}},
2796                    "required": ["path"]
2797                }
2798            },
2799            "description": "File arguments"
2800        });
2801
2802        sanitize_for_kimi_parameters(&mut schema).unwrap();
2803
2804        assert_eq!(schema["type"], "object");
2805        assert_eq!(schema["properties"]["path"]["type"], "string");
2806        assert_eq!(schema["required"], json!(["path"]));
2807        assert_eq!(schema["description"], "File arguments");
2808        assert!(schema["$defs"].is_object());
2809        assert!(schema.get("$ref").is_none());
2810        assert!(schema.get("allOf").is_none());
2811    }
2812
2813    #[test]
2814    fn kimi_parameters_rejects_unresolved_root_ref_without_leaking_it() {
2815        let mut schema = json!({
2816            "$ref": "#/$defs/private-schema-name-9217",
2817            "$defs": {}
2818        });
2819        let original = schema.clone();
2820
2821        let error = sanitize_for_kimi_parameters(&mut schema).unwrap_err();
2822
2823        assert_eq!(error, KimiParameterSchemaError::UnresolvedRootReference);
2824        assert!(!error.to_string().contains("private-schema-name-9217"));
2825        assert_eq!(schema, original, "a rejected schema must never be emitted");
2826    }
2827
2828    fn contains_key_anywhere(value: &Value, key: &str) -> bool {
2829        match value {
2830            Value::Object(map) => {
2831                map.contains_key(key) || map.values().any(|v| contains_key_anywhere(v, key))
2832            }
2833            Value::Array(items) => items.iter().any(|v| contains_key_anywhere(v, key)),
2834            _ => false,
2835        }
2836    }
2837
2838    fn action_discriminated_schema() -> Value {
2839        json!({
2840            "type": "object",
2841            "properties": {
2842                "action": {"type": "string", "enum": ["start", "status"]},
2843                "prompt": {"type": "string"},
2844                "agent_id": {"type": "string"}
2845            },
2846            "required": ["action"],
2847            "dependentRequired": {
2848                "prompt": ["action"]
2849            },
2850            "dependentSchemas": {
2851                "action": {"required": ["prompt"]}
2852            }
2853        })
2854    }
2855
2856    #[test]
2857    fn kimi_degrades_dependent_keywords_to_the_flat_schema() {
2858        let mut schema = action_discriminated_schema();
2859
2860        let note = sanitize_for_kimi_parameters(&mut schema).expect("must not refuse the schema");
2861
2862        assert!(!contains_key_anywhere(&schema, "dependentSchemas"));
2863        assert!(!contains_key_anywhere(&schema, "dependentRequired"));
2864        let properties = schema["properties"].as_object().expect("properties");
2865        for name in ["action", "prompt", "agent_id"] {
2866            assert!(properties.contains_key(name), "{name} left the flat schema");
2867        }
2868        assert_eq!(schema["required"], json!(["action"]));
2869        validate_mfjs_parameters(&schema).expect("degraded schema must validate");
2870
2871        let note = note.expect("dropping a requirement must be reported to the model");
2872        assert_eq!(
2873            note,
2874            "This provider cannot express conditional requirements from the original schema. \
2875             Honor any such requirements documented by the tool when calling it."
2876        );
2877    }
2878
2879    #[test]
2880    fn kimi_leaves_schemas_without_dependent_keywords_unannotated() {
2881        let mut schema = json!({
2882            "type": "object",
2883            "properties": {"path": {"type": "string"}},
2884            "required": ["path"]
2885        });
2886
2887        let note = sanitize_for_kimi_parameters(&mut schema).expect("plain schema");
2888
2889        assert_eq!(
2890            note, None,
2891            "a schema that lost nothing must not gain a note"
2892        );
2893        assert_eq!(schema["required"], json!(["path"]));
2894    }
2895
2896    #[test]
2897    fn kimi_degrades_dependent_keywords_nested_under_properties() {
2898        let mut schema = json!({
2899            "type": "object",
2900            "properties": {
2901                "target": {
2902                    "type": "object",
2903                    "properties": {
2904                        "kind": {"type": "string"},
2905                        "path": {"type": "string"}
2906                    },
2907                    "dependentRequired": {"kind": ["path"]}
2908                }
2909            }
2910        });
2911
2912        let note = sanitize_for_kimi_parameters(&mut schema).expect("nested composition");
2913
2914        assert!(!contains_key_anywhere(&schema, "dependentRequired"));
2915        assert!(
2916            schema["properties"]["target"]["properties"]
2917                .as_object()
2918                .expect("nested properties")
2919                .contains_key("path")
2920        );
2921        validate_mfjs_parameters(&schema).expect("degraded schema must validate");
2922        assert!(note.is_some(), "nested drop must still be reported");
2923    }
2924
2925    #[test]
2926    fn kimi_reports_malformed_dependent_keywords_that_it_drops() {
2927        let mut schema = json!({
2928            "type": "object",
2929            "properties": {},
2930            "dependentRequired": false,
2931            "dependentSchemas": ["invalid"]
2932        });
2933
2934        let note = sanitize_for_kimi_parameters(&mut schema).expect("degraded schema");
2935
2936        assert!(note.is_some(), "every dropped dependency must be reported");
2937        assert!(!contains_key_anywhere(&schema, "dependentRequired"));
2938        assert!(!contains_key_anywhere(&schema, "dependentSchemas"));
2939    }
2940
2941    #[test]
2942    fn kimi_parameters_rejects_non_object_root_ref_without_leaking_it() {
2943        let mut schema = json!({
2944            "$ref": "#/$defs/private-scalar-name-4831",
2945            "$defs": {
2946                "private-scalar-name-4831": {"type": "string"}
2947            }
2948        });
2949        let original = schema.clone();
2950
2951        let error = sanitize_for_kimi_parameters(&mut schema).unwrap_err();
2952
2953        assert_eq!(error, KimiParameterSchemaError::ReferencedRootMustBeObject);
2954        assert!(!error.to_string().contains("private-scalar-name-4831"));
2955        assert_eq!(schema, original, "a rejected schema must never be emitted");
2956    }
2957}