ante-llm 0.4.2

Streaming LLM client for Anthropic, OpenAI, Gemini and Chat Completions servers, from the Ante coding agent
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
// Copyright 2026 Antigma Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! External tool-schema portability.
//!
//! Every provider Ante speaks to accepts a slightly different JSON Schema
//! dialect, and Gemini's proto-based parser is the strictest: unknown keys are
//! a hard 400 (`Unknown name "exclusiveMinimum" ...: Cannot find field`), not
//! ignored. [`normalize_tool_schema`] rewrites externally-supplied schemas
//! (MCP servers) into the portable subset at ingestion. A schema already
//! written in that subset passes through unchanged, so a caller can test its
//! own schemas against the normalizer.

use serde_json::{Map, Value};

/// Recursion / `$ref`-inlining cap. Real tool schemas are a handful of levels
/// deep; the cap exists to break `$ref` cycles, not to bound honest schemas.
const MAX_DEPTH: usize = 24;

/// Rewrite an externally-supplied JSON Schema (e.g. an MCP server's tool
/// `inputSchema`) into the portable subset every provider accepts.
///
/// An allowlist: only `type`, `description`, `title`, `properties`,
/// `required`, `items`, `enum`, `anyOf`, `nullable`, `format`, `default`,
/// `example`, and the numeric `min*`/`max*` bounds survive. `pattern` is
/// excluded: regex dialects differ per provider, and an unsupported construct
/// such as lookaround rejects the entire tool set before the model runs.
///
/// Folded rather than dropped:
///
/// - `exclusiveMinimum`/`exclusiveMaximum` (numeric form) → the closed bound
/// - `const` → single-value `enum`; `oneOf` → `anyOf`; single-branch
///   `allOf`/`anyOf` inlined
/// - `type: ["X","null"]`, `{"type":"null"}` union branches, and `null` enum
///   entries → `nullable: true`; other `type` arrays → `anyOf`, one branch
///   per type
/// - local `$ref`s (`#/$defs/...`) inlined, cycle-capped; `examples` →
///   `example`
/// - `enum`/`const` values other than non-empty strings (booleans, numbers,
///   `""`) → dropped from `enum` and listed in `description`, keeping the
///   inferred `type`
///
/// Guarantees: the top level is `{"type":"object", ...}` (MCP requires it; a
/// degenerate input becomes an unconstrained object); every node carries a
/// `type` unless an `anyOf` union stands in for it; `required` only names
/// declared properties; empty `properties`/`required`/`enum` are omitted.
/// `items` appears on every array (an unconstrained object when the source
/// gave none) and nowhere else, and `properties`/`required` only on objects;
/// in a `type` union they sit on the matching branch. The result is a
/// fixpoint: normalizing twice equals normalizing once.
pub fn normalize_tool_schema(schema: &Value) -> Value {
    let normalized = normalize_node(schema, schema, 0);
    if normalized.get("type").and_then(Value::as_str) == Some("object") {
        return normalized;
    }
    // Not an object (boolean schema, scalar type, bare union): degrade to an
    // unconstrained object, keeping the description.
    let mut map = Map::new();
    map.insert("type".to_string(), Value::String("object".to_string()));
    if let Some(description) = normalized.get("description") {
        map.insert("description".to_string(), description.clone());
    }
    Value::Object(map)
}

fn normalize_node(node: &Value, root: &Value, depth: usize) -> Value {
    if depth > MAX_DEPTH {
        return unconstrained_object();
    }
    // Boolean schemas (`true` / `false`) carry no constraints providers can
    // express; treat them as an unconstrained object.
    let Value::Object(node) = node else {
        return unconstrained_object();
    };
    let mut node = node.clone();
    collapse_indirections(&mut node, root);
    fold_keywords(&mut node);
    build_portable(&node, root, depth)
}

