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] = &[
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 = serde_json::json!(review).to_string();
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/// Builds one multi-line debug report for a protocol parsing failure.
151///
152/// The report summarizes response sizing, markdown wrapping, JSON parse
153/// diagnostics, and any visible top-level keys so schema mismatch errors
154/// include enough context to diagnose malformed provider output quickly.
155///
156/// Every line is *derived* metadata: sizes, parser locations, and key names.
157/// No provider payload text is reproduced. Turn errors are rendered into the
158/// session transcript, so quoting the payload here would print raw provider
159/// output into the chat.
160pub fn format_protocol_parse_debug_details(raw: &str) -> String {
161    let trimmed = raw.trim();
162    let mut detail_lines = vec![
163        format!("response_len: {} chars", raw.chars().count()),
164        format!("response_lines: {}", raw.lines().count()),
165        format!("trimmed_len: {} chars", trimmed.chars().count()),
166        format!(
167            "wrapped_in_markdown_fence: {}",
168            strip_markdown_code_fence(trimmed).is_some()
169        ),
170    ];
171
172    if trimmed.is_empty() {
173        return detail_lines.join("\n");
174    }
175
176    push_character_boundary_debug_lines(&mut detail_lines, trimmed);
177    push_json_debug_lines(&mut detail_lines, "direct_json", trimmed);
178
179    if let Some(inner) = strip_markdown_code_fence(trimmed) {
180        detail_lines.push(format!(
181            "code_fence_inner_len: {} chars",
182            inner.chars().count()
183        ));
184        push_json_debug_lines(&mut detail_lines, "code_fence_json", inner);
185    }
186
187    if let Some(embedded_value) = find_last_embedded_json_value(trimmed) {
188        detail_lines.push("embedded_json_candidate: found".to_string());
189        push_json_value_debug_lines(&mut detail_lines, "embedded_json", &embedded_value);
190    } else {
191        detail_lines.push("embedded_json_candidate: none".to_string());
192    }
193
194    detail_lines.join("\n")
195}
196
197/// Parses one schema-driven JSON response and returns the structured error
198/// detail when the payload cannot be parsed or validated.
199fn parse_structured_json_response_with_reason(
200    raw: &str,
201) -> Result<AgentResponse, AgentResponseParseError> {
202    let value: Value = serde_json::from_str(raw.trim()).map_err(|error| {
203        AgentResponseParseError::InvalidFormat {
204            reason: format!("invalid JSON ({error})"),
205        }
206    })?;
207
208    if !value_has_recognized_protocol_key(&value) {
209        return Err(AgentResponseParseError::InvalidFormat {
210            reason: format!(
211                "json object is missing all protocol keys ({})",
212                PROTOCOL_KEYS.join(", ")
213            ),
214        });
215    }
216
217    serde_json::from_value(value).map_err(|error| AgentResponseParseError::InvalidFormat {
218        reason: format!("schema validation failed ({error})"),
219    })
220}
221
222/// Returns whether a parsed JSON value is an object containing at least one
223/// recognized protocol key.
224fn value_has_recognized_protocol_key(value: &Value) -> bool {
225    value
226        .as_object()
227        .is_some_and(|object| PROTOCOL_KEYS.iter().any(|key| object.contains_key(*key)))
228}
229
230/// Strips a leading markdown code fence and trailing closing fence from a
231/// trimmed response payload, returning the inner content if the pattern
232/// matches.
233fn strip_markdown_code_fence(trimmed: &str) -> Option<&str> {
234    let rest = trimmed.strip_prefix("```")?;
235    let body_start = rest.find('\n').map(|index| index + 1)?;
236    let body = &rest[body_start..];
237    let inner = body.strip_suffix("```")?.trim();
238
239    if inner.is_empty() {
240        return None;
241    }
242
243    Some(inner)
244}
245
246/// Parses one full protocol payload and then falls back to recovering a
247/// trailing schema object from wrapped provider output.
248fn parse_structured_json_response_with_recovery(raw: &str) -> Option<AgentResponse> {
249    parse_structured_json_response(raw).or_else(|| recover_embedded_structured_json_response(raw))
250}
251
252/// Attempts to parse one schema-driven structured JSON response.
253///
254/// The raw text must parse as a JSON object containing at least one
255/// recognized protocol key from [`PROTOCOL_KEYS`]. Returns `None` when parsing
256/// fails or no recognized keys are present.
257fn parse_structured_json_response(raw: &str) -> Option<AgentResponse> {
258    parse_structured_json_response_with_reason(raw).ok()
259}
260
261/// Recovers one trailing protocol payload from provider output that starts
262/// with extra prose before the final JSON object.
263///
264/// This intentionally keeps trailing text strict: once a candidate JSON object
265/// parses successfully, only whitespace may remain after it. The candidate
266/// must also contain at least one recognized protocol key.
267fn recover_embedded_structured_json_response(raw: &str) -> Option<AgentResponse> {
268    let value = find_last_embedded_json_value(raw)?;
269    if !value_has_recognized_protocol_key(&value) {
270        return None;
271    }
272
273    serde_json::from_value(value).ok()
274}
275
276/// Extracts the inner content from the last markdown code fence embedded in a
277/// response that also contains surrounding prose text.
278///
279/// Handles the pattern where a provider prepends commentary before a fenced
280/// JSON payload (e.g., `"Some explanation\n` ` ```json\n{...}\n``` ` `"`).
281fn find_embedded_code_fence_content(raw: &str) -> Option<&str> {
282    let closing_fence_start = raw.rfind("```")?;
283    let before_closing = raw[..closing_fence_start].trim_end();
284
285    let opening_fence_start = before_closing.rfind("```")?;
286    let after_opening_backticks = &before_closing[opening_fence_start + 3..];
287
288    let body_start = after_opening_backticks.find('\n').map(|index| index + 1)?;
289    let inner = &after_opening_backticks[body_start..];
290    let trimmed = inner.trim();
291
292    if trimmed.is_empty() {
293        return None;
294    }
295
296    Some(trimmed)
297}
298
299/// Finds the last JSON object embedded in a response when it consumes the full
300/// trailing suffix except for whitespace.
301fn find_last_embedded_json_value(raw: &str) -> Option<Value> {
302    for (start_index, _) in raw.match_indices('{').rev() {
303        let candidate = &raw[start_index..];
304        let mut deserializer = serde_json::Deserializer::from_str(candidate).into_iter::<Value>();
305        let Some(Ok(value)) = deserializer.next() else {
306            continue;
307        };
308        let trailing_text = &candidate[deserializer.byte_offset()..];
309        if !trailing_text.trim().is_empty() {
310            continue;
311        }
312
313        return Some(value);
314    }
315
316    None
317}
318
319/// Appends stable character-boundary diagnostics for one trimmed response.
320fn push_character_boundary_debug_lines(detail_lines: &mut Vec<String>, trimmed: &str) {
321    if let Some(first_character) = trimmed.chars().next() {
322        detail_lines.push(format!("first_non_whitespace_char: {first_character:?}"));
323    }
324
325    if let Some(last_character) = trimmed.chars().last() {
326        detail_lines.push(format!("last_non_whitespace_char: {last_character:?}"));
327    }
328}
329
330/// Appends either JSON parse failure details or top-level JSON shape details.
331fn push_json_debug_lines(detail_lines: &mut Vec<String>, label: &str, raw: &str) {
332    match serde_json::from_str::<Value>(raw) {
333        Ok(value) => push_json_value_debug_lines(detail_lines, label, &value),
334        Err(error) => {
335            detail_lines.push(format!("{label}_error: {error}"));
336            detail_lines.push(format!(
337                "{label}_error_category: {}",
338                describe_json_error_category(&error)
339            ));
340            detail_lines.push(format!(
341                "{label}_error_location: line {}, column {}",
342                error.line(),
343                error.column()
344            ));
345        }
346    }
347}
348
349/// Appends the top-level JSON type and protocol-key visibility for one value.
350fn push_json_value_debug_lines(detail_lines: &mut Vec<String>, label: &str, value: &Value) {
351    detail_lines.push(format!("{label}_type: {}", describe_json_type(value)));
352
353    if let Some(object) = value.as_object() {
354        let mut keys = object.keys().cloned().collect::<Vec<_>>();
355        keys.sort_unstable();
356
357        let recognized_keys = PROTOCOL_KEYS
358            .iter()
359            .filter(|key| object.contains_key(**key))
360            .map(|key| (*key).to_string())
361            .collect::<Vec<_>>();
362        let missing_keys = PROTOCOL_KEYS
363            .iter()
364            .filter(|key| !object.contains_key(**key))
365            .map(|key| (*key).to_string())
366            .collect::<Vec<_>>();
367
368        detail_lines.push(format!("{label}_keys: {}", format_debug_list(&keys)));
369        detail_lines.push(format!(
370            "{label}_recognized_protocol_keys: {}",
371            format_debug_list(&recognized_keys)
372        ));
373        detail_lines.push(format!(
374            "{label}_missing_protocol_keys: {}",
375            format_debug_list(&missing_keys)
376        ));
377    }
378}
379
380/// Returns one stable label for a top-level JSON value type.
381fn describe_json_type(value: &Value) -> &'static str {
382    match value {
383        Value::Null => "null",
384        Value::Bool(_) => "boolean",
385        Value::Number(_) => "number",
386        Value::String(_) => "string",
387        Value::Array(_) => "array",
388        Value::Object(_) => "object",
389    }
390}
391
392/// Formats one debug list as a comma-separated string or `(none)`.
393fn format_debug_list(items: &[String]) -> String {
394    if items.is_empty() {
395        return "(none)".to_string();
396    }
397
398    items.join(", ")
399}
400
401/// Returns one stable label for the serde JSON error category.
402fn describe_json_error_category(error: &serde_json::Error) -> &'static str {
403    match error.classify() {
404        serde_json::error::Category::Io => "io",
405        serde_json::error::Category::Syntax => "syntax",
406        serde_json::error::Category::Data => "data",
407        serde_json::error::Category::Eof => "eof",
408    }
409}
410
411#[cfg(test)]
412#[path = "parse_test.rs"]
413mod tests;