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
chore: files changed crates/openhuman-core/src/agent/session_host/runtime_session/memory_ingest.rs
Steven Enamakel4b1a317b3fce
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 46bd0a81e3..3a299eead9 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@@ -1,25 +1,144 @@-//! Handing committed turns to memory's conversation ingestion.+//! The session host's memory hooks: the pre-turn pack and the post-turn log.+//!+//! Before the model runs, [`OpenHumanTurnPrelude::memory_pre_turn`] logs the+//! user turn and recalls the pack the turn is given+//! (`memory::lifecycle::hooks::pre_turn`); `MemoryPackMiddleware` then adds the+//! pack to the turn's requests without persisting it. After the durable+//! commit, [`OpenHumanTurnPrelude::memory_post_turn`] logs the reply with its+//! tool calls. Both run under the session's own config, so a host binding set+//! on a derived context (`[memory] agent_id` / `root`) is honoured, and both+//! resolve the identity the turn runs as (`memory::scope`).+//!+//! The committed turn is also published as+//! `DomainEvent::ConversationTurnCommitted` for observers.+use std::sync::Arc;++use chrono::Utc;+use tinyagents_harness::summarization::is_checkpoint;use tinyagents_runtime::CommitReceipt;use tinyinference_llm::message::Message;use super::OpenHumanTurnPrelude;use crate::agent::tinyagents::host::OpenHumanRunContext;+use crate::memory::lifecycle::hooks::{+ self, PostTurnInput, PreTurnInput, ToolCallSummary, TurnPack,+};+use crate::memory::scope::ResolvedIdentity;++/// The memory side of the turn in flight, held from pre-turn to commit.+#[derive(Debug, Clone)]+pub(super) struct PendingMemoryTurn {+ identity: ResolvedIdentity,+ user_index: u32,+}++/// Where the prompt's verbatim thread starts, as a user turn index, and+/// whether earlier turns were compacted away. Without a checkpoint the whole+/// thread is in the prompt (`0`).+pub(super) fn in_prompt_window(+ history: &[Message],+ committed_turns: usize,+ current: Option<&Message>,+) -> (u32, bool) {+ let Some(checkpoint) = history.iter().rposition(is_checkpoint) else {+ return (0, false);+ };+ let kept_user_turns = history[checkpoint + 1..]+ .iter()+ .filter(|message| matches!(message, Message::User(_)))+ .filter(|message| Some(*message) != current)+ .count();+ (+ hooks::user_turn_index(committed_turns.saturating_sub(kept_user_turns)),+ true,+ )+}impl OpenHumanTurnPrelude {- /// Hands a committed, user-authored, threaded turn to memory's- /// conversation ingestion (`DomainEvent::ConversationTurnCommitted`).- /// Tool calls travel by name and id only.- pub(super) fn publish_committed_turn(&self, receipt: &CommitReceipt<OpenHumanRunContext>) {+ /// The config memory runs under: the session's own, else the+ /// workspace's on disk.+ async fn memory_config(&self) -> Option<Arc<crate::config::Config>> {+ if let Some(config) = &self.runtime_config {+ return Some(config.clone());+ }+ crate::config::rpc::load_config_for_workspace_with_timeout(&self.workspace_dir)+ .await+ .map(Arc::new)+ .map_err(|error| {+ log::debug!("[session_host:memory] no config for memory: {error}");+ })+ .ok()+ }++ /// Logs a user-authored turn and recalls its pack. Remembers the turn so+ /// the reply is logged under the same identity and index.+ pub(super) async fn memory_pre_turn(+ &self,+ history: &[Message],+ committed_turns: usize,+ current: Option<&Message>,+ ) -> Option<Arc<TurnPack>> {let user_text = self.mutable.lock().unwrap_or_else(std::sync::PoisonError::into_inner).pending_user_text- .take();+ .clone()?;+ let thread_id = self.thread_id.clone()?;+ let config = self.memory_config().await?;+ let mut identity = crate::memory::scope::resolve_current(&config);+ if self.omit_memory_context {+ identity.recall = false;+ }+ let user_index = hooks::user_turn_index(committed_turns);+ let (in_prompt_from, compacted) = in_prompt_window(history, committed_turns, current);+ self.mutable+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .pending_memory_turn = Some(PendingMemoryTurn {+ identity: identity.clone(),+ user_index,+ });+ let pack = hooks::pre_turn(+ &config,+ &identity,+ PreTurnInput {+ thread_id: thread_id.clone(),+ turn_index: user_index,+ user_text,+ in_prompt_from,+ at: Utc::now(),+ resumed_after_compaction: compacted && committed_turns > 0,+ },+ )+ .await?;+ crate::core::bus::BUS.publish(crate::core::events::DomainEvent::MemoryPackInjected {+ thread_id,+ agent_id: identity.agent_id.clone(),+ tokens: pack.tokens,+ refs: pack.refs.len(),+ });+ Some(Arc::new(pack))+ }++ /// Logs the committed reply (spawned; never delays the commit) and+ /// publishes `ConversationTurnCommitted`.+ pub(super) fn memory_post_turn(&self, receipt: &CommitReceipt<OpenHumanRunContext>) {+ let (user_text, pending) = {+ let mut mutable = self+ .mutable+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ (+ mutable.pending_user_text.take(),+ mutable.pending_memory_turn.take(),+ )+ };let (Some(user_text), Some(thread_id)) = (user_text, self.thread_id.clone()) else {return;};+ let assistant_text = receipt.outcome.output.clone().unwrap_or_default();let tool_calls = committed_tool_calls(&receipt.outcome.history);log::debug!("[session_host] conversation turn committed tool_calls={}",@@ -27,37 +146,78 @@ impl OpenHumanTurnPrelude {);crate::core::bus::BUS.publish(crate::core::events::DomainEvent::ConversationTurnCommitted {- thread_id,+ thread_id: thread_id.clone(),agent_id: Some(self.agent_definition_id.clone()).filter(|id| !id.trim().is_empty()),workspace: Some(self.action_dir.display().to_string()),channel: Some(self.event_channel.clone()).filter(|channel| !channel.trim().is_empty()),user_text,- assistant_text: receipt.outcome.output.clone().unwrap_or_default(),- tool_calls,+ assistant_text: assistant_text.clone(),+ tool_calls: tool_calls+ .iter()+ .map(|call| crate::core::events::ConversationToolCall {+ name: call.name.clone(),+ id: call.id.clone(),+ })+ .collect(),workspace_dir: self.workspace_dir.clone(),},);+ let Some(pending) = pending else {+ return;+ };+ let prelude = self.clone();+ tokio::spawn(async move {+ let Some(config) = prelude.memory_config().await else {+ return;+ };+ hooks::post_turn(+ &config,+ &pending.identity,+ PostTurnInput {+ thread_id,+ turn_index: pending.user_index.saturating_add(1),+ assistant_text,+ tool_calls,+ at: Utc::now(),+ },+ )+ .await;+ });}}/// The tool calls of the last exchange in `history` (everything after the-/// final user message), by name and id.-fn committed_tool_calls(history: &[Message]) -> Vec<crate::core::events::ConversationToolCall> {+/// final user message), with the start of each result.+fn committed_tool_calls(history: &[Message]) -> Vec<ToolCallSummary> {let start = history.iter().rposition(|message| matches!(message, Message::User(_))).map_or(0, |index| index + 1);- history[start..]+ let exchange = &history[start..];+ let result_of = |id: &str| {+ exchange.iter().find_map(|message| match message {+ Message::Tool(tool) if !id.is_empty() && tool.tool_call_id == id => {+ Some(tool.content.text())+ }+ _ => None,+ })+ };+ exchange.iter().filter_map(|message| match message {Message::Assistant(assistant) => Some(&assistant.tool_calls),_ => None,}).flatten()- .map(|call| crate::core::events::ConversationToolCall {+ .map(|call| ToolCallSummary {name: call.name.clone(),id: Some(call.id.clone()).filter(|id| !id.is_empty()),+ result: result_of(&call.id),}).collect()}++#[cfg(test)]+#[path = "memory_ingest_tests.rs"]+mod tests;