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
feat(memory): keep the memory tool's thread window live across a turn
sanil-23b3fdc874bf3d
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rs b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rsindex 2ed272bfcf..e6076b9f60 100644--- a/crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rs@@ -167,7 +167,10 @@ impl OpenHumanTurnPrelude {identity,thread_id,pack,- in_prompt_from,+ in_prompt_from: Arc::new(crate::memory::lifecycle::window::InPromptFrom::new(+ in_prompt_from,+ user_index,+ )),core: self.host_env.core.clone(),}))}diff --git a/crates/openhuman-core/src/agent/tinyagents/host/operation_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/operation_context.rsindex 373a577ed7..3fd41a08de 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/operation_context.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/operation_context.rs@@ -53,10 +53,10 @@ pub(crate) struct HostOperationContext {/// Who the run acts as on memory; see/// [`OpenHumanRunContext::memory_identity`](super::OpenHumanRunContext::memory_identity).pub(crate) memory_identity: Option<crate::memory::scope::MemoryIdentity>,- /// The thread's turns still verbatim in the run's prompt, from the turn's- /// memory (see [`MemoryTurn::in_prompt`](crate::memory::lifecycle::hooks::MemoryTurn::in_prompt)).+ /// The turn's memory, read live for the thread's turns still verbatim in+ /// the run's prompt (see [`MemoryTurn::in_prompt`](crate::memory::lifecycle::hooks::MemoryTurn::in_prompt))./// `None` when the turn has no memory, as a sub-agent's run does.- pub(crate) memory_in_prompt: Option<tinymemory_api::ThreadWindow>,+ pub(crate) memory_turn: Option<std::sync::Arc<crate::memory::lifecycle::hooks::MemoryTurn>>,/// The context the run acts under; see/// [`OpenHumanRunContext::core`](super::OpenHumanRunContext::core).pub(crate) core: Option<std::sync::Weak<crate::core::runtime::CoreContext>>,@@ -124,7 +124,8 @@ pub(crate) fn memory_identity_for_tool(}/// Reads the thread's turns still verbatim in the run's prompt from the-/// explicit tool carrier. Direct tool dispatch has none.+/// explicit tool carrier, as they stand now: a compaction earlier in the turn+/// has already moved them. Direct tool dispatch has none.pub(crate) fn memory_in_prompt_for_tool(context: Option<&dyn tinytools::ToolRunContext>,) -> Option<tinymemory_api::ThreadWindow> {@@ -134,7 +135,7 @@ pub(crate) fn memory_in_prompt_for_tool(extension.downcast_ref::<tinyagents_harness::tool::ToolExecutionContext>()}).and_then(|context| context.state::<HostOperationContext>())- .and_then(|host| host.memory_in_prompt.clone())+ .and_then(|host| host.memory_turn.as_ref().map(|turn| turn.in_prompt()))}/// Reads the calling agent's sandbox policy from the explicit tool carrier.diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rsindex eb8210205e..6d45f0535b 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs@@ -682,7 +682,7 @@ impl OpenHumanRunContext {.as_ref().map(|parent| parent.agent_definition_id.clone()),memory_identity: self.memory_identity.clone(),- memory_in_prompt: self.memory_turn.as_ref().map(|turn| turn.in_prompt()),+ memory_turn: self.memory_turn.clone(),core: self.core.clone(),});let context = tinyagents_harness::context::RunContext::new(config, self)diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rsindex 99c4e228c8..821af67226 100644--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context_tests.rs@@ -696,7 +696,9 @@ fn the_turns_still_in_the_prompt_reach_the_runs_tools() {config: std::sync::Arc::new(config),thread_id: "thread-long".into(),pack: None,- in_prompt_from: 12,+ in_prompt_from: std::sync::Arc::new(+ crate::memory::lifecycle::window::InPromptFrom::new(12, 20),+ ),core: None,},));diff --git a/crates/openhuman-core/src/agent/tinyagents/memory_summarizer.rs b/crates/openhuman-core/src/agent/tinyagents/memory_summarizer.rsindex e4b3a92297..6c0b163d47 100644--- a/crates/openhuman-core/src/agent/tinyagents/memory_summarizer.rs+++ b/crates/openhuman-core/src/agent/tinyagents/memory_summarizer.rs@@ -16,7 +16,7 @@ use std::sync::Arc;use async_trait::async_trait;use tinyagents_harness::error::Result;-use tinyagents_harness::summarization::{Summarizer, SummaryRecord, SummaryRequest};+use tinyagents_harness::summarization::{is_checkpoint, Summarizer, SummaryRecord, SummaryRequest};use tinyinference_llm::message::{ContentBlock, Message};use tinymemory_api::{Role, Turn};@@ -57,6 +57,14 @@ impl MemoryRecallSummarizer {dropped_turns(messages),);let mut record = summary.await?;+ // The folded user turns are out of the prompt now, so the turn's next+ // memory read may return them.+ self.turn.in_prompt_from.advance_past(+ messages+ .iter()+ .filter(|message| matches!(message, Message::User(_)) && !is_checkpoint(message))+ .map(Message::text),+ );// A later compaction folds the previous checkpoint, recall included;// keep one recall section, the current one.strip_recalled(&mut record.summary);diff --git a/crates/openhuman-core/src/agent/tinyagents/memory_summarizer_tests.rs b/crates/openhuman-core/src/agent/tinyagents/memory_summarizer_tests.rsindex f551d7c23b..583047df05 100644--- a/crates/openhuman-core/src/agent/tinyagents/memory_summarizer_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/memory_summarizer_tests.rs@@ -54,7 +54,7 @@ async fn bound_turn(tmp: &tempfile::TempDir) -> Arc<MemoryTurn> {identity,thread_id: "t".into(),pack: None,- in_prompt_from: 0,+ in_prompt_from: Arc::new(crate::memory::lifecycle::window::InPromptFrom::new(0, 20)),core: None,})}@@ -238,7 +238,7 @@ async fn a_held_memory_engine_does_not_delay_transcript_compaction() {identity,thread_id: "held".into(),pack: None,- in_prompt_from: 0,+ in_prompt_from: Arc::new(crate::memory::lifecycle::window::InPromptFrom::new(0, 20)),core: None,});let summarizer = MemoryRecallSummarizer::wrap(Box::new(ConcatSummarizer), Some(turn));@@ -251,3 +251,33 @@ async fn a_held_memory_engine_does_not_delay_transcript_compaction() {.unwrap();assert!(record.summary.text().contains("March 3rd"));}++#[tokio::test]+async fn a_compaction_during_the_turn_moves_its_memory_window() {+ let tmp = tempfile::tempdir().unwrap();+ let turn = bound_turn(&tmp).await;+ assert_eq!(turn.in_prompt().from_turn, 0);++ // A failed fold folds nothing: the window stays.+ let failing = MemoryRecallSummarizer::wrap(Box::new(Failing), Some(turn.clone()));+ assert!(failing.summarize(&dropped()).await.is_err());+ assert_eq!(turn.in_prompt().from_turn, 0);++ // One user message folded: its turn and the reply leave the prompt, so the+ // turn's next memory read may return them.+ let summarizer = MemoryRecallSummarizer::wrap(Box::new(ConcatSummarizer), Some(turn.clone()));+ summarizer.summarize(&dropped()).await.unwrap();+ assert_eq!(turn.in_prompt().from_turn, 2);++ // The same span folded again moves nothing; a new one moves it on.+ summarizer.summarize(&dropped()).await.unwrap();+ assert_eq!(turn.in_prompt().from_turn, 2);+ summarizer+ .summarize(&[+ Message::user("what about the venue?"),+ Message::assistant("The hall."),+ ])+ .await+ .unwrap();+ assert_eq!(turn.in_prompt().from_turn, 4);+}diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack_tests.rsindex 0f23e94cf2..5e6295d4f9 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack_tests.rs@@ -19,7 +19,7 @@ fn context(pack: Option<TurnPack>) -> RunContext<OpenHumanRunContext> {config: Arc::new(config),thread_id: "t".into(),pack,- in_prompt_from: 0,+ in_prompt_from: Arc::new(crate::memory::lifecycle::window::InPromptFrom::new(0, 0)),core: None,}));RunContext::new(RunConfig::new("memory-pack-test"), data)diff --git a/crates/openhuman-core/src/memory/lifecycle/hooks.rs b/crates/openhuman-core/src/memory/lifecycle/hooks.rsindex d2122fd7c4..395266741f 100644--- a/crates/openhuman-core/src/memory/lifecycle/hooks.rs+++ b/crates/openhuman-core/src/memory/lifecycle/hooks.rs@@ -151,10 +151,10 @@ pub struct MemoryTurn {pub thread_id: String,/// The pack the turn was given, if any.pub pack: Option<TurnPack>,- /// The first turn of the thread still verbatim in the turn's prompt:- /// the turns before it were compacted into a checkpoint. 0 when nothing- /// was compacted.- pub in_prompt_from: u32,+ /// The first turn of the thread still verbatim in the turn's prompt: the+ /// turns before it were compacted into a checkpoint (0 when nothing was).+ /// Live: a compaction during the turn moves it forward.+ pub in_prompt_from: std::sync::Arc<super::window::InPromptFrom>,/// The context the turn runs under, held weakly so a finished tenant's/// lease is not kept alive by a lingering turn handle.pub core: Option<std::sync::Weak<crate::core::runtime::CoreContext>>,@@ -167,7 +167,7 @@ impl MemoryTurn {pub fn in_prompt(&self) -> tinymemory_api::ThreadWindow {tinymemory_api::ThreadWindow {thread_id: self.thread_id.clone(),- from_turn: self.in_prompt_from,+ from_turn: self.in_prompt_from.get(),}}diff --git a/crates/openhuman-core/src/memory/lifecycle/mod.rs b/crates/openhuman-core/src/memory/lifecycle/mod.rsindex 3a48f5838d..5dc8ea5e2c 100644--- a/crates/openhuman-core/src/memory/lifecycle/mod.rs+++ b/crates/openhuman-core/src/memory/lifecycle/mod.rs@@ -22,6 +22,7 @@ pub mod jobs;pub(crate) mod prefetch;pub mod sender;pub mod views;+pub mod window;use std::sync::Arc;diff --git a/crates/openhuman-core/src/memory/lifecycle/window.rs b/crates/openhuman-core/src/memory/lifecycle/window.rsnew file mode 100644index 0000000000..9b9057863d--- /dev/null+++ b/crates/openhuman-core/src/memory/lifecycle/window.rs@@ -0,0 +1,80 @@+//! The first turn of a thread still verbatim in a turn's prompt, kept live+//! across the turn: the turn's memory reads leave the thread out from there,+//! and a compaction during the turn moves it forward.++use std::collections::HashSet;+use std::hash::{DefaultHasher, Hash, Hasher};+use std::sync::atomic::{AtomicU32, Ordering};+use std::sync::Mutex;++/// The first turn of a thread still verbatim in a turn's prompt.+///+/// The pre-turn step sets it from the transcript's last checkpoint. When a+/// compaction during the turn folds more of the thread, the compaction hook+/// advances it past the user turns it folded, so the turn's next memory read+/// can return them. It never passes the turn's own index: the message being+/// answered, and the reply being written, stay out.+#[derive(Debug)]+pub struct InPromptFrom {+ from: AtomicU32,+ ceiling: u32,+ folded: Mutex<HashSet<u64>>,+}++impl InPromptFrom {+ /// Starts at `from`, never past `ceiling`: the turn's own user-turn index.+ #[must_use]+ pub fn new(from: u32, ceiling: u32) -> Self {+ Self {+ from: AtomicU32::new(from.min(ceiling)),+ ceiling,+ folded: Mutex::default(),+ }+ }++ /// The first turn still in the prompt.+ #[must_use]+ pub fn get(&self) -> u32 {+ self.from.load(Ordering::Acquire)+ }++ /// Moves past the user messages a compaction folded: two memory turns (the+ /// message and its reply) for each one not folded before, so a span folded+ /// again does not count twice. Returns the new value.+ pub fn advance_past<I>(&self, folded_user_texts: I) -> u32+ where+ I: IntoIterator,+ I::Item: AsRef<str>,+ {+ let mut seen = self+ .folded+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ let fresh = folded_user_texts+ .into_iter()+ .filter(|text| {+ let mut hasher = DefaultHasher::new();+ text.as_ref().hash(&mut hasher);+ seen.insert(hasher.finish())+ })+ .count();+ let from = self.get();+ if fresh == 0 {+ return from;+ }+ let step = u32::try_from(fresh).unwrap_or(u32::MAX).saturating_mul(2);+ let next = from.saturating_add(step).min(self.ceiling);+ self.from.store(next, Ordering::Release);+ tracing::debug!(+ from,+ next,+ folded = fresh,+ "[memory:window] compaction moved the in-prompt window"+ );+ next+ }+}++#[cfg(test)]+#[path = "window_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/memory/lifecycle/window_tests.rs b/crates/openhuman-core/src/memory/lifecycle/window_tests.rsnew file mode 100644index 0000000000..f75009f3a2--- /dev/null+++ b/crates/openhuman-core/src/memory/lifecycle/window_tests.rs@@ -0,0 +1,28 @@+use super::*;++#[test]+fn starts_where_the_pre_turn_step_put_it_and_never_past_the_turn() {+ assert_eq!(InPromptFrom::new(6, 20).get(), 6);+ assert_eq!(InPromptFrom::new(30, 20).get(), 20);+}++#[test]+fn a_fold_moves_it_two_turns_per_new_user_message() {+ let window = InPromptFrom::new(6, 20);+ assert_eq!(+ window.advance_past(["first question", "second question"]),+ 10+ );+ assert_eq!(window.get(), 10);+ // Folding the same messages again (a retried or extended compaction)+ // moves nothing.+ assert_eq!(window.advance_past(["second question"]), 10);+ assert_eq!(window.advance_past(Vec::<String>::new()), 10);+ assert_eq!(window.advance_past(["third question"]), 12);+}++#[test]+fn it_stops_at_the_turn_being_answered() {+ let window = InPromptFrom::new(16, 20);+ assert_eq!(window.advance_past(["a", "b", "c", "d", "e"]), 20);+}