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(runtime_session): handle missing session state on resume
Steven Enamakel0215bf91a783
diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session.rs b/crates/openhuman-core/src/agent/session_host/runtime_session.rsindex 4ffc7ee11d..188782b059 100644--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs@@ -47,9 +47,6 @@ pub(super) struct OpenHumanSessionState {pub(crate) pending_turn_overrides: super::types::TurnOverrides,pub(super) active_turn_overrides: super::types::TurnOverrides,prelude: Option<OpenHumanTurnPrelude>,- pub(crate) pending_citations:- Option<tokio::task::JoinHandle<Vec<crate::memory::agent::memory_loader::MemoryCitation>>>,- pub(crate) last_turn_citations: Vec<crate::memory::agent::memory_loader::MemoryCitation>,}/// Owned host-only inputs used by the async runtime preparation hook.@@ -57,11 +54,8 @@ pub(super) struct OpenHumanSessionState {/// `tinyagents_runtime::Session`.#[derive(Clone)]struct OpenHumanTurnPrelude {- memory: Arc<dyn crate::memory::Memory>,- learning_enabled: bool,- explicit_preferences_enabled: bool,config: crate::config::AgentConfig,- /// Host session-memory state, shared by the runtime hooks. It is not+ /// Host prompt/utilisation state, shared by the runtime hooks. It is not/// generic conversation state and the runtime never persists it.context: Arc<std::sync::Mutex<crate::agent::context::ContextManager>>,tool_policy: Arc<dyn crate::agent::tool_policy::ToolPolicy>,@@ -70,15 +64,13 @@ struct OpenHumanTurnPrelude {action_dir: std::path::PathBuf,model_name: String,agent_definition_name: String,- omit_profile: bool,- omit_memory_md: bool,- auto_save: bool,+ /// Skip the `context.md` injection on new sessions (definition's+ /// `omit_memory_context`).+ omit_memory_context: bool,thread_id: Option<String>,- auto_recall: Option<Arc<crate::memory::auto_recall::AutoRecall>>,agent_definition_id: String,event_session_id: String,event_channel: String,- trigger_memory_agent: crate::agent::harness::definition::TriggerMemoryAgent,subagent_tool_ceiling_names: std::collections::HashSet<String>,turn_model_source: crate::agent::tinyagents::TurnModelSource,temperature: f64,@@ -91,7 +83,6 @@ struct OpenHumanTurnPrelude {allowed_subagent_ids: std::collections::HashSet<String>,sandbox_mode: crate::agent::harness::definition::SandboxMode,runtime_config: Option<Arc<crate::config::Config>>,- archivist_hook: Option<Arc<crate::agent::harness::archivist::ArchivistHook>>,/// The one authoritative, request-refreshable composition of executable/// tools, policy, and provider schema. Generic runtime owns the immutable/// `ToolSnapshot`; this host surface is the source used to create it.@@ -169,7 +160,9 @@ struct OpenHumanTurnPreludeMutable {workflows: Vec<crate::skills::Workflow>,composio_events: Option<tinybus::events::EventReceiver<crate::core::events::DomainEvent>>,skill_events: Option<tinybus::events::EventReceiver<crate::core::events::DomainEvent>>,- pending_user_autosave: Option<String>,+ /// The user-authored text of the in-flight turn, held until commit so the+ /// committed turn can be handed to memory's conversation ingestion.+ pending_user_text: Option<String>,}impl OpenHumanTurnPrelude {@@ -240,8 +233,7 @@ impl OpenHumanTurnPrelude {.map_err(|error| anyhow::anyhow!(error.to_string()))?};let prefix = if cold {- let learned = self.fetch_learned_context().await;- let tiered = self.build_system_prompt_tiered(learned)?;+ let tiered = self.build_system_prompt_tiered()?;Some(super::prefix_snapshot::tiered_prefix_snapshot(&tiered))} else {None@@ -251,111 +243,16 @@ impl OpenHumanTurnPrelude {tools: Some(tools),})}- fn begin_user_effects(&self, state: &mut OpenHumanSessionState, request: &SessionTurnRequest) {- let user_text = request.input.text();- if self.auto_save && crate::agent::turn_origin::current_is_user_authored() {- self.mutable- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .pending_user_autosave = Some(user_text.clone());- }- state.last_turn_citations.clear();- if let Some(previous) = state.pending_citations.take() {- previous.abort();- }- let memory = self.memory.clone();- state.pending_citations = Some(tokio::spawn(async move {- crate::memory::agent::memory_loader::collect_recall_citations(- memory.as_ref(),- &user_text,- 5,- 0.4,- )- .await- .unwrap_or_default()- }));- }-- async fn fetch_learned_context(&self) -> crate::agent::prompts::LearnedContextData {- if !self.learning_enabled && !self.explicit_preferences_enabled {- return Default::default();- }- if !self.learning_enabled && self.explicit_preferences_enabled {- return crate::agent::prompts::LearnedContextData {- user_profile: crate::memory::preferences::load_general_preferences_on(- &self.memory,- crate::memory::preferences::STANDING_PREFS_LIMIT,- )- .await,- ..Default::default()- };- }- use crate::memory::MemoryCategory;- let observations = self- .memory- .list(- Some("learning_observations"),- Some(&MemoryCategory::Custom("learning_observations".into())),- None,- )- .await- .unwrap_or_default();- let patterns = self- .memory- .list(- Some("learning_patterns"),- Some(&MemoryCategory::Custom("learning_patterns".into())),- None,- )- .await- .unwrap_or_default();- let reflections = self- .memory- .list(- Some(crate::agent::learning::reflection::REFLECTIONS_NAMESPACE),- Some(&MemoryCategory::Custom(- crate::agent::learning::reflection::REFLECTIONS_NAMESPACE.into(),- )),- None,- )- .await- .unwrap_or_default();- let limits = self.config.resolved_memory_limits();- crate::agent::prompts::LearnedContextData {- observations: observations- .iter()- .rev()- .take(5)- .map(|entry| sanitize_prelude_entry(&entry.content))- .collect(),- patterns: patterns- .iter()- .take(3)- .map(|entry| sanitize_prelude_entry(&entry.content))- .collect(),- user_profile: crate::memory::preferences::load_general_preferences_on(- &self.memory,- crate::memory::preferences::STANDING_PREFS_LIMIT,- )- .await,- reflections: reflections- .iter()- .rev()- .take(10)- .map(|entry| sanitize_prelude_entry(&entry.content))- .collect(),- tree_root_summaries: collect_prelude_tree_roots(- limits.per_namespace_max_chars,- limits.total_tree_max_chars,- )- .await,- }+ fn begin_user_effects(&self, request: &SessionTurnRequest) {+ let user_text = crate::agent::turn_origin::current_is_user_authored()+ .then(|| request.input.text());+ self.mutable+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .pending_user_text = user_text;}- fn build_system_prompt_tiered(- &self,- learned: crate::agent::prompts::LearnedContextData,- ) -> Result<crate::agent::prompts::TieredPrompt> {+ fn build_system_prompt_tiered(&self) -> Result<crate::agent::prompts::TieredPrompt> {use crate::agent::prompts::{tool_call_format_from_dialect, PromptContext, PromptTool};let surface = self.tool_surface@@ -396,16 +293,12 @@ impl OpenHumanTurnPrelude {tools: &prompt_tools,workflows: &mutable.workflows,dispatcher_instructions: &instructions,- learned,visible_tool_names: &visible_tool_names,tool_call_format: tool_call_format_from_dialect(self.tool_dispatcher.tool_call_format(),),connected_integrations: &mutable.connected_integrations,connected_identities_md: crate::agent::prompts::render_connected_identities(),- include_profile: !self.omit_profile,- include_memory_md: !self.omit_memory_md,- curated_snapshot: None,user_identity: crate::security::credentials::identity::peek_credential_user_identity(),personality_roster: vec![],agents_md_global: agents_md.global,@@ -613,10 +506,9 @@ impl OpenHumanTurnPrelude {original_user_message: &str,overrides: &super::types::TurnOverrides,run_context: &mut OpenHumanRunContext,+ new_session: bool,) -> String {let mut context = String::new();- self.append_recall_lanes(original_user_message, &mut context)- .await;let active_goal = if overrides.suppress_active_goal {None@@ -696,36 +588,12 @@ impl OpenHumanTurnPrelude {.unwrap_or_else(std::sync::PoisonError::into_inner);mutable.last_memory_context = (!context.is_empty()).then_some(context);}- enriched = self- .inject_agent_experience_context(original_user_message, enriched)- .await;-- let parent = run_context.attach_parent(self.parent_context());- let (enriched_with_memory_agent, memory_agent_context_injected) = self- .inject_triggered_memory_agent_context(- original_user_message,- enriched,- parent,- overrides.suppress_memory_agent,- )- .await;- enriched = enriched_with_memory_agent;- let mut prepared_sources = Vec::new();- if memory_agent_context_injected {- prepared_sources.push(crate::agent::harness::AgentContextPreparedSource {- source: "memory agent context retrieval".to_string(),- has_enough_context: None,- });- }- if !prepared_sources.is_empty() {- enriched = format!(- "{}\n\n{enriched}",- render_agent_context_status_note(&prepared_sources)- );- }+ run_context.attach_parent(self.parent_context());self.apply_pending_announcements(&mut enriched);+ if new_session {+ enriched = self.prepend_memory_context(enriched);+ }- run_context.prepared_context_sources = Arc::new(prepared_sources);run_context.attachment_placeholders = Arc::new(crate::agent::multimodal::extract_image_placeholders_in_text(original_user_message),);@@ -744,88 +612,23 @@ impl OpenHumanTurnPrelude {self.tool_dispatcher.tool_call_format(),).harness_dispatcher();- self.context- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .tick_turn();format!("{}\n\n{enriched}",crate::agent::prompts::current_datetime_line())}- async fn append_recall_lanes(&self, user_message: &str, context: &mut String) {- const BUDGET: std::time::Duration = std::time::Duration::from_secs(5);- let preferences = tokio::time::timeout(- BUDGET,- crate::memory::preferences::recall_situational_preferences_on(- &self.memory,- user_message,- ),- )- .await- .unwrap_or_default();- if !preferences.is_empty() {- context.push_str("## Relevant preferences\n\n");- for preference in preferences {- context.push_str(preference.trim());- context.push('\n');- }- context.push('\n');- }- if let Some(auto_recall) = &self.auto_recall {- if let Some(block) = auto_recall.block_for(user_message).await {- context.push_str(&block);- }- }- }-- async fn inject_agent_experience_context(- &self,- user_message: &str,- enriched: String,- ) -> String {- if !self.learning_enabled {+ /// Prepends the compiled `context.md` (wrapped in `<memory-context>`) to a+ /// new session's first user message. A resumed session never reaches+ /// here: its transcript, first message included, is frozen.+ fn prepend_memory_context(&self, enriched: String) -> String {+ if self.omit_memory_context {return enriched;}- let visible_tools = self- .tool_surface- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .visible_tool_specs- .iter()- .map(|spec| spec.name.clone())- .collect();- let query = crate::agent::experience::ExperienceQuery {- query: user_message.to_string(),- tools: visible_tools,- tags: Vec::new(),- agent_id: Some(self.agent_definition_id.clone()).filter(|id| !id.trim().is_empty()),- entrypoint: Some(self.event_channel.clone())- .filter(|channel| !channel.trim().is_empty()),- max_hits: 3,+ let Some(config) = self.runtime_config.as_deref() else {+ return enriched;};- let stores = vec![crate::agent::experience::AgentExperienceStore::new(- self.memory.clone(),- )];- match crate::agent::experience::retrieve_across_stores(&stores, query).await {- Ok(hits) => {- let matched: Vec<_> = hits- .into_iter()- .filter(|hit| !hit.match_reasons.is_empty())- .collect();- let block = crate::agent::experience::render_experience_hits(&matched, 2048);- if block.is_empty() {- enriched- } else {- crate::agent::experience::prepend_experience_block(&enriched, &block)- }- }- Err(error) => {- log::warn!("[agent-experience] retrieval failed (non-fatal): {error}");- enriched- }- }+ crate::memory::context::prepend_to_first_message(config, &enriched)}fn parent_context(&self) -> crate::agent::harness::ParentExecutionContext {@@ -859,7 +662,6 @@ impl OpenHumanTurnPrelude {workspace_descriptor: crate::agent::harness::current_parent().and_then(|parent| parent.workspace_descriptor).or_else(|| self.workspace_descriptor.clone()),- memory: self.memory.clone(),agent_config: self.config.clone(),workflows: Arc::new(workflows),memory_context: Arc::new(memory_context),@@ -876,51 +678,6 @@ impl OpenHumanTurnPrelude {}}- async fn inject_triggered_memory_agent_context(- &self,- user_message: &str,- enriched: String,- parent_context: &crate::agent::harness::ParentExecutionContext,- force_skip: bool,- ) -> (String, bool) {- use crate::agent::harness::definition::TriggerMemoryAgent;- if force_skip- || self.trigger_memory_agent != TriggerMemoryAgent::Always- || self.agent_definition_id == "agent_memory"- {- return (enriched, false);- }- let Some(registry) = crate::agent::harness::AgentDefinitionRegistry::global() else {- return (enriched, false);- };- let Some(definition) = registry.get("agent_memory").cloned() else {- return (enriched, false);- };- let prompt = format!(- "Search the user's memory tree and return only context relevant to the next agent turn.\n\nUser prompt:\n{user_message}"- );- let options = crate::agent::subagent_host::SubagentRunOptions {- task_id: Some(format!("mem-trigger-{}", uuid::Uuid::new_v4())),- model_override: Some(parent_context.model_name.clone()),- run_context: OpenHumanRunContext::new().with_parent(parent_context.clone()),- ..Default::default()- };- match crate::agent::subagent_host::run_subagent(&definition, &prompt, options).await {- Ok(outcome) if !outcome.output.trim().is_empty() => (- format!(- "## Memory agent context\n\n{}\n\n---\n\n{enriched}",- crate::util::truncate_with_ellipsis(&outcome.output, 8000)- ),- true,- ),- Ok(_) => (enriched, false),- Err(error) => {- log::warn!("[agent_memory:trigger] failed: {error:#}");- (enriched, false)- }- }- }-fn apply_pending_announcements(&self, enriched: &mut String) {let mut mutable = self.mutable@@ -942,54 +699,38 @@ impl OpenHumanTurnPrelude {}async fn finalize_after_durable_commit(&self, receipt: &CommitReceipt<OpenHumanRunContext>) {- if self.flush_user_autosave().await {- self.flush_assistant_autosave(receipt.outcome.output.as_deref())- .await;- }self.mirror_transcript_after_commit(receipt);- self.spawn_transcript_ingestion_after_commit(receipt);- self.spawn_session_memory_extraction_after_commit(receipt)- .await;+ self.publish_committed_turn(receipt);}- async fn flush_user_autosave(&self) -> bool {- let message = self+ /// Hands a committed, user-authored, threaded turn to memory's+ /// conversation ingestion (`DomainEvent::ConversationTurnCommitted`).+ /// Tool calls travel by name and id only.+ fn publish_committed_turn(&self, receipt: &CommitReceipt<OpenHumanRunContext>) {+ let user_text = self.mutable.lock().unwrap_or_else(std::sync::PoisonError::into_inner)- .pending_user_autosave+ .pending_user_text.take();- let Some(message) = message else {- return false;- };- self.store_autosave_message("user_msg", &message).await- }-- async fn flush_assistant_autosave(&self, message: Option<&str>) {- let Some(message) = message.filter(|message| !message.trim().is_empty()) else {+ let (Some(user_text), Some(thread_id)) = (user_text, self.thread_id.clone()) else {return;};- self.store_autosave_message("assistant_msg", message).await;- }-- async fn store_autosave_message(&self, kind: &str, message: &str) -> bool {- let key = format!("{kind}:{}", uuid::Uuid::new_v4());- if let Err(error) = self- .memory- .store(- crate::agent::learning::transcript_ingest::CONVERSATION_RAW_NAMESPACE,- &key,- message,- crate::memory::MemoryCategory::Conversation,- self.thread_id.as_deref(),- )- .await- {- log::warn!("[agent_autosave] durable message autosave failed kind={kind} key={key} err={error}");- false- } else {- true- }+ let tool_calls = committed_tool_calls(&receipt.outcome.history);+ log::debug!(+ "[session_host] conversation turn committed tool_calls={}",+ tool_calls.len()+ );+ crate::core::bus::BUS.publish(crate::core::events::DomainEvent::ConversationTurnCommitted {+ thread_id,+ 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,+ workspace_dir: self.workspace_dir.clone(),+ });}fn mirror_transcript_after_commit(&self, receipt: &CommitReceipt<OpenHumanRunContext>) {@@ -1034,89 +775,6 @@ impl OpenHumanTurnPrelude {});}- fn spawn_transcript_ingestion_after_commit(- &self,- receipt: &CommitReceipt<OpenHumanRunContext>,- ) {- let Some(path) = receipt- .transcript- .as_ref()- .map(|commit| commit.path.clone())- else {- return;- };- let memory = self.memory.clone();- tokio::spawn(async move {- if let Err(error) = crate::agent::learning::transcript_ingest::ingest_transcript_path(- memory.as_ref(),- &path,- )- .await- {- log::warn!("[transcript_ingest] background ingest failed: {error}");- }- });- }-- async fn spawn_session_memory_extraction_after_commit(- &self,- receipt: &CommitReceipt<OpenHumanRunContext>,- ) {- let should_extract = self- .context- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .should_extract_session_memory();- if !should_extract {- return;- }- if let Some(archivist) = &self.archivist_hook {- archivist.flush_open_segment(&self.event_session_id).await;- }- // Resolve all fallible launch inputs before mutating the extraction- // state. A missing registry/definition/parent is a no-op, not a- // permanently "in progress" session-memory extraction.- let Some(registry) = crate::agent::harness::AgentDefinitionRegistry::global() else {- return;- };- let Some(definition) = registry.get("archivist").cloned() else {- return;- };- let Some(parent) = receipt.options.context.parent.clone() else {- return;- };- let (handle, stats) = {- let mut context = self- .context- .lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);- let stats = context.stats();- context.mark_session_memory_started();- (context.session_memory_handle(), stats)- };- log::info!(- "[session_memory] scheduling durable archivist extraction turn={}",- stats.session_memory_current_turn- );- tokio::spawn(async move {- let result = crate::agent::subagent_host::run_subagent(- &definition,- crate::agent::context::ARCHIVIST_EXTRACTION_PROMPT,- crate::agent::subagent_host::SubagentRunOptions {- run_context: OpenHumanRunContext::new().with_parent(parent),- ..Default::default()- },- )- .await;- if let Ok(mut state) = handle.lock() {- if result.is_ok() {- state.mark_extraction_complete();- } else {- state.mark_extraction_failed();- }- }- });- }}/// Reconcile visible delegate names without reopening a caller's explicit@@ -1205,58 +863,25 @@ pub(super) fn holistic_last_turn_usage(}}-fn sanitize_prelude_entry(content: &str) -> String {- let value: String = content.trim().chars().take(200).collect();- if value.contains("Bearer ")- || value.contains("sk-")- || value.contains("ghp_")- || value.contains("-----BEGIN")- {- "[redacted: potential secret]".into()- } else {- value- }-}--fn render_agent_context_status_note(- sources: &[crate::agent::harness::AgentContextPreparedSource],-) -> String {- let sources = if sources.is_empty() {- "the OpenHuman harness".to_string()- } else {- sources- .iter()- .map(|source| source.source.as_str())- .collect::<Vec<_>>()- .join(", ")- };- format!(- "## Agent context status\n\nAgent context retrieval/preparation has already run once \- for this turn in code via {sources}. Do not gather general context again. Use the \- prepared context below, and call only specific follow-up tools if a concrete missing \- detail is required."- )-}--async fn collect_prelude_tree_roots(- per_namespace_cap: usize,- total_cap: usize,-) -> Vec<crate::agent::prompts::NamespaceSummary> {- use crate::memory::api::provider::MemoryProvider;- let Ok(guard) = crate::memory::ops::guard::active_memory_guard().await else {- return Vec::new();- };- let Some(tree) = guard.as_tree() else {- return Vec::new();- };- tree.root_summaries_with_caps(per_namespace_cap, total_cap)- .await- .unwrap_or_default()- .into_iter()- .map(|row| crate::agent::prompts::NamespaceSummary {- namespace: row.namespace,- body: row.body,- updated_at: row.updated_at,+/// The tool calls of the last exchange in `history` (everything after the+/// final user message), by name and id.+pub(super) fn committed_tool_calls(+ history: &[Message],+) -> Vec<crate::core::events::ConversationToolCall> {+ let start = history+ .iter()+ .rposition(|message| matches!(message, Message::User(_)))+ .map_or(0, |index| index + 1);+ history[start..]+ .iter()+ .filter_map(|message| match message {+ Message::Assistant(assistant) => Some(&assistant.tool_calls),+ _ => None,+ })+ .flatten()+ .map(|call| crate::core::events::ConversationToolCall {+ name: call.name.clone(),+ id: Some(call.id.clone()).filter(|id| !id.is_empty()),}).collect()}@@ -1468,9 +1093,6 @@ impl OpenHumanSessionHost {.as_ref().map(crate::agent::tinyagents::config::required_output_from);state.prelude = Some(OpenHumanTurnPrelude {- memory: self.memory.clone(),- learning_enabled: self.learning_enabled,- explicit_preferences_enabled: self.explicit_preferences_enabled,config: self.config.clone(),context: self.context.clone(),tool_policy: self.tool_policy.clone(),@@ -1479,15 +1101,11 @@ impl OpenHumanSessionHost {action_dir: self.action_dir.clone(),model_name: self.model_name.clone(),agent_definition_name: self.agent_definition_name.clone(),- omit_profile: self.omit_profile,- omit_memory_md: self.omit_memory_md,- auto_save: self.auto_save,+ omit_memory_context: self.omit_memory_context,thread_id: self.thread_id.clone(),- auto_recall: self.auto_recall.clone(),agent_definition_id: self.agent_definition_id.clone(),event_session_id: self.event_session_id.clone(),event_channel: self.event_channel.clone(),- trigger_memory_agent: self.trigger_memory_agent,subagent_tool_ceiling_names: self.subagent_tool_ceiling_names.clone(),turn_model_source: self.turn_model_source.clone(),temperature: self.temperature,@@ -1505,7 +1123,6 @@ impl OpenHumanSessionHost {.map(|definition| definition.sandbox_mode).unwrap_or(crate::agent::harness::definition::SandboxMode::None),runtime_config: self.runtime_config.clone(),- archivist_hook: self.archivist_hook.clone(),tool_surface: Arc::new(std::sync::Mutex::new(OpenHumanTurnToolSurface {tools: self.tools.clone(),synthesized_tools: self.synthesized_tools.clone(),