1use 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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21pub enum SchemaRequiredPolicy {
22 AllProperties,
24 MinimumProtocolKeys,
26}
27
28pub 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
41pub fn agent_response_json_schema_json() -> String {
47 let schema = agent_response_json_schema();
48
49 stringify_schema_json(&schema)
50}
51
52pub 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
63pub fn focused_review_json_schema_json() -> String {
69 let schema_value = focused_review_json_schema();
70
71 stringify_schema_json(&schema_value)
72}
73
74pub 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
83pub 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
94pub(crate) fn protocol_json_schema_json(profile: ProtocolRequestProfile) -> String {
96 stringify_schema_json(&protocol_schema(profile))
97}
98
99fn 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
113fn 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
123fn 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
139fn 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
161fn 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
192fn 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
222fn 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
281fn 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
295fn 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
329fn 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;