1use serde_json::Value;
5
6use super::model::{AgentResponse, questions_field_description, subtasks_field_description};
7use super::review::FocusedReview;
8
9#[derive(Clone, Copy, Debug, Eq, PartialEq)]
18pub enum SchemaRequiredPolicy {
19 AllProperties,
21 MinimumProtocolKeys,
23}
24
25pub 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
38pub fn agent_response_json_schema_json() -> String {
44 let schema = agent_response_json_schema();
45
46 stringify_schema_json(&schema)
47}
48
49pub 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
60pub fn focused_review_json_schema_json() -> String {
66 let schema_value = focused_review_json_schema();
67
68 stringify_schema_json(&schema_value)
69}
70
71pub 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
80pub 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
92pub(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
101fn 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
111fn 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
127fn 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
149fn 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
180fn 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
210fn 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
269fn 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
283fn 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
317fn 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;