Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

7.3 KB
Raw Blame
use std::collections::HashMap;
#[cfg(not(feature = "cli"))]
use std::collections::HashSet;
use std::sync::Arc;

#[cfg(not(feature = "cli"))]
use crate::core::downloads::models::DownloadManagerState;
#[cfg(not(feature = "cli"))]
use crate::core::mcp::models::{McpSettings, ToolWithServer};
#[cfg(not(feature = "cli"))]
use crate::core::mcp::progress::JanClientHandler;
#[cfg(feature = "cli")]
use rmcp::model::{CallToolRequestParams, CallToolResult, InitializeRequestParams, Tool};
#[cfg(feature = "cli")]
use rmcp::ServiceError;
use rmcp::{service::RunningService, RoleClient};
use tokio::sync::Mutex;
#[cfg(not(feature = "cli"))]
use tokio::sync::{oneshot, Notify};

/// Server handle type for managing the proxy server lifecycle
#[cfg(not(feature = "cli"))]
pub type ServerHandle =
    tokio::task::JoinHandle<Result<(), Box<dyn std::error::Error + Send + Sync>>>;

/// Provider configuration for remote model providers
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct ProviderConfig {
    pub provider: String,
    /// First key (mirrors `api_keys[0]` when populated); kept for backward compatibility.
    pub api_key: Option<String>,
    /// Ordered keys for Bearer auth: proxy tries each on 401/403/429.
    #[serde(default)]
    pub api_keys: Vec<String>,
    pub base_url: Option<String>,
    pub custom_headers: Vec<ProviderCustomHeader>,
    pub models: Vec<String>,
    /// Upstream wire API this provider speaks. `None`/`"openai"` = OpenAI
    /// chat/completions (verbatim passthrough). Other values select a
    /// translating converter (e.g. `"openai-responses"`, `"google"`,
    /// `"anthropic"`) so the proxy can accept OpenAI-shaped requests and talk
    /// the provider's native API.
    #[serde(default)]
    pub api_type: Option<String>,
    /// Share of the context window a prompt may fill before a run routed
    /// through this provider compacts ahead of dispatching. Overrides
    /// `[agent].compaction_ratio`; `None` inherits it. Sized per provider
    /// because windows differ by an order of magnitude across them.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub compaction_ratio: Option<f64>,
}

impl ProviderConfig {
    pub fn bearer_key_chain(&self) -> Vec<String> {
        if !self.api_keys.is_empty() {
            return self.api_keys.clone();
        }
        self.api_key.clone().into_iter().collect()
    }
}

#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct ProviderCustomHeader {
    pub header: String,
    pub value: String,
}

/// Every connection uses the same handler, so that progress notifications are
/// observed at all -- rmcp drops them on the `()` handler. Desktop-only: the
/// handler emits through a Tauri `AppHandle`, which the CLI build doesn't have.
#[cfg(not(feature = "cli"))]
pub type RunningMcpService = RunningService<RoleClient, JanClientHandler>;
#[cfg(not(feature = "cli"))]
pub type SharedMcpServers = Arc<Mutex<HashMap<String, RunningMcpService>>>;

/// CLI's MCP client has no progress-notification sink, so it can use either
/// the plain handler or one seeded with an `initialize` response.
#[cfg(feature = "cli")]
pub enum RunningServiceEnum {
    NoInit(RunningService<RoleClient, ()>),
    WithInit(RunningService<RoleClient, InitializeRequestParams>),
}
#[cfg(feature = "cli")]
pub type SharedMcpServers = Arc<Mutex<HashMap<String, RunningServiceEnum>>>;

#[cfg(feature = "cli")]
impl RunningServiceEnum {
    pub async fn list_all_tools(&self) -> Result<Vec<Tool>, ServiceError> {
        match self {
            Self::NoInit(s) => s.list_all_tools().await,
            Self::WithInit(s) => s.list_all_tools().await,
        }
    }
    pub async fn call_tool(
        &self,
        params: CallToolRequestParams,
    ) -> Result<CallToolResult, ServiceError> {
        match self {
            Self::NoInit(s) => s.call_tool(params).await,
            Self::WithInit(s) => s.call_tool(params).await,
        }
    }

