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