Skip to main content

ag_protocol/
model.rs

1//! Structured response protocol data model and display helpers.
2
3use std::fmt;
4
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7
8use super::question::QuestionItem;
9use super::subtask::SubtaskItem;
10use super::verification::VerificationVerdictItem;
11
12/// Hard cap on the number of clarification questions extracted from one agent
13/// response. Prevents runaway output from flooding the question UI even when
14/// the agent ignores the prompt-level limit.
15///
16/// This constant is also injected into the protocol instruction prompt
17/// templates so the prompt-level guidance and the server-side cap stay in
18/// sync automatically.
19pub(crate) const MAX_QUESTIONS: usize = 5;
20/// Hard cap on the number of subtasks accepted from one orchestrator planning
21/// turn. Bounds how many child sessions, worktrees, and agent CLI processes a
22/// single approved plan can create even when the agent ignores the
23/// prompt-level limit.
24pub(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
30/// Returns the canonical JSON Schema description for the `questions` field.
31///
32/// This is the single source of truth for the runtime-injected schema
33/// description and the matching test expectation. The static `schemars`
34/// metadata on `AgentResponse::questions` is overwritten by
35/// `inject_dynamic_schema_guidance` before any consumer observes the schema,
36/// so all schema-facing call sites must route through this helper to stay in
37/// sync.
38pub(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
46/// Returns the canonical JSON Schema description for the `subtasks` field.
47///
48/// This mirrors [`questions_field_description`]: the static `schemars`
49/// metadata on `AgentResponse::subtasks` carries only the field title, and
50/// `inject_dynamic_schema_guidance` overwrites the description with this
51/// helper's output before any consumer observes the schema.
52pub(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
60/// Substitutes one `{{ name }}` placeholder with a runtime cap value.
61///
62/// The placeholder is matched after collapsing whitespace runs inside every
63/// `{{ ... }}` span, because `mdformat` reflows these templates at a fixed
64/// column width and will break a line in the middle of a placeholder. Matching
65/// the literal text alone silently left the raw `{{ ... }}` in the description
66/// shown to models, so normalization keeps the templates safe to reformat.
67fn 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
86/// Collapses every whitespace run in `text` to one space.
87fn collapse_whitespace(text: &str) -> String {
88    text.split_whitespace().collect::<Vec<_>>().join(" ")
89}
90
91/// Protocol-owned request family preserved across prompt submission and repair
92/// retries.
93///
94/// Session discussion turns and ordinary utility prompts share the top-level
95/// [`AgentResponse`] schema. Focused reviews use their own direct structured
96/// response so transports can enforce the review fields instead of embedding
97/// JSON inside `AgentResponse::answer`.
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99#[non_exhaustive]
100pub enum ProtocolRequestProfile {
101    /// Isolated focused review with a direct structured review response.
102    FocusedReview,
103    /// Interactive session turn.
104    SessionTurn,
105    /// Isolated utility prompt.
106    UtilityPrompt,
107}
108
109/// Agent-reported disposition for one forge review thread.
110#[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    /// The agent completed the requested action and the thread can be
118    /// resolved after its reply is posted.
119    Fixed,
120    /// The agent determined that no code or documentation change was needed;
121    /// its explanatory reply is posted while the thread remains open.
122    NoChangeNeeded,
123}
124
125/// Structured outcome for one forge review thread targeted by the turn.
126#[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    /// Concise forge reply explaining what changed or why no change was needed.
134    #[schemars(
135        title = "reply",
136        description = "Concise reply suitable for posting to the forge review thread."
137    )]
138    pub reply: String,
139    /// Whether the thread was fixed or did not require a change.
140    #[schemars(
141        title = "resolution",
142        description = "Whether the targeted thread was fixed or required no change."
143    )]
144    pub resolution: ReviewCommentResolution,
145    /// Opaque forge thread identifier copied exactly from the turn prompt.
146    #[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/// Wire-format protocol payload used for schema-driven provider output.
154///
155/// Providers that support output schemas (for example, Codex app-server) are
156/// asked to emit this object as the entire assistant response payload.
157#[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    /// Markdown answer text emitted for this turn.
167    #[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    /// Ordered clarification questions emitted for this turn.
176    ///
177    /// The canonical JSON Schema description for this field is produced by
178    /// [`questions_field_description`] and injected at schema generation time
179    /// by `inject_dynamic_schema_guidance`. The static `schemars` metadata
180    /// here only sets the field title; the description is intentionally
181    /// omitted so the helper is the single source of truth.
182    #[serde(default)]
183    #[schemars(title = "questions")]
184    pub questions: Vec<QuestionItem>,
185    /// Per-thread outcomes for an agent-driven forge comment-resolution turn.
186    ///
187    /// Ordinary session and utility turns leave this empty. Resolution
188    /// workflows accept only identifiers explicitly allowlisted in the turn
189    /// prompt before applying any forge-side effect.
190    #[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    /// Proposed child-session subtasks for an orchestrator planning turn.
199    ///
200    /// The canonical JSON Schema description is produced by
201    /// [`subtasks_field_description`] and injected at schema generation time,
202    /// so the static `schemars` metadata here only sets the field title.
203    /// Ordinary session and utility turns leave this empty, and orchestration
204    /// consumers ignore it unless the turn prompt asked for a plan.
205    #[serde(default)]
206    #[schemars(title = "subtasks")]
207    pub subtasks: Vec<SubtaskItem>,
208    /// Per-task decisions emitted for an orchestration verification turn.
209    ///
210    /// Ordinary turns leave this empty. The controller must copy task keys
211    /// from the coordinator envelope so only explicit passes can proceed to
212    /// integration.
213    #[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    /// Creates a plain response from raw text as one `answer` string.
225    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    /// Returns display text by joining non-empty answer and question text with
236    /// blank lines.
237    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    /// Returns transcript text for session output by joining non-empty
246    /// `answer` content with blank lines.
247    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    /// Returns the answer as one single-item vector when it is non-empty.
255    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    /// Returns up to [`MAX_QUESTIONS`] clarification questions in response
265    /// order.
266    pub fn question_items(&self) -> Vec<QuestionItem> {
267        self.questions.iter().take(MAX_QUESTIONS).cloned().collect()
268    }
269
270    /// Returns up to [`MAX_SUBTASKS`] proposed subtasks in response order.
271    ///
272    /// Callers must still reject plans whose keys collide; this only bounds how
273    /// much of a runaway plan is considered.
274    pub fn subtask_items(&self) -> Vec<SubtaskItem> {
275        self.subtasks.iter().take(MAX_SUBTASKS).cloned().collect()
276    }
277
278    /// Returns up to [`MAX_SUBTASKS`] verification decisions in response
279    /// order.
280    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/// Structured response parsing failure details.
290#[derive(Debug, Clone, PartialEq, Eq)]
291pub enum AgentResponseParseError {
292    /// Response was empty or whitespace-only.
293    Empty,
294    /// Response was JSON, but it did not satisfy the structured protocol
295    /// contract.
296    InvalidFormat {
297        /// Explanation of the protocol contract violation.
298        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
315/// Appends one non-empty display message.
316fn 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
324/// Appends non-empty clarification question text in order.
325fn 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    /// Ensures the dynamic `questions` field description renders from the
337    /// checked-in prompt-schema template.
338    fn test_questions_field_description_renders_template_limit() {
339        // Arrange
340        let expected_limit = format!("Emit at most {MAX_QUESTIONS} items");
341
342        // Act
343        let description = questions_field_description();
344        let normalized_description = description.split_whitespace().collect::<Vec<_>>().join(" ");
345
346        // Assert
347        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    /// Ensures display text includes the answer and clarification questions in
359    /// order.
360    fn test_agent_response_to_display_text_joins_answer_and_questions() {
361        // Arrange
362        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        // Act
371        let display_text = response.to_display_text();
372
373        // Assert
374        assert_eq!(display_text, "Primary answer\n\nNeed one clarification.");
375    }
376
377    #[test]
378    /// Preserves review-comment outcomes through the wire JSON contract.
379    fn test_agent_response_review_comment_outcomes_round_trip() {
380        // Arrange
381        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        // Act
394        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
399        assert_eq!(deserialized, response);
400        assert!(serialized.contains(r#""resolution":"fixed""#));
401    }
402
403    #[test]
404    /// Ensures question extraction respects the protocol question cap.
405    fn test_agent_response_question_items_applies_question_cap() {
406        // Arrange
407        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        // Act
418        let questions = response.question_items();
419
420        // Assert
421        assert_eq!(questions.len(), MAX_QUESTIONS);
422    }
423
424    #[test]
425    /// Ensures subtask extraction respects the protocol subtask cap so a
426    /// runaway plan cannot fan out past the bounded child-session budget.
427    fn test_agent_response_subtask_items_applies_subtask_cap() {
428        // Arrange
429        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        // Act
438        let subtasks = response.subtask_items();
439
440        // Assert
441        assert_eq!(subtasks.len(), MAX_SUBTASKS);
442        assert_eq!(subtasks[0].task_key, "task-0");
443    }
444
445    #[test]
446    /// Preserves proposed subtasks through the wire JSON contract and keeps
447    /// them absent from ordinary responses.
448    fn test_agent_response_subtasks_round_trip() {
449        // Arrange
450        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        // Act
459        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
464        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    /// Preserves typed verification decisions through JSON and applies the
474    /// same bounded task count as orchestration plans.
475    fn test_agent_response_verification_verdicts_round_trip_and_cap() {
476        // Arrange
477        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        // Act
492        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
498        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    /// Ensures optional `touched_areas` planning guidance defaults to an empty
505    /// list instead of failing the whole turn.
506    fn test_subtask_item_defaults_touched_areas() {
507        // Arrange
508        let raw = r#"{"prompt":"Do the work","task_key":"task-1","title":"Work"}"#;
509
510        // Act
511        let subtask =
512            serde_json::from_str::<SubtaskItem>(raw).expect("subtask should parse without areas");
513
514        // Assert
515        assert_eq!(subtask.kind, crate::SubtaskKind::Implementation);
516        assert_eq!(subtask.touched_areas, [] as [std::string::String; 0]);
517    }
518
519    #[test]
520    /// Keeps the injected `subtasks` schema description in sync with the
521    /// server-side cap the parser enforces.
522    fn test_subtasks_field_description_reports_the_subtask_cap() {
523        // Arrange
524        let expected_limit = format!("at most {MAX_SUBTASKS} items");
525
526        // Act
527        let description = subtasks_field_description();
528        let normalized_description = description.split_whitespace().collect::<Vec<_>>().join(" ");
529
530        // Assert
531        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    /// Substitutes a cap placeholder that markdown reflowing wrapped across a
548    /// line break, so reformatting a template cannot leak raw `{{ ... }}` text
549    /// into the schema description models read.
550    fn test_field_description_template_survives_a_wrapped_placeholder() {
551        // Arrange
552        let template = "Emit at most {{\nmax_items }} items, and no more.\n";
553
554        // Act
555        let rendered = render_field_description_template(template, "{{ max_items }}", 4);
556
557        // Assert
558        assert_eq!(rendered, "Emit at most 4 items, and no more.");
559    }
560
561    #[test]
562    /// Leaves an unterminated placeholder untouched instead of truncating the
563    /// remaining guidance text.
564    fn test_field_description_template_keeps_unterminated_placeholder_text() {
565        // Arrange
566        let template = "Emit at most {{ max_items items.";
567
568        // Act
569        let rendered = render_field_description_template(template, "{{ max_items }}", 4);
570
571        // Assert
572        assert_eq!(rendered, "Emit at most {{ max_items items.");
573    }
574
575    /// Builds one deterministic subtask with a touched-area planning hint.
576    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}