use crate::config::Config;
use crate::mcp::get_available_functions;
use crate::session::chat::get_animation_manager;
use crate::session::chat::session::ChatSession;
use crate::session::estimate_full_context_tokens;
use anyhow::Result;
use colored::*;
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_manager = get_animation_manager();
let current_cost = chat_session.session.info.total_cost;
let max_threshold = config.max_session_tokens_threshold;
let tools = get_available_functions(config).await;
let current_context_tokens =
estimate_full_context_tokens(&chat_session.session.messages, Some(&tools)) as u64;
animation_manager
.start_with_params(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_manager.stop_current().await;
return Err(e);
}
}
} else {
input.to_string()
}
} else {
input.to_string()
};
animation_manager.stop_current().await;
Ok(workflow_output)
}