Skip to main content

agent_base/engine/
session.rs

1use std::collections::HashSet;
2
3use serde::{Deserialize, Serialize};
4
5use crate::types::{ChatMessage, ImageAttachment, Message, MessageRole, ToolCallMessage};
6
7use crate::types::SessionId;
8
9// RunState moved to agent-types (D5+OV-11): the counting state rides in
10// `CheckpointData`, so it must live where the checkpoint payload lives.
11// Re-exported here so existing `engine::session::RunState` imports keep working.
12pub use crate::types::RunState;
13
14/// Deserialization shim for backward compatibility.
15///
16/// Before `RunState` was introduced, `nudge_count`, `turn_tool_calls`,
17/// `reasoning_only_strikes`, and `empty_response_strikes` were flat fields
18/// on `AgentSession` — and the session-lifetime total lived at the top level
19/// as `total_tool_calls`. This struct accepts **both** the old flat format and
20/// the new nested `run_state` format, migrating legacy data on the fly.
21#[derive(Deserialize)]
22struct RawAgentSession {
23    id: Option<SessionId>,
24    chat_messages: Vec<ChatMessage>,
25    always_allowed_actions: HashSet<String>,
26    /// Pre-T7 session total (D5 moved it into `RunState::total_actions`).
27    /// Optional so new-format payloads omit it; when present it migrates into
28    /// the counting state — the one counting home.
29    #[serde(default)]
30    total_tool_calls: Option<usize>,
31
32    // ── new format (preferred) ──
33    run_state: Option<RunState>,
34
35    // ── legacy flat fields (fallback) ──
36    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        // Pre-T7 wire kept the session total at the top level; migrate it into
52        // the counting state (D5: one counting home). New-format payloads omit
53        // the top-level key and keep the total already inside `run_state`.
54        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/// Stable identity + rolling state of a single chat thread.
67///
68/// `Default` returns a fresh session; load persisted state via serde.
69/// Backward-compatible with the old flat-field format (pre-`RunState` migration).
70#[derive(Clone, Debug, Default, Serialize, Deserialize)]
71#[serde(from = "RawAgentSession")]
72pub struct AgentSession {
73    id: Option<SessionId>,
74    /// LLM API format messages, sent directly to the provider.
75    /// This is the single source of truth for the conversation state.
76    chat_messages: Vec<ChatMessage>,
77    always_allowed_actions: HashSet<String>,
78    /// Run-level state tracking for the react loop. Holds ALL counting state
79    /// (D5): `run_state.total_actions` is the session-lifetime total middleware
80    /// decisions like "first_turn_only" read.
81    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    /// Derive a simplified `Vec<Message>` view from the canonical `chat_messages`.
99    /// Assistant messages that contain only tool_calls (no text content) are
100    /// skipped, since they have no corresponding simplified representation.
101    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    /// Mutable reference, for advanced scenarios that need to operate on messages directly.
121    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    /// Push a message as ephemeral (user/system only): the LLM sees it this
145    /// turn, then `remove_ephemeral_messages` strips it at turn end — from
146    /// both memory and persistence.
147    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                // Ephemeral assistant/tool messages are not a thing; fall back
154                // to a regular push rather than silently mis-marking.
155                self.push_message(role, content);
156                return;
157            }
158        };
159        self.chat_messages.push(chat_msg);
160    }
161
162    /// Push machine-composed input on the user role (a tool-failure notice, a
163    /// background-task wake): the model treats it like a user turn, but the
164    /// synthetic flag keeps it out of the task trail context rotation carries
165    /// into a fresh window.
166    pub fn push_user_synthetic(&mut self, content: impl Into<String>) {
167        self.chat_messages
168            .push(ChatMessage::user_synthetic(content));
169    }
170
171    /// Replace the system prompt — the first **non-ephemeral** System message
172    /// (wherever it sits, matching how `context` locates it); inserted at
173    /// index 0 if none exists. All other messages are untouched. Hosts that
174    /// own prompt composition (e.g. skill activation) re-bake through this.
175    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    /// Push an assistant message with reasoning/thinking content preserved.
193    /// This allows the LLM to see its own prior reasoning in subsequent turns,
194    /// preventing it from re-deriving the same conclusions every turn.
195    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    /// Escape and truncate the arguments to their first `max_chars` characters, so the
227    /// truncation WARN can display the raw content directly. Rust debug escaping keeps
228    /// unclosed JSON, control characters, and CJK boundaries clearly distinguishable, so
229    /// troubleshooting provider truncation in production no longer requires indirectly
230    /// reconstructing the content.
231    fn preview_args(args: &str, max_chars: usize) -> String {
232        format!("{:?}", args.chars().take(max_chars).collect::<String>())
233    }
234
235    /// Render one assistant message carrying tool calls — the tool backend's
236    /// history protocol (invalid-JSON sanitization included). Split out of
237    /// [`Self::push_assistant_tool_calls`] so the backend can both push the
238    /// message and carry it in `Observation::history_messages` for checkpoint
239    /// replay (M3 seam).
240    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                // Invalid JSON args (provider truncated the stream mid-generation)
249                // are sanitized to an empty object. We deliberately do NOT wrap
250                // them in a descriptive `{error, original_args_preview, message}`
251                // object: "{}" is valid JSON so the next request is never rejected
252                // with 400, and — critically — a rich error object here becomes an
253                // imitation vector: the model replays it verbatim as the next
254                // call's arguments and, because it parses, it slips past the react
255                // truncation guard. The truncation explanation lives in the
256                // paired tool_result, which is where the model reads feedback.
257                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    /// Push one already-built message — the kernel's verbatim push for
296    /// backend-rendered history ([`crate::types::Observation::history_messages`]).
297    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    /// Remove all ephemeral messages (ephemeral=true).
307    ///
308    /// Called at the end of a turn to ensure injected ephemeral content does not linger into the next turn.
309    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    /// Count the number of conversation turns.
323    /// A turn starts with a User message and includes subsequent Assistant/Tool messages.
324    pub fn turn_count(&self) -> usize {
325        self.chat_messages
326            .iter()
327            .filter(|m| matches!(m, ChatMessage::User { .. }))
328            .count()
329    }
330
331    /// Remove the oldest turns from the front until turn count ≤ max_turns.
332    /// Preserves the System message at index 0 if present.
333    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        // Find User message positions (turn boundaries) in chat_messages
341        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        // Preserve system prefix: count leading System messages
359        let system_prefix = self
360            .chat_messages
361            .iter()
362            .take_while(|m| matches!(m, ChatMessage::System { .. }))
363            .count();
364
365        // Drain from system_prefix up to the start of the (turns_to_remove + 1)-th turn
366        let drain_end = user_positions[turns_to_remove];
367        if system_prefix >= drain_end {
368            return; // nothing to drain after system messages
369        }
370
371        self.chat_messages.drain(system_prefix..drain_end);
372    }
373
374    /// Remove the last message from `chat_messages`.
375    /// Used by the max_message_tokens safety valve to discard oversized messages.
376    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    /// Replace chat messages — for persistence restore and window compaction.
415    /// Validates message sequence before replacing.
416    ///
417    /// Counters are NOT touched (D5): the counting source is explicit. A
418    /// checkpoint restore trusts the persisted `RunState` (co-written with the
419    /// checkpoint/journal — OV-11); only a messages-only restore — the
420    /// old-format corpus — recounts via [`Self::recount_actions_from_messages`].
421    /// Recounting here would also deflate the total after compaction and lie
422    /// for restored histories that carry synthesized "已中断/未执行" results.
423    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    /// Old-format compatibility (D5: 消息重算只做旧格式兼容): rebuild the
430    /// session-lifetime action total from the history's assistant tool-call
431    /// lens. Call ONLY on restores that carry no persisted counting state —
432    /// the lens counts call attempts, not executed actions, so it is a
433    /// fallback, never the primary source.
434    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
449/// Validate that a chat message sequence is well-formed for LLM API consumption.
450///
451/// Checks:
452/// - At least one non-System/non-Custom message (System maps to the
453///   top-level `system` parameter, Custom is stripped — a sequence of only
454///   those leaves an empty `messages` array, which providers reject with
455///   HTTP 400). Guards compaction outputs against producing an unsendable
456///   window.
457/// - No Tool message without a preceding Assistant with matching tool_call
458/// - No duplicate Tool messages for the same tool_call_id
459/// - All tool_calls in an Assistant batch must be answered before the next Assistant batch
460/// - No unanswered tool calls at the end of the sequence
461pub 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                // Remove the ID on match — also detects duplicates (second remove returns false)
485                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                // Previous batch must be fully answered before a new batch starts
497                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    // All tool calls must be answered by the end of the sequence
510    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;