Skip to main content

vtcode_core/core/agent/session/
mod.rs

1//! Centralized agent session state management.
2
3use crate::core::agent::error_recovery::ErrorRecoveryState;
4use crate::core::agent::task::{TaskOutcome, TaskResults};
5use crate::core::pending_actions::PendingActions;
6use crate::core::state_schema::SchemaVersion;
7use crate::exec::events::Usage;
8use crate::llm::provider::{Message, ResponsesContinuationState, ResponsesContinuationStore};
9use crate::llm::providers::gemini::wire::{Content, FunctionResponse, Part};
10use crate::llm::request_gap::RequestGapTracker;
11use parking_lot::Mutex;
12use std::collections::VecDeque;
13use std::sync::Arc;
14use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
15use vtcode_commons::ErrorCategory;
16use vtcode_exec_events::ThreadEvent;
17
18#[derive(Debug, Clone)]
19pub struct ToolExecutionObservation {
20    pub tool_name: String,
21    pub attempts: u32,
22    pub duration_ms: u64,
23    pub error_category: Option<ErrorCategory>,
24}
25
26/// Manages the state of an active agent session, including conversation history,
27/// statistics, and turn-based constraints.
28pub struct AgentSessionState {
29    /// The thread or session ID.
30    pub session_id: String,
31
32    /// Provider-specific conversation history (e.g., Gemini style).
33    pub conversation: Vec<Content>,
34
35    /// Standardized conversation messages (OpenAI/Anthropic style).
36    ///
37    /// Stored in an `Arc` so request construction can share the history with
38    /// the provider without cloning the full conversation every turn.
39    /// Mutations use copy-on-write; the common unique-owner path remains O(1).
40    pub messages: Arc<Vec<Message>>,
41
42    /// Schema version for durable state persistence.
43    pub schema_version: SchemaVersion,
44
45    /// Statistics for the current session.
46    pub stats: SessionStats,
47    /// Auto-compaction suppression state: `SUPPRESS_NONE` allows compaction;
48    /// other values gate automatic compaction until cleared by success, model
49    /// switch, or explicit `/compact`.
50    pub auto_compact_suppressed: u8,
51
52    /// Constraints and limits for the session.
53    pub constraints: SessionConstraints,
54
55    /// Outcome of the session if completed.
56    pub outcome: TaskOutcome,
57    /// Provider stop reason associated with the last model turn, when available.
58    pub stop_reason: Option<String>,
59    /// Estimated total API cost in USD for the session, when available.
60    pub total_cost_usd: Option<f64>,
61
62    /// Whether the session has completed.
63    pub is_completed: bool,
64
65    /// Current reasoning stage.
66    pub current_stage: Option<String>,
67
68    // Tracking for side-effects and progress
69    pub created_contexts: Vec<String>,
70    pub modified_files: Vec<String>,
71    pub executed_commands: Vec<String>,
72    pub warnings: Vec<String>,
73    pub last_file_path: Option<String>,
74    pub last_dir_path: Option<String>,
75
76    // Internal loop state
77    pub consecutive_tool_loops: usize,
78    pub tool_loop_limit_hit: bool,
79    /// Consecutive escalation events in the current escalation chain.
80    /// Reset to 0 when tool calls dispatch without escalation.
81    pub consecutive_escalations: u32,
82    /// Rolling window of progress hashes for stagnation detection.
83    /// Each entry is a hash of the assistant response content + key state.
84    pub progress_hashes: VecDeque<u64>,
85    /// Consecutive turns with matching progress hashes.
86    pub stagnant_turns: usize,
87    pub last_processed_message_idx: usize,
88    /// Responses-style continuation state keyed by normalized provider/model pairs.
89    pub previous_response_chains: ResponsesContinuationStore,
90    /// Agent-local recent error diagnostics for interrupted or repeated tool failures.
91    pub error_recovery: Arc<Mutex<ErrorRecoveryState>>,
92    /// Pending tool actions that have been issued but not yet returned.
93    pub pending_actions: PendingActions,
94
95    // Legacy / Stats fields for compatibility
96    pub consecutive_idle_turns: usize,
97    pub max_tool_loop_streak: usize,
98    pub turn_count: usize,
99    pub turn_total_ms: u128,
100    pub turn_max_ms: u128,
101    pub turn_durations_ms: Vec<u128>,
102    /// One canonical terminal observation per tool invocation in this turn.
103    pub turn_tool_observations: Vec<ToolExecutionObservation>,
104    /// Cached total estimated token count for the conversation history.
105    /// Updated incrementally on each push to avoid O(n) scans per turn.
106    cached_total_tokens: usize,
107
108    /// Tracks the idle gap since the last dispatched LLM request, so a long
109    /// enough pause can warn that the provider prompt cache has likely
110    /// expired. Shared with the interactive session state; see
111    /// [`RequestGapTracker`].
112    request_gap: RequestGapTracker,
113
114    /// Reasoning effort used for the last dispatched request, used to detect
115    /// mid-task changes that invalidate the provider prompt cache.
116    last_reasoning_effort: Option<crate::config::types::ReasoningEffortLevel>,
117    /// Model used for the last dispatched request, used to detect mid-task
118    /// model switches. Prompt caches are unique per model, so switching
119    /// rebuilds the cache at full input cost even when the rest of the
120    /// prefix is unchanged.
121    last_model: Option<String>,
122}
123
124/// Statistics tracked during an agent session.
125#[derive(Debug, Default, Clone)]
126pub struct SessionStats {
127    pub turns_executed: usize,
128    pub total_duration: Duration,
129    pub turn_durations: Vec<Duration>,
130    pub total_usage: Usage,
131    /// Provider name for the active session, used to normalize per-turn usage
132    /// (see [`crate::llm::usage_cost::provider_reports_exclusive_input`]). An
133    /// empty string is treated as a non-exclusive-input provider, which
134    /// preserves existing behavior for callers that never set it.
135    pub provider_name: String,
136    /// Rolling prompt-cache health fed by every merged turn. Fires at most
137    /// two session-scoped alerts (sustained misses, low hit rate) mirroring
138    /// the "monitor cache hit rate like uptime" discipline.
139    pub prompt_cache_health: super::cache_health::PromptCacheHealthMonitor,
140}
141
142impl SessionStats {
143    /// Merge one turn's provider usage into the session totals and feed the
144    /// prompt-cache health monitor. Returns a health alert the first time a
145    /// degraded pattern is confirmed, `None` otherwise.
146    pub fn merge_usage(
147        &mut self,
148        usage: &crate::llm::provider::Usage,
149    ) -> Option<super::cache_health::CacheHealthAlert> {
150        let normalized = crate::llm::usage_cost::normalized_turn_usage(&self.provider_name, usage);
151        self.total_usage.add(&normalized);
152        self.prompt_cache_health.record_turn(&normalized)
153    }
154}
155
156/// Constraints applied to an agent session.
157#[derive(Debug, Clone)]
158pub struct SessionConstraints {
159    pub max_turns: usize,
160    pub max_tool_loops: usize,
161    pub max_context_tokens: usize,
162}
163
164impl AgentSessionState {
165    pub fn new(session_id: String, max_turns: usize, max_tool_loops: usize, max_context_tokens: usize) -> Self {
166        Self {
167            session_id,
168            schema_version: SchemaVersion::CURRENT,
169            conversation: Vec::new(),
170            messages: Arc::new(Vec::new()),
171            stats: SessionStats::default(),
172            auto_compact_suppressed: crate::compaction::SUPPRESS_NONE,
173            constraints: SessionConstraints { max_turns, max_tool_loops, max_context_tokens },
174            outcome: TaskOutcome::Unknown,
175            stop_reason: None,
176            total_cost_usd: None,
177            is_completed: false,
178            current_stage: None,
179            created_contexts: Vec::with_capacity(16),
180            modified_files: Vec::with_capacity(32),
181            executed_commands: Vec::with_capacity(64),
182            warnings: Vec::with_capacity(16),
183            last_file_path: None,
184            last_dir_path: None,
185            consecutive_tool_loops: 0,
186            tool_loop_limit_hit: false,
187            consecutive_escalations: 0,
188            progress_hashes: VecDeque::with_capacity(16),
189            stagnant_turns: 0,
190            last_processed_message_idx: 0,
191            previous_response_chains: ResponsesContinuationStore::default(),
192            error_recovery: Arc::new(Mutex::new(ErrorRecoveryState::default())),
193            pending_actions: PendingActions::new(100),
194            consecutive_idle_turns: 0,
195            max_tool_loop_streak: 0,
196            turn_count: 0,
197            turn_total_ms: 0,
198            turn_max_ms: 0,
199            turn_durations_ms: Vec::with_capacity(max_turns),
200            turn_tool_observations: Vec::with_capacity(32),
201            cached_total_tokens: 0,
202            request_gap: RequestGapTracker::default(),
203            last_reasoning_effort: None,
204            last_model: None,
205        }
206    }
207
208    /// Records that an LLM request was just dispatched, so the next call to
209    /// [`Self::cache_gap_exceeds`] can measure the idle gap since this request.
210    pub fn note_request_sent(&mut self) {
211        self.request_gap.note_request_sent();
212    }
213
214    /// Returns the elapsed time since the last dispatched request when it
215    /// exceeds `threshold`, or `None` if there was no prior request or the gap
216    /// is still within the threshold. Used to warn that the provider prompt
217    /// cache has likely expired before the next request re-pays full input
218    /// cost.
219    pub fn cache_gap_exceeds(&self, threshold: Duration) -> Option<Duration> {
220        self.request_gap.cache_gap_exceeds(threshold)
221    }
222
223    /// Checks whether `effort` differs from the reasoning effort used for the
224    /// previous request in this session, then stores `effort` as the new
225    /// baseline. Returns `true` only when a prior effort was recorded and it
226    /// differs from `effort` (i.e. this is a genuine mid-task change, not the
227    /// first request of the session).
228    pub fn note_reasoning_effort_change(&mut self, effort: Option<crate::config::types::ReasoningEffortLevel>) -> bool {
229        let changed = matches!(
230            (self.last_reasoning_effort, effort),
231            (Some(previous), Some(current)) if previous != current
232        );
233        self.last_reasoning_effort = effort;
234        changed
235    }
236
237    /// Checks whether `model` differs from the model used for the previous
238    /// request in this session, then stores `model` as the new baseline.
239    /// Returns `true` only when a prior model was recorded and it differs
240    /// from `model` (i.e. this is a genuine mid-task switch, not the first
241    /// request of the session). Prompt caches are unique per model, so a
242    /// switch re-pays full input cost even for an otherwise identical prefix.
243    pub fn note_model_change(&mut self, model: &str) -> bool {
244        let changed = self.last_model.as_deref().is_some_and(|previous| previous != model);
245        self.last_model = Some(model.to_string());
246        changed
247    }
248
249    /// Record a completed turn.
250    pub fn record_turn(&mut self, start: &Instant, recorded: &mut bool) {
251        if *recorded {
252            return;
253        }
254        let duration = start.elapsed();
255        let ms = duration.as_millis() as u64;
256
257        self.stats.turns_executed += 1;
258        self.stats.total_duration += duration;
259        self.stats.turn_durations.push(duration);
260
261        // Legacy stats
262        self.turn_count += 1;
263        self.turn_total_ms += ms as u128;
264        self.turn_max_ms = self.turn_max_ms.max(ms as u128);
265        self.turn_durations_ms.push(ms as u128);
266
267        *recorded = true;
268    }
269
270    pub fn finalize_outcome(&mut self, max_turns: usize) {
271        if self.outcome != TaskOutcome::Unknown {
272            return;
273        }
274        // Priority order: tool loop limit > completion > turn limit
275        if self.tool_loop_limit_hit {
276            self.outcome =
277                TaskOutcome::tool_loop_limit_reached(self.constraints.max_tool_loops, self.consecutive_tool_loops);
278        } else if self.is_completed {
279            self.outcome = TaskOutcome::Success;
280        } else if self.stats.turns_executed >= max_turns {
281            self.outcome = TaskOutcome::turn_limit_reached(max_turns, self.stats.turns_executed);
282        }
283    }
284
285    pub fn register_tool_loop(&mut self) -> usize {
286        self.consecutive_tool_loops += 1;
287        self.max_tool_loop_streak = self.max_tool_loop_streak.max(self.consecutive_tool_loops);
288        self.consecutive_tool_loops
289    }
290
291    pub fn reset_tool_loop_guard(&mut self) {
292        self.consecutive_tool_loops = 0;
293    }
294
295    pub fn previous_response_id_for(&self, provider: &str, model: &str) -> Option<String> {
296        self.previous_response_chain_for(provider, model)
297            .map(|chain| chain.response_id.clone())
298    }
299
300    pub fn previous_response_chain_for(&self, provider: &str, model: &str) -> Option<&ResponsesContinuationState> {
301        self.previous_response_chains.get(provider, model)
302    }
303
304    pub fn set_previous_response_chain(
305        &mut self,
306        provider: &str,
307        model: &str,
308        response_id: Option<&str>,
309        messages: Vec<Message>,
310    ) {
311        self.set_previous_response_chain_shared(provider, model, response_id, Arc::new(messages));
312    }
313
314    /// Store a continuation history that is already reference-counted.
315    ///
316    /// The runtime keeps the exact sent request history alive for provider
317    /// continuation without cloning every message a second time.
318    pub(crate) fn set_previous_response_chain_shared(
319        &mut self,
320        provider: &str,
321        model: &str,
322        response_id: Option<&str>,
323        messages: Arc<Vec<Message>>,
324    ) {
325        self.previous_response_chains.set(provider, model, response_id, messages);
326    }
327
328    pub fn clear_previous_response_chain_for(&mut self, provider: &str, model: &str) {
329        self.previous_response_chains.clear_for(provider, model);
330    }
331
332    pub fn clear_previous_response_chain(&mut self) {
333        self.previous_response_chains.clear();
334    }
335
336    pub fn mark_tool_loop_limit_hit(&mut self) {
337        if self.tool_loop_limit_hit {
338            return;
339        }
340        self.tool_loop_limit_hit = true;
341        self.outcome =
342            TaskOutcome::tool_loop_limit_reached(self.constraints.max_tool_loops, self.consecutive_tool_loops);
343    }
344
345    /// Mutable access to the conversation history.
346    ///
347    /// Returns mutable history with copy-on-write when a request still shares it.
348    #[inline]
349    pub fn messages_mut(&mut self) -> &mut Vec<Message> {
350        Arc::make_mut(&mut self.messages)
351    }
352
353    /// Add a user message to the history with metadata.
354    pub fn add_user_message(&mut self, text: String) {
355        self.add_user_message_with_intent(text, None);
356    }
357
358    /// Add a harness-generated `User`-role notice (recovery nudge, tracker
359    /// continuation, evaluator retry).
360    ///
361    /// The role must stay `User` so the provider treats it as steering, but the
362    /// message is tagged synthetic so reverse history can skip it.
363    pub fn add_synthetic_user_message(&mut self, text: String) {
364        self.add_synthetic_user_message_with_intent(text, None);
365    }
366
367    /// Add a synthetic `User`-role message with its originating follow-up ID.
368    pub fn add_synthetic_user_message_with_intent(&mut self, text: String, intent_id: Option<String>) {
369        let metadata = Self::user_message_metadata(&text, intent_id, true);
370        self.push_user_message(text, metadata);
371    }
372
373    /// Add a user message and optionally tag it with the steering intent that
374    /// produced it. The tag survives message serialization for recovery.
375    pub fn add_user_message_with_intent(&mut self, text: String, intent_id: Option<String>) {
376        let metadata = Self::user_message_metadata(&text, intent_id, false);
377        self.push_user_message(text, metadata);
378    }
379
380    fn user_message_metadata(
381        text: &str,
382        intent_id: Option<String>,
383        synthetic: bool,
384    ) -> crate::core::message_metadata::MessageMetadata {
385        let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
386        let tokens = text.len().saturating_div(4); // rough estimate: ~4 chars per token
387        let metadata = if synthetic {
388            crate::core::message_metadata::MessageMetadata::harness_notice(now, tokens)
389        } else {
390            crate::core::message_metadata::MessageMetadata::user_input(now, tokens)
391        };
392        match intent_id {
393            Some(id) => metadata.with_intent_id(id),
394            None => metadata,
395        }
396    }
397
398    fn push_user_message(&mut self, text: String, metadata: crate::core::message_metadata::MessageMetadata) {
399        self.conversation.push(Content::user_text(text.as_str()));
400        let msg = Message::user(text).with_metadata(metadata);
401        // Role overhead (~4 tokens) + content tokens
402        let msg_tokens = msg.estimate_tokens();
403        self.cached_total_tokens = self.cached_total_tokens.saturating_add(msg_tokens);
404        self.messages_mut().push(msg);
405    }
406
407    /// Threshold for consecutive identical progress hashes before stagnation is declared.
408    const PROGRESS_STAGNATION_THRESHOLD: usize = 4;
409
410    /// Compute a hash of the current assistant response content for progress tracking.
411    fn assistant_response_hash(&self) -> Option<u64> {
412        use crate::llm::provider::{MessageContent, MessageRole};
413        let last_assistant = self.messages.iter().rev().find(|m| m.role == MessageRole::Assistant)?;
414        use std::hash::{Hash, Hasher};
415        let mut hasher = std::collections::hash_map::DefaultHasher::new();
416        match &last_assistant.content {
417            MessageContent::Text(t) => t.hash(&mut hasher),
418            MessageContent::Parts(parts) => {
419                for part in parts {
420                    if let crate::llm::provider::ContentPart::Text { text, .. } = part {
421                        text.hash(&mut hasher);
422                    }
423                }
424            }
425        }
426        Some(hasher.finish())
427    }
428
429    /// Record the current assistant response hash and return true if stagnation detected.
430    pub fn record_progress_hash_and_check_stagnation(&mut self) -> bool {
431        let Some(hash) = self.assistant_response_hash() else {
432            self.stagnant_turns = 0;
433            return false;
434        };
435        if self.progress_hashes.back() == Some(&hash) {
436            self.stagnant_turns += 1;
437        } else {
438            self.stagnant_turns = 0;
439        }
440        self.progress_hashes.push_back(hash);
441        if self.progress_hashes.len() > 16 {
442            self.progress_hashes.pop_front();
443        }
444        self.stagnant_turns >= Self::PROGRESS_STAGNATION_THRESHOLD
445    }
446
447    /// Attach metadata to the most recent message. Used by the execution loop
448    /// to annotate LLM responses and tool results after they are pushed.
449    pub fn attach_metadata_to_last(&mut self, source: &str, estimated_tokens: usize) {
450        if let Some(last) = self.messages_mut().last_mut() {
451            let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
452            let metadata = match source {
453                "llm_response" => crate::core::message_metadata::MessageMetadata::llm_response(now, estimated_tokens),
454                "tool_result" => crate::core::message_metadata::MessageMetadata::tool_result(now, estimated_tokens),
455                "system" => crate::core::message_metadata::MessageMetadata::system(now, estimated_tokens),
456                "synthetic" => crate::core::message_metadata::MessageMetadata::synthetic(now, estimated_tokens),
457                _ => crate::core::message_metadata::MessageMetadata::user_input(now, estimated_tokens),
458            };
459            last.metadata = Some(metadata);
460        }
461    }
462
463    /// Check if context limits are approaching.
464    pub fn utilization(&self) -> f64 {
465        if self.constraints.max_context_tokens == 0 {
466            return 0.0;
467        }
468        self.total_tokens() as f64 / self.constraints.max_context_tokens as f64
469    }
470
471    /// Calculate total estimated tokens in the conversation.
472    /// Returns the cached value updated incrementally on each push.
473    /// Use [`Self::reconcile_token_count`] after mutations that bypass push methods.
474    #[inline]
475    pub fn total_tokens(&self) -> usize {
476        self.cached_total_tokens
477    }
478
479    /// Recompute the cached token count from scratch by scanning all messages.
480    /// Call this after mutations that bypass push methods (e.g., `normalize_history`,
481    /// direct `messages` field access, or deserialization).
482    pub fn reconcile_token_count(&mut self) {
483        self.cached_total_tokens = self.messages.iter().map(|m| m.estimate_tokens()).sum();
484    }
485
486    /// Manually adjust the cached token count. Use when a message is added
487    /// or removed outside of the standard push methods.
488    #[inline]
489    pub fn adjust_token_count(&mut self, delta: isize) {
490        if delta >= 0 {
491            // `delta >= 0` is checked above, so the conversion is infallible
492            self.cached_total_tokens = self
493                .cached_total_tokens
494                .saturating_add(usize::try_from(delta).expect("delta >= 0 checked above"));
495        } else {
496            self.cached_total_tokens = self.cached_total_tokens.saturating_sub(delta.unsigned_abs());
497        }
498    }
499
500    /// Pre-flight check: does the assembled prompt fit within the context window?
501    ///
502    /// Estimates total tokens for the full request (conversation history +
503    /// system prompt + tool definitions) and compares against the available
504    /// budget (`max_context_tokens - reserved_output_tokens`).
505    ///
506    /// Returns `(fits, estimated_total, available_budget)`.
507    pub fn preflight_token_check(
508        &self,
509        system_prompt_tokens: usize,
510        tool_def_tokens: usize,
511        reserved_output_tokens: usize,
512    ) -> (bool, usize, usize) {
513        let budget = self.constraints.max_context_tokens.saturating_sub(reserved_output_tokens);
514        let estimated = self
515            .total_tokens()
516            .saturating_add(system_prompt_tokens)
517            .saturating_add(tool_def_tokens);
518        (estimated <= budget, estimated, budget)
519    }
520
521    /// Find a safe split point for history trimming that doesn't break tool call/output pairs.
522    pub fn find_safe_split_point(&self, preferred_split_at: usize) -> usize {
523        crate::core::agent::state::safe_history_split_point(&self.messages, self.conversation.len(), preferred_split_at)
524    }
525
526    /// Normalize history to enforce call/output pairing invariants.
527    pub fn normalize(&mut self) {
528        crate::core::agent::state::normalize_history(self.messages_mut());
529        self.reconcile_token_count();
530    }
531
532    /// Clear all conversation history for a context reset.
533    ///
534    /// Following the context engineering pattern: "Context reset uses external
535    /// artifacts as startup material to open a clean new context/session. It
536    /// does not preserve the full conversation history."
537    ///
538    /// This clears `messages`, `conversation`, resets the token count, and
539    /// resets the processed-message cursor. The orient context (injected via
540    /// the system prompt) provides the agent with durable artifact references
541    /// to reorient from. Response continuation chains are also cleared since
542    /// they reference the discarded history.
543    pub fn clear_conversation_history(&mut self) {
544        self.messages_mut().clear();
545        self.conversation.clear();
546        self.cached_total_tokens = 0;
547        self.last_processed_message_idx = 0;
548        self.previous_response_chains.clear();
549        self.consecutive_tool_loops = 0;
550        self.tool_loop_limit_hit = false;
551        self.consecutive_escalations = 0;
552        self.progress_hashes.clear();
553        self.stagnant_turns = 0;
554        self.pending_actions = PendingActions::new(100);
555        self.consecutive_idle_turns = 0;
556        self.max_tool_loop_streak = 0;
557        self.turn_tool_observations.clear();
558        self.current_stage = None;
559        self.auto_compact_suppressed = crate::compaction::SUPPRESS_NONE;
560        self.error_recovery.lock().reset();
561    }
562
563    pub fn into_results(
564        self,
565        summary: String,
566        thread_events: Vec<ThreadEvent>,
567        total_duration_ms: u128,
568    ) -> TaskResults {
569        let average_turn_duration_ms = if self.turn_count > 0 {
570            Some(self.turn_total_ms as f64 / self.turn_count as f64)
571        } else {
572            None
573        };
574        let max_turn_duration_ms = if self.turn_count > 0 {
575            Some(self.turn_max_ms)
576        } else {
577            None
578        };
579
580        TaskResults {
581            created_contexts: self.created_contexts,
582            modified_files: self.modified_files,
583            executed_commands: self.executed_commands,
584            summary,
585            stop_reason: self.stop_reason,
586            total_cost_usd: self.total_cost_usd,
587            warnings: self.warnings,
588            thread_events,
589            outcome: self.outcome,
590            turns_executed: self.stats.turns_executed,
591            total_duration_ms,
592            average_turn_duration_ms,
593            max_turn_duration_ms,
594            turn_durations_ms: self.turn_durations_ms,
595        }
596    }
597
598    /// Push a tool event (result or error) to both conversation (for Gemini) and messages.
599    ///
600    /// Shared implementation for `push_tool_result` and `push_tool_error` to
601    /// eliminate the duplicated Gemini FunctionResponse construction.
602    fn push_tool_event(&mut self, call_id: String, tool_name: &str, value: &serde_json::Value, is_gemini: bool) {
603        if is_gemini {
604            self.conversation.push(Content {
605                role: "function".to_string(),
606                parts: vec![Part::FunctionResponse {
607                    function_response: FunctionResponse {
608                        name: tool_name.to_string(),
609                        response: value.clone(),
610                        id: Some(call_id.clone()),
611                    },
612                    thought_signature: None,
613                }],
614            });
615        }
616        let serialized = serde_json::to_string(value).expect("Value serialization is infallible");
617        let msg = Message::tool_response(call_id, serialized);
618        let tokens = msg.estimate_tokens();
619        self.cached_total_tokens = self.cached_total_tokens.saturating_add(tokens);
620        self.messages_mut().push(msg);
621    }
622
623    /// Push a successful tool result to both conversation (for Gemini) and messages.
624    pub fn push_tool_result(&mut self, call_id: String, tool_name: &str, result: &serde_json::Value, is_gemini: bool) {
625        self.push_tool_event(call_id, tool_name, result, is_gemini);
626        // Deduplicate tool names — a long session may call the same tool
627        // hundreds of times, and the results report only needs unique entries.
628        let tool_name_owned = tool_name.to_owned();
629        if !self.executed_commands.contains(&tool_name_owned) {
630            self.executed_commands.push(tool_name_owned);
631        }
632    }
633
634    /// Push a tool error to both conversation (for Gemini) and messages.
635    pub fn push_tool_error(
636        &mut self,
637        call_id: String,
638        tool_name: &str,
639        error_payload: &serde_json::Value,
640        is_gemini: bool,
641    ) {
642        self.push_tool_event(call_id, tool_name, error_payload, is_gemini);
643    }
644
645    /// Record a session warning, skipping exact duplicates.
646    ///
647    /// In long-running sessions, the same warning can fire repeatedly (e.g.
648    /// "Tool was rate limited; halting further tool calls this turn." on every
649    /// rate-limited call). Deduplicating keeps the `TaskResults.warnings` Vec
650    /// bounded and the evaluator prompt clean. The Vec is also capped at
651    /// `MAX_SESSION_WARNINGS` as a safety net against unbounded growth from
652    /// unique-but-repetitive warnings. When the cap is reached a single
653    /// elision marker is appended so consumers know warnings were truncated
654    /// rather than silently losing data.
655    pub fn push_warning(&mut self, warning: impl Into<String>) {
656        let warning = warning.into();
657        if self.warnings.contains(&warning) {
658            return;
659        }
660        if self.warnings.len() < MAX_SESSION_WARNINGS {
661            self.warnings.push(warning);
662        } else if self.warnings.last().is_none_or(|w| w != WARNINGS_ELIDED_MARKER) {
663            self.warnings.push(WARNINGS_ELIDED_MARKER.to_string());
664        }
665    }
666}
667
668/// Maximum number of warnings retained in session state. Exact duplicates are
669/// always skipped; this cap limits unique-but-repetitive warnings. One extra
670/// elision marker may be appended beyond this count.
671const MAX_SESSION_WARNINGS: usize = 200;
672const WARNINGS_ELIDED_MARKER: &str = "[Additional unique warnings elided — session warning cap reached]";
673
674#[cfg(test)]
675mod tests {
676    use super::AgentSessionState;
677    use crate::config::types::ReasoningEffortLevel;
678    use crate::llm::provider::Message;
679    use crate::llm::providers::gemini::wire::Part;
680    use std::sync::Arc;
681    use std::thread;
682    use std::time::Duration;
683
684    /// `cache_gap_exceeds`/`note_request_sent` delegate to the shared
685    /// `RequestGapTracker`, which owns the full behavioral test coverage
686    /// (see `crate::llm::request_gap`); this just pins the delegation.
687    #[test]
688    fn cache_gap_exceeds_delegates_to_request_gap_tracker() {
689        let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
690        assert_eq!(state.cache_gap_exceeds(Duration::from_millis(1)), None);
691
692        state.note_request_sent();
693        thread::sleep(Duration::from_millis(15));
694        let gap = state.cache_gap_exceeds(Duration::from_millis(5));
695        assert!(gap.is_some_and(|elapsed| elapsed >= Duration::from_millis(15)));
696    }
697
698    #[test]
699    fn note_reasoning_effort_change_is_false_on_first_request() {
700        let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
701        assert!(!state.note_reasoning_effort_change(Some(ReasoningEffortLevel::Medium)));
702    }
703
704    #[test]
705    fn note_reasoning_effort_change_is_false_when_unchanged() {
706        let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
707        assert!(!state.note_reasoning_effort_change(Some(ReasoningEffortLevel::Medium)));
708        assert!(!state.note_reasoning_effort_change(Some(ReasoningEffortLevel::Medium)));
709    }
710
711    #[test]
712    fn note_reasoning_effort_change_is_true_when_changed() {
713        let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
714        assert!(!state.note_reasoning_effort_change(Some(ReasoningEffortLevel::Medium)));
715        assert!(state.note_reasoning_effort_change(Some(ReasoningEffortLevel::High)));
716        // Baseline is now High; requesting High again is not a change.
717        assert!(!state.note_reasoning_effort_change(Some(ReasoningEffortLevel::High)));
718    }
719
720    #[test]
721    fn note_model_change_is_false_on_first_request() {
722        let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
723        assert!(!state.note_model_change("gpt-5.6"));
724    }
725
726    #[test]
727    fn note_model_change_is_false_when_unchanged() {
728        let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
729        assert!(!state.note_model_change("gpt-5.6"));
730        assert!(!state.note_model_change("gpt-5.6"));
731    }
732
733    #[test]
734    fn note_model_change_is_true_when_changed() {
735        let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
736        assert!(!state.note_model_change("gpt-5.6"));
737        assert!(state.note_model_change("claude-opus-4-6"));
738        // Baseline is now Opus; requesting Opus again is not a change.
739        assert!(!state.note_model_change("claude-opus-4-6"));
740    }
741
742    #[test]
743    fn previous_response_chain_is_scoped_to_provider_and_model() {
744        let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
745        let messages_52 = vec![Message::user("hello".to_string())];
746        let messages_54 = vec![Message::user("continue".to_string())];
747
748        state.set_previous_response_chain("openai", "gpt-5.6", Some("resp_123"), messages_52.clone());
749        state.set_previous_response_chain("openai", "gpt-5.6-sol", Some("resp_456"), messages_54.clone());
750
751        assert_eq!(state.previous_response_id_for("openai", "gpt-5.6"), Some("resp_123".to_string()));
752        assert_eq!(state.previous_response_id_for("openai", "gpt-5.6-sol"), Some("resp_456".to_string()));
753        assert_eq!(state.previous_response_id_for("gemini", "gpt-5.6"), None);
754
755        state.clear_previous_response_chain_for("openai", "gpt-5.6");
756
757        assert_eq!(state.previous_response_id_for("openai", "gpt-5.6"), None);
758        assert_eq!(state.previous_response_chain_for("openai", "gpt-5.6"), None);
759        assert_eq!(state.previous_response_id_for("openai", "gpt-5.6-sol"), Some("resp_456".to_string()));
760        assert_eq!(
761            state
762                .previous_response_chain_for("openai", "gpt-5.6-sol")
763                .map(|chain| chain.messages.as_slice()),
764            Some(messages_54.as_slice())
765        );
766
767        state.clear_previous_response_chain();
768        assert_eq!(state.previous_response_id_for("openai", "gpt-5.6-sol"), None);
769        assert_eq!(state.previous_response_chain_for("openai", "gpt-5.6-sol"), None);
770    }
771
772    #[test]
773    fn shared_previous_response_chain_reuses_history_arc() {
774        let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
775        let messages = Arc::new(vec![Message::user("hello".to_string())]);
776
777        state.set_previous_response_chain_shared("openai", "gpt-5.6-sol", Some("resp_123"), Arc::clone(&messages));
778
779        let stored = &state
780            .previous_response_chain_for("openai", "gpt-5.6-sol")
781            .expect("continuation state")
782            .messages;
783        assert!(Arc::ptr_eq(&messages, stored));
784    }
785
786    #[test]
787    fn register_tool_loop_tracks_current_and_max_streak() {
788        let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
789
790        assert_eq!(state.register_tool_loop(), 1);
791        assert_eq!(state.register_tool_loop(), 2);
792        assert_eq!(state.consecutive_tool_loops, 2);
793        assert_eq!(state.max_tool_loop_streak, 2);
794
795        state.reset_tool_loop_guard();
796        assert_eq!(state.register_tool_loop(), 1);
797        assert_eq!(state.max_tool_loop_streak, 2);
798    }
799
800    #[test]
801    fn push_tool_error_preserves_structured_json_for_gemini() {
802        let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
803        let payload = serde_json::json!({
804            "error": {
805                "tool_name": "read_file",
806                "message": "missing file",
807                "category": "ResourceNotFound"
808            }
809        });
810
811        state.push_tool_error("call_1".to_string(), "read_file", &payload, true);
812
813        match &state.conversation[0].parts[0] {
814            Part::FunctionResponse { function_response, .. } => {
815                assert_eq!(function_response.response["error"]["message"], "missing file");
816            }
817            other => panic!("expected function response, got {other:?}"),
818        }
819        let expected_serialized = serde_json::to_string(&payload).unwrap();
820        assert_eq!(state.messages[0], Message::tool_response("call_1".to_string(), expected_serialized));
821    }
822
823    #[test]
824    fn harness_notices_are_tagged_synthetic_while_user_messages_are_not() {
825        let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
826        state.add_user_message("fix the flaky test".to_string());
827        state.add_synthetic_user_message("It looks like you're repeating the same response.".to_string());
828        state.add_user_message_with_intent("steer: stop after this".to_string(), Some("intent-1".to_string()));
829
830        let sources: Vec<Option<&str>> = state
831            .messages
832            .iter()
833            .map(|message| message.metadata.as_ref().and_then(|metadata| metadata.source()))
834            .collect();
835        assert_eq!(sources, vec![Some("user_input"), Some("synthetic"), Some("user_input")]);
836        assert!(
837            state.messages[1]
838                .metadata
839                .as_ref()
840                .is_some_and(vtcode_commons::message_metadata::MessageMetadata::is_synthetic)
841        );
842        // Tags survive archive round-trips so reverse history can filter them.
843        let archived: Vec<crate::utils::session_archive::SessionMessage> =
844            state.messages.iter().map(Into::into).collect();
845        assert!(
846            archived[1]
847                .metadata
848                .as_deref()
849                .is_some_and(vtcode_commons::message_metadata::MessageMetadata::is_synthetic)
850        );
851        assert!(archived[0].metadata.as_deref().is_some_and(|m| !m.is_synthetic()));
852    }
853
854    #[test]
855    fn cached_total_tokens_matches_direct_computation() {
856        let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
857
858        // Add messages through the standard push methods
859        state.add_user_message("Hello, how are you?".to_string());
860        state.push_tool_result(
861            "call_1".to_string(),
862            "read_file",
863            &serde_json::json!({"content": "test file content"}),
864            false,
865        );
866        state.push_tool_error(
867            "call_2".to_string(),
868            "write_file",
869            &serde_json::json!({"error": "permission denied"}),
870            false,
871        );
872
873        // Cached value should match direct computation
874        let direct = state.messages.iter().map(|m| m.estimate_tokens()).sum::<usize>();
875        assert_eq!(state.total_tokens(), direct);
876        assert!(state.total_tokens() > 0);
877    }
878
879    #[test]
880    fn reconcile_token_count_resyncs_after_external_mutation() {
881        let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
882        state.add_user_message("test message".to_string());
883        let before = state.total_tokens();
884
885        // Simulate external mutation (bypassing push methods)
886        state.messages_mut().push(Message::assistant("extra response".to_string()));
887        assert_ne!(state.total_tokens(), before + Message::assistant("extra response".to_string()).estimate_tokens());
888
889        // Reconcile should fix it
890        state.reconcile_token_count();
891        let expected = state.messages.iter().map(|m| m.estimate_tokens()).sum::<usize>();
892        assert_eq!(state.total_tokens(), expected);
893    }
894
895    #[test]
896    fn clear_conversation_history_resets_all_state() {
897        let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
898        state.messages_mut().push(Message::user("hello".to_string()));
899        state.messages_mut().push(Message::assistant("hi".to_string()));
900        state.conversation.push(crate::llm::providers::gemini::wire::Content {
901            role: "user".to_string(),
902            parts: vec![Part::Text { text: "hello".to_string(), thought_signature: None }],
903        });
904        state.reconcile_token_count();
905        state.last_processed_message_idx = 2;
906        state.progress_hashes.push_back(123);
907        state.stagnant_turns = 3;
908        state.set_previous_response_chain("openai", "gpt-5", Some("resp_1"), vec![]);
909
910        assert!(!state.messages.is_empty());
911        assert!(!state.conversation.is_empty());
912        assert!(state.total_tokens() > 0);
913
914        state.clear_conversation_history();
915
916        assert!(state.messages.is_empty());
917        assert!(state.conversation.is_empty());
918        assert_eq!(state.total_tokens(), 0);
919        assert_eq!(state.last_processed_message_idx, 0);
920        assert!(state.progress_hashes.is_empty());
921        assert_eq!(state.stagnant_turns, 0);
922        assert!(state.previous_response_chains.is_empty());
923    }
924
925    #[test]
926    fn push_warning_skips_exact_duplicates() {
927        let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
928        state.push_warning("rate limited");
929        state.push_warning("rate limited");
930        state.push_warning("rate limited");
931        assert_eq!(state.warnings.len(), 1);
932        assert_eq!(state.warnings[0], "rate limited");
933    }
934
935    #[test]
936    fn push_warning_retains_distinct_warnings() {
937        let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
938        state.push_warning("first warning");
939        state.push_warning("second warning");
940        state.push_warning("third warning");
941        assert_eq!(state.warnings.len(), 3);
942        assert_eq!(state.warnings[0], "first warning");
943        assert_eq!(state.warnings[1], "second warning");
944        assert_eq!(state.warnings[2], "third warning");
945    }
946
947    #[test]
948    fn push_warning_inserts_elision_marker_at_cap() {
949        let mut state = AgentSessionState::new("session".to_string(), 4, 4, 16_000);
950        // Fill up to the cap with unique warnings.
951        for i in 0..super::MAX_SESSION_WARNINGS {
952            state.push_warning(format!("warning {i}"));
953        }
954        assert_eq!(state.warnings.len(), super::MAX_SESSION_WARNINGS);
955        assert!(!state.warnings.iter().any(|w| w == super::WARNINGS_ELIDED_MARKER));
956
957        // Next unique warning triggers the marker exactly once.
958        state.push_warning("overflow A");
959        assert_eq!(state.warnings.len(), super::MAX_SESSION_WARNINGS + 1);
960        assert_eq!(state.warnings.last().unwrap(), super::WARNINGS_ELIDED_MARKER);
961
962        // Further unique warnings are silently dropped — marker stays as the
963        // last entry and the count does not grow.
964        state.push_warning("overflow B");
965        state.push_warning("overflow C");
966        assert_eq!(state.warnings.len(), super::MAX_SESSION_WARNINGS + 1);
967        assert_eq!(state.warnings.last().unwrap(), super::WARNINGS_ELIDED_MARKER);
968        // The overflow warnings themselves were not stored.
969        assert!(!state.warnings.iter().any(|w| w == "overflow A"));
970        assert!(!state.warnings.iter().any(|w| w == "overflow B"));
971    }
972}