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