Skip to main content

lean_ctx/tools/
server.rs

1use std::sync::atomic::AtomicUsize;
2use std::sync::Arc;
3use std::time::Instant;
4use tokio::sync::RwLock;
5
6use crate::core::cache::SessionCache;
7use crate::core::session::SessionState;
8use rmcp::service::{Peer, RoleServer};
9
10pub(super) struct CepComputedStats {
11    pub(super) cep_score: u32,
12    pub(super) cache_util: u32,
13    pub(super) mode_diversity: u32,
14    pub(super) compression_rate: u32,
15    pub(super) total_original: u64,
16    pub(super) total_compressed: u64,
17    pub(super) total_saved: u64,
18    pub(super) mode_counts: std::collections::HashMap<String, u64>,
19    pub(super) complexity: String,
20    pub(super) cache_hits: u64,
21    pub(super) total_reads: u64,
22    pub(super) tool_call_count: u64,
23}
24
25pub use crate::core::protocol::CrpMode;
26// CrpMode is now defined in core::protocol to avoid reverse-dependency.
27// Re-exported here for backward compatibility.
28
29impl CrpMode {
30    /// Effective CRP mode: explicit env var wins; otherwise derived from CompressionLevel.
31    pub fn effective() -> Self {
32        if let Ok(v) = std::env::var("LEAN_CTX_CRP_MODE") {
33            if !v.trim().is_empty() {
34                return Self::parse(&v).unwrap_or(Self::Off);
35            }
36        }
37        let config = crate::core::config::Config::load();
38        let level = crate::core::config::CompressionLevel::effective(&config);
39        let (_, _, crp_str, _) = level.to_components();
40        Self::parse(crp_str).unwrap_or(Self::Off)
41    }
42
43    /// Returns true if the mode is TDD (maximum compression).
44    pub fn is_tdd(&self) -> bool {
45        *self == Self::Tdd
46    }
47}
48
49/// Thread-safe handle to the shared file content cache.
50pub type SharedCache = Arc<RwLock<SessionCache>>;
51
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53pub enum SessionMode {
54    /// Traditional single-client session persistence under `~/.lean-ctx/sessions/`.
55    Personal,
56    /// Context OS mode: shared sessions + event bus for multi-client HTTP/team-server.
57    Shared,
58}
59
60/// Central MCP server state: cache, session, metrics, and autonomy runtime.
61#[derive(Clone)]
62pub struct LeanCtxServer {
63    pub cache: SharedCache,
64    pub session: Arc<RwLock<SessionState>>,
65    pub tool_calls: Arc<RwLock<Vec<ToolCallRecord>>>,
66    pub call_count: Arc<AtomicUsize>,
67    pub cache_ttl_secs: u64,
68    pub last_call: Arc<RwLock<Instant>>,
69    pub agent_id: Arc<RwLock<Option<String>>>,
70    pub client_name: Arc<RwLock<String>>,
71    pub autonomy: Arc<super::autonomy::AutonomyState>,
72    pub loop_detector: Arc<RwLock<crate::core::loop_detection::LoopDetector>>,
73    pub workflow: Arc<RwLock<Option<crate::core::workflow::WorkflowRun>>>,
74    pub ledger: Arc<RwLock<crate::core::context_ledger::ContextLedger>>,
75    pub pipeline_stats: Arc<RwLock<crate::core::pipeline::PipelineStats>>,
76    pub session_mode: SessionMode,
77    pub workspace_id: String,
78    pub channel_id: String,
79    pub context_os: Option<Arc<crate::core::context_os::ContextOsRuntime>>,
80    pub context_ir: Option<Arc<RwLock<crate::core::context_ir::ContextIrV1>>>,
81    pub registry: Option<Arc<crate::server::registry::ToolRegistry>>,
82    pub(crate) rules_stale_checked: Arc<std::sync::atomic::AtomicBool>,
83    pub(crate) last_seen_event_id: Arc<std::sync::atomic::AtomicI64>,
84    pub(crate) startup_project_root: Option<String>,
85    pub(crate) startup_shell_cwd: Option<String>,
86    pub(crate) peer: Arc<RwLock<Option<Peer<RoleServer>>>>,
87}
88
89pub use crate::core::protocol::ToolCallRecord;