Skip to main content

infinity_daemon/
lib.rs

1pub mod client_handler;
2pub mod config;
3pub mod ids;
4pub mod mcp_proxy;
5pub mod memory_store;
6pub mod migrate;
7pub mod models;
8pub mod rap_callback;
9pub mod rap_servers;
10pub mod remote;
11pub mod session;
12pub mod session_store;
13pub mod set_title_tool;
14pub mod web_assets;
15pub mod ws_handler;
16
17use infinity_protocol::socket_path;
18use tokio::net::{TcpListener, UnixListener};
19use tracing_subscriber::EnvFilter;
20
21/// Line printed to stdout when `run_daemon` is called with
22/// `announce_ready = true`, once initialization has succeeded and the daemon
23/// is serving. A supervising process (the CLI auto-launch) races this line
24/// against daemon exit to detect startup failures. It must remain the
25/// daemon's only stdout output.
26pub const DAEMON_READY_LINE: &str = "infinity-daemon ready";
27
28/// Launch a fully-initialized session manager: bind the RAP callback
29/// listener, build the [`session::SessionManager`] with the listener's
30/// callback URL, and start serving callbacks into it. This is the shared
31/// startup path for the daemon and the CLI's direct (daemonless) mode.
32pub async fn launch_session_manager(
33    state_dir: std::path::PathBuf,
34) -> Result<session::SharedSessionManager, Box<dyn std::error::Error + Send + Sync>> {
35    let bridge = infinity_rap_bridge::RapCallbackBridge::bind().await?;
36    let session_manager =
37        session::SessionManager::new(state_dir, bridge.callback_url().to_owned()).await?;
38    Ok(rap_callback::serve_callbacks(bridge, session_manager))
39}
40
41/// Run the daemon until it receives a shutdown signal. When `announce_ready`
42/// is true, prints [`DAEMON_READY_LINE`] to stdout after all initialization
43/// (including the session manager and its model providers) has succeeded.
44pub async fn run_daemon(
45    announce_ready: bool,
46) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
47    let state_dir = infinity_protocol::state_dir();
48    std::fs::create_dir_all(&state_dir)?;
49
50    let log_file = std::fs::File::create(state_dir.join("daemon.log"))?;
51    tracing_subscriber::fmt()
52        .with_env_filter(EnvFilter::from_default_env())
53        .with_writer(std::sync::Mutex::new(log_file))
54        .with_ansi(false)
55        .init();
56
57    let sock_path = socket_path();
58    if sock_path.exists() {
59        std::fs::remove_file(&sock_path)?;
60    }
61
62    let listener = UnixListener::bind(&sock_path)?; // TODO(shadaj): do we also need to lock the file?
63    tracing::info!("daemon listening on {}", sock_path.display());
64
65    let pid_path = infinity_protocol::pid_path();
66    std::fs::write(&pid_path, std::process::id().to_string())?;
67
68    let session_manager = launch_session_manager(infinity_protocol::state_dir())
69        .await
70        .map_err(|e| format!("Failed to launch session manager: {e}"))?;
71    tracing::info!("shared callback server started");
72
73    // Initialize remote daemon connections
74    let remote_configs = remote::load_remotes_config();
75    if !remote_configs.is_empty() {
76        tracing::info!("loaded {} remote daemon config(s)", remote_configs.len());
77        session_manager.lock().await.init_remotes(remote_configs);
78    }
79
80    // Start WebSocket server
81    let ws_port: u16 = std::env::var("INFINITY_WS_PORT")
82        .ok()
83        .and_then(|s| s.parse().ok())
84        .unwrap_or(8080);
85    let ws_bind_addr = std::env::var("INFINITY_WS_BIND").unwrap_or_else(|_| "127.0.0.1".to_owned());
86    let ws_listener = TcpListener::bind((&*ws_bind_addr, ws_port)).await?;
87    tracing::info!("websocket server listening on {ws_bind_addr}:{ws_port}");
88
89    let ws_accept = ws_handler::serve(ws_listener, session_manager.clone());
90
91    let shutdown = async {
92        let mut sigint = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::interrupt())
93            .expect("failed to register SIGINT handler");
94        let mut sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
95            .expect("failed to register SIGTERM handler");
96        tokio::select! {
97            _ = sigint.recv() => {}
98            _ = sigterm.recv() => {}
99        }
100        tracing::info!("received shutdown signal");
101    };
102
103    if announce_ready {
104        println!("{DAEMON_READY_LINE}");
105    }
106
107    tokio::select! {
108        _ = async {
109            loop {
110                match listener.accept().await {
111                    Ok((stream, _)) => {
112                        let mgr = session_manager.clone();
113                        tokio::task::spawn_local(rap_protocol::log_panic("client_handler", client_handler::handle_client(stream, mgr)));
114                    }
115                    Err(e) => {
116                        tracing::warn!("accept error: {e}");
117                    }
118                }
119            }
120        } => {}
121        _ = ws_accept => {}
122        _ = shutdown => {}
123    }
124
125    let _ = std::fs::remove_file(&sock_path);
126    let _ = std::fs::remove_file(infinity_protocol::pid_path());
127
128    // Stop every booted RAP server; sessions themselves need no teardown
129    // (their state is already durable, and they resume on the next input
130    // after the daemon restarts).
131    let mgr = session_manager.lock().await;
132    mgr.rap_manager.shutdown_all().await;
133
134    tracing::info!("daemon shut down");
135    Ok(())
136}