use switchyard_protocol::{AggLlmResponse, Message};
use super::turn::visible_text;
pub(super) const TRUNCATION_MARKER: &str = "\n...<middle of the conversation truncated>...\n";
pub(super) const NO_TEXT_PLACEHOLDER: &str = "(no text)";
pub(super) const VERDICT_PATTERN: &str =
r#"(?i)^[\s*_#>"'(\[`]*(?:(?:final\s+)?verdict\s*:\s*[\s*_#>"'(\[`]*)?(APPROVE|REDO)\b"#;
pub(super) enum Verdict {
Approve,
Redo { plan: String },
}
pub(super) fn review_transcript(
messages: &[Message],
review_tail: Option<&str>,
cap: usize,
) -> String {
let text = serde_json::to_string(messages).unwrap_or_default();
let text = middle_drop(text, cap);
format!(
"Conversation so far (JSON):\n\n{text}\n\nThe executor's latest turn (a plan, or its claim the task is done):\n{}",
review_tail.unwrap_or(NO_TEXT_PLACEHOLDER)
)
}
pub(super) fn middle_drop(text: String, cap: usize) -> String {
let total = text.chars().count();
if total <= cap {
return text;
}
let head_chars = cap / 4;
let tail_chars = cap - head_chars;
let head_end = text
.char_indices()
.nth(head_chars)
.map(|(index, _)| index)
.unwrap_or(text.len());
let tail_start = text
.char_indices()
.nth(total - tail_chars)
.map(|(index, _)| index)
.unwrap_or(0);
format!(
"{}{TRUNCATION_MARKER}{}",
&text[..head_end],
&text[tail_start..]
)
}
pub(super) fn advisor_reply_text(agg: &AggLlmResponse) -> String {
visible_text(agg).unwrap_or_default().trim().to_string()
}
pub(super) fn parse_verdict(verdict_re: ®ex::Regex, reply: &str) -> Option<Verdict> {
let reply = reply.trim();
let captures = verdict_re.captures(reply)?;
let token = captures.get(1)?;
if token.as_str().eq_ignore_ascii_case("APPROVE") {
return Some(Verdict::Approve);
}
let plan = reply[token.end()..]
.trim_start_matches([' ', '*', '_', ':', '\n', '-'])
.trim();
let plan = if plan.is_empty() { reply } else { plan };
Some(Verdict::Redo {
plan: plan.to_string(),
})
}