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)]
332#[path = "model_test.rs"]
333mod tests;