1use serde_json::Value;
5
6use super::model::{AgentResponse, questions_field_description, subtasks_field_description};
7
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
17pub enum SchemaRequiredPolicy {
18 AllProperties,
20 MinimumProtocolKeys,
22}
23
24pub fn agent_response_output_schema(required_policy: SchemaRequiredPolicy) -> Value {
31 let mut value = agent_response_json_schema();
32 normalize_schema_for_transport(&mut value, required_policy);
33
34 value
35}
36
37pub fn agent_response_json_schema_json() -> String {
43 let schema = agent_response_json_schema();
44
45 stringify_schema_json(&schema)
46}
47
48pub fn agent_response_output_schema_json(required_policy: SchemaRequiredPolicy) -> String {
54 let schema = agent_response_output_schema(required_policy);
55
56 stringify_schema_json(&schema)
57}
58
59fn agent_response_json_schema() -> Value {
65 let schema = schemars::schema_for!(AgentResponse);
66 let mut schema_value = serde_json::to_value(schema).unwrap_or(Value::Null);
67
68 inject_dynamic_schema_guidance(&mut schema_value);
69 inject_additional_properties_false(&mut schema_value);
70 inject_minimum_required_protocol_key(&mut schema_value);
71
72 schema_value
73}
74
75fn inject_dynamic_schema_guidance(schema: &mut Value) {
78 let Some(properties) = schema.get_mut("properties").and_then(Value::as_object_mut) else {
79 return;
80 };
81
82 for (property_name, description) in [
83 ("questions", questions_field_description()),
84 ("subtasks", subtasks_field_description()),
85 ] {
86 let Some(property) = properties
87 .get_mut(property_name)
88 .and_then(Value::as_object_mut)
89 else {
90 continue;
91 };
92
93 property.insert("description".to_string(), Value::String(description));
94 }
95}
96
97fn inject_additional_properties_false(value: &mut Value) {
107 match value {
108 Value::Object(object) => {
109 if object.contains_key("properties") && !object.contains_key("additionalProperties") {
110 object.insert("additionalProperties".to_string(), Value::Bool(false));
111 }
112
113 for nested_value in object.values_mut() {
114 inject_additional_properties_false(nested_value);
115 }
116 }
117 Value::Array(array) => {
118 for nested_value in array {
119 inject_additional_properties_false(nested_value);
120 }
121 }
122 _ => {}
123 }
124}
125
126fn inject_minimum_required_protocol_key(schema: &mut Value) {
135 let Some(object) = schema.as_object_mut() else {
136 return;
137 };
138
139 let required = object
140 .entry("required")
141 .or_insert_with(|| Value::Array(Vec::new()));
142
143 let Some(required_array) = required.as_array_mut() else {
144 return;
145 };
146
147 let already_listed = required_array
148 .iter()
149 .any(|value| value.as_str() == Some("answer"));
150
151 if !already_listed {
152 required_array.push(Value::String("answer".to_string()));
153 }
154}
155
156fn normalize_schema_for_transport(value: &mut Value, required_policy: SchemaRequiredPolicy) {
165 match value {
166 Value::Object(object) => {
167 object.remove("$schema");
168
169 for nested_value in object.values_mut() {
170 normalize_schema_for_transport(nested_value, required_policy);
171 }
172
173 normalize_ref_object_for_codex(object);
174 if required_policy == SchemaRequiredPolicy::AllProperties {
175 normalize_required_for_codex(object);
176 }
177
178 let one_of_values = object
179 .get("oneOf")
180 .and_then(Value::as_array)
181 .map(|items| {
182 items
183 .iter()
184 .filter_map(Value::as_object)
185 .map(|item| item.get("const").and_then(Value::as_str))
186 .collect::<Option<Vec<_>>>()
187 })
188 .map(|option| {
189 option.map(|values| {
190 values
191 .into_iter()
192 .map(ToString::to_string)
193 .collect::<Vec<_>>()
194 })
195 });
196
197 if let Some(Some(enum_variants)) = one_of_values {
198 object.remove("oneOf");
199 object.insert("type".to_string(), Value::String("string".to_string()));
200 object.insert(
201 "enum".to_string(),
202 Value::Array(enum_variants.into_iter().map(Value::String).collect()),
203 );
204 }
205 }
206 Value::Array(array) => {
207 for nested_value in array {
208 normalize_schema_for_transport(nested_value, required_policy);
209 }
210 }
211 _ => {}
212 }
213}
214
215fn normalize_ref_object_for_codex(object: &mut serde_json::Map<String, Value>) {
221 let Some(reference) = object.get("$ref").cloned() else {
222 return;
223 };
224
225 object.clear();
226 object.insert("$ref".to_string(), reference);
227}
228
229fn normalize_required_for_codex(object: &mut serde_json::Map<String, Value>) {
235 let Some(properties) = object.get("properties").and_then(Value::as_object) else {
236 return;
237 };
238
239 let property_keys: Vec<String> = properties.keys().cloned().collect();
240 if property_keys.is_empty() {
241 return;
242 }
243
244 let required = object
245 .entry("required")
246 .or_insert_with(|| Value::Array(Vec::new()));
247
248 let Some(required_array) = required.as_array_mut() else {
249 return;
250 };
251
252 for key in &property_keys {
253 let already_listed = required_array
254 .iter()
255 .any(|value| value.as_str() == Some(key));
256
257 if !already_listed {
258 required_array.push(Value::String(key.clone()));
259 }
260 }
261}
262
263fn stringify_schema_json(schema: &Value) -> String {
265 serde_json::to_string_pretty(schema).unwrap_or("null".to_string())
266}
267
268#[cfg(test)]
269mod tests {
270 use super::*;
271
272 #[test]
273 fn test_agent_response_output_schema_contains_required_fields() {
275 let schema = agent_response_output_schema(SchemaRequiredPolicy::AllProperties);
277 let required_fields = schema
278 .get("required")
279 .and_then(Value::as_array)
280 .expect("schema required fields should exist");
281 let properties = schema
282 .get("properties")
283 .and_then(Value::as_object)
284 .expect("schema properties should exist");
285
286 assert!(
288 required_fields
289 .iter()
290 .any(|value| value.as_str() == Some("answer"))
291 );
292 assert!(
293 required_fields
294 .iter()
295 .any(|value| value.as_str() == Some("questions"))
296 );
297 assert!(
298 required_fields
299 .iter()
300 .any(|value| value.as_str() == Some("review_comment_outcomes"))
301 );
302 assert!(
303 required_fields
304 .iter()
305 .any(|value| value.as_str() == Some("subtasks"))
306 );
307 assert!(properties.contains_key("answer"));
308 assert!(properties.contains_key("questions"));
309 assert!(properties.contains_key("review_comment_outcomes"));
310 assert!(properties.contains_key("subtasks"));
311 }
312
313 #[test]
314 fn test_inject_dynamic_schema_guidance_skips_absent_properties() {
317 let mut schema = serde_json::json!({
319 "properties": {
320 "answer": { "type": "string" }
321 }
322 });
323
324 inject_dynamic_schema_guidance(&mut schema);
326
327 assert_eq!(
329 schema,
330 serde_json::json!({
331 "properties": {
332 "answer": { "type": "string" }
333 }
334 })
335 );
336 }
337
338 #[test]
339 fn test_agent_response_json_schema_injects_subtasks_description() {
342 let schema = agent_response_json_schema();
344 let response_properties = schema
345 .get("properties")
346 .and_then(Value::as_object)
347 .expect("response properties should exist");
348 let subtask_properties = schema_definition_properties(&schema, "SubtaskItem");
349
350 assert_eq!(
352 response_properties
353 .get("subtasks")
354 .and_then(|value| value.get("description"))
355 .and_then(Value::as_str),
356 Some(subtasks_field_description().as_str())
357 );
358 assert!(subtask_properties.contains_key("prompt"));
359 assert!(subtask_properties.contains_key("kind"));
360 assert!(subtask_properties.contains_key("task_key"));
361 assert!(subtask_properties.contains_key("title"));
362 assert!(subtask_properties.contains_key("touched_areas"));
363 }
364
365 #[test]
366 fn test_agent_response_output_schema_all_properties_are_required() {
369 let schema = agent_response_output_schema(SchemaRequiredPolicy::AllProperties);
371
372 assert!(
374 all_properties_in_required(&schema),
375 "every object with `properties` should list all keys in `required`"
376 );
377 }
378
379 #[test]
380 fn test_agent_response_output_schema_minimum_policy_requires_only_answer() {
384 let schema = agent_response_output_schema(SchemaRequiredPolicy::MinimumProtocolKeys);
386 let required_fields = schema
387 .get("required")
388 .and_then(Value::as_array)
389 .expect("schema required fields should exist");
390
391 assert_eq!(
393 required_fields,
394 &vec![Value::String("answer".to_string())],
395 "only `answer` should be required; demanding optional response fields rejects \
396 ordinary replies that omit them"
397 );
398 }
399
400 #[test]
401 fn test_agent_response_output_schema_does_not_contain_one_of() {
404 let schema = agent_response_output_schema(SchemaRequiredPolicy::AllProperties);
406
407 assert!(!contains_schema_key(&schema, "oneOf"));
409 }
410
411 #[test]
412 fn test_agent_response_output_schema_does_not_contain_schema_metadata() {
415 let schema = agent_response_output_schema(SchemaRequiredPolicy::MinimumProtocolKeys);
417
418 assert!(!contains_schema_key(&schema, "$schema"));
420 }
421
422 #[test]
423 fn test_agent_response_json_schema_requires_answer_key() {
426 let schema = agent_response_json_schema();
428 let required_fields = schema
429 .get("required")
430 .and_then(Value::as_array)
431 .expect("schema required fields should exist");
432
433 assert!(
435 required_fields
436 .iter()
437 .any(|value| value.as_str() == Some("answer")),
438 "prompt schema should require `answer` to align with parser key-presence check"
439 );
440 }
441
442 #[test]
443 fn test_agent_response_json_schema_sets_additional_properties_false() {
447 let schema = agent_response_json_schema();
449
450 assert!(
452 all_properties_objects_deny_additional(&schema),
453 "every object with `properties` should set `additionalProperties: false`"
454 );
455 }
456
457 #[test]
458 fn test_inject_additional_properties_false_preserves_existing_value() {
461 let mut schema = serde_json::json!({
463 "type": "object",
464 "properties": {
465 "extra": { "type": "object", "additionalProperties": { "type": "string" } }
466 }
467 });
468
469 inject_additional_properties_false(&mut schema);
471
472 assert_eq!(schema["additionalProperties"], Value::Bool(false));
474 assert_eq!(
476 schema["properties"]["extra"]["additionalProperties"],
477 serde_json::json!({ "type": "string" })
478 );
479 }
480
481 #[test]
482 fn test_agent_response_output_schema_ref_objects_have_no_sibling_keywords() {
484 let schema = agent_response_output_schema(SchemaRequiredPolicy::AllProperties);
486
487 assert!(!contains_ref_with_sibling_keywords(&schema));
489 }
490
491 #[test]
492 fn test_agent_response_json_schema_json_is_parseable_value() {
494 let schema_json = agent_response_json_schema_json();
496 let parsed_schema: Value =
497 serde_json::from_str(&schema_json).expect("schema string should parse as JSON");
498 let schema_value = agent_response_json_schema();
499
500 assert_eq!(parsed_schema, schema_value);
502 }
503
504 #[test]
505 fn test_agent_response_json_schema_preserves_explicit_payload_metadata() {
508 let schema = agent_response_json_schema();
510
511 assert_eq!(
513 schema.get("title").and_then(Value::as_str),
514 Some("AgentResponse")
515 );
516 assert_eq!(
517 schema.get("description").and_then(Value::as_str),
518 Some(
519 "Wire-format protocol payload used for schema-driven provider output. Return this \
520 object as the entire assistant response payload. Providers that support output \
521 schemas (for example, Codex app-server) are asked to emit this object directly."
522 )
523 );
524 }
525
526 #[test]
527 fn test_agent_response_json_schema_preserves_nested_metadata() {
529 let schema = agent_response_json_schema();
531 let question_definition = schema
532 .get("$defs")
533 .and_then(|value| value.get("QuestionItem"))
534 .and_then(Value::as_object)
535 .expect("question definition should exist");
536 let review_comment_outcome_definition = schema
537 .get("$defs")
538 .and_then(|value| value.get("ReviewCommentOutcome"))
539 .and_then(Value::as_object)
540 .expect("review comment outcome definition should exist");
541 let review_comment_resolution_definition = schema
542 .get("$defs")
543 .and_then(|value| value.get("ReviewCommentResolution"))
544 .and_then(Value::as_object)
545 .expect("review comment resolution definition should exist");
546
547 assert_eq!(
549 question_definition.get("title").and_then(Value::as_str),
550 Some("QuestionItem")
551 );
552 assert_eq!(
553 review_comment_outcome_definition
554 .get("title")
555 .and_then(Value::as_str),
556 Some("ReviewCommentOutcome")
557 );
558 assert_eq!(
559 review_comment_resolution_definition
560 .get("title")
561 .and_then(Value::as_str),
562 Some("ReviewCommentResolution")
563 );
564 }
565
566 #[test]
567 fn test_agent_response_json_schema_preserves_field_metadata() {
569 let schema = agent_response_json_schema();
571 let response_properties = schema
572 .get("properties")
573 .and_then(Value::as_object)
574 .expect("response properties should exist");
575 let question_properties = schema_definition_properties(&schema, "QuestionItem");
576 let review_comment_outcome_properties =
577 schema_definition_properties(&schema, "ReviewCommentOutcome");
578 let expected_questions_description = questions_field_description();
579
580 assert_schema_property_title_and_description(
582 response_properties,
583 "answer",
584 "answer",
585 "Markdown answer text for delivered work, status updates, or concise completion \
586 notes. Keep clarification requests out of this field and emit them through \
587 `questions` instead.",
588 );
589 assert_eq!(
590 response_properties
591 .get("questions")
592 .and_then(|value| value.get("description"))
593 .and_then(Value::as_str),
594 Some(expected_questions_description.as_str())
595 );
596 assert_schema_property_title_and_description(
597 response_properties,
598 "review_comment_outcomes",
599 "review_comment_outcomes",
600 "Per-thread outcomes for an agent-driven forge comment-resolution turn. Emit an empty \
601 array unless the prompt explicitly supplies forge thread IDs. Copy each reported \
602 `thread_id` exactly from the prompt.",
603 );
604 assert_schema_property_title_and_description(
605 question_properties,
606 "text",
607 "text",
608 "Human-readable markdown text for this question. Ask one specific actionable question \
609 instead of bundling multiple decisions into one item.",
610 );
611 assert_schema_property_title(question_properties, "options", "options");
612 assert_schema_property_title_and_description(
613 review_comment_outcome_properties,
614 "reply",
615 "reply",
616 "Concise reply suitable for posting to the forge review thread.",
617 );
618 assert_schema_property_title_and_description(
619 review_comment_outcome_properties,
620 "resolution",
621 "resolution",
622 "Whether the targeted thread was fixed or required no change.",
623 );
624 assert_schema_property_title_and_description(
625 review_comment_outcome_properties,
626 "thread_id",
627 "thread_id",
628 "Opaque forge thread identifier copied exactly from the turn prompt.",
629 );
630 }
631
632 #[test]
633 fn test_agent_response_json_schema_keeps_optional_question_options() {
636 let schema = agent_response_json_schema();
638 let question_definition = schema
639 .get("$defs")
640 .and_then(|value| value.get("QuestionItem"))
641 .and_then(Value::as_object)
642 .expect("question definition should exist");
643 let question_required_fields = question_definition
644 .get("required")
645 .and_then(Value::as_array)
646 .cloned()
647 .unwrap_or_default();
648
649 assert!(
651 question_required_fields
652 .iter()
653 .all(|field| field.as_str() != Some("options")),
654 "question schema should keep `options` optional for omitted empty lists"
655 );
656 }
657
658 #[test]
659 fn test_agent_response_output_schema_json_is_parseable_value() {
662 let schema_json =
664 agent_response_output_schema_json(SchemaRequiredPolicy::MinimumProtocolKeys);
665 let parsed_schema: Value =
666 serde_json::from_str(&schema_json).expect("schema string should parse as JSON");
667 let schema_value = agent_response_output_schema(SchemaRequiredPolicy::MinimumProtocolKeys);
668
669 assert_eq!(parsed_schema, schema_value);
671 }
672
673 fn contains_schema_key(value: &Value, key: &str) -> bool {
675 match value {
676 Value::Object(object) => {
677 if object.contains_key(key) {
678 return true;
679 }
680
681 object
682 .values()
683 .any(|nested_value| contains_schema_key(nested_value, key))
684 }
685 Value::Array(array) => array
686 .iter()
687 .any(|nested_value| contains_schema_key(nested_value, key)),
688 _ => false,
689 }
690 }
691
692 fn contains_ref_with_sibling_keywords(value: &Value) -> bool {
694 match value {
695 Value::Object(object) => {
696 if object.contains_key("$ref") && object.len() > 1 {
697 return true;
698 }
699
700 object.values().any(contains_ref_with_sibling_keywords)
701 }
702 Value::Array(array) => array.iter().any(contains_ref_with_sibling_keywords),
703 _ => false,
704 }
705 }
706
707 fn all_properties_in_required(value: &Value) -> bool {
710 match value {
711 Value::Object(object) => {
712 if let Some(properties) = object.get("properties").and_then(Value::as_object) {
713 let required_keys: Vec<&str> = object
714 .get("required")
715 .and_then(Value::as_array)
716 .map(|array| array.iter().filter_map(Value::as_str).collect())
717 .unwrap_or_default();
718
719 for key in properties.keys() {
720 if !required_keys.contains(&key.as_str()) {
721 return false;
722 }
723 }
724 }
725
726 object.values().all(all_properties_in_required)
727 }
728 Value::Array(array) => array.iter().all(all_properties_in_required),
729 _ => true,
730 }
731 }
732
733 fn all_properties_objects_deny_additional(value: &Value) -> bool {
736 match value {
737 Value::Object(object) => {
738 if object.contains_key("properties")
739 && object.get("additionalProperties") != Some(&Value::Bool(false))
740 {
741 return false;
742 }
743
744 object.values().all(all_properties_objects_deny_additional)
745 }
746 Value::Array(array) => array.iter().all(all_properties_objects_deny_additional),
747 _ => true,
748 }
749 }
750
751 fn schema_definition_properties<'a>(
753 schema: &'a Value,
754 definition_name: &str,
755 ) -> &'a serde_json::Map<String, Value> {
756 schema
757 .get("$defs")
758 .and_then(|value| value.get(definition_name))
759 .and_then(|value| value.get("properties"))
760 .and_then(Value::as_object)
761 .expect("schema definition properties should exist")
762 }
763
764 fn assert_schema_property_title(
766 properties: &serde_json::Map<String, Value>,
767 property_name: &str,
768 expected_title: &str,
769 ) {
770 assert_eq!(
771 properties
772 .get(property_name)
773 .and_then(|value| value.get("title"))
774 .and_then(Value::as_str),
775 Some(expected_title)
776 );
777 }
778
779 fn assert_schema_property_title_and_description(
782 properties: &serde_json::Map<String, Value>,
783 property_name: &str,
784 expected_title: &str,
785 expected_description: &str,
786 ) {
787 assert_schema_property_title(properties, property_name, expected_title);
788 assert_eq!(
789 properties
790 .get(property_name)
791 .and_then(|value| value.get("description"))
792 .and_then(Value::as_str),
793 Some(expected_description)
794 );
795 }
796}