rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! How each MCP server's last start in this process ended, for `rho/mcp/list`
//! to show beside its configuration: a daemon hosts every session of its
//! user, so its process's book covers every session on that daemon.
//!
//! A start is kept with the configuration it started from, and read back
//! only for that configuration, so a server edited since reads as not yet
//! started instead of showing an outcome its old configuration had. Storing
//! or deleting one of its secrets forgets it the same way, since its next
//! start reads them.
//!
//! Sessions start their servers concurrently and record a batch at once, so
//! a record can arrive late. Two rules keep a late one from replacing what
//! is known now: a start that began before its server's secrets changed
//! records nothing, and of two starts the one that ended last wins,
//! whichever records first.
//!
//! Sessions record through their `McpSessionOptions`, which hold this
//! process's book unless built with another.

use std::{
    collections::HashMap,
    sync::{Arc, Mutex, OnceLock},
    time::SystemTime,
};

use rho_protocol::{McpSeenOutcome, McpServerSeen};

use super::config::McpServerConfig;

/// The last start of each server, by identity. Clones share one book.
#[derive(Clone, Default)]
pub(crate) struct McpSightings {
    book: Arc<Mutex<Book>>,
}

#[derive(Default)]
struct Book {
    servers: HashMap<String, Server>,
    /// Counts the starts that ended, to order them.
    ended: u64,
}

/// What the book knows of one server.
#[derive(Default)]
struct Server {
    /// How many times its secrets changed.
    secret_changes: u64,
    last: Option<Sighting>,
}

/// One server's last start.
struct Sighting {
    /// What it started from. May hold literal `env` or `headers` values, as
    /// the session's own config does; it never leaves the process.
    server: McpServerConfig,
    seen: McpServerSeen,
    /// When it ended among all starts.
    order: u64,
}

/// A start of one server, taken before it reads its secrets.
pub(crate) struct McpStartBegun {
    secret_changes: u64,
}

/// A start of one server that ended, ready to record.
pub(crate) struct McpStartEnded {
    secret_changes: u64,
    order: u64,
    at: SystemTime,
}

impl McpSightings {
    /// This process's book, which sessions record into by default.
    pub(crate) fn process() -> Self {
        static PROCESS: OnceLock<McpSightings> = OnceLock::new();
        PROCESS.get_or_init(Self::default).clone()
    }

    /// Begins a start of `identity`, before it reads its secrets.
    pub(crate) fn begin(&self, identity: &str) -> McpStartBegun {
        let book = self.lock();
        McpStartBegun {
            secret_changes: book
                .servers
                .get(identity)
                .map_or(0, |server| server.secret_changes),
        }
    }

    /// Marks `start` ended now, as soon as its server's connect does.
    pub(crate) fn end(&self, start: McpStartBegun) -> McpStartEnded {
        let mut book = self.lock();
        book.ended += 1;
        McpStartEnded {
            secret_changes: start.secret_changes,
            order: book.ended,
            at: SystemTime::now(),
        }
    }

    /// Records that `start` of `identity` from `server` ended in `outcome`,
    /// unless the server's secrets changed since it began or a start that
    /// ended later is recorded already.
    pub(crate) fn record(
        &self,
        identity: &str,
        server: &McpServerConfig,
        outcome: McpSeenOutcome,
        start: McpStartEnded,
    ) {
        let mut book = self.lock();
        let known = book.servers.entry(identity.to_owned()).or_default();
        let stale = known.secret_changes != start.secret_changes
            || known
                .last
                .as_ref()
                .is_some_and(|last| last.order > start.order);
        if stale {
            return;
        }
        let at = start
            .at
            .duration_since(SystemTime::UNIX_EPOCH)
            .map_or(0, |since| since.as_secs());
        known.last = Some(Sighting {
            server: server.clone(),
            seen: McpServerSeen::new(outcome, at),
            order: start.order,
        });
    }

    /// Forgets the last start of `identity`, whose stored secrets changed,
    /// and any start of it that began before.
    pub(crate) fn forget(&self, identity: &str) {
        let mut book = self.lock();
        let known = book.servers.entry(identity.to_owned()).or_default();
        known.secret_changes += 1;
        known.last = None;
    }

    /// How the last start of `identity` ended, when it started from
    /// `server` as configured now.
    pub(crate) fn seen(&self, identity: &str, server: &McpServerConfig) -> Option<McpServerSeen> {
        self.lock()
            .servers
            .get(identity)
            .and_then(|known| known.last.as_ref())
            .filter(|sighting| sighting.server == *server)
            .map(|sighting| sighting.seen.clone())
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, Book> {
        // A panic while holding it leaves a whole book: each write finishes
        // without calling out.
        self.book
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }
}

#[cfg(test)]
#[path = "sightings_tests.rs"]
mod tests;