The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(agent): reconcile delegation tools without owning the tools Arc
Shanud149ab0f01e4
diff --git a/src/openhuman/agent/debug/mod.rs b/src/openhuman/agent/debug/mod.rsindex 876462f39e..6f1f5ea499 100644--- a/src/openhuman/agent/debug/mod.rs+++ b/src/openhuman/agent/debug/mod.rs@@ -104,7 +104,10 @@ pub struct DumpedPrompt {pub tool_specs: Vec<serde_json::Value>,}-fn tool_specs_of<T: std::ops::Deref<Target = dyn crate::openhuman::tools::Tool>>(+// The `+ 'a` is load-bearing: a bare `dyn Tool` here means `dyn Tool ++// 'static`, which `Box<dyn Tool>` satisfies but a borrowed `&'a dyn Tool` (what+// `Agent::all_tool_refs` yields) does not.+fn tool_specs_of<'a, T: std::ops::Deref<Target = dyn crate::openhuman::tools::Tool + 'a>>(tools: &[T],) -> Vec<serde_json::Value> {tools@@ -257,18 +260,17 @@ async fn render_via_session(config: &Config, agent_id: &str) -> Result<DumpedProagent.fetch_connected_integrations().await;// Mirror turn-1: synthesise `delegate_*` tools for connected// Composio toolkits now that we know what's actually authorised.- // The shared-Arc failure path is unreachable here (this is the- // debug dumper running against a freshly-built agent — no- // sub-agent has cloned the tool list), so ignore the bool return.- let _ = agent.refresh_delegation_tools();+ agent.refresh_delegation_tools();let text = agent.build_system_prompt(LearnedContextData::default()).with_context(|| format!("rendering system prompt for `{agent_id}`"))?;- let tools = agent.tools();+ // The whole callable surface, so the dump shows the `delegate_*` tools+ // the refresh above just synthesised alongside the durable registry.+ let tools = agent.all_tool_refs();let tool_names: Vec<String> = tools.iter().map(|t| t.name().to_string()).collect();- let tool_specs = tool_specs_of(tools);+ let tool_specs = tool_specs_of(&tools);let skill_tool_count = tools.iter().filter(|t| t.category() == ToolCategory::Workflow)diff --git a/src/openhuman/agent/harness/session/builder/setters.rs b/src/openhuman/agent/harness/session/builder/setters.rsindex f418ee193c..df883ac38a 100644--- a/src/openhuman/agent/harness/session/builder/setters.rs+++ b/src/openhuman/agent/harness/session/builder/setters.rs@@ -605,6 +605,9 @@ impl AgentBuilder {Ok(Agent {turn_model_source,tools,+ // Populated by the first `refresh_delegation_tools`; agents that+ // declare no sub-agents never leave it empty-but-allocated.+ synthesized_tools: Arc::new(Vec::new()),tool_specs: Arc::new(tool_specs),visible_tool_specs: Arc::new(visible_tool_specs),visible_tool_names: visible_names,@@ -703,7 +706,6 @@ impl AgentBuilder {pending_skill_retraction: Vec::new(),archivist_hook: self.archivist_hook,synthesized_tool_names: std::collections::HashSet::new(),- pending_synthesized_tools_mask: std::collections::HashSet::new(),pending_turn_overrides: super::super::types::TurnOverrides::default(),})}diff --git a/src/openhuman/agent/harness/session/runtime_impl_01_part_01.rs b/src/openhuman/agent/harness/session/runtime_impl_01_part_01.rsindex 0a9ac14ea7..0363bf6249 100644--- a/src/openhuman/agent/harness/session/runtime_impl_01_part_01.rs+++ b/src/openhuman/agent/harness/session/runtime_impl_01_part_01.rs@@ -42,17 +42,48 @@ impl Agent {self.turn_model_source.clone()}- /// Borrow the agent's tools as a slice. Used by the sub-agent runner- /// to filter the parent's tool registry per-archetype.+ /// Borrow the agent's durable tool registry as a slice. Used by the+ /// sub-agent runner to filter the parent's tool registry per-archetype.+ ///+ /// This is **not** the agent's whole callable surface — the synthesised+ /// delegation tools live in their own `Arc`. Use [`Self::all_tool_refs`]+ /// when you mean "every tool this agent can run".pub fn tools(&self) -> &[Box<dyn Tool>] {self.tools.as_slice()}- /// Clone the agent's tools `Arc` for sharing with sub-agents.+ /// Clone the agent's durable tools `Arc` for sharing with sub-agents.+ ///+ /// Deliberately excludes [`Self::synthesized_tools_arc`]: a sub-agent must+ /// never be handed a `delegate_*` tool, which the harness re-asserts at+ /// registration time (issue #4452).pub fn tools_arc(&self) -> Arc<Vec<Box<dyn Tool>>> {Arc::clone(&self.tools)}+ /// Clone the agent's synthesised delegation tools `Arc`.+ ///+ /// Replaced wholesale on every [`Agent::refresh_delegation_tools`], so a+ /// clone taken here is a stable snapshot for the rest of the caller's turn+ /// even if the connection set changes underneath it.+ pub fn synthesized_tools_arc(&self) -> Arc<Vec<Box<dyn Tool>>> {+ Arc::clone(&self.synthesized_tools)+ }++ /// Every tool this agent can execute: the durable registry plus the+ /// synthesised delegation set.+ ///+ /// Borrowed rather than materialised as a `Vec<Box<dyn Tool>>` because+ /// `Box<dyn Tool>` is not cloneable — the two sets can be read together but+ /// never merged into one owned slice.+ pub fn all_tool_refs(&self) -> Vec<&dyn Tool> {+ self.tools+ .iter()+ .chain(self.synthesized_tools.iter())+ .map(|t| t.as_ref())+ .collect()+ }+/// Borrow the agent's tool specs (pre-serialised). Captured at/// turn-start so sub-agents can pass byte-identical schemas to the/// provider for prefix-cache reuse.@@ -372,12 +403,17 @@ impl Agent {}pub(super) fn rebuild_tool_policy_session(&mut self) {- self.tool_policy_session = ToolPolicyEngine::build_session(+ // Classify the synthesised delegates too: they are advertised to the+ // provider and callable, so a policy snapshot built from the durable+ // registry alone would leave every `delegate_*` tool with no decision+ // at all.+ let all_tools = self.all_tool_refs();+ self.tool_policy_session = ToolPolicyEngine::build_session_from_refs(&self.agent_definition_name,&self.event_channel,"session",&self.config.channel_permissions,- self.tools.as_slice(),+ &all_tools,&self.visible_tool_names,);let visible_specs = super::builder::visible_tool_specs_for_policy(diff --git a/src/openhuman/agent/harness/session/session_tests.rs b/src/openhuman/agent/harness/session/session_tests.rsindex 9437488206..fe86cdfeff 100644--- a/src/openhuman/agent/harness/session/session_tests.rs+++ b/src/openhuman/agent/harness/session/session_tests.rs@@ -223,6 +223,69 @@ fn integration_delegate_toolkit_enum(agent: &Agent) -> Vec<String> {out}+/// Every synthesised delegate the agent advertises must have an executable+/// instance behind it, and vice versa.+///+/// This is the invariant #6145 broke: `tool_specs` reconciled unconditionally+/// while the instances only reconciled when the `tools` `Arc` happened to be+/// uniquely owned, so a mid-session connect published a `delegate_*` schema+/// that no registered tool set could dispatch. Asserted through the public+/// surface only, like every other test in this file.+fn assert_synthesized_delegates_are_executable(agent: &Agent) {+ let instances = agent.synthesized_tools_arc();+ let executable: std::collections::HashSet<String> =+ instances.iter().map(|t| t.name().to_string()).collect();+ assert_eq!(+ executable.len(),+ instances.len(),+ "the synthesised set must not contain duplicate tool names"+ );++ let spec_names: std::collections::HashSet<String> = agent+ .tool_specs()+ .iter()+ .map(|spec| spec.name.clone())+ .collect();+ for name in &executable {+ assert!(+ spec_names.contains(name),+ "executable synthesised tool `{name}` is not advertised in tool_specs"+ );+ }++ // The other direction is the one that actually regressed: a+ // `delegate_*` spec on the wire with nothing registered to run it.+ let advertised_delegates: Vec<&String> = spec_names+ .iter()+ .filter(|name| name.starts_with("delegate_"))+ .collect();+ for name in advertised_delegates {+ assert!(+ executable.contains(name),+ "advertised delegate `{name}` has no executable instance; executable={executable:?}"+ );+ }++ // Presence is not enough. A stale instance under a fresh spec is the same+ // class of bug one step quieter: the model reads the new `toolkit` enum+ // and routes to an instance built from the previous connection set. Pin+ // that each instance's own schema is byte-identical to what is advertised.+ for tool in instances.iter() {+ let advertised = agent+ .tool_specs()+ .iter()+ .find(|spec| spec.name == tool.name())+ .unwrap_or_else(|| panic!("no spec advertised for synthesised tool `{}`", tool.name()));+ assert_eq!(+ tool.spec().parameters,+ advertised.parameters,+ "synthesised instance `{}` carries a stale schema — advertised and executable \+ must be rebuilt in the same pass",+ tool.name()+ );+ }+}+async fn turn_dispatches_spawn_subagent_through_full_path_inner() {// The embedding seam fails loudly when unwired; before the memory// extraction this was a direct call and needed no setup.diff --git a/src/openhuman/agent/harness/session/session_tests_part_01_tests.rs b/src/openhuman/agent/harness/session/session_tests_part_01_tests.rsindex 98c978b47f..4d6859a370 100644--- a/src/openhuman/agent/harness/session/session_tests_part_01_tests.rs+++ b/src/openhuman/agent/harness/session/session_tests_part_01_tests.rs@@ -103,7 +103,7 @@ fn refresh_delegation_tools_updates_schema_even_when_tool_arc_is_shared() {},]);- assert!(agent.refresh_delegation_tools());+ agent.refresh_delegation_tools();assert_eq!(integration_delegate_toolkit_enum(&agent),vec!["gmail".to_string()]@@ -132,11 +132,15 @@ fn refresh_delegation_tools_updates_schema_even_when_tool_arc_is_shared() {},]);- assert!(agent.refresh_delegation_tools());+ agent.refresh_delegation_tools();assert_eq!(integration_delegate_toolkit_enum(&agent),vec!["gmail".to_string(), "notion".to_string()]);+ // The schema moved; the executable instances must have moved with it.+ // Before #6145 the shared clone above blocked the instance reconcile and+ // only this assertion would have failed.+ super::assert_synthesized_delegates_are_executable(&agent);}/// Regression for #3044: repeated mid-session connects while the `tools`@@ -176,7 +180,7 @@ fn refresh_delegation_tools_no_duplicate_specs_across_shared_arc_connects() {// Turn 1: gmail connects.agent.set_connected_integrations(vec![conn("gmail", "Email")]);- assert!(agent.refresh_delegation_tools());+ agent.refresh_delegation_tools();// Hold a shared clone across every subsequent refresh so `Arc::get_mut`// always fails — exactly what happens during an in-flight turn.@@ -184,7 +188,7 @@ fn refresh_delegation_tools_no_duplicate_specs_across_shared_arc_connects() {// Turn 2: notion connects mid-session.agent.set_connected_integrations(vec![conn("gmail", "Email"), conn("notion", "Docs")]);- assert!(agent.refresh_delegation_tools());+ agent.refresh_delegation_tools();// Turn 3: slack connects mid-session — this is where the old code// produced a duplicate `delegate_to_integrations_agent` spec.@@ -193,7 +197,7 @@ fn refresh_delegation_tools_no_duplicate_specs_across_shared_arc_connects() {conn("notion", "Docs"),conn("slack", "Chat"),]);- assert!(agent.refresh_delegation_tools());+ agent.refresh_delegation_tools();assert_eq!(delegate_spec_count(&agent),@@ -208,6 +212,7 @@ fn refresh_delegation_tools_no_duplicate_specs_across_shared_arc_connects() {"slack".to_string()]);+ super::assert_synthesized_delegates_are_executable(&agent);}#[tokio::test]@@ -604,3 +609,121 @@ async fn last_turn_usage_is_public_and_non_draining() {// After the drain the peek accessor reports nothing, as expected.assert!(agent.last_turn_usage().is_none());}++/// Regression for #6145: a delegate tool that appears for the **first time**+/// while the `tools` Arc is shared must be dispatchable, not just advertised.+///+/// This is the exact field scenario from the issue — an agent whose surface+/// carried no `delegate_to_integrations_agent` at all, a mid-session Composio+/// connect while an in-flight turn held a clone, and a refresh that logged+/// `added=["delegate_to_integrations_agent"] tools_reconciled=false`. The spec+/// reached the provider and the model called a tool the harness had never+/// registered.+#[test]+fn newly_synthesized_delegate_is_executable_while_tool_arc_is_shared() {+ use crate::openhuman::agent::harness::AgentDefinitionRegistry;++ AgentDefinitionRegistry::init_global_builtins().unwrap();+ let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));++ // Turn 1 with nothing connected: no integration delegate exists yet.+ agent.refresh_delegation_tools();+ let advertised_before = agent+ .tool_specs()+ .iter()+ .any(|spec| spec.name == "delegate_to_integrations_agent");+ let executable_before = agent+ .synthesized_tools_arc()+ .iter()+ .any(|t| t.name() == "delegate_to_integrations_agent");+ assert_eq!(+ advertised_before, executable_before,+ "schema and instances must agree even before anything is connected"+ );++ // An in-flight turn (or a spawned sub-agent's ParentExecutionContext)+ // holds a clone for the rest of the session. `Arc::get_mut` would fail+ // from here on — which is what used to break the instance reconcile.+ let _shared_tools = agent.tools_arc();++ agent.set_connected_integrations(vec![+ crate::openhuman::agent::context::prompt::ConnectedIntegration {+ toolkit: "gmail".into(),+ description: "Email".into(),+ tools: vec![],+ gated_tools: vec![],+ connected: true,+ connections: Vec::new(),+ non_active_status: None,+ },+ ]);+ agent.refresh_delegation_tools();++ assert!(+ agent+ .tool_specs()+ .iter()+ .any(|spec| spec.name == "delegate_to_integrations_agent"),+ "the mid-session connect must publish the delegate spec"+ );+ assert!(+ agent+ .synthesized_tools_arc()+ .iter()+ .any(|t| t.name() == "delegate_to_integrations_agent"),+ "the delegate must also exist as an executable instance — advertising a \+ tool with nothing registered to run it is #6145"+ );+ super::assert_synthesized_delegates_are_executable(&agent);+}++/// The superseded synthesised instances are released once the readers holding+/// them go away — the issue's "clean up the old one once its refcount drops".+#[test]+fn superseded_synthesized_instances_are_released_when_readers_drop() {+ use crate::openhuman::agent::harness::AgentDefinitionRegistry;++ AgentDefinitionRegistry::init_global_builtins().unwrap();+ let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));++ let conn =+ |slug: &str, desc: &str| crate::openhuman::agent::context::prompt::ConnectedIntegration {+ toolkit: slug.into(),+ description: desc.into(),+ tools: vec![],+ gated_tools: vec![],+ connected: true,+ connections: Vec::new(),+ non_active_status: None,+ };++ agent.set_connected_integrations(vec![conn("gmail", "Email")]);+ agent.refresh_delegation_tools();++ // A turn takes its snapshot of the synthesised set and keeps it.+ let in_flight = agent.synthesized_tools_arc();+ assert_eq!(Arc::strong_count(&in_flight), 2, "agent + in-flight turn");++ // The connection set changes underneath it.+ agent.set_connected_integrations(vec![conn("gmail", "Email"), conn("notion", "Docs")]);+ agent.refresh_delegation_tools();++ // The reader still sees a coherent set, and it is the *previous* one.+ assert_eq!(+ Arc::strong_count(&in_flight),+ 1,+ "the agent has moved on to a fresh Arc; only the in-flight turn holds the old one"+ );+ assert!(+ !Arc::ptr_eq(&in_flight, &agent.synthesized_tools_arc()),+ "a refresh must publish a new Arc rather than mutating the shared one"+ );++ // When the turn ends, the superseded instances are freed.+ drop(in_flight);+ assert_eq!(+ Arc::strong_count(&agent.synthesized_tools_arc()),+ 2,+ "only the agent's own Arc and this test's clone remain"+ );+}diff --git a/src/openhuman/agent/harness/session/turn/context.rs b/src/openhuman/agent/harness/session/turn/context.rsindex 38185ba679..91068a0f81 100644--- a/src/openhuman/agent/harness/session/turn/context.rs+++ b/src/openhuman/agent/harness/session/turn/context.rs@@ -285,11 +285,13 @@ impl Agent {.tool_dispatcher.prompt_instructions_for_specs(self.visible_tool_specs.as_slice()).unwrap_or_else(|| self.tool_dispatcher.prompt_instructions(tools_slice));- // Adapt the owned Box<dyn Tool> slice into the shared PromptTool+ // Adapt the agent's whole callable surface into the shared PromptTool// shape that every prompt-building call-site uses. Temporary vec- // borrows from `tools_slice` and lives for the duration of the- // prompt build.- let prompt_tools = PromptTool::from_tools(tools_slice);+ // borrows from the two tool `Arc`s and lives for the duration of the+ // prompt build. The synthesised delegates belong here: the catalogue+ // this renders is what tells the model a `delegate_*` tool exists.+ let all_tools = self.all_tool_refs();+ let prompt_tools = PromptTool::from_tool_refs(all_tools.iter().copied());let prompt_visible_tool_names = self.tool_policy_session.visible_tool_names_for_prompt();// Load AGENTS.md instruction layers once per system-prompt build (never// re-read per turn — the caller builds the prompt once at session startdiff --git a/src/openhuman/agent/harness/session/turn/core_session.rs b/src/openhuman/agent/harness/session/turn/core_session.rsindex a4dde8e5ed..8b81785260 100644--- a/src/openhuman/agent/harness/session/turn/core_session.rs+++ b/src/openhuman/agent/harness/session/turn/core_session.rs@@ -91,19 +91,13 @@ impl Agent {// model cannot enter the tool loop and answers in a single call. The// agent's durable `self.tools` / `self.visible_tool_names` are left// untouched — the next un-overridden turn gets the full toolbelt back.- let (turn_tools, turn_visible_tool_names) = if suppress_tools {- (- std::sync::Arc::new(Vec::new()),- std::collections::HashSet::new(),- )- } else {- (self.tools.clone(), self.visible_tool_names.clone())- };+ let (turn_tools, turn_synthesized_tools, turn_visible_tool_names) =+ self.turn_tool_sets(suppress_tools);tracing::info!(model = %effective_model,max_iterations,- tools = turn_tools.len(),+ tools = turn_tools.len() + turn_synthesized_tools.len(),suppress_tools,"[agent_loop] routing chat turn through the tinyagents harness");@@ -159,6 +153,7 @@ impl Agent {model: effective_model.to_string(),messages,tools: turn_tools,+ synthesized_tools: turn_synthesized_tools,visible_tool_names: turn_visible_tool_names,max_iterations,on_progress: self.on_progress.clone(),diff --git a/src/openhuman/agent/harness/session/turn/core_turn.rs b/src/openhuman/agent/harness/session/turn/core_turn.rsindex 8271578930..3cf56aa274 100644--- a/src/openhuman/agent/harness/session/turn/core_turn.rs+++ b/src/openhuman/agent/harness/session/turn/core_turn.rs@@ -71,12 +71,9 @@ impl Agent {self.fetch_connected_integrations().await;// Sessions born without a cached Composio view still need// a one-shot delegation-surface reconcile before the system- // prompt is frozen. The shared-Arc failure path returns- // `false`, but on turn 1 the Arc should still be uniquely- // owned; a `false` return here indicates a programmer error- // and the warn-level log inside the helper already surfaces- // it, so we keep the existing best-effort contract.- let _ = self.refresh_delegation_tools();+ // prompt is frozen. It runs before `build_system_prompt`+ // below so the rendered tool catalogue carries the delegates.+ self.refresh_delegation_tools();}let learned = self.fetch_learned_context().await;let rendered_prompt = self.build_system_prompt(learned)?;diff --git a/src/openhuman/agent/harness/session/turn/graph.rs b/src/openhuman/agent/harness/session/turn/graph.rsindex 7b95702f9f..a9bbaa4df3 100644--- a/src/openhuman/agent/harness/session/turn/graph.rs+++ b/src/openhuman/agent/harness/session/turn/graph.rs@@ -54,8 +54,16 @@ pub(crate) struct ChatTurnGraph {/// Provider-ready messages (system + prior history + this turn's user turn,/// multimodal markers already expanded).pub messages: Vec<ChatMessage>,- /// The agent's resolved, `Arc`-shared harness tool set.+ /// The agent's durable, `Arc`-shared harness tool set.pub tools: Arc<Vec<Box<dyn Tool>>>,+ /// The delegation tools synthesised for the current connection set,+ /// carried as their own set rather than merged into `tools`.+ ///+ /// This mirrors what the channel path has always done with its per-turn+ /// `extra_tools` (see [`crate::openhuman::agent::harness::graph`]), and it+ /// is what lets a mid-session Composio connect reach the model as a+ /// *callable* tool rather than a schema entry with no instance behind it.+ pub synthesized_tools: Arc<Vec<Box<dyn Tool>>>,/// Callable-tool whitelist (empty = every visible tool).pub visible_tool_names: HashSet<String>,/// Model-call cap for the loop.@@ -110,7 +118,10 @@ pub(crate) async fn run_chat_turn_graph(graph: ChatTurnGraph) -> Result<Tinyagenprovider_id,&graph.model,graph.messages,- vec![graph.tools],+ // Synthesised set first: registration de-duplicates by name on a+ // first-wins basis, so a freshly synthesised delegate takes+ // precedence over any same-named instance in the durable registry.+ vec![graph.synthesized_tools, graph.tools],visible_tool_names,graph.max_iterations,// Mirror the harness event stream onto this session's progress sink.diff --git a/src/openhuman/agent/harness/session/turn/tools.rs b/src/openhuman/agent/harness/session/turn/tools.rsindex 73235b1348..647c9213b3 100644--- a/src/openhuman/agent/harness/session/turn/tools.rs+++ b/src/openhuman/agent/harness/session/turn/tools.rs@@ -7,6 +7,14 @@ use crate::openhuman::agent::progress::AgentProgress;use std::sync::Arc;+/// One turn's tool inputs: the durable registry, the synthesised delegation+/// set, and the callable-name allowlist. See [`Agent::turn_tool_sets`].+type TurnToolSets = (+ Arc<Vec<Box<dyn crate::openhuman::tools::Tool>>>,+ Arc<Vec<Box<dyn crate::openhuman::tools::Tool>>>,+ std::collections::HashSet<String>,+);+impl Agent {// ─────────────────────────────────────────────────────────────────// Sub-agent context snapshots@@ -86,6 +94,32 @@ impl Agent {}}+ /// The tool sets and callable-name allowlist for one turn.+ ///+ /// Returns `(durable tools, synthesised delegation tools, visible names)`.+ /// The two tool sets stay separate all the way to dispatch — see+ /// [`Agent::synthesized_tools`] for why they are not one `Arc`.+ ///+ /// `suppress_tools` is the per-turn scope override (#1725): a chat /+ /// small-talk turn runs with an EMPTY tool set, so the provider request+ /// carries no tool schema and the model answers in a single call. The+ /// agent's durable fields are left untouched either way — the next+ /// un-overridden turn gets the full toolbelt back.+ pub(super) fn turn_tool_sets(&self, suppress_tools: bool) -> TurnToolSets {+ if suppress_tools {+ return (+ Arc::new(Vec::new()),+ Arc::new(Vec::new()),+ std::collections::HashSet::new(),+ );+ }+ (+ Arc::clone(&self.tools),+ Arc::clone(&self.synthesized_tools),+ self.visible_tool_names.clone(),+ )+ }+/// Emit a lifecycle progress event. Uses `send().await` so control/// events (turn/iteration boundaries, tool_call_started/completed,/// turn_completed) survive downstream backpressure from the@@ -277,33 +311,32 @@ impl Agent {new_hash);- let prev_integrations = std::mem::replace(&mut self.connected_integrations, cache_view);- if self.refresh_delegation_tools() {- self.last_seen_integrations_hash = new_hash;- self.connected_integrations_initialized = true;- // Surface newly-connected toolkits onto the next user message so- // the model acts on them on the FIRST post-connect ask instead of- // refusing from stale chat context. Schema-only refresh already- // updated the enum; this closes the prose/decision gap.- let connected_slugs: Vec<String> = self- .connected_integrations- .iter()- .map(|i| i.toolkit.clone())- .collect();- // Append (don't overwrite) so a second connect before the next- // user turn doesn't drop the first one's announcement. Slugs are- // already de-duped against `announced_integrations`, but guard the- // pending list too in case the same slug is re-queued.- for slug in newly_connected_slugs(&connected_slugs, &mut self.announced_integrations) {- if !self.pending_integration_announcement.contains(&slug) {- self.pending_integration_announcement.push(slug);- }+ // No rollback path: `refresh_delegation_tools` reconciles the specs and+ // the executable instances in one pass and cannot half-apply, so there+ // is no failed state to restore `connected_integrations` from.+ self.connected_integrations = cache_view;+ self.refresh_delegation_tools();+ self.last_seen_integrations_hash = new_hash;+ self.connected_integrations_initialized = true;+ // Surface newly-connected toolkits onto the next user message so+ // the model acts on them on the FIRST post-connect ask instead of+ // refusing from stale chat context. The refresh above already+ // updated the enum; this closes the prose/decision gap.+ let connected_slugs: Vec<String> = self+ .connected_integrations+ .iter()+ .map(|i| i.toolkit.clone())+ .collect();+ // Append (don't overwrite) so a second connect before the next+ // user turn doesn't drop the first one's announcement. Slugs are+ // already de-duped against `announced_integrations`, but guard the+ // pending list too in case the same slug is re-queued.+ for slug in newly_connected_slugs(&connected_slugs, &mut self.announced_integrations) {+ if !self.pending_integration_announcement.contains(&slug) {+ self.pending_integration_announcement.push(slug);}- true- } else {- self.connected_integrations = prev_integrations;- false}+ true}/// Reconcile the tracked installed-skill set ([`Self::workflows`]) against@@ -501,37 +534,41 @@ impl Agent {/// [`Self::last_seen_integrations_hash`] vs./// [`crate::openhuman::integrations::composio::cached_active_integrations`]).///- /// **Shared-Arc behavior**: when `self.tools` is currently shared- /// (e.g. an in-flight turn cloned the Arc into its tool source), we- /// still refresh `self.tool_specs` / `self.visible_tool_specs` so the- /// provider-facing schema updates immediately. The executable tool- /// registry is refreshed only when `self.tools` has unique ownership.- /// This keeps same-turn routing unblocked while preserving ownership- /// safety for non-cloneable `Box<dyn Tool>` values.+ /// **Concurrency**: this cannot fail on a shared session. The synthesised+ /// instances live in their own [`Agent::synthesized_tools`] `Arc`, which is+ /// *replaced* rather than mutated in place — so an in-flight turn or a+ /// spawned sub-agent holding a clone never blocks reconciliation. Those+ /// readers keep the previous, self-consistent set for the rest of their+ /// turn; the superseded instances are freed when the last of them drops.+ ///+ /// This is what makes the schema and the executable surface inseparable.+ /// Reconciling into `self.tools` instead required `Arc::get_mut`, which+ /// fails under exactly that sharing — and the old code proceeded to publish+ /// the new `tool_specs` anyway, advertising `delegate_*` tools to the+ /// provider that were registered nowhere (#6145).///- /// **Return value** — `true` when schema reconciliation succeeded (or- /// no reconcile was needed). Returns `false` only when a non-shared- /// reconcile path failed unexpectedly.- pub fn refresh_delegation_tools(&mut self) -> bool {+ /// Returns nothing: with the synthesised set held in its own `Arc` there is+ /// no longer a way for this to half-apply, so the `bool` it used to hand+ /// back — and the caller rollback keyed on it — had no reachable `false`.+ pub fn refresh_delegation_tools(&mut self) {use crate::openhuman::agent::harness::definition::AgentDefinitionRegistry;use crate::openhuman::tools::orchestrator_tools::collect_orchestrator_tools;let Some(reg) = AgentDefinitionRegistry::global() else {// No registry — there's nothing we can do until the// registry is initialised. The agent's surface stays at- // whatever the builder produced; callers can safely treat- // this as "no reconcile needed right now".- return true;+ // whatever the builder produced.+ return;};let Some(def) = reg.get(&self.agent_definition_id) else {log::debug!("[agent] refresh_delegation_tools: definition '{}' not in registry — skipping",self.agent_definition_id);- return true;+ return;};if def.subagents.is_empty() {- return true;+ return;}let synthed = collect_orchestrator_tools(def, reg, &self.connected_integrations);@@ -542,17 +579,17 @@ impl Agent {// Skip mutation when neither the previous nor the next synthesis// produced any names — saves work on agents without dynamic- // delegation.+ // delegation. `synthesized_tools` is already empty in that state, so+ // there is nothing to publish either.if self.synthesized_tool_names.is_empty() && synthed_names.is_empty() {- return true;+ return;}// Mask of the previous synthesis — the names whose `tool_specs` are// currently live (this set is kept in lock-step with `tool_specs`).let old_synth = std::mem::take(&mut self.synthesized_tool_names);- // `tool_specs` are plain data and therefore cloneable; we can always- // reconcile schema even when the Arc is shared. Drop exactly the+ // `tool_specs` are plain data and therefore cloneable. Drop exactly the// previous synthesised spec set, then append the fresh one.{let specs_vec = Arc::make_mut(&mut self.tool_specs);@@ -560,37 +597,20 @@ impl Agent {specs_vec.extend(synthed_specs);}- // `tools` contains non-cloneable trait objects. Reconcile it only when- // uniquely owned. The set of stale synthesised *instances* to drop is- // the previous synthesis (`old_synth`) plus any instances a prior- // shared-Arc refresh couldn't remove (`pending_synthesized_tools_mask`).- let tools_remove_mask: std::collections::HashSet<String> = old_synth- .iter()- .chain(self.pending_synthesized_tools_mask.iter())- .cloned()- .collect();- let tools_reconciled = if let Some(tools_vec) = Arc::get_mut(&mut self.tools) {- tools_vec.retain(|t| !tools_remove_mask.contains(t.name()));- tools_vec.extend(synthed);- // `tools` now matches `tool_specs` exactly — nothing pending.- self.pending_synthesized_tools_mask.clear();- true- } else {- // Schema (`tool_specs`) was updated to the new set, but the stale- // tool *instances* still sit in `self.tools`. Record their names- // so the next unique-owner refresh removes them. Crucially we do- // NOT roll `synthesized_tool_names` back to `old_synth` here — that- // would desync it from `tool_specs` and cause duplicate specs on- // the following refresh (#3044).- self.pending_synthesized_tools_mask = tools_remove_mask;- log::warn!(- "[agent] refresh_delegation_tools: tools Arc is shared — refreshed schema only \- ({} synthesised tool name(s)); {} stale tool instance(s) pending removal on the next unique-owner refresh",- synthed_names.len(),- self.pending_synthesized_tools_mask.len()- );- false- };+ // The executable instances are replaced wholesale. `synthed` already IS+ // the complete new set — `collect_orchestrator_tools` rebuilds every+ // delegate from the current connection set — so there is nothing to+ // retain and no mask to apply: assigning a fresh `Arc` drops exactly+ // the previous synthesis and nothing else.+ //+ // This is the step that used to be conditional on `Arc::get_mut`+ // succeeding against `self.tools`. It no longer touches `self.tools` at+ // all, so a concurrent reader cannot block it, and the specs above can+ // never advertise an instance that was dropped on the floor (#6145).+ // Readers still holding the previous `Arc` keep a coherent set for the+ // rest of their turn; those instances are freed when the last one goes.+ let previous_instances = self.synthesized_tools.len();+ self.synthesized_tools = Arc::new(synthed);// `visible_tool_names` carries an explicit allowlist for// [`ToolScope::Named`] agents. Drop the previously-synthesised@@ -639,21 +659,18 @@ impl Agent {.cloned().collect();- // `tool_specs` always reconciled to the new set, so the name mask must- // track that set unconditionally — whether or not `tools` (the- // executable instances) could be reconciled this pass.+ // Specs and instances reconciled to the same set in the same pass, so+ // the name mask tracks that set unconditionally.self.synthesized_tool_names = synthed_names.clone();log::info!(- "[agent] refresh_delegation_tools: reconciled delegation schema for agent '{}' (display='{}'); now {} synthesised tool name(s); added={:?} removed={:?} tools_reconciled={} pending_tool_instances={}",+ "[agent] refresh_delegation_tools: reconciled delegation surface for agent '{}' (display='{}'); now {} synthesised tool name(s); added={:?} removed={:?} superseded_instances={}",self.agent_definition_id,self.agent_definition_name,synthed_names.len(),added,removed,- tools_reconciled,- self.pending_synthesized_tools_mask.len()+ previous_instances);- true}}diff --git a/src/openhuman/agent/harness/session/types.rs b/src/openhuman/agent/harness/session/types.rsindex 1433c2a0b3..3adfb6a46f 100644--- a/src/openhuman/agent/harness/session/types.rs+++ b/src/openhuman/agent/harness/session/types.rs@@ -75,9 +75,36 @@ pub struct Agent {/// set per turn (issue #4249, Phase 3 / Motion A). Replaces the raw/// `Arc<dyn Provider>`; the harness names crate model types only.pub(super) turn_model_source: TurnModelSource,- /// Full tool registry. Sub-agents pull from this via- /// [`ParentExecutionContext::all_tools`].+ /// Durable tool registry — everything the session was built with.+ /// Sub-agents pull from this via [`ParentExecutionContext::all_tools`].+ ///+ /// Fixed for the life of the agent: the synthesised delegation surface,+ /// which *does* change mid-session, lives in [`Self::synthesized_tools`]+ /// instead. See that field for why.pub(super) tools: Arc<Vec<Box<dyn Tool>>>,+ /// The delegation tools synthesised for the current connection set —+ /// `delegate_<toolkit>` skill tools and archetype delegates, produced by+ /// [`crate::openhuman::tools::orchestrator_tools::collect_orchestrator_tools`].+ ///+ /// Held apart from [`Self::tools`] because it is the only part of the+ /// surface that changes mid-session, and `Box<dyn Tool>` is not cloneable:+ /// reconciling it *inside* `tools` meant `Arc::get_mut`, which fails+ /// whenever any reader holds a clone (an in-flight turn, a spawned+ /// sub-agent's `ParentExecutionContext`). The old code then updated+ /// `tool_specs` anyway and dropped the fresh instances on the floor, so the+ /// provider was advertised a `delegate_*` tool that no longer existed in+ /// any registered tool set — the model called it and got "unknown tool"+ /// (#6145).+ ///+ /// Because these instances are regenerated from scratch on every refresh,+ /// this `Arc` can always be *replaced* wholesale — no unique ownership+ /// required, so reconciliation cannot fail. Readers holding the previous+ /// `Arc` keep a consistent view for the rest of their turn, and the+ /// superseded instances are freed once the last of them drops.+ ///+ /// Spliced ahead of `tools` at dispatch, so name de-duplication prefers a+ /// freshly synthesised instance. Empty for agents that do not delegate.+ pub(super) synthesized_tools: Arc<Vec<Box<dyn Tool>>>,/// Full tool specs — sub-agents receive these via/// [`ParentExecutionContext::all_tool_specs`].pub(super) tool_specs: Arc<Vec<ToolSpec>>,@@ -431,41 +458,26 @@ pub struct Agent {/// closest available signal to "session is ending") to finalize the/// trailing open segment with an LLM recap + embedding.pub(super) archivist_hook: Option<Arc<ArchivistHook>>,- /// Names of every tool currently in [`Agent::tools`] that was+ /// Names of every tool currently in [`Agent::synthesized_tools`] — those/// produced by [`crate::openhuman::tools::orchestrator_tools::collect_orchestrator_tools`]/// (i.e. `delegate_<toolkit>` skill tools and archetype-delegation/// tools like `delegate_archivist`). Tracked so/// [`Agent::refresh_delegation_tools`] can drop the entire- /// previously-synthesised subset on each refresh and append the- /// fresh set — without that mask we'd risk either leaking stale- /// `delegate_<toolkit>` entries on revoke or accidentally removing+ /// previously-synthesised subset of [`Agent::tool_specs`] on each refresh+ /// and append the fresh set — without that mask we'd risk either leaking+ /// stale `delegate_<toolkit>` specs on revoke or accidentally removing/// direct tools (`query_memory`, `cron_add`, …) that share a name/// prefix.////// Populated by `refresh_delegation_tools` itself; empty at/// construction time.///- /// Invariant: this tracks the names whose **`tool_specs`** are currently- /// live. `tool_specs` reconcile on every refresh (they're cloneable- /// data), so this set always equals the most recent synthesised set —- /// even when the executable `tools` Vec could not be reconciled because- /// its `Arc` was shared. Removing stale `tools` entries is tracked- /// separately by [`Self::pending_synthesized_tools_mask`].+ /// Invariant: this set is the name mask for **both** [`Self::tool_specs`]'+ /// synthesised half and [`Self::synthesized_tools`], which reconcile+ /// together on every refresh. There is no longer a case where one advances+ /// without the other — the schema and the executable instances cannot+ /// drift (#6145).pub(super) synthesized_tool_names: std::collections::HashSet<String>,- /// Names of synthesised tool *instances* still present in [`Agent::tools`]- /// that a future unique-owner refresh must drop.- ///- /// When `refresh_delegation_tools` updates `tool_specs` but cannot- /// reconcile `tools` (the `Arc` is shared — the normal case while- /// `AgentToolSource` holds a clone during `before_dispatch`), the- /// previously-synthesised tool objects remain in `tools`. Their names are- /// accumulated here so the next refresh that *does* own `tools` uniquely- /// removes them — instead of overloading `synthesized_tool_names` (which- /// must stay in sync with `tool_specs`) and corrupting the spec- /// reconciliation on the following refresh (duplicate `ToolSpec`s, #3044).- ///- /// Empty at construction time and whenever `tools` is fully reconciled.- pub(super) pending_synthesized_tools_mask: std::collections::HashSet<String>,/// Overrides applied to the **next** [`Agent::turn`] call, then reset.////// Defaults to [`TurnOverrides::default`] (no suppression), so an agentdiff --git a/src/openhuman/agent/prompts/types.rs b/src/openhuman/agent/prompts/types.rsindex c2869a0eb0..b9bd1dec8b 100644--- a/src/openhuman/agent/prompts/types.rs+++ b/src/openhuman/agent/prompts/types.rs@@ -257,8 +257,20 @@ impl<'a> PromptTool<'a> {/// Adapt a `Box<dyn Tool>` slice into a `Vec<PromptTool<'_>>`.pub fn from_tools(tools: &'a [Box<dyn Tool>]) -> Vec<PromptTool<'a>> {+ Self::from_tool_refs(tools.iter().map(|t| t.as_ref()))+ }++ /// Adapt any iterator of borrowed tools into a `Vec<PromptTool<'_>>`.+ ///+ /// An agent's callable surface is not one contiguous slice: the durable+ /// registry and the freshly-synthesised delegation set live in separate+ /// `Arc`s (see `Agent::synthesized_tools`), and the prompt catalogue must+ /// render both. Taking an iterator lets the caller chain them without+ /// materialising a combined `Vec<Box<dyn Tool>>` — which is impossible+ /// anyway, since `Box<dyn Tool>` is not cloneable.+ pub fn from_tool_refs(tools: impl IntoIterator<Item = &'a dyn Tool>) -> Vec<PromptTool<'a>> {tools- .iter()+ .into_iter().map(|t| PromptTool {name: t.name(),description: t.description(),diff --git a/src/openhuman/mcp/server/tools/dispatch.rs b/src/openhuman/mcp/server/tools/dispatch.rsindex a840850af4..4c9a139c20 100644--- a/src/openhuman/mcp/server/tools/dispatch.rs+++ b/src/openhuman/mcp/server/tools/dispatch.rs@@ -215,7 +215,7 @@ async fn build_orchestrator_agent() -> Result<Agent, ToolCallError> {ToolCallError::Internal(format!("failed to build orchestrator agent: {err}"))})?;agent.fetch_connected_integrations().await;- let _ = agent.refresh_delegation_tools();+ agent.refresh_delegation_tools();Ok(agent)}@@ -330,7 +330,7 @@ async fn run_subagent_tool(params: &Map<String, Value>) -> Result<Value, ToolCal"mcp_server",);agent.fetch_connected_integrations().await;- let _ = agent.refresh_delegation_tools();+ agent.refresh_delegation_tools();// The MCP server surface exposes openhuman agents to remote MCP// clients. Treat callers as ExternalChannel — their prompt text isdiff --git a/src/openhuman/platform/socket/medulla/mod.rs b/src/openhuman/platform/socket/medulla/mod.rsindex 0d484ba9b6..ff5d23f61c 100644--- a/src/openhuman/platform/socket/medulla/mod.rs+++ b/src/openhuman/platform/socket/medulla/mod.rs@@ -410,7 +410,7 @@ async fn build_agent(agent_id: &str, task_id: &str, session_id: &str) -> Result<// per-thread `set_agent_definition_name`).agent.set_agent_definition_name(medulla_session_key(agent_id, session_id));agent.fetch_connected_integrations().await;- let _ = agent.refresh_delegation_tools();+ agent.refresh_delegation_tools();Ok(agent)}diff --git a/src/openhuman/tools/agent_policy/engine.rs b/src/openhuman/tools/agent_policy/engine.rsindex c58785f828..08e92247ce 100644--- a/src/openhuman/tools/agent_policy/engine.rs+++ b/src/openhuman/tools/agent_policy/engine.rs@@ -19,6 +19,33 @@ impl ToolPolicyEngine {channel_permissions: &HashMap<String, String>,tools: &[Box<dyn Tool>],visible_tool_names: &HashSet<String>,+ ) -> super::ToolPolicySession {+ let tools: Vec<&dyn Tool> = tools.iter().map(|t| t.as_ref()).collect();+ Self::build_session_from_refs(+ agent_id,+ channel,+ entrypoint,+ channel_permissions,+ &tools,+ visible_tool_names,+ )+ }++ /// [`Self::build_session`] over a borrowed tool set that need not be one+ /// contiguous slice.+ ///+ /// A session agent's callable surface is split across two `Arc`s — the+ /// durable registry and the freshly-synthesised delegation set (see+ /// `Agent::synthesized_tools`). Both must be classified, or a delegate tool+ /// the model can see and call would carry no policy decision at all and+ /// fall through the per-channel permission gate.+ pub fn build_session_from_refs(+ agent_id: impl Into<String>,+ channel: impl Into<String>,+ entrypoint: impl Into<String>,+ channel_permissions: &HashMap<String, String>,+ tools: &[&dyn Tool],+ visible_tool_names: &HashSet<String>,) -> super::ToolPolicySession {let channel = channel.into();let allowed_permission = permission_for_channel(channel_permissions, &channel);