Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(agent): keep synthesised delegates out of the durable registry\n\nReview follow-up for #6162 (CodeRabbit precedence finding + the\nmaintainer's correction on #6145).\n\nThe synthesised delegation set and the durable registry were ordered\ndifferently on different surfaces: `tool_specs` (and the first-wins\nspec dedup) listed durable tools first, while turn dispatch registered\nthe synthesised set first. A durable tool that owned a delegate's name\nwas therefore advertised under its own schema and executed as the\ndelegate. The ordering was also load-bearing for a reason the PR did\nnot state: `from_config` still appended the build-time delegates into\n`tools`, so after the first refresh the durable Arc held stale delegate\ninstances that only the synthesised-first order kept off the wire —\nand that the prompt catalogue listed twice.\n\n- `AgentBuilder::synthesized_tools`: the factory hands the build-time\n delegates to the builder as their own set; `build()` keeps them in\n `Agent::synthesized_tools`, advertises them, classifies them in the\n policy session and seeds the refresh mask. `Agent::tools` never holds\n a delegate again.\n- `builder::drop_synthesized_name_collisions`: a synthesised name a\n durable tool already owns is dropped, at build time and on every\n refresh, so the two sets are disjoint by construction and a durable\n tool wins on every surface. Filtering before the mask also closes a\n latent bug: the unfiltered mask let the next refresh's spec `retain`\n withdraw the durable tool's own spec.\n- Dispatch enumerates durable then synthesised, the same order as\n `tool_specs` and `Agent::all_tool_refs`.\n- `pformat::build_registry_from_refs` so the P-Format registry still\n covers both sets.\n- Docs and the PR narrative corrected per the maintainer's trace: the\n connect direction was invisible (the fail-closed policy filter hid the\n spec-without-instance), the revoke direction left a withdrawn\n delegate registered and callable. `AgentToolSource` mentions removed.\n\nTests: revoke-direction regression (instance and policy decision go\nwith the spec while an in-flight turn holds clones), durable-name\ncollision across refreshes, builder split, and `from_config` wiring.\nThe shared invariant helper now also asserts the two sets are disjoint\nand that every synthesised tool carries a policy decision.\n

