1use 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
27pub struct AgentSessionState {
30 pub session_id: String,
32
33 pub conversation: Vec<Content>,
35
36 pub messages: Arc<Vec<Message>>,
42
43 pub schema_version: SchemaVersion,
45
46 pub stats: SessionStats,
48 pub auto_compact_suppressed: u8,
52
53 pub constraints: SessionConstraints,
55
56 pub outcome: TaskOutcome,
58 pub stop_reason: Option<String>,
60 pub total_cost_usd: Option<f64>,
62
63 pub is_completed: bool,
65
66 pub current_stage: Option<String>,
68
69 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 pub consecutive_escalations: u32,
81 pub progress_hashes: VecDeque<u64>,
84 pub stagnant_turns: usize,
86 pub last_processed_message_idx: usize,
87 pub previous_response_chains: ResponsesContinuationStore,
89 pub error_recovery: Arc<Mutex<ErrorRecoveryState>>,
91 pub pending_actions: PendingActions,
93
94 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 pub turn_tool_observations: Vec<ToolExecutionObservation>,
102 cached_total_tokens: usize,
105
106 request_gap: RequestGapTracker,
111
112 last_reasoning_effort: Option<crate::config::types::ReasoningEffortLevel>,
115 last_model: Option<String>,
120}
121
122#[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 pub provider_name: String,
134 pub prompt_cache_health: super::cache_health::PromptCacheHealthMonitor,
138}
139
140impl SessionStats {
141 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#[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 pub fn note_request_sent(&mut self) {
205 self.request_gap.note_request_sent();
206 }
207
208 pub fn cache_gap_exceeds(&self, threshold: Duration) -> Option<Duration> {
214 self.request_gap.cache_gap_exceeds(threshold)
215 }
216
217 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 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 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 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 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 #[inline]
320 pub fn messages_mut(&mut self) -> &mut Vec<Message> {
321 Arc::make_mut(&mut self.messages)
322 }
323
324 pub fn add_user_message(&mut self, text: String) {
326 self.add_user_message_with_intent(text, None);
327 }
328
329 pub fn add_synthetic_user_message(&mut self, text: String) {
335 self.add_synthetic_user_message_with_intent(text, None);
336 }
337
338 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 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 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 const PROGRESS_STAGNATION_THRESHOLD: usize = 4;
380
381 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 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 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 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 #[inline]
446 pub fn total_tokens(&self) -> usize {
447 self.cached_total_tokens
448 }
449
450 pub fn reconcile_token_count(&mut self) {
454 self.cached_total_tokens = self.messages.iter().map(|m| m.estimate_tokens()).sum();
455 }
456
457 #[inline]
460 pub fn adjust_token_count(&mut self, delta: isize) {
461 if delta >= 0 {
462 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 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 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 pub fn normalize(&mut self) {
499 crate::core::agent::state::normalize_history(self.messages_mut());
500 self.reconcile_token_count();
501 }
502
503 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 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 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 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 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 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
636const MAX_SESSION_WARNINGS: usize = 200;
640const WARNINGS_ELIDED_MARKER: &str = "[Additional unique warnings elided — session warning cap reached]";
641
642#[cfg(test)]
643mod tests;