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;