Skip to main content

lean_ctx/tools/
server.rs

1use std::sync::Arc;
2use std::sync::atomic::AtomicUsize;
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 for the active profile — see [`CrpMode::resolve`].
31    pub fn effective() -> Self {
32        Self::resolve(
33            crate::core::profiles::active_profile()
34                .compression
35                .crp_mode
36                .as_deref(),
37        )
38    }
39
40    /// Returns true if the mode is TDD (maximum compression).
41    pub fn is_tdd(&self) -> bool {
42        *self == Self::Tdd
43    }
44}
45
46/// Thread-safe handle to the shared file content cache.
47pub type SharedCache = Arc<RwLock<SessionCache>>;
48
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub enum SessionMode {
51    /// Traditional single-client session persistence under `~/.lean-ctx/sessions/`.
52    Personal,
53    /// Context OS mode: shared sessions + event bus for multi-client HTTP/team-server.
54    Shared,
55}
56
57/// IDE interaction mode communicated via `_meta.interactionMode` in MCP requests.
58/// Controls which tools are advertised and callable — Plan mode restricts to
59/// read-only tools (see `plan_mode_tools()`), Agent mode exposes the full set.
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
61#[repr(u8)]
62pub enum InteractionMode {
63    Agent = 0,
64    Plan = 1,
65}
66
67impl InteractionMode {
68    pub fn from_u8(v: u8) -> Self {
69        match v {
70            1 => Self::Plan,
71            _ => Self::Agent,
72        }
73    }
74
75    /// Parse the string value from `_meta.interactionMode`.
76    /// Accepts multiple conventions across IDEs (OpenCode, Cursor, Claude Code).
77    pub fn from_meta_str(s: &str) -> Option<Self> {
78        match s.to_ascii_lowercase().as_str() {
79            "plan" | "readonly" | "read-only" => Some(Self::Plan),
80            "agent" | "normal" | "edit" | "act" => Some(Self::Agent),
81            _ => None,
82        }
83    }
84}
85
86/// Central MCP server state: cache, session, metrics, and autonomy runtime.
87#[derive(Clone)]
88pub struct LeanCtxServer {
89    pub cache: SharedCache,
90    pub session: Arc<RwLock<SessionState>>,
91    pub tool_calls: Arc<RwLock<Vec<ToolCallRecord>>>,
92    pub call_count: Arc<AtomicUsize>,
93    /// Every tool call, counted unconditionally at the top of
94    /// `call_tool_guarded`.
95    ///
96    /// `call_count` only advances inside `record_checkpoint`, which returns
97    /// early whenever checkpointing is skipped — and `minimal_overhead`
98    /// (default `true`) skips it for every tool. Anything scheduled off
99    /// `call_count` therefore never runs in a default install. The daily
100    /// telemetry flush was scheduled that way and consequently never sent.
101    pub background_tick: Arc<AtomicUsize>,
102    pub pro_trigger_check_count: Arc<AtomicUsize>,
103    pub cache_ttl_secs: u64,
104    pub last_call: Arc<RwLock<Instant>>,
105    pub agent_id: Arc<RwLock<Option<String>>>,
106    pub task_envelope: Arc<RwLock<Option<lean_ctx_protocol::TaskEnvelopeV1>>>,
107    /// Installed by the trusted host before serving; never sourced from tool arguments.
108    pub(crate) native_receipt_authority:
109        Option<Arc<crate::core::execution_ledger::host::HostReceiptAuthority>>,
110    pub(crate) presence_agent_id: Arc<RwLock<Option<String>>>,
111    /// Single-flight for the fail-closed presence retry: concurrent first
112    /// calls register once instead of racing N writers on the registry lock.
113    pub(crate) presence_init: Arc<tokio::sync::Mutex<()>>,
114    /// The role this session resolved at `initialize` (#1766). The fail-closed
115    /// presence retry re-registers with it instead of the construction-time
116    /// `context-engine` placeholder, which silently turned a `reviewer` (or a
117    /// `coder`) into a context engine.
118    pub(crate) presence_role: Arc<RwLock<Option<String>>>,
119    pub client_name: Arc<RwLock<String>>,
120    pub autonomy: Arc<crate::core::autonomy::AutonomyState>,
121    pub loop_detector: Arc<RwLock<crate::core::loop_detection::LoopDetector>>,
122    pub workflow: Arc<RwLock<Option<crate::core::workflow::WorkflowRun>>>,
123    pub ledger: Arc<RwLock<crate::core::context_ledger::ContextLedger>>,
124    pub pipeline_stats: Arc<RwLock<crate::core::pipeline::PipelineStats>>,
125    pub session_mode: SessionMode,
126    pub workspace_id: String,
127    pub channel_id: String,
128    pub context_os: Option<Arc<crate::core::context_os::ContextOsRuntime>>,
129    pub context_ir: Option<Arc<RwLock<crate::core::context_ir::ContextIrV1>>>,
130    pub registry: Option<Arc<crate::server::registry::ToolRegistry>>,
131    pub(crate) rules_stale_checked: Arc<std::sync::atomic::AtomicBool>,
132    pub(crate) rules_tip_shown: Arc<std::sync::atomic::AtomicBool>,
133    pub(crate) last_seen_event_id: Arc<std::sync::atomic::AtomicI64>,
134    pub(crate) startup_project_root: Option<String>,
135    pub(crate) startup_shell_cwd: Option<String>,
136    pub(crate) peer: Arc<RwLock<Option<Peer<RoleServer>>>>,
137    pub(crate) has_client_roots: Arc<std::sync::atomic::AtomicBool>,
138    pub(crate) roots_resolved: Arc<std::sync::atomic::AtomicBool>,
139    /// Failed `roots/list` attempts (GH #694): transient failures re-arm
140    /// `roots_resolved` until a small budget is exhausted.
141    pub(crate) roots_list_attempts: Arc<std::sync::atomic::AtomicU32>,
142    pub(crate) bm25_cache: Arc<std::sync::Mutex<Option<crate::core::bm25_cache::Bm25CacheEntry>>>,
143    pub(crate) _eviction_target: Arc<crate::core::eviction_orchestrator::EvictionOrchestrator>,
144    pub(crate) progress_sender: crate::server::progress::SharedProgressSender,
145    pub(crate) last_tools_config_hash: Arc<std::sync::atomic::AtomicU64>,
146    /// Current IDE interaction mode (Agent/Plan). Updated from `_meta.interactionMode`
147    /// on each tool call; controls tool visibility and destructive-tool guards.
148    pub(crate) interaction_mode: Arc<std::sync::atomic::AtomicU8>,
149}
150
151pub use crate::core::protocol::ToolCallRecord;
152
153#[cfg(test)]
154mod tests {
155    use super::InteractionMode;
156
157    #[test]
158    fn from_u8_round_trips() {
159        assert_eq!(InteractionMode::from_u8(0), InteractionMode::Agent);
160        assert_eq!(InteractionMode::from_u8(1), InteractionMode::Plan);
161        assert_eq!(InteractionMode::from_u8(42), InteractionMode::Agent);
162    }
163
164    #[test]
165    fn from_meta_str_plan_variants() {
166        for s in ["plan", "Plan", "PLAN", "readonly", "read-only"] {
167            assert_eq!(
168                InteractionMode::from_meta_str(s),
169                Some(InteractionMode::Plan),
170                "failed for: {s}"
171            );
172        }
173    }
174
175    #[test]
176    fn from_meta_str_agent_variants() {
177        for s in ["agent", "Agent", "normal", "edit", "act"] {
178            assert_eq!(
179                InteractionMode::from_meta_str(s),
180                Some(InteractionMode::Agent),
181                "failed for: {s}"
182            );
183        }
184    }
185
186    #[test]
187    fn from_meta_str_unknown_returns_none() {
188        assert_eq!(InteractionMode::from_meta_str("debug"), None);
189        assert_eq!(InteractionMode::from_meta_str(""), None);
190    }
191
192    #[test]
193    fn default_mode_is_agent() {
194        let mode = std::sync::atomic::AtomicU8::new(InteractionMode::Agent as u8);
195        assert_eq!(
196            InteractionMode::from_u8(mode.load(std::sync::atomic::Ordering::Relaxed)),
197            InteractionMode::Agent,
198        );
199    }
200}