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;
9
10/// Protocol-owned request family preserved across prompt submission and repair
11/// retries.
12///
13/// Session turns use [`AgentResponse`]. Isolated utilities, reviews, and
14/// metadata reconciliation have narrow wire schemas and normalize into
15/// `AgentResponse` only after request-specific validation.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17#[non_exhaustive]
18pub enum ProtocolRequestProfile {
19    /// Isolated focused review with a direct structured review response.
20    FocusedReview,
21    /// Direct review-request title and description reconciliation.
22    ReviewMetadata,
23    /// Interactive session turn.
24    SessionTurn,
25    /// Isolated utility prompt.
26    UtilityPrompt,
27}
28
29/// Minimal wire response for isolated text generation tasks.
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
31#[serde(deny_unknown_fields)]
32pub struct UtilityResponse {
33    /// Requested result, without commentary or session control fields.
34    pub answer: String,
35}
36
37/// Direct wire response for review-request metadata reconciliation.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
39#[serde(deny_unknown_fields)]
40pub struct ReviewMetadata {
41    /// Proposed description; user-owned content must be preserved.
42    pub description: String,
43    /// Whether a replaced primary objective makes the current title misleading.
44    pub is_title_change_significant: bool,
45    /// Proposed single-line title.
46    pub title: String,
47}
48
49/// Agent-reported disposition for one forge review thread.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
51#[serde(rename_all = "snake_case")]
52#[schemars(
53    title = "ReviewCommentResolution",
54    description = "Disposition reported for one targeted forge review thread."
55)]
56pub enum ReviewCommentResolution {
57    /// The agent completed the requested action and the thread can be
58    /// resolved after its reply is posted.
59    Fixed,
60    /// The agent determined that no code or documentation change was needed;
61    /// its explanatory reply is posted while the thread remains open.
62    NoChangeNeeded,
63}
64
65/// Structured outcome for one forge review thread targeted by the turn.
66#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
67#[schemars(
68    title = "ReviewCommentOutcome",
69    description = "Structured outcome for one forge review thread explicitly included in the turn \
70                   prompt."
71)]
72pub struct ReviewCommentOutcome {
73    /// Concise forge reply explaining what changed or why no change was needed.
74    #[schemars(
75        title = "reply",
76        description = "Concise reply suitable for posting to the forge review thread."
77    )]
78    pub reply: String,
79    /// Whether the thread was fixed or did not require a change.
80    #[schemars(
81        title = "resolution",
82        description = "Whether the targeted thread was fixed or required no change."
83    )]
84    pub resolution: ReviewCommentResolution,
85    /// Opaque forge thread identifier copied exactly from the turn prompt.
86    #[schemars(
87        title = "thread_id",
88        description = "Opaque forge thread identifier copied exactly from the turn prompt."
89    )]
90    pub thread_id: String,
91}
92
93/// Wire-format protocol payload used for schema-driven provider output.
94///
95/// Providers that support output schemas (for example, Codex app-server) are
96/// asked to emit this object as the entire assistant response payload.
97#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
98#[schemars(
99    title = "AgentResponse",
100    description = "Wire-format protocol payload used for schema-driven provider output. Return \
101                   this object as the entire assistant response payload. Providers that support \
102                   output schemas (for example, Codex app-server) are asked to emit this object \
103                   directly."
104)]
105pub struct AgentResponse {
106    /// Markdown answer text emitted for this turn.
107    #[serde(default)]
108    #[schemars(
109        title = "answer",
110        description = "Markdown answer text for delivered work, status updates, or concise \
111                       completion notes. Keep clarification requests out of this field and emit \
112                       them through `questions` instead."
113    )]
114    pub answer: String,
115    /// Ordered clarification questions emitted for this turn.
116    ///
117    /// The canonical JSON Schema description for this field is produced by
118    /// [`questions_field_description`] and injected at schema generation time
119    /// by `inject_dynamic_schema_guidance`. The static `schemars` metadata
120    /// here only sets the field title; the description is intentionally
121    /// omitted so the helper is the single source of truth.
122    #[serde(default)]
123    #[schemars(title = "questions")]
124    pub questions: Vec<QuestionItem>,
125    /// Per-thread outcomes for an agent-driven forge comment-resolution turn.
126    ///
127    /// Ordinary session and utility turns leave this empty. Resolution
128    /// workflows accept only identifiers explicitly allowlisted in the turn
129    /// prompt before applying any forge-side effect.
130    #[serde(default)]
131    #[schemars(
132        title = "review_comment_outcomes",
133        description = "Per-thread outcomes for an agent-driven forge comment-resolution turn. \
134                       Emit an empty array unless the prompt explicitly supplies forge thread \
135                       IDs. Copy each reported `thread_id` exactly from the prompt."
136    )]
137    pub review_comment_outcomes: Vec<ReviewCommentOutcome>,
138}
139
140impl AgentResponse {
141    /// Creates a plain response from raw text as one `answer` string.
142    pub fn plain(text: impl Into<String>) -> Self {
143        Self {
144            answer: text.into(),
145            questions: Vec::new(),
146            review_comment_outcomes: Vec::new(),
147        }
148    }
149
150    /// Returns display text by joining non-empty answer and question text with
151    /// blank lines.
152    pub fn to_display_text(&self) -> String {
153        let mut display_messages = Vec::new();
154        push_display_message(&mut display_messages, &self.answer);
155        push_question_display_messages(&mut display_messages, &self.questions);
156
157        display_messages.join("\n\n")
158    }
159
160    /// Returns transcript text for session output by joining non-empty
161    /// `answer` content with blank lines.
162    pub fn to_answer_display_text(&self) -> String {
163        let mut display_messages = Vec::new();
164        push_display_message(&mut display_messages, &self.answer);
165
166        display_messages.join("\n\n")
167    }
168
169    /// Returns the answer as one single-item vector when it is non-empty.
170    pub fn answers(&self) -> Vec<String> {
171        let answer = self.to_answer_display_text();
172        if answer.is_empty() {
173            return Vec::new();
174        }
175
176        vec![answer]
177    }
178
179    /// Returns up to [`MAX_QUESTIONS`] clarification questions in response
180    /// order.
181    pub fn question_items(&self) -> Vec<QuestionItem> {
182        self.questions.iter().take(MAX_QUESTIONS).cloned().collect()
183    }
184}
185
186/// Structured response parsing failure details.
187#[derive(Debug, Clone, PartialEq, Eq)]
188pub enum AgentResponseParseError {
189    /// Response was empty or whitespace-only.
190    Empty,
191    /// Response was JSON, but it did not satisfy the structured protocol
192    /// contract.
193    InvalidFormat {
194        /// Explanation of the protocol contract violation.
195        reason: String,
196    },
197}
198
199impl fmt::Display for AgentResponseParseError {
200    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
201        match self {
202            Self::Empty => write!(formatter, "response is empty"),
203            Self::InvalidFormat { reason } => {
204                write!(formatter, "response is not valid protocol JSON: {reason}")
205            }
206        }
207    }
208}
209
210impl std::error::Error for AgentResponseParseError {}
211
212/// Hard cap on the number of clarification questions extracted from one agent
213/// response. Prevents runaway output from flooding the question UI even when
214/// the agent ignores the prompt-level limit.
215///
216/// This constant is also injected into the protocol instruction prompt
217/// templates so the prompt-level guidance and the server-side cap stay in
218/// sync automatically.
219pub(crate) const MAX_QUESTIONS: usize = 5;
220/// Returns the canonical JSON Schema description for the `questions` field.
221///
222/// This is the single source of truth for the runtime-injected schema
223/// description and the matching test expectation. The static `schemars`
224/// metadata on `AgentResponse::questions` is overwritten by
225/// `inject_dynamic_schema_guidance` before any consumer observes the schema,
226/// so all schema-facing call sites must route through this helper to stay in
227/// sync.
228pub(crate) fn questions_field_description() -> String {
229    render_field_description_template(
230        QUESTIONS_FIELD_DESCRIPTION_TEMPLATE,
231        "{{ max_questions }}",
232        MAX_QUESTIONS,
233    )
234}
235
236const QUESTIONS_FIELD_DESCRIPTION_TEMPLATE: &str =
237    include_str!("template/questions_field_description.md");
238
239/// Appends one non-empty display message.
240fn push_display_message(display_messages: &mut Vec<String>, text: &str) {
241    if text.trim().is_empty() {
242        return;
243    }
244
245    display_messages.push(text.to_string());
246}
247
248/// Appends non-empty clarification question text in order.
249fn push_question_display_messages(display_messages: &mut Vec<String>, questions: &[QuestionItem]) {
250    for question in questions {
251        push_display_message(display_messages, &question.text);
252    }
253}
254
255/// Substitutes one `{{ name }}` placeholder with a runtime cap value.
256///
257/// The placeholder is matched after collapsing whitespace runs inside every
258/// `{{ ... }}` span, because `mdformat` reflows these templates at a fixed
259/// column width and will break a line in the middle of a placeholder. Matching
260/// the literal text alone silently left the raw `{{ ... }}` in the description
261/// shown to models, so normalization keeps the templates safe to reformat.
262fn render_field_description_template(template: &str, placeholder: &str, value: usize) -> String {
263    let mut rendered = String::with_capacity(template.len());
264    let mut remaining = template.trim_end();
265
266    while let Some(open_index) = remaining.find("{{") {
267        let after_open = &remaining[open_index..];
268        let Some(close_end) = after_open.find("}}").map(|index| index + "}}".len()) else {
269            break;
270        };
271
272        rendered.push_str(&remaining[..open_index]);
273        rendered.push_str(&collapse_whitespace(&after_open[..close_end]));
274        remaining = &after_open[close_end..];
275    }
276    rendered.push_str(remaining);
277
278    rendered.replace(placeholder, &value.to_string())
279}
280
281/// Collapses every whitespace run in `text` to one space.
282fn collapse_whitespace(text: &str) -> String {
283    text.split_whitespace().collect::<Vec<_>>().join(" ")
284}
285
286#[cfg(test)]
287#[path = "model_test.rs"]
288mod tests;