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 rmcp::service::{Peer, RoleServer};
8
9pub(super) struct CepComputedStats {
10    pub(super) cep_score: u32,
11    pub(super) cache_util: u32,
12    pub(super) mode_diversity: u32,
13    pub(super) compression_rate: u32,
14    pub(super) total_original: u64,
15    pub(super) total_compressed: u64,
16    pub(super) total_saved: u64,
17    pub(super) mode_counts: std::collections::HashMap<String, u64>,
18    pub(super) complexity: String,
19    pub(super) cache_hits: u64,
20    pub(super) total_reads: u64,
21    pub(super) tool_call_count: u64,
22}
23
24pub use crate::core::protocol::CrpMode;
25// CrpMode is now defined in core::protocol to avoid reverse-dependency.
26// Re-exported here for backward compatibility.
27
28impl CrpMode {
29    /// Effective CRP mode for the active profile — see [`CrpMode::resolve`].
30    pub fn effective() -> Self {
31        Self::resolve(
32            crate::core::profiles::active_profile()
33                .compression
34                .crp_mode
35                .as_deref(),
36        )
37    }
38
39    /// Returns true if the mode is TDD (maximum compression).
40    pub fn is_tdd(&self) -> bool {
41        *self == Self::Tdd
42    }
43}
44
45/// Thread-safe handle to the shared file content cache.
46pub type SharedCache = Arc<RwLock<SessionCache>>;
47
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49pub enum SessionMode {
50    /// Traditional single-client session persistence under `~/.lean-ctx/sessions/`.
51    Personal,
52    /// Context OS mode: shared sessions + event bus for multi-client HTTP/team-server.
53    Shared,
54}
55
56/// IDE interaction mode communicated via `_meta.interactionMode` in MCP requests.
57/// Controls which tools are advertised and callable — Plan mode restricts to
58/// read-only tools (see `plan_mode_tools()`), Agent mode exposes the full set.
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60#[repr(u8)]
61pub enum InteractionMode {
62    Agent = 0,
63    Plan = 1,
64}
65
66impl InteractionMode {
67    pub fn from_u8(v: u8) -> Self {
68        match v {
69            1 => Self::Plan,
70            _ => Self::Agent,
71        }
72    }
73
74    /// Parse the string value from `_meta.interactionMode`.
75    /// Accepts multiple conventions across IDEs (OpenCode, Cursor, Claude Code).
76    pub fn from_meta_str(s: &str) -> Option<Self> {
77        match s.to_ascii_lowercase().as_str() {
78            "plan" | "readonly" | "read-only" => Some(Self::Plan),
79            "agent" | "normal" | "edit" | "act" => Some(Self::Agent),
80            _ => None,
81        }
82    }
83}
84
85/// Central MCP server state: cache, session, metrics, and autonomy runtime.
86#[derive(Clone)]
87pub struct LeanCtxServer {
88    pub cache: SharedCache,
89    pub session: crate::core::session::SessionSlot,
90    pub tool_calls: Arc<RwLock<Vec<ToolCallRecord>>>,
91    pub call_count: Arc<AtomicUsize>,
92    /// Every tool call, counted unconditionally at the top of
93    /// `call_tool_guarded`.
94    ///
95    /// `call_count` only advances inside `record_checkpoint`, which returns
96    /// early whenever checkpointing is skipped — and `minimal_overhead`
97    /// (default `true`) skips it for every tool. Anything scheduled off
98    /// `call_count` therefore never runs in a default install. The daily
99    /// telemetry flush was scheduled that way and consequently never sent.
100    pub background_tick: Arc<AtomicUsize>,
101    pub cache_ttl_secs: u64,
102    pub last_call: Arc<RwLock<Instant>>,
103    pub agent_id: Arc<RwLock<Option<String>>>,
104    pub task_envelope: Arc<RwLock<Option<lean_ctx_protocol::TaskEnvelopeV1>>>,
105    /// Installed by the trusted host before serving; never sourced from tool arguments.
106    pub(crate) native_receipt_authority:
107        Option<Arc<crate::core::execution_ledger::host::HostReceiptAuthority>>,
108    pub(crate) presence_agent_id: Arc<RwLock<Option<String>>>,
109    /// Single-flight for the fail-closed presence retry: concurrent first
110    /// calls register once instead of racing N writers on the registry lock.
111    pub(crate) presence_init: Arc<tokio::sync::Mutex<()>>,
112    /// The role this session resolved at `initialize` (#1766). The fail-closed
113    /// presence retry re-registers with it instead of the construction-time
114    /// `context-engine` placeholder, which silently turned a `reviewer` (or a
115    /// `coder`) into a context engine.
116    pub(crate) presence_role: Arc<RwLock<Option<String>>>,
117    pub client_name: Arc<RwLock<String>>,
118    pub autonomy: Arc<crate::core::autonomy::AutonomyState>,
119    pub loop_detector: Arc<RwLock<crate::core::loop_detection::LoopDetector>>,
120    pub workflow: Arc<RwLock<Option<crate::core::workflow::WorkflowRun>>>,
121    pub ledger: Arc<RwLock<crate::core::context_ledger::ContextLedger>>,
122    pub pipeline_stats: Arc<RwLock<crate::core::pipeline::PipelineStats>>,
123    pub session_mode: SessionMode,
124    pub workspace_id: String,
125    pub channel_id: String,
126    pub context_os: Option<Arc<crate::core::context_os::ContextOsRuntime>>,
127    pub context_ir: Option<Arc<RwLock<crate::core::context_ir::ContextIrV1>>>,
128    pub registry: Option<Arc<crate::server::registry::ToolRegistry>>,
129    pub(crate) rules_stale_checked: Arc<std::sync::atomic::AtomicBool>,
130    pub(crate) rules_tip_shown: Arc<std::sync::atomic::AtomicBool>,
131    pub(crate) last_seen_event_id: Arc<std::sync::atomic::AtomicI64>,
132    pub(crate) startup_project_root: Option<String>,
133    pub(crate) startup_shell_cwd: Option<String>,
134    pub(crate) peer: Arc<RwLock<Option<Peer<RoleServer>>>>,
135    /// The user's answers to shell approval prompts in this session.
136    pub(crate) shell_approvals: Arc<crate::server::shell_approval::ShellApprovalState>,
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}