Skip to content

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

fix(composio): persist document metadata in file store

Steven Enamakel4481b4964bd3
diff --git a/crates/openhuman-core/src/integrations/composio/file_store.rs b/crates/openhuman-core/src/integrations/composio/file_store.rs
index 1c8a5e6136..3c5eaf9320 100644
--- a/crates/openhuman-core/src/integrations/composio/file_store.rs
+++ b/crates/openhuman-core/src/integrations/composio/file_store.rs
@@ -44,6 +44,11 @@ pub(crate) async fn load<T>(path: &Path) -> Result<T, String>
where
T: DeserializeOwned + Default,
{
+ if let Some(docs) = super::file_store_documents::current().map_err(|e| format!("[composio:store] {e:#}"))? {
+ return docs
+ .load(path)
+ .map_err(|error| format!("[composio:store] reading {} failed: {error:#}", path.display()));
+ }
let bytes = match tokio::fs::read(path).await {
Ok(bytes) => bytes,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(T::default()),
@@ -71,6 +76,11 @@ pub(crate) async fn save<T>(path: &Path, value: &T) -> Result<(), String>
where
T: Serialize,
{
+ if let Some(docs) = super::file_store_documents::current().map_err(|e| format!("[composio:store] {e:#}"))? {
+ return docs
+ .save(path, value)
+ .map_err(|error| format!("[composio:store] writing {} failed: {error:#}", path.display()));
+ }
let bytes = serde_json::to_vec_pretty(value)
.map_err(|error| format!("[composio:store] serializing failed: {error}"))?;
if let Some(dir) = path.parent() {
diff --git a/crates/openhuman-core/src/integrations/composio/file_store_documents.rs b/crates/openhuman-core/src/integrations/composio/file_store_documents.rs
new file mode 100644
index 0000000000..95de116621
--- /dev/null
+++ b/crates/openhuman-core/src/integrations/composio/file_store_documents.rs
@@ -0,0 +1,78 @@
+//! The Composio host state files on the `tinystoragedrivers` document port.
+//!
+//! Used instead of `<workspace>/integrations/<file>.json` when the host
+//! configured a storage backend ([`crate::storage`]); `file_store.rs` picks it
+//! per call, so the state lives under the acting agent's storage scope
+//! (`local` on a single-user host). These are the connected-account identities
+//! and the per-toolkit agent scope preferences: user data, so unlike a cache
+//! they must follow the user to a shared backend.
+//!
+//! # Layout
+//!
+//! | Collection | Document id | Holds |
+//! | --- | --- | --- |
+//! | `composio_state` | the file name (`composio_identities.json`, ...) | `value`: the serde value the file held |
+
+use std::path::Path;
+
+use anyhow::{anyhow, Result};
+use serde::de::DeserializeOwned;
+use serde::Serialize;
+use serde_json::json;
+use tinystoragedrivers::{CollectionSpec, Precondition};
+
+use crate::storage::documents::Repo;
+use crate::storage::DocumentStoreExt;
+
+const STATE: &str = "composio_state";
+const DOMAIN: &str = "composio::file_store";
+
+fn collections() -> Vec<CollectionSpec> {
+ vec![CollectionSpec::new(STATE)]
+}
+
+/// The document store for this call, when the host configured one.
+pub(super) fn current() -> Result<Option<Docs>> {
+ Ok(Repo::current(DOMAIN, collections)?.map(Docs))
+}
+
+fn id_of(path: &Path) -> Result<String> {
+ path.file_name()
+ .map(|name| name.to_string_lossy().into_owned())
+ .ok_or_else(|| anyhow!("composio state path {} has no file name", path.display()))
+}
+
+/// The composio state over one scoped document handle.
+pub(super) struct Docs(Repo);
+
+impl Docs {
+ #[cfg(test)]
+ pub(super) fn over(scoped: &crate::storage::ScopedStorage) -> Self {
+ Self(Repo::over(scoped, DOMAIN, collections))
+ }
+
+ /// The value stored for the file `path` names, or `T::default()`.
+ pub(super) fn load<T: DeserializeOwned + Default>(&self, path: &Path) -> Result<T> {
+ let id = id_of(path)?;
+ let stored = self.0.run(|docs| async move { docs.get(STATE, &id).await })?;
+ match stored.and_then(|stored| stored.doc.get("value").cloned()) {
+ Some(value) => Ok(serde_json::from_value(value)?),
+ None => Ok(T::default()),
+ }
+ }
+
+ pub(super) fn save<T: Serialize>(&self, path: &Path, value: &T) -> Result<()> {
+ let id = id_of(path)?;
+ let doc = json!({ "value": serde_json::to_value(value)? });
+ log::debug!("[composio:store] document save id={id}");
+ self.0.run(|docs| async move {
+ docs.put(STATE, &id, doc, Precondition::None)
+ .await
+ .map(|_| ())
+ })
+ }
+}
+
+#[cfg(test)]
+#[path = "file_store_documents_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/integrations/composio/file_store_documents_tests.rs b/crates/openhuman-core/src/integrations/composio/file_store_documents_tests.rs
new file mode 100644
index 0000000000..27d5da1c7e
--- /dev/null
+++ b/crates/openhuman-core/src/integrations/composio/file_store_documents_tests.rs
@@ -0,0 +1,56 @@
+use super::*;
+use crate::storage::{MemoryStorage, Scope, StorageBackend};
+use std::collections::BTreeMap;
+use std::path::PathBuf;
+
+fn docs_in(storage: &MemoryStorage, scope: &str) -> Docs {
+ Docs::over(&storage.for_scope(&Scope::new(scope).unwrap()).unwrap())
+}
+
+fn path() -> PathBuf {
+ PathBuf::from("/ws/integrations/composio_identities.json")
+}
+
+#[test]
+fn a_missing_file_loads_the_default() {
+ let loaded: BTreeMap<String, u32> =
+ docs_in(&MemoryStorage::new(), "local").load(&path()).unwrap();
+ assert!(loaded.is_empty());
+}
+
+#[test]
+fn save_then_load_round_trips_by_file_name() {
+ let docs = docs_in(&MemoryStorage::new(), "local");
+ let mut value = BTreeMap::new();
+ value.insert("gmail".to_string(), 3u32);
+ docs.save(&path(), &value).unwrap();
+ // The workspace part of the path is irrelevant; the file name is the key.
+ let loaded: BTreeMap<String, u32> = docs
+ .load(&PathBuf::from("/elsewhere/composio_identities.json"))
+ .unwrap();
+ assert_eq!(loaded, value);
+ let other: BTreeMap<String, u32> = docs
+ .load(&PathBuf::from("/ws/integrations/composio_user_scopes.json"))
+ .unwrap();
+ assert!(other.is_empty());
+}
+
+#[test]
+fn scopes_do_not_see_each_others_state() {
+ let storage = MemoryStorage::new();
+ let mut value = BTreeMap::new();
+ value.insert("gmail".to_string(), 1u32);
+ docs_in(&storage, "alice").save(&path(), &value).unwrap();
+ let bob: BTreeMap<String, u32> = docs_in(&storage, "bob").load(&path()).unwrap();
+ assert!(bob.is_empty());
+}
+
+#[tokio::test]
+async fn the_file_path_still_works_with_no_backend() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("state.json");
+ let mut value = BTreeMap::new();
+ value.insert("gmail".to_string(), 3u32);
+ super::super::file_store::save(&path, &value).await.unwrap();
+ assert!(path.exists());
+}
diff --git a/crates/openhuman-core/src/integrations/composio/mod.rs b/crates/openhuman-core/src/integrations/composio/mod.rs
index 467688aee0..e42c581743 100644
--- a/crates/openhuman-core/src/integrations/composio/mod.rs
+++ b/crates/openhuman-core/src/integrations/composio/mod.rs
@@ -47,6 +47,7 @@ pub mod contract_gate;
pub(crate) mod direct_auth;
pub mod execute_dispatch;
pub(crate) mod file_store;
+mod file_store_documents;
pub mod googlecalendar_args;
pub mod identity;
pub mod identity_store;