/// Collapse `$ref`, `allOf`, `oneOf`, and null-branch `anyOf` wrappers into
/// the node itself so the allowlist copy sees plain keys. Bounded, not
/// exhaustive: pathological nesting leaves keys behind for the allowlist to
/// drop rather than looping.
fn collapse_indirections(node: &mut Map<String, Value>, root: &Value) {
    for _ in 0..MAX_DEPTH {
        // Local `$ref` (`#/$defs/...`, the pydantic shape): inline the
        // target, explicit keys on the ref site winning. Unresolvable or
        // external refs are dropped and the remaining keys stand on their
        // own.
        if let Some(reference) = node.remove("$ref") {
            let target = reference
                .as_str()
                .and_then(|r| r.strip_prefix('#'))
                .and_then(|pointer| root.pointer(pointer))
                .and_then(Value::as_object);
            if let Some(target) = target {
                for (key, value) in target {
                    node.entry(key.clone()).or_insert_with(|| value.clone());
                }
            }
            continue;
        }
        // `allOf`: shallow-merge the branches, first occurrence of a key
        // winning. Branch-level `$ref`s land on the node and resolve on the
        // next pass.
        if let Some(all_of) = node.remove("allOf") {
            if let Value::Array(branches) = all_of {
                for branch in branches {
                    if let Value::Object(branch) = branch {
                        for (key, value) in branch {
                            node.entry(key).or_insert(value);
                        }
                    }
                }
            }
            continue;
        }
        // `oneOf` → `anyOf`: exclusivity doesn't matter for argument
        // generation, and Gemini's parser only defines `anyOf`.
        if let Some(one_of) = node.remove("oneOf") {
            if let Value::Array(mut extra) = one_of {
                if let Some(Value::Array(mut any_of)) = node.remove("anyOf") {
                    any_of.append(&mut extra);
                    extra = any_of;
                }
                node.insert("anyOf".to_string(), Value::Array(extra));
            }
            continue;
        }
        // `anyOf`: fold `{"type":"null"}` branches (pydantic `Optional`)
        // into `nullable`, and inline the branch when only one remains.
        if let Some(any_of) = node.remove("anyOf") {
            let Value::Array(mut branches) = any_of else { continue };
            let with_null = branches.len();
            branches.retain(|branch| !is_null_type(branch));
            if branches.len() != with_null {
                node.insert("nullable".to_string(), Value::Bool(true));
            }
            match branches.len() {
                0 => {}
                1 => {
                    if let Value::Object(branch) = branches.remove(0) {
                        for (key, value) in branch {
                            node.entry(key).or_insert(value);
                        }
                    }
                }
                _ => {
                    let stable = branches.len() == with_null;
                    node.insert("anyOf".to_string(), Value::Array(branches));
                    if stable {
                        break;
                    }
                }
            }
            continue;
        }
        break;
    }
}

/// Meaning-preserving keyword folds, applied after indirections collapse.
fn fold_keywords(node: &mut Map<String, Value>) {
    // `const` → single-value `enum`.
    if let Some(value) = node.remove("const") {
        node.entry("enum").or_insert_with(|| Value::Array(vec![value]));
    }
    // Draft-2020 numeric exclusive bounds fold into the closed bound — the
    // off-by-epsilon is irrelevant for argument guidance. The draft-4
    // boolean form just drops (its paired `minimum`/`maximum` already
    // carries the bound).
    if let Some(bound) = node.remove("exclusiveMinimum")
        && bound.is_number()
    {
        node.entry("minimum").or_insert(bound);
    }
    if let Some(bound) = node.remove("exclusiveMaximum")
        && bound.is_number()
    {
        node.entry("maximum").or_insert(bound);
    }
    // `examples` → single `example`, matching the openapi3 preset.
    if let Some(Value::Array(examples)) = node.remove("examples")
        && let Some(first) = examples.into_iter().next()
    {
        node.entry("example").or_insert(first);
    }
}

