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/builder/factory.rs,crates/openhuma

Steven Enamakelb68227bc7d4b
diff --git a/crates/openhuman-core/src/agent/session_host/builder/factory.rs b/crates/openhuman-core/src/agent/session_host/builder/factory.rs
index c808286d49..631cb47174 100644
--- a/crates/openhuman-core/src/agent/session_host/builder/factory.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/factory.rs
@@ -2,7 +2,6 @@
//! `build_session_agent_inner` constructor.
use super::dispatcher::{resolve_dispatcher_kind, DispatcherKind};
-use super::helpers::prefetch_tool_memory_rules_blocking;
use super::should_synthesize_delegation_tools;
use crate::agent::harness::definition::NO_TOOLS_SENTINEL;
use crate::agent::harness::definition::{AgentDefinitionRegistry, PromptSource, ToolScope};
@@ -10,9 +9,6 @@ use crate::agent::host_runtime;
use crate::agent::prompts::SystemPromptBuilder;
use crate::agent::session_host::types::OpenHumanSessionHost;
use crate::config::Config;
-use crate::inference::provider;
-use crate::memory::tool_memory::capture::ToolMemoryCaptureHook;
-use crate::memory::Memory;
use crate::security::SecurityPolicy;
use crate::tools;
use anyhow::Result;
@@ -58,10 +54,10 @@ impl OpenHumanSessionHost {
/// Shared infrastructure between agent ids is identical:
/// 1. Initializing the host runtime (native or docker).
/// 2. Setting up security policies.
- /// 3. Initializing memory and embedding services.
- /// 4. Registering all built-in and orchestrator tools.
- /// 5. Configuring the routed AI provider.
- /// 6. Setting up the learning system and post-turn hooks.
+ /// 3. Registering all built-in and orchestrator tools (the `memory` tool
+ /// only while memory is on).
+ /// 4. Configuring the routed AI provider.
+ /// 5. Setting up post-turn hooks.
///
/// What differs per agent id:
/// * `visible_tool_names` is the agent's `ToolScope::Named` list
@@ -89,7 +85,7 @@ impl OpenHumanSessionHost {
log::info!(
"[agent::builder] building session agent id={} \
- (scope={}, omit_identity={}, omit_profile={}, omit_memory_md={}, temperature={:.2})",
+ (scope={}, omit_identity={}, omit_memory_context={}, temperature={:.2})",
agent_id,
target_def
.as_ref()
@@ -102,11 +98,10 @@ impl OpenHumanSessionHost {
.as_ref()
.map(|d| d.omit_identity)
.unwrap_or(false),
- target_def.as_ref().map(|d| d.omit_profile).unwrap_or(true),
target_def
.as_ref()
- .map(|d| d.omit_memory_md)
- .unwrap_or(true),
+ .map(|d| d.omit_memory_context)
+ .unwrap_or(false),
target_def
.as_ref()
.map(|d| d.temperature)
@@ -156,7 +151,7 @@ impl OpenHumanSessionHost {
host: Option<&super::HostTools>,
session_id: Option<&str>,
) -> Result<Self> {
- let workspace_descriptor = super::helpers::derive_turn_workspace_descriptor();
+ let workspace_descriptor = derive_turn_workspace_descriptor();
let runtime: Arc<dyn host_runtime::RuntimeAdapter> = Arc::from(
host_runtime::create_runtime(&config.runtime, config.shell.hide_window)?,
@@ -172,35 +167,6 @@ impl OpenHumanSessionHost {
config.workspace_dir.clone(),
)?;
- // The session's store, through the same binding the archivist resolves
- // two statements down — so one subtree yields one store rather than an
- // engine handle beside a driver over the same files.
- //
- // The two reasons this was deferred are both settled. **Embedder
- // resolution**: the factory's ladder and the driver's are the same
- // code reading the same field. `Config::workload_local_model` and
- // `EngineRuntimeConfig::workload_local_model` both take
- // `embeddings_provider`, strip `"ollama:"`, trim and reject empty, and
- // that `Option` is the only input to `effective_embedding_settings`.
- // The Ollama health-gate is not a difference either: it lives inside
- // `create_unified_memory_full`, which the module runs because the
- // module *is* the engine, and its probe address is proxied back here
- // through `EmbeddingHost::ollama_base_url`. (`embedding_routes` never
- // mattered — the engine's own parameter is underscore-prefixed and
- // unused.) **The test build**: `binding::module_provider` under
- // `cfg(test)` loads the module when `TINYMEMORY_TEST_MODULE` names it
- // and degrades to the null driver otherwise, which is the same footing
- // the archivist has had here all along.
- let memory: Arc<dyn Memory> =
- crate::agent::experience::ops::DriverMemory::for_config(config)
- .map_err(|e| anyhow::anyhow!("session memory binding: {e}"))?;
- // The archivist takes the bound driver for this session's memory
- // subtree — the same subtree `session_memory` opened — rather than the
- // raw SQLite handle the factory used to strip off the engine result.
- // That handle was the #5378 `:290` blocker: a concrete connection no
- // module or remote driver can supply. The engine's connection is now
- // exclusively the engine's. Lane C (#6040) rides the same binding.
- let (archivist_provider, auto_recall) = super::helpers::bind_session_memory(config)?;
// Load the user's persisted tool preferences once. They drive two
// things below: granting the App UI Control / App Automation mutation
// opt-in (#3762) and filtering the tool set to the enabled snapshot.
@@ -224,7 +190,7 @@ impl OpenHumanSessionHost {
enabled_tools.extend(["browser".to_string(), "browser_open".to_string()]);
}
// Share a single `Arc<Config>` across the heavyweight per-build consumers
- // (the tool registry, the reflection hook, the turn provider) instead of
+ // (the tool registry, the turn provider) instead of
// deep-cloning the large `Config` at each site (#5050, Fix 1). `Config` is
// immutable after construction, so one refcounted instance is behaviourally
// identical to N independent clones.
@@ -382,7 +348,7 @@ impl OpenHumanSessionHost {
// fetched asynchronously on session start land in the prompt.
// `Inline`/`File` sources still resolve to just the archetype
// body and get wrapped by [`SystemPromptBuilder::for_subagent`].
- let mut prompt_builder = match target_def {
+ let prompt_builder = match target_def {
Some(def) => match &def.system_prompt {
PromptSource::Dynamic(build) => SystemPromptBuilder::from_dynamic(*build),
PromptSource::Inline(text) => SystemPromptBuilder::for_subagent(
@@ -430,140 +396,8 @@ impl OpenHumanSessionHost {
},
None => SystemPromptBuilder::with_defaults(),
};
- if config.learning.enabled {
- // Insert the privileged reflection block ahead of the
- // generic `user_memory` section when one is already
- // present (the `with_defaults` chain includes it). For
- // builders that do not contain `user_memory` (dynamic /
- // sub-agent prompts), the helper falls back to appending,
- // which still keeps reflections ahead of the
- // learned-context / user-profile blocks added immediately
- // after.
- prompt_builder = prompt_builder
- .insert_section_before(
- "user_memory",
- Box::new(crate::agent::prompts::UserReflectionsSection),
- )
- .add_section(Box::new(
- crate::agent::learning::LearnedContextSection::new(memory.clone()),
- ))
- .add_section(Box::new(crate::agent::learning::UserProfileSection::new(
- memory.clone(),
- )));
- // NOTE: MemoryAccessSection is added after tool-filtering so we can
- // gate it on retrieval-tool visibility — see below.
- log::info!(
- "[learning] prompt sections registered (user_reflections, learned_context, user_profile)"
- );
- }
-
- // Explicit-preferences injection — independent of the full learning
- // subsystem. When `explicit_preferences_enabled` is true (the default)
- // and the full learning subsystem is NOT already wiring UserProfileSection,
- // we add it here so pinned preferences written by `remember_preference`
- // reach every session prompt. The `fetch_learned_context` gate is
- // widened by `explicit_preferences_enabled` on the OpenHumanSessionHost (see
- // `session/turn.rs`) so the data is actually fetched and populated.
- if config.learning.explicit_preferences_enabled && !config.learning.enabled {
- prompt_builder = prompt_builder.add_section(Box::new(
- crate::agent::learning::UserProfileSection::new(memory.clone()),
- ));
- log::info!(
- "[learning] explicit-preference UserProfileSection registered \
- (learning.enabled=false, explicit_preferences_enabled=true)"
- );
- }
-
- // Build post-turn hooks when learning is enabled
- let mut post_turn_hooks: Vec<Arc<dyn crate::agent::hooks::PostTurnHook>> = Vec::new();
- if config.learning.enabled {
- if config.learning.reflection_enabled {
- // The reflection hook needs an owned `Arc<Config>`; reuse the
- // shared base config (a refcount bump) rather than a second deep
- // clone of the full config (#5050, Fix 1).
- let full_config = Arc::clone(&base_config);
- // For cloud reflection, wrap the provider in an Arc.
- // For local, no provider needed.
- let reflection_provider: Option<Arc<dyn tinyinference_llm::model::ChatModel<()>>> =
- if config.learning.reflection_source == crate::config::ReflectionSource::Cloud {
- let (model, resolved_model) =
- provider::create_chat_model_with_model_id("reasoning", config, 0.3)?;
- log::debug!(
- "[learning] built crate-native reflection model resolved_model={resolved_model}"
- );
- Some(model)
- } else {
- None
- };
- post_turn_hooks.push(Arc::new(crate::agent::learning::ReflectionHook::new(
- config.learning.clone(),
- full_config.clone(),
- memory.clone(),
- reflection_provider,
- )));
- log::info!(
- "[learning] reflection hook registered (source={:?})",
- config.learning.reflection_source
- );
- }
-
- if config.learning.user_profile_enabled {
- post_turn_hooks.push(Arc::new(crate::agent::learning::UserProfileHook::new(
- config.learning.clone(),
- memory.clone(),
- )));
- log::info!("[learning] user_profile hook registered");
- }
-
- if config.learning.tool_tracking_enabled {
- post_turn_hooks.push(Arc::new(crate::agent::learning::ToolTrackerHook::new(
- config.learning.clone(),
- memory.clone(),
- )));
- log::info!("[learning] tool_tracker hook registered");
- }
-
- if config.learning.tool_memory_capture_enabled {
- post_turn_hooks.push(Arc::new(ToolMemoryCaptureHook::new(memory.clone(), true)));
- log::info!("[learning] tool_memory_capture hook registered");
- }
-
- if config.learning.tool_memory_capture_enabled {
- post_turn_hooks.push(Arc::new(
- crate::agent::experience::AgentExperienceCaptureHook::new(memory.clone(), true),
- ));
- log::info!("[learning] agent_experience_capture hook registered");
- }
- }
-
- // ── ArchivistHook — register independently of learning.enabled ──────
- //
- // Episodic capture (FTS5 index, segment lifecycle, LLM recap, embedding)
- // is the system-of-record for chat turns and must stay active even when
- // the inference stack (`reflection`, `stability_detector`) is disabled.
- // Gated only on `config.learning.episodic_capture_enabled` (default: true)
- // using the explicit SQLite resource returned by the session factory.
- let archivist_hook_arc: Option<Arc<crate::agent::harness::archivist::ArchivistHook>> =
- if config.learning.episodic_capture_enabled {
- let hook = Arc::new(
- crate::agent::harness::archivist::ArchivistHook::new(archivist_provider, true)
- .with_config(Arc::clone(&base_config)),
- );
- post_turn_hooks
- .push(Arc::clone(&hook) as Arc<dyn crate::agent::hooks::PostTurnHook>);
- log::info!(
- "[archivist] episodic capture hook registered (learning.enabled={})",
- config.learning.enabled
- );
- Some(hook)
- } else {
- log::info!(
- "[archivist] episodic_capture_enabled=false — archivist hook not registered"
- );
- None
- };
-
- post_turn_hooks.extend(crate::agent::hooks::embedder_post_turn_hooks());
+ let post_turn_hooks: Vec<Arc<dyn crate::agent::hooks::PostTurnHook>> =
+ crate::agent::hooks::embedder_post_turn_hooks();
// Best-effort prewarm from the shared Composio cache. This avoids
// building the session with a knowingly stale `&[]` integration view
@@ -584,7 +418,7 @@ impl OpenHumanSessionHost {
// connected Composio action (reached through `tool_search`).
//
// For an agent without `subagents` (today: welcome, critic,
- // archivist, etc.), no delegation tools are synthesised — the
+ // summarizer, etc.), no delegation tools are synthesised — the
// LLM only sees the agent's own `ToolScope::Named` entries
// from the global registry, narrowed by the visible-tool
// filter.
@@ -788,45 +622,11 @@ impl OpenHumanSessionHost {
}
}
- // Memory prompt sections — the read side (#566) and the write side
- // (#6048); both gates live in `helpers::add_memory_prompt_sections`.
- prompt_builder = super::helpers::add_memory_prompt_sections(
- prompt_builder,
- &tools,
- &delegation_tools,
- &visible,
- agent_id,
- );
-
// The delegation tools stay beside the durable registry rather than
// inside it: the builder holds them in `OpenHumanSessionHost::synthesized_tools`,
// drops any name a durable tool already owns, and
// `refresh_delegation_tools` replaces the whole set later (#6145).
- // Pre-fetch Critical + High priority tool-scoped memory rules so they
- // pin into the (compression-resistant) system prompt for the whole
- // session. Done here — after the tool list is finalised — so we only
- // fetch rules for tools this agent can actually use. Skipped when
- // `learning.enabled` is false (no new rules are written in that mode,
- // and users who opt out of learning expect no stored rules to surface)
- // or when the runtime cannot host a synchronous bridge (single-threaded
- // test harnesses).
- if config.learning.enabled && config.learning.tool_memory_capture_enabled {
- let agent_tool_names: Vec<String> = tools
- .iter()
- .chain(delegation_tools.iter())
- .map(|t| t.name().to_string())
- .collect();
- let pinned = prefetch_tool_memory_rules_blocking(memory.clone(), &agent_tool_names);
- if !pinned.is_empty() {
- log::info!(
- "[memory::tool_memory] pinning {} tool-scoped rule(s) into system prompt",
- pinned.len()
- );
- prompt_builder = prompt_builder.with_tool_memory_rules(pinned);
- }
- }
-
// Build the P-Format registry AFTER the tool list is finalised
// (including orchestrator tools) so every tool gets a signature
// entry. The registry is self-contained — it doesn't hold a
@@ -860,14 +660,11 @@ impl OpenHumanSessionHost {
.map(|def| def.temperature)
.unwrap_or(config.default_temperature);
- // Thread PROFILE.md + MEMORY.md inclusion from the resolved
- // definition. Legacy / no-definition path stays on the safe
- // `true` default (omit) for both files.
- let effective_omit_profile = target_def.map(|def| def.omit_profile).unwrap_or(true);
- let effective_omit_memory_md = target_def.map(|def| def.omit_memory_md).unwrap_or(true);
- let effective_trigger_memory_agent = target_def
- .map(|def| def.trigger_memory_agent)
- .unwrap_or_default();
+ // Whether a new session gets `context.md` prepended to its first user
+ // message; agents without a definition get it.
+ let effective_omit_memory_context = target_def
+ .map(|def| def.omit_memory_context)
+ .unwrap_or(false);
let effective_tokenjuice_compression = target_def
.map(|def| def.effective_tokenjuice_compression())
.unwrap_or(crate::inference::tokenjuice::AgentTokenjuiceCompression::Full);
@@ -954,50 +751,70 @@ impl OpenHumanSessionHost {
// `agent_harness_e2e` mock now serves SSE for streaming, so the crate-native
// streaming path is exercised end-to-end.
//
- // Issue #4868 / #6958 — resolve the per-agent iteration cap at its one
- // shared resolution point (explicit override, then the definition's
- // `effective_max_iterations()`, then the global default). See
- // `iteration_cap::resolve_max_tool_iterations`.
+ // Issue #4868 — resolve the per-agent iteration cap. When a named
+ // definition is present, its `effective_max_iterations()` (which honors
+ // `iteration_policy = "extended"` -> 50, and the declared `max_iterations`
+ // for strict agents) takes priority over the global
+ // `config.agent.max_tool_iterations` (default 10). This is the single
+ // shared resolution point that closes #4868 for every direct-invocation
+ // path: flows_build, flows_discover, agent-node runtime, cron, MCP
+ // server, etc. Falls back to the global default when there is no
+ // definition for this agent_id.
let mut effective_agent_config = config.agent.clone();
- effective_agent_config.max_tool_iterations =
- super::iteration_cap::resolve_max_tool_iterations(&config.agent, target_def);
- let mut builder =
- super::host_tools::tool_builder(host, agent_id, session_id, tools, visible)?
- .crate_native_provider(provider_role, Arc::clone(&base_config))
- .synthesized_tools(delegation_tools)
- .deferred_tools(target_def.map_or_else(Vec::new, |d| d.deferred_tools.clone()))
- .memory(memory)
- .auto_recall(Some(auto_recall))
- .tool_dispatcher(tool_dispatcher)
- .prompt_builder(prompt_builder)
- .config(effective_agent_config)
- .context_config(config.context.clone())
- .model_name(model_name)
- .model_vision(model_vision)
- .temperature(effective_temperature)
- .workspace_dir(config.workspace_dir.clone())
- .action_dir(config.action_dir.clone())
- .workspace_descriptor(workspace_descriptor)
- .workflows({
- let mut catalogue =
- crate::skills::load_workflow_metadata(&config.workspace_dir);
- #[cfg(feature = "flows")]
- catalogue.extend(crate::flows::catalogue::flow_entries(config));
- catalogue
- })
- .auto_save(config.memory.auto_save)
- .post_turn_hooks(post_turn_hooks)
- .learning_enabled(config.learning.enabled)
- .explicit_preferences_enabled(config.learning.explicit_preferences_enabled)
- .agent_definition_name(agent_id.to_string())
- .omit_profile(effective_omit_profile)
- .omit_memory_md(effective_omit_memory_md)
- .trigger_memory_agent(effective_trigger_memory_agent)
- .tokenjuice_compression(effective_tokenjuice_compression);
+ if let Some(def) = target_def {
+ let def_cap = def.effective_max_iterations();
+ log::info!(
+ "[agent::builder] applying definition iteration cap for agent_id={}: \
+ definition.max_iterations={} iteration_policy={:?} -> effective={} \
+ (was global default {})",
+ agent_id,
+ def.max_iterations,
+ def.iteration_policy,
+ def_cap,
+ config.agent.max_tool_iterations,
+ );
+ effective_agent_config.max_tool_iterations = def_cap;
+ }
+ // Host-first, so a host tool wins a name collision -- see
+ // `HostTurnTools::merge_into`, which owns that rule and why.
+ let (host_policy, withheld_tool_names) =
+ super::host_tools::merge_for_turn(host, agent_id, session_id, &mut tools, &mut visible);
+ let mut builder = OpenHumanSessionHost::builder()
+ .crate_native_provider(provider_role, Arc::clone(&base_config))
+ .tools(tools)
+ .synthesized_tools(delegation_tools)
+ .visible_tool_names(visible)
+ .withheld_tool_names(withheld_tool_names)
+ .deferred_tools(target_def.map_or_else(Vec::new, |d| d.deferred_tools.clone()))
+ .tool_dispatcher(tool_dispatcher)
+ .prompt_builder(prompt_builder)
+ .config(effective_agent_config)
+ .context_config(config.context.clone())
+ .model_name(model_name)
+ .model_vision(model_vision)
+ .temperature(effective_temperature)
+ .workspace_dir(config.workspace_dir.clone())
+ .action_dir(config.action_dir.clone())
+ .workspace_descriptor(workspace_descriptor)
+ .workflows({
+ let mut catalogue = crate::skills::load_workflow_metadata(&config.workspace_dir);
+ #[cfg(feature = "flows")]
+ catalogue.extend(crate::flows::catalogue::flow_entries(config));
+ catalogue
+ })
+ .post_turn_hooks(post_turn_hooks)
+ .agent_definition_name(agent_id.to_string())
+ .omit_memory_context(effective_omit_memory_context)
+ .tokenjuice_compression(effective_tokenjuice_compression);
if let Some(ps) = payload_summarizer {
builder = builder.payload_summarizer(ps);
}
- builder = builder.archivist_hook(archivist_hook_arc);
+ // A host gate REPLACES the session's rather than fronting it --
+ // `tool_policy` assigns. `HostTurnTools::with_policy` says why, and
+ // what it costs a host that gates only its own names.
+ if let Some(policy) = host_policy {
+ builder = builder.tool_policy(policy);
+ }
let mut agent = builder.build()?;
let connected_integrations_initialized = prewarmed_integrations.is_some();
agent.connected_integrations = prewarmed_integrations.unwrap_or_default();
@@ -1012,7 +829,6 @@ impl OpenHumanSessionHost {
config: Arc::clone(&base_config),
definitions,
security_policy: security,
- memory: agent.memory_arc(),
post_turn_hooks: agent.post_turn_hooks.clone(),
// The caller's own definition, when this session was built from
// one rather than from a registry id. `AgentSpec::into_core`
@@ -1021,21 +837,7 @@ impl OpenHumanSessionHost {
// names no registry holds; without handing the definition over
// here the lookup misses and the turn is rejected as a policy
// failure before any provider call (#6404/#6392/#6393).
- session_definition: target_def.cloned().map(|mut definition| {
- if let crate::agent::harness::definition::ToolScope::Named(names) =
- &mut definition.tools
- {
- for name in &agent.permanent_tool_names {
- if !names.contains(name) {
- names.push(name.clone());
- }
- }
- }
- definition
- .deferred_tools
- .retain(|name| !agent.permanent_tool_names.contains(name));
- Arc::new(definition)
- }),
+ session_definition: target_def.cloned().map(Arc::new),
})
});
if agent.hosted_base.is_none() {
@@ -1179,3 +981,20 @@ pub(crate) fn provider_role_for_definition(
.flatten();
provider_role_for(master_hint.as_deref().or(default_model))
}
+
+fn derive_turn_workspace_descriptor() -> Option<tinytools::WorkspaceDescriptor> {
+ let root = crate::agent::turn_workspace::current()?;
+ if !root.is_dir() {
+ tracing::warn!(
+ root = %root.display(),
+ "[turn_workspace] scoped root is not an existing directory — \
+ falling back to the shared action_dir cwd for this turn"
+ );
+ return None;
+ }
+ tracing::debug!(
+ root = %root.display(),
+ "[turn_workspace] turn bound to the embedder's per-turn root as default cwd"
+ );
+ Some(tinytools::WorkspaceDescriptor::new(root).with_policy_id("turn-workspace"))
+}
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 f5790e2885..02f34553bc 100644
--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs
+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs
@@ -5,9 +5,6 @@
//! prefix reconciliation, tool snapshots, resume and persistence remain inside
//! the runtime session.
-mod permanent;
-mod prompt;
-
use std::sync::Arc;
use anyhow::Result;
@@ -50,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.
@@ -60,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>,
@@ -73,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,
@@ -94,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.
@@ -125,7 +113,6 @@ struct OpenHumanTurnToolSurface {
/// as the final allowlist, and classified `Allow` by the policy, so a
/// found tool is callable. See `OpenHumanSessionHost::deferred_tool_names`.
deferred_tool_names: std::collections::HashSet<String>,
- permanent_tool_names: std::collections::HashSet<String>,
/// Whether this belt reaches deferred tools at all; fixed at build.
discovery_enabled: bool,
/// The definition's own `deferred_tools`; see `meta::deferred_set`.
@@ -173,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 {
@@ -250,8 +239,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
@@ -261,105 +249,71 @@ 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()
- }));
+ 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;
}
- 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 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
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let specs = surface
+ .visible_tool_specs
+ .iter()
+ .map(|spec| spec.as_ref().clone())
+ .collect::<Vec<_>>();
+ let instructions = self.tool_dispatcher.prompt_instructions(&specs);
+ let tool_refs = surface
+ .tools
+ .iter()
+ .chain(surface.synthesized_tools.iter())
+ .map(|tool| tool.as_ref())
+ .collect::<Vec<_>>();
+ let mut prompt_tools = PromptTool::from_tool_refs(tool_refs.iter().copied());
+ let mut visible_tool_names = surface.tool_policy_session.visible_tool_names_for_prompt();
+ crate::agent::prompts::swap_deferred_for_discovery_bridge(
+ &mut prompt_tools,
+ &mut visible_tool_names,
+ &surface.deferred_tool_names,
+ );
+ let agents_md = if self.config.agents_md_enabled {
+ crate::agent::prompts::load_agents_md_layers(&self.workspace_dir, &self.action_dir)
+ } else {
+ Default::default()
+ };
+ let mutable = self
+ .mutable
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner);
+ let context = PromptContext {
+ workspace_dir: &self.workspace_dir,
+ model_name: &self.model_name,
+ agent_id: &self.agent_definition_name,
+ tools: &prompt_tools,
+ workflows: &mutable.workflows,
+ dispatcher_instructions: &instructions,
+ 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(),
+ user_identity: crate::security::credentials::identity::peek_credential_user_identity(),
+ personality_roster: vec![],
+ agents_md_global: agents_md.global,
+ agents_md_local: agents_md.local,
+ };
+ self.context
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .build_system_prompt_tiered(&context)
}
#[cfg(test)]
@@ -376,19 +330,19 @@ impl OpenHumanTurnPrelude {
/// semantics, but keeps the mutable authority in hook state rather than a
/// second turn loop. A revoked delegate is removed from the executable
/// source, schema, and policy together before this request is prepared.
- fn refresh_delegation_tool_surface(&self) -> Result<()> {
+ fn refresh_delegation_tool_surface(&self) {
use crate::agent::harness::definition::AgentDefinitionRegistry;
use crate::tools::agent_policy::ToolPolicyEngine;
use crate::tools::orchestrator_tools::collect_orchestrator_tools;
let Some(registry) = AgentDefinitionRegistry::global() else {
- return Ok(());
+ return;
};
let Some(definition) = registry.get(&self.agent_definition_id).cloned() else {
- return Ok(());
+ return;
};
if definition.subagents.is_empty() {
- return Ok(());
+ return;
}
let (integrations, integrations_are_authoritative) = {
let mutable = self
@@ -417,10 +371,6 @@ impl OpenHumanTurnPrelude {
integrations_are_authoritative,
);
collected.extend(rebuilt);
- super::managed_tools::reject_synthesized_collisions(
- &surface.permanent_tool_names,
- &collected,
- )?;
let synthesized =
super::builder::drop_synthesized_name_collisions(&surface.tools, collected);
let synthesized_names = synthesized
@@ -432,13 +382,31 @@ impl OpenHumanTurnPrelude {
synthesized_names.clone(),
);
let auto_include_new_synthesized_tools = surface.auto_include_new_synthesized_tools;
+ let agent_definition_name = surface.agent_definition_name.clone();
reconcile_synthesized_visibility(
&mut surface.visible_tool_names,
&previous_synthesized,
&synthesized_names,
auto_include_new_synthesized_tools,
);
- permanent::refresh_visibility(&mut surface, &synthesized);
+ crate::tools::toolpacks::strip_packed_from_visible(
+ &mut surface.visible_tool_names,
+ &agent_definition_name,
+ );
+ // Same split as the session host's `recompute_deferred_tool_names`:
+ // a `Deferred` synthesised tool leaves the wire and joins the
+ // searchable set, on a belt that opted into discovery.
+ if surface.discovery_enabled {
+ let deferred = crate::tools::implementations::meta::deferred_set(
+ surface.tools.as_slice(),
+ synthesized.as_slice(),
+ &surface.requested_deferred_tools,
+ );
+ surface
+ .visible_tool_names
+ .retain(|name| !deferred.contains(name));
+ surface.deferred_tool_names = deferred;
+ }
let specs = surface
.durable_tool_specs
@@ -492,7 +460,6 @@ impl OpenHumanTurnPrelude {
surface.synthesized_tools = synthesized_tools;
surface.visible_tool_specs = Arc::new(visible);
surface.tool_policy_session = policy;
- Ok(())
}
fn drain_host_events(&self) -> bool {
@@ -545,10 +512,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
@@ -628,36 +594,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),
);
@@ -676,88 +618,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 {
@@ -791,7 +668,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),
@@ -808,51 +684,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
@@ -874,54 +705,41 @@ 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>) {
@@ -965,90 +783,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
@@ -1137,58 +871,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()
}
@@ -1403,9 +1104,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(),
@@ -1414,15 +1112,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,
@@ -1440,7 +1134,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(),
@@ -1449,7 +1142,6 @@ impl OpenHumanSessionHost {
visible_tool_specs: self.visible_tool_specs.clone(),
visible_tool_names: self.visible_tool_names.clone(),
deferred_tool_names: self.deferred_tool_names.clone(),
- permanent_tool_names: self.permanent_tool_names.clone(),
discovery_enabled: self.discovery_enabled,
requested_deferred_tools: self.requested_deferred_tools.clone(),
auto_include_new_synthesized_tools: true,
@@ -1481,7 +1173,7 @@ impl OpenHumanSessionHost {
workflows: self.workflows.clone(),
composio_events: None,
skill_events: None,
- pending_user_autosave: None,
+ pending_user_text: None,
})),
});
}
@@ -1527,12 +1219,8 @@ impl OpenHumanSessionHost {
"OpenHumanTurnPrelude",
)
})?;
- prelude
- .refresh_turn_boundary(!view.resumed && view.history.is_empty())
- .await
- .map_err(|error| {
- tinyagents_runtime::RuntimeError::Driver(error.to_string())
- })?;
+ let new_session = !view.resumed && view.history.is_empty();
+ prelude.refresh_turn_boundary(new_session).await;
let context_window = prelude
.turn_model_source
.effective_context_window(&prelude.model_name)
@@ -1546,12 +1234,7 @@ impl OpenHumanSessionHost {
.unwrap_or_else(std::sync::PoisonError::into_inner)
.context_window = context_window;
let original_user_message = user_text_with_markers(&request.input);
- prelude.begin_user_effects(
- &mut state
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner()),
- request,
- );
+ prelude.begin_user_effects(request);
let overrides = std::mem::take(
&mut state
.lock()
@@ -1563,16 +1246,14 @@ impl OpenHumanSessionHost {
&original_user_message,
&overrides,
&mut options.run_context.data,
+ new_session,
)
.await;
request.input = user_message_from_text(&enriched);
- let mut preparation = prelude
- .prepare(!view.resumed && view.history.is_empty())
- .await
- .map_err(|error| {
+ let mut preparation =
+ prelude.prepare(new_session).await.map_err(|error| {
tinyagents_runtime::RuntimeError::Driver(error.to_string())
})?;
- prelude.refresh_permanent_prefix(&mut preparation, view.prefix);
if overrides.suppress_tools {
// One-off tool-less turn: must not become the
// thread's recorded tool list.
@@ -1673,6 +1354,7 @@ impl OpenHumanSessionHost {
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone();
let usage = holistic_last_turn_usage(&sidecar);
+ let interrupted = sidecar.hit_cap || receipt.outcome.interrupted;
let tool_calls = sidecar
.tool_outcomes
.iter()
@@ -1697,11 +1379,6 @@ impl OpenHumanSessionHost {
.unwrap_or_else(|poisoned| poisoned.into_inner())
.prelude
.clone();
- let citations = state
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner())
- .pending_citations
- .take();
if let Some(prelude) = prelude {
prelude.finalize_after_durable_commit(&receipt).await;
account_committed_turn_against_goal(
@@ -1711,14 +1388,6 @@ impl OpenHumanSessionHost {
)
.await;
}
- // Citations are display-only, but their result belongs
- // to this committed turn. Join only after durability so
- // a failed/cancelled candidate never becomes the UI's
- // "last turn" citation set.
- let citations = match citations {
- Some(task) => task.await.unwrap_or_default(),
- None => Vec::new(),
- };
let _ =
progress::send_receipt_progress(&receipt, &input, &output, iterations)
.await;
@@ -1730,9 +1399,8 @@ impl OpenHumanSessionHost {
let mut state = state
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
- state.last_turn_hit_cap = sidecar.hit_cap;
+ state.last_turn_hit_cap = interrupted;
state.last_turn_usage = Some(usage);
- state.last_turn_citations = citations;
}
crate::agent::hooks::fire_hooks(
&post_turn_hooks,
@@ -1823,7 +1491,6 @@ impl OpenHumanSessionHost {
visible_tool_specs: self.visible_tool_specs.clone(),
visible_tool_names: self.visible_tool_names.clone(),
deferred_tool_names: self.deferred_tool_names.clone(),
- permanent_tool_names: self.permanent_tool_names.clone(),
discovery_enabled: self.discovery_enabled,
requested_deferred_tools: self.requested_deferred_tools.clone(),
auto_include_new_synthesized_tools: auto_include_new_synthesized_tools