Skip to main content

rpi_cli/host/
daemon.rs

1//! Working Host ownership for foreground and supervised execution.
2pub use super::daemon_administration::{DaemonAdministration, DaemonAdministrationConfig};
3use super::{
4    ordinary::{OrdinaryBinding, OrdinaryLimits},
5    profile::HostStartupAgent,
6    recovery::Bindings,
7    server::{ControlConfig, ControlServer, ServerError},
8    service::{HostService, ServiceError},
9    AgentId, AgentRecord, AgentSpec, CatalogError, HostCatalog, HostConfig, ProfileRef,
10    TrustedProfileSet,
11};
12use rpi_harness::session::{
13    jsonl::{JsonlSessionStorage, JsonlV4Header},
14    DefaultIdGenerator, SystemClock,
15};
16use rpi_tools::OsExecutionEnv;
17use std::{
18    collections::{BTreeMap, BTreeSet},
19    path::PathBuf,
20    sync::Arc,
21    time::{SystemTime, UNIX_EPOCH},
22};
23
24#[derive(Debug, thiserror::Error)]
25pub enum DaemonError {
26    #[error("shared Host daemon does not support the requested Agent timers")]
27    UnsupportedTimers,
28    #[error("Host daemon catalog initialization failed")]
29    Catalog(#[source] CatalogError),
30    #[error(transparent)]
31    Control(#[from] ServerError),
32    #[error("Host daemon retains unsettled owners; reconcile before stopping")]
33    Settlement(#[source] ServiceError),
34    #[error("Host daemon startup Agent profile was rejected")]
35    StartupAgent,
36    #[error("Host daemon administrative configuration was rejected")]
37    Administration,
38    #[error("Host daemon startup failed and settlement is incomplete; reconcile before retrying")]
39    StartupCleanup(#[source] ServiceError),
40}
41
42pub struct HostDaemon {
43    service: HostService,
44    control: ControlServer,
45    administration: Option<DaemonAdministration>,
46    #[cfg(target_os = "macos")]
47    launch_lock: Option<super::registry::InstanceLock>,
48}
49impl HostDaemon {
50    pub async fn open(
51        directory: PathBuf,
52        host: HostConfig,
53        control: ControlConfig,
54    ) -> Result<Self, DaemonError> {
55        Self::open_with_agents(directory, host, control, Vec::new()).await
56    }
57
58    /// Open the catalog, start the explicitly configured Agents, then bind the
59    /// control endpoint. A startup failure settles every started owner before
60    /// returning; it never publishes readiness with a partially started Host.
61    pub async fn open_with_agents(
62        directory: PathBuf,
63        host: HostConfig,
64        control: ControlConfig,
65        agents: Vec<HostStartupAgent>,
66    ) -> Result<Self, DaemonError> {
67        Self::open_configured(directory, host, control, agents, None).await
68    }
69
70    /// Explicit private policy and dynamically available profiles. Only `agents`
71    /// are started. One union is frozen before catalog or Session creation.
72    pub async fn open_configured(
73        directory: PathBuf,
74        host: HostConfig,
75        control: ControlConfig,
76        agents: Vec<HostStartupAgent>,
77        administration: Option<DaemonAdministrationConfig>,
78    ) -> Result<Self, DaemonError> {
79        Self::open_with_mini(directory, host, control, agents, administration, None).await
80    }
81
82    /// Mini is opt-in via separate private authority. It never inherits the
83    /// Persistent administrative grant or durable lifecycle journal.
84    pub async fn open_with_mini(
85        directory: PathBuf,
86        host: HostConfig,
87        control: ControlConfig,
88        agents: Vec<HostStartupAgent>,
89        administration: Option<DaemonAdministrationConfig>,
90        mini_control: Option<super::mini_control::MiniControlConfig>,
91    ) -> Result<Self, DaemonError> {
92        Self::open_with_recovery(
93            directory,
94            host,
95            control,
96            agents,
97            administration,
98            mini_control,
99            (None, None, super::area_rpc::SessionRoutes::default()),
100        )
101        .await
102    }
103
104    pub(super) async fn open_with_recovery(
105        directory: PathBuf,
106        host: HostConfig,
107        control: ControlConfig,
108        agents: Vec<HostStartupAgent>,
109        administration: Option<DaemonAdministrationConfig>,
110        mini_control: Option<super::mini_control::MiniControlConfig>,
111        startup: (
112            Option<Bindings>,
113            Option<std::os::unix::net::UnixListener>,
114            super::area_rpc::SessionRoutes,
115        ),
116    ) -> Result<Self, DaemonError> {
117        let (recovery, listener, routes) = startup;
118        let session_rpc_agents = &routes.agents;
119        // Reject invalid options before opening SQLite or creating directories.
120        control.validate()?;
121        if routes.restore_on_attach
122            && (session_rpc_agents.is_empty()
123                || !administration.as_ref().is_some_and(|policy| {
124                    policy.permissions.restore
125                        && session_rpc_agents.is_subset(&policy.allowed_agents)
126                }))
127        {
128            return Err(ServerError::InvalidConfiguration.into());
129        }
130        if (session_rpc_agents.is_empty() && host.default_timeouts.disconnected_ms.is_some())
131            || (mini_control.is_some() && host.default_timeouts != Default::default())
132        {
133            return Err(DaemonError::UnsupportedTimers);
134        }
135        host.validate()
136            .map_err(CatalogError::from)
137            .map_err(DaemonError::Catalog)?;
138        for agent in agents
139            .iter()
140            .chain(administration.iter().flat_map(|policy| &policy.profiles))
141        {
142            let timers = host
143                .resolve_timeouts(agent.spec.timeouts)
144                .map_err(CatalogError::from)
145                .map_err(DaemonError::Catalog)?;
146            let has_route = session_rpc_agents.contains(&agent.spec.id);
147            if has_route
148                && agent
149                    .profile
150                    .instruction_resources
151                    .as_ref()
152                    .is_some_and(|resources| resources.has_hooks())
153            {
154                return Err(ServerError::InvalidConfiguration.into());
155            }
156            let reclaim =
157                timers.idle.milliseconds.is_some() || timers.disconnected.milliseconds.is_some();
158            let restore_granted = administration.as_ref().is_some_and(|policy| {
159                policy.permissions.restore && policy.allowed_agents.contains(&agent.spec.id)
160            });
161            if (reclaim && !restore_granted)
162                || (timers.disconnected.milliseconds.is_some() && !has_route)
163                || (agent.spec.mode == super::AgentMode::Mini
164                    && (reclaim
165                        || timers.run.milliseconds.is_some()
166                        || timers.shutdown_grace.milliseconds.is_some()))
167            {
168                return Err(DaemonError::UnsupportedTimers);
169            }
170        }
171        match &mini_control {
172            Some(policy) => policy.preflight(&agents).await?,
173            None if agents
174                .iter()
175                .any(|agent| agent.spec.mode == super::AgentMode::Mini) =>
176            {
177                return Err(DaemonError::StartupAgent);
178            }
179            None => {}
180        }
181        let (minis, agents): (Vec<_>, Vec<_>) = agents
182            .into_iter()
183            .partition(|agent| agent.spec.mode == super::AgentMode::Mini);
184        if administration.as_ref().is_some_and(|policy| {
185            policy
186                .profiles
187                .iter()
188                .any(|profile| minis.iter().any(|mini| mini.spec.id == profile.spec.id))
189        }) {
190            return Err(DaemonError::Administration);
191        }
192        let (agents, prepared, recovery_profiles) = match administration {
193            Some(policy) => (Vec::new(), Some(policy.prepare(agents).await?), None),
194            None if recovery.is_some() => {
195                let profiles = TrustedProfileSet::freeze(agents)
196                    .await
197                    .map_err(|_| DaemonError::StartupAgent)?;
198                (Vec::new(), None, Some(profiles))
199            }
200            None => (agents, None, None),
201        };
202        #[cfg(target_os = "macos")]
203        let launch_lock = if listener.is_none() {
204            Some(
205                super::registry::own_directory_lock(&directory, "supervisor.lock")
206                    .map_err(DaemonError::Catalog)?,
207            )
208        } else {
209            None
210        };
211        let catalog =
212            HostCatalog::open_with_recovery(directory, host, recovery.clone().unwrap_or_default())
213                .await
214                .map_err(DaemonError::Catalog)?;
215        let service = HostService::new(catalog);
216        let startup = async {
217            if let Some(bindings) = &recovery {
218                let loaded = match &prepared {
219                    Some(policy) => {
220                        policy
221                            .start_recovery(&service, bindings, minis.len())
222                            .await?
223                    }
224                    None => {
225                        let profiles = recovery_profiles
226                            .as_ref()
227                            .ok_or(DaemonError::StartupAgent)?;
228                        let startup: Vec<_> = profiles.references().collect();
229                        start_recovery(
230                            &service,
231                            profiles,
232                            &startup,
233                            &BTreeSet::new(),
234                            bindings,
235                            minis.len(),
236                        )
237                        .await?
238                    }
239                };
240                super::mini_control::start_minis(&service, minis).await?;
241                return service
242                    .catalog()
243                    .remember_members(loaded)
244                    .await
245                    .map_err(DaemonError::Catalog);
246            }
247            super::mini_control::start_minis(&service, minis).await?;
248            match &prepared {
249                Some(prepared) => prepared.start(&service).await,
250                None => start_agents(&service, agents).await,
251            }
252        }
253        .await;
254        if let Err(error) = startup {
255            // A failed startup must not leave owners or catalog ownership behind.
256            return match service.shutdown().await {
257                Ok(()) => Err(error),
258                Err(settlement) => Err(DaemonError::StartupCleanup(settlement)),
259            };
260        }
261        let administration = match prepared
262            .map(|prepared| prepared.assemble(service.clone()))
263            .transpose()
264        {
265            Ok(administration) => administration,
266            Err(error) => {
267                return match service.shutdown().await {
268                    Ok(()) => Err(error),
269                    Err(settlement) => Err(DaemonError::StartupCleanup(settlement)),
270                };
271            }
272        };
273        let mini = mini_control
274            .map(|policy| super::mini_control::MiniControl::new(service.clone(), policy));
275        let server = match ControlServer::bind_with_controls(
276            control,
277            service.clone(),
278            administration.clone(),
279            mini,
280            listener,
281            routes,
282            service.catalog().idle_timeout(),
283        )
284        .await
285        {
286            Ok(server) => server,
287            Err(error) => {
288                service.shutdown().await.map_err(DaemonError::Settlement)?;
289                return Err(error.into());
290            }
291        };
292        Ok(Self {
293            service,
294            control: server,
295            administration,
296            #[cfg(target_os = "macos")]
297            launch_lock,
298        })
299    }
300    /// Trusted native integrations can install explicit bindings. This handle
301    /// is not an IPC grant and must not be exposed directly to model tools.
302    pub fn service(&self) -> &HostService {
303        &self.service
304    }
305    /// Trusted native handle. Its private policy fixes all authority for the
306    /// lifetime; IPC only wraps explicitly implemented typed operations and
307    /// never accepts a grant from a caller.
308    pub fn administration(&self) -> Option<&DaemonAdministration> {
309        self.administration.as_ref()
310    }
311    pub fn welcome(&self) -> &super::protocol::Welcome {
312        self.control.welcome()
313    }
314    pub async fn wait_control(&mut self) -> Result<(), ServerError> {
315        self.control.wait().await
316    }
317    pub(crate) fn control_stopped_by_administration(&self) -> bool {
318        self.control.stopped_by_administration()
319    }
320    pub(crate) fn control_stopped_for_idleness(&self) -> bool {
321        self.control.stopped_for_idleness()
322    }
323    /// Failed native settlement deliberately retains owners, catalog ownership
324    /// and the query listener for diagnosis/retry. Never force-abort backends.
325    pub async fn shutdown(&mut self) -> Result<(), DaemonError> {
326        self.service
327            .shutdown()
328            .await
329            .map_err(DaemonError::Settlement)?;
330        self.control.stop().await?;
331        #[cfg(target_os = "macos")]
332        drop(self.launch_lock.take());
333        Ok(())
334    }
335}
336
337async fn start_agents(
338    service: &HostService,
339    agents: Vec<HostStartupAgent>,
340) -> Result<(), DaemonError> {
341    for agent in agents {
342        let binding = agent
343            .profile
344            .bind(agent.spec.clone())
345            .await
346            .map_err(|_| DaemonError::StartupAgent)?;
347        let existing = preflight_startup(service, &agent.spec, binding).await?;
348        let binding = agent
349            .profile
350            .bind(agent.spec.clone())
351            .await
352            .map_err(|_| DaemonError::StartupAgent)?;
353        load_startup(service, agent.spec, agent.limits, binding, existing).await?;
354    }
355    Ok(())
356}
357
358pub(super) async fn start_frozen_agents(
359    service: &HostService,
360    profiles: &TrustedProfileSet,
361    startup: &[ProfileRef],
362) -> Result<(), DaemonError> {
363    for &reference in startup {
364        let prepared = profiles
365            .prepare(reference)
366            .await
367            .map_err(|_| DaemonError::StartupAgent)?;
368        let existing = preflight_startup(service, &prepared.spec, prepared.binding).await?;
369        let fresh = profiles
370            .prepare(reference)
371            .await
372            .map_err(|_| DaemonError::StartupAgent)?;
373        load_startup(service, fresh.spec, fresh.limits, fresh.binding, existing).await?;
374    }
375    Ok(())
376}
377
378pub(super) async fn start_recovery(
379    service: &HostService,
380    profiles: &TrustedProfileSet,
381    startup: &[ProfileRef],
382    restorable: &BTreeSet<AgentId>,
383    bindings: &Bindings,
384    mini_count: usize,
385) -> Result<Vec<AgentId>, DaemonError> {
386    let catalog = service.catalog();
387    let previous = catalog
388        .recovery_members(startup.iter().map(|reference| reference.agent_id).collect())
389        .await
390        .map_err(DaemonError::Catalog)?;
391    let mut selected: BTreeMap<_, _> = startup
392        .iter()
393        .map(|reference| (reference.agent_id, *reference))
394        .collect();
395    let configured: BTreeMap<_, _> = profiles
396        .references()
397        .map(|reference| (reference.agent_id, reference))
398        .collect();
399    for (&id, version) in &previous {
400        match version {
401            None => {
402                selected.remove(&id);
403            }
404            Some(version) => {
405                if bindings.get(&id) != Some(version)
406                    || !(selected.contains_key(&id) || restorable.contains(&id))
407                {
408                    return Err(DaemonError::StartupAgent);
409                }
410                selected.insert(id, *configured.get(&id).ok_or(DaemonError::StartupAgent)?);
411            }
412        }
413    }
414    let capacity = catalog
415        .status()
416        .await
417        .map_err(DaemonError::Catalog)?
418        .max_agents;
419    if capacity.is_some_and(|limit| selected.len().saturating_add(mini_count) > limit) {
420        return Err(DaemonError::StartupAgent);
421    }
422    // Check every existing history before creating any new Session or taking a
423    // writer. A recorded member missing its history is a permanent failure.
424    for (&id, &reference) in &selected {
425        let prepared = profiles
426            .prepare(reference)
427            .await
428            .map_err(|_| DaemonError::StartupAgent)?;
429        let session = prepared
430            .spec
431            .session
432            .as_ref()
433            .ok_or(DaemonError::StartupAgent)?;
434        match catalog.get(id).await {
435            Ok(record) if record.spec != prepared.spec => return Err(DaemonError::StartupAgent),
436            Ok(_) => {}
437            Err(CatalogError::UnknownAgent) if !previous.contains_key(&id) => {
438                match tokio::fs::symlink_metadata(&session.path).await {
439                    Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
440                    _ => {}
441                }
442            }
443            Err(CatalogError::UnknownAgent) => return Err(DaemonError::StartupAgent),
444            Err(error) => return Err(DaemonError::Catalog(error)),
445        }
446        prepared
447            .binding
448            .preflight_session(&prepared.spec)
449            .await
450            .map_err(|_| DaemonError::StartupAgent)?;
451    }
452    let references: Vec<_> = selected.values().copied().collect();
453    start_frozen_agents(service, profiles, &references).await?;
454    Ok(selected.into_keys().collect())
455}
456
457async fn preflight_startup(
458    service: &HostService,
459    spec: &AgentSpec,
460    binding: OrdinaryBinding,
461) -> Result<Option<AgentRecord>, DaemonError> {
462    let existing = match service.catalog().get(spec.id).await {
463        Ok(record) if record.spec == *spec => Some(record),
464        Ok(_) => return Err(DaemonError::StartupAgent),
465        Err(CatalogError::UnknownAgent) => None,
466        Err(error) => return Err(DaemonError::Catalog(error)),
467    };
468    if existing.is_none() {
469        ensure_session(spec).await?;
470    }
471    binding
472        .preflight_session(spec)
473        .await
474        .map_err(|_| DaemonError::StartupAgent)?;
475    Ok(existing)
476}
477
478async fn load_startup(
479    service: &HostService,
480    spec: AgentSpec,
481    limits: OrdinaryLimits,
482    binding: OrdinaryBinding,
483    existing: Option<AgentRecord>,
484) -> Result<(), DaemonError> {
485    let catalog = service.catalog();
486    let record = match existing {
487        Some(record) => record,
488        None => catalog.register(spec).await.map_err(DaemonError::Catalog)?,
489    };
490    service
491        .restore_bound(record.spec.id, catalog.guard(&record), limits, binding)
492        .await
493        .map_err(|_| DaemonError::StartupAgent)?;
494    Ok(())
495}
496
497/// Create only a *new* Session file for a profile that names an absent path.
498/// Existing files are left for the ordinary strict restore to verify, so an
499/// external or torn history is never overwritten here.
500async fn ensure_session(spec: &AgentSpec) -> Result<(), DaemonError> {
501    let session = spec.session.as_ref().ok_or(DaemonError::StartupAgent)?;
502    match tokio::fs::symlink_metadata(&session.path).await {
503        Ok(_) => return Ok(()),
504        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
505        Err(_) => return Err(DaemonError::StartupAgent),
506    }
507    let cwd = super::profile::canonical_workspace(spec).map_err(|_| DaemonError::StartupAgent)?;
508    super::profile::session_parent(&session.path).map_err(|_| DaemonError::StartupAgent)?;
509    let path = session.path.to_str().ok_or(DaemonError::StartupAgent)?;
510    let created_at = SystemTime::now()
511        .duration_since(UNIX_EPOCH)
512        .map(|elapsed| i64::try_from(elapsed.as_millis()).unwrap_or(i64::MAX))
513        .unwrap_or(0);
514    let storage = JsonlSessionStorage::create_new(
515        Arc::new(OsExecutionEnv::with_cwd(cwd.clone())),
516        path,
517        JsonlV4Header::new(
518            session.id.clone(),
519            created_at,
520            cwd.to_string_lossy().into_owned(),
521            None,
522            None,
523            None,
524        ),
525        Arc::new(SystemClock),
526        Arc::new(DefaultIdGenerator::new()),
527    )
528    .await
529    .map_err(|_| DaemonError::StartupAgent)?;
530    storage.drain().await;
531    storage.release_writer_lease();
532    Ok(())
533}