adk-model 3.0.0

LLM model integrations for Rust Agent Development Kit (ADK-Rust) (Gemini, OpenAI, Claude, DeepSeek, etc.)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
//! Schema adapter for Anthropic's Claude models.
//!
//! Anthropic has the most permissive JSON Schema support among major LLM providers.
//! The [`AnthropicSchemaAdapter`] applies only minimal transforms:
//!
//! 1. Strip `$schema` keyword (meta-keyword no provider supports)
//! 2. Strip conditional keywords (`if`/`then`/`else`)
//! 3. Add implicit `"type": "object"` when `properties` exists without a `type` field
//!
//! Everything else passes through unchanged: `$ref`, `$defs`, `anyOf`, `oneOf`,
//! `allOf`, `additionalProperties`, type arrays, `const`, and all `format` values.
//!
//! # Example
//!
//! ```rust
//! use adk_model::anthropic::AnthropicSchemaAdapter;
//! use adk_core::SchemaAdapter;
//! use serde_json::json;
//!
//! let adapter = AnthropicSchemaAdapter;
//! let schema = json!({
//!     "$schema": "http://json-schema.org/draft-07/schema#",
//!     "type": "object",
//!     "properties": {
//!         "name": { "type": "string", "const": "fixed" }
//!     },
//!     "$ref": "#/$defs/Foo",
//!     "$defs": { "Foo": { "type": "string" } },
//!     "anyOf": [{ "type": "string" }, { "type": "number" }],
//!     "additionalProperties": false
//! });
//!
//! let normalized = adapter.normalize_schema(schema);
//! // $schema removed
//! assert!(normalized.get("$schema").is_none());
//! // const preserved (Anthropic supports it natively)
//! assert_eq!(normalized["properties"]["name"]["const"], "fixed");
//! // $ref, $defs, anyOf, additionalProperties all preserved
//! assert!(normalized.get("$ref").is_some());
//! assert!(normalized.get("$defs").is_some());
//! assert!(normalized.get("anyOf").is_some());
//! assert!(normalized.get("additionalProperties").is_some());
//! ```

use std::borrow::Cow;

use adk_core::{SchemaAdapter, schema_utils};
use serde_json::{Map, Value};

/// Schema adapter for Anthropic's Claude models (near pass-through).
///
/// Anthropic's function-calling API accepts most JSON Schema features natively.
/// This adapter only strips the meta-keywords that no provider supports and adds
/// implicit object types where needed.
///
/// ## Preserved Features
///
/// - `$ref` and `$defs` (reference resolution not needed)
/// - `anyOf`, `oneOf`, `allOf` (combiners supported)
/// - `additionalProperties` (supported as-is)
/// - Type arrays (e.g., `["string", "null"]`)
/// - `const` keyword (native support)
/// - All `format` values (no stripping)
///
/// ## Transforms Applied
///
/// 1. `strip_schema_keyword` — removes `$schema` meta-keyword
/// 2. `strip_conditional_keywords` — removes `if`/`then`/`else`
/// 3. `add_implicit_object_type` — adds `"type": "object"` when `properties` exists
///
/// ## Tool Name Normalization
///
/// Truncates tool names exceeding 64 characters at the nearest valid UTF-8
/// character boundary, preserving the prefix.
#[derive(Debug)]
pub struct AnthropicSchemaAdapter;

impl SchemaAdapter for AnthropicSchemaAdapter {
    fn normalize_schema(&self, mut schema: Value) -> Value {
        schema_utils::strip_schema_keyword(&mut schema);
        schema_utils::strip_conditional_keywords(&mut schema);
        schema_utils::add_implicit_object_type(&mut schema);
        schema
    }

    fn normalize_tool_name<'a>(&self, name: &'a str) -> Cow<'a, str> {
        if name.len() <= 64 {
            Cow::Borrowed(name)
        } else {
            // Find the largest valid UTF-8 boundary at or before 64 bytes.
            let mut end = 64;
            while end > 0 && !name.is_char_boundary(end) {
                end -= 1;
            }
            Cow::Owned(name[..end].to_string())
        }
    }
}