Shanu92b661750a97
diff --git a/src/openhuman/agent/harness/fork_context.rs b/src/openhuman/agent/harness/fork_context.rs
index 1238142329..1b7e9d1d84 100644
--- a/src/openhuman/agent/harness/fork_context.rs
+++ b/src/openhuman/agent/harness/fork_context.rs
@@ -49,9 +49,13 @@ pub struct ParentExecutionContext {
/// per-archetype before handing it to the sub-agent's tool loop.
pub all_tools: Arc<Vec<Box<dyn Tool>>>,
- /// Pre-serialised tool specs matching `all_tools`. Captured at
- /// turn-start so sub-agents can pass byte-identical schemas to the
- /// provider for prefix-cache reuse.
+ /// Pre-serialised tool specs. Captured at turn-start so sub-agents can
+ /// pass byte-identical schemas to the provider for prefix-cache reuse.
+ ///
+ /// `all_tool_specs[i]` describes `all_tools[i]` for every durable index;
+ /// the parent's synthesised delegation specs follow at the tail with no
+ /// instance here, since a sub-agent is never handed a `delegate_*` tool
+ /// (#4452). Index into this only with indices taken from `all_tools`.
pub all_tool_specs: Arc<Vec<ToolSpec>>,
/// Names of the tools the parent actually advertises and will execute this
diff --git a/src/openhuman/agent/harness/session/builder/builder_tests_part_01_tests.rs b/src/openhuman/agent/harness/session/builder/builder_tests_part_01_tests.rs
index e0e2b10891..da19eea8ad 100644
--- a/src/openhuman/agent/harness/session/builder/builder_tests_part_01_tests.rs
+++ b/src/openhuman/agent/harness/session/builder/builder_tests_part_01_tests.rs
@@ -648,3 +648,51 @@ async fn from_config_for_agent_synthesizes_custom_registry_entry_with_named_scop
"a tool outside the custom agent's allowlist must not be visible: {visible:?}"
);
}
+
+/// `from_config` hands the build-time delegation tools to the builder's
+/// synthesised set rather than folding them into the durable registry.
+///
+/// Before #6145 the factory appended them to `tools`, so the first
+/// `refresh_delegation_tools` — which replaces `Agent::synthesized_tools` and
+/// never touches `tools` — would have left the build-time instances behind:
+/// duplicated in the prompt catalogue next to their fresh replacements, and
+/// only kept off the dispatch path by set ordering.
+#[test]
+fn from_config_keeps_build_time_delegation_tools_out_of_the_durable_registry() {
+ crate::openhuman::memory::host_impls::install_for_tests();
+ crate::openhuman::agent::harness::AgentDefinitionRegistry::init_global_builtins().unwrap();
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let agent = crate::openhuman::agent::Agent::from_config_for_agent(&config, "orchestrator")
+ .expect("orchestrator session build");
+
+ let synthesized: Vec<String> = agent
+ .synthesized_tools_arc()
+ .iter()
+ .map(|tool| tool.name().to_string())
+ .collect();
+ assert!(
+ !synthesized.is_empty(),
+ "the orchestrator declares sub-agents, so the factory must synthesise delegates"
+ );
+ for name in &synthesized {
+ assert!(
+ agent.tools().iter().all(|tool| tool.name() != name),
+ "build-time delegate `{name}` must not also sit in the durable registry"
+ );
+ assert!(
+ agent.tool_specs().iter().any(|spec| &spec.name == name),
+ "build-time delegate `{name}` must be advertised"
+ );
+ assert!(
+ agent.tool_policy_session.decisions.contains_key(name),
+ "build-time delegate `{name}` must carry a policy decision"
+ );
+ }
+ let expected_mask: std::collections::HashSet<String> = synthesized.iter().cloned().collect();
+ assert_eq!(
+ agent.synthesized_tool_names, expected_mask,
+ "the refresh mask must be seeded with exactly the synthesised names"
+ );
+}
diff --git a/src/openhuman/agent/harness/session/builder/factory.rs b/src/openhuman/agent/harness/session/builder/factory.rs
index acb0a5835a..2e443c046f 100644
--- a/src/openhuman/agent/harness/session/builder/factory.rs
+++ b/src/openhuman/agent/harness/session/builder/factory.rs
@@ -983,20 +983,10 @@ impl Agent {
agent_id,
);
- // De-duplicate: some synthesised tool names may collide with
- // already-registered tools (unlikely for `delegate_*` names but
- // cheap to guard against).
- let existing_names: std::collections::HashSet<String> =
- tools.iter().map(|t| t.name().to_string()).collect();
- let inserted_delegation_tools: Vec<Box<dyn Tool>> = delegation_tools
- .into_iter()
- .filter(|t| !existing_names.contains(t.name()))
- .collect();
- let synthesized_tool_names: std::collections::HashSet<String> = inserted_delegation_tools
- .iter()
- .map(|t| t.name().to_string())
- .collect();
- tools.extend(inserted_delegation_tools);
+ // The delegation tools stay beside the durable registry rather than
+ // inside it: the builder holds them in `Agent::synthesized_tools`,
+ // drops any name a durable tool already owns, and
+ // `refresh_delegation_tools` replaces the whole set later (#6145).
// Pre-fetch Critical + High priority tool-scoped memory rules so they
// pin into the (compression-resistant) system prompt for the whole
@@ -1007,8 +997,11 @@ impl Agent {
// or when the runtime cannot host a synchronous bridge (single-threaded
// test harnesses).
if config.learning.enabled && config.learning.tool_memory_capture_enabled {
- let agent_tool_names: Vec<String> =
- tools.iter().map(|t| t.name().to_string()).collect();
+ let agent_tool_names: Vec<String> = tools
+ .iter()
+ .chain(delegation_tools.iter())
+ .map(|t| t.name().to_string())
+ .collect();
let pinned = prefetch_tool_memory_rules_blocking(memory.clone(), &agent_tool_names);
if !pinned.is_empty() {
log::info!(
@@ -1023,7 +1016,12 @@ impl Agent {
// (including orchestrator tools) so every tool gets a signature
// entry. The registry is self-contained — it doesn't hold a
// reference back into the tools Vec.
- let pformat_registry = crate::openhuman::agent::pformat::build_registry(&tools);
+ let pformat_registry = crate::openhuman::agent::pformat::build_registry_from_refs(
+ tools
+ .iter()
+ .chain(delegation_tools.iter())
+ .map(|t| t.as_ref()),
+ );
let dispatcher_kind =
resolve_dispatcher_kind(&dispatcher_choice, supports_native, agent_id);
let tool_dispatcher: Box<dyn crate::openhuman::agent::dispatcher::ToolDispatcher> =
@@ -1188,6 +1186,7 @@ impl Agent {
let mut builder = Agent::builder()
.crate_native_provider(provider_role, Arc::clone(&base_config))
.tools(tools)
+ .synthesized_tools(delegation_tools)
.visible_tool_names(visible)
.memory(memory)
.shared_experience_memory(shared_experience_memory)
@@ -1251,7 +1250,6 @@ impl Agent {
crate::openhuman::integrations::composio::connected_set_hash(
&agent.connected_integrations,
);
- agent.synthesized_tool_names = synthesized_tool_names;
Ok(agent)
}
}
diff --git a/src/openhuman/agent/harness/session/builder/mod.rs b/src/openhuman/agent/harness/session/builder/mod.rs
index 235b267fcd..ad788c919a 100644
--- a/src/openhuman/agent/harness/session/builder/mod.rs
+++ b/src/openhuman/agent/harness/session/builder/mod.rs
@@ -15,7 +15,7 @@ mod builder_tests;
use crate::openhuman::agent::harness::definition::{AgentDefinition, ToolScope};
use crate::openhuman::tools::agent_policy::ToolPolicySession;
-use crate::openhuman::tools::ToolSpec;
+use crate::openhuman::tools::{Tool, ToolSpec};
/// Drop entries with duplicate `name` fields, first occurrence wins.
///
@@ -51,6 +51,41 @@ pub(crate) fn dedup_visible_tool_specs(specs: Vec<ToolSpec>) -> Vec<ToolSpec> {
deduped
}
+/// Drop every synthesised delegation tool whose name a durable tool already
+/// owns.
+///
+/// The durable registry and the synthesised set are advertised, classified and
+/// dispatched as one surface, and every reader resolves a name to its first
+/// match with the durable set enumerated first. A synthesised entry that
+/// collides can therefore never be reached — keeping it would put one tool's
+/// schema on the wire and run another's (a `delegate_name = "research"`
+/// beside a same-named skill tool, #1710). Applied when the session is built
+/// and again on every refresh, so the two sets are disjoint by construction
+/// and a collision resolves the same way at both sites.
+pub(crate) fn drop_synthesized_name_collisions(
+ durable: &[Box<dyn Tool>],
+ synthesized: Vec<Box<dyn Tool>>,
+) -> Vec<Box<dyn Tool>> {
+ let taken: std::collections::HashSet<&str> = durable.iter().map(|t| t.name()).collect();
+ let mut kept: Vec<Box<dyn Tool>> = Vec::with_capacity(synthesized.len());
+ let mut dropped: Vec<String> = Vec::new();
+ for tool in synthesized {
+ if taken.contains(tool.name()) {
+ dropped.push(tool.name().to_string());
+ } else {
+ kept.push(tool);
+ }
+ }
+ if !dropped.is_empty() {
+ log::warn!(
+ "[agent] dropped {} synthesised delegation tool(s) whose name a durable tool already owns: {:?}",
+ dropped.len(),
+ dropped
+ );
+ }
+ kept
+}
+
pub(super) fn visible_tool_specs_for_policy(
tool_specs: &[ToolSpec],
visible_names: &std::collections::HashSet<String>,
diff --git a/src/openhuman/agent/harness/session/builder/setters.rs b/src/openhuman/agent/harness/session/builder/setters.rs
index df883ac38a..8d7e7ba5d9 100644
--- a/src/openhuman/agent/harness/session/builder/setters.rs
+++ b/src/openhuman/agent/harness/session/builder/setters.rs
@@ -20,6 +20,7 @@ impl AgentBuilder {
Self {
turn_model_source: None,
tools: None,
+ synthesized_tools: None,
visible_tool_names: None,
subagent_tool_ceiling_names: None,
memory: None,
@@ -94,6 +95,14 @@ impl AgentBuilder {
self
}
+ /// Sets the delegation tools synthesised for the session's initial
+ /// connection set — see [`Agent::synthesized_tools`]. A name a durable
+ /// tool already owns is dropped in [`Self::build`]. Defaults to none.
+ pub fn synthesized_tools(mut self, tools: Vec<Box<dyn Tool>>) -> Self {
+ self.synthesized_tools = Some(tools);
+ self
+ }
+
/// Restricts which tools the main agent can see and call directly.
/// Tools not in this set are still available to sub-agents via the
/// runner. Pass `None` (default) to make all tools visible.
@@ -460,7 +469,23 @@ impl AgentBuilder {
let tools = self
.tools
.ok_or_else(|| anyhow::anyhow!("tools are required"))?;
- let tool_specs: Vec<ToolSpec> = tools.iter().map(|tool| tool.spec()).collect();
+ // The synthesised set lives beside the durable registry, never inside
+ // it (`Agent::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_tool_names: std::collections::HashSet<String> = synthesized_tools
+ .iter()
+ .map(|tool| tool.name().to_string())
+ .collect();
+ // Durable specs first, synthesised after: the order every reader of
+ // the two sets enumerates them in (`Agent::all_tool_refs`, dispatch).
+ let tool_specs: Vec<ToolSpec> = tools
+ .iter()
+ .chain(synthesized_tools.iter())
+ .map(|tool| tool.spec())
+ .collect();
let mut visible_names = self.visible_tool_names.unwrap_or_default();
// Resolved here rather than at its historical position below: the pack
@@ -476,7 +501,11 @@ impl AgentBuilder {
// advertised surface shrinks. Applied here, before the policy filter,
// so the visible set and the policy session cannot disagree.
if visible_names.is_empty() {
- visible_names = tools.iter().map(|tool| tool.name().to_string()).collect();
+ visible_names = tools
+ .iter()
+ .chain(synthesized_tools.iter())
+ .map(|tool| tool.name().to_string())
+ .collect();
}
crate::openhuman::tools::toolpacks::strip_packed_from_visible(
&mut visible_names,
@@ -491,12 +520,18 @@ impl AgentBuilder {
.event_channel
.clone()
.unwrap_or_else(|| "internal".to_string());
- let tool_policy_session = ToolPolicyEngine::build_session(
+ // Classify both sets: a synthesised delegate needs a decision too.
+ let all_tools: Vec<&dyn Tool> = tools
+ .iter()
+ .chain(synthesized_tools.iter())
+ .map(|tool| tool.as_ref())
+ .collect();
+ let tool_policy_session = ToolPolicyEngine::build_session_from_refs(
&agent_definition_name,
&event_channel,
"session",
&config.channel_permissions,
- &tools,
+ &all_tools,
&visible_names,
);
@@ -510,12 +545,12 @@ impl AgentBuilder {
// `tool_policy_session` marks both channel-blocked and role-hidden tools
// as restricted, so deriving the child ceiling from it would reintroduce
// exactly that conflation.
- let channel_policy_session = ToolPolicyEngine::build_session(
+ let channel_policy_session = ToolPolicyEngine::build_session_from_refs(
&agent_definition_name,
&event_channel,
"session",
&config.channel_permissions,
- &tools,
+ &all_tools,
&std::collections::HashSet::new(),
);
let mut subagent_tool_ceiling_names = self.subagent_tool_ceiling_names.unwrap_or_default();
@@ -605,9 +640,7 @@ 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()),
+ synthesized_tools: Arc::new(synthesized_tools),
tool_specs: Arc::new(tool_specs),
visible_tool_specs: Arc::new(visible_tool_specs),
visible_tool_names: visible_names,
@@ -705,7 +738,7 @@ impl AgentBuilder {
pending_skill_announcement: Vec::new(),
pending_skill_retraction: Vec::new(),
archivist_hook: self.archivist_hook,
- synthesized_tool_names: std::collections::HashSet::new(),
+ synthesized_tool_names,
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.rs
index 0363bf6249..55b829f2e3 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
@@ -70,8 +70,9 @@ impl Agent {
Arc::clone(&self.synthesized_tools)
}
- /// Every tool this agent can execute: the durable registry plus the
- /// synthesised delegation set.
+ /// Every tool this agent can execute: the durable registry first, then the
+ /// synthesised delegation set — the same order as [`Self::tool_specs`] and
+ /// turn dispatch.
///
/// 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
diff --git a/src/openhuman/agent/harness/session/session_tests.rs b/src/openhuman/agent/harness/session/session_tests.rs
index fe86cdfeff..f8f8f9a687 100644
--- a/src/openhuman/agent/harness/session/session_tests.rs
+++ b/src/openhuman/agent/harness/session/session_tests.rs
@@ -176,6 +176,16 @@ fn _assert_builder_is_exported() -> AgentBuilder {
/// built `Agent` so individual tests can assert against the
/// [`Agent::agent_definition_name`] accessor.
fn build_minimal_agent_with_definition_name(definition_name: Option<&str>) -> Agent {
+ build_minimal_agent_with_tool_sets(vec![Box::new(MockTool)], Vec::new(), definition_name)
+}
+
+/// [`build_minimal_agent_with_definition_name`] with caller-chosen durable and
+/// synthesised tool sets, for the tests that pin how the two sets relate.
+fn build_minimal_agent_with_tool_sets(
+ tools: Vec<Box<dyn Tool>>,
+ synthesized_tools: Vec<Box<dyn Tool>>,
+ definition_name: Option<&str>,
+) -> Agent {
// The embedding seam fails loudly when unwired; before the memory
// extraction this was a direct call and needed no setup.
crate::openhuman::memory::host_impls::install_for_tests();
@@ -195,7 +205,8 @@ fn build_minimal_agent_with_definition_name(definition_name: Option<&str>) -> Ag
let mut builder = Agent::builder()
.chat_model(provider)
- .tools(vec![Box::new(MockTool)])
+ .tools(tools)
+ .synthesized_tools(synthesized_tools)
.memory(mem)
.tool_dispatcher(Box::new(NativeToolDispatcher))
.workspace_dir(workspace_path);
@@ -228,9 +239,12 @@ fn integration_delegate_toolkit_enum(agent: &Agent) -> Vec<String> {
///
/// 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.
+/// uniquely owned. A mid-session connect published a `delegate_*` spec with no
+/// instance behind it — and, the policy snapshot being built from the
+/// instances, no decision either, so the fail-closed visibility filter hid it
+/// — while a revoke withdrew the spec and left the instance registered and
+/// callable. 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> =
@@ -253,16 +267,21 @@ fn assert_synthesized_delegates_are_executable(agent: &Agent) {
);
}
- // The other direction is the one that actually regressed: a
- // `delegate_*` spec on the wire with nothing registered to run it.
+ // The other direction is the connect case: a `delegate_*` spec with
+ // nothing registered to run it. Checked against the whole callable
+ // surface, since a durable tool may legitimately own a `delegate_*` name
+ // (in which case the synthesised one is dropped, not the durable one).
+ let all_names: Vec<&str> = agent.all_tool_refs().iter().map(|t| t.name()).collect();
+ let callable: std::collections::HashSet<&str> = all_names.iter().copied().collect();
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:?}"
+ callable.contains(name.as_str()),
+ "advertised delegate `{name}` has no executable instance in either set; \
+ callable={callable:?}"
);
}
@@ -284,6 +303,24 @@ fn assert_synthesized_delegates_are_executable(agent: &Agent) {
tool.name()
);
}
+
+ // The two sets are disjoint by construction, so a name never resolves to
+ // two instances however the readers order them.
+ assert_eq!(
+ callable.len(),
+ all_names.len(),
+ "the durable and synthesised sets must not share a name: {all_names:?}"
+ );
+
+ // And every synthesised tool carries a policy decision — without one the
+ // fail-closed visibility filter would hide it, which is how the connect
+ // direction of #6145 stayed invisible.
+ for name in &executable {
+ assert!(
+ agent.tool_policy_session.decisions.contains_key(name),
+ "synthesised tool `{name}` has no policy decision"
+ );
+ }
}
async fn turn_dispatches_spawn_subagent_through_full_path_inner() {
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.rs
index 4d6859a370..1a3065f175 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
@@ -144,9 +144,8 @@ fn refresh_delegation_tools_updates_schema_even_when_tool_arc_is_shared() {
}
/// Regression for #3044: repeated mid-session connects while the `tools`
-/// Arc stays shared (the normal `before_dispatch` path, where
-/// `AgentToolSource` holds a clone) must not accumulate duplicate
-/// synthesised `ToolSpec`s.
+/// Arc stays shared (a detached sub-agent's cloned `ParentExecutionContext`
+/// outliving its turn) must not accumulate duplicate synthesised `ToolSpec`s.
///
/// Before the fix, a failed `tools` reconcile rolled `synthesized_tool_names`
/// back to the *old* mask. On the next refresh the spec `retain` used that
@@ -615,10 +614,11 @@ async fn last_turn_usage_is_public_and_non_draining() {
///
/// 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
+/// connect while a clone was held, 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.
+/// was reconciled, the instance was not, and the policy snapshot — built from
+/// the instances — had no entry for it, so the fail-closed visibility filter
+/// hid the delegate: silently missing until a unique-owner refresh happened.
#[test]
fn newly_synthesized_delegate_is_executable_while_tool_arc_is_shared() {
use crate::openhuman::agent::harness::AgentDefinitionRegistry;
@@ -641,9 +641,9 @@ fn newly_synthesized_delegate_is_executable_while_tool_arc_is_shared() {
"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.
+ // A detached sub-agent's cloned ParentExecutionContext holds a clone for
+ // as long as it runs. `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![
@@ -671,8 +671,8 @@ fn newly_synthesized_delegate_is_executable_while_tool_arc_is_shared() {
.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"
+ "the delegate must also exist as an executable instance — a spec with \
+ nothing registered to run it is #6145"
);
super::assert_synthesized_delegates_are_executable(&agent);
}
diff --git a/src/openhuman/agent/harness/session/session_tests_part_02_tests.rs b/src/openhuman/agent/harness/session/session_tests_part_02_tests.rs
index e8d951b69f..75cff4eb32 100644
--- a/src/openhuman/agent/harness/session/session_tests_part_02_tests.rs
+++ b/src/openhuman/agent/harness/session/session_tests_part_02_tests.rs
@@ -503,3 +503,215 @@ fn bound_cached_transcript_messages_snaps_past_leading_orphan_tool() {
vec!["u2", "a2", "u3"]
);
}
+
+/// A durable tool with a caller-chosen name, for the tests that pin how the
+/// durable registry and the synthesised delegation set relate.
+struct NamedTool(&'static str);
+
+#[async_trait]
+impl Tool for NamedTool {
+ fn name(&self) -> &str {
+ self.0
+ }
+
+ fn description(&self) -> &str {
+ "durable"
+ }
+
+ fn parameters_schema(&self) -> serde_json::Value {
+ serde_json::json!({"type": "object", "properties": {"durable": {"type": "boolean"}}})
+ }
+
+ async fn execute(
+ &self,
+ _args: serde_json::Value,
+ ) -> Result<crate::openhuman::tools::ToolResult> {
+ Ok(crate::openhuman::tools::ToolResult::success("durable"))
+ }
+}
+
+fn connected(slug: &str) -> crate::openhuman::agent::context::prompt::ConnectedIntegration {
+ crate::openhuman::agent::context::prompt::ConnectedIntegration {
+ toolkit: slug.into(),
+ description: slug.into(),
+ tools: vec![],
+ gated_tools: vec![],
+ connected: true,
+ connections: Vec::new(),
+ non_active_status: None,
+ }
+}
+
+/// Regression for #6145, revoke direction: a delegate whose toolkit was
+/// disconnected must leave the executable set and the policy snapshot in the
+/// same pass its spec is withdrawn, even while an in-flight turn holds clones.
+///
+/// This was the damaging half of the drift: the spec went, but the instance
+/// stayed in the shared `tools` Arc, the policy session built from that Arc
+/// kept allowing it, and the adapter registered from it kept advertising it —
+/// so a disconnected integration's delegate remained callable.
+#[test]
+fn revoked_delegate_leaves_instances_and_policy_with_its_spec_while_tool_arc_is_shared() {
+ use crate::openhuman::agent::harness::AgentDefinitionRegistry;
+ const DELEGATE: &str = "delegate_to_integrations_agent";
+
+ AgentDefinitionRegistry::init_global_builtins().unwrap();
+ let mut agent = build_minimal_agent_with_definition_name(Some("orchestrator"));
+
+ agent.set_connected_integrations(vec![connected("gmail"), connected("notion")]);
+ agent.refresh_delegation_tools();
+ assert_eq!(
+ integration_delegate_toolkit_enum(&agent),
+ vec!["gmail".to_string(), "notion".to_string()]
+ );
+
+ // An in-flight turn holds both sets for its whole duration.
+ let _durable_in_flight = agent.tools_arc();
+ let synthesized_in_flight = agent.synthesized_tools_arc();
+
+ // notion is disconnected: the enum shrinks and the instance follows it.
+ agent.set_connected_integrations(vec![connected("gmail")]);
+ agent.refresh_delegation_tools();
+ assert_eq!(
+ integration_delegate_toolkit_enum(&agent),
+ vec!["gmail".to_string()]
+ );
+ super::assert_synthesized_delegates_are_executable(&agent);
+
+ // Everything is disconnected: the delegate leaves every surface at once.
+ agent.set_connected_integrations(Vec::new());
+ agent.refresh_delegation_tools();
+ assert!(
+ !agent.tool_specs().iter().any(|spec| spec.name == DELEGATE),
+ "the withdrawn delegate must not keep a spec"
+ );
+ assert!(
+ !agent
+ .synthesized_tools_arc()
+ .iter()
+ .any(|tool| tool.name() == DELEGATE),
+ "the executable instance must go with the spec — this is what stayed \
+ behind before #6145"
+ );
+ assert!(!agent
+ .all_tool_refs()
+ .iter()
+ .any(|tool| tool.name() == DELEGATE));
+ assert!(
+ !agent.tool_policy_session.is_allowed(DELEGATE)
+ && !agent.tool_policy_session.decisions.contains_key(DELEGATE),
+ "a withdrawn delegate must not keep a policy allowance"
+ );
+ super::assert_synthesized_delegates_are_executable(&agent);
+
+ // The turn that started before the revoke still sees its own coherent set.
+ assert!(
+ synthesized_in_flight
+ .iter()
+ .any(|tool| tool.name() == DELEGATE),
+ "an in-flight turn keeps the snapshot it started with"
+ );
+}
+
+/// A durable tool that owns a delegate's name wins on every surface, at build
+/// time and on every refresh — and a refresh must never withdraw the durable
+/// tool's spec when it re-synthesises the colliding delegate.
+///
+/// The old refresh put the unfiltered synthesised names into its mask, so the
+/// next refresh's spec `retain` dropped the durable tool's spec and appended
+/// the delegate's: the model then read the delegate's schema for a name whose
+/// first-wins dispatch ran the durable tool.
+#[test]
+fn a_durable_tool_owning_a_delegate_name_wins_everywhere_across_refreshes() {
+ use crate::openhuman::agent::harness::AgentDefinitionRegistry;
+ const DELEGATE: &str = "delegate_to_integrations_agent";
+
+ AgentDefinitionRegistry::init_global_builtins().unwrap();
+ let mut agent = build_minimal_agent_with_tool_sets(
+ vec![Box::new(MockTool), Box::new(NamedTool(DELEGATE))],
+ Vec::new(),
+ Some("orchestrator"),
+ );
+ let durable_schema = NamedTool(DELEGATE).parameters_schema();
+
+ for toolkits in [vec!["gmail"], vec!["gmail", "notion"], vec!["notion"]] {
+ agent.set_connected_integrations(toolkits.iter().map(|slug| connected(slug)).collect());
+ agent.refresh_delegation_tools();
+
+ assert!(
+ !agent
+ .synthesized_tools_arc()
+ .iter()
+ .any(|tool| tool.name() == DELEGATE),
+ "the colliding delegate must not be synthesised beside the durable tool"
+ );
+ let specs: Vec<&crate::openhuman::tools::ToolSpec> = agent
+ .tool_specs()
+ .iter()
+ .filter(|spec| spec.name == DELEGATE)
+ .collect();
+ assert_eq!(specs.len(), 1, "exactly one spec may carry the name");
+ assert_eq!(
+ specs[0].parameters, durable_schema,
+ "and it must be the durable tool's schema — a refresh must not swap it \
+ for the delegate's"
+ );
+ assert_eq!(
+ agent
+ .all_tool_refs()
+ .iter()
+ .filter(|tool| tool.name() == DELEGATE)
+ .count(),
+ 1
+ );
+ assert!(agent.tool_policy_session.is_allowed(DELEGATE));
+ super::assert_synthesized_delegates_are_executable(&agent);
+ }
+}
+
+/// The builder keeps the synthesised set beside the durable registry, never
+/// inside it, and drops a synthesised name a durable tool already owns.
+#[test]
+fn builder_holds_synthesized_tools_apart_from_the_durable_registry() {
+ let agent = build_minimal_agent_with_tool_sets(
+ vec![Box::new(MockTool)],
+ vec![
+ Box::new(NamedTool("delegate_probe")),
+ Box::new(NamedTool("echo")),
+ ],
+ None,
+ );
+
+ assert!(
+ agent.tools().iter().all(|tool| tool.name() == "echo"),
+ "the durable registry must hold only what was handed to `tools`"
+ );
+ let synthesized: Vec<String> = agent
+ .synthesized_tools_arc()
+ .iter()
+ .map(|tool| tool.name().to_string())
+ .collect();
+ assert_eq!(
+ synthesized,
+ vec!["delegate_probe".to_string()],
+ "the synthesised `echo` collides with the durable tool and must be dropped"
+ );
+ assert_eq!(
+ agent
+ .tool_specs()
+ .iter()
+ .filter(|spec| spec.name == "echo")
+ .count(),
+ 1,
+ "the durable tool keeps the only `echo` spec"
+ );
+ assert!(agent
+ .tool_specs()
+ .iter()
+ .any(|spec| spec.name == "delegate_probe"));
+ assert!(agent.tool_policy_session.is_allowed("delegate_probe"));
+ let expected_mask: std::collections::HashSet<String> =
+ std::iter::once("delegate_probe".to_string()).collect();
+ assert_eq!(agent.synthesized_tool_names, expected_mask);
+ super::assert_synthesized_delegates_are_executable(&agent);
+}
diff --git a/src/openhuman/agent/harness/session/turn/graph.rs b/src/openhuman/agent/harness/session/turn/graph.rs
index a9bbaa4df3..8860545c98 100644
--- a/src/openhuman/agent/harness/session/turn/graph.rs
+++ b/src/openhuman/agent/harness/session/turn/graph.rs
@@ -57,12 +57,11 @@ pub(crate) struct ChatTurnGraph {
/// 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.
+ /// carried as their own set rather than merged into `tools` — the channel
+ /// path does the same with its per-turn `extra_tools` (see
+ /// [`crate::openhuman::agent::harness::graph`]). This is what lets a
+ /// mid-session Composio connect reach the model as a *callable* tool and a
+ /// revoke withdraw one, without owning `tools`.
pub synthesized_tools: Arc<Vec<Box<dyn Tool>>>,
/// Callable-tool whitelist (empty = every visible tool).
pub visible_tool_names: HashSet<String>,
@@ -118,10 +117,13 @@ pub(crate) async fn run_chat_turn_graph(graph: ChatTurnGraph) -> Result<Tinyagen
provider_id,
&graph.model,
graph.messages,
- // 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],
+ // Durable set first, synthesised second — the order `tool_specs` and
+ // `Agent::all_tool_refs` use, so the name a spec was advertised
+ // under resolves to the same instance here. The two sets are
+ // disjoint by construction (`builder::drop_synthesized_name_collisions`),
+ // so the order never decides a collision; it only keeps every
+ // surface enumerating the tools in one sequence.
+ vec![graph.tools, graph.synthesized_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.rs
index 647c9213b3..3e3014825b 100644
--- a/src/openhuman/agent/harness/session/turn/tools.rs
+++ b/src/openhuman/agent/harness/session/turn/tools.rs
@@ -502,17 +502,20 @@ impl Agent {
/// Re-synthesise `delegate_*` tools for the orchestrator's `subagents`
/// declaration using the live `connected_integrations` slice, and
- /// reconcile the resulting set into `self.tools` / `self.tool_specs` /
- /// `self.visible_tool_specs` / `self.visible_tool_names`.
+ /// reconcile the resulting set into `self.synthesized_tools` /
+ /// `self.tool_specs` / `self.visible_tool_specs` / `self.visible_tool_names`.
+ /// `self.tools` is never touched.
///
/// **Reconciliation strategy** — full rebuild of the synthesised
/// subset:
///
- /// 1. Drop every tool whose name was in [`Self::synthesized_tool_names`]
+ /// 1. Drop every spec whose name was in [`Self::synthesized_tool_names`]
/// from the previous synthesis. Direct tools (`query_memory`,
/// `cron_add`, …) are untouched because their names are not in
/// that set.
- /// 2. Append the freshly collected synthesis output verbatim.
+ /// 2. Append the fresh specs, and replace [`Self::synthesized_tools`]
+ /// with the fresh instances — minus any name a durable tool owns,
+ /// which the durable tool keeps (the same rule the builder applies).
/// 3. Replace `synthesized_tool_names` with the new set so the
/// next refresh has a clean mask to undo.
///
@@ -522,10 +525,11 @@ impl Agent {
/// previous synthesis is unconditionally dropped, the new set is
/// authoritative.
/// * Direct tools can never be accidentally removed — only names
- /// in `synthesized_tool_names` are touched.
- /// * Duplicate registration is impossible — retain+extend
- /// guarantees every final entry is either a non-synthesised
- /// direct tool or a member of the fresh `synthed` set.
+ /// in `synthesized_tool_names` are touched, and a durable name is
+ /// never added to that mask.
+ /// * Duplicate registration is impossible — the fresh set replaces the
+ /// previous one wholesale and is disjoint from `self.tools`, so a
+ /// name is registered at most once across both sets.
///
/// **When to call**: on turn 1 only when the session was built
/// without a prewarmed Composio cache snapshot, and on any
@@ -543,9 +547,12 @@ impl Agent {
///
/// 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).
+ /// fails under exactly that sharing — and the old code proceeded to
+ /// reconcile `tool_specs` anyway, so the two halves drifted: a newly
+ /// connected toolkit's delegate had a spec with no instance (and no policy
+ /// decision, so the fail-closed visibility filter hid it — silently missing
+ /// until a unique-owner refresh) while a revoked toolkit's delegate kept its
+ /// instance with no spec — still registered and callable (#6145).
///
/// 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
@@ -571,7 +578,13 @@ impl Agent {
return;
}
- let synthed = collect_orchestrator_tools(def, reg, &self.connected_integrations);
+ // A durable name wins a collision, exactly as at build time. Filtering
+ // here also keeps such a name out of the mask below, so the spec
+ // `retain` can never withdraw a durable tool's spec.
+ let synthed = super::super::builder::drop_synthesized_name_collisions(
+ &self.tools,
+ collect_orchestrator_tools(def, reg, &self.connected_integrations),
+ );
let synthed_names: std::collections::HashSet<String> =
synthed.iter().map(|t| t.name().to_string()).collect();
let synthed_specs: Vec<crate::openhuman::tools::ToolSpec> =
@@ -605,8 +618,8 @@ impl Agent {
//
// 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).
+ // all, so a concurrent reader cannot block it, and the specs above and
+ // the instances here can never drift apart again (#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();
diff --git a/src/openhuman/agent/harness/session/types.rs b/src/openhuman/agent/harness/session/types.rs
index 3adfb6a46f..3f7dce0cf3 100644
--- a/src/openhuman/agent/harness/session/types.rs
+++ b/src/openhuman/agent/harness/session/types.rs
@@ -89,12 +89,15 @@ pub struct Agent {
/// 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).
+ /// whenever any reader holds a clone — in practice a detached sub-agent's
+ /// cloned `ParentExecutionContext`, which outlives the turn that spawned
+ /// it. The old code then reconciled `tool_specs` anyway and left the
+ /// instances as they were, so the two halves drifted (#6145): a newly
+ /// connected toolkit's delegate had a spec but no instance — and, the
+ /// policy snapshot being built from the instances, no decision either, so
+ /// the fail-closed visibility filter silently hid it until a unique-owner
+ /// refresh — while a revoked toolkit's delegate lost its spec but stayed
+ /// registered, advertised through its adapter, and callable.
///
/// Because these instances are regenerated from scratch on every refresh,
/// this `Arc` can always be *replaced* wholesale — no unique ownership
@@ -102,8 +105,13 @@ pub struct Agent {
/// `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.
+ /// Disjoint from [`Self::tools`] by construction: a synthesised tool whose
+ /// name a durable tool owns is dropped at build time and on every refresh
+ /// (`builder::drop_synthesized_name_collisions`), so the durable tool wins
+ /// on every surface. Every reader enumerates `tools` first and this set
+ /// second — [`Self::tool_specs`], [`Self::all_tool_refs`], turn dispatch —
+ /// so a name resolves in the same order everywhere. 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`].
@@ -469,8 +477,9 @@ pub struct Agent {
/// direct tools (`query_memory`, `cron_add`, …) that share a name
/// prefix.
///
- /// Populated by `refresh_delegation_tools` itself; empty at
- /// construction time.
+ /// Seeded by [`AgentBuilder::build`] from the set handed to
+ /// [`AgentBuilder::synthesized_tools`], then replaced by
+ /// `refresh_delegation_tools` on every refresh.
///
/// Invariant: this set is the name mask for **both** [`Self::tool_specs`]'
/// synthesised half and [`Self::synthesized_tools`], which reconcile
@@ -492,6 +501,9 @@ pub struct Agent {
pub struct AgentBuilder {
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.
+ /// Held in [`Agent::synthesized_tools`], never inside [`Agent::tools`].
+ pub(super) synthesized_tools: Option<Vec<Box<dyn Tool>>>,
/// When set, restricts which tools the main agent sees/calls.
pub(super) visible_tool_names: Option<std::collections::HashSet<String>>,
/// Optional explicit profile ceiling for tools delegated agents may inherit.
diff --git a/src/openhuman/agent/pformat.rs b/src/openhuman/agent/pformat.rs
index 1d5dd8cd5d..abcfffc3a8 100644
--- a/src/openhuman/agent/pformat.rs
+++ b/src/openhuman/agent/pformat.rs
@@ -37,8 +37,19 @@ pub use tinyagents_harness::tool_calling::{
/// exist. A registry built from anything other than the agent's real tools
/// would widen that.
pub fn build_registry(tools: &[Box<dyn Tool>]) -> PFormatRegistry {
+ build_registry_from_refs(tools.iter().map(|t| t.as_ref()))
+}
+
+/// [`build_registry`] over any iterator of borrowed tools.
+///
+/// A session agent's surface is two sets — the durable registry and the
+/// synthesised delegation set (`Agent::synthesized_tools`) — that cannot be
+/// merged into one owned slice, since `Box<dyn Tool>` is not cloneable.
+pub fn build_registry_from_refs<'a>(
+ tools: impl IntoIterator<Item = &'a dyn Tool>,
+) -> PFormatRegistry {
tinyagents_harness::tool_calling::build_registry(
- tools.iter().map(|t| (t.name(), t.parameters_schema())),
+ tools.into_iter().map(|t| (t.name(), t.parameters_schema())),
)
}