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