Skip to main content

adk_gemini/
schema_adapter.rs

1//! Gemini-specific schema normalization adapter.
2//!
3//! The [`GeminiSchemaAdapter`] applies all destructive transforms required by
4//! Gemini's function-calling API. It composes shared utilities from
5//! [`adk_core::schema_utils`] with Gemini-specific keyword removal to produce
6//! schemas that Gemini accepts.
7//!
8//! # Transform Order
9//!
10//! Steps 3-12 exist because Gemini's **OpenAPI subset** cannot express those
11//! keywords, so they are skipped for [`GeminiSchemaDialect::JsonSchema`], whose
12//! field accepts them. Steps 1, 2, 13, 14 and 15 are about what the *endpoint*
13//! rejects regardless of dialect, so they always run.
14//!
15//! | # | Transform | OpenAPI subset | JSON Schema |
16//! | --- | --- | --- | --- |
17//! | 1 | Resolve `$ref` (inline from definitions/`$defs`; recursive, over-long or over-budget references become `{"type": "object"}`) | ✓ | ✓ |
18//! | 2 | Strip `$schema` keyword | ✓ | ✓ |
19//! | 3 | Replace boolean subschemas (`true` → `{}`; a `false` property is dropped) | ✓ | — |
20//! | 4 | Reduce `anyOf`/`oneOf` (null branches → `nullable: true`; one branch is merged, several stay as `anyOf`) | ✓ | — |
21//! | 5 | Merge `allOf` sub-schemas | ✓ | — |
22//! | 6 | Reduce type arrays (`["string", "null"]` → `"string"` + `nullable: true`; several types → `anyOf`) | ✓ | — |
23//! | 7 | Strip conditional keywords (`if`/`then`/`else`) | ✓ | — |
24//! | 8 | Convert `const` to single-element `enum` | ✓ | — |
25//! | 9 | Reduce `enum` to strings (`null` → `nullable: true`; `1` → `"1"`, keeping `type`) | ✓ | — |
26//! | 10 | Add implicit `"type": "object"` when `properties` exists | ✓ | — |
27//! | 11 | Describe a map's value type (`additionalProperties` schema) in its `description` | ✓ | — |
28//! | 12 | Remove unsupported keywords recursively (bounds the Schema proto defines are kept) | ✓ | — |
29//! | 13 | Strip unsupported `format` values | ✓ | ✓ |
30//! | 14 | Enforce nesting depth limit (5 levels) | ✓ | ✓ |
31//! | 15 | Remove `definitions`/`$defs` blocks | ✓ | ✓ |
32//!
33//! # Example
34//!
35//! ```rust
36//! use adk_gemini::schema_adapter::GeminiSchemaAdapter;
37//! use adk_core::SchemaAdapter;
38//! use serde_json::json;
39//!
40//! let adapter = GeminiSchemaAdapter::new();
41//! let schema = json!({
42//!     "$schema": "http://json-schema.org/draft-07/schema#",
43//!     "type": "object",
44//!     "properties": {
45//!         "name": { "type": "string", "format": "hostname" }
46//!     },
47//!     "additionalProperties": true
48//! });
49//!
50//! let normalized = adapter.normalize_schema(schema);
51//! assert!(normalized.get("$schema").is_none());
52//! assert!(normalized.get("additionalProperties").is_none());
53//! assert!(normalized["properties"]["name"].get("format").is_none());
54//! ```
55
56use adk_core::SchemaAdapter;
57use adk_core::schema_utils;
58use serde_json::{Map, Value};
59use std::borrow::Cow;
60
61/// Allowed `format` values for the Gemini API.
62const GEMINI_ALLOWED_FORMATS: &[&str] =
63    &["date-time", "date", "time", "email", "uri", "uuid", "int32", "int64", "float", "double"];
64
65/// Keywords that Gemini does not support and must be removed from all schema nodes
66/// (standard API surface — removes `additionalProperties` entirely).
67///
68/// The Schema proto for function declarations rejects any field it does not
69/// define with a 400 (`Unknown name "..."`) on `generateContent` and a WS 1007
70/// close on the Live API. It defines the string, numeric and array bounds
71/// `minLength`, `maxLength`, `pattern`, `minimum`, `maximum`, `minItems` and
72/// `maxItems`, so those are kept; `exclusiveMinimum`, `exclusiveMaximum`,
73/// `multipleOf` and the rest below are not, so they are stripped.
74///
75/// Reference: https://ai.google.dev/api/caching#Schema
76const UNSUPPORTED_KEYWORDS: &[&str] = &[
77    "$id",
78    "additionalProperties",
79    "contains",
80    "contentEncoding",
81    "contentMediaType",
82    "default",
83    "dependentRequired",
84    "dependentSchemas",
85    "deprecated",
86    "examples",
87    "exclusiveMaximum",
88    "exclusiveMinimum",
89    "maxProperties",
90    "minProperties",
91    "multipleOf",
92    "not",
93    "patternProperties",
94    "prefixItems",
95    "propertyNames",
96    "readOnly",
97    "title",
98    "unevaluatedProperties",
99    "uniqueItems",
100    "writeOnly",
101];
102
103/// Keywords that Gemini does not support on the Vertex AI surface.
104/// Unlike the standard surface, Vertex AI requires `additionalProperties: false`
105/// on object schemas rather than removing it.
106///
107/// Same comprehensive list as [`UNSUPPORTED_KEYWORDS`] but without
108/// `additionalProperties` (which is handled separately for Vertex AI).
109const UNSUPPORTED_KEYWORDS_VERTEX: &[&str] = &[
110    "$id",
111    "contains",
112    "contentEncoding",
113    "contentMediaType",
114    "default",
115    "dependentRequired",
116    "dependentSchemas",
117    "deprecated",
118    "examples",
119    "exclusiveMaximum",
120    "exclusiveMinimum",
121    "maxProperties",
122    "minProperties",
123    "multipleOf",
124    "not",
125    "patternProperties",
126    "prefixItems",
127    "propertyNames",
128    "readOnly",
129    "title",
130    "unevaluatedProperties",
131    "uniqueItems",
132    "writeOnly",
133];
134
135/// The schema dialect a [`GeminiSchemaAdapter`] produces, and the
136/// function-declaration field its output must be posted under.
137///
138/// Gemini accepts **two mutually exclusive** schema fields on a function
139/// declaration, and they are not two spellings of one thing:
140///
141/// | Dialect | Field | Expresses |
142/// | --- | --- | --- |
143/// | [`OpenApiSubset`](Self::OpenApiSubset) | `parameters` | An OpenAPI subset. No `allOf`, no `if`/`then`, no `additionalProperties`, no exclusive bounds. Keeps `minimum`/`maximum`, `minLength`/`maxLength`, `pattern` and `minItems`/`maxItems`. |
144/// | [`VertexOpenApiSubset`](Self::VertexOpenApiSubset) | `parameters` | The same subset, except `additionalProperties: false` is set on objects rather than removed. |
145/// | [`JsonSchema`](Self::JsonSchema) | `parametersJsonSchema` | Standard JSON Schema: `allOf`, `anyOf`, `if`/`then`, `additionalProperties`, `minLength`, numeric bounds. |
146///
147/// Selecting the dialect and selecting the field is therefore **one decision**,
148/// which is why they live in one type. Posting a schema that kept its
149/// constraints under the legacy `parameters` field does not degrade — the Live
150/// socket closes with **WS 1007** (`Unknown name "additionalProperties"`), so
151/// the call dies before any audio flows.
152///
153/// # Choosing
154///
155/// [`JsonSchema`](Self::JsonSchema) is verified on Google AI Studio `v1beta`
156/// with `gemini-3.1-flash-live-preview`. Google's function-calling reference
157/// documents only `parameters` and does not mention `parametersJsonSchema` at
158/// all; support is stated in the structured-outputs announcement and confirmed
159/// here by probing the live endpoint. Re-probe before assuming it on another
160/// model, surface, or endpoint version — and note that acceptance is not
161/// enforcement: `setupComplete` proves the schema *parsed*, not that the model
162/// honours every keyword while generating.
163///
164/// The default remains [`OpenApiSubset`](Self::OpenApiSubset), so existing
165/// callers see no behaviour change.
166#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
167pub enum GeminiSchemaDialect {
168    /// OpenAPI subset on `parameters`. Removes `additionalProperties`.
169    #[default]
170    OpenApiSubset,
171    /// OpenAPI subset on `parameters`, Vertex AI flavour: sets
172    /// `additionalProperties: false` on object schemas instead of removing it.
173    VertexOpenApiSubset,
174    /// Standard JSON Schema on `parametersJsonSchema`.
175    JsonSchema,
176}
177
178impl GeminiSchemaDialect {
179    /// The function-declaration field a schema in this dialect belongs under.
180    pub fn parameters_field(self) -> &'static str {
181        match self {
182            Self::OpenApiSubset | Self::VertexOpenApiSubset => "parameters",
183            Self::JsonSchema => "parametersJsonSchema",
184        }
185    }
186
187    /// Whether this dialect is limited to Gemini's OpenAPI subset, and so needs
188    /// the combiners, conditionals and type arrays reduced away before sending.
189    ///
190    /// Asked as a *capability* rather than by comparing against a variant, so
191    /// that adding a dialect means classifying it here once instead of hunting
192    /// for scattered equality checks.
193    pub fn requires_openapi_reduction(self) -> bool {
194        match self {
195            Self::OpenApiSubset | Self::VertexOpenApiSubset => true,
196            Self::JsonSchema => false,
197        }
198    }
199}
200
201/// Schema adapter for the Gemini API surface.
202///
203/// Applies the transforms required by Gemini's function-calling API. How
204/// destructive those transforms are depends on the target
205/// [`GeminiSchemaDialect`]:
206///
207/// - **Standard** (`GeminiSchemaAdapter::new()`): OpenAPI subset; removes
208///   `additionalProperties` entirely.
209/// - **Vertex AI** (`GeminiSchemaAdapter::vertex_ai()`): OpenAPI subset; sets
210///   `additionalProperties: false` on object schemas instead of removing it.
211/// - **JSON Schema** (`GeminiSchemaAdapter::json_schema()`): keeps `allOf`,
212///   `anyOf`, `if`/`then`, `additionalProperties` and the string/numeric
213///   bounds, and its output must be posted under `parametersJsonSchema`.
214///
215/// Use [`parameters_field()`](adk_core::SchemaAdapter::parameters_field) rather
216/// than hardcoding a field name; it is derived from the dialect so the two
217/// cannot disagree.
218///
219/// # Example
220///
221/// ```rust
222/// use adk_gemini::schema_adapter::GeminiSchemaAdapter;
223/// use adk_core::SchemaAdapter;
224/// use serde_json::json;
225///
226/// let adapter = GeminiSchemaAdapter::new();
227/// let schema = json!({
228///     "anyOf": [
229///         {"type": "null"},
230///         {"type": "string", "minLength": 1}
231///     ]
232/// });
233///
234/// let normalized = adapter.normalize_schema(schema);
235/// assert_eq!(normalized["type"], "string");
236/// assert!(normalized.get("anyOf").is_none());
237/// ```
238#[derive(Debug)]
239pub struct GeminiSchemaAdapter {
240    /// The dialect this adapter reduces to, which also decides the wire field.
241    dialect: GeminiSchemaDialect,
242}
243
244impl GeminiSchemaAdapter {
245    /// Creates a new `GeminiSchemaAdapter` for the standard Gemini API surface.
246    ///
247    /// This variant removes `additionalProperties` from all schema nodes.
248    pub fn new() -> Self {
249        Self::with_dialect(GeminiSchemaDialect::OpenApiSubset)
250    }
251
252    /// Creates a new `GeminiSchemaAdapter` for the Vertex AI surface.
253    ///
254    /// This variant sets `additionalProperties: false` on object schemas
255    /// instead of removing the keyword entirely.
256    pub fn vertex_ai() -> Self {
257        Self::with_dialect(GeminiSchemaDialect::VertexOpenApiSubset)
258    }
259
260    /// Creates a new `GeminiSchemaAdapter` targeting standard JSON Schema.
261    ///
262    /// Keeps `allOf`, `anyOf`, `if`/`then`, `additionalProperties` and the
263    /// string/numeric bounds instead of stripping them, so a model is shown the
264    /// same contract the caller validates against. Its output belongs under
265    /// `parametersJsonSchema`; see [`GeminiSchemaDialect::JsonSchema`] for the
266    /// surfaces this is verified on.
267    pub fn json_schema() -> Self {
268        Self::with_dialect(GeminiSchemaDialect::JsonSchema)
269    }
270
271    /// Creates a new `GeminiSchemaAdapter` for an explicitly chosen dialect.
272    pub fn with_dialect(dialect: GeminiSchemaDialect) -> Self {
273        Self { dialect }
274    }
275
276    /// The dialect this adapter reduces to.
277    pub fn dialect(&self) -> GeminiSchemaDialect {
278        self.dialect
279    }
280}
281
282impl Default for GeminiSchemaAdapter {
283    fn default() -> Self {
284        Self::new()
285    }
286}
287
288impl SchemaAdapter for GeminiSchemaAdapter {
289    fn normalize_schema(&self, mut schema: Value) -> Value {
290        // Which steps run depends on the target dialect, along one line: a
291        // transform that exists because the *OpenAPI subset cannot express* a
292        // keyword is skipped for JSON Schema, which can; a transform that
293        // exists because the *endpoint rejects* something runs for every
294        // dialect. Steps 3-12 below are the first kind. Steps 1, 2 and 13-15
295        // are the second, so they are unconditional.
296
297        // Step 1: Extract definitions and resolve $ref references.
298        // Always resolve refs — even with empty definitions — so that
299        // unresolvable $ref values are replaced with {"type": "object"}.
300        //
301        // Unconditional despite JSON Schema supporting `$ref`: Google's own
302        // guidance warns that large or deeply nested schemas may be rejected,
303        // and an inlined document is the shape both fields are known to accept.
304        let definitions = extract_definitions(&schema);
305        schema_utils::resolve_refs(&mut schema, &definitions, 0);
306
307        // Step 2: Strip $schema keyword — rejected on both fields.
308        schema_utils::strip_schema_keyword(&mut schema);
309
310        if self.dialect.requires_openapi_reduction() {
311            // Step 3: Replace boolean subschemas, which the Schema proto cannot carry.
312            replace_boolean_subschemas(&mut schema);
313
314            // Step 4: Reduce anyOf/oneOf: null branches become `nullable`, a single
315            // remaining branch is merged, several stay as `anyOf`.
316            reduce_combiners(&mut schema);
317
318            // Step 5: Merge allOf sub-schemas
319            schema_utils::merge_all_of(&mut schema);
320
321            // Step 6: Reduce type arrays: `null` becomes `nullable`, several types an `anyOf`.
322            reduce_type_arrays(&mut schema);
323
324            // Step 7: Strip conditional keywords (if/then/else)
325            schema_utils::strip_conditional_keywords(&mut schema);
326
327            // Step 8: Convert const to single-element enum
328            schema_utils::convert_const_to_enum(&mut schema);
329
330            // Step 9: Reduce enums to strings: `null` becomes `nullable`, numbers and
331            // booleans become their text, because the proto's `enum` is a string list.
332            reduce_enums(&mut schema);
333
334            // Step 10: Add implicit object type.
335            //
336            // Skipped for JSON Schema not merely as unnecessary but as
337            // *harmful*: it injects `type: "object"` into every schema-shaped
338            // node it walks, including the `if` clause of a conditional, which
339            // changes what that clause matches.
340            schema_utils::add_implicit_object_type(&mut schema);
341
342            // Step 11: Record a map's value type in its description before step 12
343            // removes `additionalProperties`.
344            describe_map_values(&mut schema);
345        }
346
347        // Step 12: Remove unsupported keywords recursively.
348        //
349        // Matched exhaustively rather than defaulted: a dialect added later
350        // must state what it strips, instead of silently inheriting the
351        // subset's answer and quietly dropping constraints again.
352        match self.dialect {
353            // Nothing to remove. `additionalProperties`, `minLength`, `pattern`
354            // and the numeric bounds are all expressible here, and stripping
355            // them is exactly what leaves a model guessing at rules the caller
356            // still enforces.
357            GeminiSchemaDialect::JsonSchema => {}
358            GeminiSchemaDialect::VertexOpenApiSubset => {
359                remove_unsupported_keywords_vertex(&mut schema)
360            }
361            GeminiSchemaDialect::OpenApiSubset => remove_unsupported_keywords(&mut schema),
362        }
363
364        // Step 13: Strip unsupported format values
365        schema_utils::strip_unsupported_formats(&mut schema, GEMINI_ALLOWED_FORMATS);
366
367        // Step 14: Enforce nesting depth (max 5 levels)
368        schema_utils::enforce_nesting_depth(&mut schema, 5, 0);
369
370        // Step 15: Remove definitions/$defs blocks
371        if let Some(obj) = schema.as_object_mut() {
372            obj.remove("definitions");
373            obj.remove("$defs");
374        }
375
376        schema
377    }
378
379    /// Truncates tool names exceeding 64 bytes at a valid UTF-8 character boundary.
380    ///
381    /// Preserves the prefix of the name, truncating from the end.
382    fn normalize_tool_name<'a>(&self, name: &'a str) -> Cow<'a, str> {
383        if name.len() <= 64 {
384            Cow::Borrowed(name)
385        } else {
386            let mut end = 64;
387            while end > 0 && !name.is_char_boundary(end) {
388                end -= 1;
389            }
390            Cow::Owned(name[..end].to_string())
391        }
392    }
393
394    /// Returns the fallback schema for tools with no `parameters_schema`.
395    ///
396    /// Gemini requires `{"type": "object", "properties": {}}` as the minimum
397    /// valid function declaration parameters.
398    fn empty_schema(&self) -> Value {
399        serde_json::json!({"type": "object", "properties": {}})
400    }
401
402    /// The function-declaration field this adapter's output belongs under,
403    /// derived from the dialect so the reduction and the field cannot disagree.
404    fn parameters_field(&self) -> &'static str {
405        self.dialect.parameters_field()
406    }
407}
408
409/// Calls `visit` on every sub-schema location of `schema`.
410fn for_each_subschema(schema: &mut Value, visit: &mut dyn FnMut(&mut Value)) {
411    let Some(obj) = schema.as_object_mut() else {
412        return;
413    };
414    for keyword in ["properties", "patternProperties"] {
415        if let Some(Value::Object(members)) = obj.get_mut(keyword) {
416            members.values_mut().for_each(&mut *visit);
417        }
418    }
419    for keyword in ["additionalProperties", "not", "if", "then", "else"] {
420        if let Some(sub @ Value::Object(_)) = obj.get_mut(keyword) {
421            visit(sub);
422        }
423    }
424    match obj.get_mut("items") {
425        Some(Value::Array(items)) => items.iter_mut().for_each(&mut *visit),
426        Some(items @ Value::Object(_)) => visit(items),
427        _ => {}
428    }
429    for keyword in ["prefixItems", "allOf", "anyOf", "oneOf"] {
430        if let Some(Value::Array(subs)) = obj.get_mut(keyword) {
431            subs.iter_mut().for_each(&mut *visit);
432        }
433    }
434}
435
436/// Replaces boolean subschemas, which the Schema proto rejects with a 400.
437///
438/// `true` accepts anything and becomes `{}`. A property whose schema is `false` can
439/// never be supplied, so it is dropped together with its `required` entry, and a
440/// `false` branch of `anyOf`/`oneOf` is dropped; elsewhere `false` becomes `{}`.
441fn replace_boolean_subschemas(schema: &mut Value) {
442    let Some(obj) = schema.as_object_mut() else {
443        return;
444    };
445    if let Some(Value::Object(properties)) = obj.get_mut("properties") {
446        let never: Vec<String> = properties
447            .iter()
448            .filter(|(_, sub)| **sub == Value::Bool(false))
449            .map(|(name, _)| name.clone())
450            .collect();
451        properties.retain(|name, _| !never.contains(name));
452        if let Some(Value::Array(required)) = obj.get_mut("required") {
453            required
454                .retain(|name| name.as_str().is_none_or(|name| !never.iter().any(|n| n == name)));
455        }
456    }
457    for keyword in ["anyOf", "oneOf"] {
458        if let Some(Value::Array(branches)) = obj.get_mut(keyword) {
459            branches.retain(|branch| *branch != Value::Bool(false));
460        }
461    }
462    for_each_subschema(schema, &mut |sub| {
463        if sub.is_boolean() {
464            *sub = Value::Object(Map::new());
465        }
466        replace_boolean_subschemas(sub);
467    });
468    // `items` and `additionalProperties` may themselves be booleans.
469    if let Some(obj) = schema.as_object_mut()
470        && let Some(items @ Value::Bool(_)) = obj.get_mut("items")
471    {
472        *items = Value::Object(Map::new());
473    }
474}
475
476fn is_null_type(schema: &Value) -> bool {
477    schema.get("type").and_then(Value::as_str) == Some("null")
478}
479
480/// Reduces `anyOf` and `oneOf` to what the Schema proto carries.
481///
482/// Null branches become `nullable: true` on the parent. One remaining branch is merged
483/// into the parent; several remain as `anyOf`, which the proto supports, rather than
484/// being cut down to the first.
485fn reduce_combiners(schema: &mut Value) {
486    if let Some(obj) = schema.as_object_mut() {
487        for keyword in ["anyOf", "oneOf"] {
488            let Some(Value::Array(branches)) = obj.remove(keyword) else {
489                continue;
490            };
491            let total = branches.len();
492            let mut branches: Vec<Value> =
493                branches.into_iter().filter(|branch| !is_null_type(branch)).collect();
494            if branches.len() < total {
495                obj.insert("nullable".to_string(), Value::Bool(true));
496            }
497            match branches.len() {
498                0 => {
499                    obj.insert("type".to_string(), Value::from("null"));
500                }
501                1 => {
502                    if let Some(Value::Object(branch)) = branches.pop() {
503                        obj.extend(branch);
504                    }
505                }
506                _ if !obj.contains_key("anyOf") => {
507                    obj.insert("anyOf".to_string(), Value::Array(branches));
508                }
509                // Both keywords carried a union; only one `anyOf` can be sent.
510                _ => {
511                    if let Some(Value::Object(branch)) = branches.into_iter().next() {
512                        obj.extend(branch);
513                    }
514                }
515            }
516        }
517    }
518    for_each_subschema(schema, &mut reduce_combiners);
519}
520
521/// Reduces `type` arrays: `"null"` becomes `nullable: true`, and several remaining
522/// types become an `anyOf` of single-type schemas.
523fn reduce_type_arrays(schema: &mut Value) {
524    if let Some(obj) = schema.as_object_mut()
525        && let Some(Value::Array(types)) = obj.get("type").cloned()
526    {
527        let mut kinds: Vec<Value> = types.into_iter().filter(|kind| kind != "null").collect();
528        let nullable = kinds.len() < obj.get("type").and_then(Value::as_array).map_or(0, Vec::len);
529        obj.remove("type");
530        if nullable {
531            obj.insert("nullable".to_string(), Value::Bool(true));
532        }
533        match kinds.len() {
534            0 => {
535                obj.insert("type".to_string(), Value::from("null"));
536            }
537            1 => {
538                obj.insert("type".to_string(), kinds.remove(0));
539            }
540            _ if !obj.contains_key("anyOf") => {
541                let branches = kinds.into_iter().map(|kind| serde_json::json!({ "type": kind }));
542                obj.insert("anyOf".to_string(), Value::Array(branches.collect()));
543            }
544            _ => {
545                obj.insert("type".to_string(), kinds.remove(0));
546            }
547        }
548    }
549    for_each_subschema(schema, &mut reduce_type_arrays);
550}
551
552/// Reduces `enum` to the string list the Schema proto defines.
553///
554/// `null` becomes `nullable: true`. Numbers and booleans become their JSON text and
555/// the schema keeps (or is given) its numeric or boolean `type`, so Gemini still
556/// answers with a number: `{"type": "integer", "enum": ["1", "2"]}` yields `2`, not
557/// `"2"`.
558fn reduce_enums(schema: &mut Value) {
559    if let Some(obj) = schema.as_object_mut()
560        && let Some(Value::Array(values)) = obj.remove("enum")
561    {
562        let total = values.len();
563        let values: Vec<Value> = values.into_iter().filter(|value| !value.is_null()).collect();
564        if values.len() < total {
565            obj.insert("nullable".to_string(), Value::Bool(true));
566        }
567        if !obj.contains_key("type") {
568            let kind = if values.iter().all(Value::is_string) {
569                None
570            } else if values.iter().all(|value| value.is_i64() || value.is_u64()) {
571                Some("integer")
572            } else if values.iter().all(Value::is_number) {
573                Some("number")
574            } else if values.iter().all(Value::is_boolean) {
575                Some("boolean")
576            } else {
577                Some("string")
578            };
579            if let Some(kind) = kind {
580                obj.insert("type".to_string(), Value::from(kind));
581            }
582        }
583        if !values.is_empty() {
584            let values = values.into_iter().map(|value| match value {
585                Value::String(text) => Value::String(text),
586                other => Value::String(other.to_string()),
587            });
588            obj.insert("enum".to_string(), Value::Array(values.collect()));
589        }
590    }
591    for_each_subschema(schema, &mut reduce_enums);
592}
593
594/// Records a map's value type in its description.
595///
596/// A map is an object whose `additionalProperties` is a schema and which declares no
597/// properties. The Schema proto has no `additionalProperties`, so without this the
598/// model sees only an empty object.
599fn describe_map_values(schema: &mut Value) {
600    if let Some(obj) = schema.as_object_mut()
601        && obj.get("properties").and_then(Value::as_object).is_none_or(Map::is_empty)
602        && let Some(Value::Object(values)) = obj.get("additionalProperties")
603    {
604        let kind = values.get("type").and_then(Value::as_str).unwrap_or("any");
605        let note = format!("An object mapping string keys to {kind} values.");
606        let description = match obj.get("description").and_then(Value::as_str) {
607            Some(text) if !text.trim().is_empty() => format!("{} {note}", text.trim_end()),
608            _ => note,
609        };
610        obj.insert("description".to_string(), Value::String(description));
611    }
612    for_each_subschema(schema, &mut describe_map_values);
613}
614
615/// Extracts and merges `definitions` and `$defs` from the top-level schema
616/// into a single map for reference resolution.
617fn extract_definitions(schema: &Value) -> Map<String, Value> {
618    let mut defs = Map::new();
619
620    if let Some(obj) = schema.as_object() {
621        // Collect from "definitions" (Draft 4-7)
622        if let Some(definitions) = obj.get("definitions").and_then(|v| v.as_object()) {
623            for (key, value) in definitions {
624                defs.insert(key.clone(), value.clone());
625            }
626        }
627
628        // Collect from "$defs" (Draft 2019-09+)
629        if let Some(dollar_defs) = obj.get("$defs").and_then(|v| v.as_object()) {
630            for (key, value) in dollar_defs {
631                defs.insert(key.clone(), value.clone());
632            }
633        }
634    }
635
636    defs
637}
638
639/// Recursively removes unsupported keywords from the schema and all nested sub-schemas.
640///
641/// Removes: `additionalProperties`, `exclusiveMinimum`, `exclusiveMaximum`,
642/// `items` (when type is not "array"), `not`, `propertyNames`, `patternProperties`,
643/// `unevaluatedProperties`.
644fn remove_unsupported_keywords(schema: &mut Value) {
645    let Some(obj) = schema.as_object_mut() else {
646        return;
647    };
648
649    // Remove standard unsupported keywords
650    for keyword in UNSUPPORTED_KEYWORDS {
651        obj.remove(*keyword);
652    }
653
654    // Handle `items`:
655    // 1. If type is NOT "array", remove items entirely (meaningless on non-array types).
656    // 2. If type IS "array" and items is a JSON array (tuple validation syntax),
657    //    convert to single schema using the first element. Gemini requires items
658    //    on array types but only supports a single schema, not tuple validation.
659    // 3. If type IS "array" and items is already an object, keep it (valid).
660    // 4. If type IS "array" and items is missing, add a default items schema.
661    let is_array_type = obj.get("type").and_then(|t| t.as_str()).is_some_and(|t| t == "array");
662    if !is_array_type {
663        obj.remove("items");
664    } else if obj.get("items").is_some_and(|v| v.is_array()) {
665        // Convert tuple items [schema1, schema2, ...] → first schema as single items
666        let first_schema = obj
667            .get("items")
668            .and_then(|v| v.as_array())
669            .and_then(|arr| arr.first())
670            .cloned()
671            .unwrap_or_else(|| serde_json::json!({"type": "string"}));
672        obj.insert("items".to_string(), first_schema);
673    } else if !obj.contains_key("items") {
674        // Gemini requires items on array types — add default if missing
675        obj.insert("items".to_string(), serde_json::json!({"type": "string"}));
676    }
677
678    // Recurse into properties
679    if let Some(props) = obj.get_mut("properties")
680        && let Some(props_obj) = props.as_object_mut()
681    {
682        for value in props_obj.values_mut() {
683            remove_unsupported_keywords(value);
684        }
685    }
686
687    // Recurse into items (now guaranteed to be a single schema object if present)
688    if let Some(items) = obj.get_mut("items")
689        && items.is_object()
690    {
691        remove_unsupported_keywords(items);
692    }
693
694    // Recurse into allOf, anyOf, oneOf (may still exist if not collapsed)
695    for keyword in &["allOf", "anyOf", "oneOf"] {
696        if let Some(arr_val) = obj.get_mut(*keyword)
697            && let Some(arr) = arr_val.as_array_mut()
698        {
699            for sub in arr.iter_mut() {
700                remove_unsupported_keywords(sub);
701            }
702        }
703    }
704}
705
706/// Recursively removes unsupported keywords for the Vertex AI surface.
707///
708/// Unlike the standard surface, Vertex AI requires `additionalProperties: false`
709/// on object schemas. This function:
710/// - Sets `additionalProperties` to `false` on object schemas (instead of removing it)
711/// - Removes all other unsupported keywords the same as the standard surface
712fn remove_unsupported_keywords_vertex(schema: &mut Value) {
713    let Some(obj) = schema.as_object_mut() else {
714        return;
715    };
716
717    // Remove Vertex-specific unsupported keywords (does NOT include additionalProperties)
718    for keyword in UNSUPPORTED_KEYWORDS_VERTEX {
719        obj.remove(*keyword);
720    }
721
722    // For object schemas, set additionalProperties to false
723    let is_object_type = obj.get("type").and_then(|t| t.as_str()).is_some_and(|t| t == "object");
724    if is_object_type {
725        obj.insert("additionalProperties".to_string(), Value::Bool(false));
726    } else {
727        // For non-object schemas, remove additionalProperties if present
728        obj.remove("additionalProperties");
729    }
730
731    // Handle `items`:
732    // 1. If type is NOT "array", remove items entirely (meaningless on non-array types).
733    // 2. If type IS "array" and items is a JSON array (tuple validation syntax),
734    //    convert to single schema using the first element. Gemini requires items
735    //    on array types but only supports a single schema, not tuple validation.
736    // 3. If type IS "array" and items is already an object, keep it (valid).
737    // 4. If type IS "array" and items is missing, add a default items schema.
738    let is_array_type = obj.get("type").and_then(|t| t.as_str()).is_some_and(|t| t == "array");
739    if !is_array_type {
740        obj.remove("items");
741    } else if obj.get("items").is_some_and(|v| v.is_array()) {
742        let first_schema = obj
743            .get("items")
744            .and_then(|v| v.as_array())
745            .and_then(|arr| arr.first())
746            .cloned()
747            .unwrap_or_else(|| serde_json::json!({"type": "string"}));
748        obj.insert("items".to_string(), first_schema);
749    } else if !obj.contains_key("items") {
750        obj.insert("items".to_string(), serde_json::json!({"type": "string"}));
751    }
752
753    // Recurse into properties
754    if let Some(props) = obj.get_mut("properties")
755        && let Some(props_obj) = props.as_object_mut()
756    {
757        for value in props_obj.values_mut() {
758            remove_unsupported_keywords_vertex(value);
759        }
760    }
761
762    // Recurse into items (now guaranteed to be a single schema object if present)
763    if let Some(items) = obj.get_mut("items")
764        && items.is_object()
765    {
766        remove_unsupported_keywords_vertex(items);
767    }
768
769    // Recurse into allOf, anyOf, oneOf (may still exist if not collapsed)
770    for keyword in &["allOf", "anyOf", "oneOf"] {
771        if let Some(arr_val) = obj.get_mut(*keyword)
772            && let Some(arr) = arr_val.as_array_mut()
773        {
774            for sub in arr.iter_mut() {
775                remove_unsupported_keywords_vertex(sub);
776            }
777        }
778    }
779}
780
781#[cfg(test)]
782mod tests {
783    use super::*;
784    use serde_json::json;
785
786    #[test]
787    fn test_strips_schema_keyword() {
788        let adapter = GeminiSchemaAdapter::new();
789        let schema = json!({
790            "$schema": "http://json-schema.org/draft-07/schema#",
791            "type": "object",
792            "properties": { "name": { "type": "string" } }
793        });
794        let result = adapter.normalize_schema(schema);
795        assert!(result.get("$schema").is_none());
796    }
797
798    #[test]
799    fn test_removes_additional_properties() {
800        let adapter = GeminiSchemaAdapter::new();
801        let schema = json!({
802            "type": "object",
803            "properties": { "name": { "type": "string" } },
804            "additionalProperties": true
805        });
806        let result = adapter.normalize_schema(schema);
807        assert!(result.get("additionalProperties").is_none());
808    }
809
810    #[test]
811    fn test_removes_exclusive_min_max() {
812        let adapter = GeminiSchemaAdapter::new();
813        let schema = json!({
814            "type": "number",
815            "exclusiveMinimum": 0,
816            "exclusiveMaximum": 100
817        });
818        let result = adapter.normalize_schema(schema);
819        assert!(result.get("exclusiveMinimum").is_none());
820        assert!(result.get("exclusiveMaximum").is_none());
821    }
822
823    #[test]
824    fn test_removes_items_when_not_array() {
825        let adapter = GeminiSchemaAdapter::new();
826        let schema = json!({
827            "type": "object",
828            "items": { "type": "string" }
829        });
830        let result = adapter.normalize_schema(schema);
831        assert!(result.get("items").is_none());
832    }
833
834    #[test]
835    fn test_preserves_items_when_array() {
836        let adapter = GeminiSchemaAdapter::new();
837        let schema = json!({
838            "type": "array",
839            "items": { "type": "string" }
840        });
841        let result = adapter.normalize_schema(schema);
842        assert!(result.get("items").is_some());
843        assert_eq!(result["items"]["type"], "string");
844    }
845
846    #[test]
847    fn test_converts_items_tuple_validation_to_single_schema() {
848        // Gemini's proto doesn't support tuple validation (items as JSON array).
849        // Convert to single schema using first element so arrays still have items.
850        let adapter = GeminiSchemaAdapter::new();
851        let schema = json!({
852            "type": "array",
853            "items": [
854                { "type": "number" },
855                { "type": "number" }
856            ]
857        });
858        let result = adapter.normalize_schema(schema);
859        // items should be converted to the first element schema, not removed
860        assert_eq!(result["items"], json!({"type": "number"}));
861        assert_eq!(result["type"], "array");
862    }
863
864    #[test]
865    fn test_vertex_ai_converts_items_tuple_validation() {
866        let adapter = GeminiSchemaAdapter::vertex_ai();
867        let schema = json!({
868            "type": "array",
869            "items": [
870                { "type": "integer" },
871                { "type": "boolean" }
872            ]
873        });
874        let result = adapter.normalize_schema(schema);
875        // Converts to first element schema
876        assert_eq!(result["items"], json!({"type": "integer"}));
877    }
878
879    #[test]
880    fn test_removes_not_keyword() {
881        let adapter = GeminiSchemaAdapter::new();
882        let schema = json!({
883            "type": "string",
884            "not": { "enum": ["bad"] }
885        });
886        let result = adapter.normalize_schema(schema);
887        assert!(result.get("not").is_none());
888    }
889
890    #[test]
891    fn test_removes_property_names() {
892        let adapter = GeminiSchemaAdapter::new();
893        let schema = json!({
894            "type": "object",
895            "propertyNames": { "pattern": "^[a-z]+$" }
896        });
897        let result = adapter.normalize_schema(schema);
898        assert!(result.get("propertyNames").is_none());
899    }
900
901    #[test]
902    fn test_removes_pattern_properties() {
903        let adapter = GeminiSchemaAdapter::new();
904        let schema = json!({
905            "type": "object",
906            "patternProperties": { "^S_": { "type": "string" } }
907        });
908        let result = adapter.normalize_schema(schema);
909        assert!(result.get("patternProperties").is_none());
910    }
911
912    #[test]
913    fn test_removes_unevaluated_properties() {
914        let adapter = GeminiSchemaAdapter::new();
915        let schema = json!({
916            "type": "object",
917            "unevaluatedProperties": false
918        });
919        let result = adapter.normalize_schema(schema);
920        assert!(result.get("unevaluatedProperties").is_none());
921    }
922
923    #[test]
924    fn test_collapses_any_of() {
925        let adapter = GeminiSchemaAdapter::new();
926        let schema = json!({
927            "anyOf": [
928                { "type": "null" },
929                { "type": "string", "description": "A non-empty string" }
930            ]
931        });
932        let result = adapter.normalize_schema(schema);
933        assert!(result.get("anyOf").is_none());
934        assert_eq!(result["type"], "string");
935        assert_eq!(result["description"], "A non-empty string");
936    }
937
938    #[test]
939    fn test_collapses_one_of() {
940        let adapter = GeminiSchemaAdapter::new();
941        let schema = json!({
942            "oneOf": [
943                { "type": "null" },
944                { "type": "integer", "minimum": 0 }
945            ]
946        });
947        let result = adapter.normalize_schema(schema);
948        assert!(result.get("oneOf").is_none());
949        assert_eq!(result["type"], "integer");
950    }
951
952    #[test]
953    fn test_merges_all_of() {
954        let adapter = GeminiSchemaAdapter::new();
955        let schema = json!({
956            "allOf": [
957                { "type": "object", "properties": { "a": { "type": "string" } } },
958                { "properties": { "b": { "type": "number" } }, "required": ["b"] }
959            ]
960        });
961        let result = adapter.normalize_schema(schema);
962        assert!(result.get("allOf").is_none());
963        assert_eq!(result["properties"]["a"]["type"], "string");
964        assert_eq!(result["properties"]["b"]["type"], "number");
965        assert_eq!(result["required"], json!(["b"]));
966    }
967
968    #[test]
969    fn test_collapses_type_arrays() {
970        let adapter = GeminiSchemaAdapter::new();
971        let schema = json!({
972            "type": ["string", "null"],
973            "minLength": 1
974        });
975        let result = adapter.normalize_schema(schema);
976        assert_eq!(result["type"], "string");
977    }
978
979    #[test]
980    fn test_strips_conditional_keywords() {
981        let adapter = GeminiSchemaAdapter::new();
982        let schema = json!({
983            "type": "object",
984            "if": { "properties": { "kind": { "const": "a" } } },
985            "then": { "required": ["extra"] },
986            "else": { "required": [] }
987        });
988        let result = adapter.normalize_schema(schema);
989        assert!(result.get("if").is_none());
990        assert!(result.get("then").is_none());
991        assert!(result.get("else").is_none());
992    }
993
994    #[test]
995    fn test_converts_const_to_enum() {
996        let adapter = GeminiSchemaAdapter::new();
997        let schema = json!({
998            "type": "string",
999            "const": "fixed"
1000        });
1001        let result = adapter.normalize_schema(schema);
1002        assert!(result.get("const").is_none());
1003        assert_eq!(result["enum"], json!(["fixed"]));
1004    }
1005
1006    #[test]
1007    fn test_strips_null_from_enum() {
1008        let adapter = GeminiSchemaAdapter::new();
1009        let schema = json!({
1010            "type": "string",
1011            "enum": ["a", null, "b"]
1012        });
1013        let result = adapter.normalize_schema(schema);
1014        assert_eq!(result["enum"], json!(["a", "b"]));
1015    }
1016
1017    #[test]
1018    fn test_removes_empty_enum_after_null_strip() {
1019        let adapter = GeminiSchemaAdapter::new();
1020        let schema = json!({
1021            "type": "string",
1022            "enum": [null]
1023        });
1024        let result = adapter.normalize_schema(schema);
1025        assert!(result.get("enum").is_none());
1026    }
1027
1028    #[test]
1029    fn test_adds_implicit_object_type() {
1030        let adapter = GeminiSchemaAdapter::new();
1031        let schema = json!({
1032            "properties": { "name": { "type": "string" } }
1033        });
1034        let result = adapter.normalize_schema(schema);
1035        assert_eq!(result["type"], "object");
1036    }
1037
1038    #[test]
1039    fn test_strips_unsupported_formats() {
1040        let adapter = GeminiSchemaAdapter::new();
1041        let schema = json!({
1042            "type": "object",
1043            "properties": {
1044                "created": { "type": "string", "format": "date-time" },
1045                "hostname": { "type": "string", "format": "hostname" },
1046                "id": { "type": "string", "format": "uuid" }
1047            }
1048        });
1049        let result = adapter.normalize_schema(schema);
1050        assert_eq!(result["properties"]["created"]["format"], "date-time");
1051        assert!(result["properties"]["hostname"].get("format").is_none());
1052        assert_eq!(result["properties"]["id"]["format"], "uuid");
1053    }
1054
1055    #[test]
1056    fn test_preserves_all_allowed_formats() {
1057        let adapter = GeminiSchemaAdapter::new();
1058        for format in GEMINI_ALLOWED_FORMATS {
1059            let schema = json!({ "type": "string", "format": format });
1060            let result = adapter.normalize_schema(schema);
1061            assert_eq!(result["format"], *format, "format '{format}' should be preserved");
1062        }
1063    }
1064
1065    #[test]
1066    fn test_enforces_nesting_depth() {
1067        let adapter = GeminiSchemaAdapter::new();
1068        // Create a schema nested 7 levels deep
1069        let schema = json!({
1070            "type": "object",
1071            "properties": {
1072                "l1": {
1073                    "type": "object",
1074                    "properties": {
1075                        "l2": {
1076                            "type": "object",
1077                            "properties": {
1078                                "l3": {
1079                                    "type": "object",
1080                                    "properties": {
1081                                        "l4": {
1082                                            "type": "object",
1083                                            "properties": {
1084                                                "l5": {
1085                                                    "type": "object",
1086                                                    "properties": {
1087                                                        "l6": { "type": "string" }
1088                                                    }
1089                                                }
1090                                            }
1091                                        }
1092                                    }
1093                                }
1094                            }
1095                        }
1096                    }
1097                }
1098            }
1099        });
1100        let result = adapter.normalize_schema(schema);
1101        // At depth 5, the schema should be truncated to {"type": "object"}
1102        let l5 = &result["properties"]["l1"]["properties"]["l2"]["properties"]["l3"]["properties"]
1103            ["l4"]["properties"]["l5"];
1104        assert_eq!(l5, &json!({"type": "object"}));
1105    }
1106
1107    #[test]
1108    fn test_resolves_refs() {
1109        let adapter = GeminiSchemaAdapter::new();
1110        let schema = json!({
1111            "type": "object",
1112            "properties": {
1113                "address": { "$ref": "#/definitions/Address" }
1114            },
1115            "definitions": {
1116                "Address": {
1117                    "type": "object",
1118                    "properties": {
1119                        "street": { "type": "string" }
1120                    }
1121                }
1122            }
1123        });
1124        let result = adapter.normalize_schema(schema);
1125        // $ref should be resolved
1126        assert!(result["properties"]["address"].get("$ref").is_none());
1127        assert_eq!(result["properties"]["address"]["type"], "object");
1128        assert_eq!(result["properties"]["address"]["properties"]["street"]["type"], "string");
1129        // definitions should be removed
1130        assert!(result.get("definitions").is_none());
1131    }
1132
1133    #[test]
1134    fn test_resolves_dollar_defs() {
1135        let adapter = GeminiSchemaAdapter::new();
1136        let schema = json!({
1137            "type": "object",
1138            "properties": {
1139                "item": { "$ref": "#/$defs/Item" }
1140            },
1141            "$defs": {
1142                "Item": {
1143                    "type": "object",
1144                    "properties": {
1145                        "name": { "type": "string" }
1146                    }
1147                }
1148            }
1149        });
1150        let result = adapter.normalize_schema(schema);
1151        assert!(result["properties"]["item"].get("$ref").is_none());
1152        assert_eq!(result["properties"]["item"]["type"], "object");
1153        assert!(result.get("$defs").is_none());
1154    }
1155
1156    #[test]
1157    fn test_unresolvable_ref_becomes_object() {
1158        let adapter = GeminiSchemaAdapter::new();
1159        let schema = json!({
1160            "type": "object",
1161            "properties": {
1162                "unknown": { "$ref": "#/definitions/DoesNotExist" }
1163            }
1164        });
1165        let result = adapter.normalize_schema(schema);
1166        assert_eq!(result["properties"]["unknown"], json!({"type": "object"}));
1167    }
1168
1169    #[test]
1170    fn test_circular_ref_breaks() {
1171        let adapter = GeminiSchemaAdapter::new();
1172        let schema = json!({
1173            "type": "object",
1174            "properties": {
1175                "self_ref": { "$ref": "#/definitions/Node" }
1176            },
1177            "definitions": {
1178                "Node": {
1179                    "type": "object",
1180                    "properties": {
1181                        "child": { "$ref": "#/definitions/Node" }
1182                    }
1183                }
1184            }
1185        });
1186        let result = adapter.normalize_schema(schema);
1187        // Should not panic and should terminate
1188        assert_eq!(result["properties"]["self_ref"]["type"], "object");
1189        assert!(result.get("definitions").is_none());
1190    }
1191
1192    #[test]
1193    fn test_removes_definitions_and_defs() {
1194        let adapter = GeminiSchemaAdapter::new();
1195        let schema = json!({
1196            "type": "object",
1197            "definitions": { "Foo": { "type": "string" } },
1198            "$defs": { "Bar": { "type": "number" } }
1199        });
1200        let result = adapter.normalize_schema(schema);
1201        assert!(result.get("definitions").is_none());
1202        assert!(result.get("$defs").is_none());
1203    }
1204
1205    #[test]
1206    fn test_nested_unsupported_keywords_removed() {
1207        let adapter = GeminiSchemaAdapter::new();
1208        let schema = json!({
1209            "type": "object",
1210            "properties": {
1211                "inner": {
1212                    "type": "object",
1213                    "additionalProperties": false,
1214                    "exclusiveMinimum": 5,
1215                    "properties": {
1216                        "deep": {
1217                            "type": "number",
1218                            "exclusiveMaximum": 100
1219                        }
1220                    }
1221                }
1222            }
1223        });
1224        let result = adapter.normalize_schema(schema);
1225        let inner = &result["properties"]["inner"];
1226        assert!(inner.get("additionalProperties").is_none());
1227        assert!(inner.get("exclusiveMinimum").is_none());
1228        assert!(inner["properties"]["deep"].get("exclusiveMaximum").is_none());
1229    }
1230
1231    #[test]
1232    fn test_full_transform_pipeline() {
1233        let adapter = GeminiSchemaAdapter::new();
1234        let schema = json!({
1235            "$schema": "http://json-schema.org/draft-07/schema#",
1236            "definitions": {
1237                "Status": { "type": "string", "enum": ["active", null, "inactive"] }
1238            },
1239            "properties": {
1240                "name": { "type": ["string", "null"], "format": "hostname" },
1241                "status": { "$ref": "#/definitions/Status" },
1242                "config": {
1243                    "type": "object",
1244                    "additionalProperties": true,
1245                    "properties": {
1246                        "value": { "const": "fixed" }
1247                    }
1248                }
1249            },
1250            "if": { "properties": { "name": { "type": "string" } } },
1251            "then": { "required": ["status"] },
1252            "additionalProperties": false
1253        });
1254        let result = adapter.normalize_schema(schema);
1255
1256        // $schema removed
1257        assert!(result.get("$schema").is_none());
1258        // definitions removed
1259        assert!(result.get("definitions").is_none());
1260        // conditional keywords removed
1261        assert!(result.get("if").is_none());
1262        assert!(result.get("then").is_none());
1263        // additionalProperties removed
1264        assert!(result.get("additionalProperties").is_none());
1265        // type array collapsed
1266        assert_eq!(result["properties"]["name"]["type"], "string");
1267        // unsupported format stripped
1268        assert!(result["properties"]["name"].get("format").is_none());
1269        // $ref resolved and null stripped from enum
1270        assert_eq!(result["properties"]["status"]["enum"], json!(["active", "inactive"]));
1271        // const converted to enum
1272        assert_eq!(result["properties"]["config"]["properties"]["value"]["enum"], json!(["fixed"]));
1273        // nested additionalProperties removed
1274        assert!(result["properties"]["config"].get("additionalProperties").is_none());
1275        // implicit type added
1276        assert_eq!(result["type"], "object");
1277    }
1278
1279    #[test]
1280    fn test_idempotent() {
1281        let adapter = GeminiSchemaAdapter::new();
1282        let schema = json!({
1283            "$schema": "http://json-schema.org/draft-07/schema#",
1284            "type": "object",
1285            "properties": {
1286                "name": { "type": ["string", "null"], "format": "hostname" },
1287                "items": { "type": "array", "items": { "type": "string" } }
1288            },
1289            "additionalProperties": true,
1290            "if": { "const": true },
1291            "then": { "required": ["name"] }
1292        });
1293        let first = adapter.normalize_schema(schema);
1294        let second = adapter.normalize_schema(first.clone());
1295        assert_eq!(first, second);
1296    }
1297
1298    #[test]
1299    fn test_empty_schema() {
1300        let adapter = GeminiSchemaAdapter::new();
1301        let schema = json!({});
1302        let result = adapter.normalize_schema(schema);
1303        assert_eq!(result, json!({}));
1304    }
1305
1306    #[test]
1307    fn test_array_items_nested_cleanup() {
1308        let adapter = GeminiSchemaAdapter::new();
1309        let schema = json!({
1310            "type": "array",
1311            "items": {
1312                "type": "object",
1313                "additionalProperties": true,
1314                "properties": {
1315                    "id": { "type": "integer", "exclusiveMinimum": 0 }
1316                }
1317            }
1318        });
1319        let result = adapter.normalize_schema(schema);
1320        assert!(result["items"].get("additionalProperties").is_none());
1321        assert!(result["items"]["properties"]["id"].get("exclusiveMinimum").is_none());
1322    }
1323
1324    // --- Task 4.2: Vertex AI surface variant tests ---
1325
1326    #[test]
1327    fn test_vertex_ai_sets_additional_properties_false() {
1328        let adapter = GeminiSchemaAdapter::vertex_ai();
1329        let schema = json!({
1330            "type": "object",
1331            "properties": { "name": { "type": "string" } },
1332            "additionalProperties": true
1333        });
1334        let result = adapter.normalize_schema(schema);
1335        assert_eq!(result["additionalProperties"], json!(false));
1336    }
1337
1338    #[test]
1339    fn test_vertex_ai_sets_additional_properties_false_on_nested_objects() {
1340        let adapter = GeminiSchemaAdapter::vertex_ai();
1341        let schema = json!({
1342            "type": "object",
1343            "properties": {
1344                "inner": {
1345                    "type": "object",
1346                    "properties": {
1347                        "value": { "type": "string" }
1348                    }
1349                }
1350            }
1351        });
1352        let result = adapter.normalize_schema(schema);
1353        assert_eq!(result["additionalProperties"], json!(false));
1354        assert_eq!(result["properties"]["inner"]["additionalProperties"], json!(false));
1355    }
1356
1357    #[test]
1358    fn test_vertex_ai_does_not_set_additional_properties_on_non_object() {
1359        let adapter = GeminiSchemaAdapter::vertex_ai();
1360        let schema = json!({
1361            "type": "string",
1362            "additionalProperties": true
1363        });
1364        let result = adapter.normalize_schema(schema);
1365        // Non-object schemas should have additionalProperties removed
1366        assert!(result.get("additionalProperties").is_none());
1367    }
1368
1369    #[test]
1370    fn test_standard_mode_removes_additional_properties() {
1371        let adapter = GeminiSchemaAdapter::new();
1372        let schema = json!({
1373            "type": "object",
1374            "properties": { "name": { "type": "string" } },
1375            "additionalProperties": true
1376        });
1377        let result = adapter.normalize_schema(schema);
1378        assert!(result.get("additionalProperties").is_none());
1379    }
1380
1381    #[test]
1382    fn test_vertex_ai_still_removes_other_unsupported_keywords() {
1383        let adapter = GeminiSchemaAdapter::vertex_ai();
1384        let schema = json!({
1385            "type": "object",
1386            "properties": { "x": { "type": "number" } },
1387            "exclusiveMinimum": 0,
1388            "exclusiveMaximum": 100,
1389            "not": { "type": "null" },
1390            "propertyNames": { "pattern": "^[a-z]" },
1391            "patternProperties": { "^S_": { "type": "string" } },
1392            "unevaluatedProperties": false
1393        });
1394        let result = adapter.normalize_schema(schema);
1395        assert!(result.get("exclusiveMinimum").is_none());
1396        assert!(result.get("exclusiveMaximum").is_none());
1397        assert!(result.get("not").is_none());
1398        assert!(result.get("propertyNames").is_none());
1399        assert!(result.get("patternProperties").is_none());
1400        assert!(result.get("unevaluatedProperties").is_none());
1401        // But additionalProperties: false is set
1402        assert_eq!(result["additionalProperties"], json!(false));
1403    }
1404
1405    // --- Task 4.3: normalize_tool_name tests ---
1406
1407    #[test]
1408    fn test_normalize_tool_name_short_name_unchanged() {
1409        let adapter = GeminiSchemaAdapter::new();
1410        let name = "get_weather";
1411        let result = adapter.normalize_tool_name(name);
1412        assert_eq!(result, "get_weather");
1413        assert!(matches!(result, Cow::Borrowed(_)));
1414    }
1415
1416    #[test]
1417    fn test_normalize_tool_name_exactly_64_bytes() {
1418        let adapter = GeminiSchemaAdapter::new();
1419        let name = "a".repeat(64);
1420        let result = adapter.normalize_tool_name(&name);
1421        assert_eq!(result.len(), 64);
1422        assert!(matches!(result, Cow::Borrowed(_)));
1423    }
1424
1425    #[test]
1426    fn test_normalize_tool_name_truncates_at_64_bytes() {
1427        let adapter = GeminiSchemaAdapter::new();
1428        let name = "a".repeat(100);
1429        let result = adapter.normalize_tool_name(&name);
1430        assert_eq!(result.len(), 64);
1431        assert_eq!(result.as_ref(), "a".repeat(64));
1432    }
1433
1434    #[test]
1435    fn test_normalize_tool_name_multibyte_boundary() {
1436        let adapter = GeminiSchemaAdapter::new();
1437        // Each '日' is 3 bytes in UTF-8. 21 chars = 63 bytes.
1438        // Adding one more '日' would be 66 bytes, so truncation should stop at 63.
1439        let name = "日".repeat(22); // 66 bytes
1440        let result = adapter.normalize_tool_name(&name);
1441        assert!(result.len() <= 64);
1442        // Should be 63 bytes (21 chars × 3 bytes)
1443        assert_eq!(result.len(), 63);
1444        assert_eq!(result.as_ref(), "日".repeat(21));
1445        // Verify it's valid UTF-8
1446        assert!(std::str::from_utf8(result.as_bytes()).is_ok());
1447    }
1448
1449    #[test]
1450    fn test_normalize_tool_name_emoji_boundary() {
1451        let adapter = GeminiSchemaAdapter::new();
1452        // '🎯' is 4 bytes. 16 emojis = 64 bytes exactly.
1453        let name = "🎯".repeat(16);
1454        assert_eq!(name.len(), 64);
1455        let result = adapter.normalize_tool_name(&name);
1456        assert_eq!(result.len(), 64);
1457
1458        // 17 emojis = 68 bytes, should truncate to 16 emojis = 64 bytes
1459        let name = "🎯".repeat(17);
1460        let result = adapter.normalize_tool_name(&name);
1461        assert_eq!(result.len(), 64);
1462        assert_eq!(result.as_ref(), "🎯".repeat(16));
1463    }
1464
1465    // --- Task 4.4: empty_schema tests ---
1466
1467    #[test]
1468    fn test_empty_schema_returns_object_with_properties() {
1469        let adapter = GeminiSchemaAdapter::new();
1470        let result = adapter.empty_schema();
1471        assert_eq!(result, json!({"type": "object", "properties": {}}));
1472    }
1473
1474    #[test]
1475    fn test_empty_schema_vertex_ai_same_as_standard() {
1476        let adapter = GeminiSchemaAdapter::vertex_ai();
1477        let result = adapter.empty_schema();
1478        assert_eq!(result, json!({"type": "object", "properties": {}}));
1479    }
1480
1481    // --- Comprehensive unsupported keyword stripping tests ---
1482    // These validate that ALL keywords not in Gemini's Schema proto are removed.
1483
1484    #[test]
1485    fn test_removes_unsupported_and_keeps_proto_bounds() {
1486        let adapter = GeminiSchemaAdapter::new();
1487        let schema = json!({
1488            "type": "object",
1489            "title": "MySchema",
1490            "$id": "https://example.com/schema",
1491            "default": {},
1492            "deprecated": true,
1493            "readOnly": true,
1494            "writeOnly": false,
1495            "examples": [{"name": "test"}],
1496            "minProperties": 1,
1497            "maxProperties": 10,
1498            "properties": {
1499                "name": {
1500                    "type": "string",
1501                    "title": "Name",
1502                    "default": "",
1503                    "minLength": 1,
1504                    "maxLength": 100,
1505                    "pattern": "^[a-z]+$"
1506                },
1507                "age": {
1508                    "type": "integer",
1509                    "minimum": 0,
1510                    "maximum": 150,
1511                    "multipleOf": 1
1512                },
1513                "tags": {
1514                    "type": "array",
1515                    "items": { "type": "string" },
1516                    "minItems": 1,
1517                    "maxItems": 10,
1518                    "uniqueItems": true,
1519                    "contains": { "type": "string" }
1520                }
1521            }
1522        });
1523        let result = adapter.normalize_schema(schema);
1524
1525        // Top-level annotation/validation keywords removed
1526        assert!(result.get("title").is_none());
1527        assert!(result.get("$id").is_none());
1528        assert!(result.get("default").is_none());
1529        assert!(result.get("deprecated").is_none());
1530        assert!(result.get("readOnly").is_none());
1531        assert!(result.get("writeOnly").is_none());
1532        assert!(result.get("examples").is_none());
1533        assert!(result.get("minProperties").is_none());
1534        assert!(result.get("maxProperties").is_none());
1535
1536        // String property: annotations removed, the proto's string bounds kept
1537        let name = &result["properties"]["name"];
1538        assert!(name.get("title").is_none());
1539        assert!(name.get("default").is_none());
1540        assert_eq!(name["minLength"], 1);
1541        assert_eq!(name["maxLength"], 100);
1542        assert_eq!(name["pattern"], "^[a-z]+$");
1543        assert_eq!(name["type"], "string");
1544
1545        // Integer property: inclusive bounds kept, `multipleOf` removed
1546        let age = &result["properties"]["age"];
1547        assert_eq!(age["minimum"], 0);
1548        assert_eq!(age["maximum"], 150);
1549        assert!(age.get("multipleOf").is_none());
1550        assert_eq!(age["type"], "integer");
1551
1552        // Array property: item-count bounds kept, other array keywords removed
1553        let tags = &result["properties"]["tags"];
1554        assert_eq!(tags["minItems"], 1);
1555        assert_eq!(tags["maxItems"], 10);
1556        assert!(tags.get("uniqueItems").is_none());
1557        assert!(tags.get("contains").is_none());
1558        assert_eq!(tags["type"], "array");
1559        assert_eq!(tags["items"]["type"], "string");
1560    }
1561
1562    /// Every bound the Schema proto defines survives both OpenAPI-subset
1563    /// dialects; the exclusive bounds, which it does not define, do not.
1564    #[test]
1565    fn openapi_subset_dialects_keep_the_bounds_the_proto_defines() {
1566        let schema = json!({
1567            "type": "object",
1568            "properties": {
1569                "room": {"type": "string", "minLength": 2, "maxLength": 4, "pattern": "^[A-Z][0-9]$"},
1570                "count": {"type": "integer", "minimum": 1, "maximum": 10, "exclusiveMaximum": 11},
1571                "tags": {"type": "array", "items": {"type": "string"}, "minItems": 0, "maxItems": 3}
1572            }
1573        });
1574        for adapter in [GeminiSchemaAdapter::new(), GeminiSchemaAdapter::vertex_ai()] {
1575            let properties = &adapter.normalize_schema(schema.clone())["properties"];
1576            assert_eq!(properties["room"]["minLength"], 2);
1577            assert_eq!(properties["room"]["maxLength"], 4);
1578            assert_eq!(properties["room"]["pattern"], "^[A-Z][0-9]$");
1579            assert_eq!(properties["count"]["minimum"], 1);
1580            assert_eq!(properties["count"]["maximum"], 10);
1581            assert!(properties["count"].get("exclusiveMaximum").is_none());
1582            assert_eq!(properties["tags"]["minItems"], 0);
1583            assert_eq!(properties["tags"]["maxItems"], 3);
1584        }
1585    }
1586
1587    /// A field's own description sits beside its `$ref`; inlining the
1588    /// definition keeps it, and the inlined fields keep their bounds.
1589    #[test]
1590    fn ref_sibling_description_survives_inlining() {
1591        let schema = json!({
1592            "type": "object",
1593            "properties": {
1594                "confirm_to": {"$ref": "#/$defs/Address", "description": "Where to post it."},
1595                "home": {"$ref": "#/$defs/Address"}
1596            },
1597            "$defs": {
1598                "Address": {
1599                    "type": "object",
1600                    "description": "A postal address.",
1601                    "properties": {"city": {"type": "string", "maxLength": 40}},
1602                    "additionalProperties": false
1603                }
1604            }
1605        });
1606        let result = GeminiSchemaAdapter::new().normalize_schema(schema);
1607        let confirm_to = &result["properties"]["confirm_to"];
1608        assert_eq!(confirm_to["description"], "Where to post it.");
1609        assert_eq!(confirm_to["properties"]["city"]["maxLength"], 40);
1610        assert!(confirm_to.get("$ref").is_none());
1611        assert!(confirm_to.get("additionalProperties").is_none());
1612        assert_eq!(result["properties"]["home"]["description"], "A postal address.");
1613        assert!(result.get("$defs").is_none());
1614    }
1615
1616    #[test]
1617    fn test_removes_prefix_items() {
1618        let adapter = GeminiSchemaAdapter::new();
1619        let schema = json!({
1620            "type": "array",
1621            "prefixItems": [
1622                { "type": "string" },
1623                { "type": "integer" }
1624            ]
1625        });
1626        let result = adapter.normalize_schema(schema);
1627        assert!(result.get("prefixItems").is_none());
1628    }
1629
1630    #[test]
1631    fn test_removes_dependent_keywords() {
1632        let adapter = GeminiSchemaAdapter::new();
1633        let schema = json!({
1634            "type": "object",
1635            "properties": {
1636                "name": { "type": "string" },
1637                "credit_card": { "type": "string" }
1638            },
1639            "dependentRequired": {
1640                "credit_card": ["billing_address"]
1641            },
1642            "dependentSchemas": {
1643                "credit_card": {
1644                    "properties": {
1645                        "billing_address": { "type": "string" }
1646                    }
1647                }
1648            }
1649        });
1650        let result = adapter.normalize_schema(schema);
1651        assert!(result.get("dependentRequired").is_none());
1652        assert!(result.get("dependentSchemas").is_none());
1653    }
1654
1655    #[test]
1656    fn test_removes_content_keywords() {
1657        let adapter = GeminiSchemaAdapter::new();
1658        let schema = json!({
1659            "type": "string",
1660            "contentMediaType": "application/json",
1661            "contentEncoding": "base64"
1662        });
1663        let result = adapter.normalize_schema(schema);
1664        assert!(result.get("contentMediaType").is_none());
1665        assert!(result.get("contentEncoding").is_none());
1666    }
1667
1668    // --- Dialect selection -------------------------------------------------
1669
1670    /// The mapping that makes the reduction and the wire field one decision.
1671    #[test]
1672    fn parameters_field_follows_the_dialect() {
1673        assert_eq!(GeminiSchemaAdapter::new().parameters_field(), "parameters");
1674        assert_eq!(GeminiSchemaAdapter::vertex_ai().parameters_field(), "parameters");
1675        assert_eq!(GeminiSchemaAdapter::json_schema().parameters_field(), "parametersJsonSchema");
1676        // The default must stay the legacy field: it is what every existing
1677        // caller gets without asking.
1678        assert_eq!(GeminiSchemaDialect::default(), GeminiSchemaDialect::OpenApiSubset);
1679    }
1680
1681    /// A realistic acquisition schema: a conditional rule, a closed object, and
1682    /// a bounded string. The OpenAPI subset cannot carry the first two, so it
1683    /// strips them; the JSON Schema dialect keeps all three.
1684    fn schema_with_constraints_the_subset_cannot_carry() -> Value {
1685        json!({
1686            "type": "object",
1687            "additionalProperties": false,
1688            "properties": {
1689                "request_kind": {"type": "string", "enum": ["order", "information"]},
1690                "callback_number": {"type": "string", "minLength": 7},
1691                "party_size": {"type": "integer", "minimum": 1, "maximum": 40}
1692            },
1693            "required": ["request_kind"],
1694            "allOf": [{
1695                "if": {"properties": {"request_kind": {"const": "order"}}, "required": ["request_kind"]},
1696                "then": {"required": ["callback_number"]}
1697            }]
1698        })
1699    }
1700
1701    #[test]
1702    fn json_schema_dialect_keeps_what_the_subset_strips() {
1703        let result = GeminiSchemaAdapter::json_schema()
1704            .normalize_schema(schema_with_constraints_the_subset_cannot_carry());
1705
1706        assert_eq!(result["additionalProperties"], json!(false));
1707        assert!(result.get("allOf").is_some(), "conditional rule dropped: {result}");
1708        assert_eq!(result["properties"]["callback_number"]["minLength"], 7);
1709        assert_eq!(result["properties"]["party_size"]["minimum"], 1);
1710        assert_eq!(result["properties"]["party_size"]["maximum"], 40);
1711    }
1712
1713    /// `add_implicit_object_type` is skipped for JSON Schema because it is
1714    /// actively wrong there, not merely redundant: it stamps `type: "object"`
1715    /// onto every schema-shaped node it walks, including an `if` clause, which
1716    /// changes what that clause matches.
1717    #[test]
1718    fn json_schema_dialect_does_not_stamp_a_type_onto_conditionals() {
1719        let result = GeminiSchemaAdapter::json_schema()
1720            .normalize_schema(schema_with_constraints_the_subset_cannot_carry());
1721
1722        let if_clause = &result["allOf"][0]["if"];
1723        assert!(
1724            if_clause.get("type").is_none(),
1725            "an implicit object type was injected into the `if` clause: {if_clause}"
1726        );
1727    }
1728
1729    /// The two OpenAPI-subset constructors still post under the legacy field
1730    /// and still reduce away what the subset cannot express, while keeping the
1731    /// bounds it can.
1732    #[test]
1733    fn openapi_subset_dialects_reduce_what_the_subset_cannot_carry() {
1734        for adapter in [GeminiSchemaAdapter::new(), GeminiSchemaAdapter::vertex_ai()] {
1735            assert_eq!(adapter.parameters_field(), "parameters");
1736
1737            let result =
1738                adapter.normalize_schema(schema_with_constraints_the_subset_cannot_carry());
1739
1740            assert!(result.get("allOf").is_none(), "{result}");
1741            assert_eq!(result["properties"]["callback_number"]["minLength"], 7);
1742            assert_eq!(result["properties"]["party_size"]["minimum"], 1);
1743            assert_eq!(result["properties"]["party_size"]["maximum"], 40);
1744        }
1745    }
1746
1747    /// The declaration that Gemini rejected with a 400 before step 3 and step 9 existed:
1748    /// a boolean subschema and a numeric enum, beside a nullable string, a union and a map.
1749    fn schema_beyond_the_subset() -> Value {
1750        json!({
1751            "type": "object",
1752            "properties": {
1753                "priority": { "type": "integer", "enum": [1, 2, 3] },
1754                "level": { "enum": [1, 2, null] },
1755                "note": { "type": ["string", "null"] },
1756                "owner": { "anyOf": [{ "type": "string" }, { "type": "null" }] },
1757                "reference": { "oneOf": [{ "type": "string" }, { "type": "integer" }] },
1758                "code": { "type": ["string", "integer"] },
1759                "labels": { "type": "object", "additionalProperties": { "type": "integer" } },
1760                "extra": true,
1761                "forbidden": false,
1762                "tags": { "type": "array", "items": true }
1763            },
1764            "required": ["priority", "forbidden"]
1765        })
1766    }
1767
1768    #[test]
1769    fn openapi_subset_dialects_carry_nullability_unions_enums_and_maps() {
1770        for adapter in [GeminiSchemaAdapter::new(), GeminiSchemaAdapter::vertex_ai()] {
1771            let result = adapter.normalize_schema(schema_beyond_the_subset());
1772            let props = &result["properties"];
1773
1774            assert_eq!(props["priority"], json!({ "type": "integer", "enum": ["1", "2", "3"] }));
1775            assert_eq!(
1776                props["level"],
1777                json!({ "type": "integer", "enum": ["1", "2"], "nullable": true })
1778            );
1779            assert_eq!(props["note"], json!({ "type": "string", "nullable": true }));
1780            assert_eq!(props["owner"], json!({ "type": "string", "nullable": true }));
1781            assert_eq!(
1782                props["reference"],
1783                json!({ "anyOf": [{ "type": "string" }, { "type": "integer" }] })
1784            );
1785            assert_eq!(
1786                props["code"],
1787                json!({ "anyOf": [{ "type": "string" }, { "type": "integer" }] })
1788            );
1789            assert_eq!(
1790                props["labels"]["description"],
1791                "An object mapping string keys to integer values."
1792            );
1793            assert_eq!(props["extra"], json!({}));
1794            assert!(props.get("forbidden").is_none(), "{result}");
1795            assert_eq!(result["required"], json!(["priority"]));
1796            assert_eq!(props["tags"]["items"], json!({}));
1797        }
1798    }
1799
1800    #[test]
1801    fn a_map_description_keeps_the_fields_own_text() {
1802        let result = GeminiSchemaAdapter::new().normalize_schema(json!({
1803            "type": "object",
1804            "description": "Label counts.",
1805            "additionalProperties": { "type": "integer" }
1806        }));
1807        assert_eq!(
1808            result,
1809            json!({
1810                "type": "object",
1811                "description": "Label counts. An object mapping string keys to integer values."
1812            })
1813        );
1814    }
1815
1816    #[test]
1817    fn the_reductions_are_idempotent() {
1818        for adapter in [GeminiSchemaAdapter::new(), GeminiSchemaAdapter::vertex_ai()] {
1819            let first = adapter.normalize_schema(schema_beyond_the_subset());
1820            assert_eq!(adapter.normalize_schema(first.clone()), first);
1821        }
1822    }
1823
1824    #[test]
1825    fn json_schema_dialect_leaves_booleans_unions_and_enums_alone() {
1826        let result =
1827            GeminiSchemaAdapter::json_schema().normalize_schema(schema_beyond_the_subset());
1828        let props = &result["properties"];
1829        assert_eq!(props["extra"], json!(true));
1830        assert_eq!(props["priority"]["enum"], json!([1, 2, 3]));
1831        assert_eq!(props["note"]["type"], json!(["string", "null"]));
1832    }
1833}