lean-ctx-engine 3.12.10

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
Documentation
// SPDX-License-Identifier: Apache-2.0
//! Logical-session presence on the agent registry, kept beside `registry.rs`.

use super::{
    AgentRegistry, AgentStatus, LOGICAL_SESSION_ID_MAX_BYTES, LOGICAL_SESSION_SOURCE_MAX_BYTES,
    LOGICAL_SESSION_WORKSPACE_MAX_BYTES, LogicalSessionPresence, UtcDateTime, mutate_persistent,
};

impl AgentRegistry {
    /// Records explicit logical-session presence supplied by an owning editor
    /// integration. Tool activity is deliberately never treated as a session.
    pub(crate) fn open_or_heartbeat_logical_session(
        &mut self,
        source: &str,
        workspace: &str,
        session_id: &str,
    ) {
        let now = UtcDateTime::now();
        self.logical_session_telemetry_seen = true;
        if let Some(session) = self.logical_sessions.iter_mut().find(|session| {
            session.source == source
                && session.workspace == workspace
                && session.session_id == session_id
        }) {
            session.last_heartbeat = now;
        } else {
            self.logical_sessions.push(LogicalSessionPresence {
                source: source.to_string(),
                workspace: workspace.to_string(),
                session_id: session_id.to_string(),
                opened_at: now,
                last_heartbeat: now,
            });
        }
        self.updated_at = now;
    }

    pub(crate) fn close_logical_session(
        &mut self,
        source: &str,
        workspace: &str,
        session_id: &str,
    ) -> bool {
        self.logical_session_telemetry_seen = true;
        let previous_len = self.logical_sessions.len();
        self.logical_sessions.retain(|session| {
            session.source != source
                || session.workspace != workspace
                || session.session_id != session_id
        });
        let removed = self.logical_sessions.len() != previous_len;
        self.updated_at = UtcDateTime::now();
        removed
    }

    pub fn cleanup_stale_logical_sessions(&mut self, max_age_seconds: u64) {
        let seconds = i64::try_from(max_age_seconds).unwrap_or(i64::MAX);
        let cutoff = UtcDateTime::now() - lean_ctx_time::Duration::seconds(seconds);
        self.logical_sessions
            .retain(|session| session.last_heartbeat >= cutoff);
        self.updated_at = UtcDateTime::now();
    }

    pub fn record_logical_session_presence(
        event: &str,
        source: &str,
        workspace: &str,
        session_id: &str,
    ) -> Result<(), String> {
        let valid_field = |value: &str, max_bytes: usize| {
            !value.is_empty() && value.len() <= max_bytes && !value.chars().any(char::is_control)
        };
        if !valid_field(source, LOGICAL_SESSION_SOURCE_MAX_BYTES)
            || !valid_field(workspace, LOGICAL_SESSION_WORKSPACE_MAX_BYTES)
            || !valid_field(session_id, LOGICAL_SESSION_ID_MAX_BYTES)
        {
            return Err(
                "presence fields are empty, too long, or contain control characters".to_string(),
            );
        }
        if !matches!(event, "open" | "heartbeat" | "close") {
            return Err("event must be open, heartbeat, or close".to_string());
        }

        let ttl = crate::core::config::Config::load()
            .agents
            .logical_session_ttl_seconds;
        mutate_persistent(|registry| {
            registry.cleanup_stale_logical_sessions(ttl);
            match event {
                "open" | "heartbeat" => {
                    registry.open_or_heartbeat_logical_session(source, workspace, session_id);
                }
                "close" => {
                    registry.close_logical_session(source, workspace, session_id);
                }
                _ => unreachable!("event validated above"),
            }
        })
    }

    /// Gate operations for an explicitly bound presence. Legacy unbound
    /// entries retain their prior behavior until a migration enables a
    /// mandatory-binding mode.
    pub fn require_active_for_presence(
        &self,
        agent_id: &str,
        operation: &str,
    ) -> Result<(), String> {
        let Some(agent) = self.agents.iter().find(|agent| agent.agent_id == agent_id) else {
            return Ok(());
        };
        let Some(durable_id) = agent.durable_identity_id.as_deref() else {
            return Ok(());
        };
        if agent.status == AgentStatus::Finished {
            return Err(format!(
                "agent presence '{agent_id}' is finished; cannot {operation}"
            ));
        }
        crate::core::agent_registry::require_active(durable_id).map_err(|error| {
            format!("agent presence '{agent_id}' is not authorized for {operation}: {error}")
        })
    }
}