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, subtasks_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    for (property_name, description) in [
147        ("questions", questions_field_description()),
148        ("subtasks", subtasks_field_description()),
149    ] {
150        let Some(property) = properties
151            .get_mut(property_name)
152            .and_then(Value::as_object_mut)
153        else {
154            continue;
155        };
156
157        property.insert("description".to_string(), Value::String(description));
158    }
159}
160
161/// Recursively injects `additionalProperties: false` into every schema object
162/// that declares `properties` and does not already set `additionalProperties`.
163///
164/// Most wire-format structs omit `#[serde(deny_unknown_fields)]` so their
165/// deserialization tolerates extra fields that LLM providers sometimes add.
166/// Focused-review structs are stricter because their dedicated parser must
167/// match the direct transport schema. This function restores the
168/// `additionalProperties: false` constraint elsewhere so prompt-level guidance
169/// still tells models not to add extra fields. Pre-existing
170/// `additionalProperties` values (e.g. on map-like schema fields) are
171/// preserved.
172fn inject_additional_properties_false(value: &mut Value) {
173    match value {
174        Value::Object(object) => {
175            if object.contains_key("properties") && !object.contains_key("additionalProperties") {
176                object.insert("additionalProperties".to_string(), Value::Bool(false));
177            }
178
179            for nested_value in object.values_mut() {
180                inject_additional_properties_false(nested_value);
181            }
182        }
183        Value::Array(array) => {
184            for nested_value in array {
185                inject_additional_properties_false(nested_value);
186            }
187        }
188        _ => {}
189    }
190}
191
192/// Ensures the top-level `required` array includes `answer` so the prompt
193/// schema rejects `{}` the same way the parser does.
194///
195/// The parser requires at least one recognized protocol key. The schema is
196/// intentionally stricter: it
197/// requires `answer` specifically, because models should always include it.
198/// If a model omits `answer` but includes another recognized key, the
199/// parser still accepts the payload gracefully thanks to `#[serde(default)]`.
200fn inject_minimum_required_protocol_key(schema: &mut Value) {
201    let Some(object) = schema.as_object_mut() else {
202        return;
203    };
204
205    let required = object
206        .entry("required")
207        .or_insert_with(|| Value::Array(Vec::new()));
208
209    let Some(required_array) = required.as_array_mut() else {
210        return;
211    };
212
213    let already_listed = required_array
214        .iter()
215        .any(|value| value.as_str() == Some("answer"));
216
217    if !already_listed {
218        required_array.push(Value::String("answer".to_string()));
219    }
220}
221
222/// Normalizes one schema tree for transport-level provider compatibility.
223///
224/// Claude rejects schemas with a top-level `$schema` URI when its validator
225/// cannot resolve that meta-schema. Codex rejects schemas that use `oneOf` for
226/// enum-like constants. Schemars can emit both shapes, so this normalizer
227/// strips transport-only metadata and rewrites enum fragments to string `enum`
228/// definitions. `required_policy` decides whether optional properties are also
229/// forced into `required`.
230fn normalize_schema_for_transport(value: &mut Value, required_policy: SchemaRequiredPolicy) {
231    match value {
232        Value::Object(object) => {
233            object.remove("$schema");
234
235            for nested_value in object.values_mut() {
236                normalize_schema_for_transport(nested_value, required_policy);
237            }
238
239            normalize_ref_object_for_codex(object);
240            if required_policy == SchemaRequiredPolicy::AllProperties {
241                normalize_required_for_codex(object);
242            }
243
244            let one_of_values = object
245                .get("oneOf")
246                .and_then(Value::as_array)
247                .map(|items| {
248                    items
249                        .iter()
250                        .filter_map(Value::as_object)
251                        .map(|item| item.get("const").and_then(Value::as_str))
252                        .collect::<Option<Vec<_>>>()
253                })
254                .map(|option| {
255                    option.map(|values| {
256                        values
257                            .into_iter()
258                            .map(ToString::to_string)
259                            .collect::<Vec<_>>()
260                    })
261                });
262
263            if let Some(Some(enum_variants)) = one_of_values {
264                object.remove("oneOf");
265                object.insert("type".to_string(), Value::String("string".to_string()));
266                object.insert(
267                    "enum".to_string(),
268                    Value::Array(enum_variants.into_iter().map(Value::String).collect()),
269                );
270            }
271        }
272        Value::Array(array) => {
273            for nested_value in array {
274                normalize_schema_for_transport(nested_value, required_policy);
275            }
276        }
277        _ => {}
278    }
279}
280
281/// Rewrites one `$ref` schema object to Codex-compatible form.
282///
283/// Codex rejects sibling keywords alongside `$ref` (for example
284/// `{ "$ref": "...", "description": "..." }`), so this keeps only the
285/// reference key when present.
286fn normalize_ref_object_for_codex(object: &mut serde_json::Map<String, Value>) {
287    let Some(reference) = object.get("$ref").cloned() else {
288        return;
289    };
290
291    object.clear();
292    object.insert("$ref".to_string(), reference);
293}
294
295/// Ensures all `properties` keys appear in `required` for Codex compatibility.
296///
297/// Codex rejects schemas where `properties` contains keys not listed in
298/// `required`. Schemars omits optional fields from `required`, so this
299/// normalizer adds any missing property keys.
300fn normalize_required_for_codex(object: &mut serde_json::Map<String, Value>) {
301    let Some(properties) = object.get("properties").and_then(Value::as_object) else {
302        return;
303    };
304
305    let property_keys: Vec<String> = properties.keys().cloned().collect();
306    if property_keys.is_empty() {
307        return;
308    }
309
310    let required = object
311        .entry("required")
312        .or_insert_with(|| Value::Array(Vec::new()));
313
314    let Some(required_array) = required.as_array_mut() else {
315        return;
316    };
317
318    for key in &property_keys {
319        let already_listed = required_array
320            .iter()
321            .any(|value| value.as_str() == Some(key));
322
323        if !already_listed {
324            required_array.push(Value::String(key.clone()));
325        }
326    }
327}
328
329/// Pretty-prints one schema document for prompt or transport wiring.
330fn stringify_schema_json(schema: &Value) -> String {
331    serde_json::to_string_pretty(schema).unwrap_or("null".to_string())
332}
333
334#[cfg(test)]
335#[path = "schema_test.rs"]
336mod tests;