Skip to main content

ag_protocol/
schema.rs

1//! JSON Schema generation and transport-compatibility normalization for the
2//! structured response protocol.
3
4use serde_json::Value;
5
6use super::graph_proposal::GraphProposalResponse;
7use super::model::{
8    AgentResponse, ProtocolRequestProfile, ReviewMetadata, UtilityResponse,
9    questions_field_description,
10};
11use super::review::FocusedReview;
12
13/// Selects how a provider transport lists `required` schema properties.
14///
15/// Providers disagree on what a valid schema looks like. Codex rejects schemas
16/// whose `properties` contain keys missing from `required`, so it needs every
17/// key listed. Validators that enforce `required` literally, such as Claude,
18/// must only demand `answer`; listing optional keys there rejects ordinary
19/// replies that omit optional array fields, even though the parser accepts
20/// them through `#[serde(default)]`.
21#[derive(Clone, Copy, Debug, Eq, PartialEq)]
22pub enum SchemaRequiredPolicy {
23    /// Lists every `properties` key in `required` for Codex compatibility.
24    AllProperties,
25    /// Lists only the minimum protocol keys the parser insists on.
26    MinimumProtocolKeys,
27}
28
29/// Returns the JSON Schema used for structured assistant output.
30///
31/// The returned value is passed directly to providers that support enforced
32/// output schemas. It starts from the self-descriptive response schema and then
33/// applies compatibility normalization required by schema-enforcing agents.
34/// `required_policy` selects how strictly optional protocol keys are demanded.
35pub fn agent_response_output_schema(required_policy: SchemaRequiredPolicy) -> Value {
36    let mut value = agent_response_json_schema();
37    normalize_schema_for_transport(&mut value, required_policy);
38
39    value
40}
41
42/// Returns the output schema selected for one protocol request profile.
43pub fn protocol_output_schema(
44    profile: super::model::ProtocolRequestProfile,
45    required_policy: SchemaRequiredPolicy,
46) -> Value {
47    let mut schema = protocol_schema(profile);
48    normalize_schema_for_transport(&mut schema, required_policy);
49
50    schema
51}
52
53/// Returns the prompt-facing schema selected for one protocol request profile.
54pub(crate) fn protocol_json_schema_json(profile: ProtocolRequestProfile) -> String {
55    stringify_schema_json(&protocol_schema(profile))
56}
57
58/// Selects a task-specific schema before provider normalization.
59fn protocol_schema(profile: ProtocolRequestProfile) -> Value {
60    match profile {
61        ProtocolRequestProfile::FocusedReview => focused_review_json_schema(),
62        ProtocolRequestProfile::GraphProposal => {
63            let mut schema = serde_json::json!(schemars::schema_for!(GraphProposalResponse));
64            normalize_proposal_unions(&mut schema);
65            inject_additional_properties_false(&mut schema);
66
67            schema
68        }
69        ProtocolRequestProfile::SessionTurn => agent_response_json_schema(),
70        ProtocolRequestProfile::UtilityPrompt => {
71            serde_json::json!(schemars::schema_for!(UtilityResponse))
72        }
73        ProtocolRequestProfile::ReviewMetadata => {
74            serde_json::json!(schemars::schema_for!(ReviewMetadata))
75        }
76    }
77}
78
79/// Tagged proposal variants are disjoint. `anyOf` preserves their meaning
80/// while avoiding `oneOf`, which structured-output transports do not support.
81fn normalize_proposal_unions(value: &mut Value) {
82    match value {
83        Value::Object(object) => {
84            if let Some(variants) = object.remove("oneOf") {
85                object.insert("anyOf".to_string(), variants);
86            }
87            for nested in object.values_mut() {
88                normalize_proposal_unions(nested);
89            }
90        }
91        Value::Array(items) => {
92            for item in items {
93                normalize_proposal_unions(item);
94            }
95        }
96        _ => {}
97    }
98}
99
100/// Returns the self-descriptive focused-review JSON Schema.
101fn focused_review_json_schema() -> Value {
102    let schema = schemars::schema_for!(FocusedReview);
103    let mut schema_value = serde_json::to_value(schema).unwrap_or(Value::Null);
104
105    inject_additional_properties_false(&mut schema_value);
106
107    schema_value
108}
109
110/// Returns the self-descriptive JSON Schema for the response payload.
111///
112/// This preserves the raw `schemars` output, including metadata such as
113/// `title` and `description`, so prompt templates can show models the richest
114/// possible schema contract.
115fn agent_response_json_schema() -> Value {
116    let schema = schemars::schema_for!(AgentResponse);
117    let mut schema_value = serde_json::to_value(schema).unwrap_or(Value::Null);
118
119    inject_dynamic_schema_guidance(&mut schema_value);
120    inject_additional_properties_false(&mut schema_value);
121    inject_minimum_required_protocol_key(&mut schema_value);
122
123    schema_value
124}
125
126/// Injects dynamic prompt guidance that depends on runtime constants into the
127/// schema metadata shown to providers.
128fn inject_dynamic_schema_guidance(schema: &mut Value) {
129    let Some(properties) = schema.get_mut("properties").and_then(Value::as_object_mut) else {
130        return;
131    };
132
133    let Some(property) = properties
134        .get_mut("questions")
135        .and_then(Value::as_object_mut)
136    else {
137        return;
138    };
139    property.insert(
140        "description".to_string(),
141        Value::String(questions_field_description()),
142    );
143}
144
145/// Recursively injects `additionalProperties: false` into every schema object
146/// that declares `properties` and does not already set `additionalProperties`.
147///
148/// Most wire-format structs omit `#[serde(deny_unknown_fields)]` so their
149/// deserialization tolerates extra fields that LLM providers sometimes add.
150/// Focused-review structs are stricter because their dedicated parser must
151/// match the direct transport schema. This function restores the
152/// `additionalProperties: false` constraint elsewhere so prompt-level guidance
153/// still tells models not to add extra fields. Pre-existing
154/// `additionalProperties` values (e.g. on map-like schema fields) are
155/// preserved.
156fn inject_additional_properties_false(value: &mut Value) {
157    match value {
158        Value::Object(object) => {
159            if object.contains_key("properties") && !object.contains_key("additionalProperties") {
160                object.insert("additionalProperties".to_string(), Value::Bool(false));
161            }
162
163            for nested_value in object.values_mut() {
164                inject_additional_properties_false(nested_value);
165            }
166        }
167        Value::Array(array) => {
168            for nested_value in array {
169                inject_additional_properties_false(nested_value);
170            }
171        }
172        _ => {}
173    }
174}
175
176/// Ensures the top-level `required` array includes `answer` so the prompt
177/// schema rejects `{}` the same way the parser does.
178///
179/// The parser requires at least one recognized protocol key. The schema is
180/// intentionally stricter: it
181/// requires `answer` specifically, because models should always include it.
182/// If a model omits `answer` but includes another recognized key, the
183/// parser still accepts the payload gracefully thanks to `#[serde(default)]`.
184fn inject_minimum_required_protocol_key(schema: &mut Value) {
185    let Some(object) = schema.as_object_mut() else {
186        return;
187    };
188
189    let required = object
190        .entry("required")
191        .or_insert_with(|| Value::Array(Vec::new()));
192
193    let Some(required_array) = required.as_array_mut() else {
194        return;
195    };
196
197    let already_listed = required_array
198        .iter()
199        .any(|value| value.as_str() == Some("answer"));
200
201    if !already_listed {
202        required_array.push(Value::String("answer".to_string()));
203    }
204}
205
206/// Normalizes one schema tree for transport-level provider compatibility.
207///
208/// Claude rejects schemas with a top-level `$schema` URI when its validator
209/// cannot resolve that meta-schema. Codex rejects schemas that use `oneOf` for
210/// enum-like constants. Schemars can emit both shapes, so this normalizer
211/// strips transport-only metadata and rewrites enum fragments to string `enum`
212/// definitions. `required_policy` decides whether optional properties are also
213/// forced into `required`.
214fn normalize_schema_for_transport(value: &mut Value, required_policy: SchemaRequiredPolicy) {
215    match value {
216        Value::Object(object) => {
217            object.remove("$schema");
218
219            for nested_value in object.values_mut() {
220                normalize_schema_for_transport(nested_value, required_policy);
221            }
222
223            normalize_ref_object_for_codex(object);
224            if required_policy == SchemaRequiredPolicy::AllProperties {
225                normalize_required_for_codex(object);
226            }
227
228            let one_of_values = object
229                .get("oneOf")
230                .and_then(Value::as_array)
231                .map(|items| {
232                    items
233                        .iter()
234                        .filter_map(Value::as_object)
235                        .map(|item| item.get("const").and_then(Value::as_str))
236                        .collect::<Option<Vec<_>>>()
237                })
238                .map(|option| {
239                    option.map(|values| {
240                        values
241                            .into_iter()
242                            .map(ToString::to_string)
243                            .collect::<Vec<_>>()
244                    })
245                });
246
247            if let Some(Some(enum_variants)) = one_of_values {
248                object.remove("oneOf");
249                object.insert("type".to_string(), Value::String("string".to_string()));
250                object.insert(
251                    "enum".to_string(),
252                    Value::Array(enum_variants.into_iter().map(Value::String).collect()),
253                );
254            }
255        }
256        Value::Array(array) => {
257            for nested_value in array {
258                normalize_schema_for_transport(nested_value, required_policy);
259            }
260        }
261        _ => {}
262    }
263}
264
265/// Rewrites one `$ref` schema object to Codex-compatible form.
266///
267/// Codex rejects sibling keywords alongside `$ref` (for example
268/// `{ "$ref": "...", "description": "..." }`), so this keeps only the
269/// reference key when present.
270fn normalize_ref_object_for_codex(object: &mut serde_json::Map<String, Value>) {
271    let Some(reference) = object.get("$ref").cloned() else {
272        return;
273    };
274
275    object.clear();
276    object.insert("$ref".to_string(), reference);
277}
278
279/// Ensures all `properties` keys appear in `required` for Codex compatibility.
280///
281/// Codex rejects schemas where `properties` contains keys not listed in
282/// `required`. Schemars omits optional fields from `required`, so this
283/// normalizer adds any missing property keys.
284fn normalize_required_for_codex(object: &mut serde_json::Map<String, Value>) {
285    let Some(properties) = object.get("properties").and_then(Value::as_object) else {
286        return;
287    };
288
289    let property_keys: Vec<String> = properties.keys().cloned().collect();
290    if property_keys.is_empty() {
291        return;
292    }
293
294    let required = object
295        .entry("required")
296        .or_insert_with(|| Value::Array(Vec::new()));
297
298    let Some(required_array) = required.as_array_mut() else {
299        return;
300    };
301
302    for key in &property_keys {
303        let already_listed = required_array
304            .iter()
305            .any(|value| value.as_str() == Some(key));
306
307        if !already_listed {
308            required_array.push(Value::String(key.clone()));
309        }
310    }
311}
312
313/// Pretty-prints one schema document for prompt or transport wiring.
314fn stringify_schema_json(schema: &Value) -> String {
315    serde_json::to_string_pretty(schema).unwrap_or("null".to_string())
316}
317
318#[cfg(test)]
319#[path = "schema_test.rs"]
320mod tests;