/// Nests root `anyOf`, `oneOf` and `allOf` of a non-strict tool under `not`/`not`.
///
/// The Messages API rejects these combiners at the root of `input_schema`; double
/// negation keeps their constraints and the visible root fields. Anthropic documents
/// neither root `not` nor `not` for strict tools, so [`convert_tools`] leaves strict
/// declarations unchanged. Schemas with unevaluated annotations or references whose
/// targets could move are also left unchanged rather than silently weakened.
///
/// [`convert_tools`]: super::convert::convert_tools
pub(super) fn nest_composition(schema: &mut Value) {
    if !can_nest(schema) {
        return;
    }
    let Some(fields) = schema.as_object_mut() else {
        return;
    };
    let mut composition = Map::new();
    for keyword in ["oneOf", "anyOf", "allOf"] {
        if let Some(value) = fields.remove(keyword) {
            composition.insert(keyword.into(), value);
        }
    }
    if !composition.is_empty() {
        if let Some(value) = fields.remove("not") {
            composition.insert("not".into(), value);
        }
        fields.insert("not".into(), serde_json::json!({"not": composition}));
    }
}

fn can_nest(value: &Value) -> bool {
    match value {
        Value::Object(fields) => {
            // Negation does not forward evaluation annotations. Definition
            // pointers stay at the root; other reference targets may move.
            !fields.contains_key("unevaluatedProperties")
                && !fields.contains_key("unevaluatedItems")
                && ["$ref", "$dynamicRef", "$recursiveRef"].into_iter().all(|keyword| {
                    fields.get(keyword).and_then(Value::as_str).is_none_or(|reference| {
                        reference.starts_with("#/$defs/") || reference.starts_with("#/definitions/")
                    })
                })
                && fields.values().all(can_nest)
        }
        Value::Array(items) => items.iter().all(can_nest),
        _ => true,
    }
}

/// Keywords Anthropic's structured outputs reject: numeric, length and count bounds.
const UNSUPPORTED_OUTPUT_KEYWORDS: [&str; 10] = [
    "minimum",
    "maximum",
    "exclusiveMinimum",
    "exclusiveMaximum",
    "multipleOf",
    "minLength",
    "maxLength",
    "maxItems",
    "minProperties",
    "maxProperties",
];

