use std::collections::HashMap;
use ai_agents_state::Transition;
use serde_json::Value;
use uuid::Uuid;
use super::branch::RuntimeOptimizationKind;
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct TurnOptimizationContext {
pub turn_id: Uuid,
pub processed_input: String,
pub input_context: HashMap<String, Value>,
pub staged_context_writes: HashMap<String, Value>,
pub pre_turn_lifecycle_completed: bool,
pub user_message_committed: bool,
pub post_turn_lifecycle_completed: bool,
pub redispatch_depth: u32,
pub speculative_llm_calls_used: u32,
pub max_speculative_llm_calls: u32,
}
#[allow(dead_code)]
impl TurnOptimizationContext {
pub fn new(
processed_input: impl Into<String>,
input_context: HashMap<String, Value>,
max_speculative_llm_calls: u32,
) -> Self {
Self {
turn_id: Uuid::new_v4(),
processed_input: processed_input.into(),
input_context,
staged_context_writes: HashMap::new(),
pre_turn_lifecycle_completed: false,
user_message_committed: false,
post_turn_lifecycle_completed: false,
redispatch_depth: 0,
speculative_llm_calls_used: 0,
max_speculative_llm_calls,
}
}
pub fn reserve_speculative_llm_call(&mut self) -> bool {
if self.speculative_llm_calls_used >= self.max_speculative_llm_calls {
return false;
}
self.speculative_llm_calls_used += 1;
true
}
pub fn reserve_speculative_llm_call_for(&mut self, _kind: RuntimeOptimizationKind) -> bool {
self.reserve_speculative_llm_call()
}
pub fn release_or_mark_failed_reservation(&mut self, _kind: RuntimeOptimizationKind) {}
pub fn can_schedule_branch(&self, active_tasks: usize, max_parallel_tasks: usize) -> bool {
active_tasks < max_parallel_tasks
}
pub fn stage_context_write(&mut self, key: impl Into<String>, value: Value) {
self.staged_context_writes.insert(key.into(), value);
}
pub fn take_staged_context_writes(&mut self) -> HashMap<String, Value> {
std::mem::take(&mut self.staged_context_writes)
}
pub fn reserve_speculative_llm_calls(&mut self, count: u32) -> bool {
if self.speculative_llm_calls_used + count > self.max_speculative_llm_calls {
return false;
}
self.speculative_llm_calls_used += count;
true
}
pub fn mark_user_message_committed(&mut self) {
self.user_message_committed = true;
}
pub fn mark_post_turn_lifecycle_completed(&mut self) {
self.post_turn_lifecycle_completed = true;
}
pub fn enter_redispatch(&mut self) {
self.redispatch_depth += 1;
}
pub fn exit_redispatch(&mut self) {
self.redispatch_depth = self.redispatch_depth.saturating_sub(1);
}
}
#[derive(Debug, Clone)]
pub struct TransitionCandidate {
pub from_state: String,
pub transition: Transition,
pub reason: String,
}
impl TransitionCandidate {
pub fn new(
from_state: impl Into<String>,
transition: Transition,
reason: impl Into<String>,
) -> Self {
Self {
from_state: from_state.into(),
transition,
reason: reason.into(),
}
}
pub fn target(&self) -> &str {
&self.transition.to
}
}