Skip to main content

ag_protocol/
parse.rs

1//! Structured response parsing and streaming normalization helpers.
2
3use serde_json::Value;
4
5use super::model::{AgentResponse, AgentResponseParseError, ProtocolRequestProfile};
6use super::review::{FocusedReview, FocusedReviewSeverity};
7
8/// Top-level keys the protocol recognizes in a structured response payload.
9const PROTOCOL_KEYS: &[&str] = &[
10    "answer",
11    "questions",
12    "review_comment_outcomes",
13    "subtasks",
14    "verification_verdicts",
15];
16
17/// Parses one raw assistant message strictly as protocol payload.
18///
19/// The final assistant payload must match [`AgentResponse`] and contain at
20/// least one recognized protocol key (`answer`, `questions`,
21/// `review_comment_outcomes`, `subtasks`, or `verification_verdicts`).
22///
23/// When a provider prepends stray prose before the final schema object, this
24/// still recovers the trailing protocol payload as long as nothing except
25/// whitespace follows the JSON object. As a further resilience fallback,
26/// markdown code fences wrapping the JSON object are stripped before parsing
27/// when neither direct parsing nor trailing-object recovery succeeds. An
28/// additional fallback extracts JSON from an embedded code fence preceded by
29/// prose text (e.g., commentary followed by a fenced JSON block).
30/// Top-level fields may rely on the wire type's defaults.
31///
32/// # Errors
33/// Returns [`AgentResponseParseError`] when no valid protocol payload is found.
34pub fn parse_agent_response_strict(raw: &str) -> Result<AgentResponse, AgentResponseParseError> {
35    let trimmed = raw.trim();
36    if trimmed.is_empty() {
37        return Err(AgentResponseParseError::Empty);
38    }
39
40    let direct_parse = parse_structured_json_response_with_reason(trimmed);
41    if let Ok(response) = direct_parse {
42        return Ok(response);
43    }
44
45    let direct_parse_error = match direct_parse {
46        Err(error) => error.to_string(),
47        Ok(_) => unreachable!("direct parse branch already returned successful parse"),
48    };
49
50    if let Some(inner) = strip_markdown_code_fence(trimmed) {
51        if let Some(response) = parse_structured_json_response_with_recovery(inner) {
52            return Ok(response);
53        }
54
55        let fence_parse_error = parse_structured_json_response_with_reason(inner)
56            .err()
57            .map_or_else(
58                || "no protocol payload found in markdown code fence".to_string(),
59                |error| error.to_string(),
60            );
61
62        return Err(AgentResponseParseError::InvalidFormat {
63            reason: format!("markdown code fence extraction failed ({fence_parse_error})"),
64        });
65    }
66
67    if let Some(inner) = find_embedded_code_fence_content(trimmed)
68        && let Some(response) = parse_structured_json_response_with_recovery(inner)
69    {
70        return Ok(response);
71    }
72
73    if let Some(response) = recover_embedded_structured_json_response(trimmed) {
74        return Ok(response);
75    }
76
77    Err(AgentResponseParseError::InvalidFormat {
78        reason: format!(
79            "direct parse failed ({direct_parse_error}); no markdown wrapper/embedded protocol \
80             object found"
81        ),
82    })
83}
84
85/// Parses one response against the schema selected for its request profile.
86///
87/// Focused reviews arrive as direct [`FocusedReview`] objects so native
88/// provider schemas can enforce their fields. The validated object is
89/// normalized back into `AgentResponse::answer` for existing application
90/// consumers.
91///
92/// # Errors
93/// Returns [`AgentResponseParseError`] when the response is empty or does not
94/// match the profile's structured response schema.
95pub fn parse_protocol_response_strict(
96    raw: &str,
97    profile: ProtocolRequestProfile,
98) -> Result<AgentResponse, AgentResponseParseError> {
99    if !matches!(profile, ProtocolRequestProfile::FocusedReview) {
100        return parse_agent_response_strict(raw);
101    }
102
103    let trimmed = raw.trim();
104    if trimmed.is_empty() {
105        return Err(AgentResponseParseError::Empty);
106    }
107
108    let review = serde_json::from_str::<FocusedReview>(trimmed).map_err(|error| {
109        AgentResponseParseError::InvalidFormat {
110            reason: format!("focused review parse failed ({error})"),
111        }
112    })?;
113    let answer = focused_review_answer(review);
114
115    Ok(AgentResponse::plain(answer))
116}
117
118/// Serializes a validated focused review through infallible JSON values.
119fn focused_review_answer(review: FocusedReview) -> String {
120    let project_impact = review
121        .project_impact
122        .into_iter()
123        .map(Value::String)
124        .collect();
125    let suggestions = review
126        .suggestions
127        .into_iter()
128        .map(|suggestion| {
129            let severity = match suggestion.severity {
130                FocusedReviewSeverity::High => "high",
131                FocusedReviewSeverity::Medium => "medium",
132            };
133
134            Value::Object(
135                [
136                    ("details".to_string(), Value::String(suggestion.details)),
137                    ("severity".to_string(), Value::String(severity.to_string())),
138                ]
139                .into_iter()
140                .collect(),
141            )
142        })
143        .collect();
144
145    Value::Object(
146        [
147            ("project_impact".to_string(), Value::Array(project_impact)),
148            ("suggestions".to_string(), Value::Array(suggestions)),
149        ]
150        .into_iter()
151        .collect(),
152    )
153    .to_string()
154}
155
156/// Builds one multi-line debug report for a protocol parsing failure.
157///
158/// The report summarizes response sizing, markdown wrapping, JSON parse
159/// diagnostics, and any visible top-level keys so schema mismatch errors
160/// include enough context to diagnose malformed provider output quickly.
161///
162/// Every line is *derived* metadata: sizes, parser locations, and key names.
163/// No provider payload text is reproduced. Turn errors are rendered into the
164/// session transcript, so quoting the payload here would print raw provider
165/// output into the chat.
166pub fn format_protocol_parse_debug_details(raw: &str) -> String {
167    let trimmed = raw.trim();
168    let mut detail_lines = vec![
169        format!("response_len: {} chars", raw.chars().count()),
170        format!("response_lines: {}", raw.lines().count()),
171        format!("trimmed_len: {} chars", trimmed.chars().count()),
172        format!(
173            "wrapped_in_markdown_fence: {}",
174            strip_markdown_code_fence(trimmed).is_some()
175        ),
176    ];
177
178    if trimmed.is_empty() {
179        return detail_lines.join("\n");
180    }
181
182    push_character_boundary_debug_lines(&mut detail_lines, trimmed);
183    push_json_debug_lines(&mut detail_lines, "direct_json", trimmed);
184
185    if let Some(inner) = strip_markdown_code_fence(trimmed) {
186        detail_lines.push(format!(
187            "code_fence_inner_len: {} chars",
188            inner.chars().count()
189        ));
190        push_json_debug_lines(&mut detail_lines, "code_fence_json", inner);
191    }
192
193    if let Some(embedded_value) = find_last_embedded_json_value(trimmed) {
194        detail_lines.push("embedded_json_candidate: found".to_string());
195        push_json_value_debug_lines(&mut detail_lines, "embedded_json", &embedded_value);
196    } else {
197        detail_lines.push("embedded_json_candidate: none".to_string());
198    }
199
200    detail_lines.join("\n")
201}
202
203/// Parses one schema-driven JSON response and returns the structured error
204/// detail when the payload cannot be parsed or validated.
205fn parse_structured_json_response_with_reason(
206    raw: &str,
207) -> Result<AgentResponse, AgentResponseParseError> {
208    let value: Value = serde_json::from_str(raw.trim()).map_err(|error| {
209        AgentResponseParseError::InvalidFormat {
210            reason: format!("invalid JSON ({error})"),
211        }
212    })?;
213
214    if !value_has_recognized_protocol_key(&value) {
215        return Err(AgentResponseParseError::InvalidFormat {
216            reason: format!(
217                "json object is missing all protocol keys ({})",
218                PROTOCOL_KEYS.join(", ")
219            ),
220        });
221    }
222
223    serde_json::from_value(value).map_err(|error| AgentResponseParseError::InvalidFormat {
224        reason: format!("schema validation failed ({error})"),
225    })
226}
227
228/// Returns whether a parsed JSON value is an object containing at least one
229/// recognized protocol key.
230fn value_has_recognized_protocol_key(value: &Value) -> bool {
231    value
232        .as_object()
233        .is_some_and(|object| PROTOCOL_KEYS.iter().any(|key| object.contains_key(*key)))
234}
235
236/// Strips a leading markdown code fence and trailing closing fence from a
237/// trimmed response payload, returning the inner content if the pattern
238/// matches.
239fn strip_markdown_code_fence(trimmed: &str) -> Option<&str> {
240    let rest = trimmed.strip_prefix("```")?;
241    let body_start = rest.find('\n').map(|index| index + 1)?;
242    let body = &rest[body_start..];
243    let inner = body.strip_suffix("```")?.trim();
244
245    if inner.is_empty() {
246        return None;
247    }
248
249    Some(inner)
250}
251
252/// Parses one full protocol payload and then falls back to recovering a
253/// trailing schema object from wrapped provider output.
254fn parse_structured_json_response_with_recovery(raw: &str) -> Option<AgentResponse> {
255    parse_structured_json_response(raw).or_else(|| recover_embedded_structured_json_response(raw))
256}
257
258/// Attempts to parse one schema-driven structured JSON response.
259///
260/// The raw text must parse as a JSON object containing at least one
261/// recognized protocol key from [`PROTOCOL_KEYS`]. Returns `None` when parsing
262/// fails or no recognized keys are present.
263fn parse_structured_json_response(raw: &str) -> Option<AgentResponse> {
264    parse_structured_json_response_with_reason(raw).ok()
265}
266
267/// Recovers one trailing protocol payload from provider output that starts
268/// with extra prose before the final JSON object.
269///
270/// This intentionally keeps trailing text strict: once a candidate JSON object
271/// parses successfully, only whitespace may remain after it. The candidate
272/// must also contain at least one recognized protocol key.
273fn recover_embedded_structured_json_response(raw: &str) -> Option<AgentResponse> {
274    let value = find_last_embedded_json_value(raw)?;
275    if !value_has_recognized_protocol_key(&value) {
276        return None;
277    }
278
279    serde_json::from_value(value).ok()
280}
281
282/// Extracts the inner content from the last markdown code fence embedded in a
283/// response that also contains surrounding prose text.
284///
285/// Handles the pattern where a provider prepends commentary before a fenced
286/// JSON payload (e.g., `"Some explanation\n` ` ```json\n{...}\n``` ` `"`).
287fn find_embedded_code_fence_content(raw: &str) -> Option<&str> {
288    let closing_fence_start = raw.rfind("```")?;
289    let before_closing = raw[..closing_fence_start].trim_end();
290
291    let opening_fence_start = before_closing.rfind("```")?;
292    let after_opening_backticks = &before_closing[opening_fence_start + 3..];
293
294    let body_start = after_opening_backticks.find('\n').map(|index| index + 1)?;
295    let inner = &after_opening_backticks[body_start..];
296    let trimmed = inner.trim();
297
298    if trimmed.is_empty() {
299        return None;
300    }
301
302    Some(trimmed)
303}
304
305/// Finds the last JSON object embedded in a response when it consumes the full
306/// trailing suffix except for whitespace.
307fn find_last_embedded_json_value(raw: &str) -> Option<Value> {
308    for (start_index, _) in raw.match_indices('{').rev() {
309        let candidate = &raw[start_index..];
310        let mut deserializer = serde_json::Deserializer::from_str(candidate).into_iter::<Value>();
311        let Some(Ok(value)) = deserializer.next() else {
312            continue;
313        };
314        let trailing_text = &candidate[deserializer.byte_offset()..];
315        if !trailing_text.trim().is_empty() {
316            continue;
317        }
318
319        return Some(value);
320    }
321
322    None
323}
324
325/// Appends stable character-boundary diagnostics for one trimmed response.
326fn push_character_boundary_debug_lines(detail_lines: &mut Vec<String>, trimmed: &str) {
327    if let Some(first_character) = trimmed.chars().next() {
328        detail_lines.push(format!("first_non_whitespace_char: {first_character:?}"));
329    }
330
331    if let Some(last_character) = trimmed.chars().last() {
332        detail_lines.push(format!("last_non_whitespace_char: {last_character:?}"));
333    }
334}
335
336/// Appends either JSON parse failure details or top-level JSON shape details.
337fn push_json_debug_lines(detail_lines: &mut Vec<String>, label: &str, raw: &str) {
338    match serde_json::from_str::<Value>(raw) {
339        Ok(value) => push_json_value_debug_lines(detail_lines, label, &value),
340        Err(error) => {
341            detail_lines.push(format!("{label}_error: {error}"));
342            detail_lines.push(format!(
343                "{label}_error_category: {}",
344                describe_json_error_category(&error)
345            ));
346            detail_lines.push(format!(
347                "{label}_error_location: line {}, column {}",
348                error.line(),
349                error.column()
350            ));
351        }
352    }
353}
354
355/// Appends the top-level JSON type and protocol-key visibility for one value.
356fn push_json_value_debug_lines(detail_lines: &mut Vec<String>, label: &str, value: &Value) {
357    detail_lines.push(format!("{label}_type: {}", describe_json_type(value)));
358
359    if let Some(object) = value.as_object() {
360        let mut keys = object.keys().cloned().collect::<Vec<_>>();
361        keys.sort_unstable();
362
363        let recognized_keys = PROTOCOL_KEYS
364            .iter()
365            .filter(|key| object.contains_key(**key))
366            .map(|key| (*key).to_string())
367            .collect::<Vec<_>>();
368        let missing_keys = PROTOCOL_KEYS
369            .iter()
370            .filter(|key| !object.contains_key(**key))
371            .map(|key| (*key).to_string())
372            .collect::<Vec<_>>();
373
374        detail_lines.push(format!("{label}_keys: {}", format_debug_list(&keys)));
375        detail_lines.push(format!(
376            "{label}_recognized_protocol_keys: {}",
377            format_debug_list(&recognized_keys)
378        ));
379        detail_lines.push(format!(
380            "{label}_missing_protocol_keys: {}",
381            format_debug_list(&missing_keys)
382        ));
383    }
384}
385
386/// Returns one stable label for a top-level JSON value type.
387fn describe_json_type(value: &Value) -> &'static str {
388    match value {
389        Value::Null => "null",
390        Value::Bool(_) => "boolean",
391        Value::Number(_) => "number",
392        Value::String(_) => "string",
393        Value::Array(_) => "array",
394        Value::Object(_) => "object",
395    }
396}
397
398/// Formats one debug list as a comma-separated string or `(none)`.
399fn format_debug_list(items: &[String]) -> String {
400    if items.is_empty() {
401        return "(none)".to_string();
402    }
403
404    items.join(", ")
405}
406
407/// Returns one stable label for the serde JSON error category.
408fn describe_json_error_category(error: &serde_json::Error) -> &'static str {
409    match error.classify() {
410        serde_json::error::Category::Io => "io",
411        serde_json::error::Category::Syntax => "syntax",
412        serde_json::error::Category::Data => "data",
413        serde_json::error::Category::Eof => "eof",
414    }
415}
416
417#[cfg(test)]
418#[path = "parse_test.rs"]
419mod tests;