Skip to main content

ag_protocol/
parse.rs

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