| 1 | //! Session state management for the core engine. |
| 2 | //! |
| 3 | //! Tracks conversation history, token usage, and session metadata. |
| 4 | |
| 5 | use crate::project_context::{PinnedProjectInstructions, ProjectContext}; |
| 6 | |
| 7 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 8 | pub enum MessageAuthorship { |
| 9 | Person, |
| 10 | ApprovedPlan, |
| 11 | #[default] |
| 12 | NotPerson, |
| 13 | } |
| 14 | |
| 15 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 16 | pub struct RecordedIntentMessage { |
| 17 | pub authorship: MessageAuthorship, |
| 18 | pub text: String, |
| 19 | pub message_index: Option<usize>, |
| 20 | } |
| 21 | use codewhale_core::prefix_cache::PrefixStabilityManager; |
| 22 | use codewhale_execpolicy::ApprovalMode; |
| 23 | use codewhale_models::{Message, SystemPrompt, Usage}; |
| 24 | use codewhale_runtime::prompt_zones::{AppendLog, FrozenPrefix}; |
| 25 | use codewhale_runtime::working_set::WorkingSet; |
| 26 | use std::collections::{HashMap, HashSet, VecDeque}; |
| 27 | use std::path::PathBuf; |
| 28 | |
| 29 | /// Soft target for deferred schemas a conversation keeps in its active toolbox. |
| 30 | /// Eviction is disabled by default so the active tool prefix stays append-only |
| 31 | /// for provider prompt caches up to twice this target; callers that opt into |
| 32 | /// eviction via `with_eviction(true)` evict MCP tools before first-party tools |
| 33 | /// while never evicting tools used in the current or previous turn. The eager |
| 34 | /// catalog head is not counted here. |
| 35 | pub const TOOL_ACTIVATION_CACHE_MAX_NAMES: usize = 16; |
| 36 | /// Soft target for added provider-wire schema bytes, under the same append-only |
| 37 | /// default and opt-in eviction rule as the name bound. Unknown adapter |
| 38 | /// measurements remain unknown. |
| 39 | pub const TOOL_ACTIVATION_CACHE_MAX_SCHEMA_BYTES: usize = 32 * 1024; |
| 40 | const TOOL_ACTIVATION_CACHE_CEILING_FACTOR: usize = 2; |
| 41 | |
| 42 | /// Bounded, process-local conversation cache for tools activated by |
| 43 | /// `tool_search`, a program's `tools.load`, or a result that needs them. |
| 44 | /// |
| 45 | /// Only names are retained. Every turn revalidates them against the currently |
| 46 | /// filtered catalog, so a disconnected MCP server, changed allow/deny rule, or |
| 47 | /// mode switch cannot resurrect a tool from an older authority posture. |
| 48 | #[derive(Debug, Clone, Default)] |
| 49 | pub struct ToolActivationCache { |
| 50 | /// Least-recently used at the front, most-recently used at the back. |
| 51 | names: VecDeque<String>, |
| 52 | last_use: HashMap<String, u64>, |
| 53 | uses: u64, |
| 54 | current_turn_floor: u64, |
| 55 | previous_turn_floor: u64, |
| 56 | eviction_enabled: bool, |
| 57 | } |
| 58 | |
| 59 | #[derive(Debug, Clone, Default, Eq, PartialEq)] |
| 60 | pub struct ToolActivationDelta { |
| 61 | pub admitted: Vec<String>, |
| 62 | pub evicted: Vec<String>, |
| 63 | pub rejected: Vec<String>, |
| 64 | pub held: Vec<String>, |
| 65 | pub schema_bytes: Option<usize>, |
| 66 | pub exceeds_soft_target: bool, |
| 67 | } |
| 68 | |
| 69 | #[derive(Debug, Clone, Default)] |
| 70 | pub struct ToolActivationMeasurement { |
| 71 | pub schema_bytes: Option<usize>, |
| 72 | pub unavailable: Vec<String>, |
| 73 | } |
| 74 | |
| 75 | pub type ToolActivationMeasurer<'a> = |
| 76 | dyn FnMut(&[String]) -> Result<ToolActivationMeasurement, crate::tools::spec::ToolError> + 'a; |
| 77 | |
| 78 | impl ToolActivationCache { |
| 79 | #[must_use] |
| 80 | pub fn with_eviction(mut self, enabled: bool) -> Self { |
| 81 | self.eviction_enabled = enabled; |
| 82 | self |
| 83 | } |
| 84 | |
| 85 | #[must_use] |
| 86 | pub fn eviction_enabled(&self) -> bool { |
| 87 | self.eviction_enabled |
| 88 | } |
| 89 | |
| 90 | /// Forget every deferred tool activated by the current conversation. |
| 91 | /// |
| 92 | /// `Op::SyncSession` calls this before installing another conversation's |
| 93 | /// identity, history, and workspace. The cache is intentionally |
| 94 | /// process-local, but it must still be conversation-local. |
| 95 | pub fn clear(&mut self) { |
| 96 | *self = Self { |
| 97 | eviction_enabled: self.eviction_enabled, |
| 98 | ..Self::default() |
| 99 | }; |
| 100 | } |
| 101 | |
| 102 | pub fn begin_turn(&mut self) { |
| 103 | self.previous_turn_floor = self.current_turn_floor; |
| 104 | self.current_turn_floor = self.uses; |
| 105 | } |
| 106 | |
| 107 | pub fn record_use(&mut self, name: &str) -> bool { |
| 108 | let Some(index) = self.names.iter().position(|cached| cached == name) else { |
| 109 | return false; |
| 110 | }; |
| 111 | if let Some(name) = self.names.remove(index) { |
| 112 | self.uses += 1; |
| 113 | self.last_use.insert(name.clone(), self.uses); |
| 114 | self.names.push_back(name); |
| 115 | } |
| 116 | true |
| 117 | } |
| 118 | |
| 119 | fn pinned(&self, name: &str) -> bool { |
| 120 | !self.eviction_enabled |
| 121 | || self |
| 122 | .last_use |
| 123 | .get(name) |
| 124 | .is_some_and(|used| *used > self.previous_turn_floor) |
| 125 | } |
| 126 | |
| 127 | fn catalog_tool<'a>( |
| 128 | catalog: &'a [codewhale_models::Tool], |
| 129 | name: &str, |
| 130 | ) -> Option<&'a codewhale_models::Tool> { |
| 131 | catalog |
| 132 | .iter() |
| 133 | .find(|tool| tool.name == name && tool.defer_loading.unwrap_or(false)) |
| 134 | } |
| 135 | |
| 136 | #[cfg(any(test, feature = "test-support"))] |
| 137 | fn serialized_bytes(tool: &codewhale_models::Tool) -> usize { |
| 138 | serde_json::to_vec(tool).map_or(usize::MAX, |bytes| bytes.len()) |
| 139 | } |
| 140 | |
| 141 | #[cfg(test)] |
| 142 | fn total_serialized_bytes(&self, catalog: &[codewhale_models::Tool]) -> usize { |
| 143 | self.names |
| 144 | .iter() |
| 145 | .filter_map(|name| Self::catalog_tool(catalog, name)) |
| 146 | .map(Self::serialized_bytes) |
| 147 | .fold(0usize, usize::saturating_add) |
| 148 | } |
| 149 | |
| 150 | fn exceeds_budget( |
| 151 | names: &[String], |
| 152 | measure: &mut ToolActivationMeasurer<'_>, |
| 153 | ) -> Result<bool, crate::tools::spec::ToolError> { |
| 154 | Self::exceeds_targets(names, 1, measure) |
| 155 | } |
| 156 | |
| 157 | fn exceeds_targets( |
| 158 | names: &[String], |
| 159 | factor: usize, |
| 160 | measure: &mut ToolActivationMeasurer<'_>, |
| 161 | ) -> Result<bool, crate::tools::spec::ToolError> { |
| 162 | let measured = measure(names)?; |
| 163 | Ok(names.len() > factor * TOOL_ACTIVATION_CACHE_MAX_NAMES |
| 164 | || measured |
| 165 | .schema_bytes |
| 166 | .is_some_and(|bytes| bytes > factor * TOOL_ACTIVATION_CACHE_MAX_SCHEMA_BYTES) |
| 167 | || !measured.unavailable.is_empty()) |
| 168 | } |
| 169 | |
| 170 | fn eviction_candidate(&self, keep: &[String]) -> Option<usize> { |
| 171 | self.names |
| 172 | .iter() |
| 173 | .enumerate() |
| 174 | .filter(|&(_, name)| !keep.contains(name) && !self.pinned(name)) |
| 175 | .min_by_key(|&(index, name)| { |
| 176 | ( |
| 177 | !crate::mcp::McpPool::is_mcp_tool(name), |
| 178 | self.last_use.get(name).copied(), |
| 179 | index, |
| 180 | ) |
| 181 | }) |
| 182 | .map(|(index, _)| index) |
| 183 | } |
| 184 | |
| 185 | pub fn revalidate_measured( |
| 186 | &mut self, |
| 187 | catalog: &[codewhale_models::Tool], |
| 188 | measure: &mut ToolActivationMeasurer<'_>, |
| 189 | ) -> Result<Vec<String>, crate::tools::spec::ToolError> { |
| 190 | let mut next = self.clone(); |
| 191 | let mut evicted = Vec::new(); |
| 192 | for name in &self.names { |
| 193 | let keep = if Self::catalog_tool(catalog, name).is_some() { |
| 194 | !Self::exceeds_budget(std::slice::from_ref(name), measure)? |
| 195 | } else { |
| 196 | false |
| 197 | }; |
| 198 | if !keep { |
| 199 | next.names.retain(|cached| cached != name); |
| 200 | next.last_use.remove(name); |
| 201 | evicted.push(name.clone()); |
| 202 | } |
| 203 | } |
| 204 | *self = next; |
| 205 | Ok(evicted) |
| 206 | } |
| 207 | |
| 208 | pub fn remove_names(&mut self, removed: &std::collections::HashSet<String>) { |
| 209 | if removed.is_empty() { |
| 210 | return; |
| 211 | } |
| 212 | self.names.retain(|name| !removed.contains(name)); |
| 213 | self.last_use.retain(|name, _| !removed.contains(name)); |
| 214 | } |
| 215 | |
| 216 | #[cfg(any(test, feature = "test-support"))] |
| 217 | pub fn test_measure( |
| 218 | catalog: &[codewhale_models::Tool], |
| 219 | names: &[String], |
| 220 | ) -> Result<ToolActivationMeasurement, crate::tools::spec::ToolError> { |
| 221 | Ok(ToolActivationMeasurement { |
| 222 | schema_bytes: Some( |
| 223 | names |
| 224 | .iter() |
| 225 | .filter_map(|name| Self::catalog_tool(catalog, name)) |
| 226 | .map(Self::serialized_bytes) |
| 227 | .fold(0usize, usize::saturating_add), |
| 228 | ), |
| 229 | unavailable: names |
| 230 | .iter() |
| 231 | .filter(|name| Self::catalog_tool(catalog, name).is_none()) |
| 232 | .cloned() |
| 233 | .collect(), |
| 234 | }) |
| 235 | } |
| 236 | |
| 237 | #[cfg(any(test, feature = "test-support"))] |
| 238 | pub fn revalidate(&mut self, catalog: &[codewhale_models::Tool]) -> Vec<String> { |
| 239 | self.revalidate_measured(catalog, &mut |names| Self::test_measure(catalog, names)) |
| 240 | .unwrap() |
| 241 | } |
| 242 | |
| 243 | #[cfg(any(test, feature = "test-support"))] |
| 244 | pub fn activate( |
| 245 | &mut self, |
| 246 | catalog: &[codewhale_models::Tool], |
| 247 | requested: &[String], |
| 248 | ) -> ToolActivationDelta { |
| 249 | self.activate_measured(catalog, requested, &mut |names| { |
| 250 | Self::test_measure(catalog, names) |
| 251 | }) |
| 252 | .unwrap() |
| 253 | } |
| 254 | |
| 255 | /// Admit requested deferred tools in search-result priority order. An |
| 256 | /// oversized schema is rejected. By default eviction is disabled so |
| 257 | /// previously admitted tools remain pinned (append-only) to preserve |
| 258 | /// provider prompt caches up to twice the soft targets. When eviction is |
| 259 | /// opted in via `with_eviction(true)`, room comes from MCP tools before |
| 260 | /// first-party tools, and within each group from entries never used |
| 261 | /// (oldest admission first), then from the least recently used; tools |
| 262 | /// used in the current or previous turn are never evicted. A match past |
| 263 | /// the 2x ceiling, or past the soft targets of its own batch, is held; |
| 264 | /// the best match is always admitted. The batch is stored best-match-last. |
| 265 | pub fn activate_measured( |
| 266 | &mut self, |
| 267 | catalog: &[codewhale_models::Tool], |
| 268 | requested: &[String], |
| 269 | measure: &mut ToolActivationMeasurer<'_>, |
| 270 | ) -> Result<ToolActivationDelta, crate::tools::spec::ToolError> { |
| 271 | let mut next = self.clone(); |
| 272 | let delta = next.activate_inner(catalog, requested, measure)?; |
| 273 | *self = next; |
| 274 | Ok(delta) |
| 275 | } |
| 276 | |
| 277 | fn activate_inner( |
| 278 | &mut self, |
| 279 | catalog: &[codewhale_models::Tool], |
| 280 | requested: &[String], |
| 281 | measure: &mut ToolActivationMeasurer<'_>, |
| 282 | ) -> Result<ToolActivationDelta, crate::tools::spec::ToolError> { |
| 283 | let mut delta = ToolActivationDelta { |
| 284 | evicted: self.revalidate_measured(catalog, measure)?, |
| 285 | ..ToolActivationDelta::default() |
| 286 | }; |
| 287 | let mut seen = HashSet::new(); |
| 288 | let mut batch: Vec<String> = Vec::new(); |
| 289 | for name in requested.iter().filter(|name| seen.insert(name.as_str())) { |
| 290 | let fits_alone = Self::catalog_tool(catalog, name).is_some() |
| 291 | && !Self::exceeds_budget(std::slice::from_ref(name), measure)?; |
| 292 | if !fits_alone { |
| 293 | delta.rejected.push(name.clone()); |
| 294 | continue; |
| 295 | } |
| 296 | if !batch.is_empty() { |
| 297 | let mut candidate = batch.clone(); |
| 298 | candidate.push(name.clone()); |
| 299 | let mut protected = self |
| 300 | .names |
| 301 | .iter() |
| 302 | .filter(|cached| !candidate.contains(*cached) && self.pinned(cached)) |
| 303 | .cloned() |
| 304 | .collect::<Vec<_>>(); |
| 305 | protected.extend(candidate.iter().cloned()); |
| 306 | if Self::exceeds_budget(&candidate, measure)? |
| 307 | || Self::exceeds_targets( |
| 308 | &protected, |
| 309 | TOOL_ACTIVATION_CACHE_CEILING_FACTOR, |
| 310 | measure, |
| 311 | )? |
| 312 | { |
| 313 | delta.held.push(name.clone()); |
| 314 | continue; |
| 315 | } |
| 316 | } |
| 317 | batch.push(name.clone()); |
| 318 | if self.names.contains(name) { |
| 319 | continue; |
| 320 | } |
| 321 | self.names.push_back(name.clone()); |
| 322 | while Self::exceeds_budget(&self.names.iter().cloned().collect::<Vec<_>>(), measure)? { |
| 323 | let Some(index) = self.eviction_candidate(&batch) else { |
| 324 | break; |
| 325 | }; |
| 326 | if let Some(evicted) = self.names.remove(index) { |
| 327 | self.last_use.remove(&evicted); |
| 328 | delta.evicted.push(evicted); |
| 329 | } |
| 330 | } |
| 331 | } |
| 332 | for name in batch.iter().rev() { |
| 333 | if let Some(index) = self.names.iter().position(|cached| cached == name) |
| 334 | && let Some(name) = self.names.remove(index) |
| 335 | { |
| 336 | self.names.push_back(name); |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | let retained = self.names.iter().collect::<HashSet<_>>(); |
| 341 | delta.admitted = requested |
| 342 | .iter() |
| 343 | .filter(|name| retained.contains(name)) |
| 344 | .cloned() |
| 345 | .collect(); |
| 346 | delta.evicted.retain(|name| !retained.contains(name)); |
| 347 | delta.held.retain(|name| !retained.contains(name)); |
| 348 | delta.evicted.sort(); |
| 349 | delta.evicted.dedup(); |
| 350 | delta.rejected.sort(); |
| 351 | delta.rejected.dedup(); |
| 352 | let names = self.names.iter().cloned().collect::<Vec<_>>(); |
| 353 | let measured = measure(&names)?; |
| 354 | if !measured.unavailable.is_empty() { |
| 355 | return Err(crate::tools::spec::ToolError::not_available( |
| 356 | "Provider omitted an active deferred schema; toolbox admission was not changed", |
| 357 | )); |
| 358 | } |
| 359 | delta.schema_bytes = measured.schema_bytes; |
| 360 | delta.exceeds_soft_target = names.len() > TOOL_ACTIVATION_CACHE_MAX_NAMES |
| 361 | || measured |
| 362 | .schema_bytes |
| 363 | .is_some_and(|bytes| bytes > TOOL_ACTIVATION_CACHE_MAX_SCHEMA_BYTES); |
| 364 | Ok(delta) |
| 365 | } |
| 366 | |
| 367 | pub fn names(&self) -> impl Iterator<Item = &str> { |
| 368 | self.names.iter().map(String::as_str) |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | /// Session state for the engine. |
| 373 | #[derive(Debug, Clone)] |
| 374 | pub struct Session { |
| 375 | pub snapshot_source: Option<crate::core::ops::SessionSnapshotSource>, |
| 376 | /// Model being used |
| 377 | pub model: String, |
| 378 | |
| 379 | /// Reasoning-effort tier for DeepSeek thinking mode: |
| 380 | /// `"off" | "low" | "medium" | "high" | "max"`. `None` lets the provider |
| 381 | /// apply its own defaults. |
| 382 | pub reasoning_effort: Option<String>, |
| 383 | /// Whether the user selected automatic reasoning effort. |
| 384 | pub reasoning_effort_auto: bool, |
| 385 | |
| 386 | /// Whether the user selected automatic model routing. |
| 387 | pub auto_model: bool, |
| 388 | |
| 389 | /// Workspace directory |
| 390 | pub workspace: PathBuf, |
| 391 | |
| 392 | /// System prompt (optional) |
| 393 | pub system_prompt: Option<SystemPrompt>, |
| 394 | pub instruction_assembly: Option<std::sync::Arc<crate::project_context::InstructionAssembly>>, |
| 395 | /// True when `system_prompt` is a persisted/runtime-supplied prefix that |
| 396 | /// should not be replaced by mode/context refreshes. |
| 397 | pub system_prompt_override: bool, |
| 398 | /// Hash of the last assembled stable system prompt. Used to avoid |
| 399 | /// replacing `system_prompt` when unchanged. |
| 400 | pub last_system_prompt_hash: Option<u64>, |
| 401 | /// Reason the pinned prefix will move on the next model request, set by |
| 402 | /// an explicit header-change op (`/model`, mode change, goal edit, session |
| 403 | /// sync) when it actually alters the system-prompt bytes. Consumed by the |
| 404 | /// turn loop's prefix check so a declared change re-pins under a logged |
| 405 | /// reason while an undeclared mid-loop change is reported as drift and the |
| 406 | /// pin holds. `None` means "no declared change since the last request". |
| 407 | pub pending_prefix_change_reason: Option<String>, |
| 408 | /// The explicit prompt inputs (model, mode, goal, route, translation, |
| 409 | /// verbosity) the pinned system prompt was composed from. At each new user |
| 410 | /// turn the engine recomposes: if these inputs are unchanged but the |
| 411 | /// composed bytes differ, that is workspace/instruction/skills/memory |
| 412 | /// drift and is delivered to the model as a `<context_update>` message, |
| 413 | /// never by moving the pinned header. |
| 414 | pub pinned_prompt_context: Option<crate::core::engine::NextTurnPromptContext>, |
| 415 | /// Flat text of the session context the model has last been shown, either |
| 416 | /// as the pinned header or through `<context_update>` messages. New-turn |
| 417 | /// deltas are computed against this so an update is delivered exactly once. |
| 418 | pub context_update_baseline: Option<String>, |
| 419 | /// Host-persistence copy of the history checkpoint generated by context |
| 420 | /// compaction. This is never part of the standing system prompt. |
| 421 | pub compaction_summary_prompt: Option<SystemPrompt>, |
| 422 | |
| 423 | /// Conversation history (API format), backed by AppendLog (#2264). |
| 424 | pub messages: AppendLog, |
| 425 | |
| 426 | /// Total tokens used in this session |
| 427 | pub total_usage: SessionUsage, |
| 428 | |
| 429 | /// Whether shell execution is allowed |
| 430 | pub allow_shell: bool, |
| 431 | |
| 432 | /// Whether to trust paths outside workspace |
| 433 | pub trust_mode: bool, |
| 434 | |
| 435 | /// Whether the current session should auto-approve tool safety checks. |
| 436 | pub auto_approve: bool, |
| 437 | |
| 438 | /// Live UI approval policy used to steer the system prompt. |
| 439 | pub approval_mode: ApprovalMode, |
| 440 | |
| 441 | /// MCP config path |
| 442 | pub mcp_config_path: PathBuf, |
| 443 | |
| 444 | /// Session ID (for tracking) |
| 445 | pub id: String, |
| 446 | |
| 447 | /// Project context loaded from AGENTS.md, etc. |
| 448 | pub project_context: Option<ProjectContext>, |
| 449 | pub pinned_project_instructions: PinnedProjectInstructions, |
| 450 | pub recorded_intents: Vec<RecordedIntentMessage>, |
| 451 | |
| 452 | /// Repo-aware working set for context management. |
| 453 | pub working_set: WorkingSet, |
| 454 | |
| 455 | /// Prefix-cache stability monitor (inspired by Reasonix's Pillar 1). |
| 456 | /// Tracks the immutable prefix fingerprint and detects drift across turns. |
| 457 | /// Set during engine construction; None until the first system prompt assembly. |
| 458 | pub prefix_stability: Option<PrefixStabilityManager>, |
| 459 | |
| 460 | /// Three-zone immutable prefix baseline (#2264). Frozen on the first |
| 461 | /// request of the session; verified against the current system+tool |
| 462 | /// state before every subsequent request. None until the first turn. |
| 463 | pub frozen_prefix: Option<FrozenPrefix>, |
| 464 | |
| 465 | /// Deferred tools explicitly discovered during this conversation. Names |
| 466 | /// are revalidated against the live catalog before each request. |
| 467 | pub(super) tool_activation_cache: ToolActivationCache, |
| 468 | |
| 469 | /// Monotonic counter bumped on every direct mutation of `messages`. |
| 470 | /// Consumed by the engine token-estimate cache |
| 471 | /// to memoize the per-turn token estimate without re-walking the message |
| 472 | /// list. Defaults to 0; bumped in [`Session::add_message`], |
| 473 | /// [`Session::replace_messages`], and at other mutation sites in |
| 474 | /// `core/engine.rs`. |
| 475 | pub messages_revision: u64, |
| 476 | |
| 477 | /// Provider-billed prompt tokens from the most recent parent-route |
| 478 | /// request that still describes the live message list. Survives turn |
| 479 | /// boundaries so the next send can compact on last-turn pressure |
| 480 | /// (#5577). Cleared when history is rewritten (compaction, restore). |
| 481 | pub latest_parent_input_tokens: Option<u32>, |
| 482 | |
| 483 | pub last_request_tools: Option<Vec<codewhale_models::Tool>>, |
| 484 | |
| 485 | pub agent_preset: Option<String>, |
| 486 | } |
| 487 | |
| 488 | /// Cumulative usage statistics for a session. |
| 489 | #[derive(Debug, Clone, Default)] |
| 490 | #[allow(clippy::struct_field_names)] |
| 491 | pub struct SessionUsage { |
| 492 | pub input_tokens: u64, |
| 493 | pub output_tokens: u64, |
| 494 | /// Cache creation (write) tokens. `None` when never observed by the API — |
| 495 | /// do NOT display as 0, which would be indistinguishable from "no writes". |
| 496 | pub cache_creation_input_tokens: Option<u64>, |
| 497 | /// Cache read (hit) tokens. `None` when never observed by the API — |
| 498 | /// do NOT display as 0, which would be indistinguishable from "no hits". |
| 499 | pub cache_read_input_tokens: Option<u64>, |
| 500 | } |
| 501 | |
| 502 | impl SessionUsage { |
| 503 | /// Add usage from a turn |
| 504 | pub fn add(&mut self, usage: &Usage) { |
| 505 | self.input_tokens += u64::from(usage.input_tokens); |
| 506 | self.output_tokens += u64::from(usage.output_tokens); |
| 507 | if let Some(tokens) = usage.prompt_cache_write_tokens { |
| 508 | self.cache_creation_input_tokens = |
| 509 | Some(self.cache_creation_input_tokens.unwrap_or(0) + u64::from(tokens)); |
| 510 | } |
| 511 | if let Some(tokens) = usage.prompt_cache_hit_tokens { |
| 512 | self.cache_read_input_tokens = |
| 513 | Some(self.cache_read_input_tokens.unwrap_or(0) + u64::from(tokens)); |
| 514 | } |
| 515 | } |
| 516 | } |
| 517 | |
| 518 | impl Session { |
| 519 | /// Create a new session |
| 520 | pub fn new( |
| 521 | model: String, |
| 522 | workspace: PathBuf, |
| 523 | allow_shell: bool, |
| 524 | trust_mode: bool, |
| 525 | mcp_config_path: PathBuf, |
| 526 | ) -> Self { |
| 527 | Self { |
| 528 | model, |
| 529 | reasoning_effort: None, |
| 530 | reasoning_effort_auto: false, |
| 531 | auto_model: false, |
| 532 | workspace, |
| 533 | system_prompt: None, |
| 534 | instruction_assembly: None, |
| 535 | system_prompt_override: false, |
| 536 | compaction_summary_prompt: None, |
| 537 | messages: AppendLog::new(), |
| 538 | total_usage: SessionUsage::default(), |
| 539 | allow_shell, |
| 540 | trust_mode, |
| 541 | auto_approve: false, |
| 542 | approval_mode: ApprovalMode::Suggest, |
| 543 | mcp_config_path, |
| 544 | snapshot_source: None, |
| 545 | id: uuid::Uuid::new_v4().to_string(), |
| 546 | project_context: None, |
| 547 | pinned_project_instructions: PinnedProjectInstructions::default(), |
| 548 | recorded_intents: Vec::new(), |
| 549 | last_system_prompt_hash: None, |
| 550 | pending_prefix_change_reason: None, |
| 551 | pinned_prompt_context: None, |
| 552 | context_update_baseline: None, |
| 553 | working_set: WorkingSet::default(), |
| 554 | prefix_stability: None, |
| 555 | frozen_prefix: None, |
| 556 | tool_activation_cache: ToolActivationCache::default(), |
| 557 | messages_revision: 0, |
| 558 | latest_parent_input_tokens: None, |
| 559 | last_request_tools: None, |
| 560 | agent_preset: None, |
| 561 | } |
| 562 | } |
| 563 | |
| 564 | /// Add a message to the conversation |
| 565 | pub fn add_message(&mut self, message: Message) { |
| 566 | self.messages.push(message); |
| 567 | self.messages_revision = self.messages_revision.saturating_add(1); |
| 568 | } |
| 569 | |
| 570 | /// Replace the entire message history. Used by session resume and |
| 571 | /// compaction. Bumps `messages_revision` exactly once even when the new |
| 572 | /// history has a different length, so downstream caches invalidate |
| 573 | /// atomically. |
| 574 | pub fn replace_messages(&mut self, messages: Vec<Message>) { |
| 575 | self.messages = messages.into(); |
| 576 | for intent in &mut self.recorded_intents { |
| 577 | intent.message_index = None; |
| 578 | } |
| 579 | self.messages_revision = self.messages_revision.saturating_add(1); |
| 580 | self.latest_parent_input_tokens = None; |
| 581 | } |
| 582 | |
| 583 | pub fn record_person_message(&mut self, text: impl Into<String>, message_index: Option<usize>) { |
| 584 | let text = text.into(); |
| 585 | if text.trim().is_empty() { |
| 586 | return; |
| 587 | } |
| 588 | self.recorded_intents.push(RecordedIntentMessage { |
| 589 | authorship: MessageAuthorship::Person, |
| 590 | text, |
| 591 | message_index, |
| 592 | }); |
| 593 | } |
| 594 | |
| 595 | pub fn record_approved_plan(&mut self, text: impl Into<String>, message_index: Option<usize>) { |
| 596 | let text = text.into(); |
| 597 | if text.trim().is_empty() { |
| 598 | return; |
| 599 | } |
| 600 | self.recorded_intents.push(RecordedIntentMessage { |
| 601 | authorship: MessageAuthorship::ApprovedPlan, |
| 602 | text, |
| 603 | message_index, |
| 604 | }); |
| 605 | } |
| 606 | |
| 607 | pub fn person_messages(&self) -> Vec<String> { |
| 608 | self.recorded_intents |
| 609 | .iter() |
| 610 | .filter(|intent| intent.authorship == MessageAuthorship::Person) |
| 611 | .map(|intent| intent.text.clone()) |
| 612 | .collect() |
| 613 | } |
| 614 | |
| 615 | pub fn approved_plan(&self) -> Option<&str> { |
| 616 | self.recorded_intents |
| 617 | .iter() |
| 618 | .rev() |
| 619 | .find(|intent| intent.authorship == MessageAuthorship::ApprovedPlan) |
| 620 | .map(|intent| intent.text.as_str()) |
| 621 | } |
| 622 | |
| 623 | pub fn truncate_intents_to(&mut self, message_len: usize) { |
| 624 | self.recorded_intents |
| 625 | .retain(|intent| intent.message_index.is_none_or(|index| index < message_len)); |
| 626 | } |
| 627 | |
| 628 | pub fn clear_recorded_intents(&mut self) { |
| 629 | self.recorded_intents.clear(); |
| 630 | } |
| 631 | |
| 632 | /// Bump `messages_revision` without otherwise mutating the message list. |
| 633 | /// Reserved for sites that mutate the message list in place (e.g. an |
| 634 | /// in-place rewrite of a content block). Most call sites do not need |
| 635 | /// this — prefer [`add_message`](Self::add_message) and |
| 636 | /// [`replace_messages`](Self::replace_messages). |
| 637 | pub fn bump_messages_revision(&mut self) { |
| 638 | self.messages_revision = self.messages_revision.saturating_add(1); |
| 639 | } |
| 640 | |
| 641 | /// Rebuild the working set from current messages (best effort). |
| 642 | pub fn rebuild_working_set(&mut self) { |
| 643 | self.working_set |
| 644 | .rebuild_from_messages(&self.messages, &self.workspace); |
| 645 | } |
| 646 | } |
| 647 | |
| 648 | #[cfg(test)] |
| 649 | mod tests { |
| 650 | use super::*; |
| 651 | use serde_json::json; |
| 652 | |
| 653 | fn deferred_tool(name: &str, description_bytes: usize) -> codewhale_models::Tool { |
| 654 | codewhale_models::Tool { |
| 655 | tool_type: None, |
| 656 | name: name.to_string(), |
| 657 | description: "x".repeat(description_bytes), |
| 658 | input_schema: json!({"type": "object", "properties": {}}), |
| 659 | allowed_callers: None, |
| 660 | defer_loading: Some(true), |
| 661 | input_examples: None, |
| 662 | strict: None, |
| 663 | cache_control: None, |
| 664 | } |
| 665 | } |
| 666 | |
| 667 | #[test] |
| 668 | fn session_usage_cache_starts_none() { |
| 669 | let usage = SessionUsage::default(); |
| 670 | assert!(usage.cache_creation_input_tokens.is_none()); |
| 671 | assert!(usage.cache_read_input_tokens.is_none()); |
| 672 | } |
| 673 | |
| 674 | #[test] |
| 675 | fn session_usage_cache_remains_none_when_api_omits_cache() { |
| 676 | let mut usage = SessionUsage::default(); |
| 677 | let api_usage = Usage { |
| 678 | input_tokens: 100, |
| 679 | output_tokens: 50, |
| 680 | prompt_cache_hit_tokens: None, |
| 681 | prompt_cache_miss_tokens: None, |
| 682 | prompt_cache_write_tokens: None, |
| 683 | reasoning_tokens: None, |
| 684 | reasoning_replay_tokens: None, |
| 685 | server_tool_use: None, |
| 686 | |
| 687 | input_audio_tokens: None, |
| 688 | output_audio_tokens: None, |
| 689 | |
| 690 | request_usages: Vec::new(), |
| 691 | safety_tokens: None, |
| 692 | }; |
| 693 | usage.add(&api_usage); |
| 694 | assert!(usage.cache_creation_input_tokens.is_none()); |
| 695 | assert!(usage.cache_read_input_tokens.is_none()); |
| 696 | } |
| 697 | |
| 698 | #[test] |
| 699 | fn session_usage_cache_accumulates_when_reported() { |
| 700 | let mut usage = SessionUsage::default(); |
| 701 | let api_usage = Usage { |
| 702 | input_tokens: 100, |
| 703 | output_tokens: 50, |
| 704 | prompt_cache_hit_tokens: Some(30), |
| 705 | prompt_cache_miss_tokens: Some(50), |
| 706 | prompt_cache_write_tokens: Some(20), |
| 707 | reasoning_tokens: None, |
| 708 | reasoning_replay_tokens: None, |
| 709 | server_tool_use: None, |
| 710 | |
| 711 | input_audio_tokens: None, |
| 712 | output_audio_tokens: None, |
| 713 | |
| 714 | request_usages: Vec::new(), |
| 715 | safety_tokens: None, |
| 716 | }; |
| 717 | usage.add(&api_usage); |
| 718 | assert_eq!(usage.cache_read_input_tokens, Some(30)); |
| 719 | assert_eq!(usage.cache_creation_input_tokens, Some(20)); |
| 720 | usage.add(&api_usage); |
| 721 | assert_eq!(usage.cache_read_input_tokens, Some(60)); |
| 722 | assert_eq!(usage.cache_creation_input_tokens, Some(40)); |
| 723 | } |
| 724 | |
| 725 | #[test] |
| 726 | fn session_usage_cache_preserves_explicit_zero() { |
| 727 | let mut usage = SessionUsage::default(); |
| 728 | let api_usage = Usage { |
| 729 | input_tokens: 100, |
| 730 | output_tokens: 50, |
| 731 | prompt_cache_hit_tokens: Some(0), // explicit zero from provider |
| 732 | prompt_cache_miss_tokens: Some(50), |
| 733 | prompt_cache_write_tokens: Some(1234), |
| 734 | reasoning_tokens: None, |
| 735 | reasoning_replay_tokens: None, |
| 736 | server_tool_use: None, |
| 737 | |
| 738 | input_audio_tokens: None, |
| 739 | output_audio_tokens: None, |
| 740 | |
| 741 | request_usages: Vec::new(), |
| 742 | safety_tokens: None, |
| 743 | }; |
| 744 | usage.add(&api_usage); |
| 745 | // 0 is a valid observed value, must NOT be converted to None |
| 746 | assert_eq!(usage.cache_read_input_tokens, Some(0)); |
| 747 | assert_eq!(usage.cache_creation_input_tokens, Some(1234)); |
| 748 | } |
| 749 | |
| 750 | #[test] |
| 751 | fn tool_activation_cache_retains_best_matches_on_count_overflow() { |
| 752 | let catalog = (0..TOOL_ACTIVATION_CACHE_MAX_NAMES + 2) |
| 753 | .map(|index| deferred_tool(&format!("tool_{index}"), 8)) |
| 754 | .collect::<Vec<_>>(); |
| 755 | let requested = catalog |
| 756 | .iter() |
| 757 | .map(|tool| tool.name.clone()) |
| 758 | .collect::<Vec<_>>(); |
| 759 | let mut cache = ToolActivationCache::default(); |
| 760 | let delta = cache.activate(&catalog, &requested); |
| 761 | |
| 762 | assert_eq!(cache.names().count(), TOOL_ACTIVATION_CACHE_MAX_NAMES); |
| 763 | let mut expected = requested[..TOOL_ACTIVATION_CACHE_MAX_NAMES].to_vec(); |
| 764 | expected.reverse(); |
| 765 | assert_eq!(cache.names().collect::<Vec<_>>(), expected); |
| 766 | assert_eq!(delta.admitted, requested[..TOOL_ACTIVATION_CACHE_MAX_NAMES]); |
| 767 | assert_eq!(delta.held, requested[TOOL_ACTIVATION_CACHE_MAX_NAMES..]); |
| 768 | } |
| 769 | |
| 770 | #[test] |
| 771 | fn best_match_survives_byte_overflow_eviction() { |
| 772 | let mut catalog = vec![deferred_tool( |
| 773 | "big_best", |
| 774 | TOOL_ACTIVATION_CACHE_MAX_SCHEMA_BYTES * 3 / 4, |
| 775 | )]; |
| 776 | for index in 0..4 { |
| 777 | catalog.push(deferred_tool( |
| 778 | &format!("small_{index}"), |
| 779 | TOOL_ACTIVATION_CACHE_MAX_SCHEMA_BYTES / 10, |
| 780 | )); |
| 781 | } |
| 782 | let requested = catalog |
| 783 | .iter() |
| 784 | .map(|tool| tool.name.clone()) |
| 785 | .collect::<Vec<_>>(); |
| 786 | // Isolate byte overflow: every schema fits alone and the name count |
| 787 | // fits, but the combined batch exceeds the byte limit. |
| 788 | assert!(catalog.iter().all(|tool| { |
| 789 | ToolActivationCache::serialized_bytes(tool) <= TOOL_ACTIVATION_CACHE_MAX_SCHEMA_BYTES |
| 790 | })); |
| 791 | assert!(requested.len() < TOOL_ACTIVATION_CACHE_MAX_NAMES); |
| 792 | assert!( |
| 793 | catalog |
| 794 | .iter() |
| 795 | .map(ToolActivationCache::serialized_bytes) |
| 796 | .sum::<usize>() |
| 797 | > TOOL_ACTIVATION_CACHE_MAX_SCHEMA_BYTES |
| 798 | ); |
| 799 | let mut cache = ToolActivationCache::default(); |
| 800 | let delta = cache.activate(&catalog, &requested); |
| 801 | |
| 802 | assert_eq!(delta.admitted.first().map(String::as_str), Some("big_best")); |
| 803 | assert!(cache.names().any(|name| name == "big_best")); |
| 804 | assert!(delta.admitted.len() < requested.len()); |
| 805 | assert_eq!(delta.admitted, requested[..delta.admitted.len()]); |
| 806 | assert!(!delta.held.is_empty()); |
| 807 | assert!(delta.rejected.is_empty()); |
| 808 | assert!(cache.total_serialized_bytes(&catalog) <= TOOL_ACTIVATION_CACHE_MAX_SCHEMA_BYTES); |
| 809 | } |
| 810 | |
| 811 | #[test] |
| 812 | fn duplicate_does_not_lower_first_match_priority() { |
| 813 | let catalog = (0..TOOL_ACTIVATION_CACHE_MAX_NAMES + 2) |
| 814 | .map(|index| deferred_tool(&format!("tool_{index}"), 8)) |
| 815 | .collect::<Vec<_>>(); |
| 816 | let mut requested = catalog |
| 817 | .iter() |
| 818 | .map(|tool| tool.name.clone()) |
| 819 | .collect::<Vec<_>>(); |
| 820 | requested.push("tool_0".to_string()); |
| 821 | let mut cache = ToolActivationCache::default(); |
| 822 | let delta = cache.activate(&catalog, &requested); |
| 823 | |
| 824 | assert_eq!(cache.names().count(), TOOL_ACTIVATION_CACHE_MAX_NAMES); |
| 825 | assert_eq!(cache.names().filter(|name| *name == "tool_0").count(), 1); |
| 826 | assert!(cache.names().any(|name| name == "tool_0")); |
| 827 | assert!(!cache.names().any(|name| { |
| 828 | catalog[TOOL_ACTIVATION_CACHE_MAX_NAMES..] |
| 829 | .iter() |
| 830 | .any(|held| held.name == name) |
| 831 | })); |
| 832 | // Admission reporting keeps the caller's order, including duplicates, |
| 833 | // while the cache itself retains each name only once. |
| 834 | let mut expected = requested[..TOOL_ACTIVATION_CACHE_MAX_NAMES].to_vec(); |
| 835 | expected.push("tool_0".to_string()); |
| 836 | assert_eq!(delta.admitted, expected); |
| 837 | } |
| 838 | |
| 839 | #[test] |
| 840 | fn touching_a_cached_tool_makes_it_most_recent() { |
| 841 | let max = TOOL_ACTIVATION_CACHE_MAX_NAMES; |
| 842 | let catalog = (0..=max) |
| 843 | .map(|index| deferred_tool(&format!("tool_{index}"), 8)) |
| 844 | .collect::<Vec<_>>(); |
| 845 | let first_batch = catalog[..max] |
| 846 | .iter() |
| 847 | .map(|tool| tool.name.clone()) |
| 848 | .collect::<Vec<_>>(); |
| 849 | let mut cache = ToolActivationCache::default().with_eviction(true); |
| 850 | cache.activate(&catalog, &first_batch); |
| 851 | // The initial batch puts its lowest-ranked match at the LRU front. |
| 852 | // A later touch must protect it from the following batch's eviction. |
| 853 | let lowest = format!("tool_{}", max - 1); |
| 854 | let next_lowest = format!("tool_{}", max - 2); |
| 855 | let newest = format!("tool_{max}"); |
| 856 | cache.activate(&catalog, std::slice::from_ref(&lowest)); |
| 857 | cache.activate(&catalog, std::slice::from_ref(&newest)); |
| 858 | |
| 859 | let names = cache.names().collect::<Vec<_>>(); |
| 860 | assert!(names.contains(&lowest.as_str())); |
| 861 | assert!(!names.contains(&next_lowest.as_str())); |
| 862 | assert_eq!(names.last().copied(), Some(newest.as_str())); |
| 863 | } |
| 864 | |
| 865 | #[test] |
| 866 | fn mcp_tools_evict_before_first_party_tools() { |
| 867 | let max = TOOL_ACTIVATION_CACHE_MAX_NAMES; |
| 868 | let mut catalog = vec![deferred_tool("Web", 8), deferred_tool("lsp", 8)]; |
| 869 | catalog.extend((0..max).map(|index| deferred_tool(&format!("mcp_github_{index}"), 8))); |
| 870 | let mut cache = ToolActivationCache::default().with_eviction(true); |
| 871 | cache.activate(&catalog, &["Web".to_string(), "lsp".to_string()]); |
| 872 | cache.begin_turn(); |
| 873 | cache.begin_turn(); |
| 874 | let mcp = catalog[2..] |
| 875 | .iter() |
| 876 | .map(|tool| tool.name.clone()) |
| 877 | .collect::<Vec<_>>(); |
| 878 | let first = cache.activate(&catalog, &mcp[..max - 2]); |
| 879 | assert!(first.evicted.is_empty()); |
| 880 | cache.begin_turn(); |
| 881 | cache.begin_turn(); |
| 882 | let delta = cache.activate(&catalog, &mcp[max - 2..]); |
| 883 | |
| 884 | let names = cache.names().collect::<Vec<_>>(); |
| 885 | assert!(names.contains(&"Web") && names.contains(&"lsp")); |
| 886 | assert_eq!(delta.evicted.len(), 2); |
| 887 | assert!(delta.evicted.iter().all(|name| name.starts_with("mcp_"))); |
| 888 | } |
| 889 | |
| 890 | #[test] |
| 891 | fn readmitted_tool_is_not_reported_evicted() { |
| 892 | let max = TOOL_ACTIVATION_CACHE_MAX_NAMES; |
| 893 | let catalog = (0..=max) |
| 894 | .map(|index| deferred_tool(&format!("tool_{index}"), 8)) |
| 895 | .collect::<Vec<_>>(); |
| 896 | let names = catalog |
| 897 | .iter() |
| 898 | .map(|tool| tool.name.clone()) |
| 899 | .collect::<Vec<_>>(); |
| 900 | let mut cache = ToolActivationCache::default().with_eviction(true); |
| 901 | cache.activate(&catalog, &names[..max]); |
| 902 | cache.begin_turn(); |
| 903 | cache.begin_turn(); |
| 904 | let requested = vec![names[max].clone(), names[max - 1].clone()]; |
| 905 | let delta = cache.activate(&catalog, &requested); |
| 906 | |
| 907 | let active = cache.names().collect::<Vec<_>>(); |
| 908 | assert!(active.contains(&names[max - 1].as_str())); |
| 909 | assert!( |
| 910 | delta |
| 911 | .evicted |
| 912 | .iter() |
| 913 | .all(|name| !active.contains(&name.as_str())) |
| 914 | ); |
| 915 | assert!(!delta.evicted.contains(&names[max - 1])); |
| 916 | } |
| 917 | |
| 918 | #[test] |
| 919 | fn oversized_schema_is_never_admitted() { |
| 920 | let catalog = vec![deferred_tool( |
| 921 | "huge", |
| 922 | TOOL_ACTIVATION_CACHE_MAX_SCHEMA_BYTES + 1, |
| 923 | )]; |
| 924 | let mut cache = ToolActivationCache::default(); |
| 925 | let delta = cache.activate(&catalog, &["huge".to_string()]); |
| 926 | |
| 927 | assert_eq!(cache.names().count(), 0); |
| 928 | assert_eq!(delta.rejected, vec!["huge"]); |
| 929 | } |
| 930 | |
| 931 | #[test] |
| 932 | fn revalidate_drops_removed_denied_or_eager_tools() { |
| 933 | let catalog = vec![deferred_tool("kept", 8), deferred_tool("gone", 8)]; |
| 934 | let mut cache = ToolActivationCache::default(); |
| 935 | cache.activate(&catalog, &["kept".to_string(), "gone".to_string()]); |
| 936 | let mut next_catalog = vec![deferred_tool("kept", 8), deferred_tool("gone", 8)]; |
| 937 | next_catalog[1].defer_loading = Some(false); |
| 938 | |
| 939 | let evicted = cache.revalidate(&next_catalog); |
| 940 | assert_eq!(cache.names().collect::<Vec<_>>(), vec!["kept"]); |
| 941 | assert_eq!(evicted, vec!["gone"]); |
| 942 | } |
| 943 | |
| 944 | #[test] |
| 945 | fn clearing_for_session_sync_forgets_all_activated_tools() { |
| 946 | let catalog = vec![deferred_tool("one", 8), deferred_tool("two", 8)]; |
| 947 | let mut cache = ToolActivationCache::default(); |
| 948 | cache.activate(&catalog, &["one".to_string(), "two".to_string()]); |
| 949 | |
| 950 | cache.clear(); |
| 951 | |
| 952 | assert_eq!(cache.names().count(), 0); |
| 953 | } |
| 954 | |
| 955 | #[test] |
| 956 | fn cached_tools_obey_budget_and_pinned_cached_tools_are_not_double_counted() { |
| 957 | let big = TOOL_ACTIVATION_CACHE_MAX_SCHEMA_BYTES * 5 / 8; |
| 958 | let catalog = vec![ |
| 959 | deferred_tool("cached_big", big), |
| 960 | deferred_tool("new_big", big), |
| 961 | ]; |
| 962 | let mut cache = ToolActivationCache::default().with_eviction(true); |
| 963 | cache.activate(&catalog, &["cached_big".to_string()]); |
| 964 | cache.begin_turn(); |
| 965 | cache.begin_turn(); |
| 966 | |
| 967 | let delta = cache.activate(&catalog, &["new_big".to_string(), "cached_big".to_string()]); |
| 968 | |
| 969 | assert_eq!(delta.admitted, vec!["new_big"]); |
| 970 | assert_eq!(delta.evicted, vec!["cached_big"]); |
| 971 | assert_eq!(delta.held, vec!["cached_big"]); |
| 972 | assert!(cache.total_serialized_bytes(&catalog) <= TOOL_ACTIVATION_CACHE_MAX_SCHEMA_BYTES); |
| 973 | |
| 974 | let med = TOOL_ACTIVATION_CACHE_MAX_SCHEMA_BYTES * 5 / 16; |
| 975 | let small = TOOL_ACTIVATION_CACHE_MAX_SCHEMA_BYTES / 4; |
| 976 | let pinned_catalog = vec![ |
| 977 | deferred_tool("pinned_a", med), |
| 978 | deferred_tool("pinned_b", med), |
| 979 | deferred_tool("new_small", small), |
| 980 | ]; |
| 981 | let mut pinned_cache = ToolActivationCache::default(); |
| 982 | pinned_cache.activate( |
| 983 | &pinned_catalog, |
| 984 | &["pinned_a".to_string(), "pinned_b".to_string()], |
| 985 | ); |
| 986 | assert!(pinned_cache.record_use("pinned_a")); |
| 987 | assert!(pinned_cache.record_use("pinned_b")); |
| 988 | |
| 989 | let pinned_delta = pinned_cache.activate( |
| 990 | &pinned_catalog, |
| 991 | &["new_small".to_string(), "pinned_b".to_string()], |
| 992 | ); |
| 993 | |
| 994 | assert_eq!(pinned_delta.admitted, vec!["new_small", "pinned_b"]); |
| 995 | assert!(pinned_delta.held.is_empty()); |
| 996 | assert_eq!( |
| 997 | pinned_cache.names().collect::<Vec<_>>(), |
| 998 | vec!["pinned_a", "pinned_b", "new_small"] |
| 999 | ); |
| 1000 | } |
| 1001 | |
| 1002 | #[test] |
| 1003 | fn fresh_query_matches_are_not_held_behind_full_pinned_soft_cap() { |
| 1004 | let max = TOOL_ACTIVATION_CACHE_MAX_NAMES; |
| 1005 | let mut catalog: Vec<_> = (0..max) |
| 1006 | .map(|index| deferred_tool(&format!("pinned_{index}"), 8)) |
| 1007 | .collect(); |
| 1008 | let fresh: Vec<String> = (0..4).map(|index| format!("linear_{index}")).collect(); |
| 1009 | for name in &fresh { |
| 1010 | catalog.push(deferred_tool(name, 8)); |
| 1011 | } |
| 1012 | let mut cache = ToolActivationCache::default(); |
| 1013 | let initial: Vec<String> = (0..max).map(|index| format!("pinned_{index}")).collect(); |
| 1014 | cache.activate(&catalog, &initial); |
| 1015 | for name in &initial { |
| 1016 | assert!(cache.record_use(name)); |
| 1017 | } |
| 1018 | |
| 1019 | let delta = cache.activate(&catalog, &fresh); |
| 1020 | assert_eq!(delta.admitted, fresh); |
| 1021 | assert!(delta.held.is_empty()); |
| 1022 | assert!(delta.exceeds_soft_target); |
| 1023 | let retained: HashSet<_> = cache.names().collect(); |
| 1024 | for name in &fresh { |
| 1025 | assert!(retained.contains(name.as_str())); |
| 1026 | } |
| 1027 | } |
| 1028 | |
| 1029 | #[test] |
| 1030 | fn pinned_toolbox_stops_at_twice_the_soft_targets() { |
| 1031 | let max = TOOL_ACTIVATION_CACHE_MAX_NAMES; |
| 1032 | let names = (0..2 * max + 2) |
| 1033 | .map(|index| format!("tool_{index}")) |
| 1034 | .collect::<Vec<_>>(); |
| 1035 | let catalog = names |
| 1036 | .iter() |
| 1037 | .map(|name| deferred_tool(name, 8)) |
| 1038 | .collect::<Vec<_>>(); |
| 1039 | let mut cache = ToolActivationCache::default(); |
| 1040 | for batch in [&names[..max], &names[max..2 * max - 2]] { |
| 1041 | assert!(cache.activate(&catalog, batch).held.is_empty()); |
| 1042 | for name in batch { |
| 1043 | assert!(cache.record_use(name)); |
| 1044 | } |
| 1045 | } |
| 1046 | |
| 1047 | let delta = cache.activate(&catalog, &names[2 * max - 2..]); |
| 1048 | assert_eq!(delta.admitted, names[2 * max - 2..2 * max]); |
| 1049 | assert_eq!(delta.held, names[2 * max..]); |
| 1050 | assert_eq!(cache.names().count(), 2 * max); |
| 1051 | for name in &delta.admitted { |
| 1052 | assert!(cache.record_use(name)); |
| 1053 | } |
| 1054 | |
| 1055 | let best = cache.activate(&catalog, &names[2 * max..]); |
| 1056 | assert_eq!(best.admitted, names[2 * max..=2 * max]); |
| 1057 | assert_eq!(best.held, names[2 * max + 1..]); |
| 1058 | } |
| 1059 | |
| 1060 | #[test] |
| 1061 | fn default_cache_preserves_admitted_tools_without_eviction_up_to_ceiling() { |
| 1062 | let max = TOOL_ACTIVATION_CACHE_MAX_NAMES; |
| 1063 | let names = (0..2 * max + 2) |
| 1064 | .map(|index| format!("mcp_demo_{index}")) |
| 1065 | .collect::<Vec<_>>(); |
| 1066 | let catalog = names |
| 1067 | .iter() |
| 1068 | .map(|name| deferred_tool(name, 8)) |
| 1069 | .collect::<Vec<_>>(); |
| 1070 | let mut cache = ToolActivationCache::default(); |
| 1071 | assert!(!cache.eviction_enabled()); |
| 1072 | |
| 1073 | let first = cache.activate(&catalog, &names[..max]); |
| 1074 | assert_eq!(first.admitted, names[..max]); |
| 1075 | assert!(first.evicted.is_empty()); |
| 1076 | |
| 1077 | cache.begin_turn(); |
| 1078 | cache.begin_turn(); |
| 1079 | |
| 1080 | let second = cache.activate(&catalog, &names[max..2 * max]); |
| 1081 | assert_eq!(second.admitted, names[max..2 * max]); |
| 1082 | assert!(second.evicted.is_empty()); |
| 1083 | assert!(second.held.is_empty()); |
| 1084 | assert!(second.exceeds_soft_target); |
| 1085 | assert_eq!(cache.names().count(), 2 * max); |
| 1086 | |
| 1087 | let third = cache.activate(&catalog, &names[2 * max..]); |
| 1088 | assert!(third.evicted.is_empty()); |
| 1089 | assert_eq!(third.admitted, names[2 * max..=2 * max]); |
| 1090 | assert_eq!(third.held, names[2 * max + 1..]); |
| 1091 | assert_eq!(cache.names().count(), 2 * max + 1); |
| 1092 | |
| 1093 | let mut narrowed = catalog.clone(); |
| 1094 | narrowed[0].defer_loading = Some(false); |
| 1095 | let removed = cache.revalidate(&narrowed); |
| 1096 | assert_eq!(removed, vec![names[0].clone()]); |
| 1097 | |
| 1098 | let mut opt_in = ToolActivationCache::default().with_eviction(true); |
| 1099 | assert!(opt_in.eviction_enabled()); |
| 1100 | opt_in.activate(&catalog, &names[..2]); |
| 1101 | opt_in.clear(); |
| 1102 | assert_eq!(opt_in.names().count(), 0); |
| 1103 | assert!(opt_in.eviction_enabled()); |
| 1104 | } |
| 1105 | } |
| 1106 |