Skip to main content

rpi_cli/host/ordinary/
mod.rs

1//! Supervised ordinary JSONL backend. No CLI resource loader, global cwd/env
2//! mutation, second Agent loop, IPC, or durable input-ACK protocol lives here.
3
4mod supervisor;
5#[cfg(unix)]
6pub(super) use supervisor::AreaPeer;
7pub(super) use supervisor::ReclaimClock;
8#[cfg(all(test, unix))]
9mod tests;
10
11use super::{AgentRecord, AgentSpec, CatalogError, CatalogGuard, HostCatalog, RunId};
12use rpi_agent::AgentMessage;
13use rpi_harness::{
14    agent_harness::{
15        ActiveOperationSnapshot, CompactionResult, HarnessWriteFailure, HostAdmissionReceipt,
16        HostAdmissionStatus, QueueResult, RunResult, UnsavedMessage,
17    },
18    session::{jsonl::JsonlSessionFacts, types::HistoryIdentity, Session},
19    types::AgentHarnessOptions,
20};
21use rpi_tools::OsExecutionEnv;
22use std::{
23    future::Future,
24    io,
25    sync::{Arc, Weak},
26};
27use tokio::sync::watch;
28
29pub type BackendResult<T> = Result<T, BackendError>;
30
31/// Display is deliberately fixed; source errors and reports may contain private
32/// transcript/provider details and must not be serialized with Debug by IPC.
33#[derive(Clone, Debug, thiserror::Error)]
34pub enum BackendError {
35    #[error("ordinary backend catalog operation failed")]
36    Catalog(#[source] Arc<CatalogError>),
37    /// Definite pre-effect rejection by the guarded control entry points. This
38    /// is distinct from a catalog failure after cancellation/cleanup has begun.
39    #[error("ordinary backend administrative guard was rejected; no action accepted")]
40    GuardRejected(#[source] Arc<CatalogError>),
41    #[error("ordinary backend Harness operation failed")]
42    Harness(#[source] Arc<rpi_harness::result::HarnessError>),
43    #[error("ordinary backend Session operation failed")]
44    Session(#[source] Arc<rpi_harness::error::SessionError>),
45    #[error("ordinary backend filesystem operation failed")]
46    Io(#[source] Arc<io::Error>),
47    #[error("ordinary backend binding rejected: {0}")]
48    Binding(&'static str),
49    /// A resource declaration may already be visible. This is not a pure
50    /// validation rejection; reconcile saved facts before any retry.
51    #[error("ordinary backend resource persistence failed or is uncertain")]
52    ResourcePersistence,
53    /// A DLL may still own workers/code/context and the real writer. Fixed
54    /// diagnostic; the Arc is lifecycle custody, not serializable error data.
55    #[error("ordinary backend extension cleanup is not proven; ownership retained")]
56    ExtensionUnsettled(Arc<super::NativeExtensionCustody>),
57    #[error("ordinary backend is busy; no operation was accepted")]
58    Busy,
59    #[error("ordinary backend is closing or closed")]
60    Closed,
61    #[error("ordinary backend requires reconciliation")]
62    Faulted,
63    #[error("ordinary backend input exceeds its byte budget")]
64    InputTooLarge,
65    #[error("ordinary backend operation was cancelled before Harness admission")]
66    CancelledBeforeAdmission,
67    #[error("ordinary backend request admission was rejected: {0}")]
68    Admission(&'static str),
69    #[error("ordinary backend request admission outcome is uncertain; reconcile before retrying")]
70    AdmissionUncertain,
71    #[error("ordinary backend task panicked or stopped; inspect durable state")]
72    TaskStopped,
73    #[error("ordinary backend persistence failed or is uncertain; cannot unload safely")]
74    Unsaved,
75}
76
77macro_rules! source_error {
78    ($source:ty, $variant:ident) => {
79        impl From<$source> for BackendError {
80            fn from(error: $source) -> Self {
81                Self::$variant(Arc::new(error))
82            }
83        }
84    };
85}
86source_error!(CatalogError, Catalog);
87source_error!(rpi_harness::result::HarnessError, Harness);
88source_error!(rpi_harness::error::SessionError, Session);
89source_error!(io::Error, Io);
90
91/// Mandatory trusted assembly/preflight callback. Inspect the exact saved facts,
92/// resolve resources/permissions/credentials per Agent, and reject unsupported
93/// bindings before the prepared restore claims a writer or repairs a journal.
94/// It must not call CLI `build_prepared` or mutate process globals. The supplied
95/// options' Session is replaced by this backend's exact committed JSONL Session.
96pub type OrdinaryBinder = Box<
97    dyn FnOnce(
98            &AgentSpec,
99            Arc<OsExecutionEnv>,
100            &JsonlSessionFacts,
101        ) -> BackendResult<AgentHarnessOptions>
102        + Send
103        + 'static,
104>;
105
106/// Deferred, owned resource assembly. Constructing this future is part of pure
107/// readonly validation; it must not start workers or perform registration until
108/// polled by an actual restore. No writer/repair has occurred when it runs.
109pub type OrdinaryAssembly = std::pin::Pin<
110    Box<dyn std::future::Future<Output = BackendResult<AgentHarnessOptions>> + Send + 'static>,
111>;
112
113/// Pure validation of exact saved facts, returning an unpolled assembly plan.
114/// It must reject metadata/resource/permission mismatches without loading code
115/// or starting work. Actual restore repeats validation with fresh facts. This
116/// trusted Rust interface is not a model/IPC capability or an exactly-once API.
117pub type OrdinaryDeferredBinder = Box<
118    dyn FnOnce(
119            &AgentSpec,
120            Arc<OsExecutionEnv>,
121            &JsonlSessionFacts,
122        ) -> BackendResult<OrdinaryAssembly>
123        + Send
124        + 'static,
125>;
126
127enum BindingResolver {
128    Immediate(OrdinaryBinder),
129    Deferred(OrdinaryDeferredBinder),
130}
131
132/// Explicit environment plus a trusted assembly callback. The environment is
133/// shared by Session storage, builtin tools and skill execution for this Agent;
134/// do not reuse it across Agents (its process cleanup ownership is per Agent).
135pub struct OrdinaryBinding {
136    environment: Option<Arc<OsExecutionEnv>>,
137    binder: BindingResolver,
138    // Closed native resource variants only; executable assembly additionally
139    // requires the explicit owned DLL custody below, never a generic callback.
140    pub(super) instruction_resources: Option<Arc<super::NativeBindingResources>>,
141    pub(super) extensions: Option<Arc<super::NativeExtensionCustody>>,
142    // Fault injection is test-only; production Session storage always uses the
143    // explicitly bound OS environment, never a caller-supplied weak backend.
144    #[cfg(test)]
145    filesystem: Option<Arc<dyn rpi_tools::FileSystem>>,
146}
147impl OrdinaryBinding {
148    pub fn new(environment: Arc<OsExecutionEnv>, binder: OrdinaryBinder) -> BackendResult<Self> {
149        if !environment.has_explicit_environment() {
150            return Err(BackendError::Binding(
151                "explicit execution environment required",
152            ));
153        }
154        Ok(Self {
155            environment: Some(environment),
156            binder: BindingResolver::Immediate(binder),
157            instruction_resources: None,
158            extensions: None,
159            #[cfg(test)]
160            filesystem: None,
161        })
162    }
163    /// Split pure readonly validation from asynchronous owned assembly. Only
164    /// restore polls the returned plan; preflight drops it without polling.
165    /// Assembly must retain all callback/library ownership through failure and
166    /// cleanup; the backend validates its complete options before commit_strict.
167    pub fn new_deferred(
168        environment: Arc<OsExecutionEnv>,
169        validator: OrdinaryDeferredBinder,
170    ) -> BackendResult<Self> {
171        if !environment.has_explicit_environment() {
172            return Err(BackendError::Binding(
173                "explicit execution environment required",
174            ));
175        }
176        Ok(Self {
177            environment: Some(environment),
178            binder: BindingResolver::Deferred(validator),
179            instruction_resources: None,
180            extensions: None,
181            #[cfg(test)]
182            filesystem: None,
183        })
184    }
185    /// Attach the concrete DLL batch loaded by this binding's owned assembly.
186    /// Its workers/callbacks/physical cleanup become part of the backend's
187    /// writer and residency barrier, including failed startup. This trusted
188    /// Rust API does not expose DLLs through profile/model/IPC input.
189    pub fn with_extensions(mut self, custody: Arc<super::NativeExtensionCustody>) -> Self {
190        self.extensions = Some(custody);
191        self
192    }
193
194    /// Readonly native preflight before registration/Starting. Consumes this
195    /// one-load environment; actual restore must use a fresh binding and repeat
196    /// validation, not rely on facts surviving external filesystem changes.
197    #[cfg(unix)]
198    pub(crate) async fn preflight_session(self, spec: &super::AgentSpec) -> BackendResult<()> {
199        supervisor::preflight(spec, self).await
200    }
201    #[cfg(unix)]
202    pub(crate) fn execution_environment(&self) -> BackendResult<Arc<OsExecutionEnv>> {
203        self.environment.clone().ok_or(BackendError::Binding(
204            "explicit execution environment required",
205        ))
206    }
207    pub(crate) fn legacy(binder: OrdinaryBinder) -> Self {
208        Self {
209            environment: None,
210            binder: BindingResolver::Immediate(binder),
211            instruction_resources: None,
212            extensions: None,
213            #[cfg(test)]
214            filesystem: None,
215        }
216    }
217}
218
219#[derive(Clone, Copy, Debug)]
220pub struct OrdinaryLimits {
221    pub max_input_bytes: usize,
222}
223impl Default for OrdinaryLimits {
224    fn default() -> Self {
225        Self {
226            max_input_bytes: 8 * 1024 * 1024,
227        }
228    }
229}
230
231#[derive(Debug)]
232pub enum OrdinaryOperation {
233    Prompt(Vec<AgentMessage>),
234    ResumePending,
235    ResumeDeferred(String),
236    Compact(Option<String>),
237}
238
239#[derive(Clone, Debug)]
240pub enum OrdinaryOutput {
241    Run(Box<RunResult>),
242    NoPendingResume,
243    Compaction(Box<CompactionResult>),
244    /// The exact request id was already durably admitted; this call did not
245    /// execute it again. Query the admission status for execution facts.
246    AlreadyAdmitted,
247}
248
249#[derive(Clone, Copy, Debug)]
250pub enum Delivery {
251    Steer,
252    FollowUp,
253    NextRun,
254}
255
256#[derive(Clone, Debug)]
257pub struct BackendReport {
258    pub outcome: BackendResult<OrdinaryOutput>,
259    pub write_failures: Vec<HarnessWriteFailure>,
260    pub unsaved_messages: usize,
261    /// A fallible Session path may return directly without a warning/recovery
262    /// copy. Never treat zero warnings as proof that the operation was saved.
263    pub persistence_uncertain: bool,
264    /// Execution may have settled even when publishing Idle failed. Preserve
265    /// both facts rather than replacing the actual run outcome with fake success.
266    pub catalog_error: Option<BackendError>,
267}
268
269#[derive(Clone, Debug)]
270pub struct BackendSnapshot {
271    pub record: AgentRecord,
272    pub ticket: Option<RunId>,
273    /// Volatile input association for the active task or explicitly parked
274    /// deferred operation. Not a durable receipt; absent after owner restore.
275    pub submitted_request_id: Option<String>,
276    /// Volatile signal for this supervised ticket, never proof of settlement.
277    pub cancel_requested: bool,
278    pub active: Option<ActiveOperationSnapshot>,
279    pub pending_resume: bool,
280    /// Parked external provider work is busy even without an executing task.
281    pub deferred: Option<String>,
282    pub retiring: bool,
283    pub closed: bool,
284    pub fault: Option<BackendError>,
285    pub last_report: Option<Arc<BackendReport>>,
286}
287
288type Completion = Option<BackendResult<Arc<BackendReport>>>;
289
290/// In-memory operation ticket scoped to this Host lifetime. NOT a durable input
291/// receipt or the Harness operation ID; the latter is in `OrdinaryOutput::Run`.
292/// Dropping this observer never drops/cancels the supervised operation.
293#[derive(Clone)]
294pub struct RunTicket {
295    pub id: RunId,
296    completion: watch::Receiver<Completion>,
297}
298impl RunTicket {
299    pub async fn wait(&self) -> BackendResult<Arc<BackendReport>> {
300        wait_completion(self.completion.clone()).await
301    }
302}
303
304/// Native admission outcome, published independently of execution settlement.
305/// `Pending` is observable only while the supervisor task is running.
306#[derive(Clone, Debug)]
307pub enum AdmissionState {
308    Pending,
309    Admitted(Arc<HostAdmissionReceipt>),
310    Rejected(BackendError),
311}
312
313/// Ticket for a request whose input is admitted before execution. The two
314/// waits are deliberately separate: `wait_admitted` returns as soon as the
315/// native journal and its sync barrier cover the exact input, while `wait`
316/// observes the supervised execution report.
317#[derive(Clone, Debug)]
318pub struct AdmittedRunTicket {
319    pub id: RunId,
320    admission: watch::Receiver<AdmissionState>,
321    completion: watch::Receiver<Completion>,
322}
323impl AdmittedRunTicket {
324    /// Wait for the durable input receipt. This never implies execution.
325    pub async fn wait_admitted(&self) -> BackendResult<Arc<HostAdmissionReceipt>> {
326        let mut receiver = self.admission.clone();
327        loop {
328            match receiver.borrow().clone() {
329                AdmissionState::Pending => {}
330                AdmissionState::Admitted(receipt) => return Ok(receipt),
331                AdmissionState::Rejected(error) => return Err(error),
332            }
333            receiver
334                .changed()
335                .await
336                .map_err(|_| BackendError::TaskStopped)?;
337        }
338    }
339
340    pub async fn wait(&self) -> BackendResult<Arc<BackendReport>> {
341        wait_completion(self.completion.clone()).await
342    }
343}
344
345/// Fixed mapping from native admission errors to Host-safe diagnostics. Never
346/// forward raw journal text, digests or messages to the client.
347pub(super) fn admission_error(error: rpi_harness::durable::DurableError) -> BackendError {
348    use rpi_harness::durable::DurableError as Native;
349    match error {
350        Native::Closed => BackendError::Closed,
351        Native::Recovering => BackendError::Faulted,
352        Native::LimitExceeded => BackendError::InputTooLarge,
353        Native::InvalidRequest(_) => BackendError::Admission("invalid admission request"),
354        Native::Conflict => BackendError::Admission("request identity conflicts with the journal"),
355        Native::CommitUncertain(_) | Native::ReadFailure(_) => BackendError::AdmissionUncertain,
356        _ => BackendError::Faulted,
357    }
358}
359
360async fn wait_completion(
361    mut receiver: watch::Receiver<Completion>,
362) -> BackendResult<Arc<BackendReport>> {
363    loop {
364        if let Some(result) = receiver.borrow().clone() {
365            return result;
366        }
367        receiver
368            .changed()
369            .await
370            .map_err(|_| BackendError::TaskStopped)?;
371    }
372}
373
374/// Host-owned lifetime, separate from weak client views. Explicitly close and
375/// inspect errors before removing this owner from a future service registry.
376/// Drop only starts best-effort cooperative cleanup; no forced task abort occurs.
377#[must_use = "retain the Host owner independently of transient clients"]
378pub struct OrdinaryAgent {
379    inner: Arc<supervisor::Backend>,
380}
381
382impl OrdinaryAgent {
383    pub async fn restore(
384        catalog: HostCatalog,
385        id: super::AgentId,
386        guard: CatalogGuard,
387        binder: OrdinaryBinder,
388    ) -> BackendResult<Self> {
389        Self::restore_with_limits(catalog, id, guard, OrdinaryLimits::default(), binder).await
390    }
391
392    pub async fn restore_with_limits(
393        catalog: HostCatalog,
394        id: super::AgentId,
395        guard: CatalogGuard,
396        limits: OrdinaryLimits,
397        binder: OrdinaryBinder,
398    ) -> BackendResult<Self> {
399        Self::restore_bound(catalog, id, guard, limits, OrdinaryBinding::legacy(binder)).await
400    }
401
402    pub async fn restore_bound(
403        catalog: HostCatalog,
404        id: super::AgentId,
405        guard: CatalogGuard,
406        limits: OrdinaryLimits,
407        binding: OrdinaryBinding,
408    ) -> BackendResult<Self> {
409        Self::restore_bound_with_intent(catalog, id, guard, limits, binding, false).await
410    }
411
412    pub(super) async fn restore_bound_with_intent(
413        catalog: HostCatalog,
414        id: super::AgentId,
415        guard: CatalogGuard,
416        limits: OrdinaryLimits,
417        binding: OrdinaryBinding,
418        attach: bool,
419    ) -> BackendResult<Self> {
420        if limits.max_input_bytes == 0 {
421            return Err(BackendError::Binding("input byte budget must be nonzero"));
422        }
423        // This task owns startup even if its awaiting caller disappears. An
424        // unclaimed successful owner is dropped and cooperatively cleaned up.
425        owned(async move { supervisor::restore(catalog, id, guard, limits, binding, attach).await })
426            .await
427    }
428
429    pub fn client(&self) -> OrdinaryClient {
430        OrdinaryClient {
431            inner: Arc::downgrade(&self.inner),
432        }
433    }
434
435    pub(super) fn shutdown_grace(&self) -> Option<std::time::Duration> {
436        self.inner.shutdown_grace
437    }
438
439    pub(super) fn reclaim_clock(&self) -> Option<watch::Receiver<ReclaimClock>> {
440        self.inner.reclaim.as_ref().map(watch::Sender::subscribe)
441    }
442
443    pub(super) async fn unload_idle(&self) -> BackendResult<()> {
444        self.inner.unload_idle().await
445    }
446
447    pub async fn close(&self) -> BackendResult<()> {
448        self.inner.retire();
449        let inner = self.inner.clone();
450        owned(async move { inner.close().await }).await
451    }
452
453    /// Administrative close, unlike unconditional owner shutdown. Rejection of
454    /// an epoch/revision guard cannot retire or cancel the current operation.
455    /// Once accepted, settlement remains owned if its waiting caller disappears.
456    /// This is not a durable request-id receipt or an IPC authorization grant.
457    pub async fn close_guarded(&self, guard: CatalogGuard) -> BackendResult<()> {
458        let inner = self.inner.clone();
459        owned(async move { inner.close_guarded(guard).await }).await
460    }
461}
462impl Drop for OrdinaryAgent {
463    fn drop(&mut self) {
464        if self.inner.is_closed() {
465            return;
466        }
467        self.inner.retire();
468        let inner = self.inner.clone();
469        if let Ok(runtime) = tokio::runtime::Handle::try_current() {
470            runtime.spawn(async move {
471                if let Err(error) = inner.close().await {
472                    if !matches!(error, BackendError::Busy) {
473                        tracing::warn!("ordinary backend owner dropped before clean shutdown; reconciliation required");
474                    }
475                }
476            });
477        } else {
478            tracing::warn!("ordinary backend dropped outside its runtime; reconciliation required");
479        }
480    }
481}
482
483#[derive(Clone)]
484pub struct OrdinaryClient {
485    inner: Weak<supervisor::Backend>,
486}
487impl OrdinaryClient {
488    fn upgrade(&self) -> BackendResult<Arc<supervisor::Backend>> {
489        self.inner.upgrade().ok_or(BackendError::Closed)
490    }
491
492    pub async fn submit(&self, operation: OrdinaryOperation) -> BackendResult<RunTicket> {
493        let inner = self.upgrade()?;
494        inner.validate_operation(&operation)?;
495        let guard = inner
496            .control
497            .clone()
498            .try_lock_owned()
499            .map_err(|_| BackendError::Busy)?;
500        owned(async move { inner.submit(guard, operation).await }).await
501    }
502
503    /// Admit the exact prompt under `request_id` before executing it. Only
504    /// `wait_admitted` returning a receipt is a durable input claim.
505    pub async fn submit_admitted(
506        &self,
507        host_id: String,
508        request_id: String,
509        messages: Vec<AgentMessage>,
510    ) -> BackendResult<AdmittedRunTicket> {
511        let inner = self.upgrade()?;
512        inner.validate_messages(&messages)?;
513        let guard = inner
514            .control
515            .clone()
516            .try_lock_owned()
517            .map_err(|_| BackendError::Busy)?;
518        owned(async move {
519            inner
520                .submit_admitted(guard, host_id, request_id, messages)
521                .await
522        })
523        .await
524    }
525
526    /// Read the native admission/reconciliation status for one request.
527    pub async fn admission(&self, request_id: &str) -> BackendResult<Option<HostAdmissionStatus>> {
528        let inner = self.upgrade()?;
529        inner.admission(request_id).await
530    }
531
532    /// Read an already-linked native result and prove a physical barrier after
533    /// its records/references were read. This does not execute or resume a run.
534    pub async fn get_result(
535        &self,
536        run_id: &str,
537        history: HistoryIdentity,
538    ) -> BackendResult<Option<(RunResult, HistoryIdentity)>> {
539        self.upgrade()?.get_result(run_id, history).await
540    }
541
542    /// Bounded listing of native admissions for reconciliation.
543    pub async fn admissions(&self) -> BackendResult<Vec<HostAdmissionStatus>> {
544        let inner = self.upgrade()?;
545        inner.admissions().await
546    }
547
548    pub async fn deliver(
549        &self,
550        message: AgentMessage,
551        delivery: Delivery,
552    ) -> BackendResult<QueueResult> {
553        let inner = self.upgrade()?;
554        inner.validate_message(&message)?;
555        let guard = inner
556            .control
557            .clone()
558            .try_lock_owned()
559            .map_err(|_| BackendError::Busy)?;
560        owned(async move { inner.deliver(guard, message, delivery).await }).await
561    }
562
563    /// Cooperative signal for this exact ticket, not proof of settlement. A late
564    /// cancellation can never target a subsequent operation on the same Agent.
565    pub async fn cancel(&self, ticket: RunId) -> BackendResult<bool> {
566        self.upgrade()?.cancel(ticket)
567    }
568
569    /// Validate the owner-observed epoch/revision and exact volatile ticket in
570    /// the same control critical section as cancellation. A successful signal
571    /// is not settlement or a durable request receipt; no subsequent ticket is
572    /// affected by a late cancellation of the addressed one.
573    pub async fn cancel_guarded(&self, guard: CatalogGuard, ticket: RunId) -> BackendResult<bool> {
574        self.upgrade()?.cancel_guarded(guard, ticket)
575    }
576
577    /// Signal only the active supervised task associated with this exact input
578    /// identity. Duplicates cannot retarget it. A parked deferred operation or
579    /// restored historical receipt returns false; no operation is resumed.
580    pub async fn cancel_submitted_guarded(
581        &self,
582        guard: CatalogGuard,
583        request_id: &str,
584    ) -> BackendResult<bool> {
585        self.upgrade()?.cancel_submitted_guarded(guard, request_id)
586    }
587
588    #[cfg(unix)]
589    pub(in crate::host) async fn area_session(
590        &self,
591        attach: bool,
592    ) -> BackendResult<(super::area_rpc::Events, Option<AreaPeer>)> {
593        self.upgrade()?.area_session(attach).await
594    }
595
596    #[cfg(unix)]
597    pub(in crate::host) async fn area_command(
598        &self,
599        kind: &str,
600        msg: &serde_json::Value,
601    ) -> Result<serde_json::Value, String> {
602        self.upgrade()
603            .map_err(|error| error.to_string())?
604            .area_command(kind, msg)
605            .await
606    }
607
608    /// Cheap volatile observation; does not scan transcripts or prove settlement.
609    pub async fn snapshot(&self) -> BackendResult<BackendSnapshot> {
610        self.upgrade()?.snapshot()
611    }
612
613    /// Explicit recovery/export surface. The caller owns the returned payload;
614    /// a future IPC adapter must apply its own response/output byte budgets.
615    pub fn unsaved_messages(&self) -> BackendResult<Vec<UnsavedMessage>> {
616        Ok(self.upgrade()?.unsaved_messages())
617    }
618}
619
620async fn owned<T: Send + 'static>(
621    future: impl Future<Output = BackendResult<T>> + Send + 'static,
622) -> BackendResult<T> {
623    tokio::spawn(future)
624        .await
625        .map_err(|_| BackendError::TaskStopped)?
626}