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