/// `schema` as Anthropic's structured outputs (`output_config.format`) take it, or `None`
/// when it cannot be expressed there.
///
/// Every object is closed with `additionalProperties: false` unless it sets the key itself;
/// bounds the API rejects are dropped, so the reply is checked against them by the caller,
/// as Anthropic's SDKs do; a `minItems` above 1 is dropped likewise. An object that leaves
/// `additionalProperties` open, a map type, cannot be constrained, so the schema is not sent
/// and the prompt alone asks for the format.
pub(super) fn structured_output_schema(schema: &Value) -> Option<Value> {
    fn close(node: &mut Value) -> bool {
        match node {
            Value::Array(items) => items.iter_mut().all(close),
            Value::Object(fields) => {
                for keyword in UNSUPPORTED_OUTPUT_KEYWORDS {
                    fields.remove(keyword);
                }
                if fields.get("minItems").and_then(Value::as_u64).is_some_and(|min| min > 1) {
                    fields.remove("minItems");
                }
                let is_object = fields.contains_key("properties")
                    || fields.get("type").and_then(Value::as_str) == Some("object");
                if is_object {
                    match fields.get("additionalProperties") {
                        None => {
                            fields.insert("additionalProperties".to_string(), Value::Bool(false));
                        }
                        Some(Value::Bool(false)) => {}
                        Some(_) => return false,
                    }
                }
                for (key, value) in fields.iter_mut() {
                    let ok = match key.as_str() {
                        "properties" | "$defs" | "definitions" | "patternProperties" => {
                            value.as_object_mut().is_none_or(|map| map.values_mut().all(close))
                        }
                        "items" | "prefixItems" | "anyOf" | "allOf" | "oneOf" | "not" => {
                            close(value)
                        }
                        _ => true,
                    };
                    if !ok {
                        return false;
                    }
                }
                true
            }
            _ => true,
        }
    }
    let mut schema = schema.clone();
    schema_utils::strip_schema_keyword(&mut schema);
    schema_utils::strip_conditional_keywords(&mut schema);
    schema_utils::add_implicit_object_type(&mut schema);
    close(&mut schema).then_some(schema)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn nests_root_composition() {
        let adapter = AnthropicSchemaAdapter;
        for keyword in ["oneOf", "anyOf", "allOf"] {
            let mut schema = json!({
                "type":"object",
                "properties":{"action":{"enum":["read","write"]},"value":{"type":"string"}},
                "required":["action"],
                "additionalProperties":false,
                "not":{"required":["blocked"]}
            });
            schema[keyword] = json!([
                {"type":"object","properties":{"action":{"const":"read"}},"required":["action"]},
                {"type":"object","properties":{"action":{"const":"write"}},"required":["action","value"]}
            ]);
            let mut normalized = adapter.normalize_schema(schema.clone());
            nest_composition(&mut normalized);
            assert!(normalized.get(keyword).is_none());
            assert_eq!(normalized["properties"], schema["properties"]);
            assert_eq!(normalized["required"], schema["required"]);
            assert_eq!(normalized["additionalProperties"], false);
            assert_eq!(normalized["not"]["not"][keyword], schema[keyword]);
            assert_eq!(normalized["not"]["not"]["not"], schema["not"]);
            let mut again = normalized.clone();
            nest_composition(&mut again);
            assert_eq!(again, normalized);
        }
    }

    #[test]
    fn retains_location_sensitive_composition() {
        let adapter = AnthropicSchemaAdapter;
        for constraint in [
            json!({"unevaluatedProperties":false}),
            json!({"unevaluatedItems":false}),
            json!({"$ref":"#/oneOf/0"}),
            json!({"$dynamicRef":"#node"}),
        ] {
            let schema = json!({"type":"object","oneOf":[constraint]});
            let mut nested = adapter.normalize_schema(schema.clone());
            nest_composition(&mut nested);
            assert_eq!(nested, schema);
        }
    }

    #[test]
    fn test_strips_schema_keyword() {
        let adapter = AnthropicSchemaAdapter;
        let schema = json!({
            "$schema": "http://json-schema.org/draft-07/schema#",
            "type": "object",
            "properties": { "name": { "type": "string" } }
        });
        let result = adapter.normalize_schema(schema);
        assert!(result.get("$schema").is_none());
        assert_eq!(result["type"], "object");
    }

    #[test]
    fn test_strips_conditional_keywords() {
        let adapter = AnthropicSchemaAdapter;
        let schema = json!({
            "type": "object",
            "if": { "properties": { "kind": { "const": "a" } } },
            "then": { "required": ["extra"] },
            "else": { "required": [] }
        });
        let result = adapter.normalize_schema(schema);
        assert!(result.get("if").is_none());
        assert!(result.get("then").is_none());
        assert!(result.get("else").is_none());
    }

    #[test]
    fn test_adds_implicit_object_type() {
        let adapter = AnthropicSchemaAdapter;
        let schema = json!({
            "properties": {
                "name": { "type": "string" }
            }
        });
        let result = adapter.normalize_schema(schema);
        assert_eq!(result["type"], "object");
    }

    #[test]
    fn test_preserves_ref() {
        let adapter = AnthropicSchemaAdapter;
        let schema = json!({
            "type": "object",
            "$ref": "#/$defs/Address"
        });
        let result = adapter.normalize_schema(schema);
        assert_eq!(result["$ref"], "#/$defs/Address");
    }

    #[test]
    fn test_preserves_defs() {
        let adapter = AnthropicSchemaAdapter;
        let schema = json!({
            "type": "object",
            "$defs": {
                "Address": {
                    "type": "object",
                    "properties": {
                        "street": { "type": "string" }
                    }
                }
            }
        });
        let result = adapter.normalize_schema(schema);
        assert!(result.get("$defs").is_some());
        assert_eq!(result["$defs"]["Address"]["type"], "object");
    }

    #[test]
    fn test_preserves_any_of() {
        let adapter = AnthropicSchemaAdapter;
        let schema = json!({
            "anyOf": [
                { "type": "string" },
                { "type": "number" }
            ]
        });
        let result = adapter.normalize_schema(schema);
        assert!(result.get("anyOf").is_some());
        assert_eq!(result["anyOf"].as_array().unwrap().len(), 2);
    }

    #[test]
    fn test_preserves_one_of() {
        let adapter = AnthropicSchemaAdapter;
        let schema = json!({
            "oneOf": [
                { "type": "boolean" },
                { "type": "null" }
            ]
        });
        let result = adapter.normalize_schema(schema);
        assert!(result.get("oneOf").is_some());
        assert_eq!(result["oneOf"].as_array().unwrap().len(), 2);
    }

    #[test]
    fn test_preserves_all_of() {
        let adapter = AnthropicSchemaAdapter;
        let schema = json!({
            "allOf": [
                { "type": "object", "properties": { "a": { "type": "string" } } },
                { "required": ["a"] }
            ]
        });
        let result = adapter.normalize_schema(schema);
        assert!(result.get("allOf").is_some());
        assert_eq!(result["allOf"].as_array().unwrap().len(), 2);
    }

    #[test]
    fn test_preserves_additional_properties() {
        let adapter = AnthropicSchemaAdapter;
        let schema = json!({
            "type": "object",
            "properties": { "name": { "type": "string" } },
            "additionalProperties": false
        });
        let result = adapter.normalize_schema(schema);
        assert_eq!(result["additionalProperties"], false);
    }

    #[test]
    fn test_preserves_type_arrays() {
        let adapter = AnthropicSchemaAdapter;
        let schema = json!({
            "type": ["string", "null"]
        });
        let result = adapter.normalize_schema(schema);
        assert_eq!(result["type"], json!(["string", "null"]));
    }

    #[test]
    fn test_preserves_const() {
        let adapter = AnthropicSchemaAdapter;
        let schema = json!({
            "type": "string",
            "const": "fixed_value"
        });
        let result = adapter.normalize_schema(schema);
        assert_eq!(result["const"], "fixed_value");
    }

    #[test]
    fn test_preserves_all_format_values() {
        let adapter = AnthropicSchemaAdapter;
        let formats = [
            "date-time",
            "date",
            "time",
            "email",
            "uri",
            "uuid",
            "hostname",
            "ipv4",
            "ipv6",
            "uri-reference",
            "json-pointer",
            "regex",
            "iri",
            "iri-reference",
            "uri-template",
            "int32",
            "int64",
            "float",
            "double",
        ];
        for format in formats {
            let schema = json!({ "type": "string", "format": format });
            let result = adapter.normalize_schema(schema);
            assert_eq!(
                result["format"], format,
                "format '{format}' should be preserved by Anthropic adapter"
            );
        }
    }

    #[test]
    fn test_normalize_tool_name_short() {
        let adapter = AnthropicSchemaAdapter;
        let name = "get_weather";
        assert_eq!(adapter.normalize_tool_name(name), Cow::Borrowed("get_weather"));
    }

    #[test]
    fn test_normalize_tool_name_exactly_64() {
        let adapter = AnthropicSchemaAdapter;
        let name = "a".repeat(64);
        assert_eq!(adapter.normalize_tool_name(&name), Cow::Borrowed(name.as_str()));
    }

    #[test]
    fn test_normalize_tool_name_truncates_at_64() {
        let adapter = AnthropicSchemaAdapter;
        let name = "a".repeat(100);
        let result = adapter.normalize_tool_name(&name);
        assert_eq!(result.len(), 64);
        assert_eq!(result.as_ref(), "a".repeat(64).as_str());
    }

    #[test]
    fn test_normalize_tool_name_multibyte_boundary() {
        let adapter = AnthropicSchemaAdapter;
        // Each '🦀' is 4 bytes. 16 crabs = 64 bytes exactly.
        let name = "🦀".repeat(16);
        assert_eq!(name.len(), 64);
        assert_eq!(adapter.normalize_tool_name(&name), Cow::Borrowed(name.as_str()));

        // 17 crabs = 68 bytes, should truncate to 16 crabs (64 bytes)
        let long_name = "🦀".repeat(17);
        let result = adapter.normalize_tool_name(&long_name);
        assert_eq!(result.len(), 64);
        assert_eq!(result.as_ref(), "🦀".repeat(16).as_str());
    }

    #[test]
    fn test_normalize_tool_name_truncates_at_char_boundary() {
        let adapter = AnthropicSchemaAdapter;
        // 'é' is 2 bytes. 32 of them = 64 bytes exactly.
        let name = "é".repeat(32);
        assert_eq!(name.len(), 64);
        assert_eq!(adapter.normalize_tool_name(&name), Cow::Borrowed(name.as_str()));

        // 33 'é' = 66 bytes, should truncate to 32 'é' (64 bytes)
        let long_name = "é".repeat(33);
        let result = adapter.normalize_tool_name(&long_name);
        assert_eq!(result.len(), 64);
        assert_eq!(result.as_ref(), "é".repeat(32).as_str());
    }

    #[test]
    fn test_empty_schema() {
        let adapter = AnthropicSchemaAdapter;
        assert_eq!(adapter.empty_schema(), json!({"type": "object", "properties": {}}));
    }

    #[test]
    fn test_idempotent() {
        let adapter = AnthropicSchemaAdapter;
        let schema = json!({
            "$schema": "http://json-schema.org/draft-07/schema#",
            "properties": {
                "name": { "type": "string" }
            },
            "if": { "const": true },
            "then": { "required": ["name"] },
            "anyOf": [{ "type": "string" }],
            "const": "test",
            "additionalProperties": false
        });
        let first = adapter.normalize_schema(schema);
        let second = adapter.normalize_schema(first.clone());
        assert_eq!(first, second);
    }

    #[test]
    fn test_nested_conditional_keywords_stripped() {
        let adapter = AnthropicSchemaAdapter;
        let schema = json!({
            "type": "object",
            "properties": {
                "nested": {
                    "type": "object",
                    "properties": {
                        "deep": { "type": "string" }
                    },
                    "if": { "properties": { "deep": { "const": "x" } } },
                    "then": { "required": ["deep"] }
                }
            }
        });
        let result = adapter.normalize_schema(schema);
        let nested = &result["properties"]["nested"];
        assert!(nested.get("if").is_none());
        assert!(nested.get("then").is_none());
    }

    #[test]
    fn test_combined_transforms() {
        let adapter = AnthropicSchemaAdapter;
        let schema = json!({
            "$schema": "http://json-schema.org/draft-07/schema#",
            "properties": {
                "status": { "type": "string", "const": "active" },
                "host": { "type": "string", "format": "hostname" }
            },
            "$ref": "#/$defs/Base",
            "$defs": { "Base": { "type": "object" } },
            "anyOf": [{ "type": "string" }],
            "oneOf": [{ "type": "number" }],
            "allOf": [{ "required": ["status"] }],
            "additionalProperties": { "type": "string" },
            "if": { "properties": { "status": { "const": "active" } } },
            "then": { "required": ["host"] }
        });
        let result = adapter.normalize_schema(schema);

        // $schema removed
        assert!(result.get("$schema").is_none());
        // conditional keywords removed
        assert!(result.get("if").is_none());
        assert!(result.get("then").is_none());
        // implicit type added
        assert_eq!(result["type"], "object");
        // const preserved
        assert_eq!(result["properties"]["status"]["const"], "active");
        // format preserved (even non-standard ones)
        assert_eq!(result["properties"]["host"]["format"], "hostname");
        // $ref, $defs, combiners, additionalProperties all preserved
        assert_eq!(result["$ref"], "#/$defs/Base");
        assert!(result.get("$defs").is_some());
        assert!(result.get("anyOf").is_some());
        assert!(result.get("oneOf").is_some());
        assert!(result.get("allOf").is_some());
        assert!(result.get("additionalProperties").is_some());
    }

    /// Comprehensive pass-through verification test.
    ///
    /// Verifies that `AnthropicSchemaAdapter` preserves all schema features
    /// and only strips `$schema` and conditional keywords (`if`/`then`/`else`).
    ///
    /// **Validates: Requirements 6.4**
    #[test]
    fn test_passthrough_preserves_all_schema_features() {
        let adapter = AnthropicSchemaAdapter;

        let schema = json!({
            "$schema": "http://json-schema.org/draft-07/schema#",
            "type": "object",
            "$defs": { "Foo": { "type": "string" } },
            "properties": {
                "ref_field": { "$ref": "#/$defs/Foo" },
                "nullable": { "type": ["string", "null"] },
                "status": { "const": "active" },
                "format_field": { "type": "string", "format": "hostname" }
            },
            "anyOf": [{"type": "object"}, {"type": "null"}],
            "additionalProperties": true,
            "if": { "properties": { "x": { "type": "number" } } },
            "then": { "required": ["x"] }
        });

        let result = adapter.normalize_schema(schema);

        // 1. Preserves $ref and $defs
        assert_eq!(
            result["properties"]["ref_field"]["$ref"], "#/$defs/Foo",
            "$ref must be preserved"
        );
        assert_eq!(result["$defs"]["Foo"]["type"], "string", "$defs must be preserved");

        // 2. Preserves additionalProperties
        assert_eq!(result["additionalProperties"], true, "additionalProperties must be preserved");

        // 3. Preserves type arrays
        assert_eq!(
            result["properties"]["nullable"]["type"],
            json!(["string", "null"]),
            "type arrays must be preserved"
        );

        // 4. Preserves const keywords
        assert_eq!(
            result["properties"]["status"]["const"], "active",
            "const keyword must be preserved"
        );

        // 5. Preserves all format values (including non-standard ones)
        assert_eq!(
            result["properties"]["format_field"]["format"], "hostname",
            "all format values must be preserved"
        );

        // 6. Preserves anyOf combiner
        let any_of = result["anyOf"].as_array().expect("anyOf must be preserved");
        assert_eq!(any_of.len(), 2);
        assert_eq!(any_of[0]["type"], "object");
        assert_eq!(any_of[1]["type"], "null");

        // 7. Only strips $schema and conditional keywords
        assert!(result.get("$schema").is_none(), "$schema must be stripped");
        assert!(result.get("if").is_none(), "if must be stripped");
        assert!(result.get("then").is_none(), "then must be stripped");
        assert!(
            result.get("else").is_none(),
            "else must be stripped (not present in input but verify absence)"
        );

        // Verify type is preserved
        assert_eq!(result["type"], "object");
    }

    /// Verifies that `else` conditional keyword is also stripped when present.
    ///
    /// **Validates: Requirements 6.3**
    #[test]
    fn test_passthrough_strips_else_keyword() {
        let adapter = AnthropicSchemaAdapter;

        let schema = json!({
            "type": "object",
            "properties": {
                "x": { "type": "number" }
            },
            "if": { "properties": { "x": { "minimum": 0 } } },
            "then": { "required": ["x"] },
            "else": { "properties": { "fallback": { "type": "string" } } }
        });

        let result = adapter.normalize_schema(schema);

        assert!(result.get("if").is_none(), "if must be stripped");
        assert!(result.get("then").is_none(), "then must be stripped");
        assert!(result.get("else").is_none(), "else must be stripped");
        // Properties and type preserved
        assert_eq!(result["type"], "object");
        assert!(result.get("properties").is_some());
    }

    /// Verifies that oneOf and allOf combiners are also preserved.
    ///
    /// **Validates: Requirements 6.4**
    #[test]
    fn test_passthrough_preserves_one_of_and_all_of() {
        let adapter = AnthropicSchemaAdapter;

        let schema = json!({
            "type": "object",
            "oneOf": [
                { "properties": { "a": { "type": "string" } } },
                { "properties": { "b": { "type": "number" } } }
            ],
            "allOf": [
                { "required": ["id"] },
                { "properties": { "id": { "type": "string" } } }
            ]
        });

        let result = adapter.normalize_schema(schema);

        let one_of = result["oneOf"].as_array().expect("oneOf must be preserved");
        assert_eq!(one_of.len(), 2);

        let all_of = result["allOf"].as_array().expect("allOf must be preserved");
        assert_eq!(all_of.len(), 2);
    }

    #[test]
    fn a_response_schema_is_closed_and_unbounded_for_structured_outputs() {
        let schema = json!({
            "$schema": "http://json-schema.org/draft-07/schema#",
            "type": "object",
            "properties": {
                "score": {"type": "number", "minimum": 0.0, "maximum": 1.0},
                "tags": {"type": "array", "items": {"type": "string", "maxLength": 9}, "minItems": 2},
                "owner": {"properties": {"name": {"type": "string"}}}
            },
            "required": ["score"]
        });
        assert_eq!(
            structured_output_schema(&schema).unwrap(),
            json!({
                "type": "object",
                "properties": {
                    "score": {"type": "number"},
                    "tags": {"type": "array", "items": {"type": "string"}},
                    "owner": {
                        "type": "object",
                        "properties": {"name": {"type": "string"}},
                        "additionalProperties": false
                    }
                },
                "required": ["score"],
                "additionalProperties": false
            })
        );
    }

    #[test]
    fn an_open_map_is_not_sent_as_structured_output() {
        let map = json!({"type": "object", "additionalProperties": {"type": "string"}});
        assert_eq!(structured_output_schema(&map), None);
        let nested = json!({"type": "object", "properties": {"labels": map}});
        assert_eq!(structured_output_schema(&nested), None);
    }
}