use super::animation::show_smart_animation;
use crate::config::Config;
use crate::mcp::get_available_functions;
use crate::session::chat::session::ChatSession;
use crate::session::estimate_full_context_tokens;
use anyhow::Result;
use colored::*;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
pub async fn process_layered_response(
input: &str,
chat_session: &mut ChatSession,
config: &Config,
role: &str,
operation_cancelled: tokio::sync::watch::Receiver<bool>,
) -> Result<String> {
let mut system_message_cached = false;
for msg in &chat_session.session.messages {
if msg.role == "system" && msg.cached {
system_message_cached = true;
break;
}
}
if !system_message_cached {
if let Ok(cached) = chat_session.session.add_cache_checkpoint(true) {
if cached && crate::session::model_supports_caching(&chat_session.model) {
println!(
"{}",
"System message has been automatically marked for caching to save tokens."
.yellow()
);
let _ = chat_session.save();
}
}
}
let animation_cancel = Arc::new(AtomicBool::new(false));
let animation_cancel_clone = animation_cancel.clone();
let current_cost = chat_session.session.info.total_cost;
let max_threshold = config.max_session_tokens_threshold;
let (_, _, _, _, system_prompt) = config.get_role_config(role);
let tools = get_available_functions(config).await;
let current_context_tokens = estimate_full_context_tokens(
&chat_session.session.messages,
Some(system_prompt),
Some(&tools),
) as u64;
let animation_task = tokio::spawn(async move {
let _ = show_smart_animation(
animation_cancel_clone,
current_cost,
current_context_tokens,
max_threshold,
)
.await;
});
if config.get_log_level().is_debug_enabled() {
println!("{}", "Using workflow processing with model-specific caching - only supported models will use caching".bright_cyan());
} else {
println!("{}", "Using workflow processing".bright_cyan());
}
let workflow_output: String = if let Some(role_data) = config.role_map.get(role) {
if let Some(workflow_name) = &role_data.workflow {
let workflow_def = config
.workflows
.iter()
.find(|w| &w.name == workflow_name)
.ok_or_else(|| anyhow::anyhow!("Workflow '{}' not found", workflow_name))?
.clone();
let workflow_orchestrator = crate::session::workflows::WorkflowOrchestrator::new(
workflow_def,
workflow_name.to_string(),
);
match workflow_orchestrator
.execute(
input,
&mut chat_session.session,
config,
operation_cancelled.clone(),
)
.await
{
Ok((output, _progress)) => output, Err(e) => {
animation_cancel.store(true, Ordering::SeqCst);
let _ = animation_task.await;
return Err(e);
}
}
} else {
input.to_string()
}
} else {
input.to_string()
};
animation_cancel.store(true, Ordering::SeqCst);
let _ = animation_task.await;
Ok(workflow_output)
}