use std::{
collections::BTreeSet,
io,
path::{Path, PathBuf},
sync::{
atomic::{AtomicU64, Ordering},
Arc,
},
time::{Duration, Instant},
};
use rho_protocol::methods::*;
use rho_protocol::{
BuildId, ConfigWatch, JobWatch, LoginStream, ModelWatch, ProtocolVersion, RestartCost,
RpcError, Service, SettingsService, Subscription, PROTOCOL_VERSION,
};
use rho_providers::credentials::CredentialStoreBackend;
use crate::{
app::pull_requests::unix_ms,
daemon::{DaemonLock, Ending, Shutdown},
};
mod auth;
mod compression;
mod configured;
mod hooks_config;
mod hooks_file;
mod hooks_store;
mod job_feed;
mod jobs;
mod logins;
mod machine;
mod machine_forge;
mod machine_fs;
mod machine_git;
#[cfg(test)]
mod machine_test_support;
mod machine_update;
mod mcp_probe;
mod mcp_secrets;
mod models;
mod plugins;
mod providers;
mod runtimes;
mod sessions;
mod settings;
mod settings_service;
mod store;
mod subagents;
mod sync;
mod upgrade;
mod wire;
use job_feed::JobFeed;
use jobs::{JobRegistry, JobStore};
use logins::Logins;
use machine_update::Daemon;
use sessions::{Pass, Prune, Sessions};
pub(super) use sessions::{DAEMON_COMMANDS, UNLOAD_IDLE_AFTER};
use upgrade::Upgrades;
const WORKTREE_PRUNE_INTERVAL: Duration = Duration::from_secs(24 * 60 * 60);
const WORKTREE_PRUNE_AFTER_START: Duration = Duration::from_secs(60);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Startup {
Fresh,
RestartedInPlace,
}
pub(super) struct JobRecords {
jobs: Arc<JobRegistry>,
interrupted_by_restart: Vec<rho_sdk::SessionId>,
}
impl JobRecords {
pub(super) fn open(_held: &DaemonLock, state_dir: &Path, startup: Startup) -> io::Result<Self> {
let store = JobStore::open(state_dir)?;
let jobs = JobRegistry::open(store);
let marked = jobs.take_restart_interrupted();
let interrupted_by_restart = match startup {
Startup::Fresh => Vec::new(),
Startup::RestartedInPlace => marked,
};
Ok(Self {
jobs: Arc::new(jobs),
interrupted_by_restart,
})
}
}
pub(super) struct DaemonHost {
socket: PathBuf,
started_at: u64,
started: Instant,
shutdown: Shutdown,
jobs: Arc<JobRegistry>,
job_feed: Arc<JobFeed>,
sessions: Arc<Sessions>,
logins: Arc<Logins>,
plugins: plugins::Plugins,
hooks_store: hooks_store::HooksStore,
upgrades: Arc<Upgrades>,
clients: AtomicU64,
store_environment: Option<CredentialStoreBackend>,
sync: sync::SecretSync,
machine: machine::Machine,
}
fn features() -> BTreeSet<DaemonFeature> {
let mut features = BTreeSet::from([
DaemonFeature::DaemonUpdate,
DaemonFeature::DeferredToolOutput,
DaemonFeature::EntryCursors,
DaemonFeature::Host,
DaemonFeature::HostForge,
DaemonFeature::HostFs,
DaemonFeature::HostGit,
DaemonFeature::JobChanges,
DaemonFeature::PromptRetries,
DaemonFeature::ReplayWindows,
DaemonFeature::SetupModels,
DaemonFeature::StartedSessionRuntimes,
DaemonFeature::SteerAttachments,
DaemonFeature::StoppingNotice,
DaemonFeature::SystemPrompts,
DaemonFeature::ToldStarter,
]);
if cfg!(feature = "browser") {
features.insert(DaemonFeature::Browser);
}
features
}
impl DaemonHost {
pub(super) fn new(
JobRecords {
jobs,
interrupted_by_restart,
}: JobRecords,
rho_home: &Path,
socket: PathBuf,
started_at: u64,
shutdown: Shutdown,
store_environment: Option<CredentialStoreBackend>,
) -> Self {
let forge = Arc::new(crate::app::pull_requests::GhCli::default());
let sessions = Sessions::new(Arc::clone(&jobs), rho_home, forge);
sessions.resume_after_restart(interrupted_by_restart);
let logins = Arc::new(Logins::new());
let upgrades = Arc::new(Upgrades::default());
let daemon = Daemon {
in_progress: {
let (jobs, logins, sessions) = (
Arc::clone(&jobs),
Arc::clone(&logins),
Arc::clone(&sessions),
);
Arc::new(move || in_progress(&jobs, &logins, &sessions))
},
replaced: {
let upgrades = Arc::clone(&upgrades);
Arc::new(move || upgrades.pending())
},
shutdown: shutdown.clone(),
};
Self {
socket,
started_at,
started: Instant::now(),
job_feed: JobFeed::new(Arc::clone(&jobs), Arc::clone(&sessions)),
sessions,
logins,
plugins: plugins::Plugins::new(rho_home.to_path_buf()),
hooks_store: hooks_store::HooksStore::new(rho_home),
upgrades,
clients: AtomicU64::new(0),
shutdown,
jobs,
store_environment,
sync: sync::SecretSync::default(),
machine: machine::Machine::new(rho_home, daemon),
}
}
pub(super) fn begin_stop(&self) {
self.begin(Ending::Stop);
}
pub(super) fn begin_restart(&self) {
self.begin(Ending::Restart);
}
fn begin_replace(&self) {
self.begin(Ending::Replace);
}
fn begin(&self, ending: Ending) {
self.shutdown.request(ending, |ending| {
self.jobs.stopping_for(ending);
self.sessions.begin_stop(match ending {
Ending::Stop | Ending::Replace => DetachReason::DaemonStopping,
Ending::Restart => DetachReason::Restarting,
});
});
}
fn in_progress(&self) -> u64 {
in_progress(&self.jobs, &self.logins, &self.sessions)
}
fn restart_cost(&self) -> RestartCost {
RestartCost {
in_progress: self.in_progress(),
clients: self.clients.load(Ordering::Relaxed),
}
}
pub(super) fn stopping(&self) -> bool {
self.shutdown.is_requested()
}
pub(super) async fn unload_idle_sessions(&self, grace: Duration) {
self.sessions.unload_idle(grace).await;
}
pub(super) async fn sweep_sync_journal(&self) {
self.sync.sweep_journal().await;
}
pub(super) async fn poll_pull_requests(&self) {
self.sessions.poll_pull_requests().await;
}
pub(super) async fn prune_worktrees_daily(&self) {
let mut wait = WORKTREE_PRUNE_AFTER_START;
loop {
tokio::select! {
() = tokio::time::sleep(wait) => {}
() = self.shutdown.requested() => return,
}
let pass = Pass {
prune: Prune::Daily,
measure: false,
};
self.sessions.prune_worktrees(pass).await;
wait = WORKTREE_PRUNE_INTERVAL;
}
}
pub(super) async fn stop_sessions(&self, stop_requested: tokio::time::Instant) -> bool {
self.sessions.stop(stop_requested).await
}
}
fn work_outside_jobs(logins: &Logins, sessions: &Sessions) -> usize {
logins.under_way() + sessions.upgrade_blockers()
}
fn in_progress(jobs: &JobRegistry, logins: &Logins, sessions: &Sessions) -> u64 {
u64::try_from(jobs.in_progress() + work_outside_jobs(logins, sessions)).unwrap_or(u64::MAX)
}
impl Service for DaemonHost {
async fn status(&self) -> DaemonStatus {
let in_progress = self.jobs.in_progress();
DaemonStatus {
pid: std::process::id(),
version: env!("CARGO_PKG_VERSION").to_owned(),
protocol: PROTOCOL_VERSION,
started_at: self.started_at,
uptime_secs: self.started.elapsed().as_secs(),
jobs: u64::try_from(in_progress).unwrap_or(u64::MAX),
in_progress: self.in_progress(),
socket: self.socket.clone(),
credential_store: store::status(self.store_environment).await,
upgrade: self.upgrades.pending().map(|version| PendingUpgrade {
version,
waiting_for: self.in_progress(),
}),
}
}
async fn answer_status(&self) -> DaemonStatusAnswer {
let others = self.clients.load(Ordering::Relaxed).saturating_sub(1);
DaemonStatusAnswer::new(self.status().await, Some(others))
}
fn hello(&self, client: &ClientInfo) {
self.clients.fetch_add(1, Ordering::Relaxed);
self.upgrades.heard(client);
}
fn left(&self) {
self.clients.fetch_sub(1, Ordering::Relaxed);
}
fn host(&self) -> &impl rho_protocol::HostService {
&self.machine
}
fn left_connection(&self, connection: rho_protocol::ConnectionId) {
self.left();
#[cfg(feature = "browser")]
self.sessions.browser_connection_left(connection);
#[cfg(not(feature = "browser"))]
let _ = connection;
}
fn refused_newer(&self, client: ProtocolVersion) -> RestartCost {
let cost = self.restart_cost();
tracing::info!(
%client,
in_progress = cost.in_progress,
clients = cost.clients,
may_replace = cost.is_free(),
"refused a client of a newer protocol"
);
cost
}
fn skewed(&self, client: &ClientInfo, build: &BuildId) -> RestartCost {
let cost = self.restart_cost();
tracing::info!(
client = %client.name,
version = %client.version,
%build,
in_progress = cost.in_progress,
clients = cost.clients,
"accepted a client of another build"
);
cost
}
fn compression(&self) -> &impl rho_protocol::CompressionHooks {
self
}
fn session_order(&self) -> &impl rho_protocol::SessionOrder {
&*self.sessions
}
async fn stop(&self) {
tracing::info!("stop requested");
self.begin_stop();
}
async fn restart(&self) {
tracing::info!("restart requested");
self.begin_restart();
}
async fn replace(&self, _: ReplaceParams) -> Result<ReplaceResponse, RpcError> {
tracing::info!("replacement requested");
self.begin_replace();
Ok(ReplaceResponse::default())
}
async fn new_session_query(
&self,
query: rho_protocol::SessionNewQuery,
) -> Result<SessionNewResponse, RpcError> {
self.sessions.open_new(query).await
}
async fn list_runtimes(
&self,
params: rho_protocol::RuntimeListParams,
) -> Result<rho_protocol::RuntimeListResponse, RpcError> {
runtimes::list(params)
}
async fn list_providers(
&self,
params: ProviderListParams,
) -> Result<ProviderListResponse, RpcError> {
providers::list(params).await
}
async fn fork_session(
&self,
params: SessionForkParams,
) -> Result<SessionForkResponse, RpcError> {
self.sessions.fork(params).await
}
async fn answer_prompt(
&self,
params: SessionPromptParams,
) -> Result<SessionPromptAnswer, RpcError> {
self.sessions.prompt(params).await
}
fn features(&self) -> BTreeSet<DaemonFeature> {
features()
}
fn ending(&self) -> Option<DaemonEnding> {
Some(match self.shutdown.ending() {
Ending::Stop => DaemonEnding::Stop,
Ending::Replace => DaemonEnding::Replace,
Ending::Restart => match self.upgrades.pending() {
Some(version) => DaemonEnding::upgrade(version),
None => DaemonEnding::Restart,
},
})
}
async fn prompt_sent(
&self,
params: SessionPromptSentParams,
) -> Result<SessionPromptSentResponse, RpcError> {
self.sessions.prompt_sent(params).await
}
async fn cancel_session(
&self,
params: SessionCancelParams,
) -> Result<SessionCancelResponse, RpcError> {
self.sessions.cancel(params).await
}
async fn steer_session_query(
&self,
query: rho_protocol::SessionSteerQuery,
) -> Result<SessionSteerResponse, RpcError> {
self.sessions.steer(query).await
}
async fn unsteer_session(
&self,
params: SessionUnsteerParams,
) -> Result<SessionUnsteerResponse, RpcError> {
self.sessions.unsteer(params).await
}
async fn answer_session(
&self,
params: SessionAnswerParams,
) -> Result<SessionAnswerResponse, RpcError> {
self.sessions.answer(params).await
}
async fn answer_question(
&self,
params: rho_protocol::SessionAnswerQuestionParams,
) -> Result<rho_protocol::SessionAnswerQuestionResponse, RpcError> {
self.sessions.answer_question(params).await
}
async fn answer_question_by_agent(
&self,
params: rho_protocol::SessionAnswerQuestionByAgentParams,
) -> Result<rho_protocol::SessionAnswerQuestionByAgentResponse, RpcError> {
self.sessions.answer_question_by_agent(params).await
}
async fn surface_action(
&self,
params: SessionSurfaceActionParams,
) -> Result<SessionSurfaceActionResponse, RpcError> {
self.sessions.surface_action(params).await
}
async fn hold_session(
&self,
params: SessionHoldParams,
) -> Result<SessionHoldResponse, RpcError> {
self.sessions.hold(params).await
}
async fn session_processes(
&self,
params: rho_protocol::SessionProcessesParams,
) -> Result<rho_protocol::SessionProcessesResponse, RpcError> {
self.sessions.processes(params).await
}
async fn answer_session_background_list(
&self,
) -> Result<rho_protocol::SessionBackgroundListAnswer, RpcError> {
Ok(self.sessions.background_list())
}
async fn session_background_stop(
&self,
params: rho_protocol::SessionBackgroundStopParams,
) -> Result<rho_protocol::SessionBackgroundStopResponse, RpcError> {
self.sessions.background_stop(params).await
}
async fn session_background_hold(
&self,
params: rho_protocol::SessionBackgroundHoldParams,
) -> Result<rho_protocol::SessionBackgroundHoldResponse, RpcError> {
self.sessions.background_hold(params).await
}
async fn list_session_pull_requests(
&self,
params: rho_protocol::SessionPullRequestListParams,
) -> Result<rho_protocol::SessionPullRequestListResponse, RpcError> {
self.sessions.pull_request_list(params, unix_ms()).await
}
async fn show_session_pull_request(
&self,
params: rho_protocol::SessionPullRequestShowParams,
) -> Result<rho_protocol::SessionPullRequestShowResponse, RpcError> {
self.sessions.pull_request_show(params, unix_ms()).await
}
async fn link_session_pull_request(
&self,
params: rho_protocol::SessionPullRequestLinkParams,
) -> Result<rho_protocol::SessionPullRequestLinkResponse, RpcError> {
self.sessions.pull_request_link(params, unix_ms()).await
}
async fn unlink_session_pull_request(
&self,
params: rho_protocol::SessionPullRequestUnlinkParams,
) -> Result<rho_protocol::SessionPullRequestUnlinkResponse, RpcError> {
self.sessions.pull_request_unlink(params, unix_ms()).await
}
async fn answer_session_mcp(
&self,
params: rho_protocol::SessionMcpParams,
) -> Result<rho_protocol::SessionMcpInventoryAnswer, RpcError> {
self.sessions.mcp(params).await
}
async fn session_mcp_catalog(
&self,
params: rho_protocol::SessionMcpCatalogParams,
) -> Result<rho_protocol::SessionMcpCatalog, RpcError> {
self.sessions.mcp_catalog(params).await
}
async fn session_mcp_resource(
&self,
params: rho_protocol::SessionMcpResourceParams,
) -> Result<rho_protocol::SessionMcpResourceResponse, RpcError> {
self.sessions.mcp_resource(params).await
}
async fn session_mcp_complete(
&self,
params: rho_protocol::SessionMcpCompleteParams,
) -> Result<rho_protocol::SessionMcpCompleteResponse, RpcError> {
self.sessions.mcp_complete(params).await
}
async fn answer_session_mcp_reload(
&self,
params: rho_protocol::SessionMcpReloadParams,
) -> Result<rho_protocol::SessionMcpReloadAnswer, RpcError> {
self.sessions.reload_mcp(params).await
}
async fn inspect_session(
&self,
params: rho_protocol::SessionInspectParams,
) -> Result<rho_protocol::SessionInspectResponse, RpcError> {
self.sessions.inspect(params).await
}
async fn report_session(
&self,
params: rho_protocol::SessionReportParams,
) -> Result<rho_protocol::SessionReportResponse, RpcError> {
self.sessions.report(params).await
}
async fn session_tree(
&self,
params: rho_protocol::SessionTreeParams,
) -> Result<rho_protocol::SessionTreeResponse, RpcError> {
self.sessions.tree(params).await
}
async fn preview_session_rewind(
&self,
params: rho_protocol::SessionRewindPreviewParams,
) -> Result<rho_protocol::SessionRewindPreviewResponse, RpcError> {
self.sessions.rewind_preview(params).await
}
async fn rewind_session(
&self,
params: rho_protocol::SessionRewindParams,
) -> Result<rho_protocol::SessionRewindResponse, RpcError> {
self.sessions.rewind(params).await
}
async fn reload_session_hooks(
&self,
params: rho_protocol::SessionHooksReloadParams,
) -> Result<rho_protocol::SessionHooksReloadResponse, RpcError> {
self.sessions.reload_hooks(params).await
}
async fn configure_session(
&self,
params: SessionConfigureParams,
) -> Result<SessionConfigureResponse, RpcError> {
self.sessions.configure(params).await
}
async fn attach_session(
&self,
params: SessionAttachParams,
) -> Result<(SessionAttachResponse, Subscription), RpcError> {
let (answer, subscription) = self.sessions.attach(params.into()).await?;
Ok((answer.response, subscription))
}
async fn attach_session_query(
&self,
query: SessionAttachQuery,
) -> Result<(SessionAttachAnswer, Subscription), RpcError> {
self.sessions.attach(query).await
}
async fn observe_session(
&self,
params: SessionObserveParams,
) -> Result<(SessionAttachResponse, Subscription), RpcError> {
let (answer, subscription) = self.sessions.observe(params.into()).await?;
Ok((answer.response, subscription))
}
async fn observe_session_query(
&self,
query: SessionObserveQuery,
) -> Result<(SessionAttachAnswer, Subscription), RpcError> {
self.sessions.observe(query).await
}
async fn session_history(
&self,
params: SessionHistoryParams,
) -> Result<SessionHistoryResponse, RpcError> {
self.sessions.history(params).await
}
async fn session_tool_output(
&self,
params: SessionToolOutputParams,
) -> Result<SessionToolOutputResponse, RpcError> {
self.sessions.tool_output(params).await
}
async fn list_sessions(
&self,
params: SessionListParams,
) -> Result<SessionListResponse, RpcError> {
self.sessions.list(params).await
}
async fn list_sessions_detailed(
&self,
params: SessionListParams,
) -> Result<SessionListDetailedResponse, RpcError> {
self.sessions.list_detailed(params).await
}
async fn list_owned_sessions(
&self,
params: SessionOwnedParams,
) -> Result<SessionOwnedResponse, RpcError> {
self.sessions.list_owned(params).await
}
async fn search_sessions(
&self,
params: SessionSearchParams,
) -> Result<SessionSearchResponse, RpcError> {
self.sessions.search(params).await
}
async fn rename_session(
&self,
params: SessionRenameParams,
) -> Result<SessionRenameResponse, RpcError> {
self.sessions.rename(params).await
}
async fn mark_session(
&self,
params: SessionMarkParams,
) -> Result<SessionMarkResponse, RpcError> {
self.sessions.mark(params).await
}
async fn delete_session(
&self,
params: SessionDeleteParams,
) -> Result<SessionDeleteResponse, RpcError> {
self.sessions.delete(params).await
}
async fn list_jobs(&self) -> JobListResponse {
job_feed::list(&self.jobs, &self.sessions)
}
async fn watch_jobs(&self) -> Option<JobWatch> {
Some(self.job_feed.follow())
}
async fn prune_worktrees(
&self,
params: WorktreePruneParams,
) -> Result<WorktreePruneResponse, RpcError> {
let WorktreePruneParams { dry_run, measure } = params;
let prune = match dry_run {
true => Prune::DryRun,
false => Prune::Now,
};
let pass = Pass {
prune,
measure: measure && dry_run,
};
Ok(WorktreePruneResponse {
worktrees: self.sessions.prune_worktrees(pass).await,
})
}
async fn save_auth_key(&self, params: AuthKeyParams) -> Result<AuthKeyResponse, RpcError> {
let saved = auth::save_key(params).await?;
auth::credentials_changed(&self.sessions).await;
Ok(saved)
}
async fn logout_auth(&self, params: AuthLogoutParams) -> Result<AuthLogoutResponse, RpcError> {
let logged_out = auth::logout(params).await?;
auth::credentials_changed(&self.sessions).await;
Ok(logged_out)
}
async fn list_auths(&self, params: AuthListParams) -> Result<AuthListResponse, RpcError> {
auth::list(params).await
}
async fn login(
&self,
params: AuthLoginParams,
) -> Result<(AuthLoginResponse, LoginStream), RpcError> {
self.logins.start(params, Arc::clone(&self.sessions)).await
}
async fn cancel_login(
&self,
params: AuthLoginCancelParams,
) -> Result<AuthLoginCancelResponse, RpcError> {
self.logins.cancel(params)
}
async fn choose_store(
&self,
params: AuthChooseStoreParams,
) -> Result<AuthChooseStoreResponse, RpcError> {
store::choose(params, self.store_environment, &self.sessions).await
}
#[cfg(feature = "browser")]
async fn watch_browser(
&self,
params: rho_protocol::BrowserWatchParams,
) -> Result<
(
rho_protocol::BrowserWatchResponse,
rho_protocol::BrowserFrames,
),
RpcError,
> {
self.sessions.watch_browser(params).await
}
#[cfg(feature = "browser")]
async fn ack_browser_frame(
&self,
params: rho_protocol::BrowserFrameAckParams,
) -> Result<rho_protocol::BrowserFrameAckResponse, RpcError> {
self.sessions.ack_browser_frame(params)
}
#[cfg(feature = "browser")]
async fn unwatch_browser(
&self,
params: rho_protocol::BrowserUnwatchParams,
) -> Result<rho_protocol::BrowserUnwatchResponse, RpcError> {
Ok(self.sessions.unwatch_browser(params))
}
#[cfg(feature = "browser")]
async fn control_browser_from(
&self,
connection: rho_protocol::ConnectionId,
params: rho_protocol::BrowserControlParams,
) -> Result<rho_protocol::BrowserControlResponse, RpcError> {
self.sessions.control_browser(connection, params).await
}
#[cfg(feature = "browser")]
async fn browser_input(
&self,
params: rho_protocol::BrowserInputParams,
) -> Result<rho_protocol::BrowserInputResponse, RpcError> {
self.sessions.browser_input(params).await
}
#[cfg(feature = "browser")]
async fn navigate_browser(
&self,
params: rho_protocol::BrowserNavigateParams,
) -> Result<rho_protocol::BrowserNavigateResponse, RpcError> {
self.sessions.navigate_browser(params).await
}
#[cfg(feature = "browser")]
async fn browser_tab(
&self,
params: rho_protocol::BrowserTabParams,
) -> Result<rho_protocol::BrowserTabResponse, RpcError> {
self.sessions.browser_tab(params).await
}
#[cfg(feature = "browser")]
async fn browser_viewport(
&self,
params: rho_protocol::BrowserViewportParams,
) -> Result<rho_protocol::BrowserViewportResponse, RpcError> {
self.sessions.browser_viewport(params).await
}
#[cfg(feature = "browser")]
async fn close_browser(
&self,
params: rho_protocol::BrowserCloseParams,
) -> Result<rho_protocol::BrowserCloseResponse, RpcError> {
self.sessions.close_browser(params).await
}
}
#[cfg(test)]
#[path = "mod_tests.rs"]
mod tests;