Skip to content

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

feat(tinymemes): OpenHuman inference + managed Jev, hold the stream, vendor submodule

killbillf0e2655ef3ee
diff --git a/.gitmodules b/.gitmodules
index 7054caa020..b7a1f19c60 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -60,3 +60,6 @@
[submodule "vendor/tinysearch"]
path = vendor/tinysearch
url = https://github.com/tinyhumansai/tinysearch.git
+[submodule "vendor/tinymemes"]
+ path = vendor/tinymemes
+ url = https://github.com/tinyhumansai/tinymemes.git
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index 3530800537..5adc6481de 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -354,8 +354,8 @@ once_cell = "1.19"
parking_lot = "0.12"
log = "0.4"
# Final-reply slang + meme remix (runtime flag OPENHUMAN_TINYMEMES, off by
-# default). Local path until the tinymemes repo is published and vendored.
-tinymemes = { path = "../../../tinymemes" }
+# default). Vendored submodule: vendor/tinymemes.
+tinymemes = { path = "../../vendor/tinymemes" }
libc = "0.2"
nu-ansi-term = "0.50"
base64 = "0.22"
diff --git a/crates/openhuman-core/src/tinymemes/host.rs b/crates/openhuman-core/src/tinymemes/host.rs
index 12991c4eee..d8abaab1d6 100644
--- a/crates/openhuman-core/src/tinymemes/host.rs
+++ b/crates/openhuman-core/src/tinymemes/host.rs
@@ -6,10 +6,15 @@
//! next reading can tell Jev which assistant turns carry the bot's own style.
use std::collections::{HashMap, VecDeque};
-use std::path::{Path, PathBuf};
+use std::path::PathBuf;
use std::sync::{Arc, LazyLock, Mutex};
-use tinymemes::{IndexPolicy, MemeEngine, SlangIndex, Turn};
+use tinymemes::{
+ ChatModel, EnvConfig, Evaluator, IndexPolicy, MemeEngine, RatingPolicy, SearchResearcher,
+ SlangIndex, SlangResearcher, Turn,
+};
+
+use crate::config::Config;
use crate::threads::store::ConversationMessage;
@@ -19,9 +24,8 @@ const REMIXED_FILE: &str = "remixed.json";
/// Remixed-message ids remembered per workspace (oldest dropped first).
const REMIXED_CAP: usize = 4000;
-pub(crate) const MODEL_ENV: &str = "OPENHUMAN_TINYMEMES_MODEL";
-pub(crate) const KEY_ENV: &str = "OPENHUMAN_TINYMEMES_OPENROUTER_KEY";
-const DEFAULT_MODEL: &str = "deepseek/deepseek-v4-flash";
+/// Replies to wait after a meme before sending another (0 = no cooldown).
+pub(crate) const MEME_COOLDOWN_ENV: &str = "OPENHUMAN_TINYMEMES_MEME_COOLDOWN";
pub(crate) struct Host {
pub(crate) engine: MemeEngine,
@@ -33,8 +37,17 @@ static HOSTS: LazyLock<Mutex<HashMap<PathBuf, Arc<Host>>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
/// The engine for a workspace, built on first use. `None` if it cannot be
-/// built (logged once per attempt; the turn then goes out unchanged).
-pub(crate) fn host_for(workspace_dir: &Path) -> Option<Arc<Host>> {
+/// built (the turn then goes out unchanged).
+///
+/// Backends, each overridable by `TINYMEMES_*` env (see `tinymemes::env`):
+///
+/// | piece | default (OpenHuman) | env override |
+/// | --- | --- | --- |
+/// | chat model | OpenHuman's `summarization` provider | `TINYMEMES_OPENROUTER_KEY` (+ `TINYMEMES_MODEL`) |
+/// | Jev | OpenHuman-managed; the LLM fallback when unavailable | `TINYMEMES_JEV` (+ its key variables) |
+/// | slang research | OpenHuman web search + the chat model | `TINYMEMES_OPENROUTER_KEY` (OpenRouter web plugin) |
+pub(crate) fn host_for(config: &Config) -> Option<Arc<Host>> {
+ let workspace_dir = config.workspace_dir.as_path();
let mut hosts = HOSTS.lock().unwrap_or_else(|e| e.into_inner());
if let Some(host) = hosts.get(workspace_dir) {
return Some(host.clone());
@@ -56,25 +69,71 @@ pub(crate) fn host_for(workspace_dir: &Path) -> Option<Arc<Host>> {
.and_then(|json| serde_json::from_str(&json).ok())
.unwrap_or_default();
- let key = std::env::var(KEY_ENV)
- .ok()
- .filter(|k| !k.trim().is_empty())
- .unwrap_or_else(|| super::key::OPENROUTER_KEY.to_owned());
- let model = std::env::var(MODEL_ENV).unwrap_or_else(|_| DEFAULT_MODEL.to_owned());
- let engine = match MemeEngine::openrouter(&key, &model) {
- Ok(builder) => builder
- .slang_index(Arc::new(index))
- // Research runs in the background after delivery, never on the
- // reply's critical path.
- .learn_inline(None)
- .build(),
- Err(e) => {
- log::warn!("[tinymemes] engine build failed: {e}");
- return None;
+ let env = EnvConfig::from_env();
+ let http = reqwest::Client::new();
+
+ let (chat, chat_label): (Arc<dyn ChatModel>, String) = match env.chat_model(&http) {
+ Some(model) => (model, format!("env:openrouter/{}", env.model_id())),
+ None => (
+ Arc::new(super::inference::OpenHumanChatModel::new(config.clone())),
+ format!("openhuman:{}", super::inference::resolved_model(config)),
+ ),
+ };
+
+ // Jev: OpenHuman-managed always, unless TINYMEMES_JEV overrides it. With
+ // no managed Jev (signed out / offline session), OpenHuman's LLM answers
+ // Jev's questions instead.
+ let (jev, jev_label): (Arc<dyn Evaluator>, &str) = if env.forces_llm_jev() {
+ (
+ tinymemes::env::llm_jev(chat.clone()),
+ "llm (TINYMEMES_JEV=llm)",
+ )
+ } else {
+ let overridden = match env.jev {
+ Some(_) => env.jev().unwrap_or_else(|e| {
+ log::warn!("[tinymemes] TINYMEMES_JEV override unusable, using managed: {e}");
+ None
+ }),
+ None => None,
+ };
+ match overridden {
+ Some((jev, label)) => (jev, label),
+ None => match super::jev::managed(config) {
+ Some(jev) => (jev, "openhuman-managed"),
+ None => (
+ tinymemes::env::llm_jev(chat.clone()),
+ "llm (managed jev unavailable)",
+ ),
+ },
}
};
+
+ let (researcher, research_label): (Option<Arc<dyn SlangResearcher>>, &str) =
+ match env.web_researcher(&http) {
+ Some(r) => (Some(Arc::new(r)), "env:openrouter-web"),
+ None => match openhuman_search(config) {
+ Some(search) => (
+ Some(Arc::new(SearchResearcher::new(search, chat.clone()))),
+ "openhuman-search",
+ ),
+ None => (None, "off (no search provider)"),
+ },
+ };
+
+ let mut builder = MemeEngine::builder(jev, chat)
+ .source(Arc::new(tinymemes::source::Imgflip::new(http)))
+ .slang_index(Arc::new(index))
+ .policy(rating_policy())
+ // Research runs in the background after delivery, never on the
+ // reply's critical path.
+ .learn_inline(None);
+ if let Some(researcher) = researcher {
+ builder = builder.researcher(researcher);
+ }
+ let engine = builder.build();
log::info!(
- "[tinymemes] engine ready model={model} slang_terms={}",
+ "[tinymemes] engine ready chat={chat_label} jev={jev_label} research={research_label} \
+ slang_terms={}",
engine.slang_index().len("IN")
);
let host = Arc::new(Host {
@@ -86,6 +145,28 @@ pub(crate) fn host_for(workspace_dir: &Path) -> Option<Arc<Host>> {
Some(host)
}
+#[cfg(feature = "modules")]
+fn openhuman_search(config: &Config) -> Option<Arc<dyn tinymemes::WebSearch>> {
+ super::search::OpenHumanSearch::available(config)
+ .map(|s| Arc::new(s) as Arc<dyn tinymemes::WebSearch>)
+}
+
+#[cfg(not(feature = "modules"))]
+fn openhuman_search(_config: &Config) -> Option<Arc<dyn tinymemes::WebSearch>> {
+ None
+}
+
+fn rating_policy() -> RatingPolicy {
+ let mut policy = RatingPolicy::default();
+ if let Some(turns) = std::env::var(MEME_COOLDOWN_ENV)
+ .ok()
+ .and_then(|v| v.trim().parse::<usize>().ok())
+ {
+ policy.meme_cooldown_turns = turns;
+ }
+ policy
+}
+
impl Host {
pub(crate) fn is_remixed(&self, message_id: &str) -> bool {
self.remixed
diff --git a/crates/openhuman-core/src/tinymemes/inference.rs b/crates/openhuman-core/src/tinymemes/inference.rs
new file mode 100644
index 0000000000..01b8f25201
--- /dev/null
+++ b/crates/openhuman-core/src/tinymemes/inference.rs
@@ -0,0 +1,86 @@
+//! OpenHuman's own inference as tinymemes' chat model.
+//!
+//! Every call goes through the provider OpenHuman is configured with for the
+//! `summarization` role (managed backend, BYOK cloud, or local), the same
+//! path thread titles and follow-up suggestions use. Reasoning is switched off
+//! for these calls only; a rewrite needs none, and reasoning models otherwise
+//! spend ~10 s per call. The rest of OpenHuman keeps its configured reasoning.
+
+use async_trait::async_trait;
+use tinyinference_llm::message::Message;
+use tinyinference_llm::model::ModelRequest;
+
+use crate::config::Config;
+use crate::inference::provider;
+
+/// Workload role whose provider tinymemes borrows.
+pub(crate) const ROLE: &str = "summarization";
+const TEMPERATURE: f64 = 0.7;
+
+pub(crate) struct OpenHumanChatModel {
+ config: Config,
+}
+
+impl OpenHumanChatModel {
+ pub(crate) fn new(config: Config) -> Self {
+ Self { config }
+ }
+}
+
+#[async_trait]
+impl tinymemes::ChatModel for OpenHumanChatModel {
+ async fn complete(&self, system: &str, user: &str) -> Result<String, tinymemes::BoxError> {
+ // Built per call so a provider change in Settings applies without a
+ // restart; construction is cheap and synchronous.
+ let (model, resolved) =
+ provider::create_chat_model_with_model_id(ROLE, &self.config, TEMPERATURE)
+ .map_err(|e| format!("openhuman inference unavailable: {e}"))?;
+ // Reasoning off for tinymemes' calls only (the rest of OpenHuman keeps
+ // its configured reasoning). The managed backend honours the
+ // `without_reasoning` flag; a BYOK route to OpenRouter needs
+ // OpenRouter's own switch. Other endpoints are left untouched, since an
+ // unknown field can be rejected.
+ let mut request = provider::openhuman_backend_model::without_reasoning(
+ ModelRequest::new(vec![Message::system(system), Message::user(user)])
+ .with_temperature(TEMPERATURE),
+ );
+ if routes_to_openrouter(&self.config) {
+ request.provider_options = serde_json::json!({ "reasoning": { "enabled": false } });
+ }
+ let response = model
+ .invoke(&(), request)
+ .await
+ .map_err(|e| format!("openhuman inference failed model={resolved}: {e}"))?;
+ let text = response.text();
+ if text.trim().is_empty() {
+ return Err(format!("openhuman inference returned no text model={resolved}").into());
+ }
+ Ok(text)
+ }
+}
+
+/// Whether tinymemes' role resolves to an OpenRouter endpoint: a BYOK
+/// `openrouter:` route, or a custom inference URL on openrouter.ai.
+pub(crate) fn routes_to_openrouter(config: &Config) -> bool {
+ let route_is_openrouter = config
+ .memory_provider
+ .as_deref()
+ .map(str::trim)
+ .is_some_and(|p| p.starts_with("openrouter:") || p == "openrouter");
+ let url_is_openrouter = config
+ .inference_url
+ .as_deref()
+ .is_some_and(|u| u.contains("openrouter.ai"));
+ route_is_openrouter || url_is_openrouter
+}
+
+/// The model id OpenHuman would use for tinymemes, for the startup log line.
+pub(crate) fn resolved_model(config: &Config) -> String {
+ provider::create_chat_model_with_model_id(ROLE, config, TEMPERATURE)
+ .map(|(_, id)| id)
+ .unwrap_or_else(|e| format!("unavailable ({e})"))
+}
+
+#[cfg(test)]
+#[path = "inference_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/tinymemes/inference_tests.rs b/crates/openhuman-core/src/tinymemes/inference_tests.rs
new file mode 100644
index 0000000000..683e1e7b1f
--- /dev/null
+++ b/crates/openhuman-core/src/tinymemes/inference_tests.rs
@@ -0,0 +1,15 @@
+use super::*;
+
+#[test]
+fn openrouter_routes_are_detected() {
+ let mut config = Config::default();
+ assert!(!routes_to_openrouter(&config));
+ config.inference_url = Some("https://openrouter.ai/api/v1".into());
+ assert!(routes_to_openrouter(&config));
+ config.inference_url = Some("https://api.openai.com/v1".into());
+ assert!(!routes_to_openrouter(&config));
+ config.memory_provider = Some("openrouter:deepseek/deepseek-v4-flash".into());
+ assert!(routes_to_openrouter(&config));
+ config.memory_provider = Some("ollama:llama3.1:8b".into());
+ assert!(!routes_to_openrouter(&config));
+}
diff --git a/crates/openhuman-core/src/tinymemes/jev.rs b/crates/openhuman-core/src/tinymemes/jev.rs
new file mode 100644
index 0000000000..476cf5650d
--- /dev/null
+++ b/crates/openhuman-core/src/tinymemes/jev.rs
@@ -0,0 +1,39 @@
+//! Jev as OpenHuman manages it.
+//!
+//! tinymemes uses the OpenHuman-managed Jev: a signed-in TinyHumans session
+//! reaches Jev through the backend's System One proxy, billed to the account.
+//! There is no other OpenHuman-side route. A different Jev is only used when
+//! `TINYMEMES_JEV` (and its key variables) override it in the environment.
+//!
+//! `None` means managed Jev is unavailable (signed out, or the offline local
+//! session, which has no backend account); the caller then answers Jev's
+//! questions with OpenHuman's own LLM.
+
+use std::sync::Arc;
+
+use tinymemes::decisions::{Client, ClientConfig};
+
+use crate::config::Config;
+use crate::security::credentials::session_support::{
+ is_local_session_token, resolve_backend_credential,
+};
+
+pub(crate) fn managed(config: &Config) -> Option<Arc<dyn tinymemes::Evaluator>> {
+ let secret = resolve_backend_credential(config).ok()?.into_secret();
+ if is_local_session_token(&secret) {
+ return None;
+ }
+ let base = crate::backend::base_url(&config.api_url).ok()?;
+ let mut client = ClientConfig::tinyhumans_openrouter(secret);
+ client.base_url = base;
+ if let Some(identity) = crate::backend::product_identity() {
+ client = client.with_sdk_name(&identity);
+ }
+ match Client::new(client) {
+ Ok(c) => Some(Arc::new(c)),
+ Err(e) => {
+ log::warn!("[tinymemes] managed jev client build failed: {e}");
+ None
+ }
+ }
+}
diff --git a/crates/openhuman-core/src/tinymemes/mod.rs b/crates/openhuman-core/src/tinymemes/mod.rs
index ac4c697254..8fac375d04 100644
--- a/crates/openhuman-core/src/tinymemes/mod.rs
+++ b/crates/openhuman-core/src/tinymemes/mod.rs
@@ -18,9 +18,12 @@
mod arm;
mod host;
-mod key;
+mod inference;
+mod jev;
+#[cfg(feature = "modules")]
+mod search;
-use std::path::Path;
+use crate::config::Config;
use std::time::{Duration, Instant};
pub(crate) use arm::Arm;
@@ -28,11 +31,18 @@ pub(crate) use arm::Arm;
const TIMEOUT_ENV: &str = "OPENHUMAN_TINYMEMES_TIMEOUT_MS";
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(20);
+/// Whether this thread's answer text must be held back from streaming because
+/// its final reply will be remixed (treatment arm). The UI then shows only the
+/// remixed reply instead of the original streaming in and being replaced.
+pub(crate) fn holds_text_stream(thread_id: &str) -> bool {
+ arm::assign(arm::mode(), thread_id) == Arm::Treatment
+}
+
/// Remix a finished turn's reply. Returns the text to deliver instead, or
/// `None` to deliver the original. `turn_elapsed` is the agent turn's own
/// duration, logged for both arms so throughput can be compared.
pub(crate) async fn remix_final_reply(
- workspace_dir: &Path,
+ config: &Config,
thread_id: &str,
request_id: &str,
user_message: &str,
@@ -55,7 +65,7 @@ pub(crate) async fn remix_final_reply(
}
let started = Instant::now();
- let Some(host) = host::host_for(workspace_dir) else {
+ let Some(host) = host::host_for(config) else {
log_outcome(
request_id,
bucket,
@@ -66,7 +76,7 @@ pub(crate) async fn remix_final_reply(
);
return None;
};
- let messages = crate::threads::store::get_messages(workspace_dir.to_path_buf(), thread_id)
+ let messages = crate::threads::store::get_messages(config.workspace_dir.clone(), thread_id)
.unwrap_or_else(|e| {
log::debug!("[tinymemes] thread history unavailable: {e}");
Vec::new()
diff --git a/crates/openhuman-core/src/tinymemes/search.rs b/crates/openhuman-core/src/tinymemes/search.rs
new file mode 100644
index 0000000000..64be5244bd
--- /dev/null
+++ b/crates/openhuman-core/src/tinymemes/search.rs
@@ -0,0 +1,62 @@
+//! OpenHuman's web search as tinymemes' research backend.
+//!
+//! Runs the same checks the `web_search` tool does before calling the search
+//! module: search enabled in settings, the LocalOnly egress block, and at
+//! least one provider able to serve the search role.
+
+use async_trait::async_trait;
+use serde_json::json;
+
+use crate::config::Config;
+
+const TOOL: &str = tinysearch_bus::tools::WEB_SEARCH;
+
+pub(crate) struct OpenHumanSearch {
+ config: Config,
+}
+
+impl OpenHumanSearch {
+ /// A search backend, or `None` when OpenHuman cannot search right now.
+ pub(crate) fn available(config: &Config) -> Option<Self> {
+ if !config.search.is_enabled() {
+ return None;
+ }
+ if crate::search::tools::local_only_search_block(TOOL).is_some() {
+ return None;
+ }
+ let role = tinysearch_bus::role_for_tool(TOOL)?;
+ let resolved = crate::search::providers::resolve(config);
+ if crate::search::providers::effective_role_providers(&resolved, config, role).is_empty() {
+ return None;
+ }
+ Some(Self {
+ config: config.clone(),
+ })
+ }
+}
+
+#[async_trait]
+impl tinymemes::WebSearch for OpenHumanSearch {
+ async fn search(
+ &self,
+ query: &str,
+ max_results: usize,
+ ) -> Result<Vec<tinymemes::SearchHit>, tinymemes::BoxError> {
+ let request = tinysearch_bus::ExecuteToolRequest {
+ name: TOOL.to_string(),
+ arguments: json!({ "query": query, "max_results": max_results.clamp(1, 20) }),
+ };
+ let response = crate::modules::search::execute_tool(&self.config, request)
+ .await
+ .map_err(|e| crate::search::tools::user_facing_error(&e))?;
+ Ok(response
+ .results
+ .into_iter()
+ .map(|r| tinymemes::SearchHit {
+ title: r.title,
+ url: r.url,
+ snippet: r.snippet,
+ })
+ .collect())
+ }
+}
diff --git a/crates/openhuman-core/src/web_chat/progress_bridge.rs b/crates/openhuman-core/src/web_chat/progress_bridge.rs
index 77fe2d2ced..71868350d9 100644
--- a/crates/openhuman-core/src/web_chat/progress_bridge.rs
+++ b/crates/openhuman-core/src/web_chat/progress_bridge.rs
@@ -333,7 +333,14 @@ pub(crate) fn spawn_progress_bridge(
std::sync::Mutex<Option<super::turn_timing::TurnTimingSnapshot>>,
> = std::sync::Arc::new(std::sync::Mutex::new(None));
let timing_snapshot_for_task = timing_snapshot.clone();
+ let hold_text_stream = metadata.hold_text_stream;
crate::core::runtime::spawn_scoped(async move {
+ if hold_text_stream {
+ log::debug!(
+ "[web_channel][bridge] holding text_delta stream (reply is post-processed) request_id={}",
+ request_id
+ );
+ }
log::debug!(
"[web_channel][bridge] spawned client_id={} thread_id={} request_id={} speak_reply={:?} source={:?} session_id={:?}",
client_id,
@@ -1028,19 +1035,21 @@ pub(crate) fn spawn_progress_bridge(
// Buffer the round's narration so it can be flushed as an
// interim bubble if a tool call closes this round.
pending_narration.push_str(&delta);
- publish_seq_stamped(
- &mut emit_seq,
- WebChannelEvent {
- event: "text_delta".to_string(),
- client_id: client_id.clone(),
- thread_id: thread_id.clone(),
- request_id: request_id.clone(),
- round: Some(iteration),
- delta: Some(delta),
- delta_kind: Some("text".to_string()),
- ..Default::default()
- },
- );
+ if !hold_text_stream {
+ publish_seq_stamped(
+ &mut emit_seq,
+ WebChannelEvent {
+ event: "text_delta".to_string(),
+ client_id: client_id.clone(),
+ thread_id: thread_id.clone(),
+ request_id: request_id.clone(),
+ round: Some(iteration),
+ delta: Some(delta),
+ delta_kind: Some("text".to_string()),
+ ..Default::default()
+ },
+ );
+ }
}
AgentProgress::ThinkingDelta { delta, iteration } => {
publish_seq_stamped(
diff --git a/crates/openhuman-core/src/web_chat/progress_bridge_tests.rs b/crates/openhuman-core/src/web_chat/progress_bridge_tests.rs
index 06e0fd1a58..20eb8331bf 100644
--- a/crates/openhuman-core/src/web_chat/progress_bridge_tests.rs
+++ b/crates/openhuman-core/src/web_chat/progress_bridge_tests.rs
@@ -670,3 +670,71 @@ async fn subagent_failed_carries_parent_call_id() {
let subagent = failed.subagent.expect("subagent detail present");
assert_eq!(subagent.parent_call_id.as_deref(), Some("call-parent-3"));
}
+
+/// A held turn (TinyMemes treatment arm) must not stream the answer text, but
+/// narration before a tool call still surfaces as an interim bubble.
+#[tokio::test]
+async fn hold_text_stream_suppresses_text_delta_but_keeps_interim() {
+ use crate::agent::progress::AgentProgress;
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = crate::config::Config {
+ workspace_dir: tmp.path().join("workspace"),
+ action_dir: tmp.path().join("workspace"),
+ config_path: tmp.path().join("config.toml"),
+ ..Default::default()
+ };
+ let store = TurnStateStore::new(tmp.path().join("turn_states"));
+ let (tx, rx) = tokio::sync::mpsc::channel(16);
+ let mut bus = super::super::event_bus::subscribe_web_channel_events();
+ spawn_progress_bridge(
+ rx,
+ "client-hold".into(),
+ "thread-hold".into(),
+ "req-hold".into(),
+ store,
+ ChatRequestMetadata {
+ hold_text_stream: true,
+ ..Default::default()
+ },
+ config,
+ );
+
+ tx.send(AgentProgress::TextDelta {
+ delta: "Let me check the release notes for you first.".into(),
+ iteration: 1,
+ })
+ .await
+ .unwrap();
+ tx.send(AgentProgress::ToolCallStarted {
+ call_id: "tc-hold".into(),
+ tool_name: "web_search".into(),
+ arguments: serde_json::json!({}),
+ iteration: 1,
+ display_label: None,
+ display_detail: None,
+ })
+ .await
+ .unwrap();
+
+ let events = tokio::time::timeout(std::time::Duration::from_secs(5), async {
+ let mut seen = Vec::new();
+ loop {
+ match bus.recv().await {
+ Ok(ev) if ev.thread_id == "thread-hold" => {
+ let done = ev.event == "chat_interim";
+ seen.push(ev.event.clone());
+ if done {
+ return seen;
+ }
+ }
+ Ok(_) => continue,
+ Err(err) => panic!("bus closed: {err}"),
+ }
+ }
+ })
+ .await
+ .expect("chat_interim within timeout");
+
+ assert!(!events.iter().any(|e| e == "text_delta"), "{events:?}");
+ assert!(events.iter().any(|e| e == "chat_interim"));
+}
diff --git a/crates/openhuman-core/src/web_chat/run_task.rs b/crates/openhuman-core/src/web_chat/run_task.rs
index 0244683327..3db2030a43 100644
--- a/crates/openhuman-core/src/web_chat/run_task.rs
+++ b/crates/openhuman-core/src/web_chat/run_task.rs
@@ -160,6 +160,9 @@ pub(crate) async fn run_chat_task(
// can attribute the run (`agent.id` attr / `agent.turn:<id>` trace name).
let mut bridge_metadata = metadata.clone();
bridge_metadata.agent_id = Some(current_fp.target_agent_id.clone());
+ // A TinyMemes treatment thread surfaces only the remixed reply, so the
+ // original answer text is not streamed ahead of it.
+ bridge_metadata.hold_text_stream = crate::tinymemes::holds_text_stream(thread_id);
let bridge = spawn_progress_bridge(
progress_rx,
client_id.to_string(),
@@ -296,7 +299,7 @@ pub(crate) async fn run_chat_task(
let is_placeholder = task_result.full_response == inference_budget_exceeded_user_message();
if !is_placeholder && !task_result.full_response.trim().is_empty() {
if let Some(remixed) = crate::tinymemes::remix_final_reply(
- &task_result.workspace_dir,
+ &config,
thread_id,
request_id,
message,
diff --git a/crates/openhuman-core/src/web_chat/schemas.rs b/crates/openhuman-core/src/web_chat/schemas.rs
index 0bf66f4b27..8c29b664a8 100644
--- a/crates/openhuman-core/src/web_chat/schemas.rs
+++ b/crates/openhuman-core/src/web_chat/schemas.rs
@@ -179,6 +179,9 @@ fn handle_chat(params: Map<String, Value>) -> ControllerFuture {
// Attribution is stamped later by run_chat_task once the
// target agent is resolved.
agent_id: None,
+ // Decided by run_chat_task once the thread's TinyMemes
+ // arm is known.
+ hold_text_stream: false,
},
)
.await?,
diff --git a/crates/openhuman-core/src/web_chat/types.rs b/crates/openhuman-core/src/web_chat/types.rs
index 119f71dee3..3bc4810852 100644
--- a/crates/openhuman-core/src/web_chat/types.rs
+++ b/crates/openhuman-core/src/web_chat/types.rs
@@ -149,6 +149,12 @@ pub struct ChatRequestMetadata {
/// is resolved — used purely for trace attribution (Langfuse `agent.id` /
/// `agent.turn:<id>` trace name), never for routing.
pub agent_id: Option<String>,
+ /// Do not stream the orchestrator's answer text (`text_delta`) to the
+ /// client; the reply arrives whole in `chat_done`. Set for threads whose
+ /// final reply is post-processed (TinyMemes treatment arm), so the user
+ /// never sees the original stream in and then get replaced. Interim
+ /// narration before tool calls is still flushed as `chat_interim`.
+ pub hold_text_stream: bool,
}
#[derive(Debug, Deserialize)]
diff --git a/vendor/tinymemes b/vendor/tinymemes
new file mode 160000
index 0000000000..0d93d1434a
--- /dev/null
+++ b/vendor/tinymemes
@@ -0,0 +1 @@
+Subproject commit 0d93d1434a1b6789ccc97a6c81cec7a31a5654cb