The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(embed): let an AgentSpec carry its own in-process tools
sanil-2350782e76e781
diff --git a/crates/openhuman-core/src/agent/mod.rs b/crates/openhuman-core/src/agent/mod.rsindex 11e516b8c3..cad17b2004 100644--- a/crates/openhuman-core/src/agent/mod.rs+++ b/crates/openhuman-core/src/agent/mod.rs@@ -100,4 +100,6 @@ pub use schemas::{mod tests;#[allow(unused_imports)]-pub use session_host::{OpenHumanSessionHost, SessionHostBuilder, TurnOverrides};+pub use session_host::{+ HostTools, HostTurnTools, OpenHumanSessionHost, SessionHostBuilder, TurnOverrides,+};diff --git a/crates/openhuman-core/src/agent/session_host/builder/builder_tests.rs b/crates/openhuman-core/src/agent/session_host/builder/builder_tests.rsindex d8de61606d..d8c1ca1516 100644--- a/crates/openhuman-core/src/agent/session_host/builder/builder_tests.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/builder_tests.rs@@ -46,6 +46,8 @@ fn builtin_def(id: &str) -> crate::agent::harness::definition::AgentDefinition {#[path = "builder_tests_explicit_definition_tests.rs"]mod explicit_definition_tests;+#[path = "builder_tests_host_tools_tests.rs"]+mod host_tools_tests;#[path = "builder_tests_memory_write_instruction_tests.rs"]mod memory_write_instruction_tests;#[path = "builder_tests_session_definition_tests.rs"]diff --git a/crates/openhuman-core/src/agent/session_host/builder/builder_tests_host_tools_tests.rs b/crates/openhuman-core/src/agent/session_host/builder/builder_tests_host_tools_tests.rsnew file mode 100644index 0000000000..4843b79e64--- /dev/null+++ b/crates/openhuman-core/src/agent/session_host/builder/builder_tests_host_tools_tests.rs@@ -0,0 +1,120 @@+//! A host's own `dyn Tool` on a session built from config.+//!+//! The seam exists so an embedder does not have to reach its tools over MCP,+//! which costs the model a discovery call and an `arguments` object no+//! provider can validate. These assert the two halves that make a host tool a+//! real tool: it is on the belt, and it is advertised.++use super::*;+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Arc;++/// A tool that does nothing but be present under a name nothing else uses.+#[derive(Debug)]+struct Marker(&'static str);++#[async_trait::async_trait]+impl tinytools::Tool for Marker {+ fn name(&self) -> &str {+ self.0+ }++ fn description(&self) -> &str {+ "a test marker"+ }++ fn parameters_schema(&self) -> serde_json::Value {+ serde_json::json!({ "type": "object", "properties": {} })+ }++ async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<tinytools::ToolResult> {+ Ok(tinytools::ToolResult::success("ok"))+ }+}++fn definition() -> crate::agent::harness::definition::AgentDefinition {+ crate::agent::harness::AgentDefinitionRegistry::builtins_only()+ .get("tools_agent")+ .cloned()+ .expect("tools_agent built-in definition")+}++/// The whole point: a name the host supplied is callable, and the model is+/// told about it. Advertised-but-absent is a call that fails; present-but-+/// unadvertised is a tool the model never reaches for.+#[test]+fn a_host_tool_is_on_the_belt_and_advertised() {+ let tmp = tempfile::TempDir::new().unwrap();+ let config = test_config(&tmp);+ let host: crate::agent::HostTools = Arc::new(|| {+ crate::agent::HostTurnTools::advertised(vec![Box::new(Marker("oc_marker_tool"))])+ });++ let agent = crate::agent::OpenHumanSessionHost::from_config_with_host_tools(+ &config,+ &definition(),+ &host,+ )+ .expect("build a session with a host belt");++ assert!(+ agent+ .visible_tool_specs_arc()+ .iter()+ .any(|spec| spec.name == "oc_marker_tool"),+ "a host tool must be advertised to the provider by its own name"+ );+}++/// Without this the seam would be a belt, not a factory, and a host whose+/// tools belong to something shorter-lived than the agent -- one episode, one+/// room -- would have to register a second agent to express that. It is also+/// what makes the per-turn rebuild survivable at all: `Box<dyn Tool>` is not+/// `Clone`.+#[test]+fn the_factory_runs_once_per_session_build() {+ let tmp = tempfile::TempDir::new().unwrap();+ let config = test_config(&tmp);+ let calls = Arc::new(AtomicUsize::new(0));+ let host: crate::agent::HostTools = {+ let calls = Arc::clone(&calls);+ Arc::new(move || {+ calls.fetch_add(1, Ordering::SeqCst);+ crate::agent::HostTurnTools::advertised(vec![Box::new(Marker("oc_marker_tool"))])+ })+ };++ for _ in 0..2 {+ crate::agent::OpenHumanSessionHost::from_config_with_host_tools(+ &config,+ &definition(),+ &host,+ )+ .expect("build a session with a host belt");+ }++ assert_eq!(+ calls.load(Ordering::SeqCst),+ 2,+ "the belt is rebuilt per session build, so the factory is asked each time"+ );+}++/// A session built the ordinary way must be byte-identical to before this+/// seam existed -- the factory is opt-in, and a `None` host adds nothing.+#[test]+fn no_host_belt_leaves_the_advertised_set_alone() {+ let tmp = tempfile::TempDir::new().unwrap();+ let config = test_config(&tmp);+ let agent =+ crate::agent::OpenHumanSessionHost::from_config_with_definition(&config, &definition())+ .expect("build a plain session");++ assert!(+ !agent+ .visible_tool_specs_arc()+ .iter()+ .any(|spec| spec.name == "oc_marker_tool"),+ "nothing should advertise a host tool that was never supplied"+ );+}diff --git a/crates/openhuman-core/src/agent/session_host/builder/builder_tests_memory_write_instruction_tests.rs b/crates/openhuman-core/src/agent/session_host/builder/builder_tests_memory_write_instruction_tests.rsindex aa245f3dbf..837acb6b1b 100644--- a/crates/openhuman-core/src/agent/session_host/builder/builder_tests_memory_write_instruction_tests.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/builder_tests_memory_write_instruction_tests.rs@@ -24,6 +24,7 @@ async fn memory_write_instruction_is_present_with_learning_disabled() {"orchestrator",Some(&orchestrator),false,+ None,).expect("build session");@@ -49,6 +50,7 @@ async fn memory_write_instruction_names_only_the_write_tool_a_scoped_agent_holds"archivist",Some(&archivist),false,+ None,).expect("build archivist session");diff --git a/crates/openhuman-core/src/agent/session_host/builder/factory.rs b/crates/openhuman-core/src/agent/session_host/builder/factory.rsindex f369282f5f..5e4c5bd3bd 100644--- a/crates/openhuman-core/src/agent/session_host/builder/factory.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/factory.rs@@ -113,7 +113,7 @@ impl OpenHumanSessionHost {.unwrap_or(config.default_temperature));- Self::build_session_agent_inner(config, agent_id, target_def.as_ref(), false)+ Self::build_session_agent_inner(config, agent_id, target_def.as_ref(), false, None)}/// Build a session agent from a definition the caller already holds,@@ -135,7 +135,33 @@ impl OpenHumanSessionHost {definition.id,definition.sandbox_mode,);- Self::build_session_agent_inner(config, &definition.id, Some(definition), false)+ Self::build_session_agent_inner(config, &definition.id, Some(definition), false, None)+ }++ /// [`Self::from_config_with_definition`], plus a belt the host supplies+ /// itself.+ ///+ /// The seam an embedder needs to put its **own** `dyn Tool` on an agent it+ /// configures through data. Everything else on this path is reconstructed+ /// from `Config` and the definition on every turn, so a host that owned a+ /// tool object had nowhere to put it and reached its tools over MCP+ /// instead — paying a discovery turn, an opaque `arguments` object the+ /// provider cannot validate, and a prompt section explaining the envelope.+ ///+ /// `host` is a factory rather than a belt because this constructor runs+ /// once per turn and `Box<dyn Tool>` is not `Clone`. A host may therefore+ /// return a different belt each time; see [`HostTurnTools`] for what that+ /// does and does not keep consistent with the prompt.+ ///+ /// # Errors+ ///+ /// As [`Self::from_config_with_definition`].+ pub fn from_config_with_host_tools(+ config: &Config,+ definition: &crate::agent::harness::definition::AgentDefinition,+ host: &super::HostTools,+ ) -> Result<Self> {+ Self::build_session_agent_inner(config, &definition.id, Some(definition), false, Some(host))}/// Internal constructor that consumes the optionally-resolved agent@@ -153,6 +179,7 @@ impl OpenHumanSessionHost {agent_id: &str,target_def: Option<&crate::agent::harness::definition::AgentDefinition>,read_only_tools_only: bool,+ host: Option<&super::HostTools>,) -> Result<Self> {let workspace_descriptor = derive_turn_workspace_descriptor();@@ -994,6 +1021,28 @@ impl OpenHumanSessionHost {);effective_agent_config.max_tool_iterations = def_cap;}+ // The host's own belt, last, so a host tool wins a name collision with+ // a config-derived one: the host asked for this object specifically,+ // and `dedup_visible_tool_specs` keeps the first occurrence, so the+ // advertised spec must be the one that will actually run.+ let host_policy = match host.map(|build| build()) {+ Some(host_tools) if !host_tools.is_empty() => {+ log::debug!(+ "[agent::builder] host supplied {} tool(s) for agent_id={agent_id}: {:?}",+ host_tools.tools.len(),+ host_tools+ .tools+ .iter()+ .map(|tool| tool.name())+ .collect::<Vec<_>>(),+ );+ let mut host_tools = host_tools;+ tools.append(&mut host_tools.tools);+ visible.extend(host_tools.visible);+ host_tools.policy+ }+ _ => None,+ };let mut builder = OpenHumanSessionHost::builder().crate_native_provider(provider_role, Arc::clone(&base_config)).tools(tools)@@ -1029,6 +1078,13 @@ impl OpenHumanSessionHost {if let Some(ps) = payload_summarizer {builder = builder.payload_summarizer(ps);}+ // The host's gate, when it sent one. Ahead of the session's own by+ // construction: a host that supplies both a belt and a gate is saying+ // what may run on that belt, and a config-derived policy knows nothing+ // about tools it did not produce.+ if let Some(policy) = host_policy {+ builder = builder.tool_policy(policy);+ }builder = builder.archivist_hook(archivist_hook_arc);let mut agent = builder.build()?;let connected_integrations_initialized = prewarmed_integrations.is_some();diff --git a/crates/openhuman-core/src/agent/session_host/builder/host_tools.rs b/crates/openhuman-core/src/agent/session_host/builder/host_tools.rsnew file mode 100644index 0000000000..05c96f77a2--- /dev/null+++ b/crates/openhuman-core/src/agent/session_host/builder/host_tools.rs@@ -0,0 +1,95 @@+//! Host-supplied tools a session is built with, beside the ones config names.+//!+//! A session host built through [`OpenHumanSessionHost::builder`] takes a tool+//! belt directly — an embedder hands it `Box<dyn Tool>` objects and they are+//! the belt. A session built *from config*+//! ([`from_config_with_definition`](super::super::OpenHumanSessionHost::from_config_with_definition))+//! cannot: it is reconstructed on every turn from `Config` and an+//! `AgentDefinition`, both of which are data, so nothing carrying a `dyn Tool`+//! survives between turns. That is why an `openhuman_embed::Agent` has only+//! ever reached a host's own tools over MCP.+//!+//! [`HostTools`] is the seam that closes it, and it is a **factory rather than+//! a belt** for exactly the reason above: `Box<dyn Tool>` is not `Clone` and+//! `Agent` is, so a stored belt could not survive the per-turn rebuild. The+//! closure is invoked once per turn, which also means the belt it returns may+//! differ from turn to turn — a host whose tools are bound to something+//! shorter-lived than the agent (one episode, one room, one assignment) can+//! express that here instead of registering a second agent for it.+//!+//! The prompt's tool catalogue is rendered from the same belt in the same+//! build, so a changing belt and its description stay consistent **on a turn+//! that composes its prompt**. A resumed session reuses its persisted system+//! messages, so a belt that moves under one is described by the prompt it had+//! when the thread opened; a host that varies its belt should run such turns+//! on a session of their own.++use std::collections::HashSet;+use std::sync::Arc;++use tinytools::Tool;++use crate::agent::tool_policy::ToolPolicy;++/// One turn's worth of host-supplied belt.+///+/// `visible` is the provider-visible allow-list to union into the session's+/// own; leaving it empty makes the tools reachable but unadvertised, which is+/// rarely what a host wants. `policy` is consulted for these tools before the+/// session's own gate.+#[derive(Default)]+pub struct HostTurnTools {+ /// The tools themselves, appended to the belt config produced.+ pub tools: Vec<Box<dyn Tool>>,+ /// Names to add to the provider-visible allow-list.+ pub visible: HashSet<String>,+ /// An admission gate consulted ahead of the session's own, if any.+ pub policy: Option<Arc<dyn ToolPolicy>>,+}++impl HostTurnTools {+ /// A belt with every tool advertised, which is the common case.+ #[must_use]+ pub fn advertised(tools: Vec<Box<dyn Tool>>) -> Self {+ let visible = tools.iter().map(|tool| tool.name().to_string()).collect();+ Self {+ tools,+ visible,+ policy: None,+ }+ }++ /// Sets the admission gate consulted ahead of the session's own.+ #[must_use]+ pub fn with_policy(mut self, policy: Arc<dyn ToolPolicy>) -> Self {+ self.policy = Some(policy);+ self+ }++ /// Whether this contributes nothing, so a caller can skip the union.+ #[must_use]+ pub fn is_empty(&self) -> bool {+ self.tools.is_empty() && self.visible.is_empty() && self.policy.is_none()+ }+}++impl std::fmt::Debug for HostTurnTools {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("HostTurnTools")+ .field(+ "tools",+ &self+ .tools+ .iter()+ .map(|tool| tool.name())+ .collect::<Vec<_>>(),+ )+ .field("visible", &self.visible)+ .field("policy", &self.policy.is_some())+ .finish()+ }+}++/// Builds one turn's host belt. Invoked once per session build, so a host may+/// return a different belt each time.+pub type HostTools = Arc<dyn Fn() -> HostTurnTools + Send + Sync>;diff --git a/crates/openhuman-core/src/agent/session_host/builder/mod.rs b/crates/openhuman-core/src/agent/session_host/builder/mod.rsindex 1c9e5d3c15..8c424d11b7 100644--- a/crates/openhuman-core/src/agent/session_host/builder/mod.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/mod.rs@@ -12,8 +12,11 @@ mod builder_build;mod dispatcher;mod factory;mod helpers;+mod host_tools;mod setters;+pub use host_tools::{HostTools, HostTurnTools};+#[cfg(test)]mod builder_tests;diff --git a/crates/openhuman-core/src/agent/session_host/mod.rs b/crates/openhuman-core/src/agent/session_host/mod.rsindex e4ef0d56fa..5bbc774696 100644--- a/crates/openhuman-core/src/agent/session_host/mod.rs+++ b/crates/openhuman-core/src/agent/session_host/mod.rs@@ -31,6 +31,7 @@//! The child files are an implementation detail.pub(crate) use builder::provider_role_for_definition;+pub use builder::{HostTools, HostTurnTools};mod builder;mod codec;diff --git a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rsindex c8f97ea792..4e257d51e9 100644--- a/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs+++ b/crates/openhuman-core/src/inference/host_runtime/ops/agent_chat.rs@@ -72,7 +72,7 @@ pub async fn agent_chat(}/// Which session [`agent_chat_for`] builds the turn on.-#[derive(Debug, Clone, Copy)]+#[derive(Clone, Copy)]pub enum AgentChatTarget<'a> {/// The orchestrator — [`OpenHumanSessionHost::from_config`], today's `agent_chat`.Orchestrator,@@ -82,11 +82,34 @@ pub enum AgentChatTarget<'a> {/// A definition the caller already holds; nothing is resolved by id. The/// entry point for a library host running its own per-agent specs — see/// [`OpenHumanSessionHost::from_config_with_definition`].+ ///+ /// `host` carries the caller's own `dyn Tool` objects. It rides the target+ /// rather than `agent_chat_for`'s argument list because only this target+ /// can honour it: the other two resolve a definition the caller does not+ /// hold, so there is no agent for a host belt to belong to.Definition {definition: &'a crate::agent::harness::definition::AgentDefinition,+ host: Option<&'a crate::agent::HostTools>,},}+// Hand-written because a host belt is a closure, and a closure is not `Debug`.+// Reporting whether one is present is what a log line here is ever for; the+// belt it would return is not known until the turn builds it.+impl std::fmt::Debug for AgentChatTarget<'_> {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Self::Orchestrator => f.write_str("Orchestrator"),+ Self::AgentId(id) => f.debug_tuple("AgentId").field(id).finish(),+ Self::Definition { definition, host } => f+ .debug_struct("Definition")+ .field("definition", &definition.id)+ .field("host_tools", &host.is_some())+ .finish(),+ }+ }+}+fn build_turn_agent(config: &Config,target: &AgentChatTarget<'_>,@@ -97,9 +120,12 @@ fn build_turn_agent(log::debug!("[inference] agent_chat building agent_id={id}");OpenHumanSessionHost::from_config_for_agent(config, id)}- AgentChatTarget::Definition { definition } => {- OpenHumanSessionHost::from_config_with_definition(config, definition)- }+ AgentChatTarget::Definition { definition, host } => match host {+ Some(host) => {+ OpenHumanSessionHost::from_config_with_host_tools(config, definition, host)+ }+ None => OpenHumanSessionHost::from_config_with_definition(config, definition),+ },}.map_err(|e| e.to_string())}diff --git a/crates/openhuman-embed/src/agent/build.rs b/crates/openhuman-embed/src/agent/build.rsindex 1174a010e3..1d57aa8868 100644--- a/crates/openhuman-embed/src/agent/build.rs+++ b/crates/openhuman-embed/src/agent/build.rs@@ -154,6 +154,7 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInnprovider,access,layout,+ host_tools: parts.host_tools,})}diff --git a/crates/openhuman-embed/src/agent/mod.rs b/crates/openhuman-embed/src/agent/mod.rsindex 3ee8ca4162..04e87fd63a 100644--- a/crates/openhuman-embed/src/agent/mod.rs+++ b/crates/openhuman-embed/src/agent/mod.rs@@ -90,6 +90,9 @@ pub(crate) struct AgentInner {pub(crate) provider: Provider,pub(crate) access: Access,pub(crate) layout: AgentLayout,+ /// The agent's own in-process tools, rebuilt per turn. See+ /// [`AgentSpec::tools`](super::AgentSpec::tools) for why it is a factory.+ pub(crate) host_tools: Option<openhuman_core::agent::HostTools>,}/// A handle to one agent on a runtime.diff --git a/crates/openhuman-embed/src/agent/spec.rs b/crates/openhuman-embed/src/agent/spec.rsindex ef6a2787b4..355a261989 100644--- a/crates/openhuman-embed/src/agent/spec.rs+++ b/crates/openhuman-embed/src/agent/spec.rs@@ -48,6 +48,7 @@ pub struct AgentSpec {action_dir: Option<PathBuf>,trusted: Vec<(String, TrustedAccess)>,config_fn: Option<ConfigEdit>,+ host_tools: Option<openhuman_core::agent::HostTools>,}impl AgentSpec {@@ -76,6 +77,7 @@ impl AgentSpec {action_dir: None,trusted: Vec::new(),config_fn: None,+ host_tools: None,}}@@ -196,6 +198,50 @@ impl AgentSpec {self}+ /// The agent's own in-process tools, built fresh for every turn.+ ///+ /// Until this existed, an embedder's tools could only reach an agent over+ /// [`mcp`](Self::mcp): a spec is data, and the session behind it is rebuilt+ /// from that data on every turn, so a `Box<dyn Tool>` had nowhere to live+ /// in between. The cost was paid by the model — a discovery call to learn+ /// what the server offers, an `mcp_call_tool` envelope whose inner+ /// `arguments` object no provider can validate or constrain decoding+ /// against, and a prompt section explaining the indirection.+ ///+ /// A tool named here is a real tool: its own schema on the wire, called by+ /// its own name.+ ///+ /// # A factory, not a belt+ ///+ /// `f` runs once per turn. That is forced — [`Agent`](super::Agent) is+ /// `Clone` and `Box<dyn Tool>` is not, so a stored belt could not survive+ /// the rebuild — but it is also useful: a host whose tools are bound to+ /// something shorter-lived than the agent (one episode, one room, one+ /// assignment) can return a different belt each turn rather than+ /// registering a second agent for it.+ ///+ /// The prompt's tool catalogue is rendered from the same belt in the same+ /// build, so a belt that changes stays consistent with its description on+ /// any turn that composes a prompt. A **resumed** session reuses its+ /// persisted system messages, so a belt that moves under a long-lived+ /// thread will be described by the prompt that thread opened with. Vary a+ /// belt only on turns that run on a session of their own.+ ///+ /// ```no_run+ /// # use openhuman_embed::AgentSpec;+ /// # use openhuman_core::agent::HostTurnTools;+ /// # fn belt() -> Vec<Box<dyn tinytools::Tool>> { Vec::new() }+ /// let spec = AgentSpec::new("reviewer").tools(|| HostTurnTools::advertised(belt()));+ /// ```+ #[must_use]+ pub fn tools(+ mut self,+ f: impl Fn() -> openhuman_core::agent::HostTurnTools + Send + Sync + 'static,+ ) -> Self {+ self.host_tools = Some(std::sync::Arc::new(f));+ self+ }+// ── accessors for the build step ─────────────────────────────────────pub(crate) fn into_parts(self) -> AgentSpecParts {@@ -216,6 +262,7 @@ impl AgentSpec {action_dir: self.action_dir,trusted: self.trusted,config_fn: self.config_fn,+ host_tools: self.host_tools,}}}@@ -238,6 +285,7 @@ pub(crate) struct AgentSpecParts {pub(crate) action_dir: Option<PathBuf>,pub(crate) trusted: Vec<(String, TrustedAccess)>,pub(crate) config_fn: Option<ConfigEdit>,+ pub(crate) host_tools: Option<openhuman_core::agent::HostTools>,}impl std::fmt::Debug for AgentSpec {diff --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rsindex adb1ed7466..880a825e52 100644--- a/crates/openhuman-embed/src/turn.rs+++ b/crates/openhuman-embed/src/turn.rs@@ -439,6 +439,7 @@ async fn dispatch(target: TurnTarget, request: TurnRequest) -> Result<String, Co);let target = AgentChatTarget::Definition {definition: &inner.definition,+ host: inner.host_tools.as_ref(),};agent_chat_for(&mut config,