1use std::fmt;
4
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7
8use super::question::QuestionItem;
9use super::subtask::SubtaskItem;
10use super::verification::VerificationVerdictItem;
11
12pub(crate) const MAX_QUESTIONS: usize = 5;
20pub(crate) const MAX_SUBTASKS: usize = 8;
25const QUESTIONS_FIELD_DESCRIPTION_TEMPLATE: &str =
26 include_str!("template/questions_field_description.md");
27const SUBTASKS_FIELD_DESCRIPTION_TEMPLATE: &str =
28 include_str!("template/subtasks_field_description.md");
29
30pub(crate) fn questions_field_description() -> String {
39 render_field_description_template(
40 QUESTIONS_FIELD_DESCRIPTION_TEMPLATE,
41 "{{ max_questions }}",
42 MAX_QUESTIONS,
43 )
44}
45
46pub(crate) fn subtasks_field_description() -> String {
53 render_field_description_template(
54 SUBTASKS_FIELD_DESCRIPTION_TEMPLATE,
55 "{{ max_subtasks }}",
56 MAX_SUBTASKS,
57 )
58}
59
60fn render_field_description_template(template: &str, placeholder: &str, value: usize) -> String {
68 let mut rendered = String::with_capacity(template.len());
69 let mut remaining = template.trim_end();
70
71 while let Some(open_index) = remaining.find("{{") {
72 let after_open = &remaining[open_index..];
73 let Some(close_end) = after_open.find("}}").map(|index| index + "}}".len()) else {
74 break;
75 };
76
77 rendered.push_str(&remaining[..open_index]);
78 rendered.push_str(&collapse_whitespace(&after_open[..close_end]));
79 remaining = &after_open[close_end..];
80 }
81 rendered.push_str(remaining);
82
83 rendered.replace(placeholder, &value.to_string())
84}
85
86fn collapse_whitespace(text: &str) -> String {
88 text.split_whitespace().collect::<Vec<_>>().join(" ")
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99#[non_exhaustive]
100pub enum ProtocolRequestProfile {
101 FocusedReview,
103 SessionTurn,
105 UtilityPrompt,
107}
108
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
111#[serde(rename_all = "snake_case")]
112#[schemars(
113 title = "ReviewCommentResolution",
114 description = "Disposition reported for one targeted forge review thread."
115)]
116pub enum ReviewCommentResolution {
117 Fixed,
120 NoChangeNeeded,
123}
124
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
127#[schemars(
128 title = "ReviewCommentOutcome",
129 description = "Structured outcome for one forge review thread explicitly included in the turn \
130 prompt."
131)]
132pub struct ReviewCommentOutcome {
133 #[schemars(
135 title = "reply",
136 description = "Concise reply suitable for posting to the forge review thread."
137 )]
138 pub reply: String,
139 #[schemars(
141 title = "resolution",
142 description = "Whether the targeted thread was fixed or required no change."
143 )]
144 pub resolution: ReviewCommentResolution,
145 #[schemars(
147 title = "thread_id",
148 description = "Opaque forge thread identifier copied exactly from the turn prompt."
149 )]
150 pub thread_id: String,
151}
152
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
158#[schemars(
159 title = "AgentResponse",
160 description = "Wire-format protocol payload used for schema-driven provider output. Return \
161 this object as the entire assistant response payload. Providers that support \
162 output schemas (for example, Codex app-server) are asked to emit this object \
163 directly."
164)]
165pub struct AgentResponse {
166 #[serde(default)]
168 #[schemars(
169 title = "answer",
170 description = "Markdown answer text for delivered work, status updates, or concise \
171 completion notes. Keep clarification requests out of this field and emit \
172 them through `questions` instead."
173 )]
174 pub answer: String,
175 #[serde(default)]
183 #[schemars(title = "questions")]
184 pub questions: Vec<QuestionItem>,
185 #[serde(default)]
191 #[schemars(
192 title = "review_comment_outcomes",
193 description = "Per-thread outcomes for an agent-driven forge comment-resolution turn. \
194 Emit an empty array unless the prompt explicitly supplies forge thread \
195 IDs. Copy each reported `thread_id` exactly from the prompt."
196 )]
197 pub review_comment_outcomes: Vec<ReviewCommentOutcome>,
198 #[serde(default)]
206 #[schemars(title = "subtasks")]
207 pub subtasks: Vec<SubtaskItem>,
208 #[serde(default)]
214 #[schemars(
215 title = "verification_verdicts",
216 description = "Per-task decisions for an orchestration verification turn. Emit one item \
217 for every task in the verification envelope, and use an empty array for \
218 ordinary turns."
219 )]
220 pub verification_verdicts: Vec<VerificationVerdictItem>,
221}
222
223impl AgentResponse {
224 pub fn plain(text: impl Into<String>) -> Self {
226 Self {
227 answer: text.into(),
228 questions: Vec::new(),
229 review_comment_outcomes: Vec::new(),
230 subtasks: Vec::new(),
231 verification_verdicts: Vec::new(),
232 }
233 }
234
235 pub fn to_display_text(&self) -> String {
238 let mut display_messages = Vec::new();
239 push_display_message(&mut display_messages, &self.answer);
240 push_question_display_messages(&mut display_messages, &self.questions);
241
242 display_messages.join("\n\n")
243 }
244
245 pub fn to_answer_display_text(&self) -> String {
248 let mut display_messages = Vec::new();
249 push_display_message(&mut display_messages, &self.answer);
250
251 display_messages.join("\n\n")
252 }
253
254 pub fn answers(&self) -> Vec<String> {
256 let answer = self.to_answer_display_text();
257 if answer.is_empty() {
258 return Vec::new();
259 }
260
261 vec![answer]
262 }
263
264 pub fn question_items(&self) -> Vec<QuestionItem> {
267 self.questions.iter().take(MAX_QUESTIONS).cloned().collect()
268 }
269
270 pub fn subtask_items(&self) -> Vec<SubtaskItem> {
275 self.subtasks.iter().take(MAX_SUBTASKS).cloned().collect()
276 }
277
278 pub fn verification_verdict_items(&self) -> Vec<VerificationVerdictItem> {
281 self.verification_verdicts
282 .iter()
283 .take(MAX_SUBTASKS)
284 .cloned()
285 .collect()
286 }
287}
288
289#[derive(Debug, Clone, PartialEq, Eq)]
291pub enum AgentResponseParseError {
292 Empty,
294 InvalidFormat {
297 reason: String,
299 },
300}
301
302impl fmt::Display for AgentResponseParseError {
303 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
304 match self {
305 Self::Empty => write!(formatter, "response is empty"),
306 Self::InvalidFormat { reason } => {
307 write!(formatter, "response is not valid protocol JSON: {reason}")
308 }
309 }
310 }
311}
312
313impl std::error::Error for AgentResponseParseError {}
314
315fn push_display_message(display_messages: &mut Vec<String>, text: &str) {
317 if text.trim().is_empty() {
318 return;
319 }
320
321 display_messages.push(text.to_string());
322}
323
324fn push_question_display_messages(display_messages: &mut Vec<String>, questions: &[QuestionItem]) {
326 for question in questions {
327 push_display_message(display_messages, &question.text);
328 }
329}
330
331#[cfg(test)]
332mod tests {
333 use super::*;
334
335 #[test]
336 fn test_questions_field_description_renders_template_limit() {
339 let expected_limit = format!("Emit at most {MAX_QUESTIONS} items");
341
342 let description = questions_field_description();
344 let normalized_description = description.split_whitespace().collect::<Vec<_>>().join(" ");
345
346 assert!(normalized_description.contains(&expected_limit));
348 assert!(normalized_description.contains("Emit an empty array when no input is required"));
349 assert!(normalized_description.contains("field defaults to an empty array when omitted"));
350 assert!(normalized_description.contains("genuinely ambiguous requirement"));
351 assert!(normalized_description.contains("Never request permission for agreed work"));
352 assert!(normalized_description.contains("ask for satisfaction or sign-off"));
353 assert!(normalized_description.contains("Execute agreed work"));
354 assert!(!description.contains("{{ max_questions }}"));
355 }
356
357 #[test]
358 fn test_agent_response_to_display_text_joins_answer_and_questions() {
361 let response = AgentResponse {
363 answer: "Primary answer".to_string(),
364 questions: vec![QuestionItem::new("Need one clarification.")],
365 review_comment_outcomes: Vec::new(),
366 subtasks: Vec::new(),
367 verification_verdicts: Vec::new(),
368 };
369
370 let display_text = response.to_display_text();
372
373 assert_eq!(display_text, "Primary answer\n\nNeed one clarification.");
375 }
376
377 #[test]
378 fn test_agent_response_review_comment_outcomes_round_trip() {
380 let response = AgentResponse {
382 answer: "Addressed the comment.".to_string(),
383 questions: Vec::new(),
384 review_comment_outcomes: vec![ReviewCommentOutcome {
385 reply: "Added the missing validation.".to_string(),
386 resolution: ReviewCommentResolution::Fixed,
387 thread_id: "thread-42".to_string(),
388 }],
389 subtasks: Vec::new(),
390 verification_verdicts: Vec::new(),
391 };
392
393 let serialized = serde_json::to_string(&response).expect("response should serialize");
395 let deserialized = serde_json::from_str::<AgentResponse>(&serialized)
396 .expect("response should deserialize");
397
398 assert_eq!(deserialized, response);
400 assert!(serialized.contains(r#""resolution":"fixed""#));
401 }
402
403 #[test]
404 fn test_agent_response_question_items_applies_question_cap() {
406 let response = AgentResponse {
408 answer: String::new(),
409 questions: (0..=MAX_QUESTIONS)
410 .map(|index| QuestionItem::new(format!("Question {index}")))
411 .collect(),
412 review_comment_outcomes: Vec::new(),
413 subtasks: Vec::new(),
414 verification_verdicts: Vec::new(),
415 };
416
417 let questions = response.question_items();
419
420 assert_eq!(questions.len(), MAX_QUESTIONS);
422 }
423
424 #[test]
425 fn test_agent_response_subtask_items_applies_subtask_cap() {
428 let response = AgentResponse {
430 answer: String::new(),
431 questions: Vec::new(),
432 review_comment_outcomes: Vec::new(),
433 subtasks: (0..=MAX_SUBTASKS).map(test_subtask).collect(),
434 verification_verdicts: Vec::new(),
435 };
436
437 let subtasks = response.subtask_items();
439
440 assert_eq!(subtasks.len(), MAX_SUBTASKS);
442 assert_eq!(subtasks[0].task_key, "task-0");
443 }
444
445 #[test]
446 fn test_agent_response_subtasks_round_trip() {
449 let response = AgentResponse {
451 answer: "Proposed a plan.".to_string(),
452 questions: Vec::new(),
453 review_comment_outcomes: Vec::new(),
454 subtasks: vec![test_subtask(1)],
455 verification_verdicts: Vec::new(),
456 };
457
458 let serialized = serde_json::to_string(&response).expect("response should serialize");
460 let deserialized = serde_json::from_str::<AgentResponse>(&serialized)
461 .expect("response should deserialize");
462
463 assert_eq!(deserialized, response);
465 assert!(serialized.contains(r#""task_key":"task-1""#));
466 assert_eq!(
467 AgentResponse::plain("no plan").subtask_items(),
468 [] as [crate::subtask::SubtaskItem; 0]
469 );
470 }
471
472 #[test]
473 fn test_agent_response_verification_verdicts_round_trip_and_cap() {
476 let response = AgentResponse {
478 answer: "Verified the settled tasks.".to_string(),
479 questions: Vec::new(),
480 review_comment_outcomes: Vec::new(),
481 subtasks: Vec::new(),
482 verification_verdicts: (0..=MAX_SUBTASKS)
483 .map(|index| VerificationVerdictItem {
484 reason: format!("Evidence {index}"),
485 task_key: format!("task-{index}"),
486 verdict: crate::VerificationVerdict::Pass,
487 })
488 .collect(),
489 };
490
491 let serialized = serde_json::to_string(&response).expect("response should serialize");
493 let deserialized = serde_json::from_str::<AgentResponse>(&serialized)
494 .expect("response should deserialize");
495 let verdicts = deserialized.verification_verdict_items();
496
497 assert_eq!(verdicts.len(), MAX_SUBTASKS);
499 assert_eq!(verdicts[0].task_key, "task-0");
500 assert!(serialized.contains(r#""verdict":"pass""#));
501 }
502
503 #[test]
504 fn test_subtask_item_defaults_touched_areas() {
507 let raw = r#"{"prompt":"Do the work","task_key":"task-1","title":"Work"}"#;
509
510 let subtask =
512 serde_json::from_str::<SubtaskItem>(raw).expect("subtask should parse without areas");
513
514 assert_eq!(subtask.kind, crate::SubtaskKind::Implementation);
516 assert_eq!(subtask.touched_areas, [] as [std::string::String; 0]);
517 }
518
519 #[test]
520 fn test_subtasks_field_description_reports_the_subtask_cap() {
523 let expected_limit = format!("at most {MAX_SUBTASKS} items");
525
526 let description = subtasks_field_description();
528 let normalized_description = description.split_whitespace().collect::<Vec<_>>().join(" ");
529
530 assert!(description.contains(&expected_limit));
532 assert!(
533 normalized_description
534 .contains("Emit an empty array when no decomposition was requested")
535 );
536 assert!(normalized_description.contains("field defaults to an empty array when omitted"));
537 assert!(normalized_description.contains("Ordinary session and utility turns"));
538 assert!(normalized_description.contains("unattended in its own worktree"));
539 assert!(normalized_description.contains("independently completable"));
540 assert!(normalized_description.contains("without wildcards"));
541 assert!(description.contains("Areas may overlap"));
542 assert!(normalized_description.contains("fewer than two independent subtasks"));
543 assert!(!description.contains("{{"));
544 }
545
546 #[test]
547 fn test_field_description_template_survives_a_wrapped_placeholder() {
551 let template = "Emit at most {{\nmax_items }} items, and no more.\n";
553
554 let rendered = render_field_description_template(template, "{{ max_items }}", 4);
556
557 assert_eq!(rendered, "Emit at most 4 items, and no more.");
559 }
560
561 #[test]
562 fn test_field_description_template_keeps_unterminated_placeholder_text() {
565 let template = "Emit at most {{ max_items items.";
567
568 let rendered = render_field_description_template(template, "{{ max_items }}", 4);
570
571 assert_eq!(rendered, "Emit at most {{ max_items items.");
573 }
574
575 fn test_subtask(index: usize) -> SubtaskItem {
577 SubtaskItem {
578 acceptance_criteria: vec![format!("Work item {index} is complete")],
579 kind: crate::SubtaskKind::Implementation,
580 prompt: format!("Complete work item {index}"),
581 task_key: format!("task-{index}"),
582 title: format!("Work item {index}"),
583 touched_areas: vec![format!("crates/area-{index}/")],
584 }
585 }
586}