rpi-cli 0.31.0

Terminal coding-agent CLI (the `rpi` binary) built on the rpi-* library crates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//! Working Host ownership for foreground and supervised execution.
pub use super::daemon_administration::{DaemonAdministration, DaemonAdministrationConfig};
use super::{
    ordinary::{OrdinaryBinding, OrdinaryLimits},
    profile::HostStartupAgent,
    recovery::Bindings,
    server::{ControlConfig, ControlServer, ServerError},
    service::{HostService, ServiceError},
    AgentId, AgentRecord, AgentSpec, CatalogError, HostCatalog, HostConfig, ProfileRef,
    TrustedProfileSet,
};
use rpi_harness::session::{
    jsonl::{JsonlSessionStorage, JsonlV4Header},
    DefaultIdGenerator, SystemClock,
};
use rpi_tools::OsExecutionEnv;
use std::{
    collections::{BTreeMap, BTreeSet},
    path::PathBuf,
    sync::Arc,
    time::{SystemTime, UNIX_EPOCH},
};

#[derive(Debug, thiserror::Error)]
pub enum DaemonError {
    #[error("shared Host daemon does not support the requested Agent timers")]
    UnsupportedTimers,
    #[error("Host daemon catalog initialization failed")]
    Catalog(#[source] CatalogError),
    #[error(transparent)]
    Control(#[from] ServerError),
    #[error("Host daemon retains unsettled owners; reconcile before stopping")]
    Settlement(#[source] ServiceError),
    #[error("Host daemon startup Agent profile was rejected")]
    StartupAgent,
    #[error("Host daemon administrative configuration was rejected")]
    Administration,
    #[error("Host daemon startup failed and settlement is incomplete; reconcile before retrying")]
    StartupCleanup(#[source] ServiceError),
}

pub struct HostDaemon {
    service: HostService,
    control: ControlServer,
    administration: Option<DaemonAdministration>,
    #[cfg(target_os = "macos")]
    launch_lock: Option<super::registry::InstanceLock>,
}
impl HostDaemon {
    pub async fn open(
        directory: PathBuf,
        host: HostConfig,
        control: ControlConfig,
    ) -> Result<Self, DaemonError> {
        Self::open_with_agents(directory, host, control, Vec::new()).await
    }

    /// Open the catalog, start the explicitly configured Agents, then bind the
    /// control endpoint. A startup failure settles every started owner before
    /// returning; it never publishes readiness with a partially started Host.
    pub async fn open_with_agents(
        directory: PathBuf,
        host: HostConfig,
        control: ControlConfig,
        agents: Vec<HostStartupAgent>,
    ) -> Result<Self, DaemonError> {
        Self::open_configured(directory, host, control, agents, None).await
    }

    /// Explicit private policy and dynamically available profiles. Only `agents`
    /// are started. One union is frozen before catalog or Session creation.
    pub async fn open_configured(
        directory: PathBuf,
        host: HostConfig,
        control: ControlConfig,
        agents: Vec<HostStartupAgent>,
        administration: Option<DaemonAdministrationConfig>,
    ) -> Result<Self, DaemonError> {
        Self::open_with_mini(directory, host, control, agents, administration, None).await
    }

    /// Mini is opt-in via separate private authority. It never inherits the
    /// Persistent administrative grant or durable lifecycle journal.
    pub async fn open_with_mini(
        directory: PathBuf,
        host: HostConfig,
        control: ControlConfig,
        agents: Vec<HostStartupAgent>,
        administration: Option<DaemonAdministrationConfig>,
        mini_control: Option<super::mini_control::MiniControlConfig>,
    ) -> Result<Self, DaemonError> {
        Self::open_with_recovery(
            directory,
            host,
            control,
            agents,
            administration,
            mini_control,
            (None, None, super::area_rpc::SessionRoutes::default()),
        )
        .await
    }

    pub(super) async fn open_with_recovery(
        directory: PathBuf,
        host: HostConfig,
        control: ControlConfig,
        agents: Vec<HostStartupAgent>,
        administration: Option<DaemonAdministrationConfig>,
        mini_control: Option<super::mini_control::MiniControlConfig>,
        startup: (
            Option<Bindings>,
            Option<std::os::unix::net::UnixListener>,
            super::area_rpc::SessionRoutes,
        ),
    ) -> Result<Self, DaemonError> {
        let (recovery, listener, routes) = startup;
        let session_rpc_agents = &routes.agents;
        // Reject invalid options before opening SQLite or creating directories.
        control.validate()?;
        if routes.restore_on_attach
            && (session_rpc_agents.is_empty()
                || !administration.as_ref().is_some_and(|policy| {
                    policy.permissions.restore
                        && session_rpc_agents.is_subset(&policy.allowed_agents)
                }))
        {
            return Err(ServerError::InvalidConfiguration.into());
        }
        if (session_rpc_agents.is_empty() && host.default_timeouts.disconnected_ms.is_some())
            || (mini_control.is_some() && host.default_timeouts != Default::default())
        {
            return Err(DaemonError::UnsupportedTimers);
        }
        host.validate()
            .map_err(CatalogError::from)
            .map_err(DaemonError::Catalog)?;
        for agent in agents
            .iter()
            .chain(administration.iter().flat_map(|policy| &policy.profiles))
        {
            let timers = host
                .resolve_timeouts(agent.spec.timeouts)
                .map_err(CatalogError::from)
                .map_err(DaemonError::Catalog)?;
            let has_route = session_rpc_agents.contains(&agent.spec.id);
            if has_route
                && agent
                    .profile
                    .instruction_resources
                    .as_ref()
                    .is_some_and(|resources| resources.has_hooks())
            {
                return Err(ServerError::InvalidConfiguration.into());
            }
            let reclaim =
                timers.idle.milliseconds.is_some() || timers.disconnected.milliseconds.is_some();
            let restore_granted = administration.as_ref().is_some_and(|policy| {
                policy.permissions.restore && policy.allowed_agents.contains(&agent.spec.id)
            });
            if (reclaim && !restore_granted)
                || (timers.disconnected.milliseconds.is_some() && !has_route)
                || (agent.spec.mode == super::AgentMode::Mini
                    && (reclaim
                        || timers.run.milliseconds.is_some()
                        || timers.shutdown_grace.milliseconds.is_some()))
            {
                return Err(DaemonError::UnsupportedTimers);
            }
        }
        match &mini_control {
            Some(policy) => policy.preflight(&agents).await?,
            None if agents
                .iter()
                .any(|agent| agent.spec.mode == super::AgentMode::Mini) =>
            {
                return Err(DaemonError::StartupAgent);
            }
            None => {}
        }
        let (minis, agents): (Vec<_>, Vec<_>) = agents
            .into_iter()
            .partition(|agent| agent.spec.mode == super::AgentMode::Mini);
        if administration.as_ref().is_some_and(|policy| {
            policy
                .profiles
                .iter()
                .any(|profile| minis.iter().any(|mini| mini.spec.id == profile.spec.id))
        }) {
            return Err(DaemonError::Administration);
        }
        let (agents, prepared, recovery_profiles) = match administration {
            Some(policy) => (Vec::new(), Some(policy.prepare(agents).await?), None),
            None if recovery.is_some() => {
                let profiles = TrustedProfileSet::freeze(agents)
                    .await
                    .map_err(|_| DaemonError::StartupAgent)?;
                (Vec::new(), None, Some(profiles))
            }
            None => (agents, None, None),
        };
        #[cfg(target_os = "macos")]
        let launch_lock = if listener.is_none() {
            Some(
                super::registry::own_directory_lock(&directory, "supervisor.lock")
                    .map_err(DaemonError::Catalog)?,
            )
        } else {
            None
        };
        let catalog =
            HostCatalog::open_with_recovery(directory, host, recovery.clone().unwrap_or_default())
                .await
                .map_err(DaemonError::Catalog)?;
        let service = HostService::new(catalog);
        let startup = async {
            if let Some(bindings) = &recovery {
                let loaded = match &prepared {
                    Some(policy) => {
                        policy
                            .start_recovery(&service, bindings, minis.len())
                            .await?
                    }
                    None => {
                        let profiles = recovery_profiles
                            .as_ref()
                            .ok_or(DaemonError::StartupAgent)?;
                        let startup: Vec<_> = profiles.references().collect();
                        start_recovery(
                            &service,
                            profiles,
                            &startup,
                            &BTreeSet::new(),
                            bindings,
                            minis.len(),
                        )
                        .await?
                    }
                };
                super::mini_control::start_minis(&service, minis).await?;
                return service
                    .catalog()
                    .remember_members(loaded)
                    .await
                    .map_err(DaemonError::Catalog);
            }
            super::mini_control::start_minis(&service, minis).await?;
            match &prepared {
                Some(prepared) => prepared.start(&service).await,
                None => start_agents(&service, agents).await,
            }
        }
        .await;
        if let Err(error) = startup {
            // A failed startup must not leave owners or catalog ownership behind.
            return match service.shutdown().await {
                Ok(()) => Err(error),
                Err(settlement) => Err(DaemonError::StartupCleanup(settlement)),
            };
        }
        let administration = match prepared
            .map(|prepared| prepared.assemble(service.clone()))
            .transpose()
        {
            Ok(administration) => administration,
            Err(error) => {
                return match service.shutdown().await {
                    Ok(()) => Err(error),
                    Err(settlement) => Err(DaemonError::StartupCleanup(settlement)),
                };
            }
        };
        let mini = mini_control
            .map(|policy| super::mini_control::MiniControl::new(service.clone(), policy));
        let server = match ControlServer::bind_with_controls(
            control,
            service.clone(),
            administration.clone(),
            mini,
            listener,
            routes,
            service.catalog().idle_timeout(),
        )
        .await
        {
            Ok(server) => server,
            Err(error) => {
                service.shutdown().await.map_err(DaemonError::Settlement)?;
                return Err(error.into());
            }
        };
        Ok(Self {
            service,
            control: server,
            administration,
            #[cfg(target_os = "macos")]
            launch_lock,
        })
    }
    /// Trusted native integrations can install explicit bindings. This handle
    /// is not an IPC grant and must not be exposed directly to model tools.
    pub fn service(&self) -> &HostService {
        &self.service
    }
    /// Trusted native handle. Its private policy fixes all authority for the
    /// lifetime; IPC only wraps explicitly implemented typed operations and
    /// never accepts a grant from a caller.
    pub fn administration(&self) -> Option<&DaemonAdministration> {
        self.administration.as_ref()
    }
    pub fn welcome(&self) -> &super::protocol::Welcome {
        self.control.welcome()
    }
    pub async fn wait_control(&mut self) -> Result<(), ServerError> {
        self.control.wait().await
    }
    pub(crate) fn control_stopped_by_administration(&self) -> bool {
        self.control.stopped_by_administration()
    }
    pub(crate) fn control_stopped_for_idleness(&self) -> bool {
        self.control.stopped_for_idleness()
    }
    /// Failed native settlement deliberately retains owners, catalog ownership
    /// and the query listener for diagnosis/retry. Never force-abort backends.
    pub async fn shutdown(&mut self) -> Result<(), DaemonError> {
        self.service
            .shutdown()
            .await
            .map_err(DaemonError::Settlement)?;
        self.control.stop().await?;
        #[cfg(target_os = "macos")]
        drop(self.launch_lock.take());
        Ok(())
    }
}

async fn start_agents(
    service: &HostService,
    agents: Vec<HostStartupAgent>,
) -> Result<(), DaemonError> {
    for agent in agents {
        let binding = agent
            .profile
            .bind(agent.spec.clone())
            .await
            .map_err(|_| DaemonError::StartupAgent)?;
        let existing = preflight_startup(service, &agent.spec, binding).await?;
        let binding = agent
            .profile
            .bind(agent.spec.clone())
            .await
            .map_err(|_| DaemonError::StartupAgent)?;
        load_startup(service, agent.spec, agent.limits, binding, existing).await?;
    }
    Ok(())
}

pub(super) async fn start_frozen_agents(
    service: &HostService,
    profiles: &TrustedProfileSet,
    startup: &[ProfileRef],
) -> Result<(), DaemonError> {
    for &reference in startup {
        let prepared = profiles
            .prepare(reference)
            .await
            .map_err(|_| DaemonError::StartupAgent)?;
        let existing = preflight_startup(service, &prepared.spec, prepared.binding).await?;
        let fresh = profiles
            .prepare(reference)
            .await
            .map_err(|_| DaemonError::StartupAgent)?;
        load_startup(service, fresh.spec, fresh.limits, fresh.binding, existing).await?;
    }
    Ok(())
}

pub(super) async fn start_recovery(
    service: &HostService,
    profiles: &TrustedProfileSet,
    startup: &[ProfileRef],
    restorable: &BTreeSet<AgentId>,
    bindings: &Bindings,
    mini_count: usize,
) -> Result<Vec<AgentId>, DaemonError> {
    let catalog = service.catalog();
    let previous = catalog
        .recovery_members(startup.iter().map(|reference| reference.agent_id).collect())
        .await
        .map_err(DaemonError::Catalog)?;
    let mut selected: BTreeMap<_, _> = startup
        .iter()
        .map(|reference| (reference.agent_id, *reference))
        .collect();
    let configured: BTreeMap<_, _> = profiles
        .references()
        .map(|reference| (reference.agent_id, reference))
        .collect();
    for (&id, version) in &previous {
        match version {
            None => {
                selected.remove(&id);
            }
            Some(version) => {
                if bindings.get(&id) != Some(version)
                    || !(selected.contains_key(&id) || restorable.contains(&id))
                {
                    return Err(DaemonError::StartupAgent);
                }
                selected.insert(id, *configured.get(&id).ok_or(DaemonError::StartupAgent)?);
            }
        }
    }
    let capacity = catalog
        .status()
        .await
        .map_err(DaemonError::Catalog)?
        .max_agents;
    if capacity.is_some_and(|limit| selected.len().saturating_add(mini_count) > limit) {
        return Err(DaemonError::StartupAgent);
    }
    // Check every existing history before creating any new Session or taking a
    // writer. A recorded member missing its history is a permanent failure.
    for (&id, &reference) in &selected {
        let prepared = profiles
            .prepare(reference)
            .await
            .map_err(|_| DaemonError::StartupAgent)?;
        let session = prepared
            .spec
            .session
            .as_ref()
            .ok_or(DaemonError::StartupAgent)?;
        match catalog.get(id).await {
            Ok(record) if record.spec != prepared.spec => return Err(DaemonError::StartupAgent),
            Ok(_) => {}
            Err(CatalogError::UnknownAgent) if !previous.contains_key(&id) => {
                match tokio::fs::symlink_metadata(&session.path).await {
                    Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
                    _ => {}
                }
            }
            Err(CatalogError::UnknownAgent) => return Err(DaemonError::StartupAgent),
            Err(error) => return Err(DaemonError::Catalog(error)),
        }
        prepared
            .binding
            .preflight_session(&prepared.spec)
            .await
            .map_err(|_| DaemonError::StartupAgent)?;
    }
    let references: Vec<_> = selected.values().copied().collect();
    start_frozen_agents(service, profiles, &references).await?;
    Ok(selected.into_keys().collect())
}

async fn preflight_startup(
    service: &HostService,
    spec: &AgentSpec,
    binding: OrdinaryBinding,
) -> Result<Option<AgentRecord>, DaemonError> {
    let existing = match service.catalog().get(spec.id).await {
        Ok(record) if record.spec == *spec => Some(record),
        Ok(_) => return Err(DaemonError::StartupAgent),
        Err(CatalogError::UnknownAgent) => None,
        Err(error) => return Err(DaemonError::Catalog(error)),
    };
    if existing.is_none() {
        ensure_session(spec).await?;
    }
    binding
        .preflight_session(spec)
        .await
        .map_err(|_| DaemonError::StartupAgent)?;
    Ok(existing)
}

async fn load_startup(
    service: &HostService,
    spec: AgentSpec,
    limits: OrdinaryLimits,
    binding: OrdinaryBinding,
    existing: Option<AgentRecord>,
) -> Result<(), DaemonError> {
    let catalog = service.catalog();
    let record = match existing {
        Some(record) => record,
        None => catalog.register(spec).await.map_err(DaemonError::Catalog)?,
    };
    service
        .restore_bound(record.spec.id, catalog.guard(&record), limits, binding)
        .await
        .map_err(|_| DaemonError::StartupAgent)?;
    Ok(())
}

/// Create only a *new* Session file for a profile that names an absent path.
/// Existing files are left for the ordinary strict restore to verify, so an
/// external or torn history is never overwritten here.
async fn ensure_session(spec: &AgentSpec) -> Result<(), DaemonError> {
    let session = spec.session.as_ref().ok_or(DaemonError::StartupAgent)?;
    match tokio::fs::symlink_metadata(&session.path).await {
        Ok(_) => return Ok(()),
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        Err(_) => return Err(DaemonError::StartupAgent),
    }
    let cwd = super::profile::canonical_workspace(spec).map_err(|_| DaemonError::StartupAgent)?;
    super::profile::session_parent(&session.path).map_err(|_| DaemonError::StartupAgent)?;
    let path = session.path.to_str().ok_or(DaemonError::StartupAgent)?;
    let created_at = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|elapsed| i64::try_from(elapsed.as_millis()).unwrap_or(i64::MAX))
        .unwrap_or(0);
    let storage = JsonlSessionStorage::create_new(
        Arc::new(OsExecutionEnv::with_cwd(cwd.clone())),
        path,
        JsonlV4Header::new(
            session.id.clone(),
            created_at,
            cwd.to_string_lossy().into_owned(),
            None,
            None,
            None,
        ),
        Arc::new(SystemClock),
        Arc::new(DefaultIdGenerator::new()),
    )
    .await
    .map_err(|_| DaemonError::StartupAgent)?;
    storage.drain().await;
    storage.release_writer_lease();
    Ok(())
}