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/agent/session_host/runtime_session.rs,crates/openhuma

Steven Enamakel4f3247cc2622
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session.rs b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
index bcdcfb3426..3e68e3cd20 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
@@ -1153,7 +1153,7 @@ impl OpenHumanSessionHost {
.active_turn_overrides,
);
let current_input = view.history.last().filter(|last| **last == request.input);
- let (enriched, memory_pack) = futures::join!(
+ let (enriched, memory_turn) = futures::join!(
prelude.enrich_request(
&original_user_message,
&overrides,
@@ -1165,7 +1165,7 @@ impl OpenHumanSessionHost {
current_input,
),
);
- options.run_context.data.memory_pack = memory_pack;
+ options.run_context.data.memory_turn = memory_turn;
request.input = user_message_from_text(&enriched);
let mut preparation =
prelude.prepare(new_session).await.map_err(|error| {
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.rs
index abb0294326..8bc4a89553 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
@@ -22,7 +22,7 @@ use tinyinference_llm::message::Message;
use super::OpenHumanTurnPrelude;
use crate::agent::tinyagents::host::OpenHumanRunContext;
use crate::memory::lifecycle::hooks::{
- self, PostTurnInput, PreTurnInput, ToolCallSummary, TurnPack,
+ self, MemoryTurn, PostTurnInput, PreTurnInput, ToolCallSummary,
};
use crate::memory::scope::ResolvedIdentity;
@@ -72,13 +72,14 @@ impl OpenHumanTurnPrelude {
}
/// Logs a user-authored turn and recalls its pack. Remembers the turn so
- /// the reply is logged under the same identity and index.
+ /// the reply is logged under the same identity and index, and returns
+ /// the turn's memory for the run context.
pub(super) async fn memory_pre_turn(
&self,
history: &[Message],
committed_turns: usize,
current: Option<&Message>,
- ) -> Option<Arc<TurnPack>> {
+ ) -> Option<Arc<MemoryTurn>> {
let user_text = self
.mutable
.lock()
@@ -112,14 +113,21 @@ impl OpenHumanTurnPrelude {
resumed_after_compaction: compacted && committed_turns > 0,
},
)
- .await?;
- crate::core::bus::BUS.publish(crate::core::events::DomainEvent::MemoryPackInjected {
+ .await;
+ if let Some(pack) = &pack {
+ crate::core::bus::BUS.publish(crate::core::events::DomainEvent::MemoryPackInjected {
+ thread_id: thread_id.clone(),
+ agent_id: identity.agent_id.clone(),
+ tokens: pack.tokens,
+ refs: pack.refs.len(),
+ });
+ }
+ Some(Arc::new(MemoryTurn {
+ config,
+ identity,
thread_id,
- agent_id: identity.agent_id.clone(),
- tokens: pack.tokens,
- refs: pack.refs.len(),
- });
- Some(Arc::new(pack))
+ pack,
+ }))
}
/// Logs the committed reply (spawned; never delays the commit) and
diff --git a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
index 5a0eb505c3..3d9e4a0699 100644
--- a/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/host/run_context.rs
@@ -307,11 +307,12 @@ pub struct OpenHumanRunContext {
/// the registry that recovers positional / code-style calls; `Auto`
/// (the default) leaves the harness to choose from the model profile.
pub(crate) tool_dialect: tinyagents_harness::config::ToolDispatcher,
- /// The memory pack recalled for this turn (`memory::lifecycle::hooks::
- /// pre_turn`). `MemoryPackMiddleware` adds it to every model request of
- /// the turn, ephemerally: it is never part of the committed transcript.
- /// A child run recalls its own and does not inherit it.
- pub(crate) memory_pack: Option<Arc<crate::memory::lifecycle::hooks::TurnPack>>,
+ /// This turn's memory (`memory::lifecycle::hooks::MemoryTurn`): the pack
+ /// recalled before the model ran, which `MemoryPackMiddleware` adds to
+ /// every model request of the turn ephemerally (never committed), and the
+ /// binding the compaction summarizer recalls under. A child run has its
+ /// own and does not inherit it.
+ pub(crate) memory_turn: Option<Arc<crate::memory::lifecycle::hooks::MemoryTurn>>,
}
/// Minimal immutable authority view exposed to shared tools through the
@@ -360,7 +361,7 @@ impl OpenHumanRunContext {
session_sidecar: Arc::new(Mutex::new(SessionTurnSidecar::default())),
required_output: None,
tool_dialect: tinyagents_harness::config::ToolDispatcher::Auto,
- memory_pack: None,
+ memory_turn: None,
}
}
@@ -451,7 +452,7 @@ impl OpenHumanRunContext {
child.parent_subagent_usage = Some(self.subagent_usage.clone());
child.subagent_usage = Arc::new(Mutex::new(Vec::new()));
child.resolved_route = Arc::new(Mutex::new(None));
- child.memory_pack = None;
+ child.memory_turn = None;
child
}
diff --git a/crates/openhuman-core/src/agent/tinyagents/memory_summarizer.rs b/crates/openhuman-core/src/agent/tinyagents/memory_summarizer.rs
new file mode 100644
index 0000000000..44aa9c6fb1
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/memory_summarizer.rs
@@ -0,0 +1,121 @@
+//! The compaction hook: what memory recalls about the turns a compaction
+//! folds away rides into the checkpoint that replaces them.
+//!
+//! [`MemoryRecallSummarizer`] wraps the turn's summarizer. While the inner
+//! summarizer folds the dropped messages, it asks memory for the same span
+//! (`memory::lifecycle::hooks::compaction` → TinyMemory's
+//! `recall_for_compaction`: an answered summary of the thread plus the
+//! standard sections), concurrently and under its own timeout. A non-empty
+//! pack is appended to the summary under "Recalled from memory". The
+//! checkpoint is a fresh user-role message after a compaction, which already
+//! resets the provider's cache from that point, so it costs no warm prefix.
+//!
+//! The inner summarizer's failure is the summarizer's failure; memory's never
+//! is.
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use tinyagents_harness::error::Result;
+use tinyagents_harness::summarization::{SummaryRecord, SummaryRequest, Summarizer};
+use tinyinference_llm::message::{ContentBlock, Message};
+use tinymemory_api::{Role, Turn};
+
+use crate::memory::lifecycle::hooks::{self, MemoryTurn};
+
+/// Heading of the recalled section in a checkpoint.
+pub(crate) const RECALLED_HEADING: &str = "## Recalled from memory";
+
+/// A summarizer that adds memory's recall of the folded span.
+pub(crate) struct MemoryRecallSummarizer {
+ inner: Box<dyn Summarizer>,
+ turn: Arc<MemoryTurn>,
+}
+
+impl MemoryRecallSummarizer {
+ /// Wraps `inner` for `turn`; without a turn binding the summarizer is
+ /// returned as is.
+ pub(crate) fn wrap(
+ inner: Box<dyn Summarizer>,
+ turn: Option<Arc<MemoryTurn>>,
+ ) -> Box<dyn Summarizer> {
+ match turn {
+ Some(turn) if turn.identity.recall => Box::new(Self { inner, turn }),
+ _ => inner,
+ }
+ }
+
+ async fn with_recall(
+ &self,
+ messages: &[Message],
+ summary: impl std::future::Future<Output = Result<SummaryRecord>>,
+ ) -> Result<SummaryRecord> {
+ let recall = hooks::compaction(
+ &self.turn.config,
+ &self.turn.identity,
+ &self.turn.thread_id,
+ dropped_turns(messages),
+ );
+ let (record, pack) = futures::join!(summary, recall);
+ let mut record = record?;
+ if let Some(pack) = pack {
+ append(&mut record.summary, &format!("\n\n{RECALLED_HEADING}\n\n{}", pack.markdown.trim()));
+ tracing::debug!(
+ thread_id = %self.turn.thread_id,
+ tokens = pack.tokens,
+ "[context_compression] memory recall added to the checkpoint"
+ );
+ }
+ Ok(record)
+ }
+}
+
+#[async_trait]
+impl Summarizer for MemoryRecallSummarizer {
+ async fn summarize(&self, messages: &[Message]) -> Result<SummaryRecord> {
+ self.with_recall(messages, self.inner.summarize(messages))
+ .await
+ }
+
+ async fn summarize_request(&self, request: &SummaryRequest) -> Result<SummaryRecord> {
+ self.with_recall(&request.messages, self.inner.summarize_request(request))
+ .await
+ }
+
+ async fn merge(&self, summaries: &[SummaryRecord]) -> Result<SummaryRecord> {
+ self.inner.merge(summaries).await
+ }
+}
+
+/// The user and assistant text of `messages`, as memory turns. Tool results
+/// and system text are the summarizer's to fold, not memory's to query by.
+pub(crate) fn dropped_turns(messages: &[Message]) -> Vec<Turn> {
+ messages
+ .iter()
+ .filter_map(|message| {
+ let role = match message {
+ Message::User(_) => Role::User,
+ Message::Assistant(_) => Role::Assistant,
+ _ => return None,
+ };
+ let text = message.text();
+ (!text.trim().is_empty()).then(|| Turn::new(role, text))
+ })
+ .collect()
+}
+
+/// Appends `text` to the summary message, whatever its role.
+fn append(summary: &mut Message, text: &str) {
+ let block = ContentBlock::Text(text.to_string());
+ match summary {
+ Message::User(message) => message.content.push(block),
+ Message::System(message) => message.content.push(block),
+ Message::Assistant(message) => message.content.push(block),
+ Message::Tool(message) => message.content.push(block),
+ Message::Custom(_) => {}
+ }
+}
+
+#[cfg(test)]
+#[path = "memory_summarizer_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack.rs
index 2fa10129f5..b3c7951e2f 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack.rs
@@ -2,7 +2,7 @@
//!
//! The session host recalls one pack per turn before the model runs
//! (`memory::lifecycle::hooks::pre_turn`) and parks it on the run context
-//! (`OpenHumanRunContext::memory_pack`). This middleware adds it to every model
+//! (`OpenHumanRunContext::memory_turn`). This middleware adds it to every model
//! request of that turn with [`push_ephemeral_instruction`]: a tail system
//! message, or on a model that hoists system turns (DeepSeek, native
//! Anthropic) a note on the tail user or tool message. The request is built
@@ -38,15 +38,21 @@ impl Middleware<(), OpenHumanRunContext> for MemoryPackMiddleware {
_state: &(),
request: &mut ModelRequest,
) -> TaResult<()> {
- let Some(pack) = ctx.data.memory_pack.clone() else {
+ let Some(pack) = ctx
+ .data
+ .memory_turn
+ .as_ref()
+ .and_then(|turn| turn.pack.as_ref())
+ else {
return Ok(());
};
+ let injection = pack.injection();
tracing::trace!(
tokens = pack.tokens,
refs = pack.refs.len(),
"[tinyagents::mw] memory pack added to the model request"
);
- push_ephemeral_instruction(request, pack.injection(), ctx.model_profile.as_ref());
+ push_ephemeral_instruction(request, injection, ctx.model_profile.as_ref());
Ok(())
}
}
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.rs
index d4e6e92732..e2f165fc4f 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
@@ -5,11 +5,18 @@ use std::sync::Arc;
use tinyagents_harness::context::RunConfig;
use tinyinference_llm::message::Message;
-use crate::memory::lifecycle::hooks::{TurnPack, OPEN_TAG};
+use crate::memory::lifecycle::hooks::{MemoryTurn, TurnPack, OPEN_TAG};
+use crate::memory::scope::MemoryIdentity;
fn context(pack: Option<TurnPack>) -> RunContext<OpenHumanRunContext> {
+ let config = crate::config::Config::default();
let mut data = OpenHumanRunContext::new();
- data.memory_pack = pack.map(Arc::new);
+ data.memory_turn = Some(Arc::new(MemoryTurn {
+ identity: MemoryIdentity::agent("a").resolve(&config),
+ config: Arc::new(config),
+ thread_id: "t".into(),
+ pack,
+ }));
RunContext::new(RunConfig::new("memory-pack-test"), data)
}
@@ -50,5 +57,5 @@ async fn a_turn_without_a_pack_is_left_alone() {
.await
.unwrap();
assert_eq!(request.messages.len(), 1);
- assert!(ctx.data.child().memory_pack.is_none());
+ assert!(ctx.data.child().memory_turn.is_none());
}
diff --git a/crates/openhuman-core/src/memory/lifecycle/hooks.rs b/crates/openhuman-core/src/memory/lifecycle/hooks.rs
index 352f243062..b32cc9deb7 100644
--- a/crates/openhuman-core/src/memory/lifecycle/hooks.rs
+++ b/crates/openhuman-core/src/memory/lifecycle/hooks.rs
@@ -87,6 +87,21 @@ impl TurnPack {
}
}
+/// One turn's memory, carried on its run context: what the compaction hook
+/// needs to recall for this thread under this identity, and the pack the
+/// turn was given.
+#[derive(Debug, Clone)]
+pub struct MemoryTurn {
+ /// The config the session runs under.
+ pub config: std::sync::Arc<Config>,
+ /// Who the turn runs as.
+ pub identity: ResolvedIdentity,
+ /// The conversation thread.
+ pub thread_id: String,
+ /// The pack the turn was given, if any.
+ pub pack: Option<TurnPack>,
+}
+
/// What the agent loop knows before the model runs.
#[derive(Debug, Clone)]
pub struct PreTurnInput {