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): make load_skill's listing agree with the gate that refuses it
M3gA-Mind2ce1247254a9
diff --git a/src/openhuman/agent/orchestration/tools.rs b/src/openhuman/agent/orchestration/tools.rsindex d592981b1f..bd0986b426 100644--- a/src/openhuman/agent/orchestration/tools.rs+++ b/src/openhuman/agent/orchestration/tools.rs@@ -41,7 +41,7 @@ pub(crate) use dispatch::dispatch_subagent;pub use agent_prepare_context::{run_context_scout, run_context_scout_with_catalog, AgentPrepareContextTool,};-pub use archetype_delegation::ArchetypeDelegationTool;+pub use archetype_delegation::{ArchetypeDelegationTool, DelegationTarget};pub use close_subagent::CloseSubagentTool;pub use continue_subagent::ContinueSubagentTool;pub use delegate_graph::DelegateGraphTool;diff --git a/src/openhuman/agent/orchestration/tools/archetype_delegation.rs b/src/openhuman/agent/orchestration/tools/archetype_delegation.rsindex 4bb29a51e9..18a977fece 100644--- a/src/openhuman/agent/orchestration/tools/archetype_delegation.rs+++ b/src/openhuman/agent/orchestration/tools/archetype_delegation.rs@@ -9,10 +9,31 @@ use tinytools::ToolRunContext;pub struct ArchetypeDelegationTool {pub tool_name: String,- pub agent_id: String,+ /// The agent this tool routes to, in the shape+ /// [`crate::openhuman::tools::traits::delegation_target`] reads back off the+ /// erased host-extension slot.+ ///+ /// A newtype rather than a bare `String` because that slot is one `Any` per+ /// tool: a downcast to `String` would happily match any *other* tool that+ /// parked a string there. It holds the id rather than deriving it because+ /// [`Tool::host_extension`] hands out a borrow, so there must be something+ /// to borrow from — and one field, not two, is what stops the exposed+ /// target drifting from the routed one.+ pub agent_id: DelegationTarget,pub tool_description: String,}+/// The agent a synthesised `delegate_*` tool routes to.+///+/// Lets a caller that holds only `&dyn Tool` ask "which agent does this reach?"+/// — the question the toolpack route hint needs answered, and the reason the+/// hint does not need its own copy of every agent's `delegate_name`. The tool+/// set a session was actually built with is the single source of truth: a+/// delegate that is not in it cannot be named as a route, which is exactly the+/// property we want.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct DelegationTarget(pub String);+#[async_trait]impl Tool for ArchetypeDelegationTool {fn name(&self) -> &str {@@ -23,6 +44,13 @@ impl Tool for ArchetypeDelegationTool {&self.tool_description}+ /// Publishes the routing target on the erased host-extension slot, the same+ /// way `LoadSkillTool` publishes its pack handle. `traits::delegation_target`+ /// reads it back; every other tool returns `None` and pays nothing.+ fn host_extension(&self) -> Option<&(dyn std::any::Any + Send + Sync)> {+ Some(&self.agent_id)+ }+/// The delegation envelope — deliberately description-light.////// This one literal is emitted for **every** synthesised `delegate_*` tool@@ -160,7 +188,7 @@ impl Tool for ArchetypeDelegationTool {};super::dispatch_subagent(- &self.agent_id,+ &self.agent_id.0,&self.tool_name,&prompt,None,diff --git a/src/openhuman/agent/orchestration/tools/archetype_delegation_tests.rs b/src/openhuman/agent/orchestration/tools/archetype_delegation_tests.rsindex 9713dfed73..5366e87ea0 100644--- a/src/openhuman/agent/orchestration/tools/archetype_delegation_tests.rs+++ b/src/openhuman/agent/orchestration/tools/archetype_delegation_tests.rs@@ -4,7 +4,7 @@ use crate::openhuman::agent::harness::definition::AgentDefinitionRegistry;fn sample_tool() -> ArchetypeDelegationTool {ArchetypeDelegationTool {tool_name: "delegate_researcher".to_string(),- agent_id: "researcher".to_string(),+ agent_id: DelegationTarget("researcher".to_string()),tool_description: "Use for web and docs research.".to_string(),}}diff --git a/src/openhuman/agent/orchestration/tools/tools_e2e_tests.rs b/src/openhuman/agent/orchestration/tools/tools_e2e_tests.rsindex 69edf2bb74..afd1b7cf01 100644--- a/src/openhuman/agent/orchestration/tools/tools_e2e_tests.rs+++ b/src/openhuman/agent/orchestration/tools/tools_e2e_tests.rs@@ -1,5 +1,6 @@use super::{- ArchetypeDelegationTool, SkillDelegationTool, SpawnSubagentTool, SpawnWorkerThreadTool,+ ArchetypeDelegationTool, DelegationTarget, SkillDelegationTool, SpawnSubagentTool,+ SpawnWorkerThreadTool,};use crate::openhuman::agent::context::prompt::{ConnectedIntegration, ToolCallFormat};use crate::openhuman::agent::harness::definition::AgentDefinitionRegistry;@@ -63,7 +64,7 @@ async fn archetype_delegation_tool_runs_child_agent_e2e() {)]));let tool = ArchetypeDelegationTool {tool_name: "delegate_researcher".to_string(),- agent_id: "researcher".to_string(),+ agent_id: DelegationTarget("researcher".to_string()),tool_description: "Delegate research work.".to_string(),};@@ -112,7 +113,7 @@ async fn archetype_delegation_defaults_to_async_with_durable_session_e2e() {)]));let tool = ArchetypeDelegationTool {tool_name: "delegate_researcher".to_string(),- agent_id: "researcher".to_string(),+ agent_id: DelegationTarget("researcher".to_string()),tool_description: "Delegate research work.".to_string(),};diff --git a/src/openhuman/agent/registry/agents/orchestrator/prompt.md b/src/openhuman/agent/registry/agents/orchestrator/prompt.mdindex 4140a6a101..81035635de 100644--- a/src/openhuman/agent/registry/agents/orchestrator/prompt.md+++ b/src/openhuman/agent/registry/agents/orchestrator/prompt.md@@ -89,6 +89,11 @@ Your job, in order: understand the request (ask when it is genuinely ambiguous),- **`cron_add`, `cron_list`, `cron_remove`, `current_time` are direct named tools** when they appear in your tool list. Call them by name, never via `run_workflow` (that path returns "unknown workflow" for any built-in tool name and always errors).- **Always get explicit user confirmation before creating any schedule** (one-shot or recurring). Propose the exact timing, wait for a yes, then act. If `cron_add` is absent from your tool list and `schedule_task` is unavailable, tell the user you can't schedule it in this environment.+**Workflow rule of thumb.** Route anything about building, editing or proposing a saved workflow to **`build_workflow`**, and workflow discovery to **`discover_workflows`**. Those specialists own the flow-authoring tools (`propose_workflow`, `create_workflow`, `save_workflow`, `validate_workflow` and the rest); you do not hold them and cannot borrow them through `use_skill`. Two things follow:++- **Do not `load_skill { skill: "workflows" }` to author a flow, and never try `use_skill { tool: "propose_workflow" }`.** That call is refused, and re-trying it burns the turn. Hand the request to `build_workflow` instead.+- **Delegate on the user's description — you do not need the graph first.** `build_workflow` does the discovery, node wiring and validation itself, and comes back with a proposal for the user to approve. Running the saved flow afterwards (`run_workflow`, `list_workflows`) is yours.+### Grounding and tool use- Your tools are exactly the ones listed in this prompt. You can only act through them. If a capability is not one of your tools, say so plainly rather than pretending it exists.diff --git a/src/openhuman/agent/registry/agents/orchestrator/prompt_tests.rs b/src/openhuman/agent/registry/agents/orchestrator/prompt_tests.rsindex d3cb7dffb7..1f703ff6e4 100644--- a/src/openhuman/agent/registry/agents/orchestrator/prompt_tests.rs+++ b/src/openhuman/agent/registry/agents/orchestrator/prompt_tests.rs@@ -511,3 +511,54 @@ fn build_omits_guide_when_no_integrations_connected() {let body = build(&ctx_with(&integrations)).unwrap();assert!(!body.contains("## Connected Integrations"));}++#[test]+fn prompt_routes_workflow_authoring_to_the_builder_not_use_skill() {+ // Regression for the `use_skill` routing dead end. The orchestrator loaded+ // the `workflows` pack, read `propose_workflow` off the listing, called it+ // through `use_skill`, and was refused — six times, until the+ // repeated-failure breaker killed the turn.+ //+ // The gate is the fix; this pins the prompt so the model is told the route+ // before it discovers the wall.+ assert!(+ ARCHETYPE.contains("Workflow rule of thumb"),+ "orchestrator prompt must carry the workflow routing rule"+ );+ assert!(+ ARCHETYPE.contains("`build_workflow`"),+ "the rule must name the delegate to call"+ );+ assert!(+ ARCHETYPE.contains("use_skill"),+ "the rule must name the path it is steering away from"+ );++ // The rule is only true because these are the real names. Asserting the+ // prompt against itself would survive a rename of either side; asserting it+ // against the pack and the agent definition does not.+ let pack =+ crate::openhuman::tools::toolpacks::pack("workflows").expect("the workflows pack exists");+ assert!(+ pack.tools.contains(&"propose_workflow"),+ "the prompt names propose_workflow as pack-owned: {:?}",+ pack.tools+ );+ assert!(+ pack.owners.contains(&"workflow_builder"),+ "the prompt routes to workflow_builder as an owner: {:?}",+ pack.owners+ );++ let registry =+ crate::openhuman::agent::harness::definition::AgentDefinitionRegistry::builtins_only();+ let builder = registry+ .get("workflow_builder")+ .expect("workflow_builder is a registered agent");+ assert_eq!(+ builder.delegate_name.as_deref(),+ Some("build_workflow"),+ "the prompt tells the model to call `build_workflow`; that must still be \+ workflow_builder's delegate_name, or the rule names a tool nobody has"+ );+}diff --git a/src/openhuman/agent/tinyagents/middleware_part_02.rs b/src/openhuman/agent/tinyagents/middleware_part_02.rsindex 819078993a..25b0bdb3f0 100644--- a/src/openhuman/agent/tinyagents/middleware_part_02.rs+++ b/src/openhuman/agent/tinyagents/middleware_part_02.rs@@ -561,6 +561,106 @@ impl ToolPolicyMiddleware {.find(|t| t.name() == name)}+ /// The delegation tools this session can actually call that reach one of+ /// `owners`, as tool names.+ ///+ /// Derived from the session's own tool set — every synthesised `delegate_*`+ /// tool publishes its target agent on the erased host-extension slot+ /// (`traits::delegation_target`). That is deliberately the only source: a+ /// static owner-to-tool table would duplicate each agent's `delegate_name`+ /// and could name a tool this session was never built with, sending the+ /// model from one dead end into another. Asking the tool set cannot.+ fn callable_delegates_for(&self, owners: &[&str]) -> Vec<String> {+ let mut found: Vec<String> = Vec::new();+ for tool in self.tool_sets.iter().flat_map(|set| set.iter()) {+ let Some(target) =+ crate::openhuman::tools::traits::delegation_target(tool.as_ref())+ else {+ continue;+ };+ if !owners.contains(&target) {+ continue;+ }+ let name = tool.name().to_string();+ // Uses `is_denied()`, and that is deliberate — it is the same+ // predicate as the gate this hint points at.+ //+ // Spelled out, because two predicates live in this file and a+ // sentence that does not name one has been misread three times:+ //+ // * This hint names a tool for the model to call DIRECTLY.+ // * The direct-call gate is `channel_permission_block`'s first+ // check, `if decision.is_denied()` (this file, top of the fn).+ // * `is_denied()` is `!matches!(action, Allow)`, so it is TRUE for+ // `HideFromPrompt` — that check is what refuses a prompt-hidden+ // tool called by name.+ // * Therefore a prompt-hidden delegate is not a route, and+ // `is_denied()` here is exactly what keeps it out.+ //+ // `blocks_execution()` would be wrong here: it deliberately admits+ // `HideFromPrompt` for the `use_skill` path below, where hiding is+ // the disclosure mechanism rather than a refusal. Same tool, two+ // call paths, two answers. A hint must use the predicate of the gate+ // it points at — the hint and the gate disagreeing is how this whole+ // class of bug started.+ //+ // Pinned by `a_prompt_hidden_delegate_is_not_offered_as_a_direct_route`.+ if self.session.decision_for(&name).is_denied() || found.contains(&name) {+ continue;+ }+ found.push(name);+ }+ found+ }++ /// The route sentence for a pack, resolved against THIS session.+ fn route_for_pack(&self, pack: &crate::openhuman::tools::toolpacks::ToolPack) -> String {+ crate::openhuman::tools::toolpacks::route_sentence(+ &self.callable_delegates_for(pack.owners),+ pack.owners,+ )+ }++ /// Render a `load_skill` listing scoped to what this session may call.+ ///+ /// This lives in the middleware because the middleware is the only layer+ /// that holds the session — `LoadSkillTool` is built once per registry and+ /// has no idea who is calling it. Returns `None` when there is nothing to+ /// scope (no `skill` argument, no pack handle), so the call falls through to+ /// the tool's own `execute` unchanged.+ fn render_skill_for_session(&self, call: &TaToolCall) -> Option<TaToolResult> {+ let skill = call+ .arguments+ .get("skill")+ .and_then(serde_json::Value::as_str)?;+ let tool = self.resolve_tool(&call.name)?;+ let handle = crate::openhuman::tools::traits::pack_registry_handle(tool.as_ref())?;+ let is_callable = |name: &str| !self.session.decision_for(name).blocks_execution();+ let route = crate::openhuman::tools::toolpacks::pack(skill)+ .map(|pack| self.route_for_pack(pack))+ .unwrap_or_default();+ let rendered = crate::openhuman::tools::toolpacks::render_pack_filtered(+ skill,+ handle,+ // The same predicate the gate applies to `use_skill`'s inner tool.+ // Two sources of truth for "can this session call it" is the bug.+ &is_callable,+ &route,+ );+ let (content, error) = match rendered {+ Ok(text) => (text, None),+ Err(message) => (message.clone(), Some(message)),+ };+ Some(TaToolResult {+ call_id: call.id.clone(),+ name: call.name.clone(),+ content,+ raw: None,+ error,+ elapsed_ms: 0,+ })+ }+/// The channel-permission gate the engine ran before the builder policy: a/// session-level deny, then a per-call permission-level ceiling check. Returns/// the blocking message when the call must not execute.@@ -600,10 +700,25 @@ impl ToolPolicyMiddleware {.get("tool").and_then(serde_json::Value::as_str){+ // `blocks_execution`, NOT `is_denied`. Every withheld packed+ // tool is `HideFromPrompt`, and `use_skill` is the only route it+ // has — gating that route on `is_denied` refused all of them.let inner_decision = self.session.decision_for(inner_tool);- if inner_decision.is_denied() {+ if inner_decision.blocks_execution() {+ // Name the route. A bare denial gives the model nothing to+ // do differently, and a model with no next step retries the+ // same call: one live turn burned its whole budget on six+ // identical `use_skill` denials and died on the+ // repeated-failure breaker. Same sentence the listing uses,+ // resolved against the same session, so the two cannot+ // tell the model different stories.+ let hint = crate::openhuman::tools::toolpacks::pack_for_tool(inner_tool)+ .map(|pack| self.route_for_pack(pack))+ .filter(|h| !h.is_empty())+ .map(|h| format!(" {h}"))+ .unwrap_or_default();return Some(format!(- "Tool `{inner_tool}` is not allowed in the current session and cannot be used through `use_skill`."+ "Tool `{inner_tool}` is not allowed in the current session and cannot be used through `use_skill`.{hint}"));}}diff --git a/src/openhuman/agent/tinyagents/middleware_part_03.rs b/src/openhuman/agent/tinyagents/middleware_part_03.rsindex 525c60e61d..ab78fe001f 100644--- a/src/openhuman/agent/tinyagents/middleware_part_03.rs+++ b/src/openhuman/agent/tinyagents/middleware_part_03.rs@@ -90,6 +90,20 @@ impl ToolMiddleware<()> for ToolPolicyMiddleware {}));}+ // `load_skill` renders its listing here, not in its own `execute`,+ // because only the middleware holds the session — and a listing that+ // disagrees with the session is a menu the model cannot order from.+ //+ // Placed AFTER both gates on purpose. Rendering before them would let a+ // `load_skill` that the session forbids, or that the policy denies or+ // holds for approval, still hand back a full pack listing — the gates+ // would be advisory for this one tool.+ if call.name == crate::openhuman::tools::toolpacks::LOAD_SKILL {+ if let Some(result) = self.render_skill_for_session(&call) {+ return Ok(MiddlewareToolOutcome::Result(result));+ }+ }+next.run(ctx, state, call).await}}diff --git a/src/openhuman/agent/tinyagents/middleware_tests.rs b/src/openhuman/agent/tinyagents/middleware_tests.rsindex 61db505206..b08461a4d8 100644--- a/src/openhuman/agent/tinyagents/middleware_tests.rs+++ b/src/openhuman/agent/tinyagents/middleware_tests.rs@@ -392,3 +392,5 @@ mod part_01_tests;mod part_02_tests;#[path = "middleware_tests_part_03_tests.rs"]mod part_03_tests;+#[path = "middleware_tests_part_04_tests.rs"]+mod part_04_tests;diff --git a/src/openhuman/agent/tinyagents/middleware_tests_part_04_tests.rs b/src/openhuman/agent/tinyagents/middleware_tests_part_04_tests.rsnew file mode 100644index 0000000000..97e5b2819d--- /dev/null+++ b/src/openhuman/agent/tinyagents/middleware_tests_part_04_tests.rs@@ -0,0 +1,351 @@+use super::*;++// ── the listing must agree with the gate (#workflow-routing) ────────────────+//+// End to end at the only layer that holds both halves: the session allowlist+// that `use_skill` is gated on, and the tool set the listing is rendered from.+// The unit tests in `tools/toolpacks/toolpacks_tests.rs` pin the filter itself;+// these pin that the middleware feeds it the *session's* answer and resolves+// the route out of the session's own delegation tools.++use crate::openhuman::agent::orchestration::tools::{ArchetypeDelegationTool, DelegationTarget};+use crate::openhuman::tools::agent_policy::{+ TaskProfile, TaskRiskLevel, ToolCapability, ToolPolicyAction, ToolPolicyDecision,+ ToolPolicySession,+};+use crate::openhuman::tools::toolpacks::{append_pack_tools, bind_pack_registry, LOAD_SKILL};+use crate::openhuman::tools::traits::{PermissionLevel, ToolResult};++struct RoutingFakeTool(&'static str);++#[async_trait]+impl crate::openhuman::tools::traits::Tool for RoutingFakeTool {+ fn name(&self) -> &str {+ self.0+ }+ fn description(&self) -> &str {+ "fake"+ }+ fn parameters_schema(&self) -> serde_json::Value {+ json!({ "type": "object" })+ }+ async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {+ Ok(ToolResult::success("ok"))+ }+ fn permission_level(&self) -> PermissionLevel {+ PermissionLevel::ReadOnly+ }+}++fn allow(name: &str) -> (String, ToolPolicyDecision) {+ (+ name.to_string(),+ ToolPolicyDecision {+ tool_name: name.to_string(),+ action: ToolPolicyAction::Allow,+ required_permission: None,+ allowed_permission: PermissionLevel::Dangerous,+ },+ )+}++/// A non-owner session: it holds the whole `workflows` pack in its registry and+/// a `build_workflow` delegate, but may only call the delegate and the two pack+/// tools — exactly the orchestrator's shape. Anything not named here is denied,+/// because `decision_for` defaults to `Deny`.+fn non_owner_middleware() -> ToolPolicyMiddleware {+ let mut tools: Vec<Box<dyn crate::openhuman::tools::traits::Tool>> = vec![+ Box::new(RoutingFakeTool("build_workflow")),+ Box::new(RoutingFakeTool("propose_workflow")),+ Box::new(ArchetypeDelegationTool {+ tool_name: "build_workflow".to_string(),+ agent_id: DelegationTarget("workflow_builder".to_string()),+ tool_description: "Build a workflow".to_string(),+ }),+ ];+ append_pack_tools(&mut tools);+ let tools = Arc::new(tools);+ bind_pack_registry(&tools);++ let session = ToolPolicySession {+ profile: TaskProfile {+ agent_id: "orchestrator".to_string(),+ channel: "web_chat".to_string(),+ entrypoint: "chat".to_string(),+ risk_level: TaskRiskLevel::Low,+ allowed_permission: PermissionLevel::Dangerous,+ },+ capabilities: vec![ToolCapability {+ name: "build_workflow".to_string(),+ required_permission: PermissionLevel::ReadOnly,+ }],+ allowed_tool_names: ["build_workflow", LOAD_SKILL, "use_skill"]+ .into_iter()+ .map(str::to_string)+ .collect(),+ blocked_tool_names: ["propose_workflow"]+ .into_iter()+ .map(str::to_string)+ .collect(),+ hidden_tool_names: Default::default(),+ decisions: [+ allow("build_workflow"),+ allow(LOAD_SKILL),+ allow("use_skill"),+ ]+ .into_iter()+ .collect(),+ };++ ToolPolicyMiddleware::new(+ Arc::new(crate::openhuman::agent::tool_policy::AllowAllToolPolicy::default()),+ session,+ vec![tools],+ "sess".to_string(),+ "web_chat".to_string(),+ "orchestrator".to_string(),+ )+}++fn call(name: &str, args: serde_json::Value) -> TaToolCall {+ TaToolCall {+ id: "call-1".to_string(),+ name: name.to_string(),+ arguments: args,+ invalid: None,+ }+}++/// The bug: the orchestrator loaded `workflows`, read `propose_workflow` off+/// the listing, called it, and was refused. The listing must not offer it.+#[tokio::test]+async fn load_skill_hides_what_this_session_cannot_call_and_names_the_route() {+ let mw = non_owner_middleware();+ let result = mw+ .render_skill_for_session(&call(LOAD_SKILL, json!({ "skill": "workflows" })))+ .expect("a load_skill call with a skill argument renders here");++ assert!(+ !result.content.contains("propose_workflow"),+ "a non-owner must not be offered a tool the gate will refuse:\n{}",+ result.content+ );+ // Assert the LISTING entry in its exact rendered form, not the bare name.+ //+ // `build_workflow` occurs in two different outputs: a rendered listing+ // (`## \`build_workflow\``) and the route sentence used when nothing is+ // callable (``Call `build_workflow` instead``). A bare `contains` therefore+ // passed even when the filter had dropped every tool and the render had+ // fallen through to its error path — i.e. it passed in the exact case this+ // test exists to catch. A check that cannot fail reads as coverage and is+ // worse than none.+ assert!(+ result.content.contains("## `build_workflow`"),+ "the tool it CAN call must still be LISTED, not merely mentioned in a \+ route sentence:\n{}",+ result.content+ );+ // And this really is a listing, not the "nothing callable" error.+ assert!(+ result.content.starts_with("# Skill `workflows`"),+ "expected a rendered pack listing:\n{}",+ result.content+ );+}++/// And when it calls the denied tool anyway, the refusal has to carry the way+/// out — resolved from a delegate this session actually holds.+#[tokio::test]+async fn a_use_skill_denial_names_a_delegate_this_session_can_call() {+ let mw = non_owner_middleware();+ let message = mw+ .channel_permission_block(&call(+ "use_skill",+ json!({ "skill": "workflows", "tool": "propose_workflow" }),+ ))+ .expect("propose_workflow is denied for a non-owner");++ assert!(+ message.contains("not allowed in the current session"),+ "the denial itself must survive: {message}"+ );+ assert!(+ message.contains("build_workflow"),+ "the denial must name the delegate to call instead: {message}"+ );+}++/// The route is only trustworthy because it is read off the session's own tool+/// set. A session with no delegate to `workflow_builder` must fall back to+/// naming the owning agents rather than inventing a call it cannot make.+#[tokio::test]+async fn a_session_without_the_delegate_is_not_told_to_call_it() {+ let mut tools: Vec<Box<dyn crate::openhuman::tools::traits::Tool>> =+ vec![Box::new(RoutingFakeTool("propose_workflow"))];+ append_pack_tools(&mut tools);+ let tools = Arc::new(tools);+ bind_pack_registry(&tools);++ let session = ToolPolicySession {+ profile: TaskProfile {+ agent_id: "orchestrator".to_string(),+ channel: "web_chat".to_string(),+ entrypoint: "chat".to_string(),+ risk_level: TaskRiskLevel::Low,+ allowed_permission: PermissionLevel::Dangerous,+ },+ capabilities: vec![],+ allowed_tool_names: [LOAD_SKILL, "use_skill"]+ .into_iter()+ .map(str::to_string)+ .collect(),+ blocked_tool_names: ["propose_workflow"]+ .into_iter()+ .map(str::to_string)+ .collect(),+ hidden_tool_names: Default::default(),+ decisions: [allow(LOAD_SKILL), allow("use_skill")]+ .into_iter()+ .collect(),+ };+ let mw = ToolPolicyMiddleware::new(+ Arc::new(crate::openhuman::agent::tool_policy::AllowAllToolPolicy::default()),+ session,+ vec![tools],+ "sess".to_string(),+ "web_chat".to_string(),+ "orchestrator".to_string(),+ );++ let message = mw+ .channel_permission_block(&call(+ "use_skill",+ json!({ "skill": "workflows", "tool": "propose_workflow" }),+ ))+ .expect("propose_workflow is denied");++ assert!(+ message.contains("workflow_builder"),+ "with no delegate to call, name the owning agent: {message}"+ );+ assert!(+ !message.contains("Call `build_workflow`"),+ "must not instruct a call this session cannot make: {message}"+ );+}++/// **Pre-existing, and larger than the bug this branch was opened for.**+///+/// `channel_permission_block`'s inner `use_skill` check denies on+/// `decision.is_denied()`, which is true for `HideFromPrompt`. Every withheld+/// packed tool is `HideFromPrompt` for a non-owner — that is what "withheld"+/// means. So `use_skill`, the *only* advertised route to a withheld tool, was+/// refusing all of them. AGENTS.md's disclosure table says `Withheld` is+/// "Registered and callable: yes".+#[tokio::test]+async fn use_skill_reaches_a_withheld_packed_tool() {+ use crate::openhuman::tools::agent_policy::ToolPolicyEngine;+ use crate::openhuman::tools::toolpacks::strip_packed_from_visible;++ let mut tools: Vec<Box<dyn crate::openhuman::tools::traits::Tool>> =+ vec![Box::new(RoutingFakeTool("goal_set"))];+ append_pack_tools(&mut tools);+ let tools = Arc::new(tools);+ bind_pack_registry(&tools);++ // The real harness shape: seed `visible` with everything, then withhold the+ // packed names for a non-owner.+ let mut visible: std::collections::HashSet<String> =+ tools.iter().map(|t| t.name().to_string()).collect();+ strip_packed_from_visible(&mut visible, "orchestrator");+ let session = ToolPolicyEngine::build_session(+ "orchestrator",+ "web_chat",+ "chat",+ &Default::default(),+ &tools,+ &visible,+ );++ let mw = ToolPolicyMiddleware::new(+ Arc::new(crate::openhuman::agent::tool_policy::AllowAllToolPolicy::default()),+ session,+ vec![tools],+ "sess".to_string(),+ "web_chat".to_string(),+ "orchestrator".to_string(),+ );++ assert!(+ mw.channel_permission_block(&call(+ "use_skill",+ json!({ "skill": "goals", "tool": "goal_set" }),+ ))+ .is_none(),+ "a withheld packed tool must stay reachable through use_skill — that is \+ the only route it has"+ );+}++/// **A route hint must use the predicate of the gate it points at.**+///+/// `route_sentence` tells the model to make a *direct* call, and the direct-call+/// gate rejects `HideFromPrompt`. So a prompt-hidden delegate is not a route:+/// naming it would send the model into the same refusal this branch exists to+/// remove, one hop later. The hint must fall back to the owning agent instead.+#[tokio::test]+async fn a_prompt_hidden_delegate_is_not_offered_as_a_direct_route() {+ use crate::openhuman::tools::agent_policy::ToolPolicyEngine;+ use crate::openhuman::tools::toolpacks::strip_packed_from_visible;++ let mut tools: Vec<Box<dyn crate::openhuman::tools::traits::Tool>> = vec![+ Box::new(RoutingFakeTool("propose_workflow")),+ Box::new(ArchetypeDelegationTool {+ tool_name: "build_workflow".to_string(),+ agent_id: DelegationTarget("workflow_builder".to_string()),+ tool_description: "Build a workflow".to_string(),+ }),+ ];+ append_pack_tools(&mut tools);+ let tools = Arc::new(tools);+ bind_pack_registry(&tools);++ // `build_workflow` is itself a member of the `workflows` pack, so+ // `strip_packed_from_visible` withholds it for a non-owner — leaving the+ // delegate prompt-hidden and therefore NOT directly callable.+ let mut visible: std::collections::HashSet<String> =+ tools.iter().map(|t| t.name().to_string()).collect();+ strip_packed_from_visible(&mut visible, "orchestrator");+ assert!(+ !visible.contains("build_workflow"),+ "precondition: the delegate is prompt-hidden here"+ );++ let session = ToolPolicyEngine::build_session(+ "orchestrator",+ "web_chat",+ "chat",+ &Default::default(),+ &tools,+ &visible,+ );+ let mw = ToolPolicyMiddleware::new(+ Arc::new(crate::openhuman::agent::tool_policy::AllowAllToolPolicy::default()),+ session,+ vec![tools],+ "sess".to_string(),+ "web_chat".to_string(),+ "orchestrator".to_string(),+ );++ let pack = crate::openhuman::tools::toolpacks::pack("workflows").expect("workflows pack");+ let route = mw.route_for_pack(pack);+ assert!(+ !route.contains("Call `build_workflow`"),+ "a prompt-hidden delegate must not be advertised as a direct call: {route}"+ );+ assert!(+ route.contains("workflow_builder"),+ "the hint must fall back to naming the owning agent: {route}"+ );+}diff --git a/src/openhuman/tools/agent_policy/types.rs b/src/openhuman/tools/agent_policy/types.rsindex 8405aea59e..a67b12d74e 100644--- a/src/openhuman/tools/agent_policy/types.rs+++ b/src/openhuman/tools/agent_policy/types.rs@@ -64,9 +64,52 @@ pub struct ToolPolicyDecision {}impl ToolPolicyDecision {+ /// Anything that is not a plain `Allow` — **including `HideFromPrompt`**.+ ///+ /// This is the right question for a *direct* call: a tool the model was+ /// never shown has no business being called by name, and refusing it is a+ /// deliberate safety property (see `host::security_gate`).+ ///+ /// It is the wrong question for `use_skill`. See+ /// [`Self::blocks_execution`].pub fn is_denied(&self) -> bool {!matches!(self.action, ToolPolicyAction::Allow)}++ /// Whether this tool may not be *executed*, as opposed to merely being kept+ /// off the prompt.+ ///+ /// `HideFromPrompt` is not an execution denial. It is the normal, healthy+ /// state of every withheld packed tool — AGENTS.md's disclosure table spells+ /// it out: `Withheld` means "Schemas on the wire: no (reached via+ /// `load_skill` / `use_skill`)", "Registered and callable: **yes**".+ ///+ /// Conflating the two is a live bug with teeth: `use_skill` is the only+ /// route a withheld tool has, and gating it on [`Self::is_denied`] refused+ /// every single one of them — the whole pack mechanism, not an edge case.+ /// An unknown tool still lands here, because `decision_for` defaults absent+ /// names to `Deny`: a tool this session does not have is genuinely not+ /// callable, which is the distinction that keeps owner-only tools out.+ pub fn blocks_execution(&self) -> bool {+ if matches!(+ self.action,+ ToolPolicyAction::Deny | ToolPolicyAction::RequireApproval+ ) {+ return true;+ }+ // The permission ceiling, re-checked here because the classifier cannot+ // have applied it. `build_session_from_refs` tests `explicitly_hidden`+ // BEFORE `exceeds_permission`, so a tool that is both hidden *and* over+ // the ceiling is recorded as `HideFromPrompt` and its permission verdict+ // is never taken. `is_denied()` used to mask that by treating every+ // hidden tool as blocked; a predicate that deliberately admits hidden+ // tools has to carry the ceiling itself or it hands `use_skill` a+ // laundering route into a tool the channel would refuse.+ matches!(+ self.required_permission,+ Some(required) if required > self.allowed_permission+ )+ }}/// Tool metadata used by prompt and policy summaries.diff --git a/src/openhuman/tools/orchestrator_tools.rs b/src/openhuman/tools/orchestrator_tools.rsindex a7eadd36d9..6b50fba439 100644--- a/src/openhuman/tools/orchestrator_tools.rs+++ b/src/openhuman/tools/orchestrator_tools.rs@@ -40,6 +40,7 @@ use crate::openhuman::agent::harness::definition::{#[allow(unused_imports)]use super::SpawnWorkerThreadTool;use super::{ArchetypeDelegationTool, SkillDelegationTool, Tool};+use crate::openhuman::agent::orchestration::tools::DelegationTarget;/// Synthesise the delegation tool list for an agent based on its/// declarative `subagents` field.@@ -133,7 +134,7 @@ pub fn collect_orchestrator_tools(// paying for it on every delegate schema on every turn.tools.push(Box::new(ArchetypeDelegationTool {tool_name,- agent_id: target.id.clone(),+ agent_id: DelegationTarget(target.id.clone()),tool_description: target.when_to_use.clone(),}));}diff --git a/src/openhuman/tools/toolpacks/mod.rs b/src/openhuman/tools/toolpacks/mod.rsindex 6d30f46934..3146c60b03 100644--- a/src/openhuman/tools/toolpacks/mod.rs+++ b/src/openhuman/tools/toolpacks/mod.rs@@ -30,7 +30,7 @@ pub mod types;pub use groups::{GroupMode, ToolGroups, GROUP_COUNT};pub use ops::{append_pack_tools, bind_pack_registry, strip_packed_from_visible};pub use registry::{all_packed_tool_names, pack, pack_for_tool, PACKS};-pub use tools::{PackRegistryHandle, LOAD_SKILL, USE_SKILL};+pub use tools::{render_pack_filtered, route_sentence, PackRegistryHandle, LOAD_SKILL, USE_SKILL};pub use types::ToolPack;#[cfg(test)]diff --git a/src/openhuman/tools/toolpacks/toolpacks_tests.rs b/src/openhuman/tools/toolpacks/toolpacks_tests.rsindex cd5ca13c7c..08a5aa8c4c 100644--- a/src/openhuman/tools/toolpacks/toolpacks_tests.rs+++ b/src/openhuman/tools/toolpacks/toolpacks_tests.rs@@ -45,6 +45,25 @@ impl Tool for FakeTool {}}+/// A registry holding several real packed tools plus the two pack tools, bound.+fn registry_with_all(names: &[&'static str]) -> Arc<Vec<Box<dyn Tool>>> {+ let mut tools: Vec<Box<dyn Tool>> = names+ .iter()+ .map(|name| {+ Box::new(FakeTool {+ name,+ level: PermissionLevel::ReadOnly,+ external: false,+ timeout: ToolTimeout::Inherit,+ }) as Box<dyn Tool>+ })+ .collect();+ append_pack_tools(&mut tools);+ let tools = Arc::new(tools);+ bind_pack_registry(&tools);+ tools+}+/// A registry holding one real packed tool plus the two pack tools, bound.fn registry_with(name: &'static str, level: PermissionLevel) -> Arc<Vec<Box<dyn Tool>>> {let mut tools: Vec<Box<dyn Tool>> = vec![Box::new(FakeTool {@@ -527,3 +546,96 @@ fn rebinding_a_pack_handle_repoints_it_at_the_new_registry() {"the rebound handle must resolve against the new registry, not the old one");}++// ── the listing must agree with the gate ────────────────────────────────────++/// The bug, at the layer it lives on: a non-owner was shown `propose_workflow`+/// and then refused when it called it.+///+/// `is_callable` here stands in for the session allowlist the middleware+/// applies (`channel_permission_block` denies `propose_workflow` for every+/// agent that is not `workflow_builder` / `flow_discovery`). The listing must+/// not mention a tool that gate will refuse.+#[test]+fn a_non_owner_listing_omits_the_tools_the_gate_will_refuse() {+ let tools = registry_with_all(&["build_workflow", "propose_workflow"]);+ let handle = crate::openhuman::tools::traits::pack_registry_handle(find(&tools, LOAD_SKILL))+ .expect("load_skill carries the pack handle");++ let rendered = render_pack_filtered(+ "workflows",+ handle,+ &|name: &str| name != "propose_workflow",+ "",+ )+ .expect("the pack still has a callable tool");++ assert!(+ rendered.contains("build_workflow"),+ "a tool the session CAN call must still be listed: {rendered}"+ );+ assert!(+ !rendered.contains("propose_workflow"),+ "a tool the session will refuse must not be advertised: {rendered}"+ );+}++/// When the session can reach nothing in the pack, the failure has to carry the+/// way out. A bare "no tools available" is the dead end the model retried into.+#[test]+fn a_listing_with_nothing_callable_names_the_route_out() {+ let tools = registry_with_all(&["build_workflow", "propose_workflow"]);+ let handle = crate::openhuman::tools::traits::pack_registry_handle(find(&tools, LOAD_SKILL))+ .expect("load_skill carries the pack handle");++ let route = route_sentence(&["build_workflow".to_string()], &["workflow_builder"]);+ let err = render_pack_filtered("workflows", handle, &|_| false, &route)+ .expect_err("nothing callable must not render a menu");++ assert!(+ err.contains("build_workflow"),+ "the denial must name the delegate to call instead: {err}"+ );+}++/// Naming the tool, not just the agent, is the difference between an+/// instruction and a guess — and a model that guesses wrong retries.+#[test]+fn route_sentence_prefers_a_callable_tool_and_falls_back_to_owners() {+ let named = route_sentence(&["build_workflow".to_string()], &["workflow_builder"]);+ assert!(named.contains("`build_workflow`"), "{named}");+ assert!(+ !named.contains("`workflow_builder`"),+ "naming the agent as well is noise once the call is named: {named}"+ );++ let fallback = route_sentence(&[], &["workflow_builder", "flow_discovery"]);+ assert!(fallback.contains("`workflow_builder`"), "{fallback}");+ assert!(fallback.contains("`flow_discovery`"), "{fallback}");++ assert!(+ route_sentence(&[], &[]).is_empty(),+ "an ownerless pack has no route to offer and must stay silent"+ );+}++/// The route only exists because these owners do. If the `workflows` pack is+/// ever re-owned, the hint silently stops naming `workflow_builder` — this+/// pins the assumption the two tests above rest on.+#[test]+fn the_workflows_pack_is_still_owned_by_the_flow_agents() {+ let pack = pack("workflows").expect("the workflows pack exists");+ assert!(+ pack.owners.contains(&"workflow_builder"),+ "owners moved: {:?}",+ pack.owners+ );+ assert!(+ pack.tools.contains(&"propose_workflow"),+ "propose_workflow left the pack: {:?}",+ pack.tools+ );+}++#[path = "toolpacks_tests_part_02_tests.rs"]+mod part_02_tests;diff --git a/src/openhuman/tools/toolpacks/toolpacks_tests_part_02_tests.rs b/src/openhuman/tools/toolpacks/toolpacks_tests_part_02_tests.rsnew file mode 100644index 0000000000..f139a998fe--- /dev/null+++ b/src/openhuman/tools/toolpacks/toolpacks_tests_part_02_tests.rs@@ -0,0 +1,82 @@+//! Tool-pack advertisement: the index the model reads, and the disclosure /+//! execution distinction the whole pack mechanism rests on.++use super::*;++/// **The contract this fix must not break** (AGENTS.md: `Withheld` = "Registered+/// and callable: yes"). A withheld packed tool is hidden from the prompt and+/// still callable through `use_skill` — that is the entire point of a pack.+///+/// `ToolPolicySession` records that state as `HideFromPrompt`, and+/// `ToolPolicyDecision::is_denied()` is `!matches!(action, Allow)` — so it+/// answers **true** for a perfectly callable packed tool. Any "can this session+/// call it" predicate built on `is_denied()` therefore eats the whole pack.+#[test]+fn a_withheld_packed_tool_is_hidden_but_not_denied() {+ use crate::openhuman::tools::agent_policy::{ToolPolicyAction, ToolPolicyEngine};++ let tools = registry_with_all(&["goal_set", "build_workflow"]);+ // The real shape: the harness seeds `visible` with everything, then+ // `strip_packed_from_visible` removes the packed names for a non-owner.+ let mut visible: HashSet<String> = tools.iter().map(|t| t.name().to_string()).collect();+ strip_packed_from_visible(&mut visible, "orchestrator");+ assert!(+ !visible.contains("goal_set"),+ "precondition: the packed tool is withheld from the prompt"+ );++ let session = ToolPolicyEngine::build_session(+ "orchestrator",+ "web_chat",+ "chat",+ &Default::default(),+ &tools,+ &visible,+ );++ let decision = session.decision_for("goal_set");+ assert_eq!(+ decision.action,+ ToolPolicyAction::HideFromPrompt,+ "a withheld packed tool is classified as prompt-hidden, not denied"+ );+ assert!(+ decision.is_denied(),+ "…and `is_denied()` nevertheless answers true for it — this is the trap"+ );+}++/// **The permission ceiling survives the disclosure exemption.**+///+/// `build_session_from_refs` tests `explicitly_hidden` before+/// `exceeds_permission`, so a tool that is both hidden and over the ceiling is+/// recorded as `HideFromPrompt` and never gets its permission verdict.+/// `is_denied()` masked that by blocking every hidden tool. A predicate that+/// deliberately admits hidden tools must carry the ceiling itself, or `use_skill`+/// becomes a laundering route into a tool the channel would refuse.+#[test]+fn a_hidden_tool_over_the_permission_ceiling_still_blocks_execution() {+ use crate::openhuman::tools::agent_policy::{ToolPolicyAction, ToolPolicyDecision};++ let over = ToolPolicyDecision {+ tool_name: "dangerous_packed_tool".to_string(),+ action: ToolPolicyAction::HideFromPrompt,+ required_permission: Some(PermissionLevel::Dangerous),+ allowed_permission: PermissionLevel::ReadOnly,+ };+ assert!(+ over.blocks_execution(),+ "a hidden tool above the session's ceiling must not be executable"+ );++ let within = ToolPolicyDecision {+ tool_name: "ordinary_packed_tool".to_string(),+ action: ToolPolicyAction::HideFromPrompt,+ required_permission: Some(PermissionLevel::ReadOnly),+ allowed_permission: PermissionLevel::Dangerous,+ };+ assert!(+ !within.blocks_execution(),+ "a hidden tool within the ceiling is the normal packed case and must stay callable"+ );+}diff --git a/src/openhuman/tools/toolpacks/tools.rs b/src/openhuman/tools/toolpacks/tools.rsindex be79238706..341f4edc4e 100644--- a/src/openhuman/tools/toolpacks/tools.rs+++ b/src/openhuman/tools/toolpacks/tools.rs@@ -72,7 +72,30 @@ impl PackRegistryHandle {}}-fn render_pack(skill: &str, handle: &PackRegistryHandle) -> Result<String, String> {+/// Render a pack's listing, showing only the tools `is_callable` admits.+///+/// **The filter is the whole point.** `load_skill` used to render every tool in+/// the pack this build compiled, and `use_skill` then refused any of them the+/// session's allowlist denies (`tinyagents::middleware::channel_permission_block`).+/// A non-owner was handed a menu it could not order from: the orchestrator+/// loaded `workflows`, read `propose_workflow` off the listing, called it, and+/// was told it "is not allowed in the current session". The denial named no+/// alternative, so the model retried — one live chat turn died on the+/// repeated-failure breaker after six identical denials.+///+/// `registry.rs` used to claim non-owners "reach them through `use_skill`".+/// That was never true: the gate (`d5a09ea81`, 2026-08-21) predates the comment+/// asserting it (`a8f0a002b`, 2026-08-23). The listing is the side that was+/// wrong, so the listing is the side that changed.+///+/// `route` is the sentence to append when the session can call nothing in the+/// pack — see [`route_sentence`]. Empty means "say nothing extra".+pub fn render_pack_filtered(+ skill: &str,+ handle: &PackRegistryHandle,+ is_callable: &dyn Fn(&str) -> bool,+ route: &str,+) -> Result<String, String> {let Some(pack) = registry::pack(skill) else {return Err(format!("Unknown skill `{skill}`. Available:\n{}",@@ -102,6 +125,12 @@ fn render_pack(skill: &str, handle: &PackRegistryHandle) -> Result<String, Strinlet Some(tool) = tools.iter().find(|t| t.name() == *name) else {continue;};+ // Listing a tool the gate will refuse is worse than omitting it: a+ // model cannot tell a policy denial from a transient failure, so it+ // retries the same call instead of routing around it.+ if !is_callable(name) {+ continue;+ }found += 1;out.push_str(&format!("## `{}`\n\n{}\n\n",@@ -120,14 +149,56 @@ fn render_pack(skill: &str, handle: &PackRegistryHandle) -> Result<String, Strin}if found == 0 {- return Err(format!(+ let mut message = format!("Skill `{}` has no tools available in this session.",pack.id- ));+ );+ if !route.is_empty() {+ message.push(' ');+ message.push_str(route);+ }+ return Err(message);}Ok(out)}+/// The "go here instead" sentence shared by the `load_skill` listing and the+/// `use_skill` denial, so a model never sees two different stories.+///+/// `callable_delegates` are delegation tool names the caller has already+/// confirmed this session can invoke — naming the *tool* rather than the agent+/// is the difference between guidance and an instruction, and a model left to+/// guess the call retries. When none can be reached the owning agents are named+/// instead: strictly worse, but still better than a bare denial.+pub fn route_sentence(callable_delegates: &[String], owners: &[&str]) -> String {+ if !callable_delegates.is_empty() {+ let names = callable_delegates+ .iter()+ .map(|t| format!("`{t}`"))+ .collect::<Vec<_>>()+ .join(" or ");+ return format!(+ "Call {names} instead — that agent owns these tools and runs them directly. \+ Do not retry this skill."+ );+ }+ if owners.is_empty() {+ return String::new();+ }+ format!(+ "These tools belong to {}; hand the task to one of them rather than calling directly.",+ owners+ .iter()+ .map(|o| format!("`{o}`"))+ .collect::<Vec<_>>()+ .join(" or ")+ )+}++fn render_pack(skill: &str, handle: &PackRegistryHandle) -> Result<String, String> {+ render_pack_filtered(skill, handle, &|_| true, "")+}+fn skill_enum() -> Vec<&'static str> {registry::PACKS.iter().map(|p| p.id).collect()}diff --git a/src/openhuman/tools/traits.rs b/src/openhuman/tools/traits.rsindex 8181206ced..ee2b2c10ac 100644--- a/src/openhuman/tools/traits.rs+++ b/src/openhuman/tools/traits.rs@@ -24,6 +24,7 @@ pub use tinytools::{ToolCategory, ToolContent, ToolResult, ToolRunContext, ToolScope, ToolSpec, ToolTimeout,};+use crate::openhuman::agent::orchestration::tools::DelegationTarget;use crate::openhuman::agent::tool_policy::GeneratedToolRuntimeContext;use crate::openhuman::tools::toolpacks::PackRegistryHandle;@@ -42,6 +43,22 @@ pub fn pack_registry_handle(tool: &dyn Tool) -> Option<&PackRegistryHandle> {.and_then(|any| any.downcast_ref::<PackRegistryHandle>())}+/// Reads the agent a synthesised `delegate_*` tool routes to.+///+/// The toolpack route hint uses this to answer "which of this pack's owner+/// agents can this session actually reach, and under what tool name?" without+/// keeping a second copy of every agent's `delegate_name`. Asking the session's+/// own tool set is what makes the answer trustworthy: a delegate the session was+/// not built with simply is not there to find, so a hint can never name a call+/// the model cannot make.+///+/// Erased for the same reason as [`pack_registry_handle`].+pub fn delegation_target(tool: &dyn Tool) -> Option<&str> {+ tool.host_extension()+ .and_then(|any| any.downcast_ref::<DelegationTarget>())+ .map(|target| target.0.as_str())+}+/// Reads a tool's generated-tool runtime metadata back out of the erased/// per-call host extension.///