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