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/// Protocol-owned request family preserved across prompt submission and repair
13/// retries.
14///
15/// Session turns use [`AgentResponse`]. Isolated utilities, reviews, and
16/// metadata reconciliation have narrow wire schemas and normalize into
17/// `AgentResponse` only after request-specific validation.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19#[non_exhaustive]
20pub enum ProtocolRequestProfile {
21    /// Isolated focused review with a direct structured review response.
22    FocusedReview,
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    /// Proposed child-session subtasks for an orchestrator planning turn.
141    ///
142    /// The canonical JSON Schema description is produced by
143    /// [`subtasks_field_description`] and injected at schema generation time,
144    /// so the static `schemars` metadata here only sets the field title.
145    /// Ordinary session and utility turns leave this empty, and orchestration
146    /// consumers ignore it unless the turn prompt asked for a plan.
147    #[serde(default)]
148    #[schemars(title = "subtasks")]
149    pub subtasks: Vec<SubtaskItem>,
150    /// Per-task decisions emitted for an orchestration verification turn.
151    ///
152    /// Ordinary turns leave this empty. The controller must copy task keys
153    /// from the coordinator envelope so only explicit passes can proceed to
154    /// integration.
155    #[serde(default)]
156    #[schemars(
157        title = "verification_verdicts",
158        description = "Per-task decisions for an orchestration verification turn. Emit one item \
159                       for every task in the verification envelope, and use an empty array for \
160                       ordinary turns."
161    )]
162    pub verification_verdicts: Vec<VerificationVerdictItem>,
163}
164
165impl AgentResponse {
166    /// Creates a plain response from raw text as one `answer` string.
167    pub fn plain(text: impl Into<String>) -> Self {
168        Self {
169            answer: text.into(),
170            questions: Vec::new(),
171            review_comment_outcomes: Vec::new(),
172            subtasks: Vec::new(),
173            verification_verdicts: Vec::new(),
174        }
175    }
176
177    /// Returns display text by joining non-empty answer and question text with
178    /// blank lines.
179    pub fn to_display_text(&self) -> String {
180        let mut display_messages = Vec::new();
181        push_display_message(&mut display_messages, &self.answer);
182        push_question_display_messages(&mut display_messages, &self.questions);
183
184        display_messages.join("\n\n")
185    }
186
187    /// Returns transcript text for session output by joining non-empty
188    /// `answer` content with blank lines.
189    pub fn to_answer_display_text(&self) -> String {
190        let mut display_messages = Vec::new();
191        push_display_message(&mut display_messages, &self.answer);
192
193        display_messages.join("\n\n")
194    }
195
196    /// Returns the answer as one single-item vector when it is non-empty.
197    pub fn answers(&self) -> Vec<String> {
198        let answer = self.to_answer_display_text();
199        if answer.is_empty() {
200            return Vec::new();
201        }
202
203        vec![answer]
204    }
205
206    /// Returns up to [`MAX_QUESTIONS`] clarification questions in response
207    /// order.
208    pub fn question_items(&self) -> Vec<QuestionItem> {
209        self.questions.iter().take(MAX_QUESTIONS).cloned().collect()
210    }
211
212    /// Returns up to [`MAX_SUBTASKS`] proposed subtasks in response order.
213    ///
214    /// Callers must still reject plans whose keys collide; this only bounds how
215    /// much of a runaway plan is considered.
216    pub fn subtask_items(&self) -> Vec<SubtaskItem> {
217        self.subtasks.iter().take(MAX_SUBTASKS).cloned().collect()
218    }
219
220    /// Returns up to [`MAX_SUBTASKS`] verification decisions in response
221    /// order.
222    pub fn verification_verdict_items(&self) -> Vec<VerificationVerdictItem> {
223        self.verification_verdicts
224            .iter()
225            .take(MAX_SUBTASKS)
226            .cloned()
227            .collect()
228    }
229}
230
231/// Structured response parsing failure details.
232#[derive(Debug, Clone, PartialEq, Eq)]
233pub enum AgentResponseParseError {
234    /// Response was empty or whitespace-only.
235    Empty,
236    /// Response was JSON, but it did not satisfy the structured protocol
237    /// contract.
238    InvalidFormat {
239        /// Explanation of the protocol contract violation.
240        reason: String,
241    },
242}
243
244impl fmt::Display for AgentResponseParseError {
245    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
246        match self {
247            Self::Empty => write!(formatter, "response is empty"),
248            Self::InvalidFormat { reason } => {
249                write!(formatter, "response is not valid protocol JSON: {reason}")
250            }
251        }
252    }
253}
254
255impl std::error::Error for AgentResponseParseError {}
256
257/// Hard cap on the number of clarification questions extracted from one agent
258/// response. Prevents runaway output from flooding the question UI even when
259/// the agent ignores the prompt-level limit.
260///
261/// This constant is also injected into the protocol instruction prompt
262/// templates so the prompt-level guidance and the server-side cap stay in
263/// sync automatically.
264pub(crate) const MAX_QUESTIONS: usize = 5;
265/// Hard cap on the number of subtasks accepted from one orchestrator planning
266/// turn. Bounds how many child sessions, worktrees, and agent CLI processes a
267/// single approved plan can create even when the agent ignores the
268/// prompt-level limit.
269pub(crate) const MAX_SUBTASKS: usize = 8;
270/// Returns the canonical JSON Schema description for the `questions` field.
271///
272/// This is the single source of truth for the runtime-injected schema
273/// description and the matching test expectation. The static `schemars`
274/// metadata on `AgentResponse::questions` is overwritten by
275/// `inject_dynamic_schema_guidance` before any consumer observes the schema,
276/// so all schema-facing call sites must route through this helper to stay in
277/// sync.
278pub(crate) fn questions_field_description() -> String {
279    render_field_description_template(
280        QUESTIONS_FIELD_DESCRIPTION_TEMPLATE,
281        "{{ max_questions }}",
282        MAX_QUESTIONS,
283    )
284}
285
286/// Returns the canonical JSON Schema description for the `subtasks` field.
287///
288/// This mirrors [`questions_field_description`]: the static `schemars`
289/// metadata on `AgentResponse::subtasks` carries only the field title, and
290/// `inject_dynamic_schema_guidance` overwrites the description with this
291/// helper's output before any consumer observes the schema.
292pub(crate) fn subtasks_field_description() -> String {
293    render_field_description_template(
294        SUBTASKS_FIELD_DESCRIPTION_TEMPLATE,
295        "{{ max_subtasks }}",
296        MAX_SUBTASKS,
297    )
298}
299
300const QUESTIONS_FIELD_DESCRIPTION_TEMPLATE: &str =
301    include_str!("template/questions_field_description.md");
302const SUBTASKS_FIELD_DESCRIPTION_TEMPLATE: &str =
303    include_str!("template/subtasks_field_description.md");
304
305/// Appends one non-empty display message.
306fn push_display_message(display_messages: &mut Vec<String>, text: &str) {
307    if text.trim().is_empty() {
308        return;
309    }
310
311    display_messages.push(text.to_string());
312}
313
314/// Appends non-empty clarification question text in order.
315fn push_question_display_messages(display_messages: &mut Vec<String>, questions: &[QuestionItem]) {
316    for question in questions {
317        push_display_message(display_messages, &question.text);
318    }
319}
320
321/// Substitutes one `{{ name }}` placeholder with a runtime cap value.
322///
323/// The placeholder is matched after collapsing whitespace runs inside every
324/// `{{ ... }}` span, because `mdformat` reflows these templates at a fixed
325/// column width and will break a line in the middle of a placeholder. Matching
326/// the literal text alone silently left the raw `{{ ... }}` in the description
327/// shown to models, so normalization keeps the templates safe to reformat.
328fn render_field_description_template(template: &str, placeholder: &str, value: usize) -> String {
329    let mut rendered = String::with_capacity(template.len());
330    let mut remaining = template.trim_end();
331
332    while let Some(open_index) = remaining.find("{{") {
333        let after_open = &remaining[open_index..];
334        let Some(close_end) = after_open.find("}}").map(|index| index + "}}".len()) else {
335            break;
336        };
337
338        rendered.push_str(&remaining[..open_index]);
339        rendered.push_str(&collapse_whitespace(&after_open[..close_end]));
340        remaining = &after_open[close_end..];
341    }
342    rendered.push_str(remaining);
343
344    rendered.replace(placeholder, &value.to_string())
345}
346
347/// Collapses every whitespace run in `text` to one space.
348fn collapse_whitespace(text: &str) -> String {
349    text.split_whitespace().collect::<Vec<_>>().join(" ")
350}
351
352#[cfg(test)]
353#[path = "model_test.rs"]
354mod tests;