Skip to content

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

feat(memory): add billing module for memory engine

Steven Enamakela07a3b079283
diff --git a/crates/openhuman-tinyhumans/src/memory/billing.rs b/crates/openhuman-tinyhumans/src/memory/billing.rs
new file mode 100644
index 0000000000..40b77dbdea
--- /dev/null
+++ b/crates/openhuman-tinyhumans/src/memory/billing.rs
@@ -0,0 +1,132 @@
+//! The hosted engine's "background work is free" predicate.
+//!
+//! Background memory jobs that write a user's whole memory again start on
+//! their own only when that costs the user nothing. For the hosted
+//! `tinyhumans` engine that is true only while the backend's memory free
+//! period is on (`GET /memory/free-period`). The answer is cached for
+//! [`CACHE_TTL`] per backend and account.
+//!
+//! Anything unknown (signed out, an error, a backend without the route) is
+//! not free, so nothing starts on its own.
+
+use std::collections::HashMap;
+use std::time::{Duration, Instant};
+
+use openhuman_embed::__host::config::Config;
+use openhuman_embed::__host::memory_engines::BoundEngine;
+use openhuman_embed::__host::security::credentials::session_support::{
+ resolve_backend_credential, BackendCredential,
+};
+use sha2::Digest;
+
+use crate::client::{flatten_authed_error, BackendClient};
+
+/// How long an answer is reused. A job polls between batches; the period
+/// changes on the order of days, so a minute keeps it to one request a minute.
+pub(crate) const CACHE_TTL: Duration = Duration::from_secs(60);
+
+/// The last answer for each backend. One async lock covers the lookup and the
+/// fetch on a miss, so concurrent callers (two jobs polling at once) wait for
+/// one request rather than each sending their own.
+pub(crate) struct Answer {
+ inner: tokio::sync::Mutex<Option<HashMap<String, (Instant, bool)>>>,
+}
+
+impl Answer {
+ pub(crate) const fn new() -> Self {
+ Self {
+ inner: tokio::sync::Mutex::const_new(None),
+ }
+ }
+}
+
+static ANSWER: Answer = Answer::new();
+
+/// Whether memory work is free for the user right now on the hosted engine.
+pub(crate) async fn free_period_active(config: Config, bound: BoundEngine) -> bool {
+ let Ok(credential) = resolve_backend_credential(&config) else {
+ tracing::debug!("[tinyhumans][memory] free period: no credential; not free");
+ return false;
+ };
+ // The answer is the account's on the backend memory is bound to, so the
+ // cache is keyed by both: one account's answer never serves another.
+ let key = format!("{}|{}", bound.endpoint, digest(credential.secret()));
+ active_with_cache(&ANSWER, &key, CACHE_TTL, Instant::now, || {
+ fetch(&credential, &bound.endpoint)
+ })
+ .await
+}
+
+/// A one-way digest of a credential for a cache key: the full SHA-256, so
+/// two accounts never share a key.
+pub(crate) fn digest(secret: &str) -> String {
+ sha2::Sha256::digest(secret.as_bytes())
+ .iter()
+ .map(|byte| format!("{byte:02x}"))
+ .collect()
+}
+
+/// Asks `backend` whether its memory free period is on for `credential`.
+pub(crate) async fn fetch(credential: &BackendCredential, backend: &str) -> Result<bool, String> {
+ let client = BackendClient::new(backend).map_err(|e| format!("{e:#}"))?;
+ let data = client
+ .authed_json(
+ credential.clone(),
+ reqwest::Method::GET,
+ "/memory/free-period",
+ None,
+ )
+ .await
+ .map_err(flatten_authed_error)?;
+ parse_active(&data)
+}
+
+/// `active` from the route's answer; anything else is an error. The
+/// transport unwraps the `{success, data}` envelope, but an answer that
+/// still carries it is read the same way.
+pub(crate) fn parse_active(data: &serde_json::Value) -> Result<bool, String> {
+ data.get("data")
+ .unwrap_or(data)
+ .get("active")
+ .and_then(serde_json::Value::as_bool)
+ .ok_or_else(|| "free-period answer has no boolean `active`".to_string())
+}
+
+/// The cached answer for `key`, else `fetch`'s, with a failure read as not
+/// free. Failures are cached too, so a backend without the route is asked
+/// once a minute, not once a batch.
+pub(crate) async fn active_with_cache<F, Fut>(
+ cache: &Answer,
+ key: &str,
+ ttl: Duration,
+ clock: impl Fn() -> Instant,
+ fetch: F,
+) -> bool
+where
+ F: FnOnce() -> Fut,
+ Fut: std::future::Future<Output = Result<bool, String>>,
+{
+ let mut answers = cache.inner.lock().await;
+ let answers = answers.get_or_insert_with(HashMap::new);
+ // Read after the lock: a wait behind another backend's fetch must not
+ // stretch a cached answer past its TTL.
+ let now = clock();
+ if let Some((_, active)) = answers
+ .get(key)
+ .filter(|(at, _)| now.duration_since(*at) < ttl)
+ {
+ return *active;
+ }
+ let active = match fetch().await {
+ Ok(active) => active,
+ Err(_) => {
+ // The error text can carry the backend's response; it is not
+ // logged.
+ tracing::debug!("[tinyhumans][memory] free period unknown; treating as not free");
+ false
+ }
+ };
+ // The answer's age starts when it arrives, not when it was asked for.
+ answers.insert(key.to_string(), (clock(), active));
+ active
+}
diff --git a/crates/openhuman-tinyhumans/src/memory/engine.rs b/crates/openhuman-tinyhumans/src/memory/engine.rs
new file mode 100644
index 0000000000..9bbe7f1cce
--- /dev/null
+++ b/crates/openhuman-tinyhumans/src/memory/engine.rs
@@ -0,0 +1,120 @@
+//! Binding the hosted `tinyhumans` memory engine.
+//!
+//! | | |
+//! | --- | --- |
+//! | Endpoint | `[memory.engines.tinyhumans] endpoint`, else the control-plane origin |
+//! | Credential | the host's backend credential, resolved per request |
+//! | Headers | the attribution headers (`x-sdk-name`, ...) every backend caller sends |
+//! | Off when | signed out or on the offline local session |
+//!
+//! The layout root arrives in the [`EngineRequest`]; on the TinyHumans wire
+//! the tenant root is pinned by the backend, so none is sent. The core's
+//! engine cache keys built engines by the fingerprint formed here.
+
+use std::collections::BTreeMap;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use openhuman_embed::__host::config::Config;
+use openhuman_embed::__host::memory_engines::{
+ build_cached, rooted, BearerSource, Binding, EngineCredential, EngineRequest, EngineSettings,
+ TINYHUMANS_ENGINE,
+};
+use openhuman_embed::__host::security::credentials::session_support::resolve_backend_credential;
+
+use crate::backend::headers::attribution_headers;
+use crate::backend::url::effective_backend_api_url;
+
+fn off(endpoint: Option<String>, reason: &str) -> Binding {
+ Binding::Off {
+ engine: Some(TINYHUMANS_ENGINE.to_string()),
+ endpoint,
+ reason: reason.to_string(),
+ }
+}
+
+/// The endpoint memory talks to for `config`.
+pub(crate) fn endpoint_for(config: &Config) -> String {
+ config
+ .memory
+ .endpoint_for(TINYHUMANS_ENGINE)
+ .unwrap_or_else(|| effective_backend_api_url(&config.api_url))
+}
+
+/// Binds the hosted engine for `request.config` below `request.root`.
+pub(crate) fn bind(request: &EngineRequest<'_>) -> Binding {
+ let config = request.config;
+ let endpoint = endpoint_for(config);
+ if let Err(error) = resolve_backend_credential(config) {
+ tracing::debug!(error = %error, "[tinyhumans][memory] no usable TinyHumans credential");
+ return off(Some(endpoint), "sign in to use TinyHumans memory");
+ }
+ // The backend expects the host's attribution (`x-sdk-name`, ...) on every
+ // request, as every other backend caller sends it.
+ let headers = engine_headers();
+ let fingerprint = format!(
+ "{TINYHUMANS_ENGINE}|{endpoint}|{}|{headers:?}",
+ config.config_path.display()
+ );
+ let source: Arc<dyn BearerSource> = Arc::new(HostBearer {
+ config: Arc::new(config.clone()),
+ });
+ let (settings, layout) = rooted(
+ EngineSettings {
+ endpoint: Some(endpoint),
+ headers,
+ ..EngineSettings::default()
+ },
+ request.root,
+ true,
+ config.memory.legacy_user_segment_read,
+ );
+ build_cached(
+ TINYHUMANS_ENGINE,
+ settings,
+ fingerprint + &layout,
+ EngineCredential::Dynamic(source),
+ )
+}
+
+/// The attribution headers as engine settings carry them. A value that is not
+/// text is left out (and logged by name only).
+fn engine_headers() -> BTreeMap<String, String> {
+ let headers = match attribution_headers() {
+ Ok(headers) => headers,
+ Err(error) => {
+ tracing::debug!(error = %error, "[tinyhumans][memory] attribution headers unavailable");
+ return BTreeMap::new();
+ }
+ };
+ headers
+ .iter()
+ .filter_map(|(name, value)| match value.to_str() {
+ Ok(value) => Some((name.as_str().to_string(), value.to_string())),
+ Err(_) => {
+ tracing::debug!(header = %name, "[tinyhumans][memory] skipping a non-text attribution header");
+ None
+ }
+ })
+ .collect()
+}
+
+/// The host's backend credential as a per-request bearer.
+pub(crate) struct HostBearer {
+ pub(crate) config: Arc<Config>,
+}
+
+#[async_trait]
+impl BearerSource for HostBearer {
+ async fn bearer(&self) -> openhuman_embed::memory::api::Result<String> {
+ match resolve_backend_credential(&self.config) {
+ Ok(credential) => Ok(credential.into_secret()),
+ Err(error) => {
+ tracing::debug!(error = %error, "[tinyhumans][memory] backend credential unavailable");
+ Err(openhuman_embed::memory::api::Error::Unauthorized(
+ "the backend credential is unavailable".to_string(),
+ ))
+ }
+ }
+ }
+}
diff --git a/crates/openhuman-tinyhumans/src/memory/mod.rs b/crates/openhuman-tinyhumans/src/memory/mod.rs
index fdd11f81a6..a76ba3f3dc 100644
--- a/crates/openhuman-tinyhumans/src/memory/mod.rs
+++ b/crates/openhuman-tinyhumans/src/memory/mod.rs
@@ -1,14 +1,42 @@
//! The hosted `tinyhumans` memory engine and its free-period check.
//!
-//! Empty for now: the code for this area moves here from `openhuman-core`'s
-//! `backend/` and its consumers, and plugs back into the core through the
-//! generic registries on `openhuman_embed::__host` (`memory_engines`). [`register`] is the
-//! one place it does so; `crate::register::register_all` calls it from
-//! `install()`.
+//! [`register`] hands the core's memory engine registry
+//! (`openhuman_embed::__host::memory_engines`) the engine id `tinyhumans`:
+//!
+//! - [`engine`] binds TinyMemory's CortexDB engine to the TinyHumans backend
+//! (endpoint, attribution headers, per-request bearer), below the layout
+//! root the core passes in the [`EngineRequest`] (`memory::scope::user_root`).
+//! - [`billing`] is the "background work is free" predicate: free only while
+//! the backend's memory free period is on, answered by a cached
+//! `GET /memory/free-period`.
+//!
+//! Generic engine resolution, scope and the `cortexdb` engine stay in the core.
+//! With nothing registered the core answers `tinyhumans` as unavailable.
+
+pub(crate) mod billing;
+pub(crate) mod engine;
+
+use openhuman_embed::__host::memory_engines::{
+ register_memory_engine, EngineEntry, TINYHUMANS_ENGINE,
+};
+use std::sync::Arc;
use crate::install::InstallOptions;
/// Registers this area's hooks with the core. Idempotent.
pub(crate) fn register(_options: &InstallOptions) {
- log::trace!("[tinyhumans] memory: nothing to register yet");
+ register_memory_engine(
+ TINYHUMANS_ENGINE,
+ EngineEntry {
+ build: Arc::new(engine::bind),
+ free_background: Some(Arc::new(|config, bound| {
+ Box::pin(billing::free_period_active(config, bound))
+ })),
+ },
+ );
+ log::debug!("[tinyhumans] memory: hosted engine registered as '{TINYHUMANS_ENGINE}'");
}
+
+#[cfg(test)]
+#[path = "mod_tests.rs"]
+mod tests;