/// Copy the portable keys into a fresh map, recursing into subschemas and
/// dropping everything else.
fn build_portable(node: &Map<String, Value>, root: &Value, depth: usize) -> Value {
    let mut out = Map::new();
    let mut nullable = node.get("nullable").and_then(Value::as_bool).unwrap_or(false);

    // `type`: single string kept; `["X","null"]` folds to nullable; other
    // arrays become an `anyOf` union below.
    let mut types: Vec<String> = match node.get("type") {
        Some(Value::String(t)) => vec![t.clone()],
        Some(Value::Array(list)) => {
            list.iter().filter_map(Value::as_str).map(str::to_string).collect()
        }
        _ => Vec::new(),
    };
    if types.iter().any(|t| t == "null") {
        types.retain(|t| t != "null");
        nullable = true;
    }

    let mut any_of: Vec<Value> = match node.get("anyOf") {
        Some(Value::Array(branches)) => {
            branches.iter().map(|b| normalize_node(b, root, depth + 1)).collect()
        }
        _ => Vec::new(),
    };

    // `enum`: null entries fold into `nullable` (several providers reject
    // JSON null inside enum arrays).
    let enum_values: Vec<Value> = match node.get("enum") {
        Some(Value::Array(values)) => {
            let non_null: Vec<Value> = values.iter().filter(|v| !v.is_null()).cloned().collect();
            if non_null.len() != values.len() {
                nullable = true;
            }
            non_null
        }
        _ => Vec::new(),
    };

    let properties: Map<String, Value> = match node.get("properties") {
        Some(Value::Object(props)) => props
            .iter()
            .map(|(name, schema)| (name.clone(), normalize_node(schema, root, depth + 1)))
            .collect(),
        _ => Map::new(),
    };
    // `required` may only name declared properties (Gemini validates this).
    let required: Vec<Value> = match node.get("required") {
        Some(Value::Array(names)) => names
            .iter()
            .filter(|name| name.as_str().is_some_and(|n| properties.contains_key(n)))
            .cloned()
            .collect(),
        _ => Vec::new(),
    };

    // `items`: object form recursed; the tuple forms (`items: [...]`,
    // `prefixItems`) have no provider equivalent and degrade to a union of
    // the element schemas.
    let items = match node.get("items").or_else(|| node.get("prefixItems")) {
        Some(Value::Array(elements)) => {
            let mut normalized: Vec<Value> =
                elements.iter().map(|e| normalize_node(e, root, depth + 1)).collect();
            match normalized.len() {
                0 => None,
                1 => Some(normalized.remove(0)),
                _ => {
                    let mut union = Map::new();
                    union.insert("anyOf".to_string(), Value::Array(normalized));
                    Some(Value::Object(union))
                }
            }
        }
        Some(schema) => Some(normalize_node(schema, root, depth + 1)),
        None => None,
    };

    // Keywords that describe one type go only on a node of that type: Gemini
    // 400s on `items` off an array, on `properties`/`required` off an object,
    // and on an array without `items`.
    let insert_typed = |out: &mut Map<String, Value>, ty: &str| match ty {
        "array" => {
            let items = items.clone().unwrap_or_else(unconstrained_object);
            out.insert("items".to_string(), items);
        }
        "object" => {
            if !required.is_empty() {
                out.insert("required".to_string(), Value::Array(required.clone()));
            }
            if !properties.is_empty() {
                out.insert("properties".to_string(), Value::Object(properties.clone()));
            }
        }
        _ => {}
    };

    // A multi-type `type` becomes a union with one branch per type.
    if any_of.is_empty() && types.len() > 1 {
        any_of = types
            .drain(..)
            .map(|t| {
                let mut branch = Map::new();
                branch.insert("type".to_string(), Value::String(t.clone()));
                insert_typed(&mut branch, &t);
                Value::Object(branch)
            })
            .collect();
    }

    let ty = if any_of.is_empty() {
        Some(declared_or_inferred_type(types, &enum_values, &properties, items.is_some()))
    } else {
        // The union stands in for the type; `type` alongside `anyOf` is
        // dropped.
        out.insert("anyOf".to_string(), Value::Array(any_of));
        None
    };
    if let Some(ty) = &ty {
        out.insert("type".to_string(), Value::String(ty.clone()));
    }

    for key in ["description", "title", "format"] {
        if let Some(value @ Value::String(_)) = node.get(key) {
            out.insert(key.to_string(), value.clone());
        }
    }
    // `enum` is non-empty-string-only on the wire (Gemini 400s on
    // `enum: [false]`, `enum: [1, 2]`, and `enum: [""]`). Any other value
    // moves the whole list into the description; the `type` inferred above
    // keeps the argument a real boolean or number, so the model doesn't send
    // `"false"` back to a server expecting `false`.
    let enum_values = if enum_values.iter().all(|v| v.as_str().is_some_and(|s| !s.is_empty())) {
        enum_values
    } else {
        let allowed = enum_values.iter().map(Value::to_string).collect::<Vec<_>>().join(", ");
        let hint = match enum_values.len() {
            1 => format!("Must be {allowed}."),
            _ => format!("Allowed values: {allowed}."),
        };
        let description = match out.get("description").and_then(Value::as_str) {
            Some(existing) => format!("{existing} {hint}"),
            None => hint,
        };
        out.insert("description".to_string(), Value::String(description));
        Vec::new()
    };
    for key in [
        "minimum",
        "maximum",
        "minItems",
        "maxItems",
        "minLength",
        "maxLength",
        "minProperties",
        "maxProperties",
    ] {
        if let Some(value) = node.get(key).filter(|v| v.is_number()) {
            out.insert(key.to_string(), value.clone());
        }
    }
    for key in ["default", "example"] {
        if let Some(value) = node.get(key) {
            out.insert(key.to_string(), value.clone());
        }
    }
    if !enum_values.is_empty() {
        out.insert("enum".to_string(), Value::Array(enum_values));
    }
    if let Some(ty) = &ty {
        insert_typed(&mut out, ty);
    }
    if nullable {
        out.insert("nullable".to_string(), Value::Bool(true));
    }
    Value::Object(out)
}

