Skip to main content

adk_model/openai/
schema_adapter.rs

1//! OpenAI schema adapters for function-calling APIs.
2//!
3//! Provides two adapters:
4//!
5//! - [`OpenAiStrictSchemaAdapter`]: For OpenAI strict mode — preserves `$ref`/`$defs`,
6//!   `anyOf`/`oneOf`, and type arrays while recursively injecting
7//!   `additionalProperties: false` on all object schemas.
8//!
9//! - [`OpenAiSchemaAdapter`]: For OpenAI non-strict mode — applies minimal safe fixes
10//!   without destroying schema semantics. Does NOT remove `$ref`, `$defs`, `anyOf`,
11//!   `oneOf`, `additionalProperties`, or collapse type arrays.
12//!
13//! Both adapters share the same allowed format list as Gemini:
14//! `date-time`, `date`, `time`, `email`, `uri`, `uuid`, `int32`, `int64`, `float`, `double`.
15
16use adk_core::{SchemaAdapter, schema_utils};
17use serde_json::Value;
18
19/// Allowed format values for OpenAI adapters (same as Gemini/Generic).
20const OPENAI_ALLOWED_FORMATS: &[&str] =
21    &["date-time", "date", "time", "email", "uri", "uuid", "int32", "int64", "float", "double"];
22
23/// Schema adapter for OpenAI strict mode.
24///
25/// Applies conservative transforms and recursively sets `additionalProperties: false`
26/// on all object schemas. Preserves `$ref`, `$defs`, `anyOf`, `oneOf`, and type arrays.
27///
28/// Transform order:
29/// 1. `strip_schema_keyword`
30/// 2. `strip_conditional_keywords`
31/// 3. `convert_const_to_enum`
32/// 4. `add_implicit_object_type`
33/// 5. `strip_unsupported_formats`
34/// 6. Recursively set `additionalProperties: false` on all object schemas
35///
36/// # Example
37///
38/// ```rust
39/// use adk_model::openai::OpenAiStrictSchemaAdapter;
40/// use adk_core::SchemaAdapter;
41/// use serde_json::json;
42///
43/// let adapter = OpenAiStrictSchemaAdapter;
44/// let schema = json!({
45///     "type": "object",
46///     "properties": {
47///         "name": { "type": "string" },
48///         "address": {
49///             "type": "object",
50///             "properties": {
51///                 "street": { "type": "string" }
52///             }
53///         }
54///     }
55/// });
56///
57/// let result = adapter.normalize_schema(schema);
58/// assert_eq!(result["additionalProperties"], false);
59/// assert_eq!(result["properties"]["address"]["additionalProperties"], false);
60/// ```
61#[derive(Debug)]
62pub struct OpenAiStrictSchemaAdapter;
63
64impl SchemaAdapter for OpenAiStrictSchemaAdapter {
65    fn normalize_schema(&self, mut schema: Value) -> Value {
66        schema_utils::strip_schema_keyword(&mut schema);
67        schema_utils::strip_conditional_keywords(&mut schema);
68        schema_utils::convert_const_to_enum(&mut schema);
69        schema_utils::add_implicit_object_type(&mut schema);
70        schema_utils::strip_unsupported_formats(&mut schema, OPENAI_ALLOWED_FORMATS);
71        set_additional_properties_false(&mut schema);
72        schema
73    }
74
75    /// Returns `{"type": "object", "properties": {}, "additionalProperties": false}`.
76    ///
77    /// OpenAI strict mode requires `additionalProperties: false` even on the
78    /// empty fallback schema.
79    fn empty_schema(&self) -> Value {
80        serde_json::json!({
81            "type": "object",
82            "properties": {},
83            "additionalProperties": false
84        })
85    }
86}
87
88/// Schema adapter for OpenAI non-strict mode.
89///
90/// Applies minimal safe fixes without destroying schema semantics. Does NOT
91/// remove `$ref`, `$defs`, `anyOf`, `oneOf`, `additionalProperties`, or
92/// collapse type arrays.
93///
94/// Transform order:
95/// 1. `strip_schema_keyword`
96/// 2. `strip_conditional_keywords`
97/// 3. `convert_const_to_enum`
98/// 4. `add_implicit_object_type`
99/// 5. `strip_unsupported_formats`
100///
101/// # Example
102///
103/// ```rust
104/// use adk_model::openai::OpenAiSchemaAdapter;
105/// use adk_core::SchemaAdapter;
106/// use serde_json::json;
107///
108/// let adapter = OpenAiSchemaAdapter;
109/// let schema = json!({
110///     "$schema": "http://json-schema.org/draft-07/schema#",
111///     "type": "object",
112///     "properties": {
113///         "name": { "type": "string" }
114///     },
115///     "$ref": "#/$defs/Base",
116///     "anyOf": [{"type": "string"}, {"type": "number"}],
117///     "additionalProperties": true
118/// });
119///
120/// let result = adapter.normalize_schema(schema);
121/// // $schema removed
122/// assert!(result.get("$schema").is_none());
123/// // $ref, anyOf, additionalProperties preserved
124/// assert!(result.get("$ref").is_some());
125/// assert!(result.get("anyOf").is_some());
126/// assert!(result.get("additionalProperties").is_some());
127/// ```
128#[derive(Debug)]
129pub struct OpenAiSchemaAdapter;
130
131impl SchemaAdapter for OpenAiSchemaAdapter {
132    fn normalize_schema(&self, mut schema: Value) -> Value {
133        schema_utils::strip_schema_keyword(&mut schema);
134        schema_utils::strip_conditional_keywords(&mut schema);
135        schema_utils::convert_const_to_enum(&mut schema);
136        schema_utils::add_implicit_object_type(&mut schema);
137        schema_utils::strip_unsupported_formats(&mut schema, OPENAI_ALLOWED_FORMATS);
138        schema
139    }
140}
141
142/// Recursively sets `additionalProperties: false` on all object schemas.
143///
144/// An "object schema" is identified by having `"type": "object"` or having
145/// a `"properties"` key. This function traverses into all nested sub-schema
146/// locations: `properties`, `items`, `allOf`, `anyOf`, `oneOf`, `not`,
147/// `patternProperties`, `prefixItems`, `$defs`, and `additionalProperties`
148/// (when it is itself a schema object).
149fn set_additional_properties_false(schema: &mut Value) {
150    let Some(obj) = schema.as_object_mut() else {
151        return;
152    };
153
154    let is_object_schema = obj.get("type").and_then(|t| t.as_str()).is_some_and(|t| t == "object")
155        || obj.contains_key("properties");
156
157    if is_object_schema {
158        obj.insert("additionalProperties".to_string(), Value::Bool(false));
159    }
160
161    // Recurse into properties
162    if let Some(props) = obj.get_mut("properties")
163        && let Some(props_obj) = props.as_object_mut()
164    {
165        for value in props_obj.values_mut() {
166            set_additional_properties_false(value);
167        }
168    }
169
170    // Recurse into items (single schema or array)
171    if let Some(items) = obj.get_mut("items") {
172        if items.is_object() {
173            set_additional_properties_false(items);
174        } else if let Some(arr) = items.as_array_mut() {
175            for item in arr.iter_mut() {
176                set_additional_properties_false(item);
177            }
178        }
179    }
180
181    // Recurse into additionalProperties when it's a schema object (not boolean)
182    if let Some(additional) = obj.get_mut("additionalProperties")
183        && additional.is_object()
184    {
185        set_additional_properties_false(additional);
186    }
187
188    // Recurse into allOf, anyOf, oneOf
189    for keyword in &["allOf", "anyOf", "oneOf"] {
190        if let Some(arr_val) = obj.get_mut(*keyword)
191            && let Some(arr) = arr_val.as_array_mut()
192        {
193            for sub in arr.iter_mut() {
194                set_additional_properties_false(sub);
195            }
196        }
197    }
198
199    // Recurse into not
200    if let Some(not_schema) = obj.get_mut("not")
201        && not_schema.is_object()
202    {
203        set_additional_properties_false(not_schema);
204    }
205
206    // Recurse into patternProperties
207    if let Some(pattern_props) = obj.get_mut("patternProperties")
208        && let Some(pp_obj) = pattern_props.as_object_mut()
209    {
210        for value in pp_obj.values_mut() {
211            set_additional_properties_false(value);
212        }
213    }
214
215    // Recurse into prefixItems
216    if let Some(prefix_items) = obj.get_mut("prefixItems")
217        && let Some(arr) = prefix_items.as_array_mut()
218    {
219        for item in arr.iter_mut() {
220            set_additional_properties_false(item);
221        }
222    }
223
224    // Recurse into $defs
225    if let Some(defs) = obj.get_mut("$defs")
226        && let Some(defs_obj) = defs.as_object_mut()
227    {
228        for value in defs_obj.values_mut() {
229            set_additional_properties_false(value);
230        }
231    }
232
233    // Recurse into definitions (Draft 4-7)
234    if let Some(defs) = obj.get_mut("definitions")
235        && let Some(defs_obj) = defs.as_object_mut()
236    {
237        for value in defs_obj.values_mut() {
238            set_additional_properties_false(value);
239        }
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246    use serde_json::json;
247
248    // --- OpenAiStrictSchemaAdapter tests ---
249
250    #[test]
251    fn test_strict_strips_schema_keyword() {
252        let adapter = OpenAiStrictSchemaAdapter;
253        let schema = json!({
254            "$schema": "http://json-schema.org/draft-07/schema#",
255            "type": "object",
256            "properties": { "name": { "type": "string" } }
257        });
258        let result = adapter.normalize_schema(schema);
259        assert!(result.get("$schema").is_none());
260    }
261
262    #[test]
263    fn test_strict_strips_conditional_keywords() {
264        let adapter = OpenAiStrictSchemaAdapter;
265        let schema = json!({
266            "type": "object",
267            "properties": {},
268            "if": { "properties": { "kind": { "const": "a" } } },
269            "then": { "required": ["extra"] },
270            "else": { "required": [] }
271        });
272        let result = adapter.normalize_schema(schema);
273        assert!(result.get("if").is_none());
274        assert!(result.get("then").is_none());
275        assert!(result.get("else").is_none());
276    }
277
278    #[test]
279    fn test_strict_converts_const_to_enum() {
280        let adapter = OpenAiStrictSchemaAdapter;
281        let schema = json!({
282            "type": "string",
283            "const": "fixed_value"
284        });
285        let result = adapter.normalize_schema(schema);
286        assert!(result.get("const").is_none());
287        assert_eq!(result["enum"], json!(["fixed_value"]));
288    }
289
290    #[test]
291    fn test_strict_adds_implicit_object_type() {
292        let adapter = OpenAiStrictSchemaAdapter;
293        let schema = json!({
294            "properties": {
295                "name": { "type": "string" }
296            }
297        });
298        let result = adapter.normalize_schema(schema);
299        assert_eq!(result["type"], "object");
300    }
301
302    #[test]
303    fn test_strict_strips_unsupported_formats() {
304        let adapter = OpenAiStrictSchemaAdapter;
305        let schema = json!({
306            "type": "object",
307            "properties": {
308                "created": { "type": "string", "format": "date-time" },
309                "hostname": { "type": "string", "format": "hostname" }
310            }
311        });
312        let result = adapter.normalize_schema(schema);
313        assert_eq!(result["properties"]["created"]["format"], "date-time");
314        assert!(result["properties"]["hostname"].get("format").is_none());
315    }
316
317    #[test]
318    fn test_strict_sets_additional_properties_false_on_root() {
319        let adapter = OpenAiStrictSchemaAdapter;
320        let schema = json!({
321            "type": "object",
322            "properties": {
323                "name": { "type": "string" }
324            }
325        });
326        let result = adapter.normalize_schema(schema);
327        assert_eq!(result["additionalProperties"], false);
328    }
329
330    #[test]
331    fn test_strict_sets_additional_properties_false_recursively() {
332        let adapter = OpenAiStrictSchemaAdapter;
333        let schema = json!({
334            "type": "object",
335            "properties": {
336                "address": {
337                    "type": "object",
338                    "properties": {
339                        "city": { "type": "string" },
340                        "geo": {
341                            "type": "object",
342                            "properties": {
343                                "lat": { "type": "number" }
344                            }
345                        }
346                    }
347                }
348            }
349        });
350        let result = adapter.normalize_schema(schema);
351        assert_eq!(result["additionalProperties"], false);
352        assert_eq!(result["properties"]["address"]["additionalProperties"], false);
353        assert_eq!(
354            result["properties"]["address"]["properties"]["geo"]["additionalProperties"],
355            false
356        );
357    }
358
359    #[test]
360    fn test_strict_sets_additional_properties_in_defs() {
361        let adapter = OpenAiStrictSchemaAdapter;
362        let schema = json!({
363            "type": "object",
364            "properties": {
365                "item": { "$ref": "#/$defs/Item" }
366            },
367            "$defs": {
368                "Item": {
369                    "type": "object",
370                    "properties": {
371                        "name": { "type": "string" }
372                    }
373                }
374            }
375        });
376        let result = adapter.normalize_schema(schema);
377        assert_eq!(result["$defs"]["Item"]["additionalProperties"], false);
378    }
379
380    #[test]
381    fn test_strict_preserves_ref() {
382        let adapter = OpenAiStrictSchemaAdapter;
383        let schema = json!({
384            "type": "object",
385            "properties": {
386                "item": { "$ref": "#/$defs/Item" }
387            },
388            "$defs": {
389                "Item": {
390                    "type": "object",
391                    "properties": { "name": { "type": "string" } }
392                }
393            }
394        });
395        let result = adapter.normalize_schema(schema);
396        assert_eq!(result["properties"]["item"]["$ref"], "#/$defs/Item");
397        assert!(result.get("$defs").is_some());
398    }
399
400    #[test]
401    fn test_strict_preserves_any_of() {
402        let adapter = OpenAiStrictSchemaAdapter;
403        let schema = json!({
404            "type": "object",
405            "properties": {
406                "value": {
407                    "anyOf": [
408                        { "type": "string" },
409                        { "type": "null" }
410                    ]
411                }
412            }
413        });
414        let result = adapter.normalize_schema(schema);
415        assert!(result["properties"]["value"].get("anyOf").is_some());
416    }
417
418    #[test]
419    fn test_strict_preserves_one_of() {
420        let adapter = OpenAiStrictSchemaAdapter;
421        let schema = json!({
422            "type": "object",
423            "properties": {
424                "value": {
425                    "oneOf": [
426                        { "type": "string" },
427                        { "type": "number" }
428                    ]
429                }
430            }
431        });
432        let result = adapter.normalize_schema(schema);
433        assert!(result["properties"]["value"].get("oneOf").is_some());
434    }
435
436    #[test]
437    fn test_strict_preserves_type_arrays() {
438        let adapter = OpenAiStrictSchemaAdapter;
439        let schema = json!({
440            "type": "object",
441            "properties": {
442                "nullable_name": {
443                    "type": ["string", "null"]
444                }
445            }
446        });
447        let result = adapter.normalize_schema(schema);
448        assert_eq!(result["properties"]["nullable_name"]["type"], json!(["string", "null"]));
449    }
450
451    #[test]
452    fn test_strict_empty_schema() {
453        let adapter = OpenAiStrictSchemaAdapter;
454        let empty = adapter.empty_schema();
455        assert_eq!(
456            empty,
457            json!({"type": "object", "properties": {}, "additionalProperties": false})
458        );
459    }
460
461    #[test]
462    fn test_strict_sets_additional_properties_in_any_of_sub_schemas() {
463        let adapter = OpenAiStrictSchemaAdapter;
464        let schema = json!({
465            "type": "object",
466            "properties": {
467                "value": {
468                    "anyOf": [
469                        {
470                            "type": "object",
471                            "properties": { "a": { "type": "string" } }
472                        },
473                        { "type": "null" }
474                    ]
475                }
476            }
477        });
478        let result = adapter.normalize_schema(schema);
479        let any_of = result["properties"]["value"]["anyOf"].as_array().unwrap();
480        assert_eq!(any_of[0]["additionalProperties"], false);
481    }
482
483    #[test]
484    fn test_strict_idempotent() {
485        let adapter = OpenAiStrictSchemaAdapter;
486        let schema = json!({
487            "type": "object",
488            "properties": {
489                "name": { "type": "string" },
490                "nested": {
491                    "type": "object",
492                    "properties": {
493                        "value": { "type": "number" }
494                    }
495                }
496            }
497        });
498        let first = adapter.normalize_schema(schema);
499        let second = adapter.normalize_schema(first.clone());
500        assert_eq!(first, second);
501    }
502
503    // --- OpenAiSchemaAdapter tests ---
504
505    #[test]
506    fn test_non_strict_strips_schema_keyword() {
507        let adapter = OpenAiSchemaAdapter;
508        let schema = json!({
509            "$schema": "http://json-schema.org/draft-07/schema#",
510            "type": "object",
511            "properties": { "name": { "type": "string" } }
512        });
513        let result = adapter.normalize_schema(schema);
514        assert!(result.get("$schema").is_none());
515    }
516
517    #[test]
518    fn test_non_strict_strips_conditional_keywords() {
519        let adapter = OpenAiSchemaAdapter;
520        let schema = json!({
521            "type": "object",
522            "if": { "properties": { "kind": { "const": "a" } } },
523            "then": { "required": ["extra"] },
524            "else": { "required": [] }
525        });
526        let result = adapter.normalize_schema(schema);
527        assert!(result.get("if").is_none());
528        assert!(result.get("then").is_none());
529        assert!(result.get("else").is_none());
530    }
531
532    #[test]
533    fn test_non_strict_converts_const_to_enum() {
534        let adapter = OpenAiSchemaAdapter;
535        let schema = json!({
536            "type": "string",
537            "const": "fixed_value"
538        });
539        let result = adapter.normalize_schema(schema);
540        assert!(result.get("const").is_none());
541        assert_eq!(result["enum"], json!(["fixed_value"]));
542    }
543
544    #[test]
545    fn test_non_strict_adds_implicit_object_type() {
546        let adapter = OpenAiSchemaAdapter;
547        let schema = json!({
548            "properties": {
549                "name": { "type": "string" }
550            }
551        });
552        let result = adapter.normalize_schema(schema);
553        assert_eq!(result["type"], "object");
554    }
555
556    #[test]
557    fn test_non_strict_strips_unsupported_formats() {
558        let adapter = OpenAiSchemaAdapter;
559        let schema = json!({
560            "type": "object",
561            "properties": {
562                "created": { "type": "string", "format": "date-time" },
563                "hostname": { "type": "string", "format": "hostname" },
564                "id": { "type": "string", "format": "uuid" }
565            }
566        });
567        let result = adapter.normalize_schema(schema);
568        assert_eq!(result["properties"]["created"]["format"], "date-time");
569        assert!(result["properties"]["hostname"].get("format").is_none());
570        assert_eq!(result["properties"]["id"]["format"], "uuid");
571    }
572
573    #[test]
574    fn test_non_strict_preserves_ref() {
575        let adapter = OpenAiSchemaAdapter;
576        let schema = json!({
577            "type": "object",
578            "properties": {
579                "item": { "$ref": "#/$defs/Item" }
580            },
581            "$defs": {
582                "Item": { "type": "object" }
583            }
584        });
585        let result = adapter.normalize_schema(schema);
586        assert_eq!(result["properties"]["item"]["$ref"], "#/$defs/Item");
587        assert!(result.get("$defs").is_some());
588    }
589
590    #[test]
591    fn test_non_strict_preserves_any_of() {
592        let adapter = OpenAiSchemaAdapter;
593        let schema = json!({
594            "anyOf": [
595                { "type": "string" },
596                { "type": "number" }
597            ]
598        });
599        let result = adapter.normalize_schema(schema);
600        assert!(result.get("anyOf").is_some());
601        assert_eq!(result["anyOf"].as_array().unwrap().len(), 2);
602    }
603
604    #[test]
605    fn test_non_strict_preserves_one_of() {
606        let adapter = OpenAiSchemaAdapter;
607        let schema = json!({
608            "oneOf": [
609                { "type": "boolean" },
610                { "type": "null" }
611            ]
612        });
613        let result = adapter.normalize_schema(schema);
614        assert!(result.get("oneOf").is_some());
615    }
616
617    #[test]
618    fn test_non_strict_preserves_additional_properties() {
619        let adapter = OpenAiSchemaAdapter;
620        let schema = json!({
621            "type": "object",
622            "properties": { "name": { "type": "string" } },
623            "additionalProperties": true
624        });
625        let result = adapter.normalize_schema(schema);
626        assert_eq!(result["additionalProperties"], true);
627    }
628
629    #[test]
630    fn test_non_strict_does_not_collapse_type_arrays() {
631        let adapter = OpenAiSchemaAdapter;
632        let schema = json!({
633            "type": ["string", "null"]
634        });
635        let result = adapter.normalize_schema(schema);
636        assert_eq!(result["type"], json!(["string", "null"]));
637    }
638
639    #[test]
640    fn test_non_strict_empty_schema() {
641        let adapter = OpenAiSchemaAdapter;
642        let empty = adapter.empty_schema();
643        assert_eq!(empty, json!({"type": "object", "properties": {}}));
644    }
645
646    #[test]
647    fn test_non_strict_idempotent() {
648        let adapter = OpenAiSchemaAdapter;
649        let schema = json!({
650            "$schema": "http://json-schema.org/draft-07/schema#",
651            "properties": {
652                "name": { "type": "string", "const": "test", "format": "hostname" }
653            },
654            "if": { "const": true },
655            "then": { "required": ["name"] }
656        });
657        let first = adapter.normalize_schema(schema);
658        let second = adapter.normalize_schema(first.clone());
659        assert_eq!(first, second);
660    }
661
662    #[test]
663    fn test_non_strict_preserves_all_formats_in_allowed_list() {
664        let adapter = OpenAiSchemaAdapter;
665        for format in OPENAI_ALLOWED_FORMATS {
666            let schema = json!({ "type": "string", "format": format });
667            let result = adapter.normalize_schema(schema);
668            assert_eq!(result["format"], *format, "format '{format}' should be preserved");
669        }
670    }
671
672    /// Verifies OpenAI strict mode preserves `$ref`/`$defs`, `anyOf`, and type arrays
673    /// while recursively adding `additionalProperties: false` to all object schemas.
674    ///
675    /// **Validates: Requirements 4.1, 4.2, 4.3**
676    #[test]
677    fn test_strict_preserves_ref_defs_and_adds_additional_properties() {
678        let adapter = OpenAiStrictSchemaAdapter;
679        let schema = json!({
680            "type": "object",
681            "$defs": {
682                "Address": {
683                    "type": "object",
684                    "properties": {
685                        "street": { "type": "string" }
686                    }
687                }
688            },
689            "properties": {
690                "home": { "$ref": "#/$defs/Address" },
691                "name": { "type": ["string", "null"] },
692                "status": {
693                    "anyOf": [
694                        { "type": "string" },
695                        { "type": "null" }
696                    ]
697                }
698            }
699        });
700
701        let result = adapter.normalize_schema(schema);
702
703        // 1. $ref and $defs are preserved (Requirement 4.1)
704        assert!(result.get("$defs").is_some(), "$defs should be preserved");
705        assert_eq!(
706            result["properties"]["home"]["$ref"], "#/$defs/Address",
707            "$ref should be preserved"
708        );
709
710        // 2. anyOf is preserved (Requirement 4.2)
711        assert!(result["properties"]["status"].get("anyOf").is_some(), "anyOf should be preserved");
712        let any_of = result["properties"]["status"]["anyOf"].as_array().unwrap();
713        assert_eq!(any_of.len(), 2, "anyOf should retain both sub-schemas");
714        assert_eq!(any_of[0]["type"], "string");
715        assert_eq!(any_of[1]["type"], "null");
716
717        // 3. additionalProperties: false added to root object (Requirement 4.3)
718        assert_eq!(
719            result["additionalProperties"], false,
720            "root object should have additionalProperties: false"
721        );
722
723        // 4. additionalProperties: false added recursively to nested object schemas (Requirement 4.4)
724        assert_eq!(
725            result["$defs"]["Address"]["additionalProperties"], false,
726            "nested object in $defs should have additionalProperties: false"
727        );
728
729        // 5. Type arrays are preserved (Requirement 4.5)
730        assert_eq!(
731            result["properties"]["name"]["type"],
732            json!(["string", "null"]),
733            "type arrays should be preserved"
734        );
735    }
736
737    /// Verifies OpenAI strict mode with `oneOf` keyword preservation.
738    ///
739    /// **Validates: Requirements 4.2**
740    #[test]
741    fn test_strict_preserves_one_of_with_object_schemas() {
742        let adapter = OpenAiStrictSchemaAdapter;
743        let schema = json!({
744            "type": "object",
745            "properties": {
746                "payload": {
747                    "oneOf": [
748                        {
749                            "type": "object",
750                            "properties": {
751                                "kind": { "type": "string" }
752                            }
753                        },
754                        { "type": "null" }
755                    ]
756                }
757            }
758        });
759
760        let result = adapter.normalize_schema(schema);
761
762        // oneOf is preserved
763        assert!(
764            result["properties"]["payload"].get("oneOf").is_some(),
765            "oneOf should be preserved"
766        );
767        let one_of = result["properties"]["payload"]["oneOf"].as_array().unwrap();
768        assert_eq!(one_of.len(), 2);
769
770        // additionalProperties: false added to object sub-schemas within oneOf
771        assert_eq!(
772            one_of[0]["additionalProperties"], false,
773            "object sub-schema in oneOf should have additionalProperties: false"
774        );
775
776        // Root also has additionalProperties: false
777        assert_eq!(result["additionalProperties"], false);
778    }
779
780    #[test]
781    fn test_strict_all_transforms_combined() {
782        let adapter = OpenAiStrictSchemaAdapter;
783        let schema = json!({
784            "$schema": "http://json-schema.org/draft-07/schema#",
785            "properties": {
786                "status": { "type": "string", "const": "active" },
787                "host": { "type": "string", "format": "hostname" },
788                "nested": {
789                    "type": "object",
790                    "properties": {
791                        "value": { "type": "number", "format": "float" }
792                    }
793                }
794            },
795            "if": { "properties": { "status": { "const": "active" } } },
796            "then": { "required": ["host"] }
797        });
798        let result = adapter.normalize_schema(schema);
799
800        // $schema removed
801        assert!(result.get("$schema").is_none());
802        // conditional keywords removed
803        assert!(result.get("if").is_none());
804        assert!(result.get("then").is_none());
805        // implicit type added
806        assert_eq!(result["type"], "object");
807        // const converted to enum
808        assert!(result["properties"]["status"].get("const").is_none());
809        assert_eq!(result["properties"]["status"]["enum"], json!(["active"]));
810        // unsupported format stripped
811        assert!(result["properties"]["host"].get("format").is_none());
812        // allowed format preserved
813        assert_eq!(result["properties"]["nested"]["properties"]["value"]["format"], "float");
814        // additionalProperties: false set recursively
815        assert_eq!(result["additionalProperties"], false);
816        assert_eq!(result["properties"]["nested"]["additionalProperties"], false);
817    }
818
819    /// The shape `#[tool]` declares: objects closed with `additionalProperties: false`,
820    /// a nested type behind a `$ref` with its own description beside it, and bounds.
821    fn closed_tool_schema() -> Value {
822        json!({
823            "type": "object",
824            "properties": {
825                "room": { "type": "string", "minLength": 2, "maxLength": 4, "pattern": "^[A-Z][0-9]$" },
826                "count": { "type": "integer", "format": "uint32", "minimum": 1, "maximum": 10 },
827                "confirm_to": { "$ref": "#/$defs/Address", "description": "Where to post it." }
828            },
829            "required": ["room", "count", "confirm_to"],
830            "additionalProperties": false,
831            "$defs": {
832                "Address": {
833                    "type": "object",
834                    "description": "A postal address.",
835                    "properties": { "city": { "type": "string" } },
836                    "required": ["city"],
837                    "additionalProperties": false
838                }
839            }
840        })
841    }
842
843    #[test]
844    fn closed_tool_schema_passes_both_adapters_intact() {
845        let schema = closed_tool_schema();
846        let mut expected = schema.clone();
847        // `uint32` is not an OpenAI format; everything else survives as declared.
848        expected["properties"]["count"].as_object_mut().unwrap().remove("format");
849
850        assert_eq!(OpenAiSchemaAdapter.normalize_schema(schema.clone()), expected);
851        assert_eq!(OpenAiStrictSchemaAdapter.normalize_schema(schema), expected);
852    }
853}