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