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 isolated utility prompts share the same
95/// top-level [`AgentResponse`] schema. Agentty still carries the request
96/// family through transport boundaries so call sites can keep one consistent
97/// protocol contract even when some callers ignore parts of the response.
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99#[non_exhaustive]
100pub enum ProtocolRequestProfile {
101    /// Interactive session turn.
102    SessionTurn,
103    /// Isolated utility prompt.
104    UtilityPrompt,
105}
106
107/// Agent-reported disposition for one forge review thread.
108#[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    /// The agent completed the requested action and the thread can be
116    /// resolved after its reply is posted.
117    Fixed,
118    /// The agent determined that no code or documentation change was needed;
119    /// its explanatory reply is posted while the thread remains open.
120    NoChangeNeeded,
121}
122
123/// Structured outcome for one forge review thread targeted by the turn.
124#[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    /// Concise forge reply explaining what changed or why no change was needed.
132    #[schemars(
133        title = "reply",
134        description = "Concise reply suitable for posting to the forge review thread."
135    )]
136    pub reply: String,
137    /// Whether the thread was fixed or did not require a change.
138    #[schemars(
139        title = "resolution",
140        description = "Whether the targeted thread was fixed or required no change."
141    )]
142    pub resolution: ReviewCommentResolution,
143    /// Opaque forge thread identifier copied exactly from the turn prompt.
144    #[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/// Wire-format protocol payload used for schema-driven provider output.
152///
153/// Providers that support output schemas (for example, Codex app-server) are
154/// asked to emit this object as the entire assistant response payload.
155#[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    /// Markdown answer text emitted for this turn.
165    #[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    /// Ordered clarification questions emitted for this turn.
174    ///
175    /// The canonical JSON Schema description for this field is produced by
176    /// [`questions_field_description`] and injected at schema generation time
177    /// by `inject_dynamic_schema_guidance`. The static `schemars` metadata
178    /// here only sets the field title; the description is intentionally
179    /// omitted so the helper is the single source of truth.
180    #[serde(default)]
181    #[schemars(title = "questions")]
182    pub questions: Vec<QuestionItem>,
183    /// Per-thread outcomes for an agent-driven forge comment-resolution turn.
184    ///
185    /// Ordinary session and utility turns leave this empty. Resolution
186    /// workflows accept only identifiers explicitly allowlisted in the turn
187    /// prompt before applying any forge-side effect.
188    #[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    /// Proposed child-session subtasks for an orchestrator planning turn.
197    ///
198    /// The canonical JSON Schema description is produced by
199    /// [`subtasks_field_description`] and injected at schema generation time,
200    /// so the static `schemars` metadata here only sets the field title.
201    /// Ordinary session and utility turns leave this empty, and orchestration
202    /// consumers ignore it unless the turn prompt asked for a plan.
203    #[serde(default)]
204    #[schemars(title = "subtasks")]
205    pub subtasks: Vec<SubtaskItem>,
206    /// Per-task decisions emitted for an orchestration verification turn.
207    ///
208    /// Ordinary turns leave this empty. The controller must copy task keys
209    /// from the coordinator envelope so only explicit passes can proceed to
210    /// integration.
211    #[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    /// Creates a plain response from raw text as one `answer` string.
223    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    /// Returns display text by joining non-empty answer and question text with
234    /// blank lines.
235    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    /// Returns transcript text for session output by joining non-empty
244    /// `answer` content with blank lines.
245    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    /// Returns the answer as one single-item vector when it is non-empty.
253    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    /// Returns up to [`MAX_QUESTIONS`] clarification questions in response
263    /// order.
264    pub fn question_items(&self) -> Vec<QuestionItem> {
265        self.questions.iter().take(MAX_QUESTIONS).cloned().collect()
266    }
267
268    /// Returns up to [`MAX_SUBTASKS`] proposed subtasks in response order.
269    ///
270    /// Callers must still reject plans whose keys collide; this only bounds how
271    /// much of a runaway plan is considered.
272    pub fn subtask_items(&self) -> Vec<SubtaskItem> {
273        self.subtasks.iter().take(MAX_SUBTASKS).cloned().collect()
274    }
275
276    /// Returns up to [`MAX_SUBTASKS`] verification decisions in response
277    /// order.
278    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/// Structured response parsing failure details.
288#[derive(Debug, Clone, PartialEq, Eq)]
289pub enum AgentResponseParseError {
290    /// Response was empty or whitespace-only.
291    Empty,
292    /// Response was JSON, but it did not satisfy the structured protocol
293    /// contract.
294    InvalidFormat {
295        /// Explanation of the protocol contract violation.
296        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
313/// Appends one non-empty display message.
314fn 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
322/// Appends non-empty clarification question text in order.
323fn 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    /// Ensures the dynamic `questions` field description renders from the
335    /// checked-in prompt-schema template.
336    fn test_questions_field_description_renders_template_limit() {
337        // Arrange
338        let expected_limit = format!("Emit at most {MAX_QUESTIONS} items");
339
340        // Act
341        let description = questions_field_description();
342        let normalized_description = description.split_whitespace().collect::<Vec<_>>().join(" ");
343
344        // Assert
345        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    /// Ensures display text includes the answer and clarification questions in
357    /// order.
358    fn test_agent_response_to_display_text_joins_answer_and_questions() {
359        // Arrange
360        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        // Act
369        let display_text = response.to_display_text();
370
371        // Assert
372        assert_eq!(display_text, "Primary answer\n\nNeed one clarification.");
373    }
374
375    #[test]
376    /// Preserves review-comment outcomes through the wire JSON contract.
377    fn test_agent_response_review_comment_outcomes_round_trip() {
378        // Arrange
379        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        // Act
392        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
397        assert_eq!(deserialized, response);
398        assert!(serialized.contains(r#""resolution":"fixed""#));
399    }
400
401    #[test]
402    /// Ensures question extraction respects the protocol question cap.
403    fn test_agent_response_question_items_applies_question_cap() {
404        // Arrange
405        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        // Act
416        let questions = response.question_items();
417
418        // Assert
419        assert_eq!(questions.len(), MAX_QUESTIONS);
420    }
421
422    #[test]
423    /// Ensures subtask extraction respects the protocol subtask cap so a
424    /// runaway plan cannot fan out past the bounded child-session budget.
425    fn test_agent_response_subtask_items_applies_subtask_cap() {
426        // Arrange
427        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        // Act
436        let subtasks = response.subtask_items();
437
438        // Assert
439        assert_eq!(subtasks.len(), MAX_SUBTASKS);
440        assert_eq!(subtasks[0].task_key, "task-0");
441    }
442
443    #[test]
444    /// Preserves proposed subtasks through the wire JSON contract and keeps
445    /// them absent from ordinary responses.
446    fn test_agent_response_subtasks_round_trip() {
447        // Arrange
448        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        // Act
457        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
462        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    /// Preserves typed verification decisions through JSON and applies the
472    /// same bounded task count as orchestration plans.
473    fn test_agent_response_verification_verdicts_round_trip_and_cap() {
474        // Arrange
475        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        // Act
490        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
496        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    /// Ensures optional `touched_areas` planning guidance defaults to an empty
503    /// list instead of failing the whole turn.
504    fn test_subtask_item_defaults_touched_areas() {
505        // Arrange
506        let raw = r#"{"prompt":"Do the work","task_key":"task-1","title":"Work"}"#;
507
508        // Act
509        let subtask =
510            serde_json::from_str::<SubtaskItem>(raw).expect("subtask should parse without areas");
511
512        // Assert
513        assert_eq!(subtask.kind, crate::SubtaskKind::Implementation);
514        assert_eq!(subtask.touched_areas, [] as [std::string::String; 0]);
515    }
516
517    #[test]
518    /// Keeps the injected `subtasks` schema description in sync with the
519    /// server-side cap the parser enforces.
520    fn test_subtasks_field_description_reports_the_subtask_cap() {
521        // Arrange
522        let expected_limit = format!("at most {MAX_SUBTASKS} items");
523
524        // Act
525        let description = subtasks_field_description();
526        let normalized_description = description.split_whitespace().collect::<Vec<_>>().join(" ");
527
528        // Assert
529        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    /// Substitutes a cap placeholder that markdown reflowing wrapped across a
546    /// line break, so reformatting a template cannot leak raw `{{ ... }}` text
547    /// into the schema description models read.
548    fn test_field_description_template_survives_a_wrapped_placeholder() {
549        // Arrange
550        let template = "Emit at most {{\nmax_items }} items, and no more.\n";
551
552        // Act
553        let rendered = render_field_description_template(template, "{{ max_items }}", 4);
554
555        // Assert
556        assert_eq!(rendered, "Emit at most 4 items, and no more.");
557    }
558
559    #[test]
560    /// Leaves an unterminated placeholder untouched instead of truncating the
561    /// remaining guidance text.
562    fn test_field_description_template_keeps_unterminated_placeholder_text() {
563        // Arrange
564        let template = "Emit at most {{ max_items items.";
565
566        // Act
567        let rendered = render_field_description_template(template, "{{ max_items }}", 4);
568
569        // Assert
570        assert_eq!(rendered, "Emit at most {{ max_items items.");
571    }
572
573    /// Builds one deterministic subtask with a touched-area planning hint.
574    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}