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): attach permanent tools to existing agents
Steven Enamakel3a6fde635e06
diff --git a/crates/openhuman-core/src/agent/session_host/builder/builder_build.rs b/crates/openhuman-core/src/agent/session_host/builder/builder_build.rsindex 19694f5613..4adffbdf7a 100644--- a/crates/openhuman-core/src/agent/session_host/builder/builder_build.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/builder_build.rs@@ -46,10 +46,12 @@ impl SessionHostBuilder {}// The synthesised set lives beside the durable registry, never inside// it (`OpenHumanSessionHost::synthesized_tools`); a durable name wins a collision.- let synthesized_tools = super::drop_synthesized_name_collisions(- &tools,- self.synthesized_tools.unwrap_or_default(),- );+ let synthesized_tools = self.synthesized_tools.unwrap_or_default();+ super::super::managed_tools::reject_synthesized_collisions(+ &self.permanent_tool_names,+ &synthesized_tools,+ )?;+ let synthesized_tools = super::drop_synthesized_name_collisions(&tools, synthesized_tools);let synthesized_tool_names: std::collections::HashSet<String> = synthesized_tools.iter().map(|tool| tool.name().to_string())@@ -188,6 +190,8 @@ impl SessionHostBuilder {.insert(crate::agent::harness::definition::NO_TOOLS_SENTINEL.to_string());}}+ visible_names.extend(self.permanent_tool_names.iter().cloned());+ deferred_names.retain(|name| !self.permanent_tool_names.contains(name));// What the policy classifies and the harness registers: the advertised// set plus the deferred set. A deferred tool outside this union would// be `HideFromPrompt`, and the direct-call gate refuses those.@@ -402,6 +406,7 @@ impl SessionHostBuilder {visible_tool_specs: Arc::new(visible_tool_specs),visible_tool_names: visible_names,deferred_tool_names: deferred_names,+ permanent_tool_names: self.permanent_tool_names,discovery_enabled,requested_deferred_tools: Arc::from(self.deferred_tools.clone()),subagent_tool_ceiling_names,diff --git a/crates/openhuman-core/src/agent/session_host/builder/factory.rs b/crates/openhuman-core/src/agent/session_host/builder/factory.rsindex a27ab436ed..1dbb545051 100644--- a/crates/openhuman-core/src/agent/session_host/builder/factory.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/factory.rs@@ -980,14 +980,21 @@ impl OpenHumanSessionHost {}// 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 (host_policy, withheld_tool_names, permanent_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)+ .permanent_tool_names(permanent_tool_names).deferred_tools(target_def.map_or_else(Vec::new, |d| d.deferred_tools.clone())).memory(memory).auto_recall(Some(auto_recall))@@ -1049,7 +1056,21 @@ 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(Arc::new),+ 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)+ }),})});if agent.hosted_base.is_none() {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.rsindex f1aa04415f..3ec8036156 100644--- a/crates/openhuman-core/src/agent/session_host/builder/host_tools.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/host_tools.rs@@ -22,7 +22,9 @@//! 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.+//! on a session of their own. Permanent attachments are the exception: their+//! catalogue occupies a managed system section refreshed independently of+//! the frozen host prompt.use std::collections::HashSet;use std::sync::Arc;@@ -46,6 +48,8 @@ pub struct HostTurnTools {/// The tools themselves, placed **ahead of** the config-derived belt so a/// host tool wins a collision on its name.pub tools: Vec<Box<dyn Tool>>,+ /// Tool names permanently advertised directly and rendered in a managed prompt section.+ pub permanent: HashSet<String>,/// Names to add to the provider-visible allow-list.pub visible: HashSet<String>,/// Names to remove from the provider-visible allow-list for this turn.@@ -67,6 +71,7 @@ impl HostTurnTools {let visible = tools.iter().map(|tool| tool.name().to_string()).collect();Self {tools,+ permanent: HashSet::new(),visible,withheld: HashSet::new(),policy: None,@@ -98,12 +103,13 @@ impl HostTurnTools {agent_id: &str,tools: &mut Vec<Box<dyn Tool>>,visible: &mut HashSet<String>,- ) -> MergedHostTurnTools {+ ) -> Result<MergedHostTurnTools> {if self.is_empty() {- return MergedHostTurnTools {+ return Ok(MergedHostTurnTools {policy: None,withheld: HashSet::new(),- };+ permanent: HashSet::new(),+ });}log::debug!("[agent::builder] host supplied {} tool(s) for agent_id={agent_id}: {:?}",@@ -113,12 +119,33 @@ impl HostTurnTools {.map(|tool| tool.name()).collect::<Vec<_>>(),);- tools.splice(0..0, self.tools);+ for name in &self.permanent {+ anyhow::ensure!(+ !tools.iter().any(|tool| tool.name() == name),+ "permanent tool name collision: {name}"+ );+ anyhow::ensure!(+ self.tools.iter().filter(|tool| tool.name() == name).count() == 1,+ "duplicate permanent tool name: {name}"+ );+ }+ let permanent = &self.permanent;+ tools.splice(+ 0..0,+ self.tools.into_iter().map(|tool| {+ if permanent.contains(tool.name()) {+ Box::new(super::permanent_tool::PermanentTool(tool)) as Box<dyn Tool>+ } else {+ tool+ }+ }),+ );visible.extend(self.visible);- MergedHostTurnTools {+ Ok(MergedHostTurnTools {policy: self.policy,withheld: self.withheld,- }+ permanent: self.permanent,+ })}/// Sets the gate for the whole session.@@ -156,6 +183,7 @@ impl HostTurnTools {pub(super) struct MergedHostTurnTools {pub policy: Option<Arc<dyn ToolPolicy>>,pub withheld: HashSet<String>,+ pub permanent: HashSet<String>,}pub(super) fn merge_for_turn(@@ -164,13 +192,20 @@ pub(super) fn merge_for_turn(session_id: Option<&str>,tools: &mut Vec<Box<dyn Tool>>,visible: &mut HashSet<String>,-) -> (Option<Arc<dyn ToolPolicy>>, HashSet<String>) {+) -> Result<(+ Option<Arc<dyn ToolPolicy>>,+ HashSet<String>,+ HashSet<String>,+)> {match host.map(|build| build(TurnContext::new(agent_id, session_id))).map(|host_tools| host_tools.merge_into(agent_id, tools, visible)){- Some(merged) => (merged.policy, merged.withheld),- None => (None, HashSet::new()),+ Some(merged) => {+ let merged = merged?;+ Ok((merged.policy, merged.withheld, merged.permanent))+ }+ None => Ok((None, HashSet::new(), HashSet::new())),}}diff --git a/crates/openhuman-core/src/agent/session_host/builder/mod.rs b/crates/openhuman-core/src/agent/session_host/builder/mod.rsindex 9126ab8ac2..905cf04e92 100644--- a/crates/openhuman-core/src/agent/session_host/builder/mod.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/mod.rs@@ -13,6 +13,7 @@ mod dispatcher;mod factory;mod helpers;mod host_tools;+mod permanent_tool;mod setters;pub use host_tools::{HostTools, HostTurnTools, TurnContext};diff --git a/crates/openhuman-core/src/agent/session_host/builder/permanent_tool.rs b/crates/openhuman-core/src/agent/session_host/builder/permanent_tool.rsnew file mode 100644index 0000000000..b92cf2c361--- /dev/null+++ b/crates/openhuman-core/src/agent/session_host/builder/permanent_tool.rs@@ -0,0 +1,98 @@+//! Preserve a host tool's execution metadata while fixing its direct exposure.+use serde_json::Value;+use std::any::Any;+use tinytools::{+ PermissionLevel, Tool, ToolCallOptions, ToolCategory, ToolExposure, ToolInjectedArgument,+ ToolPolicy, ToolResult, ToolRunContext, ToolScope, ToolSpec, ToolTimeout,+};+pub(super) struct PermanentTool(pub Box<dyn Tool>);+#[async_trait::async_trait]+impl Tool for PermanentTool {+ fn name(&self) -> &str {+ self.0.name()+ }+ fn description(&self) -> &str {+ self.0.description()+ }+ fn parameters_schema(&self) -> Value {+ self.0.parameters_schema()+ }+ fn exposure(&self) -> ToolExposure {+ ToolExposure::Direct+ }+ async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {+ self.0.execute(args).await+ }+ async fn execute_with_options(+ &self,+ args: Value,+ options: ToolCallOptions,+ ) -> anyhow::Result<ToolResult> {+ self.0.execute_with_options(args, options).await+ }+ async fn execute_with_context(+ &self,+ args: Value,+ options: ToolCallOptions,+ context: Option<&dyn ToolRunContext>,+ ) -> anyhow::Result<ToolResult> {+ self.0.execute_with_context(args, options, context).await+ }+ fn policy(&self) -> ToolPolicy {+ self.0.policy()+ }+ fn injected_arguments(&self) -> Vec<ToolInjectedArgument> {+ self.0.injected_arguments()+ }+ fn supports_markdown(&self) -> bool {+ self.0.supports_markdown()+ }+ fn permission_level(&self) -> PermissionLevel {+ self.0.permission_level()+ }+ fn permission_level_with_args(&self, args: &Value) -> PermissionLevel {+ self.0.permission_level_with_args(args)+ }+ fn scope(&self) -> ToolScope {+ self.0.scope()+ }+ fn category(&self) -> ToolCategory {+ self.0.category()+ }+ fn family(&self) -> Option<&str> {+ self.0.family()+ }+ fn is_concurrency_safe(&self, args: &Value) -> bool {+ self.0.is_concurrency_safe(args)+ }+ fn external_effect(&self) -> bool {+ self.0.external_effect()+ }+ fn external_effect_with_args(&self, args: &Value) -> bool {+ self.0.external_effect_with_args(args)+ }+ fn max_result_size_chars(&self) -> Option<usize> {+ self.0.max_result_size_chars()+ }+ fn timeout_policy(&self, args: &Value) -> ToolTimeout {+ self.0.timeout_policy(args)+ }+ fn host_extension(&self) -> Option<&(dyn Any + Send + Sync)> {+ self.0.host_extension()+ }+ fn host_call_extension(&self, args: &Value) -> Option<Box<dyn Any + Send + Sync>> {+ self.0.host_call_extension(args)+ }+ fn spec(&self) -> ToolSpec {+ self.0.spec()+ }+ fn display_label(&self, args: &Value) -> Option<String> {+ self.0.display_label(args)+ }+ fn display_detail(&self, args: &Value) -> Option<String> {+ self.0.display_detail(args)+ }+ fn return_direct(&self) -> bool {+ self.0.return_direct()+ }+}diff --git a/crates/openhuman-core/src/agent/session_host/builder/setters.rs b/crates/openhuman-core/src/agent/session_host/builder/setters.rsindex 819a584d98..0fafd8479f 100644--- a/crates/openhuman-core/src/agent/session_host/builder/setters.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/setters.rs@@ -17,6 +17,7 @@ impl SessionHostBuilder {synthesized_tools: None,visible_tool_names: None,withheld_tool_names: std::collections::HashSet::new(),+ permanent_tool_names: std::collections::HashSet::new(),deferred_tools: Vec::new(),subagent_tool_ceiling_names: None,memory: None,@@ -100,6 +101,12 @@ impl SessionHostBuilder {self}+ /// Pin these tools directly in the prompt and provider schema.+ pub fn permanent_tool_names(mut self, names: std::collections::HashSet<String>) -> Self {+ self.permanent_tool_names = names;+ self+ }+/// Removes these names from the final provider-visible tool set after the/// agent's static scope and synthesized tools have been expanded.pub fn withheld_tool_names(mut self, names: std::collections::HashSet<String>) -> Self {diff --git a/crates/openhuman-core/src/agent/session_host/managed_tools.rs b/crates/openhuman-core/src/agent/session_host/managed_tools.rsnew file mode 100644index 0000000000..93f626204b--- /dev/null+++ b/crates/openhuman-core/src/agent/session_host/managed_tools.rs@@ -0,0 +1,60 @@+//! Refresh only the attached-tool catalogue; keep the host prefix frozen.+use std::{collections::HashSet, sync::Arc};+use tinyagents_runtime::PrefixSnapshot;+use tinyinference_llm::message::Message;+use tinytools::ToolSpec;+const MARKER: &str = "<openhuman-permanent-tools>\n";+pub(super) fn refresh_prefix(+ prefix: &PrefixSnapshot,+ specs: &[Arc<ToolSpec>],+ names: &HashSet<String>,+) -> Option<PrefixSnapshot> {+ if names.is_empty() {+ return None;+ }+ let mut messages: Vec<Message> = prefix+ .messages()+ .iter()+ .filter(|message| !message.text().starts_with(MARKER))+ .cloned()+ .collect();+ let mut entries: Vec<&ToolSpec> = specs+ .iter()+ .filter(|spec| names.contains(&spec.name))+ .map(AsRef::as_ref)+ .collect();+ entries.sort_by(|a, b| a.name.cmp(&b.name));+ let catalogue = entries+ .iter()+ .map(|spec| {+ format!(+ "{}: {}\nParameters: {}",+ spec.name, spec.description, spec.parameters+ )+ })+ .collect::<Vec<_>>()+ .join("\n\n");+ messages.push(Message::system(format!(+ "{MARKER}{catalogue}\n</openhuman-permanent-tools>"+ )));+ if messages == prefix.messages() {+ None+ } else {+ Some(PrefixSnapshot::new(messages).refreshing())+ }+}++/// Check before deduplication, preserving the existing synthesized executors+/// and schemas if a new permanent source would shadow them.+pub(super) fn reject_synthesized_collisions(+ names: &HashSet<String>,+ synthesized: &[Box<dyn tinytools::Tool>],+) -> anyhow::Result<()> {+ if let Some(tool) = synthesized.iter().find(|tool| names.contains(tool.name())) {+ anyhow::bail!(+ "permanent tool name collision with synthesized tool: {}",+ tool.name()+ );+ }+ Ok(())+}diff --git a/crates/openhuman-core/src/agent/session_host/mod.rs b/crates/openhuman-core/src/agent/session_host/mod.rsindex 4075ce0396..465057663d 100644--- a/crates/openhuman-core/src/agent/session_host/mod.rs+++ b/crates/openhuman-core/src/agent/session_host/mod.rs@@ -38,6 +38,7 @@ mod codec;mod driver;mod factory;mod hooks;+mod managed_tools;mod policy;mod prefix_snapshot;mod recorded_tools;diff --git a/crates/openhuman-core/src/agent/session_host/prelude_integrations.rs b/crates/openhuman-core/src/agent/session_host/prelude_integrations.rsindex a45bee8ec1..0d5de02e76 100644--- a/crates/openhuman-core/src/agent/session_host/prelude_integrations.rs+++ b/crates/openhuman-core/src/agent/session_host/prelude_integrations.rs@@ -104,7 +104,7 @@ impl OpenHumanTurnPrelude {rebuilt}- pub(super) async fn refresh_turn_boundary(&self, cold: bool) {+ pub(super) async fn refresh_turn_boundary(&self, cold: bool) -> anyhow::Result<()> {// Hydrate on the first turn of *this session instance*, not only on a// brand-new thread. A resumed thread is never `cold`, and a session// rebuilt after a restart is seeded from an empty cache — gating the fetch on@@ -120,7 +120,8 @@ impl OpenHumanTurnPrelude {// Integration changes are authority changes, not only display// announcements. Refresh the delegation executable set and rebuild// its schema/policy in the same hook pass before the driver sees it.- self.refresh_delegation_tool_surface();+ self.refresh_delegation_tool_surface()?;+ Ok(())}/// Snapshot the installed servers' tools for this workspace, from thediff --git a/crates/openhuman-core/src/agent/session_host/runtime/accessors.rs b/crates/openhuman-core/src/agent/session_host/runtime/accessors.rsindex 75510f46eb..4d0b413a90 100644--- a/crates/openhuman-core/src/agent/session_host/runtime/accessors.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime/accessors.rs@@ -430,15 +430,18 @@ impl OpenHumanSessionHost {/// wherever either set changes; a no-op for a belt that never opted into/// discovery.pub(in crate::agent::session_host) fn recompute_deferred_tool_names(&mut self) {+ self.visible_tool_names+ .extend(self.permanent_tool_names.iter().cloned());if !self.discovery_enabled {self.deferred_tool_names.clear();return;}- let deferred = crate::tools::implementations::meta::deferred_set(+ let mut deferred = crate::tools::implementations::meta::deferred_set(self.tools.as_slice(),self.synthesized_tools.as_slice(),&self.requested_deferred_tools,);+ deferred.retain(|name| !self.permanent_tool_names.contains(name));self.visible_tool_names.retain(|name| !deferred.contains(name));self.deferred_tool_names = deferred;diff --git a/crates/openhuman-core/src/agent/session_host/runtime_session.rs b/crates/openhuman-core/src/agent/session_host/runtime_session.rsindex 06430cb62e..b10eed8287 100644--- a/crates/openhuman-core/src/agent/session_host/runtime_session.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session.rs@@ -122,6 +122,7 @@ 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`.@@ -366,7 +367,12 @@ impl OpenHumanTurnPrelude {.iter().map(|spec| spec.as_ref().clone()).collect::<Vec<_>>();- let instructions = self.tool_dispatcher.prompt_instructions(&specs);+ let prompt_specs = specs+ .iter()+ .filter(|spec| !surface.permanent_tool_names.contains(&spec.name))+ .cloned()+ .collect::<Vec<_>>();+ let instructions = self.tool_dispatcher.prompt_instructions(&prompt_specs);let tool_refs = surface.tools.iter()@@ -374,7 +380,9 @@ impl OpenHumanTurnPrelude {.map(|tool| tool.as_ref()).collect::<Vec<_>>();let mut prompt_tools = PromptTool::from_tool_refs(tool_refs.iter().copied());+ prompt_tools.retain(|tool| !surface.permanent_tool_names.contains(tool.name.as_ref()));let mut visible_tool_names = surface.tool_policy_session.visible_tool_names_for_prompt();+ visible_tool_names.retain(|name| !surface.permanent_tool_names.contains(name));crate::agent::prompts::swap_deferred_for_discovery_bridge(&mut prompt_tools,&mut visible_tool_names,@@ -431,19 +439,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) {+ fn refresh_delegation_tool_surface(&self) -> Result<()> {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;+ return Ok(());};let Some(definition) = registry.get(&self.agent_definition_id).cloned() else {- return;+ return Ok(());};if definition.subagents.is_empty() {- return;+ return Ok(());}let (integrations, integrations_are_authoritative) = {let mutable = self@@ -472,6 +480,10 @@ 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@@ -508,6 +520,11 @@ impl OpenHumanTurnPrelude {.retain(|name| !deferred.contains(name));surface.deferred_tool_names = deferred;}+ let permanent = surface.permanent_tool_names.clone();+ surface.visible_tool_names.extend(permanent.iter().cloned());+ surface+ .deferred_tool_names+ .retain(|name| !permanent.contains(name));let specs = surface.durable_tool_specs@@ -561,6 +578,7 @@ 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 {@@ -1517,6 +1535,7 @@ 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,@@ -1596,7 +1615,10 @@ impl OpenHumanSessionHost {})?;prelude.refresh_turn_boundary(!view.resumed && view.history.is_empty())- .await;+ .await+ .map_err(|error| {+ tinyagents_runtime::RuntimeError::Driver(error.to_string())+ })?;let context_window = prelude.turn_model_source.effective_context_window(&prelude.model_name)@@ -1636,6 +1658,18 @@ impl OpenHumanSessionHost {.map_err(|error| {tinyagents_runtime::RuntimeError::Driver(error.to_string())})?;+ {+ let surface = prelude+ .tool_surface+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ preparation.prefix = super::managed_tools::refresh_prefix(+ preparation.prefix.as_ref().unwrap_or(view.prefix),+ &surface.visible_tool_specs,+ &surface.permanent_tool_names,+ )+ .or(preparation.prefix);+ }if overrides.suppress_tools {// One-off tool-less turn: must not become the// thread's recorded tool list.@@ -1887,6 +1921,7 @@ 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_toolsdiff --git a/crates/openhuman-core/src/agent/session_host/runtime_session_tests.rs b/crates/openhuman-core/src/agent/session_host/runtime_session_tests.rsindex 9f03b880c8..db4b5bf757 100644--- a/crates/openhuman-core/src/agent/session_host/runtime_session_tests.rs+++ b/crates/openhuman-core/src/agent/session_host/runtime_session_tests.rs@@ -176,7 +176,7 @@ fn connected_mcp_actions_enter_search_and_leave_on_disconnect() {}];let action = searchable_name("server-1", "example/weather", "forecast");- prelude.refresh_delegation_tool_surface();+ prelude.refresh_delegation_tool_surface().unwrap();assert!(prelude.synthesized_tool_names_for_test().contains(&action));{let surface = prelude.tool_surface.lock().expect("tool surface");@@ -190,7 +190,7 @@ fn connected_mcp_actions_enter_search_and_leave_on_disconnect() {.expect("prelude state").connected_mcp_tools.clear();- prelude.refresh_delegation_tool_surface();+ prelude.refresh_delegation_tool_surface().unwrap();assert!(!prelude.synthesized_tool_names_for_test().contains(&action));assert!(!prelude.tool_surface@@ -246,7 +246,7 @@ async fn desktop_browser_setting_keeps_deferred_tools_in_fresh_and_resumed_surfaassert!(fresh.specs().iter().any(|spec| spec.name == name), "{name}");}prelude.adopt_recorded_tools(Some(&fresh));- prelude.refresh_delegation_tool_surface();+ prelude.refresh_delegation_tool_surface().unwrap();let resumed = prelude.prepare(false).await.expect("resumed tool surface");for name in ["browser", "browser_open"] {assert!(@@ -302,7 +302,7 @@ async fn a_resumed_orchestrator_keeps_the_integration_actions_it_was_sent() {let prelude = state.prelude.as_ref().expect("prelude");// Fresh process: no integrations known, so no actions are synthesised.- prelude.refresh_delegation_tool_surface();+ prelude.refresh_delegation_tool_surface().unwrap();assert!(!prelude.synthesized_tool_names_for_test().contains("GMAIL_SEND_EMAIL"));@@ -328,7 +328,7 @@ async fn a_resumed_orchestrator_keeps_the_integration_actions_it_was_sent() {}];mutable.connected_integrations_authoritative = true;}- prelude.refresh_delegation_tool_surface();+ prelude.refresh_delegation_tool_surface().unwrap();let names = prelude.synthesized_tool_names_for_test();assert!(names.contains("GMAIL_SEND_EMAIL"), "{names:?}");@@ -373,3 +373,74 @@ async fn session_locator_is_memoized_across_calls() {same-binding check rejects the second transcript bind");}++#[tokio::test]+async fn newly_connected_action_cannot_shadow_a_permanent_source() {+ use super::*;+ struct AttachedAction;+ #[async_trait::async_trait]+ impl tinytools::Tool for AttachedAction {+ fn name(&self) -> &str {+ "GMAIL_SEND_EMAIL"+ }+ fn description(&self) -> &str {+ "host-owned action"+ }+ fn parameters_schema(&self) -> serde_json::Value {+ serde_json::json!({"type":"object"})+ }+ async fn execute(&self, _: serde_json::Value) -> anyhow::Result<tinytools::ToolResult> {+ Ok(tinytools::ToolResult::success("host"))+ }+ }+ let _ = crate::agent::harness::definition::AgentDefinitionRegistry::init_global_builtins();+ let action_dir = tempfile::tempdir().unwrap();+ let model: Arc<dyn tinyinference_llm::model::ChatModel<()>> =+ Arc::new(tinyagents_harness::testkit::ScriptedModel::new(Vec::new()));+ let mut host = crate::agent::SessionHostBuilder::new()+ .chat_model(model)+ .tools(vec![Box::new(AttachedAction)])+ .permanent_tool_names(std::collections::HashSet::from(["GMAIL_SEND_EMAIL".into()]))+ .action_dir(action_dir.path().to_path_buf())+ .memory(crate::memory::test_support::noop_memory())+ .tool_dispatcher(Box::new(tinytools_agent::dialect::XmlDialect))+ .agent_definition_name("orchestrator")+ .build()+ .unwrap();+ host.ensure_runtime_session().unwrap();+ let prelude = host.runtime_state.lock().unwrap().prelude.clone().unwrap();+ prelude.refresh_delegation_tool_surface().unwrap();+ let before = prelude+ .tool_surface+ .lock()+ .unwrap()+ .visible_tool_specs+ .clone();+ prelude.adopt_recorded_tools(Some(+ &ToolSnapshot::new(vec![spec("GMAIL_SEND_EMAIL")]).unwrap(),+ ));+ {+ let mut mutable = prelude.mutable.lock().unwrap();+ mutable.connected_integrations = vec![crate::agent::prompts::ConnectedIntegration {+ toolkit: "gmail".into(),+ description: String::new(),+ tools: Vec::new(),+ gated_tools: Vec::new(),+ connected: true,+ connections: Vec::new(),+ non_active_status: None,+ }];+ mutable.connected_integrations_authoritative = true;+ }+ let error = prelude.refresh_delegation_tool_surface().unwrap_err();+ assert!(error+ .to_string()+ .contains("collision with synthesized tool"));+ let surface = prelude.tool_surface.lock().unwrap();+ assert!(Arc::ptr_eq(&surface.visible_tool_specs, &before));+ assert_eq!(surface.tools[0].description(), "host-owned action");+ assert!(!surface+ .synthesized_tools+ .iter()+ .any(|tool| tool.name() == "GMAIL_SEND_EMAIL"));+}diff --git a/crates/openhuman-core/src/agent/session_host/turn/context.rs b/crates/openhuman-core/src/agent/session_host/turn/context.rsindex 4fc9420f82..4fedabb48d 100644--- a/crates/openhuman-core/src/agent/session_host/turn/context.rs+++ b/crates/openhuman-core/src/agent/session_host/turn/context.rs@@ -29,6 +29,7 @@ impl OpenHumanSessionHost {// this renders is what tells the model a `delegate_*` tool exists.let all_tools = self.all_tool_refs();let mut prompt_tools = PromptTool::from_tool_refs(all_tools.iter().copied());+ prompt_tools.retain(|tool| !self.permanent_tool_names.contains(tool.name.as_ref()));let mut prompt_visible_tool_names =self.tool_policy_session.visible_tool_names_for_prompt();crate::agent::prompts::swap_deferred_for_discovery_bridge(diff --git a/crates/openhuman-core/src/agent/session_host/types.rs b/crates/openhuman-core/src/agent/session_host/types.rsindex 7e9d32b029..58088db1e6 100644--- a/crates/openhuman-core/src/agent/session_host/types.rs+++ b/crates/openhuman-core/src/agent/session_host/types.rs@@ -198,6 +198,7 @@ pub struct OpenHumanSessionHost {/// policy session exactly like a visible tool — a found tool the gate/// refused as "prompt-hidden" would be the old unusable find again.pub(super) deferred_tool_names: std::collections::HashSet<String>,+ pub(super) permanent_tool_names: std::collections::HashSet<String>,/// Whether this belt reaches deferred tools at all: a wildcard belt/// always does, a `[tools] named` belt only by listing `tool_search`./// Fixed at build; the refresh paths use it to recompute@@ -542,6 +543,7 @@ pub struct OpenHumanSessionHost {/// A builder for creating `OpenHumanSessionHost` instances with custom configuration.pub struct SessionHostBuilder {+ pub(super) permanent_tool_names: std::collections::HashSet<String>,pub(super) turn_model_source: Option<TurnModelSource>,pub(super) tools: Option<Vec<Box<dyn Tool>>>,/// Delegation tools synthesised for the session's initial connection set.diff --git a/crates/openhuman-core/src/tools/mod.rs b/crates/openhuman-core/src/tools/mod.rsindex a101fdf790..9c7458c34f 100644--- a/crates/openhuman-core/src/tools/mod.rs+++ b/crates/openhuman-core/src/tools/mod.rs@@ -67,5 +67,7 @@ pub use schemas::{// `Tool` itself rides here too, so an embedder implementing a tool reaches the *vendored* tinytools rather than adding a second path to it.// A second path is not merely duplicate -- it produces incompatible Rust types,// and a tool built against it cannot be handed to a session at all.-pub use tinytools::{PermissionLevel, Tool, ToolCategory, ToolResult, ToolScope, ToolSpec};+pub use tinytools::{+ PermissionLevel, Tool, ToolCategory, ToolExposure, ToolResult, ToolScope, ToolSpec,+};pub(crate) use user_filter::filter_tools_by_user_preference;diff --git a/crates/openhuman-embed/Cargo.toml b/crates/openhuman-embed/Cargo.tomlindex 51a27ae96b..f334289975 100644--- a/crates/openhuman-embed/Cargo.toml+++ b/crates/openhuman-embed/Cargo.toml@@ -32,6 +32,7 @@ file-logging = ["openhuman-core/file-logging"]scheduler-gate = ["openhuman-core/scheduler-gate"][dependencies]+async-trait = "0.1"openhuman-core = { path = "../openhuman-core", package = "openhuman", default-features = false }anyhow = "1"log = "0.4"diff --git a/crates/openhuman-embed/README.md b/crates/openhuman-embed/README.mdindex 1a64454bce..9c6a85fd28 100644--- a/crates/openhuman-embed/README.md+++ b/crates/openhuman-embed/README.md@@ -349,3 +349,12 @@ above. It does not depend on `openhuman-rpc`; `Outcome` and `StructuredRpcError`are core types (`openhuman_core::core`). `openhuman-app` and `openhuman-tui`depend on `openhuman-rpc` for its client (and the app on its server) and on`openhuman-core`; neither uses `openhuman-embed`.++## Permanent tools on supplied agents++Hosts can pass an existing configured `Agent` to another library, which adds+its tools through `Agent::attach_tools` without constructing a replacement.+Attachments are shared by clones, always directly advertised, and update only+their managed system catalogue when a continuing conversation gains tools.+See [agent attachment semantics and example](src/agent/README.md#attach-tools-to-an-existing-agent)+for source identity, collision errors, policy composition, and runtime identity.diff --git a/crates/openhuman-embed/src/agent/README.md b/crates/openhuman-embed/src/agent/README.mdindex 1e2301776e..a310e523c4 100644--- a/crates/openhuman-embed/src/agent/README.md+++ b/crates/openhuman-embed/src/agent/README.md@@ -40,8 +40,8 @@ that turn belongs to, not any other agent sharing the runtime.## Tool factories-`AgentSpec::tools` is the only way a host's own in-process tools reach an-agent without going through MCP. The factory runs once per session build,+`AgentSpec::tools` supplies a host's own in-process tools when an agent is+created. `Agent::attach_tools` adds permanent tools to an existing agent. The factory runs once per session build,which in practice means once per turn, because a session is rebuilt from thespec's data every time; see the doc comment on `AgentSpec::tools` for whythis is forced (an `Agent` is `Clone`, `Box<dyn Tool>` is not) and useful (a@@ -53,3 +53,40 @@ belt bound to something shorter-lived than the agent can vary per turn).agent and what stays runtime-wide instead of per-agent.- [`../harness/README.md`](../harness/README.md): the one-runtime,one-agent shorthand.++## Attach tools to an existing agent++`Agent::attach_tools(key, factory)` permanently adds a named `HostTools`+source without rebuilding the agent. All clones share the attachment. Reusing+both the source key and the same factory `Arc` is idempotent; another factory+under the same key or a colliding tool name returns `ToolAttachmentError`.+The factory is sampled without a session during registration, then runs per+turn. Keep its tool names stable and support the registration occasion.++Attached tools always have direct provider schemas and a separate system+catalogue, including tools originally declared deferred. Adding a source to+an existing conversation updates only that managed section on the next turn:+the configured prompt, skills, memory, and other frozen system sections stay+intact. TinyAgents seals the prior transcript generation and writes a successor+with the conversation preserved. Identical catalogues do not create generations.++Attachments do not replace the original host's tool gate. Each source's policy+applies to its own tool names; absent a source policy, those callbacks are+admitted and must perform their own operation authorization. Other tools keep+the agent's original policy, including its denials.++Use `runtime_id()` to check that supplied agents belong to one runtime and+`same_agent()` to distinguish an existing handle from a conflicting agent ID.+Runtime identities are opaque and valid for that runtime's lifetime; they are+not persistence keys.++```rust,no_run+use std::sync::Arc;+use openhuman_embed::{Agent, HostTools, HostTurnTools, Tool};+# fn connect(agent: &Agent, make_tools: impl Fn() -> Vec<Box<dyn Tool>> + Send + Sync + 'static) -> Result<(), openhuman_embed::ToolAttachmentError> {+let source: HostTools = Arc::new(move |_| HostTurnTools::advertised(make_tools()));+agent.attach_tools("tinyhivemind", source.clone())?;+agent.clone().attach_tools("tinyhivemind", source)?;+# Ok(())+# }+```diff --git a/crates/openhuman-embed/src/agent/attachments.rs b/crates/openhuman-embed/src/agent/attachments.rsnew file mode 100644index 0000000000..0d38798250--- /dev/null+++ b/crates/openhuman-embed/src/agent/attachments.rs@@ -0,0 +1,181 @@+//! Permanent tool sources attached to an already configured agent.+use super::Agent;+use openhuman_core::agent::tool_policy::{ToolPolicy, ToolPolicyDecision, ToolPolicyRequest};+use openhuman_core::agent::{HostTools, TurnContext};+use std::collections::{BTreeMap, HashSet};+use std::sync::{Arc, Mutex};++/// An invalid or conflicting permanent tool registration.+#[derive(Debug, thiserror::Error)]+pub enum ToolAttachmentError {+ /// Source keys must be nonempty.+ #[error("tool source key is empty")]+ EmptyKey,+ /// Another factory already owns this source key.+ #[error("tool source {0:?} is already attached")]+ SourceConflict(String),+ /// Tool names must be unique across sources and the configured agent.+ #[error("tool name {0:?} is already registered")]+ NameCollision(String),+}+#[derive(Default)]+pub(crate) struct Attachments(Mutex<BTreeMap<String, Attachment>>);+struct Attachment {+ factory: HostTools,+ names: HashSet<String>,+}+impl Agent {+ /// Attach a permanent, directly advertised tool source to this agent.+ ///+ /// Clones share registrations. The same key and factory `Arc` is idempotent;+ /// a different factory under that key is rejected. Factories are sampled+ /// with no session at registration to validate names, then rebuilt per turn.+ /// Keep tool names stable. Their callbacks should authorize their operations.+ /// Only these names use the attachment policy; other tools keep their gate.+ pub fn attach_tools(+ &self,+ key: impl Into<String>,+ factory: HostTools,+ ) -> Result<(), ToolAttachmentError> {+ let key = key.into();+ if key.trim().is_empty() {+ return Err(ToolAttachmentError::EmptyKey);+ }+ let mut sources = self+ .inner+ .attachments+ .0+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ if let Some(existing) = sources.get(&key) {+ return if Arc::ptr_eq(&existing.factory, &factory) {+ Ok(())+ } else {+ Err(ToolAttachmentError::SourceConflict(key))+ };+ }+ let context = TurnContext::new(self.id(), None);+ let mut occupied: HashSet<String> = sources+ .values()+ .flat_map(|source| source.names.iter().cloned())+ .collect();+ if let Some(host) = &self.inner.host_tools {+ occupied.extend(+ host(context)+ .tools+ .iter()+ .map(|tool| tool.name().to_string()),+ );+ }+ occupied.extend(+ openhuman_core::tools::registry::ops::registry_entries_for_config(&self.inner.config)+ .into_iter()+ .map(|entry| entry.name),+ );+ let config = &self.inner.config;+ let security = Arc::new(openhuman_core::security::SecurityPolicy::from_config(+ &config.autonomy,+ &config.workspace_dir,+ &config.action_dir,+ ));+ occupied.extend(+ openhuman_core::tools::ops::all_tools(+ Arc::new(config.clone()),+ &security,+ openhuman_core::security::AuditLogger::disabled(),+ &config.browser,+ &config.http_request,+ &config.action_dir,+ &Default::default(),+ config,+ )+ .iter()+ .map(|tool| tool.name().to_string()),+ );+ let tools = factory(context);+ let mut names = HashSet::new();+ for tool in tools.tools {+ let name = tool.name().to_string();+ if occupied.contains(&name) || !names.insert(name.clone()) {+ return Err(ToolAttachmentError::NameCollision(name));+ }+ }+ sources.insert(key, Attachment { factory, names });+ Ok(())+ }++ /// Opaque process-runtime identity shared by every agent on this runtime.+ pub fn runtime_id(&self) -> &str {+ &self.inner.runtime_id+ }++ /// Whether both handles refer to the same instantiated agent.+ pub fn same_agent(&self, other: &Agent) -> bool {+ Arc::ptr_eq(&self.inner, &other.inner)+ }+}++impl super::AgentInner {+ pub(crate) fn composed_host_tools(self: &Arc<Self>) -> Option<HostTools> {+ let sources: Vec<HostTools> = self+ .attachments+ .0+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .values()+ .map(|source| source.factory.clone())+ .collect();+ if sources.is_empty() {+ return self.host_tools.clone();+ }+ let host = self.host_tools.clone();+ Some(Arc::new(move |context| {+ let mut merged = host.as_ref().map(|host| host(context)).unwrap_or_default();+ let original = merged.policy.take();+ let mut policies = Vec::new();+ for source in &sources {+ let attached = source(context);+ let names: HashSet<String> = attached+ .tools+ .iter()+ .map(|tool| tool.name().to_string())+ .collect();+ merged.visible.extend(names.iter().cloned());+ merged.permanent.extend(names.iter().cloned());+ merged.tools.extend(attached.tools);+ policies.push((names, attached.policy));+ }+ merged.policy = Some(Arc::new(AttachmentPolicy { original, policies }));+ merged+ }))+ }+}+type SourcePolicy = (HashSet<String>, Option<Arc<dyn ToolPolicy>>);+struct AttachmentPolicy {+ original: Option<Arc<dyn ToolPolicy>>,+ policies: Vec<SourcePolicy>,+}+#[async_trait::async_trait]+impl ToolPolicy for AttachmentPolicy {+ fn name(&self) -> &str {+ "permanent_attachments"+ }+ async fn check(&self, request: &ToolPolicyRequest) -> ToolPolicyDecision {+ for (names, policy) in &self.policies {+ if names.contains(&request.tool_name) {+ return match policy {+ Some(policy) => policy.check(request).await,+ None => ToolPolicyDecision::Allow,+ };+ }+ }+ match &self.original {+ Some(policy) => policy.check(request).await,+ None => ToolPolicyDecision::Allow,+ }+ }+}++#[cfg(test)]+#[path = "attachments_tests.rs"]+mod tests;diff --git a/crates/openhuman-embed/src/agent/attachments_tests.rs b/crates/openhuman-embed/src/agent/attachments_tests.rsnew file mode 100644index 0000000000..d66b8639d7--- /dev/null+++ b/crates/openhuman-embed/src/agent/attachments_tests.rs@@ -0,0 +1,46 @@+use super::*;+use openhuman_core::agent::tool_policy::{ToolCallContext, ToolPolicyDecision};+struct Deny;+#[async_trait::async_trait]+impl ToolPolicy for Deny {+ fn name(&self) -> &str {+ "deny"+ }+ async fn check(&self, _: &ToolPolicyRequest) -> ToolPolicyDecision {+ ToolPolicyDecision::Deny {+ reason: "host denied".into(),+ }+ }+}+fn request(name: &str) -> ToolPolicyRequest {+ ToolPolicyRequest::new(+ name,+ serde_json::json!({}),+ ToolCallContext::session("s", "c", "a", "call", 0),+ )+}+#[tokio::test]+async fn attachment_policy_does_not_replace_original_host_authority() {+ let policy = AttachmentPolicy {+ original: Some(Arc::new(Deny)),+ policies: vec![+ (HashSet::from(["hivemind_message".into()]), None),+ (+ HashSet::from(["hivemind_create".into()]),+ Some(Arc::new(Deny)),+ ),+ ],+ };+ assert!(matches!(+ policy.check(&request("hivemind_message")).await,+ ToolPolicyDecision::Allow+ ));+ assert!(matches!(+ policy.check(&request("host_original")).await,+ ToolPolicyDecision::Deny { .. }+ ));+ assert!(matches!(+ policy.check(&request("hivemind_create")).await,+ ToolPolicyDecision::Deny { .. }+ ));+}diff --git a/crates/openhuman-embed/src/agent/build.rs b/crates/openhuman-embed/src/agent/build.rsindex 6f48f24488..45d63ccf21 100644--- a/crates/openhuman-embed/src/agent/build.rs+++ b/crates/openhuman-embed/src/agent/build.rs@@ -160,6 +160,8 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInnOk(AgentInner {id,+ runtime_id: runtime.runtime_id().to_owned(),+ attachments: Default::default(),_runtime_guard: runtime.guard(),runtime: runtime.core_runtime().clone(),ctx,diff --git a/crates/openhuman-embed/src/agent/mod.rs b/crates/openhuman-embed/src/agent/mod.rsindex 04e87fd63a..cff742591c 100644--- a/crates/openhuman-embed/src/agent/mod.rs+++ b/crates/openhuman-embed/src/agent/mod.rs@@ -14,6 +14,8 @@//! loader, DomainSet gate, tool-group filter and skill discovery all read//! the ambient context.+mod attachments;+pub use attachments::ToolAttachmentError;pub(crate) mod build;mod definition;mod layout;@@ -78,6 +80,8 @@ pub enum AgentError {/// by every [`Turn`] it issues.pub(crate) struct AgentInner {pub(crate) id: String,+ pub(crate) runtime_id: String,+ pub(crate) attachments: attachments::Attachments,/// Keeps the runtime's core and (for an ephemeral workspace) its/// directory alive for as long as this agent is, even after the host/// drops its `Runtime` handle. Seediff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rsindex dd60140cf8..ce8477b192 100644--- a/crates/openhuman-embed/src/lib.rs+++ b/crates/openhuman-embed/src/lib.rs@@ -72,7 +72,7 @@ pub use openhuman_core::tools::toolpacks::{GroupMode, ToolGroups};// would build tools of a different, incompatible type.pub use openhuman_core::agent::tinyagents::host::LastTurnUsage;pub use openhuman_core::agent::{HostTools, HostTurnTools, TurnContext};-pub use openhuman_core::tools::Tool;+pub use openhuman_core::tools::{Tool, ToolExposure};pub use openhuman_core::{CoreBuilder, CoreRuntime, DaemonConfig, DomainSet, HostKind, ServiceSet, TokenSource,};@@ -95,6 +95,7 @@ mod harness;mod runtime;mod turn;+pub use agent::ToolAttachmentError;pub use agent::{Agent, AgentDefinitionSpec, AgentError, AgentLayout, AgentSpec, SandboxModeSpec, ToolScopeSpec,};diff --git a/crates/openhuman-embed/src/runtime/mod.rs b/crates/openhuman-embed/src/runtime/mod.rsindex 9b4231d7af..f537fcb87a 100644--- a/crates/openhuman-embed/src/runtime/mod.rs+++ b/crates/openhuman-embed/src/runtime/mod.rs@@ -190,6 +190,7 @@ impl Drop for CoreGuard {/// every [`Agent`](crate::Agent) built on it tears the core down and, for/// [`Workspace::Ephemeral`], removes the workspace — see [`CoreGuard`].pub struct Runtime {+ id: String,guard: Arc<CoreGuard>,/// The config every agent starts from. Already carries the runtime-wide/// defaults (backend URL, access, provider model, supplied overrides).@@ -204,6 +205,11 @@ pub struct Runtime {}impl Runtime {+ /// Opaque identity of this instantiated runtime.+ pub fn runtime_id(&self) -> &str {+ &self.id+ }+/// Start configuring a runtime.pub fn builder() -> RuntimeBuilder {RuntimeBuilder::new()@@ -343,6 +349,7 @@ impl Runtime {access: Access,) -> Self {Self {+ id: uuid::Uuid::new_v4().to_string(),guard: Arc::new(CoreGuard {core: Some(core),workspace,diff --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rsindex 619e684062..1ea9f36974 100644--- a/crates/openhuman-embed/src/turn.rs+++ b/crates/openhuman-embed/src/turn.rs@@ -595,9 +595,10 @@ async fn dispatch(request.inference_url,request.api_key,);+ let host = inner.composed_host_tools();let target = AgentChatTarget::Definition {definition: &inner.definition,- host: inner.host_tools.as_ref(),+ host: host.as_ref(),seed: seed.as_deref(),usage: Some(usage),};diff --git a/crates/openhuman-embed/tests/attached_tools.rs b/crates/openhuman-embed/tests/attached_tools.rsnew file mode 100644index 0000000000..efa9e5b4c0--- /dev/null+++ b/crates/openhuman-embed/tests/attached_tools.rs@@ -0,0 +1,210 @@+mod common;+use common::{chat_completion, chat_requests, offline_config, runtime, stub_backend};+use openhuman_embed::{+ AgentDefinitionSpec, AgentSpec, HostTools, HostTurnTools, Provider, Runtime, Tool,+ ToolScopeSpec, Workspace,+};+use std::sync::Arc;+use wiremock::matchers::{method, path};+use wiremock::{Mock, ResponseTemplate};+struct Marker(&'static str);+#[async_trait::async_trait]+impl Tool for Marker {+ fn exposure(&self) -> openhuman_embed::ToolExposure {+ openhuman_embed::ToolExposure::Deferred+ }+ fn name(&self) -> &str {+ self.0+ }+ fn description(&self) -> &str {+ "Send a message to the hive"+ }+ fn parameters_schema(&self) -> serde_json::Value {+ serde_json::json!({"type":"object", "properties":{"message":{"type":"string"}}, "required":["message"]})+ }+ async fn execute(+ &self,+ _: serde_json::Value,+ ) -> anyhow::Result<openhuman_core::tools::ToolResult> {+ Ok(openhuman_core::tools::ToolResult::success("accepted"))+ }+}+#[test]+fn attached_tools_survive_clones_and_session_resume() {+ let collision = openhuman_core::agent::OpenHumanSessionHost::builder()+ .tools(vec![Box::new(Marker("mcp_fixture_send"))])+ .synthesized_tools(vec![Box::new(Marker("mcp_fixture_send"))])+ .permanent_tool_names(std::collections::HashSet::from(["mcp_fixture_send".into()]))+ .build()+ .err()+ .expect("a permanent source cannot shadow a synthesized MCP tool");+ assert!(collision+ .to_string()+ .contains("collision with synthesized tool"));+ runtime().block_on(async {+ tokio::spawn(async {+ let backend = stub_backend().await;+ let provider = wiremock::MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/v1/chat/completions"))+ .respond_with(ResponseTemplate::new(200).set_body_json(chat_completion("reply")))+ .mount(&provider)+ .await;+ let runtime = Runtime::builder()+ .config(offline_config())+ .workspace(Workspace::Ephemeral)+ .backend_url(backend.uri())+ .build()+ .await+ .unwrap();+ let agent = runtime+ .agent(+ AgentSpec::new("attached")+ .provider(+ Provider::openai_compatible(+ format!("{}/v1", provider.uri()),+ "fixture",+ )+ .model("fixture"),+ )+ .definition(+ AgentDefinitionSpec::new()+ .system_prompt("FROZEN_HOST_PROMPT")+ .tools(ToolScopeSpec::Named(vec![+ "shell".into(),+ "tool_search".into(),+ ])),+ ),+ )+ .unwrap();+ let original_config = agent.config().clone();+ assert!(agent+ .attach_tools("", Arc::new(|_| HostTurnTools::default()))+ .is_err());+ assert!(agent+ .attach_tools(+ "builtin-collision",+ Arc::new(|_| HostTurnTools::advertised(vec![Box::new(Marker("shell"))]))+ )+ .is_err());+ let peer = runtime.agent(AgentSpec::new("peer")).unwrap();+ assert!(!agent.same_agent(&peer));+ assert_eq!(agent.runtime_id(), peer.runtime_id());+ let clone = agent.clone();+ assert!(agent.same_agent(&clone));+ assert_eq!(agent.runtime_id(), clone.runtime_id());+ let factory: HostTools =+ Arc::new(|_| HostTurnTools::advertised(vec![Box::new(Marker("hivemind_message"))]));+ agent.attach_tools("tinyhivemind", factory.clone()).unwrap();+ clone.attach_tools("tinyhivemind", factory).unwrap();+ assert!(clone+ .attach_tools("tinyhivemind", Arc::new(|_| HostTurnTools::default()))+ .is_err());+ assert!(clone+ .attach_tools(+ "collision",+ Arc::new(|_| HostTurnTools::advertised(vec![Box::new(Marker(+ "hivemind_message"+ ))]))+ )+ .is_err());+ agent+ .turn("first user")+ .session("continuing")+ .send()+ .await+ .unwrap();+ clone+ .turn("second user")+ .session("continuing")+ .send()+ .await+ .unwrap();+ agent+ .attach_tools(+ "second",+ Arc::new(|_| {+ HostTurnTools::advertised(vec![Box::new(Marker("hivemind_list"))])+ }),+ )+ .unwrap();+ clone+ .turn("third user")+ .session("continuing")+ .send()+ .await+ .unwrap();+ clone+ .turn("fourth user")+ .session("continuing")+ .send()+ .await+ .unwrap();+ assert_eq!(agent.config().action_dir, original_config.action_dir);+ let paths = std::fs::read_dir(agent.transcripts_dir())+ .unwrap()+ .map(|entry| entry.unwrap().path())+ .collect::<Vec<_>>();+ assert!(paths+ .iter()+ .any(|path| path.to_string_lossy().contains(".g1.jsonl")));+ assert!(+ !paths+ .iter()+ .any(|path| path.to_string_lossy().contains(".g2.jsonl")),+ "identical catalogue must not create another generation"+ );+ let successor = paths+ .iter()+ .find(|path| path.to_string_lossy().contains(".g1.jsonl"))+ .unwrap();+ let durable = std::fs::read_to_string(successor).unwrap();+ assert!(+ durable+ .lines()+ .any(|line| line.contains("openhuman-permanent-tools")+ && line.contains("hivemind_list")),+ "updated catalogue must be durable"+ );+ let requests = chat_requests(&provider).await;+ assert_eq!(requests.len(), 4);+ for (index, request) in requests.iter().enumerate() {+ let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();+ let messages = body["messages"].as_array().unwrap();+ let system = messages+ .iter()+ .filter(|m| m["role"] == "system")+ .map(|m| m["content"].as_str().unwrap_or(""))+ .collect::<Vec<_>>()+ .join("\n");+ assert!(system.contains("FROZEN_HOST_PROMPT"));+ assert_eq!(system.matches("hivemind_message").count(), 1, "{system}");+ let tools = body["tools"].as_array().unwrap();+ assert_eq!(+ tools+ .iter()+ .filter(|t| t["function"]["name"] == "hivemind_message")+ .count(),+ 1,+ "request {index}: {body}"+ );+ if index >= 2 {+ assert_eq!(system.matches("hivemind_list").count(), 1);+ assert_eq!(+ tools+ .iter()+ .filter(|t| t["function"]["name"] == "hivemind_list")+ .count(),+ 1+ );+ }+ if index > 0 {+ assert!(messages.iter().any(|m| m["role"] == "user"+ && m["content"].as_str().unwrap_or("").contains("first user")));+ }+ }+ })+ .await+ .unwrap();+ });+}diff --git a/vendor/tinyagents b/vendor/tinyagentsindex 0e502b80bd..e0107b786c 160000--- a/vendor/tinyagents+++ b/vendor/tinyagents@@ -1 +1 @@-Subproject commit 0e502b80bd5dff3a43178eb790ebfcc37ceb8914+Subproject commit e0107b786cb36a817da8401cb08c2ce07556eff6