The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(tinymemes): address review findings
killbille15177540e4e
diff --git a/crates/openhuman-core/src/tinymemes/arm.rs b/crates/openhuman-core/src/tinymemes/arm.rsindex e9ee5c5e5b..9c621bf407 100644--- a/crates/openhuman-core/src/tinymemes/arm.rs+++ b/crates/openhuman-core/src/tinymemes/arm.rs@@ -59,9 +59,13 @@ pub(crate) fn mode_from(value: Option<&str>) -> Mode {"" | "off" | "0" | "false" | "no" => Mode::Off,"on" | "1" | "true" | "yes" => Mode::On,"ab" => Mode::Ab { percent: 50 },- other => match other.strip_prefix("ab:").and_then(|p| p.parse::<u8>().ok()) {+ // Parsed wide, then capped: any numeric percentage above 100 means 100.+ other => match other+ .strip_prefix("ab:")+ .and_then(|p| p.trim().parse::<u64>().ok())+ {Some(percent) => Mode::Ab {- percent: percent.min(100),+ percent: percent.min(100) as u8,},None => {log::warn!("[tinymemes] unrecognised {FLAG_ENV} value; treating as off");diff --git a/crates/openhuman-core/src/tinymemes/arm_tests.rs b/crates/openhuman-core/src/tinymemes/arm_tests.rsindex 6cf0e7b814..fabd5ba66d 100644--- a/crates/openhuman-core/src/tinymemes/arm_tests.rs+++ b/crates/openhuman-core/src/tinymemes/arm_tests.rs@@ -8,7 +8,9 @@ fn flag_values_parse() {assert_eq!(mode_from(Some("1")), Mode::On);assert_eq!(mode_from(Some("ab")), Mode::Ab { percent: 50 });assert_eq!(mode_from(Some("ab:20")), Mode::Ab { percent: 20 });- assert_eq!(mode_from(Some("ab:300")), Mode::Off);+ assert_eq!(mode_from(Some("ab:300")), Mode::Ab { percent: 100 });+ assert_eq!(mode_from(Some("ab:99999")), Mode::Ab { percent: 100 });+ assert_eq!(mode_from(Some("ab:-5")), Mode::Off);assert_eq!(mode_from(Some("ab:250")), Mode::Ab { percent: 100 });assert_eq!(mode_from(Some("ab:100")), Mode::Ab { percent: 100 });assert_eq!(mode_from(Some("sometimes")), Mode::Off);diff --git a/crates/openhuman-core/src/tinymemes/host.rs b/crates/openhuman-core/src/tinymemes/host.rsindex 47449508a1..a13b8a2186 100644--- a/crates/openhuman-core/src/tinymemes/host.rs+++ b/crates/openhuman-core/src/tinymemes/host.rs@@ -2,11 +2,19 @@//! `<workspace>/tinymemes/`://!//! - `slang-index.json`: the slang index, which grows from web research.+//! - `meme-index.json`: reaction GIFs learned from the web, already vetted.//! - `remixed.json`: ids of thread messages that were delivered remixed, so the//! next reading can tell Jev which assistant turns carry the bot's own style.+//!+//! Files are written atomically (temp file, then rename). The engine is+//! rebuilt when the configuration or credentials it was built from change,+//! keeping its learned state.+use std::collections::hash_map::DefaultHasher;use std::collections::{HashMap, VecDeque};-use std::path::PathBuf;+use std::hash::{Hash, Hasher};+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU64, Ordering};use std::sync::{Arc, LazyLock, Mutex};use tinymemes::{@@ -32,6 +40,41 @@ pub(crate) struct Host {pub(crate) engine: MemeEngine,dir: PathBuf,remixed: Mutex<VecDeque<String>>,+ /// What the engine was built from; a change rebuilds it.+ fingerprint: u64,+}++/// `TINYMEMES_*` overrides that change how the engine is built.+const ENV_KEYS: &[&str] = &[+ "TINYMEMES_OPENROUTER_KEY",+ "TINYMEMES_MODEL",+ "TINYMEMES_JEV",+ "TINYMEMES_TYPESAFE_KEY",+ "TYPESAFE_API_KEY",+ "TINYMEMES_OPENJEV_KEY",+ "OPENJEV_API_KEY",+ MEME_COOLDOWN_ENV,+];++/// A fingerprint of everything the engine is built from: the provider route,+/// endpoints, the backend credential (hashed in memory, never stored or+/// logged), search availability, and the env overrides. Settings changes,+/// sign-in after first use, and credential rotation all change it.+pub(crate) fn fingerprint(config: &Config) -> u64 {+ let mut h = DefaultHasher::new();+ config.memory_provider.hash(&mut h);+ config.inference_url.hash(&mut h);+ config.api_url.hash(&mut h);+ config.default_model.hash(&mut h);+ crate::security::credentials::session_support::resolve_backend_credential(config)+ .ok()+ .map(|c| c.into_secret())+ .hash(&mut h);+ openhuman_search(config).is_some().hash(&mut h);+ for key in ENV_KEYS {+ std::env::var(key).ok().hash(&mut h);+ }+ h.finish()}static HOSTS: LazyLock<Mutex<HashMap<PathBuf, Arc<Host>>>> =@@ -49,26 +92,34 @@ static HOSTS: LazyLock<Mutex<HashMap<PathBuf, Arc<Host>>>> =/// | 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 fp = fingerprint(config);let mut hosts = HOSTS.lock().unwrap_or_else(|e| e.into_inner());- if let Some(host) = hosts.get(workspace_dir) {- return Some(host.clone());- }+ let previous = match hosts.get(workspace_dir) {+ Some(host) if host.fingerprint == fp => return Some(host.clone()),+ Some(host) => {+ log::info!("[tinymemes] configuration or credentials changed; rebuilding the engine");+ Some(host.clone())+ }+ None => None,+ };let dir = workspace_dir.join(DIR);if let Err(e) = std::fs::create_dir_all(&dir) {log::warn!("[tinymemes] cannot create state dir: {e}");return None;}- let index = match std::fs::read_to_string(dir.join(INDEX_FILE)) {- Ok(json) => SlangIndex::from_json(&json, IndexPolicy::default()).unwrap_or_else(|e| {- log::warn!("[tinymemes] slang index unreadable, starting fresh: {e}");- SlangIndex::new(IndexPolicy::default())- }),- Err(_) => SlangIndex::new(IndexPolicy::default()),+ // Learned state carries over a rebuild; on first use it loads from disk.+ let (index, meme_index, remixed) = match &previous {+ Some(p) => (+ p.engine.slang_index().clone(),+ p.engine.meme_index().clone(),+ p.remixed.lock().unwrap_or_else(|e| e.into_inner()).clone(),+ ),+ None => (+ Arc::new(load_slang_index(&dir)),+ Arc::new(load_meme_index(&dir)),+ load_remixed(&dir),+ ),};- let remixed: VecDeque<String> = std::fs::read_to_string(dir.join(REMIXED_FILE))- .ok()- .and_then(|json| serde_json::from_str(&json).ok())- .unwrap_or_default();let env = EnvConfig::from_env();let http = reqwest::Client::new();@@ -110,14 +161,6 @@ pub(crate) fn host_for(config: &Config) -> Option<Arc<Host>> {};let search = openhuman_search(config);- let meme_policy = tinymemes::MemeIndexPolicy::default();- let meme_index = match std::fs::read_to_string(dir.join(MEME_INDEX_FILE)) {- Ok(json) => tinymemes::MemeIndex::from_json(&json, meme_policy).unwrap_or_else(|e| {- log::warn!("[tinymemes] meme index unreadable, starting fresh: {e}");- tinymemes::MemeIndex::new(meme_policy)- }),- Err(_) => tinymemes::MemeIndex::new(meme_policy),- };let (researcher, research_label): (Option<Arc<dyn SlangResearcher>>, &str) =match env.web_researcher(&http) {Some(r) => (Some(Arc::new(r)), "env:openrouter-web"),@@ -132,8 +175,8 @@ pub(crate) fn host_for(config: &Config) -> Option<Arc<Host>> {let mut builder = MemeEngine::builder(jev, chat).source(Arc::new(tinymemes::source::Imgflip::new(http.clone())))- .slang_index(Arc::new(index))- .meme_index(Arc::new(meme_index))+ .slang_index(index)+ .meme_index(meme_index).policy(rating_policy())// Research runs in the background after delivery, never on the// reply's critical path.@@ -160,6 +203,7 @@ pub(crate) fn host_for(config: &Config) -> Option<Arc<Host>> {engine,dir,remixed: Mutex::new(remixed),+ fingerprint: fp,});hosts.insert(workspace_dir.to_path_buf(), host.clone());Some(host)@@ -176,6 +220,58 @@ fn openhuman_search(_config: &Config) -> Option<Arc<dyn tinymemes::WebSearch>> {None}+fn load_slang_index(dir: &Path) -> SlangIndex {+ match std::fs::read_to_string(dir.join(INDEX_FILE)) {+ Ok(json) => SlangIndex::from_json(&json, IndexPolicy::default()).unwrap_or_else(|e| {+ log::warn!("[tinymemes] slang index unreadable, starting fresh: {e}");+ SlangIndex::new(IndexPolicy::default())+ }),+ Err(_) => SlangIndex::new(IndexPolicy::default()),+ }+}++fn load_meme_index(dir: &Path) -> tinymemes::MemeIndex {+ let policy = tinymemes::MemeIndexPolicy::default();+ match std::fs::read_to_string(dir.join(MEME_INDEX_FILE)) {+ Ok(json) => tinymemes::MemeIndex::from_json(&json, policy).unwrap_or_else(|e| {+ log::warn!("[tinymemes] meme index unreadable, starting fresh: {e}");+ tinymemes::MemeIndex::new(policy)+ }),+ Err(_) => tinymemes::MemeIndex::new(policy),+ }+}++/// Remixed ids from disk, newest `REMIXED_CAP` kept.+fn load_remixed(dir: &Path) -> VecDeque<String> {+ let mut ids: VecDeque<String> = std::fs::read_to_string(dir.join(REMIXED_FILE))+ .ok()+ .and_then(|json| serde_json::from_str(&json).ok())+ .unwrap_or_default();+ cap_remixed(&mut ids);+ ids+}++fn cap_remixed(ids: &mut VecDeque<String>) {+ while ids.len() > REMIXED_CAP {+ ids.pop_front();+ }+}++static TMP_SEQ: AtomicU64 = AtomicU64::new(0);++/// Write `contents` to `path` atomically: a unique temp file in the same+/// directory, then a rename over the target. Concurrent writers each rename a+/// complete file; a crash never leaves a half-written one.+pub(crate) fn write_atomic(path: &Path, contents: &str) -> std::io::Result<()> {+ let seq = TMP_SEQ.fetch_add(1, Ordering::Relaxed);+ let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("state");+ let tmp = path.with_file_name(format!(".{name}.{}.{seq}.tmp", std::process::id()));+ std::fs::write(&tmp, contents)?;+ std::fs::rename(&tmp, path).inspect_err(|_| {+ let _ = std::fs::remove_file(&tmp);+ })+}+fn rating_policy() -> RatingPolicy {let mut policy = RatingPolicy::default();if let Some(turns) = std::env::var(MEME_COOLDOWN_ENV)@@ -199,35 +295,36 @@ impl Host {pub(crate) fn mark_remixed(&self, message_id: String) {let snapshot = {let mut ids = self.remixed.lock().unwrap_or_else(|e| e.into_inner());- ids.push_back(message_id);- while ids.len() > REMIXED_CAP {- ids.pop_front();+ if ids.contains(&message_id) {+ return;}+ ids.push_back(message_id);+ cap_remixed(&mut ids);serde_json::to_string(&*ids).unwrap_or_default()};- if let Err(e) = std::fs::write(self.dir.join(REMIXED_FILE), snapshot) {+ if let Err(e) = write_atomic(&self.dir.join(REMIXED_FILE), &snapshot) {log::warn!("[tinymemes] cannot save remixed ids: {e}");}}pub(crate) fn save_memes(&self) {let json = self.engine.meme_index().to_json();- if let Err(e) = std::fs::write(self.dir.join(MEME_INDEX_FILE), json) {+ if let Err(e) = write_atomic(&self.dir.join(MEME_INDEX_FILE), &json) {log::warn!("[tinymemes] cannot save meme index: {e}");}}pub(crate) fn save_index(&self) {let json = self.engine.slang_index().to_json();- if let Err(e) = std::fs::write(self.dir.join(INDEX_FILE), json) {+ if let Err(e) = write_atomic(&self.dir.join(INDEX_FILE), &json) {log::warn!("[tinymemes] cannot save slang index: {e}");}}}/// The thread as the user saw it, oldest first: delivered replies (remixed or-/// not) and the user's messages. `current_user_message` is appended when the-/// store does not have it yet.+/// not) and the user's messages. `current_user_message` is appended unless it+/// is already the last stored turn (the store may have persisted it first).pub(crate) fn history_turns(messages: &[ConversationMessage],current_user_message: &str,@@ -248,10 +345,8 @@ pub(crate) fn history_turns(.collect();let current = current_user_message.trim();let already_there = turns- .iter()- .rev()- .find(|t| t.role == tinymemes::Role::User)- .is_some_and(|t| t.text.trim() == current);+ .last()+ .is_some_and(|t| t.role == tinymemes::Role::User && t.text.trim() == current);if !current.is_empty() && !already_there {turns.push(Turn::user(current.to_owned()));}diff --git a/crates/openhuman-core/src/tinymemes/host_tests.rs b/crates/openhuman-core/src/tinymemes/host_tests.rsindex f82de0dff3..e1bb2e6175 100644--- a/crates/openhuman-core/src/tinymemes/host_tests.rs+++ b/crates/openhuman-core/src/tinymemes/host_tests.rs@@ -33,3 +33,55 @@ fn pending_message_is_not_duplicated_when_already_stored() {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");+}++#[test]+fn atomic_writes_replace_the_file_and_leave_no_temp_files() {+ let dir = tempfile::TempDir::new().unwrap();+ let path = dir.path().join("slang-index.json");+ write_atomic(&path, "{\"a\":1}").unwrap();+ write_atomic(&path, "{\"a\":2}").unwrap();+ assert_eq!(std::fs::read_to_string(&path).unwrap(), "{\"a\":2}");+ let entries: Vec<_> = std::fs::read_dir(dir.path()).unwrap().collect();+ assert_eq!(entries.len(), 1, "temp files left behind");+}++#[test]+fn an_oversized_remixed_file_is_capped_on_load() {+ let dir = tempfile::TempDir::new().unwrap();+ let ids: Vec<String> = (0..REMIXED_CAP + 50).map(|i| format!("id-{i}")).collect();+ std::fs::write(+ dir.path().join(REMIXED_FILE),+ serde_json::to_string(&ids).unwrap(),+ )+ .unwrap();+ let loaded = load_remixed(dir.path());+ assert_eq!(loaded.len(), REMIXED_CAP);+ // The newest are kept.+ assert_eq!(+ loaded.back().map(String::as_str),+ Some(format!("id-{}", REMIXED_CAP + 49)).as_deref()+ );+ assert_eq!(loaded.front().map(String::as_str), Some("id-50"));+}++#[test]+fn the_fingerprint_follows_the_provider_settings() {+ let config = crate::config::Config::default();+ let base = fingerprint(&config);+ assert_eq!(fingerprint(&config), base);+ let mut changed = config.clone();+ changed.memory_provider = Some("openrouter:deepseek/deepseek-v4-flash".into());+ assert_ne!(fingerprint(&changed), base);+ let mut changed = config.clone();+ changed.inference_url = Some("https://openrouter.ai/api/v1".into());+ assert_ne!(fingerprint(&changed), base);+}diff --git a/crates/openhuman-core/src/tinymemes/inference.rs b/crates/openhuman-core/src/tinymemes/inference.rsindex 01b8f25201..cfdccb03df 100644--- a/crates/openhuman-core/src/tinymemes/inference.rs+++ b/crates/openhuman-core/src/tinymemes/inference.rs@@ -65,12 +65,12 @@ pub(crate) fn routes_to_openrouter(config: &Config) -> bool {let route_is_openrouter = config.memory_provider.as_deref()- .map(str::trim)+ .map(|p| p.trim().to_ascii_lowercase()).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"));+ .is_some_and(|u| u.to_ascii_lowercase().contains("openrouter.ai"));route_is_openrouter || url_is_openrouter}diff --git a/crates/openhuman-core/src/tinymemes/inference_tests.rs b/crates/openhuman-core/src/tinymemes/inference_tests.rsindex 683e1e7b1f..1424eb3875 100644--- a/crates/openhuman-core/src/tinymemes/inference_tests.rs+++ b/crates/openhuman-core/src/tinymemes/inference_tests.rs@@ -6,6 +6,8 @@ fn openrouter_routes_are_detected() {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://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());diff --git a/crates/openhuman-core/src/tinymemes/jev.rs b/crates/openhuman-core/src/tinymemes/jev.rsindex 476cf5650d..c89fd82cb3 100644--- a/crates/openhuman-core/src/tinymemes/jev.rs+++ b/crates/openhuman-core/src/tinymemes/jev.rs@@ -15,14 +15,16 @@ use tinymemes::decisions::{Client, ClientConfig};use crate::config::Config;use crate::security::credentials::session_support::{- is_local_session_token, resolve_backend_credential,+ is_local_session_token, resolve_backend_credential, BackendCredential,};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;- }+ // Only a session token can be the offline local session; an API key is+ // never classified by its shape.+ let secret = match resolve_backend_credential(config).ok()? {+ BackendCredential::Session(token) if is_local_session_token(&token) => return None,+ BackendCredential::Session(token) | BackendCredential::ApiKey(token) => token,+ };let base = crate::backend::base_url(&config.api_url).ok()?;let mut client = ClientConfig::tinyhumans_openrouter(secret);client.base_url = base;diff --git a/crates/openhuman-core/src/tinymemes/mod.rs b/crates/openhuman-core/src/tinymemes/mod.rsindex f6e2250a23..95f61769bb 100644--- a/crates/openhuman-core/src/tinymemes/mod.rs+++ b/crates/openhuman-core/src/tinymemes/mod.rs@@ -65,7 +65,24 @@ pub(crate) async fn remix_final_reply(}let started = Instant::now();- let Some(host) = host::host_for(config) else {+ // Engine lookup (credentials, first-use state files) and the thread read+ // are blocking file work, so they run off the async runtime.+ let blocking_config = config.clone();+ let blocking_thread = thread_id.to_owned();+ let loaded = crate::core::runtime::spawn_blocking_scoped(move || {+ let host = host::host_for(&blocking_config)?;+ let messages = crate::threads::store::get_messages(+ blocking_config.workspace_dir.clone(),+ &blocking_thread,+ )+ .map_err(|e| log::warn!("[tinymemes] thread history unavailable: {e}"))+ .ok();+ Some((host, messages))+ })+ .await+ .ok()+ .flatten();+ let Some((host, messages)) = loaded else {log_outcome(request_id,bucket,@@ -76,11 +93,19 @@ pub(crate) async fn remix_final_reply();return None;};- 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()- });+ // Fail open: without the thread, the reading would judge the reply out of+ // context, so the original goes out instead.+ let Some(messages) = messages else {+ log_outcome(+ request_id,+ bucket,+ turn_ms,+ started,+ "history_unavailable",+ None,+ );+ return None;+ };let turns = host::history_turns(&messages, user_message, |id| host.is_remixed(id));let budget = std::env::var(TIMEOUT_ENV)@@ -96,9 +121,12 @@ pub(crate) async fn remix_final_reply(}};+ // Whether the delivered reply actually changed.+ let remixed = outcome.remix.is_some() && outcome.reply.trim() != reply.trim();+// Slang research, off the critical path, only for a reply that was- // remixed and only when Jev judged the index short of slang for it.- if let (Some(reading), Some(_)) = (&outcome.reading, &outcome.remix) {+ // actually remixed and only when Jev judged the index short of slang for it.+ if let (Some(reading), true) = (&outcome.reading, remixed) {let policy = host.engine.slang_index().policy();if reading.wants_more_slang(policy.search_below) {let host = host.clone();@@ -158,7 +186,6 @@ pub(crate) async fn remix_final_reply(}}- let remixed = outcome.remix.is_some() && outcome.reply.trim() != reply.trim();let result = if remixed {host.mark_remixed(crate::threads::store::run_reply_message_id(request_id));host.save_index();diff --git a/crates/openhuman-core/src/web_chat/progress_bridge_tests.rs b/crates/openhuman-core/src/web_chat/progress_bridge_tests.rsindex 20eb8331bf..ee96209a4a 100644--- a/crates/openhuman-core/src/web_chat/progress_bridge_tests.rs+++ b/crates/openhuman-core/src/web_chat/progress_bridge_tests.rs@@ -722,7 +722,7 @@ async fn hold_text_stream_suppresses_text_delta_but_keeps_interim() {match bus.recv().await {Ok(ev) if ev.thread_id == "thread-hold" => {let done = ev.event == "chat_interim";- seen.push(ev.event.clone());+ seen.push((ev.event.clone(), ev.full_response.clone()));if done {return seen;}@@ -735,6 +735,11 @@ async fn hold_text_stream_suppresses_text_delta_but_keeps_interim() {.await.expect("chat_interim within timeout");- assert!(!events.iter().any(|e| e == "text_delta"), "{events:?}");- assert!(events.iter().any(|e| e == "chat_interim"));+ assert!(!events.iter().any(|(e, _)| e == "text_delta"), "{events:?}");+ // The interim bubble carries the held narration itself.+ let interim = events.iter().find(|(e, _)| e == "chat_interim").unwrap();+ assert_eq!(+ interim.1.as_deref(),+ Some("Let me check the release notes for you first.")+ );}