/// The node's declared type, or an inferred one — Gemini's constrained
/// decoder wants every node typed. Inference order: enum values, then
/// structural keys, then the unconstrained-object fallback.
fn declared_or_inferred_type(
    mut types: Vec<String>,
    enum_values: &[Value],
    properties: &Map<String, Value>,
    has_items: bool,
) -> String {
    if let Some(ty) = types.pop() {
        return ty;
    }
    if let Some(first) = enum_values.first() {
        let ty = match first {
            Value::Bool(_) => "boolean",
            Value::Number(_) if enum_values.iter().all(|v| v.as_i64().is_some()) => "integer",
            Value::Number(_) => "number",
            _ => "string",
        };
        return ty.to_string();
    }
    if properties.is_empty() && has_items {
        return "array".to_string();
    }
    // Declared properties, or an unconstrained ("anything goes") node:
    // providers still need a type, and `object` is the least misleading for
    // tool arguments.
    "object".to_string()
}

fn unconstrained_object() -> Value {
    let mut map = Map::new();
    map.insert("type".to_string(), Value::String("object".to_string()));
    Value::Object(map)
}

fn is_null_type(schema: &Value) -> bool {
    schema.as_object().is_some_and(|s| s.get("type").and_then(Value::as_str) == Some("null"))
}

#[cfg(test)]
mod normalize_tests {
    use super::normalize_tool_schema;
    use serde_json::{Value, json};

