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