use dashmap::DashMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TurnDecision {
Halt { reason: Option<String> },
Repeat { next_prompt: Option<String> },
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TurnMessage {
pub role: String,
pub content: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolTrace {
pub tool: String,
pub input: Value,
pub output: Value,
pub timestamp: String,
}
pub struct IsolatedTurnContext {
pub turn_index: usize,
pub scratchpad: Arc<DashMap<String, Value>>,
pub tool_traces: Arc<Mutex<Vec<ToolTrace>>>,
}
impl IsolatedTurnContext {
pub fn new(turn_index: usize) -> Self {
Self {
turn_index,
scratchpad: Arc::new(DashMap::new()),
tool_traces: Arc::new(Mutex::new(Vec::new())),
}
}
pub fn record_tool_call(&self, tool: &str, input: Value, output: Value) {
let trace = ToolTrace {
tool: tool.to_string(),
input,
output,
timestamp: chrono::Utc::now().to_rfc3339(),
};
self.tool_traces.lock().unwrap().push(trace);
}
pub fn get_traces_count(&self) -> usize {
self.tool_traces.lock().unwrap().len()
}
pub fn get_raw_traces_bytes(&self) -> usize {
let traces = self.tool_traces.lock().unwrap();
serde_json::to_string(&*traces).map(|s| s.len()).unwrap_or(0)
}
}
#[derive(Debug, Clone)]
pub struct TurnExecutionResult {
pub turn_index: usize,
pub synthesized_message: TurnMessage,
pub decision: TurnDecision,
pub intermediate_traces_count: usize,
pub pruned_raw_bytes: usize,
}
#[derive(Debug, Clone)]
pub struct ConversationalLoopOutcome {
pub turns: Vec<TurnExecutionResult>,
pub history: Vec<TurnMessage>,
pub converged: bool,
pub total_pruned_bytes: usize,
pub token_efficiency_ratio: f64,
}
pub struct ConversationalLoopEngine {
pub history: Arc<Mutex<Vec<TurnMessage>>>,
pub shared_memory: Arc<DashMap<String, Value>>,
turn_counter: AtomicUsize,
}
impl Default for ConversationalLoopEngine {
fn default() -> Self {
Self::new()
}
}
impl ConversationalLoopEngine {
pub fn new() -> Self {
Self {
history: Arc::new(Mutex::new(Vec::new())),
shared_memory: Arc::new(DashMap::new()),
turn_counter: AtomicUsize::new(0),
}
}
pub fn get_history(&self) -> Vec<TurnMessage> {
self.history.lock().unwrap().clone()
}
pub fn execute_turn<F>(
&self,
prompt: TurnMessage,
handler: F,
) -> Result<TurnExecutionResult, String>
where
F: FnOnce(&IsolatedTurnContext, &TurnMessage, &Arc<DashMap<String, Value>>) -> Result<(String, TurnDecision), String>,
{
let turn_idx = self.turn_counter.fetch_add(1, Ordering::SeqCst) + 1;
self.history.lock().unwrap().push(prompt.clone());
let turn_ctx = IsolatedTurnContext::new(turn_idx);
let (response, decision) = handler(&turn_ctx, &prompt, &self.shared_memory)?;
let intermediate_traces_count = turn_ctx.get_traces_count();
let pruned_raw_bytes = turn_ctx.get_raw_traces_bytes();
drop(turn_ctx);
let synthesized_message = TurnMessage {
role: "assistant".to_string(),
content: response,
};
self.history.lock().unwrap().push(synthesized_message.clone());
Ok(TurnExecutionResult {
turn_index: turn_idx,
synthesized_message,
decision,
intermediate_traces_count,
pruned_raw_bytes,
})
}
pub fn run_loop<F>(
&self,
initial_prompt: &str,
max_turns: usize,
mut handler: F,
) -> Result<ConversationalLoopOutcome, String>
where
F: FnMut(&IsolatedTurnContext, &TurnMessage, &Arc<DashMap<String, Value>>) -> Result<(String, TurnDecision), String>,
{
let mut turns = Vec::new();
let mut current_prompt = TurnMessage {
role: "user".to_string(),
content: initial_prompt.to_string(),
};
let mut total_pruned_bytes = 0;
let mut converged = false;
for _ in 0..max_turns {
let res = self.execute_turn(current_prompt.clone(), &mut handler)?;
total_pruned_bytes += res.pruned_raw_bytes;
let decision = res.decision.clone();
turns.push(res);
match decision {
TurnDecision::Halt { .. } => {
converged = true;
break;
}
TurnDecision::Repeat { next_prompt } => {
current_prompt = TurnMessage {
role: "user".to_string(),
content: next_prompt.unwrap_or_else(|| "Continue next step".to_string()),
};
}
}
}
let history = self.get_history();
let history_bytes = serde_json::to_string(&history).map(|s| s.len()).unwrap_or(0);
let unpruned_total = history_bytes + total_pruned_bytes;
let token_efficiency_ratio = if unpruned_total > 0 {
(total_pruned_bytes as f64 / unpruned_total as f64) * 100.0
} else {
0.0
};
Ok(ConversationalLoopOutcome {
turns,
history,
converged,
total_pruned_bytes,
token_efficiency_ratio,
})
}
}