    /// The corpus every test draws from, kept together so the fixpoint test
    /// covers each shape automatically.
    fn corpus() -> Vec<Value> {
        vec![
            // The Gemini 400 from the field: exclusiveMinimum on a property.
            json!({
                "type": "object",
                "properties": {
                    "limit": {"type": "integer", "exclusiveMinimum": 0, "description": "max rows"}
                }
            }),
            // Draft-4 boolean exclusive bound.
            json!({
                "type": "object",
                "properties": {"n": {"type": "number", "minimum": 1, "exclusiveMinimum": true}}
            }),
            // pydantic-style $defs + $ref, plus a ref wrapped in allOf.
            json!({
                "type": "object",
                "$defs": {
                    "Point": {
                        "type": "object",
                        "properties": {"x": {"type": "number"}},
                        "required": ["x"]
                    },
                    "Mode": {"type": "string", "enum": ["fast", "slow"]}
                },
                "properties": {
                    "origin": {"$ref": "#/$defs/Point"},
                    "mode": {"allOf": [{"$ref": "#/$defs/Mode"}], "default": "fast"}
                },
                "required": ["origin"]
            }),
            // pydantic Optional: anyOf with a null branch.
            json!({
                "type": "object",
                "properties": {
                    "name": {
                        "anyOf": [{"type": "string"}, {"type": "null"}],
                        "default": null,
                        "description": "optional name"
                    }
                }
            }),
            // oneOf union, const, type arrays, unknown keywords.
            json!({
                "type": "object",
                "$schema": "https://json-schema.org/draft/2020-12/schema",
                "additionalProperties": false,
                "properties": {
                    "id": {"oneOf": [{"type": "string"}, {"type": "integer"}]},
                    "kind": {"const": "user"},
                    "score": {"type": ["number", "null"], "multipleOf": 0.5},
                    "text_or_num": {"type": ["string", "number"]}
                },
                "required": ["id", "ghost"]
            }),
            // Untyped nodes: inference from enum / items / nothing.
            json!({
                "type": "object",
                "properties": {
                    "anything": {},
                    "count": {"enum": [1, 2]},
                    "mode": {"enum": ["a", null]},
                    "list": {"items": {"type": "string"}},
                    "pair": {"type": "array", "items": [{"type": "string"}, {"type": "integer"}]}
                }
            }),
            // Self-referential $defs cycle.
            json!({
                "type": "object",
                "$defs": {
                    "Node": {
                        "type": "object",
                        "properties": {"next": {"$ref": "#/$defs/Node"}}
                    }
                },
                "properties": {"root": {"$ref": "#/$defs/Node"}}
            }),
            // Regex dialects differ across providers. ChatGPT rejects
            // lookaround in tool-schema patterns before the model runs.
            json!({
                "type": "object",
                "properties": {
                    "email": {
                        "type": "string",
                        "description": "recipient email",
                        "format": "email",
                        "pattern": "^(?!blocked@example\\.com$).+@.+$"
                    }
                },
                "required": ["email"]
            }),
            // REA's discriminated unions (the Gemini 400 from the field):
            // boolean `const` inside an `anyOf` branch, numeric enums, and `const: ""`.
            json!({
                "type": "object",
                "properties": {
                    "mode": {
                        "anyOf": [
                            {"type": "string"},
                            {
                                "type": "object",
                                "properties": {
                                    "headless": {"type": "boolean", "const": false, "default": false}
                                }
                            }
                        ]
                    },
                    "flag": {"enum": [true, false], "description": "toggle"},
                    "level": {"type": "number", "enum": [0.5, 1]},
                    "blank": {"type": "string", "const": ""}
                }
            }),
            // REA's JSON-value union (the Gemini 400 from the field): `items`
            // beside a multi-type `type`, then the same misplacement for
            // `properties`, a nested array without `items`, and both keywords
            // on a type they don't describe.
            json!({
                "type": "object",
                "properties": {
                    "source_paths": {
                        "type": "array",
                        "items": {
                            "type": ["null", "boolean", "object", "array", "number", "string"],
                            "items": {}
                        }
                    },
                    "target": {
                        "type": ["string", "object"],
                        "properties": {"path": {"type": "string"}},
                        "required": ["path"]
                    },
                    "grid": {"type": "array", "items": {"type": "array"}},
                    "name": {
                        "type": "string",
                        "items": {"type": "string"},
                        "properties": {"a": {"type": "string"}},
                        "required": ["a"]
                    }
                }
            }),
            // Degenerate top levels.
            json!(true),
            json!({"type": "string", "description": "not an object"}),
            json!({"type": "object", "properties": {}}),
        ]
    }

    #[test]
    fn exclusive_minimum_folds_into_minimum() {
        let normalized = normalize_tool_schema(&corpus()[0]);
        assert_eq!(
            normalized["properties"]["limit"],
            json!({"type": "integer", "minimum": 0, "description": "max rows"})
        );
    }

    #[test]
    fn draft4_boolean_exclusive_bound_drops() {
        let normalized = normalize_tool_schema(&corpus()[1]);
        assert_eq!(normalized["properties"]["n"], json!({"type": "number", "minimum": 1}));
    }

    #[test]
    fn local_refs_inline_and_defs_disappear() {
        let normalized = normalize_tool_schema(&corpus()[2]);
        assert!(normalized.get("$defs").is_none());
        assert_eq!(
            normalized["properties"]["origin"],
            json!({
                "type": "object",
                "properties": {"x": {"type": "number"}},
                "required": ["x"]
            })
        );
        // allOf-wrapped ref keeps the sibling default.
        assert_eq!(
            normalized["properties"]["mode"],
            json!({"type": "string", "enum": ["fast", "slow"], "default": "fast"})
        );
        assert_eq!(normalized["required"], json!(["origin"]));
    }

    #[test]
    fn optional_anyof_null_becomes_nullable() {
        let normalized = normalize_tool_schema(&corpus()[3]);
        assert_eq!(
            normalized["properties"]["name"],
            json!({
                "type": "string",
                "nullable": true,
                "default": null,
                "description": "optional name"
            })
        );
    }

    #[test]
    fn unions_consts_and_unknown_keywords() {
        let normalized = normalize_tool_schema(&corpus()[4]);
        assert!(normalized.get("$schema").is_none());
        assert!(normalized.get("additionalProperties").is_none());
        let props = &normalized["properties"];
        assert_eq!(props["id"], json!({"anyOf": [{"type": "string"}, {"type": "integer"}]}));
        assert_eq!(props["kind"], json!({"type": "string", "enum": ["user"]}));
        assert_eq!(props["score"], json!({"type": "number", "nullable": true}));
        assert_eq!(
            props["text_or_num"],
            json!({"anyOf": [{"type": "string"}, {"type": "number"}]})
        );
        // `required` may only name declared properties.
        assert_eq!(normalized["required"], json!(["id"]));
    }

