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