use std::collections::HashSet;
use serde::{Deserialize, Serialize};
use crate::types::{ChatMessage, ImageAttachment, Message, MessageRole, ToolCallMessage};
use crate::types::SessionId;
pub use crate::types::RunState;
#[derive(Deserialize)]
struct RawAgentSession {
id: Option<SessionId>,
chat_messages: Vec<ChatMessage>,
always_allowed_actions: HashSet<String>,
#[serde(default)]
total_tool_calls: Option<usize>,
run_state: Option<RunState>,
nudge_count: Option<usize>,
turn_tool_calls: Option<usize>,
reasoning_only_strikes: Option<usize>,
empty_response_strikes: Option<usize>,
}
impl From<RawAgentSession> for AgentSession {
fn from(raw: RawAgentSession) -> Self {
let mut run_state = raw.run_state.unwrap_or_else(|| RunState {
nudge_count: raw.nudge_count.unwrap_or(0),
turn_actions: raw.turn_tool_calls.unwrap_or(0),
reasoning_only_strikes: raw.reasoning_only_strikes.unwrap_or(0),
empty_response_strikes: raw.empty_response_strikes.unwrap_or(0),
..RunState::default()
});
if let Some(total) = raw.total_tool_calls {
run_state.total_actions = total;
}
Self {
id: raw.id,
chat_messages: raw.chat_messages,
always_allowed_actions: raw.always_allowed_actions,
run_state,
}
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(from = "RawAgentSession")]
pub struct AgentSession {
id: Option<SessionId>,
chat_messages: Vec<ChatMessage>,
always_allowed_actions: HashSet<String>,
pub run_state: RunState,
}
impl AgentSession {
pub fn new(id: SessionId) -> Self {
Self {
id: Some(id),
chat_messages: Vec::new(),
always_allowed_actions: HashSet::new(),
run_state: RunState::default(),
}
}
pub fn id(&self) -> Option<SessionId> {
self.id.clone()
}
pub fn simple_messages(&self) -> Vec<Message> {
self.chat_messages
.iter()
.filter_map(|cm| match cm {
ChatMessage::Assistant { content: None, .. } => None,
ChatMessage::Assistant {
content: Some(c),
tool_calls: Some(tc),
..
} if c.is_empty() && !tc.is_empty() => None,
_ => Some(Message::from(cm)),
})
.collect()
}
pub fn chat_messages(&self) -> &[ChatMessage] {
&self.chat_messages
}
pub fn chat_messages_mut(&mut self) -> &mut Vec<ChatMessage> {
&mut self.chat_messages
}
pub fn is_action_allowed(&self, action_key: &str) -> bool {
self.always_allowed_actions.contains(action_key)
}
pub fn allow_action(&mut self, action_key: impl Into<String>) {
self.always_allowed_actions.insert(action_key.into());
}
pub fn push_message(&mut self, role: MessageRole, content: impl Into<String>) {
let content = content.into();
let chat_msg = match role {
MessageRole::System => ChatMessage::system(content),
MessageRole::User => ChatMessage::user(content),
MessageRole::Assistant => ChatMessage::assistant(content),
MessageRole::Tool => ChatMessage::tool(String::new(), content),
};
self.chat_messages.push(chat_msg);
}
pub fn push_message_ephemeral(&mut self, role: MessageRole, content: impl Into<String>) {
let content = content.into();
let chat_msg = match role {
MessageRole::System => ChatMessage::system_ephemeral(content),
MessageRole::User => ChatMessage::user_ephemeral(content),
MessageRole::Assistant | MessageRole::Tool => {
self.push_message(role, content);
return;
}
};
self.chat_messages.push(chat_msg);
}
pub fn push_user_synthetic(&mut self, content: impl Into<String>) {
self.chat_messages
.push(ChatMessage::user_synthetic(content));
}
pub fn set_system_prompt(&mut self, content: impl Into<String>) {
let content = content.into();
if let Some(idx) = self.chat_messages.iter().position(|m| {
matches!(
m,
ChatMessage::System {
ephemeral: false,
..
}
)
}) {
self.chat_messages[idx] = ChatMessage::system(content);
} else {
self.chat_messages.insert(0, ChatMessage::system(content));
}
}
pub fn push_assistant_with_reasoning(
&mut self,
content: impl Into<String>,
reasoning: impl Into<String>,
) {
self.chat_messages
.push(ChatMessage::assistant_with_reasoning(content, reasoning));
}
pub fn push_user_message_with_images(
&mut self,
content: impl Into<String>,
images: Vec<ImageAttachment>,
) {
self.chat_messages
.push(ChatMessage::user_with_images(content, images));
}
pub fn push_assistant_tool_call(
&mut self,
tool_call_id: &str,
tool_name: &str,
arguments_json: &str,
) {
self.chat_messages.push(ChatMessage::assistant_tool_call(
tool_call_id,
tool_name,
arguments_json,
));
}
fn preview_args(args: &str, max_chars: usize) -> String {
format!("{:?}", args.chars().take(max_chars).collect::<String>())
}
pub fn render_assistant_tool_calls(
tool_calls: &[(String, String, String)],
reasoning: Option<String>,
content: Option<String>,
) -> ChatMessage {
let calls: Vec<ToolCallMessage> = tool_calls
.iter()
.map(|(id, name, args)| {
let valid_args = if serde_json::from_str::<serde_json::Value>(args).is_ok() {
args.clone()
} else {
tracing::warn!(
tool_name = %name,
args_len = args.len(),
args_preview = %Self::preview_args(args, 80),
"tool call arguments are not valid JSON (provider truncated them), \
sanitizing to empty object; re-issue instruction goes to the tool_result"
);
"{}".to_string()
};
ToolCallMessage {
id: id.clone(),
name: name.clone(),
arguments: valid_args,
}
})
.collect();
ChatMessage::Assistant {
content,
reasoning_content: reasoning,
tool_calls: Some(calls),
thinking_signature: None,
}
}
pub fn push_assistant_tool_calls(
&mut self,
tool_calls: &[(String, String, String)],
reasoning: Option<String>,
content: Option<String>,
) {
self.push_chat_message(Self::render_assistant_tool_calls(
tool_calls, reasoning, content,
));
}
pub fn push_chat_message(&mut self, message: ChatMessage) {
self.chat_messages.push(message);
}
pub fn push_tool_result(&mut self, tool_call_id: &str, content: impl Into<String>) {
self.chat_messages
.push(ChatMessage::tool(tool_call_id, content));
}
pub fn remove_ephemeral_messages(&mut self) {
let before = self.chat_messages.len();
self.chat_messages.retain(|m| !m.is_ephemeral());
let removed = before - self.chat_messages.len();
if removed > 0 {
tracing::debug!(
removed,
remaining = self.chat_messages.len(),
"ephemeral messages cleaned up"
);
}
}
pub fn turn_count(&self) -> usize {
self.chat_messages
.iter()
.filter(|m| matches!(m, ChatMessage::User { .. }))
.count()
}
pub fn trim_oldest_turns(&mut self, max_turns: usize) {
let current_turns = self.turn_count();
if current_turns <= max_turns {
return;
}
let turns_to_remove = current_turns - max_turns;
let user_positions: Vec<usize> = self
.chat_messages
.iter()
.enumerate()
.filter_map(|(i, m)| {
if matches!(m, ChatMessage::User { .. }) {
Some(i)
} else {
None
}
})
.collect();
if user_positions.len() <= turns_to_remove {
return;
}
let system_prefix = self
.chat_messages
.iter()
.take_while(|m| matches!(m, ChatMessage::System { .. }))
.count();
let drain_end = user_positions[turns_to_remove];
if system_prefix >= drain_end {
return; }
self.chat_messages.drain(system_prefix..drain_end);
}
pub fn pop_last_message(&mut self) {
self.chat_messages.pop();
}
pub fn close_dangling_tool_calls(&mut self, error_summary: &str) {
let assistant_idx = self.chat_messages.iter().rposition(
|m| matches!(m, ChatMessage::Assistant { tool_calls: Some(tc), .. } if !tc.is_empty()),
);
let Some(assistant_idx) = assistant_idx else {
return;
};
let ChatMessage::Assistant {
tool_calls: Some(tc),
..
} = &self.chat_messages[assistant_idx]
else {
return;
};
let all_ids: Vec<String> = tc.iter().map(|t| t.id.clone()).collect();
let answered_ids: Vec<String> = self.chat_messages[assistant_idx + 1..]
.iter()
.filter_map(|m| match m {
ChatMessage::Tool { tool_call_id, .. } => Some(tool_call_id.clone()),
_ => None,
})
.collect();
for id in &all_ids {
if !answered_ids.iter().any(|a| a == id) {
self.push_tool_result(id, error_summary);
}
}
}
pub fn set_chat_messages(&mut self, messages: Vec<ChatMessage>) -> Result<(), String> {
validate_message_sequence(&messages)?;
self.chat_messages = messages;
Ok(())
}
pub fn recount_actions_from_messages(&mut self) {
self.run_state.total_actions = self
.chat_messages
.iter()
.filter_map(|m| match m {
ChatMessage::Assistant {
tool_calls: Some(tc),
..
} => Some(tc.len()),
_ => None,
})
.sum();
}
}
pub fn validate_message_sequence(messages: &[ChatMessage]) -> Result<(), String> {
if !messages
.iter()
.any(|m| !matches!(m, ChatMessage::System { .. } | ChatMessage::Custom { .. }))
{
return Err(
"sequence contains no sendable message: System/Custom alone leave the \
provider `messages` array empty"
.to_string(),
);
}
let mut pending_tool_call_ids: HashSet<String> = HashSet::new();
for (i, msg) in messages.iter().enumerate() {
match msg {
ChatMessage::Tool { tool_call_id, .. } => {
if pending_tool_call_ids.is_empty() {
return Err(format!(
"message[{}]: Tool message with call_id '{}' has no preceding tool_call",
i, tool_call_id
));
}
if !pending_tool_call_ids.remove(tool_call_id) {
return Err(format!(
"message[{}]: Tool message with call_id '{}' does not match any pending tool_call (already answered or unknown)",
i, tool_call_id
));
}
}
ChatMessage::Assistant {
tool_calls: Some(tc),
..
} => {
if !pending_tool_call_ids.is_empty() {
return Err(format!(
"message[{}]: Assistant message with new tool_calls appears before pending calls were answered: {:?}",
i, pending_tool_call_ids
));
}
pending_tool_call_ids = tc.iter().map(|t| t.id.clone()).collect();
}
_ => {}
}
}
if !pending_tool_call_ids.is_empty() {
return Err(format!(
"message sequence ends with unanswered tool calls: {:?}",
pending_tool_call_ids
));
}
Ok(())
}
#[cfg(test)]
fn make_session() -> AgentSession {
AgentSession::new(SessionId::new(1))
}
#[cfg(test)]
mod tests;
#[cfg(test)]
mod validate_tests;
#[cfg(test)]
mod proptest_tests;