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 SessionTurn,
103 UtilityPrompt,
105}
106
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
109#[serde(rename_all = "snake_case")]
110#[schemars(
111 title = "ReviewCommentResolution",
112 description = "Disposition reported for one targeted forge review thread."
113)]
114pub enum ReviewCommentResolution {
115 Fixed,
118 NoChangeNeeded,
121}
122
123#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
125#[schemars(
126 title = "ReviewCommentOutcome",
127 description = "Structured outcome for one forge review thread explicitly included in the turn \
128 prompt."
129)]
130pub struct ReviewCommentOutcome {
131 #[schemars(
133 title = "reply",
134 description = "Concise reply suitable for posting to the forge review thread."
135 )]
136 pub reply: String,
137 #[schemars(
139 title = "resolution",
140 description = "Whether the targeted thread was fixed or required no change."
141 )]
142 pub resolution: ReviewCommentResolution,
143 #[schemars(
145 title = "thread_id",
146 description = "Opaque forge thread identifier copied exactly from the turn prompt."
147 )]
148 pub thread_id: String,
149}
150
151#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
156#[schemars(
157 title = "AgentResponse",
158 description = "Wire-format protocol payload used for schema-driven provider output. Return \
159 this object as the entire assistant response payload. Providers that support \
160 output schemas (for example, Codex app-server) are asked to emit this object \
161 directly."
162)]
163pub struct AgentResponse {
164 #[serde(default)]
166 #[schemars(
167 title = "answer",
168 description = "Markdown answer text for delivered work, status updates, or concise \
169 completion notes. Keep clarification requests out of this field and emit \
170 them through `questions` instead."
171 )]
172 pub answer: String,
173 #[serde(default)]
181 #[schemars(title = "questions")]
182 pub questions: Vec<QuestionItem>,
183 #[serde(default)]
189 #[schemars(
190 title = "review_comment_outcomes",
191 description = "Per-thread outcomes for an agent-driven forge comment-resolution turn. \
192 Emit an empty array unless the prompt explicitly supplies forge thread \
193 IDs. Copy each reported `thread_id` exactly from the prompt."
194 )]
195 pub review_comment_outcomes: Vec<ReviewCommentOutcome>,
196 #[serde(default)]
204 #[schemars(title = "subtasks")]
205 pub subtasks: Vec<SubtaskItem>,
206 #[serde(default)]
212 #[schemars(
213 title = "verification_verdicts",
214 description = "Per-task decisions for an orchestration verification turn. Emit one item \
215 for every task in the verification envelope, and use an empty array for \
216 ordinary turns."
217 )]
218 pub verification_verdicts: Vec<VerificationVerdictItem>,
219}
220
221impl AgentResponse {
222 pub fn plain(text: impl Into<String>) -> Self {
224 Self {
225 answer: text.into(),
226 questions: Vec::new(),
227 review_comment_outcomes: Vec::new(),
228 subtasks: Vec::new(),
229 verification_verdicts: Vec::new(),
230 }
231 }
232
233 pub fn to_display_text(&self) -> String {
236 let mut display_messages = Vec::new();
237 push_display_message(&mut display_messages, &self.answer);
238 push_question_display_messages(&mut display_messages, &self.questions);
239
240 display_messages.join("\n\n")
241 }
242
243 pub fn to_answer_display_text(&self) -> String {
246 let mut display_messages = Vec::new();
247 push_display_message(&mut display_messages, &self.answer);
248
249 display_messages.join("\n\n")
250 }
251
252 pub fn answers(&self) -> Vec<String> {
254 let answer = self.to_answer_display_text();
255 if answer.is_empty() {
256 return Vec::new();
257 }
258
259 vec![answer]
260 }
261
262 pub fn question_items(&self) -> Vec<QuestionItem> {
265 self.questions.iter().take(MAX_QUESTIONS).cloned().collect()
266 }
267
268 pub fn subtask_items(&self) -> Vec<SubtaskItem> {
273 self.subtasks.iter().take(MAX_SUBTASKS).cloned().collect()
274 }
275
276 pub fn verification_verdict_items(&self) -> Vec<VerificationVerdictItem> {
279 self.verification_verdicts
280 .iter()
281 .take(MAX_SUBTASKS)
282 .cloned()
283 .collect()
284 }
285}
286
287#[derive(Debug, Clone, PartialEq, Eq)]
289pub enum AgentResponseParseError {
290 Empty,
292 InvalidFormat {
295 reason: String,
297 },
298}
299
300impl fmt::Display for AgentResponseParseError {
301 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
302 match self {
303 Self::Empty => write!(formatter, "response is empty"),
304 Self::InvalidFormat { reason } => {
305 write!(formatter, "response is not valid protocol JSON: {reason}")
306 }
307 }
308 }
309}
310
311impl std::error::Error for AgentResponseParseError {}
312
313fn push_display_message(display_messages: &mut Vec<String>, text: &str) {
315 if text.trim().is_empty() {
316 return;
317 }
318
319 display_messages.push(text.to_string());
320}
321
322fn push_question_display_messages(display_messages: &mut Vec<String>, questions: &[QuestionItem]) {
324 for question in questions {
325 push_display_message(display_messages, &question.text);
326 }
327}
328
329#[cfg(test)]
330mod tests {
331 use super::*;
332
333 #[test]
334 fn test_questions_field_description_renders_template_limit() {
337 let expected_limit = format!("Emit at most {MAX_QUESTIONS} items");
339
340 let description = questions_field_description();
342 let normalized_description = description.split_whitespace().collect::<Vec<_>>().join(" ");
343
344 assert!(normalized_description.contains(&expected_limit));
346 assert!(normalized_description.contains("Emit an empty array when no input is required"));
347 assert!(normalized_description.contains("field defaults to an empty array when omitted"));
348 assert!(normalized_description.contains("genuinely ambiguous requirement"));
349 assert!(normalized_description.contains("Never request permission for agreed work"));
350 assert!(normalized_description.contains("ask for satisfaction or sign-off"));
351 assert!(normalized_description.contains("Execute agreed work"));
352 assert!(!description.contains("{{ max_questions }}"));
353 }
354
355 #[test]
356 fn test_agent_response_to_display_text_joins_answer_and_questions() {
359 let response = AgentResponse {
361 answer: "Primary answer".to_string(),
362 questions: vec![QuestionItem::new("Need one clarification.")],
363 review_comment_outcomes: Vec::new(),
364 subtasks: Vec::new(),
365 verification_verdicts: Vec::new(),
366 };
367
368 let display_text = response.to_display_text();
370
371 assert_eq!(display_text, "Primary answer\n\nNeed one clarification.");
373 }
374
375 #[test]
376 fn test_agent_response_review_comment_outcomes_round_trip() {
378 let response = AgentResponse {
380 answer: "Addressed the comment.".to_string(),
381 questions: Vec::new(),
382 review_comment_outcomes: vec![ReviewCommentOutcome {
383 reply: "Added the missing validation.".to_string(),
384 resolution: ReviewCommentResolution::Fixed,
385 thread_id: "thread-42".to_string(),
386 }],
387 subtasks: Vec::new(),
388 verification_verdicts: Vec::new(),
389 };
390
391 let serialized = serde_json::to_string(&response).expect("response should serialize");
393 let deserialized = serde_json::from_str::<AgentResponse>(&serialized)
394 .expect("response should deserialize");
395
396 assert_eq!(deserialized, response);
398 assert!(serialized.contains(r#""resolution":"fixed""#));
399 }
400
401 #[test]
402 fn test_agent_response_question_items_applies_question_cap() {
404 let response = AgentResponse {
406 answer: String::new(),
407 questions: (0..=MAX_QUESTIONS)
408 .map(|index| QuestionItem::new(format!("Question {index}")))
409 .collect(),
410 review_comment_outcomes: Vec::new(),
411 subtasks: Vec::new(),
412 verification_verdicts: Vec::new(),
413 };
414
415 let questions = response.question_items();
417
418 assert_eq!(questions.len(), MAX_QUESTIONS);
420 }
421
422 #[test]
423 fn test_agent_response_subtask_items_applies_subtask_cap() {
426 let response = AgentResponse {
428 answer: String::new(),
429 questions: Vec::new(),
430 review_comment_outcomes: Vec::new(),
431 subtasks: (0..=MAX_SUBTASKS).map(test_subtask).collect(),
432 verification_verdicts: Vec::new(),
433 };
434
435 let subtasks = response.subtask_items();
437
438 assert_eq!(subtasks.len(), MAX_SUBTASKS);
440 assert_eq!(subtasks[0].task_key, "task-0");
441 }
442
443 #[test]
444 fn test_agent_response_subtasks_round_trip() {
447 let response = AgentResponse {
449 answer: "Proposed a plan.".to_string(),
450 questions: Vec::new(),
451 review_comment_outcomes: Vec::new(),
452 subtasks: vec![test_subtask(1)],
453 verification_verdicts: Vec::new(),
454 };
455
456 let serialized = serde_json::to_string(&response).expect("response should serialize");
458 let deserialized = serde_json::from_str::<AgentResponse>(&serialized)
459 .expect("response should deserialize");
460
461 assert_eq!(deserialized, response);
463 assert!(serialized.contains(r#""task_key":"task-1""#));
464 assert_eq!(
465 AgentResponse::plain("no plan").subtask_items(),
466 [] as [crate::subtask::SubtaskItem; 0]
467 );
468 }
469
470 #[test]
471 fn test_agent_response_verification_verdicts_round_trip_and_cap() {
474 let response = AgentResponse {
476 answer: "Verified the settled tasks.".to_string(),
477 questions: Vec::new(),
478 review_comment_outcomes: Vec::new(),
479 subtasks: Vec::new(),
480 verification_verdicts: (0..=MAX_SUBTASKS)
481 .map(|index| VerificationVerdictItem {
482 reason: format!("Evidence {index}"),
483 task_key: format!("task-{index}"),
484 verdict: crate::VerificationVerdict::Pass,
485 })
486 .collect(),
487 };
488
489 let serialized = serde_json::to_string(&response).expect("response should serialize");
491 let deserialized = serde_json::from_str::<AgentResponse>(&serialized)
492 .expect("response should deserialize");
493 let verdicts = deserialized.verification_verdict_items();
494
495 assert_eq!(verdicts.len(), MAX_SUBTASKS);
497 assert_eq!(verdicts[0].task_key, "task-0");
498 assert!(serialized.contains(r#""verdict":"pass""#));
499 }
500
501 #[test]
502 fn test_subtask_item_defaults_touched_areas() {
505 let raw = r#"{"prompt":"Do the work","task_key":"task-1","title":"Work"}"#;
507
508 let subtask =
510 serde_json::from_str::<SubtaskItem>(raw).expect("subtask should parse without areas");
511
512 assert_eq!(subtask.kind, crate::SubtaskKind::Implementation);
514 assert_eq!(subtask.touched_areas, [] as [std::string::String; 0]);
515 }
516
517 #[test]
518 fn test_subtasks_field_description_reports_the_subtask_cap() {
521 let expected_limit = format!("at most {MAX_SUBTASKS} items");
523
524 let description = subtasks_field_description();
526 let normalized_description = description.split_whitespace().collect::<Vec<_>>().join(" ");
527
528 assert!(description.contains(&expected_limit));
530 assert!(
531 normalized_description
532 .contains("Emit an empty array when no decomposition was requested")
533 );
534 assert!(normalized_description.contains("field defaults to an empty array when omitted"));
535 assert!(normalized_description.contains("Ordinary session and utility turns"));
536 assert!(normalized_description.contains("unattended in its own worktree"));
537 assert!(normalized_description.contains("independently completable"));
538 assert!(normalized_description.contains("without wildcards"));
539 assert!(description.contains("Areas may overlap"));
540 assert!(normalized_description.contains("fewer than two independent subtasks"));
541 assert!(!description.contains("{{"));
542 }
543
544 #[test]
545 fn test_field_description_template_survives_a_wrapped_placeholder() {
549 let template = "Emit at most {{\nmax_items }} items, and no more.\n";
551
552 let rendered = render_field_description_template(template, "{{ max_items }}", 4);
554
555 assert_eq!(rendered, "Emit at most 4 items, and no more.");
557 }
558
559 #[test]
560 fn test_field_description_template_keeps_unterminated_placeholder_text() {
563 let template = "Emit at most {{ max_items items.";
565
566 let rendered = render_field_description_template(template, "{{ max_items }}", 4);
568
569 assert_eq!(rendered, "Emit at most {{ max_items items.");
571 }
572
573 fn test_subtask(index: usize) -> SubtaskItem {
575 SubtaskItem {
576 acceptance_criteria: vec![format!("Work item {index} is complete")],
577 kind: crate::SubtaskKind::Implementation,
578 prompt: format!("Complete work item {index}"),
579 task_key: format!("task-{index}"),
580 title: format!("Work item {index}"),
581 touched_areas: vec![format!("crates/area-{index}/")],
582 }
583 }
584}