Skip to content

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

chore: files changed crates/openhuman-core/src/modules/host.rs,crates/openhuman-core/src/tinymemes/i

Steven Enamakel78fa655eaefa
diff --git a/crates/openhuman-core/src/modules/host.rs b/crates/openhuman-core/src/modules/host.rs
index 84a33a0d88..80d352c685 100644
--- a/crates/openhuman-core/src/modules/host.rs
+++ b/crates/openhuman-core/src/modules/host.rs
@@ -195,6 +195,16 @@ async fn build_runtime() -> tinybus::Result<ModuleRuntime> {
tracing::debug!("[modules] juice component off; MlHost not served");
}
super::storage_host::install(&connection).await?;
+ #[cfg(feature = "tinymemes")]
+ {
+ let memes_on = crate::core::runtime::context::CoreContext::current()
+ .is_none_or(|ctx| ctx.components().memes);
+ if memes_on {
+ crate::tinymemes::service::install(&connection).await?;
+ } else {
+ tracing::debug!("[modules] memes component off; Host callbacks not served");
+ }
+ }
#[cfg(feature = "web3")]
super::wallet_host::install(&connection).await?;
diff --git a/crates/openhuman-core/src/tinymemes/callbacks.rs b/crates/openhuman-core/src/tinymemes/callbacks.rs
new file mode 100644
index 0000000000..4b0a72f17c
--- /dev/null
+++ b/crates/openhuman-core/src/tinymemes/callbacks.rs
@@ -0,0 +1,194 @@
+//! What the module asks of the host while it works on a remix: one
+//! completion, one Jev evaluation, one web search, and the learned slang and
+//! meme index documents.
+//!
+//! The contract carries no correlation id, so a callback cannot say which
+//! remix it belongs to. Remixes therefore run one at a time per process: the
+//! [`Session`] of the running remix is the one callbacks answer for, and a
+//! callback arriving with no session is refused as unsupported.
+//!
+//! Index documents live at `<workspace>/tinymemes/{slang,meme}-index.json`,
+//! the files the in-process engine used, so learned state carries over.
+
+use std::future::Future;
+use std::path::PathBuf;
+use std::sync::{Arc, Mutex};
+
+use serde::de::DeserializeOwned;
+use serde_json::Value;
+use tinyinference_decisions::{Client, EvaluationRequest};
+use tinymemes_bus::{
+ host_methods, CompleteRequest, EvaluateEnvelope, HostFailure, HostResult, IndexKind,
+ LoadIndexRequest, SaveIndexRequest, SearchRequest,
+};
+
+use super::{inference, jev, remixed, search};
+use crate::config::Config;
+use crate::security::secret_storage::file_store::write_atomic;
+
+const SLANG_FILE: &str = "slang-index.json";
+const MEMES_FILE: &str = "meme-index.json";
+
+/// The workspace one remix runs for.
+pub(super) struct Session {
+ config: Config,
+ jev: tokio::sync::OnceCell<Option<Arc<Client>>>,
+}
+
+impl Session {
+ pub(super) fn new(config: &Config) -> Self {
+ Self {
+ config: config.clone(),
+ jev: tokio::sync::OnceCell::new(),
+ }
+ }
+
+ fn index_path(&self, kind: IndexKind) -> PathBuf {
+ let file = match kind {
+ IndexKind::Slang => SLANG_FILE,
+ IndexKind::Memes => MEMES_FILE,
+ };
+ self.config.workspace_dir.join(remixed::DIR).join(file)
+ }
+}
+
+static ACTIVE: Mutex<Option<Arc<Session>>> = Mutex::new(None);
+static GATE: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
+
+/// Clears the active session when the remix ends, including when the future
+/// is dropped by a timeout.
+struct ActiveGuard;
+
+impl Drop for ActiveGuard {
+ fn drop(&mut self) {
+ *ACTIVE.lock().unwrap_or_else(|e| e.into_inner()) = None;
+ }
+}
+
+/// Run `work` as the one active remix, answering its callbacks for `config`.
+pub(super) async fn run_with<T>(config: &Config, work: impl Future<Output = T>) -> T {
+ let _turn = GATE.lock().await;
+ *ACTIVE.lock().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(Session::new(config)));
+ let _clear = ActiveGuard;
+ work.await
+}
+
+/// The session callbacks currently answer for, if a remix is running.
+pub(super) fn active() -> Option<Arc<Session>> {
+ ACTIVE.lock().unwrap_or_else(|e| e.into_inner()).clone()
+}
+
+fn args<T: DeserializeOwned>(value: Value) -> Result<T, tinybus::Error> {
+ let (request,): (T,) = serde_json::from_value(value)
+ .map_err(|_| tinybus::Error::failed("invalid tinymemes host request"))?;
+ Ok(request)
+}
+
+fn reply<T: serde::Serialize>(result: HostResult<T>) -> Result<Value, tinybus::Error> {
+ serde_json::to_value(result)
+ .map_err(|_| tinybus::Error::failed("invalid tinymemes host response"))
+}
+
+/// Answer one host callback for `session`.
+pub(super) async fn dispatch(
+ session: &Session,
+ member: &str,
+ payload: Value,
+) -> Result<Value, tinybus::Error> {
+ log::debug!("[tinymemes] host callback member={member}");
+ match member {
+ host_methods::COMPLETE => reply(complete(session, args(payload)?).await),
+ host_methods::EVALUATE => reply(evaluate(session, args(payload)?).await),
+ host_methods::SEARCH => reply(search(session, args(payload)?).await),
+ host_methods::LOAD_INDEX => reply(load_index(session, args(payload)?).await),
+ host_methods::SAVE_INDEX => reply(save_index(session, args(payload)?).await),
+ // The remixed text is returned to the caller, which delivers it
+ // itself; nothing is handed over through the module.
+ host_methods::DELIVER => reply(HostResult::Ok(())),
+ _ => Err(tinybus::Error::failed("unknown tinymemes host operation")),
+ }
+}
+
+async fn complete(session: &Session, request: CompleteRequest) -> HostResult<String> {
+ inference::complete(&session.config, &request.system, &request.user)
+ .await
+ .map_err(|error| {
+ log::warn!("[tinymemes] complete callback failed: {error}");
+ HostFailure::Backend
+ })
+}
+
+async fn evaluate(session: &Session, envelope: EvaluateEnvelope) -> HostResult<EvaluateEnvelope> {
+ let Some(client) = session
+ .jev
+ .get_or_init(|| async { jev::managed(&session.config) })
+ .await
+ else {
+ log::debug!("[tinymemes] evaluate callback: managed jev unavailable");
+ return Err(HostFailure::Unsupported);
+ };
+ let request: EvaluationRequest =
+ serde_json::from_value(envelope.body).map_err(|_| HostFailure::Unsupported)?;
+ let result = client.evaluate(&request).await.map_err(|error| {
+ log::warn!("[tinymemes] evaluate callback failed: {error}");
+ HostFailure::Backend
+ })?;
+ let body = serde_json::to_value(result.response).map_err(|_| HostFailure::Backend)?;
+ Ok(EvaluateEnvelope { body })
+}
+
+async fn search(
+ session: &Session,
+ request: SearchRequest,
+) -> HostResult<Vec<tinymemes_bus::SearchResult>> {
+ let Some(backend) = search::OpenHumanSearch::available(&session.config) else {
+ return Err(HostFailure::Unsupported);
+ };
+ backend
+ .search(&request.query, request.max_results as usize)
+ .await
+ .map_err(|error| {
+ // The query is derived from the chat, so only the error is logged.
+ log::warn!("[tinymemes] search callback failed: {error}");
+ HostFailure::Backend
+ })
+}
+
+async fn load_index(session: &Session, request: LoadIndexRequest) -> HostResult<Option<String>> {
+ let path = session.index_path(request.kind);
+ match crate::core::runtime::spawn_blocking_scoped(move || std::fs::read_to_string(path)).await
+ {
+ Ok(Ok(json)) => Ok(Some(json)),
+ Ok(Err(error)) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
+ Ok(Err(error)) => {
+ log::warn!("[tinymemes] cannot read index: {error}");
+ Err(HostFailure::Backend)
+ }
+ Err(error) => {
+ log::warn!("[tinymemes] index read task failed: {error}");
+ Err(HostFailure::Backend)
+ }
+ }
+}
+
+async fn save_index(session: &Session, request: SaveIndexRequest) -> HostResult<()> {
+ let path = session.index_path(request.kind);
+ let json = request.json;
+ match crate::core::runtime::spawn_blocking_scoped(move || write_atomic(&path, json.as_bytes()))
+ .await
+ {
+ Ok(Ok(())) => Ok(()),
+ Ok(Err(error)) => {
+ log::warn!("[tinymemes] cannot save index: {error}");
+ Err(HostFailure::Backend)
+ }
+ Err(error) => {
+ log::warn!("[tinymemes] index write task failed: {error}");
+ Err(HostFailure::Backend)
+ }
+ }
+}
+
+#[cfg(test)]
+#[path = "callbacks_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/tinymemes/callbacks_tests.rs b/crates/openhuman-core/src/tinymemes/callbacks_tests.rs
new file mode 100644
index 0000000000..71a7f44d13
--- /dev/null
+++ b/crates/openhuman-core/src/tinymemes/callbacks_tests.rs
@@ -0,0 +1,107 @@
+use super::*;
+use serde_json::json;
+
+fn config_in(dir: &std::path::Path) -> Config {
+ let mut config = Config::default();
+ config.config_path = dir.join("config.toml");
+ config.workspace_dir = dir.join("workspace");
+ config.secrets.encrypt = false;
+ config
+}
+
+fn decode<T: DeserializeOwned>(value: Value) -> HostResult<T> {
+ serde_json::from_value(value).unwrap()
+}
+
+#[tokio::test]
+async fn an_index_saved_through_the_host_loads_back() {
+ let dir = tempfile::tempdir().unwrap();
+ let session = Session::new(&config_in(dir.path()));
+
+ let missing = dispatch(&session, host_methods::LOAD_INDEX, json!([{ "kind": "slang" }]))
+ .await
+ .unwrap();
+ assert_eq!(decode::<Option<String>>(missing), Ok(None));
+
+ let saved = dispatch(
+ &session,
+ host_methods::SAVE_INDEX,
+ json!([{ "kind": "slang", "json": "{\"terms\":1}" }]),
+ )
+ .await
+ .unwrap();
+ assert_eq!(decode::<()>(saved), Ok(()));
+
+ let loaded = dispatch(&session, host_methods::LOAD_INDEX, json!([{ "kind": "slang" }]))
+ .await
+ .unwrap();
+ assert_eq!(decode::<Option<String>>(loaded), Ok(Some("{\"terms\":1}".into())));
+ // The other index is a different document.
+ let memes = dispatch(&session, host_methods::LOAD_INDEX, json!([{ "kind": "memes" }]))
+ .await
+ .unwrap();
+ assert_eq!(decode::<Option<String>>(memes), Ok(None));
+ assert!(dir
+ .path()
+ .join("workspace/tinymemes/slang-index.json")
+ .is_file());
+}
+
+#[tokio::test]
+async fn without_managed_jev_evaluate_is_unsupported() {
+ let dir = tempfile::tempdir().unwrap();
+ let session = Session::new(&config_in(dir.path()));
+ let request = json!([{ "body": { "questions": {}, "messages": [] } }]);
+ let result = dispatch(&session, host_methods::EVALUATE, request).await.unwrap();
+ assert_eq!(
+ decode::<EvaluateEnvelope>(result),
+ Err(HostFailure::Unsupported)
+ );
+}
+
+#[tokio::test]
+async fn search_switched_off_is_unsupported() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = config_in(dir.path());
+ config.search.enabled = Some(false);
+ let session = Session::new(&config);
+ let result = dispatch(
+ &session,
+ host_methods::SEARCH,
+ json!([{ "query": "q", "max_results": 3 }]),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ decode::<Vec<tinymemes_bus::SearchResult>>(result),
+ Err(HostFailure::Unsupported)
+ );
+}
+
+#[tokio::test]
+async fn deliver_is_acknowledged_and_unknown_members_are_refused() {
+ let dir = tempfile::tempdir().unwrap();
+ let session = Session::new(&config_in(dir.path()));
+ let delivered = dispatch(
+ &session,
+ host_methods::DELIVER,
+ json!([{ "reply": "hi", "remixed": true }]),
+ )
+ .await
+ .unwrap();
+ assert_eq!(decode::<()>(delivered), Ok(()));
+ assert!(dispatch(&session, "Nope", json!([])).await.is_err());
+ assert!(dispatch(&session, host_methods::COMPLETE, json!("bad"))
+ .await
+ .is_err());
+}
+
+#[tokio::test]
+async fn callbacks_answer_only_while_a_remix_runs() {
+ let dir = tempfile::tempdir().unwrap();
+ let config = config_in(dir.path());
+ assert!(active().is_none());
+ let seen = run_with(&config, async { active().is_some() }).await;
+ assert!(seen);
+ assert!(active().is_none(), "the session is cleared when the remix ends");
+}
diff --git a/crates/openhuman-core/src/tinymemes/history_tests.rs b/crates/openhuman-core/src/tinymemes/history_tests.rs
new file mode 100644
index 0000000000..ab3022b63a
--- /dev/null
+++ b/crates/openhuman-core/src/tinymemes/history_tests.rs
@@ -0,0 +1,53 @@
+use super::*;
+
+fn msg(id: &str, sender: &str, content: &str) -> ConversationMessage {
+ ConversationMessage {
+ id: id.to_owned(),
+ content: content.to_owned(),
+ message_type: "text".to_owned(),
+ extra_metadata: serde_json::Value::Null,
+ sender: sender.to_owned(),
+ created_at: "2026-10-09T00:00:00Z".to_owned(),
+ }
+}
+
+#[test]
+fn only_real_answers_are_remixed() {
+ assert!(should_remix("a real answer", "budget exhausted"));
+ assert!(!should_remix("budget exhausted", "budget exhausted"));
+ assert!(!should_remix(" \n", "budget exhausted"));
+}
+
+#[test]
+fn history_marks_remixed_replies_and_appends_the_pending_message() {
+ let messages = vec![
+ msg("u1", "user", "bhai build fail"),
+ msg("r1", "agent", "Arre yaar, moye moye"),
+ msg("r2", "agent", "Plain reply"),
+ msg("s1", "system", "ignored"),
+ msg("u2", "user", " "),
+ ];
+ let turns = history_turns(&messages, "phir se fail", |id| id == "r1");
+ assert_eq!(turns.len(), 4);
+ assert_eq!(turns[0].role, WireRole::User);
+ assert_eq!(turns[1].role, WireRole::Assistant);
+ assert!(turns[1].remixed);
+ assert!(!turns[2].remixed);
+ assert_eq!(turns[3].text, "phir se fail");
+}
+
+#[test]
+fn pending_message_is_not_duplicated_when_already_stored() {
+ let messages = vec![msg("u1", "user", "hello there")];
+ let turns = history_turns(&messages, "hello there ", |_| false);
+ assert_eq!(turns.len(), 1);
+}
+
+#[test]
+fn a_new_message_repeating_an_earlier_one_is_still_appended() {
+ // user("hello"), agent("reply"), then a new "hello": a distinct message.
+ let messages = vec![msg("u1", "user", "hello"), msg("r1", "agent", "reply")];
+ let turns = history_turns(&messages, "hello", |_| false);
+ assert_eq!(turns.len(), 3);
+ assert_eq!(turns[2].text, "hello");
+}
diff --git a/crates/openhuman-core/src/tinymemes/inference_tests.rs b/crates/openhuman-core/src/tinymemes/inference_tests.rs
index ba2e2af360..147fd67271 100644
--- a/crates/openhuman-core/src/tinymemes/inference_tests.rs
+++ b/crates/openhuman-core/src/tinymemes/inference_tests.rs
@@ -25,5 +25,4 @@ fn the_model_label_never_fails() {
config.secrets.encrypt = false;
// Either the resolved model id or an `unavailable (...)` label.
assert!(!resolved_model(&config).trim().is_empty());
- let _model = OpenHumanChatModel::new(config);
}
diff --git a/crates/openhuman-core/src/tinymemes/mod_tests.rs b/crates/openhuman-core/src/tinymemes/mod_tests.rs
new file mode 100644
index 0000000000..c1564b4ac3
--- /dev/null
+++ b/crates/openhuman-core/src/tinymemes/mod_tests.rs
@@ -0,0 +1,217 @@
+use super::*;
+
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Arc;
+
+use crate::threads::store::ConversationMessage;
+
+/// Answers every remix with a fixed response, after an optional delay.
+struct ScriptedRemixer {
+ response: Result<RemixResponse, String>,
+ delay: Duration,
+ calls: AtomicUsize,
+ last: std::sync::Mutex<Option<RemixRequest>>,
+}
+
+impl ScriptedRemixer {
+ fn new(response: Result<RemixResponse, String>) -> Self {
+ Self {
+ response,
+ delay: Duration::ZERO,
+ calls: AtomicUsize::new(0),
+ last: std::sync::Mutex::new(None),
+ }
+ }
+}
+
+#[async_trait]
+impl Remixer for ScriptedRemixer {
+ async fn remix(&self, request: RemixRequest) -> Result<RemixResponse, String> {
+ self.calls.fetch_add(1, Ordering::SeqCst);
+ *self.last.lock().unwrap() = Some(request);
+ tokio::time::sleep(self.delay).await;
+ self.response.clone()
+ }
+}
+
+fn remixed_response(reply: &str) -> RemixResponse {
+ RemixResponse {
+ reply: reply.to_owned(),
+ remixed: true,
+ skipped: None,
+ score: Some(7),
+ wants_more_memes: false,
+ }
+}
+
+fn skipped_response(reply: &str, reason: SkipReason) -> RemixResponse {
+ RemixResponse {
+ reply: reply.to_owned(),
+ remixed: false,
+ skipped: Some(reason),
+ score: None,
+ wants_more_memes: false,
+ }
+}
+
+fn turn(request_id: &str) -> TurnInfo<'_> {
+ TurnInfo {
+ request_id,
+ bucket: 7,
+ turn_ms: 1234,
+ }
+}
+
+fn msg(id: &str, sender: &str, content: &str) -> ConversationMessage {
+ ConversationMessage {
+ id: id.to_owned(),
+ content: content.to_owned(),
+ message_type: "text".to_owned(),
+ extra_metadata: serde_json::Value::Null,
+ sender: sender.to_owned(),
+ created_at: "2026-10-09T00:00:00Z".to_owned(),
+ }
+}
+
+fn thread() -> Vec<ConversationMessage> {
+ vec![
+ msg("u1", "user", "bhai build fail ho gaya"),
+ msg("r1", "agent", "Arre yaar, moye moye"),
+ ]
+}
+
+fn store(dir: &std::path::Path) -> Arc<remixed::RemixedIds> {
+ remixed::for_workspace(dir).unwrap()
+}
+
+async fn run(
+ remixer: &ScriptedRemixer,
+ ids: &Arc<remixed::RemixedIds>,
+ request_id: &str,
+ budget: Duration,
+) -> Option<String> {
+ remix_with(
+ remixer,
+ ids,
+ &thread(),
+ &turn(request_id),
+ Instant::now(),
+ "phir se fail",
+ "Build failed again.",
+ budget,
+ )
+ .await
+}
+
+#[test]
+fn the_budget_defaults_to_twenty_seconds() {
+ if std::env::var(TIMEOUT_ENV).is_err() {
+ assert_eq!(budget(), DEFAULT_TIMEOUT);
+ }
+}
+
+#[test]
+fn only_the_treatment_arm_passes_the_gate() {
+ let t = turn("req");
+ assert!(!gate(Arm::Disabled, &t));
+ assert!(!gate(Arm::Control, &t));
+ assert!(gate(Arm::Treatment, &t));
+}
+
+#[tokio::test]
+async fn a_remixed_reply_is_delivered_and_remembered() {
+ let dir = tempfile::tempdir().unwrap();
+ let ids = store(dir.path());
+ let remixer = ScriptedRemixer::new(Ok(remixed_response("Arre yaar, build phir fail!")));
+ let out = run(&remixer, &ids, "req-ok", Duration::from_secs(5)).await;
+ assert_eq!(out.as_deref(), Some("Arre yaar, build phir fail!"));
+ assert!(ids.contains(&crate::threads::store::run_reply_message_id("req-ok")));
+
+ // The module saw the thread with the earlier remixed reply flagged.
+ let request = remixer.last.lock().unwrap().clone().unwrap();
+ assert!(request.enabled && !request.deliver);
+ assert_eq!(request.reply, "Build failed again.");
+ assert_eq!(request.timeout_ms, 5000);
+ assert_eq!(request.conversation.last().unwrap().text, "phir se fail");
+}
+
+#[tokio::test]
+async fn an_unchanged_reply_sends_the_original() {
+ let dir = tempfile::tempdir().unwrap();
+ let ids = store(dir.path());
+ for reason in [SkipReason::BelowThreshold, SkipReason::Failed, SkipReason::Timeout] {
+ let remixer = ScriptedRemixer::new(Ok(skipped_response("Build failed again.", reason)));
+ assert_eq!(run(&remixer, &ids, "req-skip", Duration::from_secs(5)).await, None);
+ }
+ assert!(!ids.contains(&crate::threads::store::run_reply_message_id("req-skip")));
+}
+
+#[tokio::test]
+async fn a_remix_that_returns_the_same_text_is_not_a_change() {
+ let dir = tempfile::tempdir().unwrap();
+ let ids = store(dir.path());
+ let remixer = ScriptedRemixer::new(Ok(remixed_response("Build failed again. ")));
+ assert_eq!(run(&remixer, &ids, "req-same", Duration::from_secs(5)).await, None);
+ assert!(!ids.contains(&crate::threads::store::run_reply_message_id("req-same")));
+}
+
+#[tokio::test]
+async fn a_module_error_sends_the_original() {
+ let dir = tempfile::tempdir().unwrap();
+ let ids = store(dir.path());
+ let remixer = ScriptedRemixer::new(Err("module unavailable".into()));
+ assert_eq!(run(&remixer, &ids, "req-err", Duration::from_secs(5)).await, None);
+}
+
+#[tokio::test]
+async fn a_slow_remix_times_out_to_the_original() {
+ let dir = tempfile::tempdir().unwrap();
+ let ids = store(dir.path());
+ let mut remixer = ScriptedRemixer::new(Ok(remixed_response("too late")));
+ remixer.delay = Duration::from_secs(30);
+ let out = run(&remixer, &ids, "req-slow", Duration::from_millis(50)).await;
+ assert_eq!(out, None);
+}
+
+#[tokio::test]
+async fn a_disabled_flag_leaves_the_task_reply_alone() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = Config::default();
+ config.config_path = dir.path().join("config.toml");
+ config.workspace_dir = dir.path().join("workspace");
+ let mut reply = String::from("Build failed again.");
+ // Disabled arm: no module is touched and nothing changes.
+ let out = remix_final_reply(
+ Arm::Disabled,
+ &config,
+ "thread",
+ "req",
+ "msg",
+ &reply,
+ Duration::from_millis(5),
+ )
+ .await;
+ assert_eq!(out, None);
+ remix_task_reply(&config, "thread", "req", "msg", &mut reply, "placeholder", Duration::ZERO)
+ .await;
+ assert_eq!(reply, "Build failed again.");
+}
+
+#[test]
+fn the_turn_line_reports_the_outcome_without_user_content() {
+ let t = turn("req-1");
+ let none = turn_line(&t, 5, "error", None);
+ assert!(none.contains("outcome=error") && none.contains("score=-1"));
+ let some = turn_line(&t, 9, "remixed", Some(&remixed_response("secret text")));
+ assert!(some.contains("score=7") && some.contains("request_id=req-1"));
+ assert!(!some.contains("secret text"));
+ let skipped = turn_line(&t, 9, "unchanged", Some(&skipped_response("x", SkipReason::BelowThreshold)));
+ assert!(skipped.contains("skipped=below_threshold"));
+}
+
+#[test]
+fn flag_values_enable_remixing() {
+ assert!(flag_enabled("on"));
+ assert!(flag_enabled("ab:30"));
+ assert!(!flag_enabled("off"));
+}
diff --git a/crates/openhuman-core/src/tinymemes/remixed_tests.rs b/crates/openhuman-core/src/tinymemes/remixed_tests.rs
new file mode 100644
index 0000000000..25ca361f35
--- /dev/null
+++ b/crates/openhuman-core/src/tinymemes/remixed_tests.rs
@@ -0,0 +1,45 @@
+use super::*;
+
+#[test]
+fn marks_survive_a_reopen_and_are_written_atomically() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let path = dir.path().join(FILE);
+ let store = RemixedIds::open(path.clone());
+ assert!(!store.contains("r1"));
+ store.mark("r1".into());
+ store.mark("r1".into());
+ store.mark("r2".into());
+ assert!(store.contains("r1"));
+
+ let reopened = RemixedIds::open(path);
+ assert!(reopened.contains("r1") && reopened.contains("r2"));
+ let entries: Vec<_> = std::fs::read_dir(dir.path()).unwrap().collect();
+ assert_eq!(entries.len(), 1, "temp files left behind");
+}
+
+#[test]
+fn an_oversized_file_is_capped_on_load_keeping_the_newest() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let path = dir.path().join(FILE);
+ let ids: Vec<String> = (0..CAP + 50).map(|i| format!("id-{i}")).collect();
+ std::fs::write(&path, serde_json::to_string(&ids).unwrap()).unwrap();
+ let store = RemixedIds::open(path);
+ assert!(!store.contains("id-0"));
+ assert!(store.contains(&format!("id-{}", CAP + 49)));
+}
+
+#[test]
+fn a_corrupt_file_starts_empty() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let path = dir.path().join(FILE);
+ std::fs::write(&path, "not json").unwrap();
+ assert!(!RemixedIds::open(path).contains("x"));
+}
+
+#[test]
+fn one_store_serves_a_workspace() {
+ let dir = tempfile::TempDir::new().unwrap();
+ let a = for_workspace(dir.path()).unwrap();
+ let b = for_workspace(dir.path()).unwrap();
+ assert!(Arc::ptr_eq(&a, &b));
+}
diff --git a/crates/openhuman-core/src/tinymemes/service.rs b/crates/openhuman-core/src/tinymemes/service.rs
new file mode 100644
index 0000000000..2e517e7efc
--- /dev/null
+++ b/crates/openhuman-core/src/tinymemes/service.rs
@@ -0,0 +1,104 @@
+//! The bus half of the `tinymemes` module: the host callbacks it is served
+//! (`Host` interface) and the client call that starts a remix.
+
+use async_trait::async_trait;
+use tinybus::{CallContext, Connection, InterfaceName, MemberName, ObjectPath};
+use tinymemes_bus::{
+ RemixClient, RemixRefusal, RemixRequest, RemixResponse, HOST_INTERFACE, HOST_METHODS,
+ HOST_PATH,
+};
+
+use super::callbacks;
+use crate::config::Config;
+
+/// Registry id of the module the callbacks serve.
+pub(crate) const MODULE_ID: &str = "tinymemes";
+
+struct HostService {
+ connection: Connection,
+}
+
+#[async_trait]
+impl tinybus::Interface for HostService {
+ fn name(&self) -> InterfaceName {
+ InterfaceName::new(HOST_INTERFACE).expect("contract interface name is well formed")
+ }
+
+ fn members(&self) -> Vec<MemberName> {
+ HOST_METHODS
+ .iter()
+ .filter_map(|member| MemberName::new(*member).ok())
+ .collect()
+ }
+
+ async fn call(
+ &self,
+ _member: &MemberName,
+ _args: serde_json::Value,
+ ) -> tinybus::Result<serde_json::Value> {
+ // Without the broker's context there is no caller to authorize.
+ Err(tinybus::Error::failed("unauthenticated tinymemes caller"))
+ }
+
+ async fn call_with_context(
+ &self,
+ member: &MemberName,
+ args: serde_json::Value,
+ context: &CallContext,
+ ) -> tinybus::Result<serde_json::Value> {
+ // Only the loaded `tinymemes` module may ask: its bus name's owner
+ // must be the authenticated sender.
+ let Some(sender) = context.authenticated_sender() else {
+ return Err(tinybus::Error::failed("unauthenticated tinymemes caller"));
+ };
+ let owner = self
+ .connection
+ .name_owner(tinymemes_bus::STATE_INTERFACE)
+ .await
+ .ok()
+ .flatten();
+ if owner.as_ref() != Some(sender) {
+ log::warn!("[tinymemes] refused a host callback from a peer that is not the module");
+ return Err(tinybus::Error::failed("unknown tinymemes caller"));
+ }
+ let Some(session) = callbacks::active() else {
+ log::debug!("[tinymemes] host callback with no remix running");
+ return Err(tinybus::Error::failed("no tinymemes remix is running"));
+ };
+ callbacks::dispatch(&session, member.as_str(), args).await
+ }
+}
+
+/// Serve the module's host callbacks on the module bus.
+pub(crate) async fn install(connection: &Connection) -> tinybus::Result<()> {
+ connection
+ .serve_at(
+ ObjectPath::new(HOST_PATH)?,
+ HostService {
+ connection: connection.clone(),
+ },
+ )
+ .await
+}
+
+/// Remix one reply through the loaded module, serving its callbacks for
+/// `config`'s workspace meanwhile.
+pub(crate) async fn remix(
+ config: &Config,
+ request: RemixRequest,
+) -> Result<RemixResponse, String> {
+ crate::modules::ensure_loaded(config, MODULE_ID).await?;
+ let runtime = crate::modules::host::runtime()
+ .await
+ .map_err(|error| format!("the module bus is not running: {error}"))?;
+ let client = RemixClient::new(runtime.connection()).map_err(|error| error.to_string())?;
+ let outcome = callbacks::run_with(config, client.remix(request)).await;
+ match outcome {
+ Ok(Ok(response)) => Ok(response),
+ Ok(Err(refusal)) => Err(match refusal {
+ RemixRefusal::Closing => "the tinymemes module is closing".to_owned(),
+ RemixRefusal::Unauthenticated => "the tinymemes module refused the caller".to_owned(),
+ }),
+ Err(error) => Err(format!("tinymemes remix call failed: {error}")),
+ }
+}