mod supervisor;
#[cfg(unix)]
pub(super) use supervisor::AreaPeer;
pub(super) use supervisor::ReclaimClock;
#[cfg(all(test, unix))]
mod tests;
use super::{AgentRecord, AgentSpec, CatalogError, CatalogGuard, HostCatalog, RunId};
use rpi_agent::AgentMessage;
use rpi_harness::{
agent_harness::{
ActiveOperationSnapshot, CompactionResult, HarnessWriteFailure, HostAdmissionReceipt,
HostAdmissionStatus, QueueResult, RunResult, UnsavedMessage,
},
session::{jsonl::JsonlSessionFacts, types::HistoryIdentity, Session},
types::AgentHarnessOptions,
};
use rpi_tools::OsExecutionEnv;
use std::{
future::Future,
io,
sync::{Arc, Weak},
};
use tokio::sync::watch;
pub type BackendResult<T> = Result<T, BackendError>;
#[derive(Clone, Debug, thiserror::Error)]
pub enum BackendError {
#[error("ordinary backend catalog operation failed")]
Catalog(#[source] Arc<CatalogError>),
#[error("ordinary backend administrative guard was rejected; no action accepted")]
GuardRejected(#[source] Arc<CatalogError>),
#[error("ordinary backend Harness operation failed")]
Harness(#[source] Arc<rpi_harness::result::HarnessError>),
#[error("ordinary backend Session operation failed")]
Session(#[source] Arc<rpi_harness::error::SessionError>),
#[error("ordinary backend filesystem operation failed")]
Io(#[source] Arc<io::Error>),
#[error("ordinary backend binding rejected: {0}")]
Binding(&'static str),
#[error("ordinary backend resource persistence failed or is uncertain")]
ResourcePersistence,
#[error("ordinary backend extension cleanup is not proven; ownership retained")]
ExtensionUnsettled(Arc<super::NativeExtensionCustody>),
#[error("ordinary backend is busy; no operation was accepted")]
Busy,
#[error("ordinary backend is closing or closed")]
Closed,
#[error("ordinary backend requires reconciliation")]
Faulted,
#[error("ordinary backend input exceeds its byte budget")]
InputTooLarge,
#[error("ordinary backend operation was cancelled before Harness admission")]
CancelledBeforeAdmission,
#[error("ordinary backend request admission was rejected: {0}")]
Admission(&'static str),
#[error("ordinary backend request admission outcome is uncertain; reconcile before retrying")]
AdmissionUncertain,
#[error("ordinary backend task panicked or stopped; inspect durable state")]
TaskStopped,
#[error("ordinary backend persistence failed or is uncertain; cannot unload safely")]
Unsaved,
}
macro_rules! source_error {
($source:ty, $variant:ident) => {
impl From<$source> for BackendError {
fn from(error: $source) -> Self {
Self::$variant(Arc::new(error))
}
}
};
}
source_error!(CatalogError, Catalog);
source_error!(rpi_harness::result::HarnessError, Harness);
source_error!(rpi_harness::error::SessionError, Session);
source_error!(io::Error, Io);
pub type OrdinaryBinder = Box<
dyn FnOnce(
&AgentSpec,
Arc<OsExecutionEnv>,
&JsonlSessionFacts,
) -> BackendResult<AgentHarnessOptions>
+ Send
+ 'static,
>;
pub type OrdinaryAssembly = std::pin::Pin<
Box<dyn std::future::Future<Output = BackendResult<AgentHarnessOptions>> + Send + 'static>,
>;
pub type OrdinaryDeferredBinder = Box<
dyn FnOnce(
&AgentSpec,
Arc<OsExecutionEnv>,
&JsonlSessionFacts,
) -> BackendResult<OrdinaryAssembly>
+ Send
+ 'static,
>;
enum BindingResolver {
Immediate(OrdinaryBinder),
Deferred(OrdinaryDeferredBinder),
}
pub struct OrdinaryBinding {
environment: Option<Arc<OsExecutionEnv>>,
binder: BindingResolver,
pub(super) instruction_resources: Option<Arc<super::NativeBindingResources>>,
pub(super) extensions: Option<Arc<super::NativeExtensionCustody>>,
#[cfg(test)]
filesystem: Option<Arc<dyn rpi_tools::FileSystem>>,
}
impl OrdinaryBinding {
pub fn new(environment: Arc<OsExecutionEnv>, binder: OrdinaryBinder) -> BackendResult<Self> {
if !environment.has_explicit_environment() {
return Err(BackendError::Binding(
"explicit execution environment required",
));
}
Ok(Self {
environment: Some(environment),
binder: BindingResolver::Immediate(binder),
instruction_resources: None,
extensions: None,
#[cfg(test)]
filesystem: None,
})
}
pub fn new_deferred(
environment: Arc<OsExecutionEnv>,
validator: OrdinaryDeferredBinder,
) -> BackendResult<Self> {
if !environment.has_explicit_environment() {
return Err(BackendError::Binding(
"explicit execution environment required",
));
}
Ok(Self {
environment: Some(environment),
binder: BindingResolver::Deferred(validator),
instruction_resources: None,
extensions: None,
#[cfg(test)]
filesystem: None,
})
}
pub fn with_extensions(mut self, custody: Arc<super::NativeExtensionCustody>) -> Self {
self.extensions = Some(custody);
self
}
#[cfg(unix)]
pub(crate) async fn preflight_session(self, spec: &super::AgentSpec) -> BackendResult<()> {
supervisor::preflight(spec, self).await
}
#[cfg(unix)]
pub(crate) fn execution_environment(&self) -> BackendResult<Arc<OsExecutionEnv>> {
self.environment.clone().ok_or(BackendError::Binding(
"explicit execution environment required",
))
}
pub(crate) fn legacy(binder: OrdinaryBinder) -> Self {
Self {
environment: None,
binder: BindingResolver::Immediate(binder),
instruction_resources: None,
extensions: None,
#[cfg(test)]
filesystem: None,
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct OrdinaryLimits {
pub max_input_bytes: usize,
}
impl Default for OrdinaryLimits {
fn default() -> Self {
Self {
max_input_bytes: 8 * 1024 * 1024,
}
}
}
#[derive(Debug)]
pub enum OrdinaryOperation {
Prompt(Vec<AgentMessage>),
ResumePending,
ResumeDeferred(String),
Compact(Option<String>),
}
#[derive(Clone, Debug)]
pub enum OrdinaryOutput {
Run(Box<RunResult>),
NoPendingResume,
Compaction(Box<CompactionResult>),
AlreadyAdmitted,
}
#[derive(Clone, Copy, Debug)]
pub enum Delivery {
Steer,
FollowUp,
NextRun,
}
#[derive(Clone, Debug)]
pub struct BackendReport {
pub outcome: BackendResult<OrdinaryOutput>,
pub write_failures: Vec<HarnessWriteFailure>,
pub unsaved_messages: usize,
pub persistence_uncertain: bool,
pub catalog_error: Option<BackendError>,
}
#[derive(Clone, Debug)]
pub struct BackendSnapshot {
pub record: AgentRecord,
pub ticket: Option<RunId>,
pub submitted_request_id: Option<String>,
pub cancel_requested: bool,
pub active: Option<ActiveOperationSnapshot>,
pub pending_resume: bool,
pub deferred: Option<String>,
pub retiring: bool,
pub closed: bool,
pub fault: Option<BackendError>,
pub last_report: Option<Arc<BackendReport>>,
}
type Completion = Option<BackendResult<Arc<BackendReport>>>;
#[derive(Clone)]
pub struct RunTicket {
pub id: RunId,
completion: watch::Receiver<Completion>,
}
impl RunTicket {
pub async fn wait(&self) -> BackendResult<Arc<BackendReport>> {
wait_completion(self.completion.clone()).await
}
}
#[derive(Clone, Debug)]
pub enum AdmissionState {
Pending,
Admitted(Arc<HostAdmissionReceipt>),
Rejected(BackendError),
}
#[derive(Clone, Debug)]
pub struct AdmittedRunTicket {
pub id: RunId,
admission: watch::Receiver<AdmissionState>,
completion: watch::Receiver<Completion>,
}
impl AdmittedRunTicket {
pub async fn wait_admitted(&self) -> BackendResult<Arc<HostAdmissionReceipt>> {
let mut receiver = self.admission.clone();
loop {
match receiver.borrow().clone() {
AdmissionState::Pending => {}
AdmissionState::Admitted(receipt) => return Ok(receipt),
AdmissionState::Rejected(error) => return Err(error),
}
receiver
.changed()
.await
.map_err(|_| BackendError::TaskStopped)?;
}
}
pub async fn wait(&self) -> BackendResult<Arc<BackendReport>> {
wait_completion(self.completion.clone()).await
}
}
pub(super) fn admission_error(error: rpi_harness::durable::DurableError) -> BackendError {
use rpi_harness::durable::DurableError as Native;
match error {
Native::Closed => BackendError::Closed,
Native::Recovering => BackendError::Busy,
Native::LimitExceeded => BackendError::InputTooLarge,
Native::InvalidRequest(_) => BackendError::Admission("invalid admission request"),
Native::Conflict => BackendError::Admission("request identity conflicts with the journal"),
Native::CommitUncertain(_) | Native::ReadFailure(_) => BackendError::AdmissionUncertain,
_ => BackendError::Faulted,
}
}
async fn wait_completion(
mut receiver: watch::Receiver<Completion>,
) -> BackendResult<Arc<BackendReport>> {
loop {
if let Some(result) = receiver.borrow().clone() {
return result;
}
receiver
.changed()
.await
.map_err(|_| BackendError::TaskStopped)?;
}
}
#[must_use = "retain the Host owner independently of transient clients"]
pub struct OrdinaryAgent {
inner: Arc<supervisor::Backend>,
}
impl OrdinaryAgent {
pub async fn restore(
catalog: HostCatalog,
id: super::AgentId,
guard: CatalogGuard,
binder: OrdinaryBinder,
) -> BackendResult<Self> {
Self::restore_with_limits(catalog, id, guard, OrdinaryLimits::default(), binder).await
}
pub async fn restore_with_limits(
catalog: HostCatalog,
id: super::AgentId,
guard: CatalogGuard,
limits: OrdinaryLimits,
binder: OrdinaryBinder,
) -> BackendResult<Self> {
Self::restore_bound(catalog, id, guard, limits, OrdinaryBinding::legacy(binder)).await
}
pub async fn restore_bound(
catalog: HostCatalog,
id: super::AgentId,
guard: CatalogGuard,
limits: OrdinaryLimits,
binding: OrdinaryBinding,
) -> BackendResult<Self> {
Self::restore_bound_with_intent(catalog, id, guard, limits, binding, false).await
}
pub(super) async fn restore_bound_with_intent(
catalog: HostCatalog,
id: super::AgentId,
guard: CatalogGuard,
limits: OrdinaryLimits,
binding: OrdinaryBinding,
attach: bool,
) -> BackendResult<Self> {
if limits.max_input_bytes == 0 {
return Err(BackendError::Binding("input byte budget must be nonzero"));
}
owned(async move { supervisor::restore(catalog, id, guard, limits, binding, attach).await })
.await
}
pub fn client(&self) -> OrdinaryClient {
OrdinaryClient {
inner: Arc::downgrade(&self.inner),
}
}
pub(super) fn shutdown_grace(&self) -> Option<std::time::Duration> {
self.inner.shutdown_grace
}
pub(super) fn reclaim_clock(&self) -> Option<watch::Receiver<ReclaimClock>> {
self.inner.reclaim.as_ref().map(watch::Sender::subscribe)
}
pub(super) async fn unload_idle(&self) -> BackendResult<()> {
self.inner.unload_idle().await
}
pub async fn close(&self) -> BackendResult<()> {
self.inner.retire();
let inner = self.inner.clone();
owned(async move { inner.close().await }).await
}
pub async fn close_guarded(&self, guard: CatalogGuard) -> BackendResult<()> {
let inner = self.inner.clone();
owned(async move { inner.close_guarded(guard).await }).await
}
}
impl Drop for OrdinaryAgent {
fn drop(&mut self) {
if self.inner.is_closed() {
return;
}
self.inner.retire();
let inner = self.inner.clone();
if let Ok(runtime) = tokio::runtime::Handle::try_current() {
runtime.spawn(async move {
if let Err(error) = inner.close().await {
if !matches!(error, BackendError::Busy) {
tracing::warn!("ordinary backend owner dropped before clean shutdown; reconciliation required");
}
}
});
} else {
tracing::warn!("ordinary backend dropped outside its runtime; reconciliation required");
}
}
}
#[derive(Clone)]
pub struct OrdinaryClient {
inner: Weak<supervisor::Backend>,
}
impl OrdinaryClient {
fn upgrade(&self) -> BackendResult<Arc<supervisor::Backend>> {
self.inner.upgrade().ok_or(BackendError::Closed)
}
pub async fn submit(&self, operation: OrdinaryOperation) -> BackendResult<RunTicket> {
let inner = self.upgrade()?;
inner.validate_operation(&operation)?;
let guard = inner
.control
.clone()
.try_lock_owned()
.map_err(|_| BackendError::Busy)?;
owned(async move { inner.submit(guard, operation).await }).await
}
pub async fn submit_admitted(
&self,
host_id: String,
request_id: String,
messages: Vec<AgentMessage>,
) -> BackendResult<AdmittedRunTicket> {
let inner = self.upgrade()?;
inner.validate_messages(&messages)?;
let guard = inner
.control
.clone()
.try_lock_owned()
.map_err(|_| BackendError::Busy)?;
owned(async move {
inner
.submit_admitted(guard, host_id, request_id, messages)
.await
})
.await
}
pub async fn admission(&self, request_id: &str) -> BackendResult<Option<HostAdmissionStatus>> {
let inner = self.upgrade()?;
inner.admission(request_id).await
}
pub async fn get_result(
&self,
run_id: &str,
history: HistoryIdentity,
) -> BackendResult<Option<(RunResult, HistoryIdentity)>> {
self.upgrade()?.get_result(run_id, history).await
}
pub async fn admissions(&self) -> BackendResult<Vec<HostAdmissionStatus>> {
let inner = self.upgrade()?;
inner.admissions().await
}
pub async fn deliver(
&self,
message: AgentMessage,
delivery: Delivery,
) -> BackendResult<QueueResult> {
let inner = self.upgrade()?;
inner.validate_message(&message)?;
let guard = inner
.control
.clone()
.try_lock_owned()
.map_err(|_| BackendError::Busy)?;
owned(async move { inner.deliver(guard, message, delivery).await }).await
}
pub async fn cancel(&self, ticket: RunId) -> BackendResult<bool> {
self.upgrade()?.cancel(ticket)
}
pub async fn cancel_guarded(&self, guard: CatalogGuard, ticket: RunId) -> BackendResult<bool> {
self.upgrade()?.cancel_guarded(guard, ticket)
}
pub async fn cancel_submitted_guarded(
&self,
guard: CatalogGuard,
request_id: &str,
) -> BackendResult<bool> {
self.upgrade()?.cancel_submitted_guarded(guard, request_id)
}
#[cfg(unix)]
pub(in crate::host) async fn area_session(
&self,
attach: bool,
) -> BackendResult<(super::area_rpc::Events, Option<AreaPeer>)> {
self.upgrade()?.area_session(attach).await
}
#[cfg(unix)]
pub(in crate::host) async fn area_command(
&self,
kind: &str,
msg: &serde_json::Value,
) -> Result<serde_json::Value, String> {
self.upgrade()
.map_err(|error| error.to_string())?
.area_command(kind, msg)
.await
}
pub async fn snapshot(&self) -> BackendResult<BackendSnapshot> {
self.upgrade()?.snapshot()
}
pub fn unsaved_messages(&self) -> BackendResult<Vec<UnsavedMessage>> {
Ok(self.upgrade()?.unsaved_messages())
}
}
async fn owned<T: Send + 'static>(
future: impl Future<Output = BackendResult<T>> + Send + 'static,
) -> BackendResult<T> {
tokio::spawn(future)
.await
.map_err(|_| BackendError::TaskStopped)?
}