    #[test]
    fn untyped_nodes_get_inferred_types() {
        let normalized = normalize_tool_schema(&corpus()[5]);
        let props = &normalized["properties"];
        assert_eq!(props["anything"], json!({"type": "object"}));
        assert_eq!(
            props["count"],
            json!({"type": "integer", "description": "Allowed values: 1, 2."})
        );
        assert_eq!(props["mode"], json!({"type": "string", "enum": ["a"], "nullable": true}));
        assert_eq!(props["list"], json!({"type": "array", "items": {"type": "string"}}));
        assert_eq!(
            props["pair"],
            json!({
                "type": "array",
                "items": {"anyOf": [{"type": "string"}, {"type": "integer"}]}
            })
        );
    }

    #[test]
    fn cyclic_refs_terminate() {
        let normalized = normalize_tool_schema(&corpus()[6]);
        // The cycle is broken by the depth cap; all that matters is that we
        // returned a valid object schema at the top.
        assert_eq!(normalized["type"], "object");
        assert!(normalized.get("$defs").is_none());
    }

    #[test]
    fn regex_patterns_drop_while_other_string_guidance_survives() {
        let normalized = normalize_tool_schema(&corpus()[7]);
        assert_eq!(
            normalized["properties"]["email"],
            json!({
                "type": "string",
                "description": "recipient email",
                "format": "email"
            })
        );
        assert_eq!(normalized["required"], json!(["email"]));
    }

    #[test]
    fn non_string_enums_move_into_description() {
        let normalized = normalize_tool_schema(&corpus()[8]);
        let props = &normalized["properties"];
        assert_eq!(
            props["mode"]["anyOf"][1]["properties"]["headless"],
            json!({"type": "boolean", "description": "Must be false.", "default": false})
        );
        assert_eq!(
            props["flag"],
            json!({"type": "boolean", "description": "toggle Allowed values: true, false."})
        );
        assert_eq!(
            props["level"],
            json!({"type": "number", "description": "Allowed values: 0.5, 1."})
        );
        assert_eq!(props["blank"], json!({"type": "string", "description": "Must be \"\"."}));
    }

    #[test]
    fn type_specific_keywords_sit_only_on_their_type() {
        let normalized = normalize_tool_schema(&corpus()[9]);
        let props = &normalized["properties"];
        assert_eq!(
            props["source_paths"],
            json!({
                "type": "array",
                "items": {
                    "anyOf": [
                        {"type": "boolean"},
                        {"type": "object"},
                        {"type": "array", "items": {"type": "object"}},
                        {"type": "number"},
                        {"type": "string"}
                    ],
                    "nullable": true
                }
            })
        );
        assert_eq!(
            props["target"],
            json!({
                "anyOf": [
                    {"type": "string"},
                    {
                        "type": "object",
                        "properties": {"path": {"type": "string"}},
                        "required": ["path"]
                    }
                ]
            })
        );
        // Every array carries `items`, at every depth.
        assert_eq!(
            props["grid"],
            json!({"type": "array", "items": {"type": "array", "items": {"type": "object"}}})
        );
        assert_eq!(props["name"], json!({"type": "string"}));
    }

    #[test]
    fn degenerate_top_levels_coerce_to_object() {
        assert_eq!(normalize_tool_schema(&json!(true)), json!({"type": "object"}));
        assert_eq!(
            normalize_tool_schema(&json!({"type": "string", "description": "not an object"})),
            json!({"type": "object", "description": "not an object"})
        );
        // Empty `properties` is omitted, not serialized as `{}` (Gemini
        // rejects empty properties on OBJECT schemas).
        assert_eq!(
            normalize_tool_schema(&json!({"type": "object", "properties": {}})),
            json!({"type": "object"})
        );
    }

    #[test]
    fn normalization_is_a_fixpoint() {
        for (i, schema) in corpus().iter().enumerate() {
            let once = normalize_tool_schema(schema);
            let twice = normalize_tool_schema(&once);
            assert_eq!(twice, once, "corpus[{i}] is not a fixpoint:\n{once:#}");
        }
    }
}