Skip to content

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

fix(agent): route bare packed-tool calls only where the session allows

M3gA-Mindc1f2fa18abd3
diff --git a/crates/openhuman-core/src/agent/agent_turn_loop_tests.rs b/crates/openhuman-core/src/agent/agent_turn_loop_tests.rs
index 41a920c2a8..126f27ff42 100644
--- a/crates/openhuman-core/src/agent/agent_turn_loop_tests.rs
+++ b/crates/openhuman-core/src/agent/agent_turn_loop_tests.rs
@@ -275,6 +275,79 @@ async fn turn_routes_a_bare_packed_tool_call_through_use_skill() {
);
}
+/// A packed tool that needs `Write` and records whether it ran.
+struct WritePackedTool(Arc<Mutex<bool>>);
+
+#[async_trait]
+impl Tool for WritePackedTool {
+ fn name(&self) -> &str {
+ "skill_registry_install"
+ }
+
+ fn description(&self) -> &str {
+ "Install a skill from the catalog."
+ }
+
+ fn parameters_schema(&self) -> serde_json::Value {
+ serde_json::json!({ "type": "object" })
+ }
+
+ async fn execute(&self, _args: serde_json::Value) -> Result<ToolResult> {
+ *self.0.lock().unwrap() = true;
+ Ok(ToolResult::success("installed"))
+ }
+
+ fn permission_level(&self) -> crate::tools::PermissionLevel {
+ crate::tools::PermissionLevel::Write
+ }
+}
+
+// #6276 review: routing must never be a way around the session's gate. A packed
+// tool this channel may not run is not rewritten at all: it keeps the crate's
+// unknown-tool answer and never executes.
+#[tokio::test]
+async fn turn_does_not_route_a_bare_call_the_session_would_refuse() {
+ let provider = Arc::new(ScriptedProvider::new(vec![
+ tool_response(vec![ToolCall {
+ id: "tc1".into(),
+ name: "skill_registry_install".into(),
+ arguments: r#"{"entry_id": "code-reviewer"}"#.into(),
+ extra_content: None,
+ }]),
+ text_response("could not install"),
+ ]));
+ let ran = Arc::new(Mutex::new(false));
+ let mut tools: Vec<Box<dyn Tool>> = vec![Box::new(WritePackedTool(ran.clone()))];
+ crate::tools::toolpacks::append_pack_tools(&mut tools);
+ // The builder's default event channel is `internal`; cap it at read-only.
+ let config = AgentConfig {
+ channel_permissions: std::collections::HashMap::from([(
+ "internal".to_string(),
+ "read".to_string(),
+ )]),
+ ..AgentConfig::default()
+ };
+
+ let (mut agent, _tmp) = build_agent_with_config(provider, tools, config);
+ agent.turn("install a code review skill").await.unwrap();
+
+ assert!(
+ !*ran.lock().unwrap(),
+ "a packed tool the session blocks must not run through a bare call"
+ );
+ let unrouted = agent.history().iter().any(|msg| match msg {
+ ConversationMessage::ToolResults(results) => results
+ .iter()
+ .any(|r| r.content.contains("unknown tool `skill_registry_install`")),
+ _ => false,
+ });
+ assert!(
+ unrouted,
+ "a bare call the session would refuse must not be rewritten into use_skill: {:?}",
+ agent.history()
+ );
+}
+
// ═══════════════════════════════════════════════════════════════════════════
// 6. Tool execution failure recovery
// ═══════════════════════════════════════════════════════════════════════════
diff --git a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs
index 6d215c2d4a..b0feec9d85 100644
--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs
@@ -642,6 +642,11 @@ pub(super) fn assemble_turn_harness(
// path bypassed it, so a deny/require-approval silently no-opped (security
// regression). Installed only when the caller threads an enforcement context
// (the session chat path); channel/CLI + sub-agent paths pass `None`.
+ // The packed-tool router below gates on the same session, and `None`
+ // disables it, so take a copy before the enforcement is moved.
+ let route_session = tool_policy
+ .as_ref()
+ .map(|enforcement| enforcement.session.clone());
if let Some(enforcement) = tool_policy {
harness.push_tool_middleware(Arc::new(middleware::ToolPolicyMiddleware::new(
enforcement.policy,
@@ -677,12 +682,14 @@ pub(super) fn assemble_turn_harness(
// Bare packed-tool routing (`before_tool`, #6276): a call that names a
// withheld packed tool directly becomes the `use_skill` call that reaches
- // it, ahead of admission, so every gate above still applies. After
+ // it, ahead of admission, so every gate above still applies. Only when the
+ // session lets that tool run, and never without a session. After
// `ArgRecoveryMiddleware` so it wraps recovered arguments; before the
// embedder hooks so they observe the call that actually runs.
let registered_tools = harness.tools().names();
harness.push_middleware(Arc::new(middleware::PackedToolRouteMiddleware::new(
registered_tools,
+ route_session,
)));
// Embedder tool lifecycle hooks. Registered AFTER `ArgRecoveryMiddleware`:
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/packed_tool_route.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/packed_tool_route.rs
index 1233e56f98..6fe95efbc8 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/packed_tool_route.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/packed_tool_route.rs
@@ -11,6 +11,7 @@ use tinyagents_harness::error::Result as TaResult;
use tinyagents_harness::middleware::Middleware;
use tinyinference::tool::ToolCall as TaToolCall;
+use crate::tools::agent_policy::ToolPolicySession;
use crate::tools::toolpacks::{self, GroupMode, USE_SKILL};
/// `before_tool`: rewrite `name(args)` into
@@ -24,31 +25,53 @@ use crate::tools::toolpacks::{self, GroupMode, USE_SKILL};
/// exists behind a pack: live turns re-read the listing and repeated the bare
/// call until the turn ran out, and nothing was ever run.
///
-/// **Routing, not a better error, because routing grants nothing new.** The
-/// rewrite happens in `before_tool`, ahead of admission, so the rewritten call
-/// goes through exactly what an explicit `use_skill` call goes through: schema
-/// validation, the approval gate, the CLI-only gate, the session allowlist on the
-/// inner tool, and permission forwarding. `use_skill` still refuses a tool its
-/// pack does not own. The intent is unambiguous (the name is in the compiled
-/// pack table), and an error would spend a round trip telling the model to make
-/// this same call.
+/// **Only where the session says the tool may run.** Routing is gated on the
+/// same predicate `ToolPolicyMiddleware` applies to `use_skill`'s inner tool and
+/// the pack listing applies to what it shows:
+/// `session.decision_for(name).blocks_execution()`. That decision is `Deny` for a
+/// name the session does not have, so a tool outside this agent's registry, over
+/// the channel ceiling, or refused by policy is never routed. The gate lives here
+/// rather than relying on the gate downstream, so a blocked tool keeps the
+/// crate's `unknown tool` answer instead of being rewritten at all.
+///
+/// **No session, no routing.** Sub-agent and channel/CLI turns carry no
+/// tool-policy session: they bound their tools with the registration allowlist,
+/// they never withhold packs, and nothing on those paths checks `use_skill`'s
+/// inner tool. There an unregistered packed name was excluded by the allowlist,
+/// so rewriting it into `use_skill` would walk around that boundary.
+///
+/// When it does route, the rewrite happens ahead of admission, so the call then
+/// goes through what an explicit `use_skill` call goes through: schema
+/// validation, the approval gate, the CLI-only gate, `ToolPolicyMiddleware`, and
+/// permission forwarding. Routing rather than an error because the intent is
+/// unambiguous (the name is in the compiled pack table), and an error would spend
+/// a round trip telling the model to make this same call.
///
/// Left alone, so the crate's own recovery answers:
/// * a name no pack owns (a hallucinated tool),
/// * a registered name (a pack owner keeps its belt advertised),
/// * a turn without `use_skill`, where the tool has no route at all,
+/// * a turn without a tool-policy session (sub-agent, channel/CLI),
+/// * a tool the session blocks,
/// * a group that is not `Withheld` (`Off` is not registered anywhere),
/// * arguments that failed to parse or are not an object.
pub(crate) struct PackedToolRouteMiddleware {
/// Tool names registered on this turn's harness.
registered: HashSet<String>,
+ /// This turn's tool-policy snapshot; `None` disables routing.
+ session: Option<ToolPolicySession>,
}
impl PackedToolRouteMiddleware {
- /// Build the middleware over the names this turn registered.
- pub(crate) fn new(registered: impl IntoIterator<Item = String>) -> Self {
+ /// Build the middleware over the names this turn registered and the turn's
+ /// tool-policy session, if it has one.
+ pub(crate) fn new(
+ registered: impl IntoIterator<Item = String>,
+ session: Option<ToolPolicySession>,
+ ) -> Self {
Self {
registered: registered.into_iter().collect(),
+ session,
}
}
@@ -60,6 +83,12 @@ impl PackedToolRouteMiddleware {
{
return false;
}
+ let Some(session) = &self.session else {
+ return false;
+ };
+ if session.decision_for(&call.name).blocks_execution() {
+ return false;
+ }
let Some(pack) = toolpacks::pack_for_tool(&call.name) else {
return false;
};
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/packed_tool_route_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/packed_tool_route_tests.rs
index 184bd5ff2a..f9beccae62 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware/packed_tool_route_tests.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/packed_tool_route_tests.rs
@@ -1,12 +1,68 @@
use super::*;
+use std::collections::HashMap;
-fn middleware(registered: &[&str]) -> PackedToolRouteMiddleware {
- PackedToolRouteMiddleware::new(registered.iter().map(|n| n.to_string()))
+use crate::tools::agent_policy::ToolPolicyEngine;
+use crate::tools::{PermissionLevel, Tool, ToolResult};
+
+/// `skill_registry_search` with a chosen permission level.
+struct PackedFake(PermissionLevel);
+
+#[async_trait]
+impl Tool for PackedFake {
+ fn name(&self) -> &str {
+ "skill_registry_search"
+ }
+
+ fn description(&self) -> &str {
+ "fake"
+ }
+
+ fn parameters_schema(&self) -> Value {
+ json!({ "type": "object" })
+ }
+
+ async fn execute(&self, _args: Value) -> anyhow::Result<ToolResult> {
+ Ok(ToolResult::success("ok"))
+ }
+
+ fn permission_level(&self) -> PermissionLevel {
+ self.0
+ }
+}
+
+/// A session in which `skill_registry_search` is withheld behind its pack
+/// (hidden from the prompt, `use_skill` visible). `ceiling` is the channel's
+/// permission; `None` means no channel policy is configured.
+fn session(required: PermissionLevel, ceiling: Option<&str>) -> ToolPolicySession {
+ let tools: Vec<Box<dyn Tool>> = vec![Box::new(PackedFake(required))];
+ let permissions: HashMap<String, String> = ceiling
+ .map(|c| ("web".to_string(), c.to_string()))
+ .into_iter()
+ .collect();
+ ToolPolicyEngine::build_session(
+ "orchestrator",
+ "web",
+ "chat",
+ &permissions,
+ &tools,
+ &HashSet::from(["use_skill".to_string()]),
+ )
+}
+
+fn open_session() -> Option<ToolPolicySession> {
+ Some(session(PermissionLevel::ReadOnly, None))
+}
+
+fn middleware(
+ registered: &[&str],
+ session: Option<ToolPolicySession>,
+) -> PackedToolRouteMiddleware {
+ PackedToolRouteMiddleware::new(registered.iter().map(|n| n.to_string()), session)
}
#[test]
fn a_bare_packed_call_becomes_the_use_skill_call_that_reaches_it() {
- let mw = middleware(&["use_skill", "shell"]);
+ let mw = middleware(&["use_skill", "shell"], open_session());
let mut call = TaToolCall::new("c1", "skill_registry_search", json!({ "query": "x" }));
assert!(mw.route(&mut call));
@@ -25,27 +81,40 @@ fn calls_the_crate_should_answer_are_left_alone() {
};
let cases = [
(
- middleware(&["use_skill"]),
+ middleware(&["use_skill"], open_session()),
TaToolCall::new("c1", "made_up_tool", json!({})),
"a name no pack owns",
),
(
- middleware(&["use_skill", "file_read"]),
+ middleware(&["use_skill", "file_read"], open_session()),
TaToolCall::new("c1", "file_read", json!({})),
"a registered name",
),
(
- middleware(&["shell"]),
+ middleware(&["shell"], open_session()),
TaToolCall::new("c1", "skill_registry_search", json!({})),
"a turn without use_skill",
),
(
- middleware(&["use_skill"]),
+ middleware(&["use_skill"], None),
+ TaToolCall::new("c1", "skill_registry_search", json!({})),
+ "a turn without a tool-policy session (sub-agent, channel/CLI)",
+ ),
+ (
+ middleware(
+ &["use_skill"],
+ Some(session(PermissionLevel::Write, Some("read"))),
+ ),
+ TaToolCall::new("c1", "skill_registry_search", json!({})),
+ "a tool over the channel ceiling",
+ ),
+ (
+ middleware(&["use_skill"], open_session()),
TaToolCall::new("c1", "skill_registry_search", json!(["x"])),
"non-object arguments",
),
(
- middleware(&["use_skill"]),
+ middleware(&["use_skill"], open_session()),
unparseable,
"unparseable arguments",
),
diff --git a/crates/openhuman-core/src/tools/toolpacks/README.md b/crates/openhuman-core/src/tools/toolpacks/README.md
index 93db172202..f682ea0d10 100644
--- a/crates/openhuman-core/src/tools/toolpacks/README.md
+++ b/crates/openhuman-core/src/tools/toolpacks/README.md
@@ -115,7 +115,10 @@ to that delegate, not a second skill runtime.
rewrites a call that names a withheld packed tool by its bare name (the name
the listing and sibling descriptions use) into the `use_skill` call that
reaches it, ahead of admission, so the rewritten call passes every gate an
- explicit `use_skill` call does (#6276).
+ explicit `use_skill` call does (#6276). It routes only when the turn's
+ tool-policy session lets that tool run (`blocks_execution()` is false), and
+ never on a turn without a session (sub-agent, channel/CLI), where an
+ unregistered name was excluded by the registration allowlist.
- `agent/registry/agents/orchestrator/prompt.rs` — `pack_for_tool` to tell
the orchestrator which pack a withheld delegate lives in.
- `crates/openhuman-embed/` — re-exports `GroupMode` and `ToolGroups` and