    /// The peer's handshake info: what the server said it implements. Read by
    /// the `/mcp` detail screen for its capabilities and version lines.
    pub fn peer_info(&self) -> Option<rmcp::model::ServerPeerInfo> {
        match self {
            Self::NoInit(s) => s.peer_info().map(|p| (*p).clone()),
            Self::WithInit(s) => s.peer_info().map(|p| (*p).clone()),
        }
    }
}

/// Shared desktop application state owned by Tauri. The CLI builds its
/// subsystems (MCP map, provider configs) directly instead.
#[cfg(not(feature = "cli"))]
pub struct AppState {
    pub app_token: Option<String>,
    pub mcp_servers: SharedMcpServers,
    pub download_manager: Arc<Mutex<DownloadManagerState>>,
    pub mcp_active_servers: Arc<Mutex<HashMap<String, serde_json::Value>>>,
    pub server_handle: Arc<Mutex<Option<ServerHandle>>>,
    pub tool_call_cancellations: Arc<Mutex<HashMap<String, oneshot::Sender<()>>>>,
    pub mcp_settings: Arc<Mutex<McpSettings>>,
    pub mcp_shutdown_in_progress: Arc<Mutex<bool>>,
    pub mcp_monitoring_tasks: Arc<Mutex<HashMap<String, tauri::async_runtime::JoinHandle<()>>>>,
    /// Names of MCP servers whose initial start is currently in flight. Guards
    /// against a server being `serve()`'d twice (e.g. boot startup racing a
    /// frontend activation), which sends duplicate `initialize` requests.
    pub mcp_starting: Arc<Mutex<HashSet<String>>>,
    pub background_cleanup_handle: Arc<Mutex<Option<tokio::task::JoinHandle<()>>>>,
    pub mcp_server_pids: Arc<Mutex<HashMap<String, u32>>>,
    /// Remote provider configurations (e.g., Anthropic, OpenAI, etc.)
    pub provider_configs: Arc<Mutex<HashMap<String, ProviderConfig>>>,
    /// Per-model sampling defaults the API server injects when the caller omits
    /// them (MLX path; llamacpp uses the router preset instead). Keyed by model
    /// id; values are objects already in the target's request-body key form.
    pub model_param_defaults: Arc<Mutex<HashMap<String, serde_json::Value>>>,
    /// Wakes up MCP monitors to trigger an immediate health check + reconnect
    pub mcp_reconnect_notify: Arc<Notify>,
    /// Last successful tool listing per enabled server, served when a server
    /// is transiently disconnected so its schema stays present and stable in
    /// the prompt instead of disappearing/reappearing across reconnects.
    /// Cleared only on explicit user deactivation, never on a transient
    /// list-tools failure.
    pub mcp_last_known_tools: Arc<Mutex<HashMap<String, Vec<ToolWithServer>>>>,
}

#[cfg(not(feature = "cli"))]
impl Default for AppState {
    fn default() -> Self {
        Self {
            app_token: None,
            mcp_servers: Default::default(),
            download_manager: Default::default(),
            mcp_active_servers: Default::default(),
            server_handle: Default::default(),
            tool_call_cancellations: Default::default(),
            mcp_settings: Default::default(),
            mcp_shutdown_in_progress: Default::default(),
            mcp_monitoring_tasks: Default::default(),
            mcp_starting: Default::default(),
            background_cleanup_handle: Default::default(),
            mcp_server_pids: Default::default(),
            provider_configs: Default::default(),
            model_param_defaults: Default::default(),
            mcp_reconnect_notify: Arc::new(Notify::new()),
            mcp_last_known_tools: Default::default(),
        }
    }
}