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 calls to withheld packed tools through use_skill

M3gA-Mindaa21918e71dd
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 3c2024ef11..41a920c2a8 100644
--- a/crates/openhuman-core/src/agent/agent_turn_loop_tests.rs
+++ b/crates/openhuman-core/src/agent/agent_turn_loop_tests.rs
@@ -194,6 +194,87 @@ async fn turn_handles_unknown_tool_gracefully() {
);
}
+/// Stands in for a packed tool and records the arguments it ran with.
+struct RecordingPackedTool(Arc<Mutex<Option<serde_json::Value>>>);
+
+#[async_trait]
+impl Tool for RecordingPackedTool {
+ fn name(&self) -> &str {
+ "skill_registry_search"
+ }
+
+ fn description(&self) -> &str {
+ "Search available skills by keyword."
+ }
+
+ fn parameters_schema(&self) -> serde_json::Value {
+ serde_json::json!({
+ "type": "object",
+ "properties": { "query": { "type": "string" } },
+ "required": ["query"]
+ })
+ }
+
+ async fn execute(&self, args: serde_json::Value) -> Result<ToolResult> {
+ *self.0.lock().unwrap() = Some(args);
+ Ok(ToolResult::success("found: code-reviewer"))
+ }
+}
+
+// #6276: the model reads a packed tool's bare name (pack listing, sibling
+// descriptions) and calls it as a top-level tool. That call must reach the tool
+// through its pack, not loop on "unknown tool".
+#[tokio::test]
+async fn turn_routes_a_bare_packed_tool_call_through_use_skill() {
+ let provider = Arc::new(ScriptedProvider::new(vec![
+ tool_response(vec![ToolCall {
+ id: "tc1".into(),
+ name: "skill_registry_search".into(),
+ arguments: r#"{"query": "code review"}"#.into(),
+ extra_content: None,
+ }]),
+ text_response("found one"),
+ ]));
+ let ran = Arc::new(Mutex::new(None));
+ let mut tools: Vec<Box<dyn Tool>> = vec![Box::new(RecordingPackedTool(ran.clone()))];
+ crate::tools::toolpacks::append_pack_tools(&mut tools);
+
+ let (mut agent, _tmp) = build_agent_with(provider, tools, Box::new(NativeToolDispatcher));
+ assert!(
+ !agent
+ .visible_tool_names_for_test()
+ .contains("skill_registry_search"),
+ "precondition: the tool is withheld behind its pack"
+ );
+
+ agent.turn("find a code review skill").await.unwrap();
+
+ assert_eq!(
+ ran.lock().unwrap().clone(),
+ Some(serde_json::json!({ "query": "code review" })),
+ "a bare call to a withheld packed tool must run that tool with its own arguments"
+ );
+ let results: Vec<String> = agent
+ .history()
+ .iter()
+ .filter_map(|msg| match msg {
+ ConversationMessage::ToolResults(results) => Some(
+ results
+ .iter()
+ .map(|r| r.content.clone())
+ .collect::<Vec<_>>(),
+ ),
+ _ => None,
+ })
+ .flatten()
+ .collect();
+ assert!(
+ results.iter().any(|c| c.contains("found: code-reviewer"))
+ && !results.iter().any(|c| c.contains("unknown tool")),
+ "the model must see the tool's result, not an unknown-tool error: {results:?}"
+ );
+}
+
// ═══════════════════════════════════════════════════════════════════════════
// 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 9bb0a2f150..6d215c2d4a 100644
--- a/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/harness_assembly.rs
@@ -675,6 +675,16 @@ pub(super) fn assemble_turn_harness(
tool_sets.clone(),
)));
+ // 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
+ // `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,
+ )));
+
// Embedder tool lifecycle hooks. Registered AFTER `ArgRecoveryMiddleware`:
// `before_tool` runs in registration order, so a hook installed earlier would
// observe the provider's raw (possibly JSON-encoded-string / non-object)
diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware.rs b/crates/openhuman-core/src/agent/tinyagents/middleware.rs
index 88764b48c8..6463c44a02 100644
--- a/crates/openhuman-core/src/agent/tinyagents/middleware.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware.rs
@@ -35,6 +35,7 @@ mod final_call_wrap_up;
mod loop_guards;
mod memory_protocol;
mod message_trim;
+mod packed_tool_route;
mod prompt_cache;
mod repeat_progress;
mod repeated_failure;
@@ -54,6 +55,7 @@ pub(crate) use embedder_hooks::EmbedderToolHooksMiddleware;
pub(crate) use final_call_wrap_up::FinalCallWrapUpMiddleware;
pub use memory_protocol::MemoryProtocolMiddleware;
pub(crate) use message_trim::{legacy_max_input_tokens, ImageAwareMessageTrimMiddleware};
+pub(crate) use packed_tool_route::PackedToolRouteMiddleware;
pub(crate) use prompt_cache::PromptCacheSegmentMiddleware;
pub(crate) use repeat_progress::RepeatProgressMiddleware;
pub(crate) use repeated_failure::RepeatedToolFailureMiddleware;
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
new file mode 100644
index 0000000000..1233e56f98
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/packed_tool_route.rs
@@ -0,0 +1,105 @@
+//! [`PackedToolRouteMiddleware`]: route a call that names a withheld packed tool
+//! by its bare name through `use_skill`, instead of answering "unknown tool".
+
+use std::collections::HashSet;
+
+use async_trait::async_trait;
+use serde_json::{json, Value};
+
+use tinyagents_harness::context::RunContext;
+use tinyagents_harness::error::Result as TaResult;
+use tinyagents_harness::middleware::Middleware;
+use tinyinference::tool::ToolCall as TaToolCall;
+
+use crate::tools::toolpacks::{self, GroupMode, USE_SKILL};
+
+/// `before_tool`: rewrite `name(args)` into
+/// `use_skill { "skill": <pack>, "tool": name, "args": args }` when `name` is a
+/// withheld packed tool this turn did not register (#6276).
+///
+/// A pack withholds a tool's schema, not its name. The pack listing documents
+/// every tool under its bare name, and sibling descriptions and prompts refer to
+/// it the same way, so a model calls that name as a top-level tool. The crate's
+/// unknown-tool answer lists only the registered tools and never says the tool
+/// 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.
+///
+/// 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 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>,
+}
+
+impl PackedToolRouteMiddleware {
+ /// Build the middleware over the names this turn registered.
+ pub(crate) fn new(registered: impl IntoIterator<Item = String>) -> Self {
+ Self {
+ registered: registered.into_iter().collect(),
+ }
+ }
+
+ /// Rewrite `call` in place when it should be routed; `true` if it was.
+ fn route(&self, call: &mut TaToolCall) -> bool {
+ if call.invalid.is_some()
+ || self.registered.contains(&call.name)
+ || !self.registered.contains(USE_SKILL)
+ {
+ return false;
+ }
+ let Some(pack) = toolpacks::pack_for_tool(&call.name) else {
+ return false;
+ };
+ if toolpacks::groups::current().mode_for_tool(&call.name) != GroupMode::Withheld {
+ return false;
+ }
+ let args = match call.arguments {
+ Value::Object(_) => call.arguments.take(),
+ Value::Null => json!({}),
+ _ => return false,
+ };
+ let tool = std::mem::replace(&mut call.name, USE_SKILL.to_string());
+ tracing::info!(
+ tool = %tool,
+ skill = pack.id,
+ call_id = %call.id,
+ "[toolpacks] routed bare packed tool call through use_skill"
+ );
+ call.arguments = json!({ "skill": pack.id, "tool": tool, "args": args });
+ true
+ }
+}
+
+#[async_trait]
+impl Middleware<()> for PackedToolRouteMiddleware {
+ fn name(&self) -> &str {
+ "packed_tool_route"
+ }
+
+ async fn before_tool(
+ &self,
+ _ctx: &mut RunContext<()>,
+ _state: &(),
+ call: &mut TaToolCall,
+ ) -> TaResult<()> {
+ self.route(call);
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+#[path = "packed_tool_route_tests.rs"]
+mod tests;
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
new file mode 100644
index 0000000000..184bd5ff2a
--- /dev/null
+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/packed_tool_route_tests.rs
@@ -0,0 +1,58 @@
+use super::*;
+
+fn middleware(registered: &[&str]) -> PackedToolRouteMiddleware {
+ PackedToolRouteMiddleware::new(registered.iter().map(|n| n.to_string()))
+}
+
+#[test]
+fn a_bare_packed_call_becomes_the_use_skill_call_that_reaches_it() {
+ let mw = middleware(&["use_skill", "shell"]);
+ let mut call = TaToolCall::new("c1", "skill_registry_search", json!({ "query": "x" }));
+
+ assert!(mw.route(&mut call));
+ assert_eq!(call.name, "use_skill");
+ assert_eq!(
+ call.arguments,
+ json!({ "skill": "skills", "tool": "skill_registry_search", "args": { "query": "x" } })
+ );
+}
+
+#[test]
+fn calls_the_crate_should_answer_are_left_alone() {
+ let unparseable = TaToolCall {
+ invalid: Some("bad json".into()),
+ ..TaToolCall::new("c1", "skill_registry_search", json!("{query"))
+ };
+ let cases = [
+ (
+ middleware(&["use_skill"]),
+ TaToolCall::new("c1", "made_up_tool", json!({})),
+ "a name no pack owns",
+ ),
+ (
+ middleware(&["use_skill", "file_read"]),
+ TaToolCall::new("c1", "file_read", json!({})),
+ "a registered name",
+ ),
+ (
+ middleware(&["shell"]),
+ TaToolCall::new("c1", "skill_registry_search", json!({})),
+ "a turn without use_skill",
+ ),
+ (
+ middleware(&["use_skill"]),
+ TaToolCall::new("c1", "skill_registry_search", json!(["x"])),
+ "non-object arguments",
+ ),
+ (
+ middleware(&["use_skill"]),
+ unparseable,
+ "unparseable arguments",
+ ),
+ ];
+ for (mw, mut call, why) in cases {
+ let before = call.clone();
+ assert!(!mw.route(&mut call), "{why}: must not route");
+ assert_eq!(call, before, "{why}: call must be untouched");
+ }
+}
diff --git a/crates/openhuman-core/src/tools/toolpacks/README.md b/crates/openhuman-core/src/tools/toolpacks/README.md
index 1b774b198d..93db172202 100644
--- a/crates/openhuman-core/src/tools/toolpacks/README.md
+++ b/crates/openhuman-core/src/tools/toolpacks/README.md
@@ -111,6 +111,11 @@ to that delegate, not a second skill runtime.
(`named_tool` is `None`) and renders it with `render_pack_filtered` against
the session's allowlist, with `route_sentence` naming the owner delegate
when nothing in the pack is callable.
+- `agent/tinyagents/middleware/packed_tool_route.rs` — `before_tool`
+ 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).
- `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