Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

refactor(memory): delegate error and status mapping to tinymemory_api

Steven Enamakeld4cb74ad006c
diff --git a/crates/openhuman-core/src/memory/error.rs b/crates/openhuman-core/src/memory/error.rs
index fab30a3017..44dbd441db 100644
--- a/crates/openhuman-core/src/memory/error.rs
+++ b/crates/openhuman-core/src/memory/error.rs
@@ -1,156 +1,27 @@
-//! The memory RPC error taxonomy.
-//!
-//! Every `openhuman.memory_*` failure carries one of seven stable codes in its
-//! structured error `data.code` (and `data.kind`): `MEMORY_OFF`,
-//! `UNSUPPORTED`, `INVALID_REQUEST`, `UNAUTHORIZED`, `INSUFFICIENT_CREDITS`,
-//! `UNAVAILABLE` or `ENGINE`. The two account-wide refusals are split out of
-//! `ENGINE` so a caller can tell "top up" and "try again later" apart from an
-//! engine fault, and neither from an empty memory (#6718). Messages never
-//! carry a credential: engine errors are already sanitised by TinyMemory, and
-//! the host adds only ids and reasons.
+//! Maps TinyMemory failures to the existing memory RPC error envelope.
use serde_json::json;
use crate::core::StructuredRpcError;
-/// `data.code` when no usable engine is configured.
-pub const MEMORY_OFF: &str = "MEMORY_OFF";
-/// `data.code` when the engine does not offer the requested operation.
-pub const UNSUPPORTED: &str = "UNSUPPORTED";
-/// `data.code` for a malformed or refused request.
-pub const INVALID_REQUEST: &str = "INVALID_REQUEST";
-/// `data.code` when the engine rejected the credential.
-pub const UNAUTHORIZED: &str = "UNAUTHORIZED";
-/// `data.code` when the hosted engine refused for an exhausted credit balance.
-pub const INSUFFICIENT_CREDITS: &str = "INSUFFICIENT_CREDITS";
-/// `data.code` when the engine could not be reached or is overloaded.
-pub const UNAVAILABLE: &str = "UNAVAILABLE";
-/// `data.code` for the engine's own failure.
-pub const ENGINE: &str = "ENGINE";
-
-/// A memory operation failure.
-#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
-pub enum Error {
- /// Memory is off: no usable engine.
- #[error("memory is off: {0}")]
- Off(String),
- /// The engine does not offer this.
- #[error("unsupported: {0}")]
- Unsupported(String),
- /// The request was malformed or refused.
- #[error("invalid request: {0}")]
- InvalidRequest(String),
- /// The engine rejected the credential.
- #[error("unauthorized: {0}")]
- Unauthorized(String),
- /// The hosted engine refused: the account is out of credits.
- #[error("insufficient credits: {0}")]
- InsufficientCredits(String),
- /// The engine could not be reached, timed out or is overloaded.
- #[error("unavailable: {0}")]
- Unavailable(String),
- /// The engine (or the host around it) failed.
- #[error("engine error: {0}")]
- Engine(String),
-}
-
-impl Error {
- /// The stable wire code.
- #[must_use]
- pub fn code(&self) -> &'static str {
- match self {
- Self::Off(_) => MEMORY_OFF,
- Self::Unsupported(_) => UNSUPPORTED,
- Self::InvalidRequest(_) => INVALID_REQUEST,
- Self::Unauthorized(_) => UNAUTHORIZED,
- Self::InsufficientCredits(_) => INSUFFICIENT_CREDITS,
- Self::Unavailable(_) => UNAVAILABLE,
- Self::Engine(_) => ENGINE,
- }
- }
-
- /// Shorthand for [`Self::InvalidRequest`].
- pub fn invalid(message: impl Into<String>) -> Self {
- Self::InvalidRequest(message.into())
- }
-
- /// Whether this refuses every request on the account, not just this one:
- /// memory off, a rejected credential, no credits, or no engine to reach.
- /// A loop over items stops on these instead of skipping every item, and
- /// a queued job is not charged an attempt for them.
- #[must_use]
- pub fn is_account_wide(&self) -> bool {
- matches!(
- self,
- Self::Off(_)
- | Self::Unauthorized(_)
- | Self::InsufficientCredits(_)
- | Self::Unavailable(_)
- )
- }
-
- /// The structured JSON-RPC error. Everything except an engine failure is
- /// an expected user-visible state, so the boundary does not report it.
- #[must_use]
- pub fn to_structured(&self) -> StructuredRpcError {
- StructuredRpcError {
- message: self.to_string(),
- data: Some(json!({ "kind": self.code(), "code": self.code() })),
- expected_user_state: !matches!(self, Self::Engine(_)),
- }
- }
-}
-
-impl From<tinymemory_api::Error> for Error {
+impl From<tinymemory_api::Error> for StructuredRpcError {
fn from(error: tinymemory_api::Error) -> Self {
- use tinymemory_api::Error as E;
- // A 402 arrives as `Engine` with the backend's code on its message.
- let credits = tinymemory_integrations::cortex::is_insufficient_credits(&error);
- match error {
- E::Unsupported(message) => Self::Unsupported(message),
- E::InvalidRequest(message) | E::NotFound(message) => Self::InvalidRequest(message),
- E::Unauthorized(message) => Self::Unauthorized(message),
- E::Config(message) => Self::InvalidRequest(message),
- E::Unavailable(message) => Self::Unavailable(message),
- E::Engine(message) if credits => Self::InsufficientCredits(message),
- E::Conflict(message) | E::Engine(message) => Self::Engine(message),
- }
- }
-}
-
-impl Error {
- /// The account-wide refusal behind a recall section's skip reason, if it
- /// was one.
- ///
- /// TinyMemory's holistic recall does not fail when a section's read
- /// fails: it skips the section and keeps the engine error's text as the
- /// reason. That text is `tinymemory_api::Error`'s `Display`, so the
- /// variant can be read back from its tag (`unauthorized: `,
- /// `unavailable: `, `engine error: [USER_INSUFFICIENT_CREDITS] …`).
- #[must_use]
- pub fn refusal_from_skip_reason(reason: &str) -> Option<Self> {
- use tinymemory_api::Error as E;
- let error = if let Some(message) = reason.strip_prefix("unauthorized: ") {
- E::Unauthorized(message.to_string())
- } else if let Some(message) = reason.strip_prefix("unavailable: ") {
- E::Unavailable(message.to_string())
- } else {
- let message = reason.strip_prefix("engine error: ")?;
- E::Engine(message.to_string())
+ let code = error.code();
+ let message = match error {
+ tinymemory_api::Error::NotFound(message)
+ | tinymemory_api::Error::Config(message) => format!("invalid request: {message}"),
+ tinymemory_api::Error::Conflict(message) => format!("engine error: {message}"),
+ error => error.to_string(),
};
- Some(Self::from(error)).filter(Self::is_account_wide)
- }
-}
-impl From<Error> for String {
- fn from(error: Error) -> Self {
- error.to_structured().encode()
+ Self {
+ message,
+ data: Some(json!({ "kind": code, "code": code })),
+ expected_user_state: code != "ENGINE",
+ }
}
}
-/// Result alias for memory operations.
-pub type Result<T> = Result<T, Error>;
-
#[cfg(test)]
#[path = "error_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/memory/status.rs b/crates/openhuman-core/src/memory/status.rs
index d86cc2d251..cc429bd43a 100644
--- a/crates/openhuman-core/src/memory/status.rs
+++ b/crates/openhuman-core/src/memory/status.rs
@@ -5,33 +5,16 @@ use crate::core::subsystem::SubsystemStatus;
use super::engine::{self, Binding};
-/// Contract version the memory slot speaks: TinyMemory's v2 engine contract.
-pub const CONTRACT_VERSION: &str = "2.0";
-
-/// The operations every v2 engine serves.
-const OPERATIONS: [&str; 5] = ["recall", "fetch", "store", "forget", "list"];
-
/// The memory slot's status for `config`: the bound engine and its health, or
/// a `null` row with the reason memory is off.
pub async fn subsystem_status(config: &Config) -> SubsystemStatus {
match engine::resolve(config) {
Binding::On(bound) => {
- let (health, reason) = match bound.engine.health().await {
- tinymemory_api::EngineHealth::Ok => ("ready", None),
- tinymemory_api::EngineHealth::Degraded(reason) => ("degraded", Some(reason)),
- tinymemory_api::EngineHealth::Down(reason) => ("down", Some(reason)),
- };
- SubsystemStatus {
- slot: "memory".to_string(),
- driver: bound.id,
- class: "external".to_string(),
- health: health.to_string(),
- health_reason: reason,
- contract_version: CONTRACT_VERSION.to_string(),
- capabilities: OPERATIONS.iter().map(|op| (*op).to_string()).collect(),
- fell_back_from: None,
- last_error: None,
- }
+ let status = tinymemory_api::EngineStatus::from_engine(
+ bound.engine.descriptor(),
+ bound.engine.health().await,
+ );
+ subsystem_status_for_engine(bound.id, status)
}
Binding::Off { engine, reason, .. } => SubsystemStatus {
slot: "memory".to_string(),
@@ -39,7 +22,7 @@ pub async fn subsystem_status(config: &Config) -> SubsystemStatus {
class: "null".to_string(),
health: "down".to_string(),
health_reason: Some(reason),
- contract_version: CONTRACT_VERSION.to_string(),
+ contract_version: tinymemory_api::CONTRACT_VERSION.to_string(),
capabilities: Vec::new(),
fell_back_from: engine,
last_error: None,
@@ -47,6 +30,28 @@ pub async fn subsystem_status(config: &Config) -> SubsystemStatus {
}
}
+fn subsystem_status_for_engine(
+ driver: String,
+ status: tinymemory_api::EngineStatus,
+) -> SubsystemStatus {
+ let health = match status.health {
+ tinymemory_api::EngineStatusHealth::Ready => "ready",
+ tinymemory_api::EngineStatusHealth::Degraded => "degraded",
+ tinymemory_api::EngineStatusHealth::Down | tinymemory_api::EngineStatusHealth::Off => "down",
+ };
+ SubsystemStatus {
+ slot: "memory".to_string(),
+ driver,
+ class: "external".to_string(),
+ health: health.to_string(),
+ health_reason: status.reason,
+ contract_version: status.contract_version.to_string(),
+ capabilities: status.capabilities.into_iter().map(str::to_string).collect(),
+ fell_back_from: None,
+ last_error: None,
+ }
+}
+
#[cfg(test)]
#[path = "status_tests.rs"]
mod tests;
diff --git a/crates/openhuman-core/src/memory/status_tests.rs b/crates/openhuman-core/src/memory/status_tests.rs
index e3f34ee0d4..78b9a294e4 100644
--- a/crates/openhuman-core/src/memory/status_tests.rs
+++ b/crates/openhuman-core/src/memory/status_tests.rs
@@ -30,7 +30,7 @@ fn upstream_engine_status_maps_health_reason_and_capabilities() {
assert_eq!(row.class, "external");
assert_eq!(row.health, expected_health);
assert_eq!(row.health_reason, reason);
- assert_eq!(row.contract_version, "2.0");
+ assert_eq!(row.contract_version, tinymemory_api::CONTRACT_VERSION);
assert_eq!(row.capabilities, vec!["recall", "store"]);
assert!(row.fell_back_from.is_none());
assert!(row.last_error.is_none());
@@ -47,7 +47,7 @@ async fn memory_off_reports_a_null_row_with_the_reason() {
assert_eq!(row.class, "null");
assert_eq!(row.health, "down");
assert!(row.health_reason.is_some());
- assert_eq!(row.contract_version, CONTRACT_VERSION);
+ assert_eq!(row.contract_version, tinymemory_api::CONTRACT_VERSION);
assert!(row.capabilities.is_empty());
assert_eq!(
row.fell_back_from.as_deref(),