1use serde_json::Value;
5
6use super::graph_proposal::GraphProposalResponse;
7use super::model::{
8 AgentResponse, ProtocolRequestProfile, ReviewMetadata, UtilityResponse,
9 questions_field_description,
10};
11use super::review::FocusedReview;
12
13#[derive(Clone, Copy, Debug, Eq, PartialEq)]
22pub enum SchemaRequiredPolicy {
23 AllProperties,
25 MinimumProtocolKeys,
27}
28
29pub fn agent_response_output_schema(required_policy: SchemaRequiredPolicy) -> Value {
36 let mut value = agent_response_json_schema();
37 normalize_schema_for_transport(&mut value, required_policy);
38
39 value
40}
41
42pub fn protocol_output_schema(
44 profile: super::model::ProtocolRequestProfile,
45 required_policy: SchemaRequiredPolicy,
46) -> Value {
47 let mut schema = protocol_schema(profile);
48 normalize_schema_for_transport(&mut schema, required_policy);
49
50 schema
51}
52
53pub(crate) fn protocol_json_schema_json(profile: ProtocolRequestProfile) -> String {
55 stringify_schema_json(&protocol_schema(profile))
56}
57
58fn protocol_schema(profile: ProtocolRequestProfile) -> Value {
60 match profile {
61 ProtocolRequestProfile::FocusedReview => focused_review_json_schema(),
62 ProtocolRequestProfile::GraphProposal => {
63 let mut schema = serde_json::json!(schemars::schema_for!(GraphProposalResponse));
64 normalize_proposal_unions(&mut schema);
65 inject_additional_properties_false(&mut schema);
66
67 schema
68 }
69 ProtocolRequestProfile::SessionTurn => agent_response_json_schema(),
70 ProtocolRequestProfile::UtilityPrompt => {
71 serde_json::json!(schemars::schema_for!(UtilityResponse))
72 }
73 ProtocolRequestProfile::ReviewMetadata => {
74 serde_json::json!(schemars::schema_for!(ReviewMetadata))
75 }
76 }
77}
78
79fn normalize_proposal_unions(value: &mut Value) {
82 match value {
83 Value::Object(object) => {
84 if let Some(variants) = object.remove("oneOf") {
85 object.insert("anyOf".to_string(), variants);
86 }
87 for nested in object.values_mut() {
88 normalize_proposal_unions(nested);
89 }
90 }
91 Value::Array(items) => {
92 for item in items {
93 normalize_proposal_unions(item);
94 }
95 }
96 _ => {}
97 }
98}
99
100fn focused_review_json_schema() -> Value {
102 let schema = schemars::schema_for!(FocusedReview);
103 let mut schema_value = serde_json::to_value(schema).unwrap_or(Value::Null);
104
105 inject_additional_properties_false(&mut schema_value);
106
107 schema_value
108}
109
110fn agent_response_json_schema() -> Value {
116 let schema = schemars::schema_for!(AgentResponse);
117 let mut schema_value = serde_json::to_value(schema).unwrap_or(Value::Null);
118
119 inject_dynamic_schema_guidance(&mut schema_value);
120 inject_additional_properties_false(&mut schema_value);
121 inject_minimum_required_protocol_key(&mut schema_value);
122
123 schema_value
124}
125
126fn inject_dynamic_schema_guidance(schema: &mut Value) {
129 let Some(properties) = schema.get_mut("properties").and_then(Value::as_object_mut) else {
130 return;
131 };
132
133 let Some(property) = properties
134 .get_mut("questions")
135 .and_then(Value::as_object_mut)
136 else {
137 return;
138 };
139 property.insert(
140 "description".to_string(),
141 Value::String(questions_field_description()),
142 );
143}
144
145fn inject_additional_properties_false(value: &mut Value) {
157 match value {
158 Value::Object(object) => {
159 if object.contains_key("properties") && !object.contains_key("additionalProperties") {
160 object.insert("additionalProperties".to_string(), Value::Bool(false));
161 }
162
163 for nested_value in object.values_mut() {
164 inject_additional_properties_false(nested_value);
165 }
166 }
167 Value::Array(array) => {
168 for nested_value in array {
169 inject_additional_properties_false(nested_value);
170 }
171 }
172 _ => {}
173 }
174}
175
176fn inject_minimum_required_protocol_key(schema: &mut Value) {
185 let Some(object) = schema.as_object_mut() else {
186 return;
187 };
188
189 let required = object
190 .entry("required")
191 .or_insert_with(|| Value::Array(Vec::new()));
192
193 let Some(required_array) = required.as_array_mut() else {
194 return;
195 };
196
197 let already_listed = required_array
198 .iter()
199 .any(|value| value.as_str() == Some("answer"));
200
201 if !already_listed {
202 required_array.push(Value::String("answer".to_string()));
203 }
204}
205
206fn normalize_schema_for_transport(value: &mut Value, required_policy: SchemaRequiredPolicy) {
215 match value {
216 Value::Object(object) => {
217 object.remove("$schema");
218
219 for nested_value in object.values_mut() {
220 normalize_schema_for_transport(nested_value, required_policy);
221 }
222
223 normalize_ref_object_for_codex(object);
224 if required_policy == SchemaRequiredPolicy::AllProperties {
225 normalize_required_for_codex(object);
226 }
227
228 let one_of_values = object
229 .get("oneOf")
230 .and_then(Value::as_array)
231 .map(|items| {
232 items
233 .iter()
234 .filter_map(Value::as_object)
235 .map(|item| item.get("const").and_then(Value::as_str))
236 .collect::<Option<Vec<_>>>()
237 })
238 .map(|option| {
239 option.map(|values| {
240 values
241 .into_iter()
242 .map(ToString::to_string)
243 .collect::<Vec<_>>()
244 })
245 });
246
247 if let Some(Some(enum_variants)) = one_of_values {
248 object.remove("oneOf");
249 object.insert("type".to_string(), Value::String("string".to_string()));
250 object.insert(
251 "enum".to_string(),
252 Value::Array(enum_variants.into_iter().map(Value::String).collect()),
253 );
254 }
255 }
256 Value::Array(array) => {
257 for nested_value in array {
258 normalize_schema_for_transport(nested_value, required_policy);
259 }
260 }
261 _ => {}
262 }
263}
264
265fn normalize_ref_object_for_codex(object: &mut serde_json::Map<String, Value>) {
271 let Some(reference) = object.get("$ref").cloned() else {
272 return;
273 };
274
275 object.clear();
276 object.insert("$ref".to_string(), reference);
277}
278
279fn normalize_required_for_codex(object: &mut serde_json::Map<String, Value>) {
285 let Some(properties) = object.get("properties").and_then(Value::as_object) else {
286 return;
287 };
288
289 let property_keys: Vec<String> = properties.keys().cloned().collect();
290 if property_keys.is_empty() {
291 return;
292 }
293
294 let required = object
295 .entry("required")
296 .or_insert_with(|| Value::Array(Vec::new()));
297
298 let Some(required_array) = required.as_array_mut() else {
299 return;
300 };
301
302 for key in &property_keys {
303 let already_listed = required_array
304 .iter()
305 .any(|value| value.as_str() == Some(key));
306
307 if !already_listed {
308 required_array.push(Value::String(key.clone()));
309 }
310 }
311}
312
313fn stringify_schema_json(schema: &Value) -> String {
315 serde_json::to_string_pretty(schema).unwrap_or("null".to_string())
316}
317
318#[cfg(test)]
319#[path = "schema_test.rs"]
320mod tests;