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