1use serde_json::Value;
5
6use super::model::{
7 AgentResponse, ProtocolRequestProfile, ReviewMetadata, UtilityResponse,
8 questions_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 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
158fn 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
189fn 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
219fn 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
278fn 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
292fn 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
326fn 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;