Skip to content

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

feat(modules): add site memory host module

Steven Enamakel1823637f6770
diff --git a/crates/openhuman-core/src/modules/host.rs b/crates/openhuman-core/src/modules/host.rs
index 80d352c685..6e3e7c5e52 100644
--- a/crates/openhuman-core/src/modules/host.rs
+++ b/crates/openhuman-core/src/modules/host.rs
@@ -194,6 +194,7 @@ async fn build_runtime() -> tinybus::Result<ModuleRuntime> {
} else {
tracing::debug!("[modules] juice component off; MlHost not served");
}
+ super::site_memory_host::install(&connection).await?;
super::storage_host::install(&connection).await?;
#[cfg(feature = "tinymemes")]
{
diff --git a/crates/openhuman-core/src/modules/mod.rs b/crates/openhuman-core/src/modules/mod.rs
index a88334c077..cf63fe6fec 100644
--- a/crates/openhuman-core/src/modules/mod.rs
+++ b/crates/openhuman-core/src/modules/mod.rs
@@ -89,6 +89,8 @@ mod source;
#[cfg(feature = "modules")]
pub mod storage_grants;
#[cfg(feature = "modules")]
+mod site_memory_host;
+#[cfg(feature = "modules")]
mod storage_host;
#[cfg(feature = "modules")]
pub mod tinybox;
diff --git a/crates/openhuman-core/src/modules/site_memory_host.rs b/crates/openhuman-core/src/modules/site_memory_host.rs
new file mode 100644
index 0000000000..ef802c6fb2
--- /dev/null
+++ b/crates/openhuman-core/src/modules/site_memory_host.rs
@@ -0,0 +1,228 @@
+//! Host side of `ai.tinyhumans.tinycomputer.SiteMemoryHost`: where the
+//! TinyComputer module keeps what finished browser tasks learned about a site.
+//!
+//! The module owns the rules (reuse, fact-value filtering, expiry, size
+//! limits); the host owns only the bytes: one file per site in
+//! `<workspace>/state/computer/sites/<site>.json`, readable by its owner
+//! alone. Site memory goes to the module and nowhere else: this file never
+//! publishes it to the event bus, the agent's memory or a prompt.
+
+use std::path::{Path, PathBuf};
+
+use tinybus::ObjectPath;
+use tinycomputer_bus::site_memory::{
+ ForgetSiteRequest, ForgetSiteResponse, LoadSiteRequest, LoadSiteResponse, SaveSiteRequest,
+ SaveSiteResponse, SiteMemory, INTERFACE, OBJECT_PATH,
+};
+
+/// Largest site file read or written: anything bigger was not written here.
+const MAX_FILE_BYTES: u64 = 2 * 1024 * 1024;
+
+/// The directory site files live in.
+pub(super) fn sites_dir(workspace: &Path) -> PathBuf {
+ workspace.join("state").join("computer").join("sites")
+}
+
+/// Whether `site` is a plain lower-cased host name and so a safe file stem.
+fn plain_site(site: &str) -> bool {
+ !site.is_empty()
+ && site.len() <= 253
+ && !site.starts_with('.')
+ && !site.contains("..")
+ && site
+ .bytes()
+ .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'.' || b == b'-')
+}
+
+/// The site files under one directory.
+pub(super) struct SiteStore {
+ dir: PathBuf,
+}
+
+impl SiteStore {
+ pub(super) fn new(dir: PathBuf) -> Self {
+ Self { dir }
+ }
+
+ fn path(&self, site: &str) -> std::io::Result<PathBuf> {
+ if plain_site(site) {
+ Ok(self.dir.join(format!("{site}.json")))
+ } else {
+ Err(std::io::Error::new(
+ std::io::ErrorKind::InvalidInput,
+ "site is not a plain host name",
+ ))
+ }
+ }
+
+ /// `site`'s memory; a missing file is empty, and an unreadable one is set
+ /// aside as `<site>.json.corrupt` and read as empty.
+ pub(super) async fn load(&self, site: &str) -> std::io::Result<SiteMemory> {
+ let path = self.path(site)?;
+ let read = match tokio::fs::metadata(&path).await {
+ Ok(m) if m.len() <= MAX_FILE_BYTES => tokio::fs::read(&path).await,
+ Ok(_) => Err(std::io::Error::other("larger than a site file can be")),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+ return Ok(SiteMemory::default())
+ }
+ Err(e) => Err(e),
+ };
+ match read.and_then(|b| serde_json::from_slice(&b).map_err(std::io::Error::other)) {
+ Ok(memory) => Ok(memory),
+ Err(error) => {
+ tracing::warn!(%error, "[site-memory-host] unreadable site file set aside");
+ let _ = tokio::fs::rename(&path, path.with_extension("json.corrupt")).await;
+ Ok(SiteMemory::default())
+ }
+ }
+ }
+
+ /// Replaces `site`'s memory; an empty one removes the file. Returns
+ /// whether the file holds the memory as sent.
+ pub(super) async fn save(&self, site: &str, memory: &SiteMemory) -> std::io::Result<bool> {
+ let path = self.path(site)?;
+ if memory.is_empty() {
+ remove(&path).await?;
+ return Ok(true);
+ }
+ let bytes = serde_json::to_vec_pretty(memory).map_err(std::io::Error::other)?;
+ if u64::try_from(bytes.len()).map_or(true, |n| n > MAX_FILE_BYTES) {
+ tracing::warn!("[site-memory-host] site memory over the file limit; not saved");
+ return Ok(false);
+ }
+ write_private(&path, &bytes).await?;
+ Ok(true)
+ }
+
+ /// Forgets `site`, or every site; returns how many were forgotten.
+ pub(super) async fn forget(&self, site: Option<&str>) -> std::io::Result<u64> {
+ if let Some(site) = site {
+ let path = self.path(site)?;
+ let aside = remove(&path.with_extension("json.corrupt")).await?;
+ remove(&path.with_extension("json.tmp")).await?;
+ let kept = remove(&path).await?;
+ return Ok(u64::from(kept || aside));
+ }
+ let mut entries = match tokio::fs::read_dir(&self.dir).await {
+ Ok(entries) => entries,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0),
+ Err(e) => return Err(e),
+ };
+ let mut sites = std::collections::BTreeSet::new();
+ while let Some(entry) = entries.next_entry().await? {
+ if entry.file_type().await?.is_file() {
+ let name = entry.file_name().to_string_lossy().into_owned();
+ if let Some(site) = name
+ .strip_suffix(".json")
+ .or_else(|| name.strip_suffix(".json.corrupt"))
+ {
+ sites.insert(site.to_owned());
+ }
+ remove(&entry.path()).await?;
+ }
+ }
+ Ok(sites.len() as u64)
+ }
+}
+
+async fn remove(path: &Path) -> std::io::Result<bool> {
+ match tokio::fs::remove_file(path).await {
+ Ok(()) => Ok(true),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
+ Err(e) => Err(e),
+ }
+}
+
+/// Writes through a temporary file, in a directory and file only their owner
+/// can read: plans and elements tell where a person browses.
+async fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
+ use tokio::io::AsyncWriteExt;
+ if let Some(dir) = path.parent() {
+ tokio::fs::create_dir_all(dir).await?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ tokio::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)).await?;
+ }
+ }
+ let staged = path.with_extension("json.tmp");
+ let mut options = tokio::fs::OpenOptions::new();
+ options.write(true).create(true).truncate(true);
+ #[cfg(unix)]
+ options.mode(0o600);
+ let mut file = options.open(&staged).await?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ file.set_permissions(std::fs::Permissions::from_mode(0o600))
+ .await?;
+ }
+ file.write_all(bytes).await?;
+ file.flush().await?;
+ drop(file);
+ tokio::fs::rename(&staged, path).await
+}
+
+#[derive(Clone)]
+struct SiteMemoryHost;
+
+async fn store() -> tinybus::Result<SiteStore> {
+ let config = crate::config::rpc::load_config_with_timeout()
+ .await
+ .map_err(|e| method_error(format!("config unavailable: {e}")))?;
+ Ok(SiteStore::new(sites_dir(&config.workspace_dir)))
+}
+
+#[tinybus::interface(name = "ai.tinyhumans.tinycomputer.SiteMemoryHost")]
+impl SiteMemoryHost {
+ /// One site's memory; empty for a site with nothing kept.
+ async fn load(&self, request: LoadSiteRequest) -> tinybus::Result<LoadSiteResponse> {
+ let memory = store()
+ .await?
+ .load(&request.site)
+ .await
+ .map_err(method_error)?;
+ Ok(LoadSiteResponse { memory })
+ }
+
+ /// Replaces one site's memory.
+ async fn save(&self, request: SaveSiteRequest) -> tinybus::Result<SaveSiteResponse> {
+ let saved = store()
+ .await?
+ .save(&request.site, &request.memory)
+ .await
+ .map_err(method_error)?;
+ Ok(SaveSiteResponse { saved })
+ }
+
+ /// Forgets one site, or every site.
+ async fn forget(&self, request: ForgetSiteRequest) -> tinybus::Result<ForgetSiteResponse> {
+ let forgotten = store()
+ .await?
+ .forget(request.site.as_deref())
+ .await
+ .map_err(method_error)?;
+ Ok(ForgetSiteResponse { forgotten })
+ }
+}
+
+fn method_error(error: impl std::fmt::Display) -> tinybus::Error {
+ tinybus::Error::MethodFailed {
+ name: "ai.tinyhumans.tinycomputer.Error.SiteMemoryHost".to_string(),
+ message: error.to_string(),
+ }
+}
+
+pub(super) async fn install(connection: &tinybus::Connection) -> tinybus::Result<()> {
+ connection
+ .serve_at(ObjectPath::new(OBJECT_PATH)?, SiteMemoryHost)
+ .await?;
+ // The interface name is served at the module's own bus name; the module
+ // reaches it through the host connection already holding the object.
+ tracing::debug!(interface = INTERFACE, "[site-memory-host] served");
+ Ok(())
+}
+
+#[cfg(test)]
+#[path = "site_memory_host_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/modules/site_memory_host_tests.rs b/crates/openhuman-core/src/modules/site_memory_host_tests.rs
new file mode 100644
index 0000000000..98d7fe0a04
--- /dev/null
+++ b/crates/openhuman-core/src/modules/site_memory_host_tests.rs
@@ -0,0 +1,84 @@
+use super::*;
+use tinycomputer_bus::site_memory::SavedHint;
+
+fn memory() -> SiteMemory {
+ serde_json::from_value(serde_json::json!({
+ "hints": [{"hint": {"app": "browser", "key": "k", "role": "button", "name": "Go"}, "ok_at": 7}]
+ }))
+ .unwrap()
+}
+
+fn store() -> (tempfile::TempDir, SiteStore) {
+ let dir = tempfile::tempdir().unwrap();
+ let store = SiteStore::new(sites_dir(dir.path()));
+ (dir, store)
+}
+
+#[tokio::test]
+async fn saved_memory_loads_back_and_empty_save_removes_the_site() {
+ let (_dir, store) = store();
+ assert!(store.load("example.com").await.unwrap().is_empty());
+ assert!(store.save("example.com", &memory()).await.unwrap());
+ let back = store.load("example.com").await.unwrap();
+ assert_eq!(back, memory());
+ let _: &SavedHint = &back.hints[0];
+ assert!(store.save("example.com", &SiteMemory::default()).await.unwrap());
+ assert!(store.load("example.com").await.unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn a_site_that_is_not_a_plain_host_is_refused() {
+ let (_dir, store) = store();
+ for bad in ["", "../x", "a/b", "A.com", ".hidden", "a..b"] {
+ assert!(store.save(bad, &memory()).await.is_err(), "{bad}");
+ assert!(store.load(bad).await.is_err(), "{bad}");
+ }
+}
+
+#[tokio::test]
+async fn an_unreadable_file_is_set_aside_and_read_as_empty() {
+ let (dir, store) = store();
+ let sites = sites_dir(dir.path());
+ std::fs::create_dir_all(&sites).unwrap();
+ std::fs::write(sites.join("x.com.json"), b"not json").unwrap();
+ assert!(store.load("x.com").await.unwrap().is_empty());
+ assert!(sites.join("x.com.json.corrupt").exists());
+ assert_eq!(store.forget(Some("x.com")).await.unwrap(), 1);
+}
+
+#[tokio::test]
+async fn forgetting_every_site_counts_distinct_sites() {
+ let (_dir, store) = store();
+ store.save("a.com", &memory()).await.unwrap();
+ store.save("b.com", &memory()).await.unwrap();
+ assert_eq!(store.forget(None).await.unwrap(), 2);
+ assert_eq!(store.forget(None).await.unwrap(), 0);
+}
+
+#[cfg(unix)]
+#[tokio::test]
+async fn site_files_are_private_to_their_owner() {
+ use std::os::unix::fs::PermissionsExt;
+ let (dir, store) = store();
+ store.save("a.com", &memory()).await.unwrap();
+ let mode = std::fs::metadata(sites_dir(dir.path()).join("a.com.json"))
+ .unwrap()
+ .permissions()
+ .mode();
+ assert_eq!(mode & 0o777, 0o600);
+}
+
+#[test]
+fn site_memory_is_never_published_to_agent_memory_or_prompts() {
+ // The adapter must stay a pure file store: no event bus, memory or prompt
+ // surface may be named in its source.
+ let source = include_str!("site_memory_host.rs");
+ let code = source.split("#[cfg(test)]").next().unwrap();
+ for forbidden in ["BUS.", "crate::memory", "prompt", "DomainEvent"] {
+ let hits = code
+ .lines()
+ .filter(|l| !l.trim_start().starts_with("//") && l.contains(forbidden))
+ .count();
+ assert_eq!(hits, 0, "{forbidden}");
+ }
+}