use std::{
io,
path::{Path, PathBuf},
sync::{
atomic::{AtomicU64, Ordering},
Arc,
},
time::{Duration, Instant},
};
use rho_protocol::{
AuthChooseStoreParams, AuthChooseStoreResponse, AuthKeyParams, AuthKeyResponse, AuthListParams,
AuthListResponse, AuthLoginCancelParams, AuthLoginCancelResponse, AuthLoginParams,
AuthLoginResponse, AuthLogoutParams, AuthLogoutResponse, BuildId, ClientInfo, ConfigGetParams,
ConfigRegisterParams, ConfigRegisterResponse, ConfigSchema, ConfigSetParams, ConfigSetResponse,
ConfigWatch, DaemonStatus, DetachReason, JobListResponse, LoginStream, ModelListParams,
ModelRefreshParams, ModelRefreshResponse, ModelWatch, PendingUpgrade, ProtocolVersion,
RestartCost, RpcError, Service, SessionAnswerParams, SessionAnswerResponse,
SessionAttachParams, SessionAttachResponse, SessionCancelParams, SessionCancelResponse,
SessionConfigureParams, SessionConfigureResponse, SessionDeleteParams, SessionDeleteResponse,
SessionForkParams, SessionForkResponse, SessionHoldParams, SessionHoldResponse,
SessionListDetailedResponse, SessionListParams, SessionListResponse, SessionMarkParams,
SessionMarkResponse, SessionNewParams, SessionNewResponse, SessionObserveParams,
SessionPromptParams, SessionPromptResponse, SessionRenameParams, SessionRenameResponse,
SessionSteerParams, SessionSteerResponse, SessionSurfaceActionParams,
SessionSurfaceActionResponse, SessionUnsteerParams, SessionUnsteerResponse, SettingsService,
Subscription, WorktreePruneParams, WorktreePruneResponse, PROTOCOL_VERSION,
};
use rho_providers::credentials::CredentialStoreBackend;
use crate::{
app::pull_requests::unix_ms,
daemon::{DaemonLock, Ending, Executable, Shutdown},
};
mod auth;
mod jobs;
mod logins;
mod models;
mod sessions;
mod settings;
mod store;
mod subagents;
mod upgrade;
mod wire;
use jobs::{JobRegistry, JobStore, JobSubject};
use logins::Logins;
use sessions::{worktree_stale, Pass, Prune, Sessions};
pub(super) use sessions::{DAEMON_COMMANDS, UNLOAD_IDLE_AFTER};
use upgrade::UPGRADE_CHECK_INTERVAL;
use upgrade::{Check, Upgrades, Watch};
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>,
sessions: Arc<Sessions>,
logins: Arc<Logins>,
upgrades: Upgrades,
clients: AtomicU64,
store_environment: Option<CredentialStoreBackend>,
}
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);
Self {
socket,
started_at,
started: Instant::now(),
sessions,
logins: Arc::new(Logins::new()),
upgrades: Upgrades::default(),
clients: AtomicU64::new(0),
shutdown,
jobs,
store_environment,
}
}
pub(super) fn begin_stop(&self) {
self.begin(Ending::Stop);
}
pub(super) fn begin_restart(&self) {
self.begin(Ending::Restart);
}
fn begin(&self, ending: Ending) {
self.shutdown.request(ending, |ending| {
self.jobs.stopping_for(ending);
self.sessions.begin_stop(match ending {
Ending::Stop => DetachReason::DaemonStopping,
Ending::Restart => DetachReason::Restarting,
});
});
}
fn claim_idle(&self) -> bool {
let Some(idle) = self.jobs.idle() else {
return false;
};
self.work_outside_jobs() == 0 && self.jobs.close_if_still(idle)
}
fn work_outside_jobs(&self) -> usize {
self.logins.under_way() + self.sessions.upgrade_blockers()
}
fn in_progress(&self) -> u64 {
u64::try_from(self.jobs.in_progress() + self.work_outside_jobs()).unwrap_or(u64::MAX)
}
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 upgrade_when_replaced(&self, executable: &Executable) {
let mut checks = tokio::time::interval(UPGRADE_CHECK_INTERVAL);
checks.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
let mut watch = Watch::default();
loop {
tokio::select! {
() = self.upgrades.next_check(&mut checks) => {}
() = self.shutdown.requested() => return,
}
if self.upgrades.check(executable, &mut watch).await == Check::Upgrade
&& self.claim_idle()
{
tracing::info!("upgrading in place");
self.begin_restart();
return;
}
}
}
pub(super) async fn unload_idle_sessions(&self, grace: Duration) {
self.sessions.unload_idle(grace).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
}
}
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(),
}),
}
}
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 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
}
async fn stop(&self) {
tracing::info!("stop requested");
self.begin_stop();
}
async fn restart(&self) {
tracing::info!("restart requested");
self.begin_restart();
}
async fn new_session(&self, params: SessionNewParams) -> Result<SessionNewResponse, RpcError> {
self.sessions.open_new(params).await
}
async fn fork_session(
&self,
params: SessionForkParams,
) -> Result<SessionForkResponse, RpcError> {
self.sessions.fork(params).await
}
async fn prompt_session(
&self,
params: SessionPromptParams,
) -> Result<SessionPromptResponse, RpcError> {
self.sessions.prompt(params).await
}
async fn cancel_session(
&self,
params: SessionCancelParams,
) -> Result<SessionCancelResponse, RpcError> {
self.sessions.cancel(params).await
}
async fn steer_session(
&self,
params: SessionSteerParams,
) -> Result<SessionSteerResponse, RpcError> {
self.sessions.steer(params).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 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 list_session_background(
&self,
) -> Result<rho_protocol::SessionBackgroundListResponse, 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 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 session_mcp(
&self,
params: rho_protocol::SessionMcpParams,
) -> Result<rho_protocol::SessionMcpInventory, 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 inspect_session(
&self,
params: rho_protocol::SessionInspectParams,
) -> Result<rho_protocol::SessionInspectResponse, RpcError> {
self.sessions.inspect(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> {
self.sessions.attach(params).await
}
async fn observe_session(
&self,
params: SessionObserveParams,
) -> Result<(SessionAttachResponse, Subscription), RpcError> {
self.sessions.observe(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 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 {
let records = self.jobs.list();
let undelivered = self.sessions.undelivered_workflow_runs();
let in_use = self.sessions.worktrees_in_use(&records);
let now = jobs::unix_now();
JobListResponse {
jobs: records
.into_iter()
.map(|record| {
let queue = self.sessions.subagents().queue_place(&record.id);
let live = match &record.subject {
JobSubject::Session { session } => self.sessions.session_live(session),
JobSubject::Subagent {
session: Some(session),
run: _,
} if record.state.in_progress() => {
self.sessions.subagents().feeds().live(session)
}
JobSubject::Subagent { .. } | JobSubject::Workflow { .. } => None,
};
let worktree_stale = worktree_stale(&record, &in_use, now);
wire::job_summary(record, queue, &undelivered, live, worktree_stale)
})
.collect(),
}
}
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
}
}
impl SettingsService for DaemonHost {
async fn config_schema(&self) -> Result<ConfigSchema, RpcError> {
Ok(self.sessions.settings().schema())
}
async fn register_config(
&self,
params: ConfigRegisterParams,
) -> Result<ConfigRegisterResponse, RpcError> {
self.sessions.settings().register(params).await
}
async fn get_config(&self, params: ConfigGetParams) -> Result<ConfigWatch, RpcError> {
self.sessions.settings().get(params).await
}
async fn set_config(&self, params: ConfigSetParams) -> Result<ConfigSetResponse, RpcError> {
self.sessions.settings().set(params).await
}
async fn list_models(&self, params: ModelListParams) -> Result<ModelWatch, RpcError> {
models::watch(params, &self.sessions).await
}
async fn refresh_models(
&self,
params: ModelRefreshParams,
) -> Result<ModelRefreshResponse, RpcError> {
models::refresh(params, &self.sessions).await
}
}