use serde_json::Value;
use crate::{RepairError, RepairOutcome, Rewrite};
pub(crate) fn unwrap_fence(raw: &str) -> Option<String> {
let trimmed = raw.trim();
let rest = trimmed.strip_prefix("```")?;
let rest = strip_fence_info(rest);
let rest = rest.strip_prefix('\n').unwrap_or(rest);
if let Some(end) = rest.rfind("```") {
let tail = &rest[end + 3..];
if tail.trim().is_empty() || tail_is_comment(tail) || suffix_is_only_prose(tail) {
return Some(rest[..end].trim().to_string());
}
return None;
}
let body = rest.trim();
if body.is_empty() {
None
} else {
Some(body.to_string())
}
}
fn tail_is_comment(tail: &str) -> bool {
let tail = tail.trim();
if let Some(rest) = tail.strip_prefix("/*") {
let Some(end) = rest.find("*/") else {
return false;
};
return rest[end + 2..].trim().is_empty();
}
let Some(rest) = tail.strip_prefix("//").or_else(|| tail.strip_prefix('#')) else {
return false;
};
match rest.split_once('\n') {
None => true,
Some((_, after)) => after.trim().is_empty(),
}
}
pub(crate) fn without_trailing_prose(text: &str) -> Option<String> {
let mut stream = serde_json::Deserializer::from_str(text).into_iter::<Value>();
let value = stream.next()?.ok()?;
if !matches!(value, Value::Object(_) | Value::Array(_)) {
return None;
}
if let Value::Array(items) = &value
&& items.len() == 1
&& items[0].is_string()
{
return None;
}
let offset = stream.byte_offset();
let rest = text.get(offset..)?;
if !suffix_is_only_prose(rest) {
return None;
}
Some(text[..offset].trim_end().to_string())
}
fn suffix_is_only_prose(tail: &str) -> bool {
let rest = tail.trim();
if rest.is_empty()
|| rest.contains('{')
|| rest.contains('[')
|| rest.contains('}')
|| rest.contains(']')
|| rest.contains('`')
|| rest.contains(':')
{
return false;
}
let Some(first) = rest.chars().next() else {
return false;
};
if first.is_ascii_digit()
|| matches!(first, '"' | '-' | '+' | ';' | ',' | ':' | '/' | '}' | ']')
{
return false;
}
let word_end = rest
.find(|ch: char| !ch.is_ascii_alphanumeric() && ch != '_')
.unwrap_or(rest.len());
if rest.as_bytes().get(word_end) == Some(&b'.')
&& rest[word_end + 1..]
.chars()
.next()
.is_some_and(|ch| ch.is_alphanumeric())
{
return false;
}
let word = &rest[..word_end];
!matches!(
word,
"true" | "false" | "null" | "True" | "False" | "None" | "undefined" | "NaN" | "Infinity"
)
}
fn suffix_is_only_prose_at(chars: &[char], index: usize) -> bool {
let mut start = index;
while start < chars.len() && chars[start].is_whitespace() {
start += 1;
}
let rest: String = chars[start..].iter().collect();
suffix_is_only_prose(&rest)
}
fn strip_fence_info(rest: &str) -> &str {
let skipped = rest.trim_start_matches([' ', '\t']);
let end = skipped
.char_indices()
.find(|(_, ch)| !ch.is_ascii_alphanumeric())
.map(|(idx, _)| idx)
.unwrap_or(skipped.len());
if end == 0 {
return rest;
}
let tag = &skipped[..end];
let allowed = matches!(
tag,
"json" | "JSON" | "jsonc" | "JSONC" | "json5" | "JSON5" | "javascript" | "js" | "JS"
);
if !allowed {
return rest;
}
let after = &skipped[end..];
if after.starts_with(['{', '[', ' ', '\t', '\n', '\r']) || after.is_empty() {
after
} else {
rest
}
}
pub(crate) struct Truncation {
pub text: String,
pub dropped_prose: bool,
}
pub(crate) fn close_truncated(raw: &str) -> Option<Truncation> {
let number_already_ended = raw.trim_end().len() != raw.len();
let trimmed = raw.trim();
if !trimmed.starts_with('{') && !trimmed.starts_with('[') {
return None;
}
let chars: Vec<char> = trimmed.chars().collect();
let mut stack = Vec::new();
let mut in_string = false;
let mut escape = false;
let mut out = String::with_capacity(trimmed.len() + 4);
let mut last_sig = None;
let mut inserted = false;
let mut dropped_prose = false;
let mut prose_clear_until = 0usize;
for (idx, &ch) in chars.iter().enumerate() {
if idx >= prose_clear_until
&& !in_string
&& !stack.is_empty()
&& matches!(last_sig, Some('}') | Some(']'))
{
if suffix_is_only_prose_at(&chars, idx) {
dropped_prose = true;
break;
}
if ch.is_whitespace() {
let mut next = idx + 1;
while next < chars.len() && chars[next].is_whitespace() {
next += 1;
}
prose_clear_until = next;
}
}
if in_string {
out.push(ch);
if escape {
escape = false;
continue;
}
if ch == '\\' {
escape = true;
continue;
}
if ch == '"' {
in_string = false;
last_sig = Some('"');
}
continue;
}
match ch {
'"' => {
in_string = true;
out.push(ch);
}
'{' => {
stack.push('}');
out.push(ch);
last_sig = Some('{');
}
'[' => {
stack.push(']');
out.push(ch);
last_sig = Some('[');
}
'}' | ']' => {
if stack.last() == Some(&ch) {
stack.pop();
out.push(ch);
last_sig = Some(ch);
continue;
}
if stack.contains(&ch) {
while stack.last().copied() != Some(ch) {
let Some(closer) = stack.pop() else {
break;
};
out.push(closer);
inserted = true;
}
stack.pop();
out.push(ch);
last_sig = Some(ch);
continue;
}
out.push(ch);
last_sig = Some(ch);
}
other if other.is_whitespace() => out.push(other),
other => {
out.push(other);
last_sig = Some(other);
}
}
}
if in_string {
return None;
}
if matches!(
last_sig,
None | Some(':') | Some(',') | Some('{') | Some('[')
) {
return None;
}
if last_sig.is_some_and(|ch| ch.is_ascii_digit()) && !number_already_ended {
return None;
}
while let Some(closer) = stack.pop() {
out.push(closer);
inserted = true;
}
if !inserted && !dropped_prose {
return None;
}
Some(Truncation {
text: out,
dropped_prose,
})
}
pub(crate) fn isolate_leading_value(text: &str) -> Result<Option<String>, RepairError> {
if let Some(inner) = tool_call_body(text)? {
return Ok(Some(inner));
}
let trimmed = text.trim();
let Some(start) = leading_json_start(trimmed) else {
return Ok(None);
};
if start == 0 {
return Ok(None);
}
Ok(Some(trimmed[start..].to_string()))
}
fn tool_call_body(text: &str) -> Result<Option<String>, RepairError> {
const OPEN: &str = "<tool_call>";
const CLOSE: &str = "</tool_call>";
let Some(first) = text.find(OPEN) else {
return Ok(None);
};
if has_json_start(&text[..first]) || text[first + OPEN.len()..].contains(OPEN) {
return Err(RepairError::Ambiguous("more than one JSON value".into()));
}
let rest = &text[first + OPEN.len()..];
let Some(end) = rest.find(CLOSE) else {
return Ok(None);
};
if has_json_start(&rest[end + CLOSE.len()..]) {
return Err(RepairError::Ambiguous("more than one JSON value".into()));
}
Ok(Some(rest[..end].trim().to_string()))
}
fn has_json_start(text: &str) -> bool {
text.contains('{') || text.contains('[') || text.contains("```")
}
fn leading_json_start(text: &str) -> Option<usize> {
let brace = text.find(['{', '[']);
let fence = text.find("```");
match (brace, fence) {
(Some(left), Some(right)) => Some(left.min(right)),
(Some(left), None) => Some(left),
(None, Some(right)) => Some(right),
(None, None) => None,
}
}
pub(crate) fn xml_parameters(raw: &str) -> Result<Option<(Value, Vec<Rewrite>)>, RepairError> {
let trimmed = raw.trim();
if !trimmed.starts_with("<parameter") {
return Ok(None);
}
let mut object = serde_json::Map::new();
let mut rewrites = Vec::new();
let mut rest = trimmed;
let mut found = false;
while let Some(start) = rest.find("<parameter") {
if !rest[..start].trim().is_empty() {
return Err(RepairError::Unfixable(
"trailing text after xml parameters".into(),
));
}
found = true;
let after = &rest[start + "<parameter".len()..];
let (name, after_name) = parameter_name(after)?;
let Some(content_end) = after_name.find("</parameter>") else {
return Err(RepairError::Unfixable(
"xml parameter tag is not closed".into(),
));
};
let content = trim_parameter_body(&after_name[..content_end]);
if object.contains_key(&name) {
return Err(RepairError::Ambiguous(format!(
"xml parameter '{name}' is repeated"
)));
}
let (value, more) = parameter_value(content)?;
rewrites.extend(more);
object.insert(name, value);
rest = &after_name[content_end + "</parameter>".len()..];
}
if !rest.trim().is_empty() {
return Err(RepairError::Unfixable(
"trailing text after xml parameters".into(),
));
}
if !found || object.is_empty() {
return Err(RepairError::Unfixable(
"xml parameter tag could not be read".into(),
));
}
Ok(Some((Value::Object(object), rewrites)))
}
fn parameter_name(after: &str) -> Result<(String, &str), RepairError> {
let after = after.trim_start();
if let Some(rest) = after.strip_prefix('=') {
let rest = rest.trim_start();
let end = rest
.find('>')
.ok_or_else(|| RepairError::Unfixable("xml parameter name is not closed".into()))?;
let name = rest[..end].trim();
if name.is_empty() {
return Err(RepairError::Unfixable("xml parameter name is empty".into()));
}
return Ok((name.to_string(), &rest[end + 1..]));
}
let Some(rest) = after.strip_prefix("name=") else {
return Err(RepairError::Unfixable("xml parameter has no name".into()));
};
let quote = rest
.chars()
.next()
.filter(|ch| *ch == '"' || *ch == '\'')
.ok_or_else(|| RepairError::Unfixable("xml parameter name is not quoted".into()))?;
let rest = &rest[1..];
let end = if quote == '\'' {
rest.char_indices().find_map(|(index, ch)| {
if ch != '\'' {
return None;
}
let inside = rest[index + 1..]
.chars()
.next()
.is_some_and(|next| next.is_alphanumeric());
if inside { None } else { Some(index) }
})
} else {
rest.find(quote)
}
.ok_or_else(|| RepairError::Unfixable("xml parameter name quote is not closed".into()))?;
let name = &rest[..end];
if name.is_empty() {
return Err(RepairError::Unfixable("xml parameter name is empty".into()));
}
let after_name = &rest[end + 1..];
let gt = after_name
.find('>')
.ok_or_else(|| RepairError::Unfixable("xml parameter tag is not closed".into()))?;
Ok((name.to_string(), &after_name[gt + 1..]))
}
fn trim_parameter_body(content: &str) -> &str {
let mut text = content;
if let Some(rest) = text.strip_prefix("\r\n") {
text = rest;
} else if let Some(rest) = text.strip_prefix('\n') {
text = rest;
}
if let Some(rest) = text.strip_suffix("\r\n") {
text = rest;
} else if let Some(rest) = text.strip_suffix('\n') {
text = rest;
}
if text.contains('\n') {
text
} else {
text.trim()
}
}
fn parameter_value(content: &str) -> Result<(Value, Vec<Rewrite>), RepairError> {
let trimmed = content.trim();
if trimmed == "{" || trimmed == "[" {
return Err(RepairError::Unfixable(
"xml parameter container is truncated".into(),
));
}
match crate::repair_json(trimmed) {
RepairOutcome::Valid(value)
if value.is_object() || value.is_array() || value.is_string() =>
{
Ok((value, Vec::new()))
}
RepairOutcome::Ambiguous(reason) => Err(RepairError::Ambiguous(reason)),
RepairOutcome::Repaired { value, repairs }
if value.is_object() || (value.is_array() && !bare_bracket_word(trimmed)) =>
{
Ok((value, repairs))
}
_ => Ok((Value::String(content.to_string()), Vec::new())),
}
}
fn bare_bracket_word(trimmed: &str) -> bool {
let Some(inner) = trimmed
.strip_prefix('[')
.and_then(|rest| rest.strip_suffix(']'))
else {
return false;
};
let inner = inner.trim().trim_end_matches(',').trim();
if inner.is_empty() || matches!(inner, "true" | "false" | "null" | "True" | "False" | "None") {
return false;
}
inner
.chars()
.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '.' | '-'))
&& inner.chars().any(|ch| ch.is_ascii_alphabetic())
}