1mod 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#[derive(Clone, Debug, thiserror::Error)]
34pub enum BackendError {
35 #[error("ordinary backend catalog operation failed")]
36 Catalog(#[source] Arc<CatalogError>),
37 #[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 #[error("ordinary backend resource persistence failed or is uncertain")]
52 ResourcePersistence,
53 #[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
91pub type OrdinaryBinder = Box<
97 dyn FnOnce(
98 &AgentSpec,
99 Arc<OsExecutionEnv>,
100 &JsonlSessionFacts,
101 ) -> BackendResult<AgentHarnessOptions>
102 + Send
103 + 'static,
104>;
105
106pub type OrdinaryAssembly = std::pin::Pin<
110 Box<dyn std::future::Future<Output = BackendResult<AgentHarnessOptions>> + Send + 'static>,
111>;
112
113pub 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
132pub struct OrdinaryBinding {
136 environment: Option<Arc<OsExecutionEnv>>,
137 binder: BindingResolver,
138 pub(super) instruction_resources: Option<Arc<super::NativeBindingResources>>,
141 pub(super) extensions: Option<Arc<super::NativeExtensionCustody>>,
142 #[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 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 pub fn with_extensions(mut self, custody: Arc<super::NativeExtensionCustody>) -> Self {
190 self.extensions = Some(custody);
191 self
192 }
193
194 #[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 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 pub persistence_uncertain: bool,
264 pub catalog_error: Option<BackendError>,
267}
268
269#[derive(Clone, Debug)]
270pub struct BackendSnapshot {
271 pub record: AgentRecord,
272 pub ticket: Option<RunId>,
273 pub submitted_request_id: Option<String>,
276 pub cancel_requested: bool,
278 pub active: Option<ActiveOperationSnapshot>,
279 pub pending_resume: bool,
280 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#[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#[derive(Clone, Debug)]
307pub enum AdmissionState {
308 Pending,
309 Admitted(Arc<HostAdmissionReceipt>),
310 Rejected(BackendError),
311}
312
313#[derive(Clone, Debug)]
318pub struct AdmittedRunTicket {
319 pub id: RunId,
320 admission: watch::Receiver<AdmissionState>,
321 completion: watch::Receiver<Completion>,
322}
323impl AdmittedRunTicket {
324 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
345pub(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::Busy,
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#[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 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 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 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 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 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 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 pub async fn cancel(&self, ticket: RunId) -> BackendResult<bool> {
566 self.upgrade()?.cancel(ticket)
567 }
568
569 pub async fn cancel_guarded(&self, guard: CatalogGuard, ticket: RunId) -> BackendResult<bool> {
574 self.upgrade()?.cancel_guarded(guard, ticket)
575 }
576
577 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 pub async fn snapshot(&self) -> BackendResult<BackendSnapshot> {
610 self.upgrade()?.snapshot()
611 }
612
613 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}