use std::sync::Arc;
use gadk_agent::{Agent, AgentState, AgentType, Tool};
use crate::llm::LlmAgentConfig;
#[derive(Debug, Default)]
pub(crate) struct LiveModeToolInjection {
done: parking_lot::Mutex<bool>,
}
impl LiveModeToolInjection {
pub(crate) fn do_once(&self, inject: impl FnOnce()) {
let mut done = self.done.lock();
if *done {
return;
}
inject();
*done = true;
}
}
pub(crate) struct LlmAgentState {
pub(crate) cfg: LlmAgentConfig,
pub(crate) tools: parking_lot::RwLock<Vec<Arc<dyn Tool>>>,
pub(crate) live_injection: LiveModeToolInjection,
pub(crate) instruction_suffix: parking_lot::RwLock<String>,
}
impl LlmAgentState {
pub(crate) fn new(cfg: LlmAgentConfig) -> Self {
let tools = cfg.tools.clone();
Self {
cfg,
tools: parking_lot::RwLock::new(tools),
live_injection: LiveModeToolInjection::default(),
instruction_suffix: parking_lot::RwLock::new(String::new()),
}
}
pub(crate) fn instruction(&self) -> String {
let suffix = self.instruction_suffix.read();
if suffix.is_empty() {
return self.cfg.instruction.clone();
}
format!("{}{}", self.cfg.instruction, suffix.as_str())
}
pub(crate) fn tools(&self) -> Vec<Arc<dyn Tool>> {
self.tools.read().clone()
}
}
pub(crate) fn reveal(agent: &dyn Agent) -> Option<&LlmAgentState> {
reveal_state(agent.agent_state())
}
pub(crate) fn reveal_arc(agent: &dyn Agent) -> Option<Arc<LlmAgentState>> {
let state = agent.agent_state();
if state.agent_type != AgentType::LlmAgent {
return None;
}
state.config.clone()?.downcast::<LlmAgentState>().ok()
}
pub(crate) fn reveal_state(state: &AgentState) -> Option<&LlmAgentState> {
if state.agent_type != AgentType::LlmAgent {
return None;
}
state.config.as_deref()?.downcast_ref::<LlmAgentState>()
}