1use 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
12const PROTOCOL_KEYS: &[&str] = &["answer", "questions", "review_comment_outcomes"];
14
15pub 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
71pub 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
130fn 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
162fn 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
181fn 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
193pub 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
240fn 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
265fn 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
273fn 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
289fn 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
295fn parse_structured_json_response(raw: &str) -> Option<AgentResponse> {
301 parse_structured_json_response_with_reason(raw).ok()
302}
303
304fn 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
319fn 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
340fn 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
360fn 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
371fn 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
390fn 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
421fn 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
433fn format_debug_list(items: &[String]) -> String {
435 if items.is_empty() {
436 return "(none)".to_string();
437 }
438
439 items.join(", ")
440}
441
442fn 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;