1use std::collections::HashSet;
2
3use serde::{Deserialize, Serialize};
4
5use crate::types::{ChatMessage, ImageAttachment, Message, MessageRole, ToolCallMessage};
6
7use crate::types::SessionId;
8
9pub use crate::types::RunState;
13
14#[derive(Deserialize)]
22struct RawAgentSession {
23 id: Option<SessionId>,
24 chat_messages: Vec<ChatMessage>,
25 always_allowed_actions: HashSet<String>,
26 #[serde(default)]
30 total_tool_calls: Option<usize>,
31
32 run_state: Option<RunState>,
34
35 nudge_count: Option<usize>,
37 turn_tool_calls: Option<usize>,
38 reasoning_only_strikes: Option<usize>,
39 empty_response_strikes: Option<usize>,
40}
41
42impl From<RawAgentSession> for AgentSession {
43 fn from(raw: RawAgentSession) -> Self {
44 let mut run_state = raw.run_state.unwrap_or_else(|| RunState {
45 nudge_count: raw.nudge_count.unwrap_or(0),
46 turn_actions: raw.turn_tool_calls.unwrap_or(0),
47 reasoning_only_strikes: raw.reasoning_only_strikes.unwrap_or(0),
48 empty_response_strikes: raw.empty_response_strikes.unwrap_or(0),
49 ..RunState::default()
50 });
51 if let Some(total) = raw.total_tool_calls {
55 run_state.total_actions = total;
56 }
57 Self {
58 id: raw.id,
59 chat_messages: raw.chat_messages,
60 always_allowed_actions: raw.always_allowed_actions,
61 run_state,
62 }
63 }
64}
65
66#[derive(Clone, Debug, Default, Serialize, Deserialize)]
71#[serde(from = "RawAgentSession")]
72pub struct AgentSession {
73 id: Option<SessionId>,
74 chat_messages: Vec<ChatMessage>,
77 always_allowed_actions: HashSet<String>,
78 pub run_state: RunState,
82}
83
84impl AgentSession {
85 pub fn new(id: SessionId) -> Self {
86 Self {
87 id: Some(id),
88 chat_messages: Vec::new(),
89 always_allowed_actions: HashSet::new(),
90 run_state: RunState::default(),
91 }
92 }
93
94 pub fn id(&self) -> Option<SessionId> {
95 self.id.clone()
96 }
97
98 pub fn simple_messages(&self) -> Vec<Message> {
102 self.chat_messages
103 .iter()
104 .filter_map(|cm| match cm {
105 ChatMessage::Assistant { content: None, .. } => None,
106 ChatMessage::Assistant {
107 content: Some(c),
108 tool_calls: Some(tc),
109 ..
110 } if c.is_empty() && !tc.is_empty() => None,
111 _ => Some(Message::from(cm)),
112 })
113 .collect()
114 }
115
116 pub fn chat_messages(&self) -> &[ChatMessage] {
117 &self.chat_messages
118 }
119
120 pub fn chat_messages_mut(&mut self) -> &mut Vec<ChatMessage> {
122 &mut self.chat_messages
123 }
124
125 pub fn is_action_allowed(&self, action_key: &str) -> bool {
126 self.always_allowed_actions.contains(action_key)
127 }
128
129 pub fn allow_action(&mut self, action_key: impl Into<String>) {
130 self.always_allowed_actions.insert(action_key.into());
131 }
132
133 pub fn push_message(&mut self, role: MessageRole, content: impl Into<String>) {
134 let content = content.into();
135 let chat_msg = match role {
136 MessageRole::System => ChatMessage::system(content),
137 MessageRole::User => ChatMessage::user(content),
138 MessageRole::Assistant => ChatMessage::assistant(content),
139 MessageRole::Tool => ChatMessage::tool(String::new(), content),
140 };
141 self.chat_messages.push(chat_msg);
142 }
143
144 pub fn push_message_ephemeral(&mut self, role: MessageRole, content: impl Into<String>) {
148 let content = content.into();
149 let chat_msg = match role {
150 MessageRole::System => ChatMessage::system_ephemeral(content),
151 MessageRole::User => ChatMessage::user_ephemeral(content),
152 MessageRole::Assistant | MessageRole::Tool => {
153 self.push_message(role, content);
156 return;
157 }
158 };
159 self.chat_messages.push(chat_msg);
160 }
161
162 pub fn push_user_synthetic(&mut self, content: impl Into<String>) {
167 self.chat_messages
168 .push(ChatMessage::user_synthetic(content));
169 }
170
171 pub fn set_system_prompt(&mut self, content: impl Into<String>) {
176 let content = content.into();
177 if let Some(idx) = self.chat_messages.iter().position(|m| {
178 matches!(
179 m,
180 ChatMessage::System {
181 ephemeral: false,
182 ..
183 }
184 )
185 }) {
186 self.chat_messages[idx] = ChatMessage::system(content);
187 } else {
188 self.chat_messages.insert(0, ChatMessage::system(content));
189 }
190 }
191
192 pub fn push_assistant_with_reasoning(
196 &mut self,
197 content: impl Into<String>,
198 reasoning: impl Into<String>,
199 ) {
200 self.chat_messages
201 .push(ChatMessage::assistant_with_reasoning(content, reasoning));
202 }
203
204 pub fn push_user_message_with_images(
205 &mut self,
206 content: impl Into<String>,
207 images: Vec<ImageAttachment>,
208 ) {
209 self.chat_messages
210 .push(ChatMessage::user_with_images(content, images));
211 }
212
213 pub fn push_assistant_tool_call(
214 &mut self,
215 tool_call_id: &str,
216 tool_name: &str,
217 arguments_json: &str,
218 ) {
219 self.chat_messages.push(ChatMessage::assistant_tool_call(
220 tool_call_id,
221 tool_name,
222 arguments_json,
223 ));
224 }
225
226 fn preview_args(args: &str, max_chars: usize) -> String {
232 format!("{:?}", args.chars().take(max_chars).collect::<String>())
233 }
234
235 pub fn render_assistant_tool_calls(
241 tool_calls: &[(String, String, String)],
242 reasoning: Option<String>,
243 content: Option<String>,
244 ) -> ChatMessage {
245 let calls: Vec<ToolCallMessage> = tool_calls
246 .iter()
247 .map(|(id, name, args)| {
248 let valid_args = if serde_json::from_str::<serde_json::Value>(args).is_ok() {
258 args.clone()
259 } else {
260 tracing::warn!(
261 tool_name = %name,
262 args_len = args.len(),
263 args_preview = %Self::preview_args(args, 80),
264 "tool call arguments are not valid JSON (provider truncated them), \
265 sanitizing to empty object; re-issue instruction goes to the tool_result"
266 );
267 "{}".to_string()
268 };
269 ToolCallMessage {
270 id: id.clone(),
271 name: name.clone(),
272 arguments: valid_args,
273 }
274 })
275 .collect();
276 ChatMessage::Assistant {
277 content,
278 reasoning_content: reasoning,
279 tool_calls: Some(calls),
280 thinking_signature: None,
281 }
282 }
283
284 pub fn push_assistant_tool_calls(
285 &mut self,
286 tool_calls: &[(String, String, String)],
287 reasoning: Option<String>,
288 content: Option<String>,
289 ) {
290 self.push_chat_message(Self::render_assistant_tool_calls(
291 tool_calls, reasoning, content,
292 ));
293 }
294
295 pub fn push_chat_message(&mut self, message: ChatMessage) {
298 self.chat_messages.push(message);
299 }
300
301 pub fn push_tool_result(&mut self, tool_call_id: &str, content: impl Into<String>) {
302 self.chat_messages
303 .push(ChatMessage::tool(tool_call_id, content));
304 }
305
306 pub fn remove_ephemeral_messages(&mut self) {
310 let before = self.chat_messages.len();
311 self.chat_messages.retain(|m| !m.is_ephemeral());
312 let removed = before - self.chat_messages.len();
313 if removed > 0 {
314 tracing::debug!(
315 removed,
316 remaining = self.chat_messages.len(),
317 "ephemeral messages cleaned up"
318 );
319 }
320 }
321
322 pub fn turn_count(&self) -> usize {
325 self.chat_messages
326 .iter()
327 .filter(|m| matches!(m, ChatMessage::User { .. }))
328 .count()
329 }
330
331 pub fn trim_oldest_turns(&mut self, max_turns: usize) {
334 let current_turns = self.turn_count();
335 if current_turns <= max_turns {
336 return;
337 }
338 let turns_to_remove = current_turns - max_turns;
339
340 let user_positions: Vec<usize> = self
342 .chat_messages
343 .iter()
344 .enumerate()
345 .filter_map(|(i, m)| {
346 if matches!(m, ChatMessage::User { .. }) {
347 Some(i)
348 } else {
349 None
350 }
351 })
352 .collect();
353
354 if user_positions.len() <= turns_to_remove {
355 return;
356 }
357
358 let system_prefix = self
360 .chat_messages
361 .iter()
362 .take_while(|m| matches!(m, ChatMessage::System { .. }))
363 .count();
364
365 let drain_end = user_positions[turns_to_remove];
367 if system_prefix >= drain_end {
368 return; }
370
371 self.chat_messages.drain(system_prefix..drain_end);
372 }
373
374 pub fn pop_last_message(&mut self) {
377 self.chat_messages.pop();
378 }
379
380 pub fn close_dangling_tool_calls(&mut self, error_summary: &str) {
381 let assistant_idx = self.chat_messages.iter().rposition(
382 |m| matches!(m, ChatMessage::Assistant { tool_calls: Some(tc), .. } if !tc.is_empty()),
383 );
384
385 let Some(assistant_idx) = assistant_idx else {
386 return;
387 };
388
389 let ChatMessage::Assistant {
390 tool_calls: Some(tc),
391 ..
392 } = &self.chat_messages[assistant_idx]
393 else {
394 return;
395 };
396
397 let all_ids: Vec<String> = tc.iter().map(|t| t.id.clone()).collect();
398
399 let answered_ids: Vec<String> = self.chat_messages[assistant_idx + 1..]
400 .iter()
401 .filter_map(|m| match m {
402 ChatMessage::Tool { tool_call_id, .. } => Some(tool_call_id.clone()),
403 _ => None,
404 })
405 .collect();
406
407 for id in &all_ids {
408 if !answered_ids.iter().any(|a| a == id) {
409 self.push_tool_result(id, error_summary);
410 }
411 }
412 }
413
414 pub fn set_chat_messages(&mut self, messages: Vec<ChatMessage>) -> Result<(), String> {
424 validate_message_sequence(&messages)?;
425 self.chat_messages = messages;
426 Ok(())
427 }
428
429 pub fn recount_actions_from_messages(&mut self) {
435 self.run_state.total_actions = self
436 .chat_messages
437 .iter()
438 .filter_map(|m| match m {
439 ChatMessage::Assistant {
440 tool_calls: Some(tc),
441 ..
442 } => Some(tc.len()),
443 _ => None,
444 })
445 .sum();
446 }
447}
448
449pub fn validate_message_sequence(messages: &[ChatMessage]) -> Result<(), String> {
462 if !messages
463 .iter()
464 .any(|m| !matches!(m, ChatMessage::System { .. } | ChatMessage::Custom { .. }))
465 {
466 return Err(
467 "sequence contains no sendable message: System/Custom alone leave the \
468 provider `messages` array empty"
469 .to_string(),
470 );
471 }
472
473 let mut pending_tool_call_ids: HashSet<String> = HashSet::new();
474
475 for (i, msg) in messages.iter().enumerate() {
476 match msg {
477 ChatMessage::Tool { tool_call_id, .. } => {
478 if pending_tool_call_ids.is_empty() {
479 return Err(format!(
480 "message[{}]: Tool message with call_id '{}' has no preceding tool_call",
481 i, tool_call_id
482 ));
483 }
484 if !pending_tool_call_ids.remove(tool_call_id) {
486 return Err(format!(
487 "message[{}]: Tool message with call_id '{}' does not match any pending tool_call (already answered or unknown)",
488 i, tool_call_id
489 ));
490 }
491 }
492 ChatMessage::Assistant {
493 tool_calls: Some(tc),
494 ..
495 } => {
496 if !pending_tool_call_ids.is_empty() {
498 return Err(format!(
499 "message[{}]: Assistant message with new tool_calls appears before pending calls were answered: {:?}",
500 i, pending_tool_call_ids
501 ));
502 }
503 pending_tool_call_ids = tc.iter().map(|t| t.id.clone()).collect();
504 }
505 _ => {}
506 }
507 }
508
509 if !pending_tool_call_ids.is_empty() {
511 return Err(format!(
512 "message sequence ends with unanswered tool calls: {:?}",
513 pending_tool_call_ids
514 ));
515 }
516
517 Ok(())
518}
519
520#[cfg(test)]
521fn make_session() -> AgentSession {
522 AgentSession::new(SessionId::new(1))
523}
524
525#[cfg(test)]
526mod tests;
527
528#[cfg(test)]
529mod validate_tests;
530
531#[cfg(test)]
532mod proptest_tests;