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
Merge remote-tracking branch 'upstream/main' into prompt-capture-live
Steven Enamakele04ea936d4ae
diff --cc src/openhuman/agent/harness/session/builder/builder_tests.rsindex 6611dfa0ff,c9004fd23a..f3bc3b06a3--- a/src/openhuman/agent/harness/session/builder/builder_tests.rs+++ b/src/openhuman/agent/harness/session/builder/builder_tests.rs@@@ -69,3 -70,205 +70,191 @@@ mod part_01_testsmod part_02_tests;#[path = "builder_tests_part_03_tests.rs"]mod part_03_tests;+-// ── load_skill's advertised spec is scoped to the session ───────────────────++// ── use_skill's advertised spec is scoped to the session ────────────────────++ use crate::openhuman::tools::agent_policy::{+ TaskProfile, TaskRiskLevel, ToolPolicyAction, ToolPolicyDecision, ToolPolicySession,+ };+ use crate::openhuman::tools::traits::PermissionLevel;++ fn session_allowing(names: &[&str]) -> ToolPolicySession {+ 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: names.iter().map(|n| n.to_string()).collect(),+ blocked_tool_names: Default::default(),+ hidden_tool_names: Default::default(),+ decisions: names+ .iter()+ .map(|n| {+ (+ n.to_string(),+ ToolPolicyDecision {+ tool_name: n.to_string(),+ action: ToolPolicyAction::Allow,+ required_permission: None,+ allowed_permission: PermissionLevel::Dangerous,+ },+ )+ })+ .collect(),+ }+ }+-fn load_skill_spec_from_registry() -> ToolSpec {++fn use_skill_spec_from_registry() -> ToolSpec {+ let mut tools: Vec<Box<dyn crate::openhuman::tools::traits::Tool>> = Vec::new();+ crate::openhuman::tools::toolpacks::append_pack_tools(&mut tools);+ let tool = tools+ .iter()- .find(|t| t.name() == crate::openhuman::tools::toolpacks::LOAD_SKILL)- .expect("append_pack_tools registers load_skill");++ .find(|t| t.name() == crate::openhuman::tools::toolpacks::USE_SKILL)++ .expect("append_pack_tools registers use_skill");+ ToolSpec {+ name: tool.name().to_string(),+ description: tool.description().to_string(),+ parameters: tool.parameters_schema(),+ }+ }++ /// Proves the scoping is actually WIRED, not merely available. A correct helper+ /// nobody calls advertises every pack exactly as before.+ #[test]-fn visible_specs_scope_load_skills_index_to_the_session() {- let specs = vec![- load_skill_spec_from_registry(),- spec(crate::openhuman::tools::toolpacks::USE_SKILL),- ];++fn visible_specs_scope_use_skills_index_to_the_session() {++ let specs = vec![use_skill_spec_from_registry()];+ let visible: std::collections::HashSet<String> = specs.iter().map(|s| s.name.clone()).collect();+ // Reachable: one workflows tool. Everything else in every other pack is+ // denied, exactly like the orchestrator against `system` / `audio`.+ let session = session_allowing(&[+ "run_workflow",- crate::openhuman::tools::toolpacks::LOAD_SKILL,+ crate::openhuman::tools::toolpacks::USE_SKILL,+ ]);++ let out = visible_tool_specs_for_policy(&specs, &visible, &session);+ let load = out+ .iter()- .find(|s| s.name == crate::openhuman::tools::toolpacks::LOAD_SKILL)- .expect("load_skill is still offered — workflows is reachable");++ .find(|s| s.name == crate::openhuman::tools::toolpacks::USE_SKILL)++ .expect("use_skill is still offered — workflows is reachable");++ assert!(+ load.description.contains("`workflows`"),+ "the reachable pack must survive: {}",+ load.description+ );+ assert!(+ !load.description.contains("`system`"),+ "a pack with nothing callable must not reach the wire: {}",+ load.description+ );+ let ids = load+ .parameters+ .pointer("/properties/skill/enum")+ .and_then(|v| v.as_array())+ .expect("skill enum")+ .iter()+ .filter_map(|v| v.as_str())+ .collect::<Vec<_>>();+ assert_eq!(ids, vec!["workflows"], "the enum is scoped too");+ }+-/// A session that can reach no pack at all should not carry the pack tools.++/// A session that can reach no pack at all should not carry the pack tool.+ #[test]-fn visible_specs_drop_the_pack_tools_when_no_pack_is_reachable() {- let specs = vec![- load_skill_spec_from_registry(),- spec(crate::openhuman::tools::toolpacks::USE_SKILL),- ];++fn visible_specs_drop_the_pack_tool_when_no_pack_is_reachable() {++ let specs = vec![use_skill_spec_from_registry()];+ let visible: std::collections::HashSet<String> = specs.iter().map(|s| s.name.clone()).collect();- let session = session_allowing(&[- crate::openhuman::tools::toolpacks::LOAD_SKILL,- crate::openhuman::tools::toolpacks::USE_SKILL,- ]);++ let session = session_allowing(&[crate::openhuman::tools::toolpacks::USE_SKILL]);++ let out = visible_tool_specs_for_policy(&specs, &visible, &session);+ assert!(+ out.is_empty(),- "with no reachable pack, neither pack tool earns its schema: {:?}",++ "with no reachable pack, the pack tool does not earn its schema: {:?}",+ out.iter().map(|s| &s.name).collect::<Vec<_>>()+ );+ }++ /// **The regression Codex caught on #6215, pinned with a realistic session.**+ ///+ /// My first tests hand-built a `ToolPolicySession` whose `decisions` were+ /// explicit `Allow`s — a fixture that cannot express the state every packed+ /// tool is actually in. The real harness strips packed names from `visible`,+ /// which classifies them `HideFromPrompt`, and `is_denied()` answers true for+ /// that. A predicate built on `is_denied` therefore reported *no* pack as-/// reachable and dropped `load_skill` and `use_skill` from the wire — deleting++/// reachable and dropped `use_skill` from the wire — deleting+ /// the only route to every withheld tool.+ #[test]+ fn a_realistic_withheld_session_keeps_its_packs_advertised() {+ use crate::openhuman::tools::agent_policy::ToolPolicyEngine;+ use crate::openhuman::tools::toolpacks::{append_pack_tools, strip_packed_from_visible};++ struct Fake(&'static str);+ #[async_trait::async_trait]+ impl crate::openhuman::tools::traits::Tool for Fake {+ 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,+ _a: serde_json::Value,+ ) -> anyhow::Result<crate::openhuman::tools::traits::ToolResult> {+ Ok(crate::openhuman::tools::traits::ToolResult::success("ok"))+ }+ }++ let mut tools: Vec<Box<dyn crate::openhuman::tools::traits::Tool>> =+ vec![Box::new(Fake("goal_set")), Box::new(Fake("goal_get"))];+ append_pack_tools(&mut tools);++ 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("goal_set"),+ "precondition: the pack is withheld from the prompt"+ );++ let session = ToolPolicyEngine::build_session(+ "orchestrator",+ "web_chat",+ "chat",+ &Default::default(),+ &tools,+ &visible,+ );++ let specs: Vec<ToolSpec> = tools+ .iter()+ .map(|t| ToolSpec {+ name: t.name().to_string(),+ description: t.description().to_string(),+ parameters: t.parameters_schema(),+ })+ .collect();++ let out = visible_tool_specs_for_policy(&specs, &visible, &session);+ let names: Vec<&str> = out.iter().map(|s| s.name.as_str()).collect();+- assert!(- names.contains(&crate::openhuman::tools::toolpacks::LOAD_SKILL),- "load_skill must survive — the pack it opens is reachable: {names:?}"- );+ assert!(+ names.contains(&crate::openhuman::tools::toolpacks::USE_SKILL),- "use_skill must survive alongside it: {names:?}"++ "use_skill must survive — the pack it opens is reachable: {names:?}"+ );+ let load = out+ .iter()- .find(|s| s.name == crate::openhuman::tools::toolpacks::LOAD_SKILL)- .expect("load_skill spec");++ .find(|s| s.name == crate::openhuman::tools::toolpacks::USE_SKILL)++ .expect("use_skill spec");+ assert!(+ load.description.contains("`goals`"),+ "the withheld-but-callable pack must still be advertised: {}",+ load.description+ );+ }diff --cc src/openhuman/agent/harness/session/builder/mod.rsindex ad788c919a,7cb04362bf..66840f9000--- a/src/openhuman/agent/harness/session/builder/mod.rs+++ b/src/openhuman/agent/harness/session/builder/mod.rs@@@ -91,6 -91,23 +91,23 @@@ pub(super) fn visible_tool_specs_for_povisible_names: &std::collections::HashSet<String>,tool_policy: &ToolPolicySession,) -> Vec<ToolSpec> {- // `load_skill`'s description carries the pack index, and its `skill` enum- // carries the pack ids. Both are built once in `LoadSkillTool::new`, before++ // `use_skill`'s description carries the pack index, and its `skill` enum++ // carries the pack ids. Both are built once in `UseSkillTool::new`, before+ // any session exists, so every agent was told all ten packs were loadable —+ // including ones it can call nothing in. The model went, found out, and came+ // back.+ //+ // This is the only place that turns tools into the specs a provider sees AND+ // holds the session, so it is where the invitation is made to agree with the+ // gate. The same predicate the gate uses (`decision_for(..).is_denied()`),+ // not `is_allowed` — matching the filter above would re-introduce the two+ // sources of truth this whole fix exists to collapse.+ // `blocks_execution`, not `is_denied`: a withheld packed tool is+ // `HideFromPrompt` and perfectly callable through `use_skill`. Using+ // `is_denied` here would drop every pack from the index and then drop- // `load_skill` / `use_skill` themselves — the exact capability the pack- // mechanism exists to preserve.++ // `use_skill` itself — the exact capability the pack mechanism exists to++ // preserve.+ let is_callable = |name: &str| !tool_policy.decision_for(name).blocks_execution();tool_specs.iter().filter(|spec| {@@@ -98,6 -115,25 +115,18 @@@&& tool_policy.is_allowed(&spec.name)}).cloned()+ .filter_map(|mut spec| {- if spec.name == crate::openhuman::tools::toolpacks::LOAD_SKILL {++ if spec.name == crate::openhuman::tools::toolpacks::USE_SKILL {+ // `false` means no pack has a callable tool: an empty index and+ // an empty enum are not a tool, so drop it rather than ship one.- return crate::openhuman::tools::toolpacks::scope_load_skill_spec(++ return crate::openhuman::tools::toolpacks::scope_use_skill_spec(+ &mut spec,+ &is_callable,+ )+ .then_some(spec);+ }- if spec.name == crate::openhuman::tools::toolpacks::USE_SKILL {- // `use_skill` is only reachable through a loaded pack, so it- // goes wherever `load_skill` goes.- let any_callable =- !crate::openhuman::tools::toolpacks::callable_pack_ids(&is_callable).is_empty();- return any_callable.then_some(spec);- }+ Some(spec)+ }).collect()}diff --cc src/openhuman/agent/harness/session/turn/core_session_part_01.rsindex 0000000000,a304e31ecd..4c6598fa7emode 000000,100644..100644--- a/src/openhuman/agent/harness/session/turn/core_session_part_01.rs+++ b/src/openhuman/agent/harness/session/turn/core_session_part_01.rs@@@ -1,0 -1,593 +1,649 @@@+ impl Agent {+ /// Drive a full chat turn through the `tinyagents` harness (issue #4249).+ ///+ /// The frozen system+prior history is converted to provider messages, the+ /// user turn appended, and the loop run over the agent's resolved tools. The+ /// final reply + the user turn are recorded into `history`, the transcript+ /// is persisted, and `TurnCompleted` is emitted so the UI stops spinning.+ ///+ /// Full-fidelity with the legacy `run_turn_engine`: live tool-timeline /+ /// text-delta progress and the cost/token footer are mirrored from the+ /// harness event stream via `OpenhumanEventBridge` (tinyagents harness),+ /// `[IMAGE:…]`/`[FILE:…]` markers are expanded for the provider, and history+ /// is trimmed to the provider's context window.+ async fn run_turn_via_tinyagents_session(+ &mut self,+ user_message: &str,+ effective_model: &str,+ temperature: f64,+ max_iterations: usize,+ artifact_store: Option<+ crate::openhuman::agent::harness::tool_result_artifacts::ToolResultArtifactStore,+ >,+ suppress_tools: bool,+ ) -> Result<String> {+ let turn_started = std::time::Instant::now();+ // This turn's stamped user message is already the last entry in+ // `self.history` (pushed by `turn()` before the engine branch), so build+ // the provider messages straight from history — do NOT push the user- // again. When a cached transcript prefix is present (a resumed session's- // KV-cache warm-up), prepend it and clear it so the first request reuses- // the cached prefix exactly once.++ // again. A resumed session's replayed prefix is folded into that same++ // history first (see below), so there is exactly one sequence to read.++ self.absorb_resumed_transcript_prefix();+ let mut messages = self.tool_dispatcher.to_provider_messages(&self.history);- if let Some(cached) = self.cached_transcript_messages.take() {- // The cached prefix already carries the system prompt + prior- // conversation, so drop the freshly-rendered leading system- // message(s) and append only this turn's new (user) messages.- let tail = messages- .into_iter()- .skip_while(|m| m.role == "system")- .collect::<Vec<_>>();- let mut combined = cached;- combined.extend(tail);- messages = combined;- }++ // Multimodal prep (parity with the legacy engine): rehydrate image+ // placeholders for vision-capable providers, then expand `[IMAGE:…]` /+ // `[FILE:…]` markers into provider-ready content before dispatch. The+ // expanded copy is provider-only and never persisted to `history`.+ let multimodal = self+ .runtime_config+ .as_ref()+ .map(|c| c.multimodal.clone())+ .unwrap_or_default();+ let multimodal_files = self+ .runtime_config+ .as_ref()+ .map(|c| c.multimodal_files.clone())+ .unwrap_or_default();+ // Resolve the effective context window and build the turn's tiered crate+ // `ChatModel` set from the session source up front (issue #4249, Phase 3 /+ // Motion A) — the harness holds crate model types, and the vision read+ // below comes off the built models, not a raw provider.+ let context_window = self+ .turn_model_source+ .effective_context_window(effective_model)+ .await;+ let turn_models =+ self.turn_model_source+ .build(effective_model, temperature, context_window)?;++ // Honor custom/BYOK vision models too: they can set `model_vision` even+ // when the provider capability bit is false, and must still rehydrate+ // `[IMAGE:…]` placeholders (else image chat silently degrades to text).+ if (turn_models.supports_vision() || self.model_vision)+ && crate::openhuman::agent::multimodal::has_image_placeholders(&messages)+ {+ messages = crate::openhuman::agent::multimodal::rehydrate_image_placeholders(&messages);+ }+ let messages = crate::openhuman::agent::multimodal::prepare_messages_for_provider(+ &messages,+ &multimodal,+ &multimodal_files,+ )+ .await+ .map(|prepared| prepared.messages)+ .unwrap_or(messages);++ // Per-turn tool scope (#1725). A chat / small-talk turn runs with an+ // EMPTY tool set: the provider request carries no tool schema, so the+ // model cannot enter the tool loop and answers in a single call. The+ // agent's durable `self.tools` / `self.visible_tool_names` are left+ // untouched — the next un-overridden turn gets the full toolbelt back.+ let (turn_tools, turn_synthesized_tools, turn_visible_tool_names) =+ self.turn_tool_sets(suppress_tools);++ tracing::info!(+ model = %effective_model,+ max_iterations,+ tools = turn_tools.len() + turn_synthesized_tools.len(),+ suppress_tools,+ "[agent_loop] routing chat turn through the tinyagents harness"+ );++ // Dispatch through the chat turn graph (this folder's `graph.rs`): a thin+ // wrapper over the shared tinyagents seam that pins the chat path's fixed+ // arguments (no child scope, no early-exit tools, graceful cap pause,+ // per-turn output cap) and runs the context-window summarization step.+ // Context middlewares sourced from this session's ContextManager: the+ // per-tool-result byte cap + payload summarizer (after_tool) and+ // microcompact tool-body clearing (before_model). KV-cache-prefix drift+ // detection is owned by the crate `PromptCacheGuardMiddleware` (fed by+ // `PromptCacheSegmentMiddleware`); the warn-only `CacheAlignMiddleware`+ // was deleted in C3.+ let context_mw = crate::openhuman::agent::tinyagents::TurnContextMiddleware {+ tool_result_budget_bytes: self.context.tool_result_budget_bytes(),+ payload_summarizer: self.payload_summarizer.clone(),+ artifact_store,+ tokenjuice_compaction_enabled: self.context.compaction_enabled(),+ tokenjuice_compression: self.tokenjuice_compression,+ microcompact_keep_recent: self.context.microcompact_keep_recent(),+ // Honor the [context].enabled / autocompact_enabled opt-outs: when off,+ // the summarization middleware is not installed (no summarizer tokens,+ // no history rewrite).+ autocompact_enabled: self.context.autocompact_enabled(),+ // Progressive-disclosure handoff is a sub-agent (integrations_agent)+ // concern; the top-level chat turn never sets it.+ handoff: None,+ // Live transcript snapshotting is a sub-agent error-recovery concern+ // (#4466); the chat path persists its transcript post-run.+ transcript_snapshot: None,+ };++ // Gather any sub-agent spend delegated during this turn (synchronous+ // `spawn_subagent` runs inline on this task and records into the collector)+ // so the turn's usage meters + the `chat_done` per-child breakdown include+ // it — the collector scope the legacy engine installed.+ // Install the turn's sub-agent dispatch guard around the same future+ // (#5804). It records two facts the turn already produces but never+ // wrote down — that a graceful pause has been requested at the+ // model-call cap, and how long this turn's sub-agents actually take —+ // so `run_subagent` can refuse a dispatch that cannot finish inside the+ // remaining wall-clock budget instead of taking the whole turn down+ // with it. Boxed at the call site: `with_dispatch_guard` takes its+ // future by value, and the collector future wraps the entire turn+ // generator, so passing it unboxed would move hundreds of KiB through+ // this frame — the same hazard `with_turn_collector`'s own comment+ // documents, with the gdb measurements behind it.+ let turn_future = Box::pin(+ crate::openhuman::agent::harness::turn_subagent_usage::with_turn_collector(+ super::graph::run_chat_turn_graph(super::graph::ChatTurnGraph {+ turn_models,+ model: effective_model.to_string(),+ messages,+ tools: turn_tools,+ synthesized_tools: turn_synthesized_tools,+ visible_tool_names: turn_visible_tool_names,+ max_iterations,+ on_progress: self.on_progress.clone(),+ context_window,+ run_queue: self.run_queue.clone(),+ context_mw,+ // Enforce the builder-configured tool policy at the tool+ // boundary (the tinyagents path otherwise bypasses it).+ tool_policy: Some(crate::openhuman::agent::tinyagents::ToolPolicyEnforcement {+ policy: self.tool_policy.clone(),+ session: self.tool_policy_session.clone(),+ session_id: self.event_session_id.clone(),+ channel: self.event_channel().to_string(),+ agent_definition_id: self.agent_definition_id.clone(),+ }),+ // Section D: forward the session's per-profile workspace+ // descriptor (if any) so the top-level chat turn's acting+ // tools default their cwd to the profile's dedicated dir.+ workspace_descriptor: self.workspace_descriptor.clone(),+ // Scope direct Master-Agent calls under its declared+ // sandbox. `agent_definition_name` can carry a thread+ // suffix, so resolve with the stable definition id.+ sandbox_mode: crate::openhuman::agent::harness::definition::AgentDefinitionRegistry::global()+ .and_then(|registry| registry.get(&self.agent_definition_id))+ .map(|definition| definition.sandbox_mode)+ .unwrap_or(crate::openhuman::agent::harness::definition::SandboxMode::None),+ }),+ ),+ );+ let (outcome, subagent_usage_entries) =+ crate::openhuman::agent::harness::turn_dispatch_guard::with_dispatch_guard(+ crate::openhuman::agent::tinyagents::agent_turn_wall_clock_ms()+ .map(std::time::Duration::from_millis),+ turn_future,+ )+ .await;+ let outcome = outcome?;++ // Record whether this turn paused at the tool-call cap (vs. finishing+ // naturally) BEFORE anything below can early-return, so a caller+ // inspecting `last_turn_hit_cap()` after `run_single` always reflects+ // this turn, never a stale value from a prior one.+ self.last_turn_hit_cap = outcome.hit_cap;++ // The stamped user turn is already in `self.history` (pushed by `turn()`),+ // so append only the structured messages this turn produced — assistant+ // tool calls + tool results + (for a clean finish) the final assistant —+ // preserving tool-call history fidelity for the UI, persisted transcript,+ // and the next turn's KV-cache prefix.+ self.history.extend(outcome.conversation.iter().cloned());++ // Token accounting for the turn (the cap checkpoint call below folds in+ // its own usage).+ // Seed from the turn outcome (the harness observed real usage incl. cached+ // tokens and an estimated cost) rather than zero, so a normal non-cap turn+ // persists real cost instead of $0. The cap-checkpoint branch below folds+ // in its extra call's usage on top.+ let mut input_tokens = outcome.input_tokens;+ let mut output_tokens = outcome.output_tokens;+ let mut cached_input_tokens = outcome.cached_input_tokens;+ let mut charged_amount_usd = outcome.charged_amount_usd;++ let reply = if outcome.hit_cap && outcome.wrap_up_injected && !outcome.text.trim().is_empty()+ {+ // The conclusion was produced INSIDE the loop (issue #6014):+ // `FinalCallWrapUpMiddleware` withdrew the tools on the last+ // permitted model call and appended the wrap-up instruction, so this+ // turn's own final response already is the capped turn's answer.+ // There is nothing left to ask for, and asking anyway would spend a+ // second call to re-summarise text the model has just written.+ //+ // No `history.push` either: unlike the out-of-band path below, this+ // response came from the loop, so it was already folded into+ // `self.history` by the `extend(outcome.conversation)` above. Pushing+ // it again would duplicate the assistant turn in the transcript and+ // in the next request's prefix.+ log::info!(+ "[agent_loop] turn capped at {} model call(s); the loop's final call produced the \+ conclusion ({} chars) — no out-of-band wrap-up needed",+ outcome.model_calls,+ outcome.text.chars().count()+ );+ outcome.text.clone()+ } else if outcome.hit_cap {+ // The loop paused at the tool-call cap. Ask the model for a resumable+ // checkpoint (tools disabled), falling back to a deterministic+ // done/next summary so the thread never ends on a dangling tool+ // cycle. Fold the extra call's usage into the turn accounting.+ //+ // Reached when the in-loop conclusion above did not happen or came+ // back empty: a run with the middleware uninstalled, a budget of one+ // model call, or a concluding call that answered with nothing. Kept+ // intact so no path loses the behaviour it had before #6014.+ // The concluding call answered with nothing, and the `extend` above+ // folded that empty assistant message into `self.history`. Anthropic+ // rejects empty content, so sending it would turn "the model said+ // nothing" into a failed turn (CodeRabbit on #6068).+ if self.history.last().is_some_and(is_empty_assistant_chat) {+ self.history.pop();+ }+ let base = self.tool_dispatcher.to_provider_messages(&self.history);+ let (summary, summary_usage) = self+ .summarize_turn_wrapup(+ &base,+ effective_model,+ outcome.model_calls as u32 + 1,+ super::super::turn_checkpoint::MAX_ITER_CHECKPOINT_INSTRUCTION,+ )+ .await;+ if let Some(u) = summary_usage {+ input_tokens += u.input_tokens;+ output_tokens += u.output_tokens;+ cached_input_tokens += u.cached_input_tokens;+ charged_amount_usd += u.charged_amount_usd;+ }+ let checkpoint = if summary.trim().is_empty() {+ super::super::turn_checkpoint::build_deterministic_checkpoint(+ &checkpoint_results_from_conversation(+ &outcome.conversation,+ &outcome.tool_outcomes,+ ),+ max_iterations,+ )+ } else {+ summary+ };+ self.history+ .push(ConversationMessage::Chat(ChatMessage::assistant(+ checkpoint.clone(),+ )));+ checkpoint+ } else if outcome.text.trim().is_empty() && outcome.tool_calls == 0 {+ // A completion with no text and no tool calls is never a valid final+ // answer — surface it as an error instead of wedging the thread on a+ // blank reply (bug-report-2026-05-26 A1, defect B).+ //+ // #4457 (defect A): the empty terminal assistant response was already+ // folded into `self.history` via `outcome.conversation` at the+ // `history.extend` above (an empty `Chat(assistant(""))`). The #4093+ // branch below pops that dangling blank row before re-prompting, but+ // this `tool_calls == 0` path returned the error with the empty row+ // still in history — so the *next* request carried an empty-content+ // assistant message and strict providers (Anthropic: "text content+ // blocks must be non-empty") 400 the whole thread, not just this turn.+ // Pop the trailing empty assistant row before returning so a retry+ // sends a clean transcript.+ if matches!(+ self.history.last(),+ Some(ConversationMessage::Chat(msg))+ if msg.role == "assistant" && msg.content.trim().is_empty()+ ) {+ log::debug!(+ "[agent_loop] EmptyProviderResponse at iteration {}: popping dangling empty assistant row before returning — #4457 defect A",+ outcome.model_calls+ );+ self.history.pop();+ }+ return Err(anyhow::Error::new(+ crate::openhuman::agent::error::AgentError::EmptyProviderResponse {+ iteration: outcome.model_calls,+ },+ ));+ } else if outcome.text.trim().is_empty() {+ // #4093: the loop ran tool calls (tool_calls > 0, so the branch+ // above did not fire) and then yielded a terminating response with+ // no final text — the turn did work but would otherwise end+ // silently, leaving the user with nothing. Enforce the+ // "must produce a final response" terminal step: re-prompt the+ // model (tools disabled) for a closing summary of what it did,+ // falling back to a deterministic summary of the tool calls so the+ // synthesized message is never itself empty. Fold the extra call's+ // usage into the turn accounting, exactly like the cap path above.+ let base = self.tool_dispatcher.to_provider_messages(&self.history);+ let (summary, summary_usage) = self+ .summarize_turn_wrapup(+ &base,+ effective_model,+ outcome.model_calls as u32 + 1,+ super::super::turn_checkpoint::FINAL_ANSWER_INSTRUCTION,+ )+ .await;+ if let Some(u) = summary_usage {+ input_tokens += u.input_tokens;+ output_tokens += u.output_tokens;+ cached_input_tokens += u.cached_input_tokens;+ charged_amount_usd += u.charged_amount_usd;+ }+ let final_answer = if summary.trim().is_empty() {+ super::super::turn_checkpoint::build_deterministic_final_summary(+ &tool_records_from_conversation(&outcome.conversation, &outcome.tool_outcomes),+ )+ } else {+ summary+ };+ log::info!(+ "[agent_loop] turn produced no final text after {} tool call(s); synthesized a closing summary ({} chars) — #4093",+ outcome.tool_calls,+ final_answer.chars().count()+ );+ // The empty terminal assistant response was already folded into+ // `self.history` via `outcome.conversation` above (an empty+ // `Chat(assistant(""))` — see `messages_to_conversation`). Drop that+ // blank turn before appending the synthesized answer so the+ // transcript and the next prompt don't carry a dangling empty+ // assistant message immediately before the real reply (Codex review).+ if matches!(+ self.history.last(),+ Some(ConversationMessage::Chat(msg))+ if msg.role == "assistant" && msg.content.trim().is_empty()+ ) {+ self.history.pop();+ }+ self.history+ .push(ConversationMessage::Chat(ChatMessage::assistant(+ final_answer.clone(),+ )));+ final_answer+ } else if outcome.early_exit_tool.is_some() {+ // Paused on `ask_user_clarification`. The run stopped right after the+ // tool round, so `outcome.conversation` ends on a tool result and+ // carries no final assistant turn — `outcome.text` (the question) is+ // standing in for one. Push it, or the reply the user is looking at+ // would be missing from the next request's prefix and the model would+ // have to infer that it asked anything from its own tool result.+ // The sub-agent path makes the same substitution when it persists a+ // paused child's transcript (`subagent_runner/ops/graph_part_01.rs`).+ self.history+ .push(ConversationMessage::Chat(ChatMessage::assistant(+ outcome.text.clone(),+ )));+ outcome.text.clone()+ } else {+ outcome.text.clone()+ };++ // Enforce the required structured-output contract (issue #4117) on the+ // accepted reply — for the branches above that actually deliver one+ // (normal finish, cap checkpoint, #4093 synthesized close), since each+ // is a reply downstream parsing depends on. When this agent must emit a JSON block+ // every turn and the reply omitted it, validate-and-repair before the+ // turn is accepted, reconciling with streaming (append-only when a live+ // stream is attached, replace otherwise — see `enforce_required_output`).+ // The trailing assistant message is rewritten to match, and the repair+ // call's usage is folded into the turn accounting. `required_output`+ // defaults to `None`, so existing agents are entirely unaffected.+ // Converted to the crate contract at the read site: the enforcement+ // helpers below are part of the runtime slated to move into TinyAgents+ // and so speak the crate type, while the session still holds the host's+ // `AgentConfig`. See `tinyagents::config::required_output_from`.+ //+ // NOT for a turn paused on `ask_user_clarification`. The reply there is+ // the question itself, which will not carry the required block, so+ // enforcement would spend a repair model call rewriting the very text+ // the user is being asked to answer — and `replace_last_assistant_reply`+ // would persist the rewrite, so the question in the transcript would+ // stop matching the one on screen. A paused turn delivers no reply for+ // downstream parsing to depend on; the contract applies to the answer+ // this agent gives after the user replies, not to the asking (#6213+ // review).+ let required_output = if outcome.early_exit_tool.is_some() {+ None+ } else {+ self.config+ .required_output+ .as_ref()+ .map(crate::openhuman::agent::tinyagents::config::required_output_from)+ };+ let reply = if let Some(contract) = required_output {+ match self+ .enforce_required_output(+ &reply,+ &contract,+ effective_model,+ outcome.model_calls as u32 + 1,+ )+ .await+ {+ Some((repaired, repair_usage)) => {+ if let Some(u) = repair_usage {+ input_tokens += u.input_tokens;+ output_tokens += u.output_tokens;+ cached_input_tokens += u.cached_input_tokens;+ charged_amount_usd += u.charged_amount_usd;+ }+ replace_last_assistant_reply(&mut self.history, &repaired);+ repaired+ }+ None => reply,+ }+ } else {+ reply+ };+ self.trim_history();++ // Fold this turn's sub-agent spend into the cumulative meters and capture+ // the holistic per-turn usage the web channel surfaces on `chat_done` (it+ // calls `take_last_turn_usage_totals()` right after the turn). Without this+ // the event reported `usage: None` despite the transcript being persisted+ // with real numbers.+ for entry in &subagent_usage_entries {+ input_tokens = input_tokens.saturating_add(entry.usage.input_tokens);+ output_tokens = output_tokens.saturating_add(entry.usage.output_tokens);+ cached_input_tokens =+ cached_input_tokens.saturating_add(entry.usage.cached_input_tokens);+ charged_amount_usd += entry.usage.charged_amount_usd;+ }+ self.last_turn_usage_totals = Some(+ crate::openhuman::agent::harness::turn_subagent_usage::LastTurnUsage {+ input_tokens,+ output_tokens,+ cached_input_tokens,+ cost_usd: charged_amount_usd,+ context_window: context_window.unwrap_or(0),+ subagents: subagent_usage_entries,+ },+ );++ let mut persisted = self.tool_dispatcher.to_provider_messages(&self.history);+ // Re-attach per-call failure outcomes (dropped when the engine folded+ // each tool result into a `role:"tool"` message) so the derived+ // transcript view renders failed tools as errors, not successes.+ stamp_tool_failures(&mut persisted, &outcome.tool_outcomes);+ // Carry the turn's provider (event channel) + effective model and usage+ // into the persisted transcript meta. Passing `None` here dropped+ // `provider`/`model` from every transcript (they are `TranscriptMeta`+ // fields sourced from the turn usage) — parity with the legacy engine,+ // which handed `self.last_turn_usage.as_ref()` to this call.+ let turn_usage = crate::openhuman::agent::harness::session::transcript::TurnUsage {+ provider: self.event_channel().to_string(),+ // The model that actually ran this turn (a per-turn override can+ // diverge from `self.model_name`); attribute usage to it.+ model: effective_model.to_string(),+ usage: crate::openhuman::agent::harness::session::transcript::MessageUsage {+ input: input_tokens,+ output: output_tokens,+ cached_input: cached_input_tokens,+ context_window: context_window.unwrap_or(0),+ cost_usd: charged_amount_usd,+ },+ ts: chrono::Utc::now().to_rfc3339(),+ reasoning_content: None,+ tool_calls: Vec::new(),+ iteration: outcome.model_calls as u32,+ };+ self.persist_session_transcript(+ &persisted,+ input_tokens,+ output_tokens,+ cached_input_tokens,+ charged_amount_usd,+ Some(&turn_usage),+ );++ // Charge this turn's usage against the thread's active goal (parity with+ // the legacy engine) so budgeted goals progress to `budget_limited` and+ // continuation scheduling reads a live budget. Self-guarding + best-effort+ // — a no-op when there is no active goal for the ambient thread.+ crate::openhuman::threads::goals::runtime::account_turn_against_goal(+ &self.workspace_dir,+ input_tokens,+ output_tokens,+ turn_started.elapsed().as_secs(),+ )+ .await;++ // Content (prompt + reply) rides its own event so a tracing consumer can+ // attach it to the turn span. Gated on the opt-in+ // `observability.agent_tracing.capture_content` flag (#4454): with the+ // default off, we don't even emit the content event, so prompt/reply text+ // never reaches the span store or any exporter. The collector applies the+ // same storage-level gate as defense in depth.+ let capture_content = self+ .runtime_config+ .as_ref()+ .map(|c| c.observability.agent_tracing.capture_content)+ .unwrap_or(false);+ if capture_content {+ log::debug!(+ target: "agent-tracing",+ "[agent-tracing] emitting TurnContent (capture_content=true)"+ );+ self.emit_progress(AgentProgress::TurnContent {+ input: Some(user_message.to_string()),+ output: Some(reply.clone()),+ })+ .await;+ } else {+ log::debug!(+ target: "agent-tracing",+ "[agent-tracing] skipping TurnContent emit (capture_content=false)"+ );+ }++ self.emit_progress(AgentProgress::TurnCompleted {+ iterations: outcome.model_calls as u32,+ })+ .await;++ if self.auto_save {+ let summary = truncate_with_ellipsis(&reply, 100);+ let autosave_key = format!("assistant_resp:{}", uuid::Uuid::new_v4());+ let _ = self+ .memory+ .store(+ crate::openhuman::agent::learning::transcript_ingest::CONVERSATION_RAW_NAMESPACE,+ &autosave_key,+ &summary,+ MemoryCategory::Daily,+ None,+ )+ .await;+ }++ // Fire post-turn hooks (non-blocking), matching the legacy engine.+ if !self.post_turn_hooks.is_empty() {+ let ctx = TurnContext {+ user_message: user_message.to_string(),+ assistant_response: reply.clone(),+ tool_calls: tool_records_from_conversation(+ &outcome.conversation,+ &outcome.tool_outcomes,+ ),+ turn_duration_ms: turn_started.elapsed().as_millis() as u64,+ session_id: Some(self.event_session_id.clone())+ .filter(|session_id| !session_id.trim().is_empty()),+ agent_id: Some(self.agent_definition_id.clone())+ .filter(|agent_id| !agent_id.trim().is_empty()),+ entrypoint: Some(self.event_channel.clone())+ .filter(|entrypoint| !entrypoint.trim().is_empty()),+ iteration_count: outcome.model_calls,+ };+ hooks::fire_hooks(&self.post_turn_hooks, ctx);+ }++ Ok(reply)+ }+ }++++impl Agent {++ /// Fold a resumed session's replayed transcript prefix into [`Agent::history`].++ ///++ /// A no-op unless `cached_transcript_messages` is set, which happens only on++ /// the first turn after a resume.++ pub(in super::super) fn absorb_resumed_transcript_prefix(&mut self) {++ let Some(cached) = self.cached_transcript_messages.take() else {++ return;++ };++ // A resumed session's replayed prefix is **absorbed into++ // `self.history`**, not merely prepended to this one request.++ //++ // It used to be prepended: the request was built from `history`,++ // the cached prefix was `take()`n and spliced in front, and++ // `history` was left holding only the new turn. That made the++ // replayed conversation visible to exactly one request, and it cost++ // the conversation twice over — both observed on the wire, not++ // reasoned about:++ //++ // 1. **The next turn lost it.** `take()` empties the field, and++ // nothing else ever re-read the transcript, so turn 2 after a++ // restart went out with only its own messages. A ten-message++ // thread answered its next question from four. That is++ // conversational amnesia first and a cache miss second.++ // 2. **The transcript written afterwards lost it.** Persistence++ // serializes `history` (see `run_turn_impl`'s++ // `persist_session_transcript` call), so the file produced after++ // a resume held only the new turn — and `latest_for_agent` hands++ // that file to the *next* resume. Each restart truncated the++ // thread a little further.++ //++ // Absorbing it makes `history` the single source of truth again, so++ // the request, the following turn and the durable record cannot++ // disagree. The bytes on the wire for *this* request are unchanged:++ // the prefix's entries are already provider-shaped `ChatMessage`s++ // and `Chat` is rendered verbatim, exactly as the splice did.++ //++ // The leading system message(s) built for this turn are dropped in++ // favour of the prefix's own, which is the whole point of resuming —++ // the stored prompt is the KV-cache prefix the backend has already++ // tokenised, and re-rendering it is what this path exists to avoid.++ //++ // `Chat` rather than the structured `AssistantToolCalls` /++ // `ToolResults` variants is deliberate: these entries have already++ // been through `bound_cached_transcript_messages`, which snaps the++ // window past an orphaned lead and strips a trailing unpaired++ // opener, so the cycle-pairing guard has nothing left to do. Lifting++ // them into the structured variants would mean re-deriving a pairing++ // that was already decided, with a second chance to get it wrong;++ // the native envelope they carry is parsed back into real tool calls++ // at the provider seam either way (see++ // `message_convert::parse_native_assistant_envelope`, which exists++ // for precisely this seeded-transcript case).++ let tail: Vec<ConversationMessage> = self++ .history++ .drain(..)++ .skip_while(|entry| {++ matches!(entry, ConversationMessage::Chat(chat) if chat.role == "system")++ })++ .collect();++ self.history = cached++ .into_iter()++ .map(ConversationMessage::Chat)++ .chain(tail)++ .collect();++ }++}diff --cc src/openhuman/agent/orchestration/tools/archetype_delegation.rsindex 4bb29a51e9,18a977fece..63cedeaf1b--- a/src/openhuman/agent/orchestration/tools/archetype_delegation.rs+++ b/src/openhuman/agent/orchestration/tools/archetype_delegation.rs@@@ -23,6 -44,13 +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`++ /// way `UseSkillTool` 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_*` tooldiff --cc src/openhuman/agent/registry/agents/orchestrator/prompt.mdindex ab50bb99c3,81035635de..1e0c85b00b--- a/src/openhuman/agent/registry/agents/orchestrator/prompt.md+++ b/src/openhuman/agent/registry/agents/orchestrator/prompt.md@@@ -66,11 -84,16 +66,16 @@@ Your job, in order: understand the requ- **Escalate when appropriate** — If orchestration is the wrong mode or a specialist cannot make progress, hand control back to OpenHuman Core with a concise explanation and let Core handle general interactions.- **Plan before you execute (interactive plan review).** For any interactive request that needs a thread-scoped plan — a multi-step task (3+ steps) or a durable objective for this conversation — call **`request_plan_review`** with a one-line `summary` and the ordered `steps` **before doing any of the work and before creating any `todo` cards**. The review card shows the user the `steps` you pass, so you do **not** need a `todo` plan to exist yet. That call PAUSES your turn until the user decides, and its result tells you what to do: `approved` → **now** lay the plan out with the `todo` tool (one card per step) and execute it; `rejected` → do **not** execute and do **not** create cards, briefly ask what they want instead; `revise` → the result carries their feedback, so call `request_plan_review` again with the revised `steps` (still no cards yet). Creating `todo` cards only **after** approval keeps a rejected/revised plan from lingering pinned on the board. Never start executing until `request_plan_review` returns `approved`. Trivial single-step requests need no plan and no review — answer directly. (On non-interactive turns `request_plan_review` auto-approves, so this same flow is safe in cron / subconscious / CLI runs.)-**Scheduling rule of thumb.** Route reminders, one-shot jobs, recurring jobs, and job list/remove to `schedule_task`; the scheduler specialist owns the schedule shapes, cron expressions, and worked examples. Two rules still bind you directly:+**Scheduling rule of thumb.** Reminders, one-shot jobs, recurring jobs and job list/remove all live in the scheduling skill, which owns the schedule shapes, cron expressions and worked examples. Two rules bind you whichever route you take:-- **`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.+- **Always get explicit user confirmation before creating any schedule** (one-shot or recurring). Propose the exact timing, wait for a yes, then act.+- **Never hand-compute a timestamp.** Resolve every date or time argument with `resolve_time` and pass its exact value.-**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:++**Workflow rule of thumb.** Route anything about building, editing or proposing a saved workflow to the workflow builder (skill `workflows`, tool `build_workflow`), and workflow discovery to its discovery specialist (skill `workflows`, tool `discover_workflows`). Those specialists own the flow-authoring tools (propose, revise, validate, save, create 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.++- **Never ask `use_skill` for an authoring tool yourself.** That call is refused, and re-trying it burns the turn. Hand the request to the builder instead.++- **Delegate on the user's description — you do not need the graph first.** The builder does the discovery, node wiring and validation itself, and comes back with a proposal for the user to approve. Running or listing the saved flow afterwards is yours, through the same skill.+### 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 --cc src/openhuman/agent/registry/agents/orchestrator/prompt_tests.rsindex 3e29299534,1f703ff6e4..b430c931aa--- a/src/openhuman/agent/registry/agents/orchestrator/prompt_tests.rs+++ b/src/openhuman/agent/registry/agents/orchestrator/prompt_tests.rs@@@ -531,190 -512,53 +531,250 @@@ fn build_omits_guide_when_no_integratioassert!(!body.contains("## Connected Integrations"));}+/// The archetype must never name a tool a pack is withholding.+///+/// This is the drift class the generated routing block exists to close. The+/// static markdown named fifteen tools and ten of them were packed, so the+/// prompt taught a call the model could not make: it emits the name, the+/// harness answers "unknown tool", and the iteration is spent. Nothing in the+/// build compared the two lists, which is why it survived.+///+/// The rule is deliberately about *packed* names, not about every tool: a name+/// that is simply off this agent's belt (`cron_add`, say) is discussed in prose+/// that already conditions on "when they appear in your tool list", while a+/// packed name is one the model provably cannot see and must reach through+/// `use_skill`.+#[test]+fn the_archetype_never_names_a_withheld_tool() {+ let named = withheld_names_presented_as_callable(ARCHETYPE);+ assert!(+ named.is_empty(),+ "orchestrator/prompt.md names withheld tools as if directly callable: {named:?}. \+ Route them through `use_skill` instead, or unpack them."+ );+}++/// The same rule over the whole rendered prompt, not just the static half.+///+/// `render_installed_skills` was the other offender — it named five packed+/// tools in a Rust string literal, where the archetype check above cannot see+/// them.+#[test]+fn the_rendered_prompt_never_names_a_withheld_tool() {+ let body = build(&ctx_with(&[])).unwrap();+ // The generated withheld-specialist block names packed tools on purpose —+ // that is the route, not a claim they are callable. It is absent here+ // because `ctx_with` supplies an empty visible set (the "everything is+ // visible" sentinel), so nothing is withheld and nothing is rendered.+ assert!(+ !body.contains("## Capabilities not in your tool list"),+ "an empty visible set means no filter, so nothing can be withheld"+ );+ let named = withheld_names_presented_as_callable(&body);+ assert!(+ named.is_empty(),+ "the rendered orchestrator prompt names withheld tools as if directly \+ callable: {named:?}"+ );+}++/// Withheld tool names that `text` presents as directly callable.+///- /// Two exemptions, and both are about telling a *route* from a *call*:++/// Three exemptions, and all are about telling a *route* from a *call*:+///+/// * The generated `## Capabilities not in your tool list` block names withheld+/// tools on purpose — that block is the route, and it is the one sanctioned+/// place to write one. It is removed wholesale before scanning.+/// * A pack **id** may be backticked anywhere, since naming the skill is how a+/// route reads in prose. Two pack ids (`composio`, `goals`) are also tool+/// names inside their own pack, so a bare substring check cannot tell the+/// two apart; routes are always spelled ``skill `<id>` ``, so removing that+/// exact form is what makes the remaining occurrences calls.++/// * A full route — ``skill `<id>`, tool `<name>` ``, the exact spelling the++/// generated block emits — may name the tool it routes to, but only in that++/// form and only under the pack that owns it. A packed name backticked on its++/// own is still a call.+fn withheld_names_presented_as_callable(text: &str) -> Vec<&'static str> {+ let packed = crate::openhuman::tools::toolpacks::all_packed_tool_names();+ let mut prose = match text.find("## Capabilities not in your tool list") {+ Some(start) => {+ let rest = &text[start + 1..];+ let end = rest+ .find("\n## ")+ .map(|i| start + 1 + i)+ .unwrap_or(text.len());+ format!("{}{}", &text[..start], &text[end..])+ }+ None => text.to_string(),+ };++ for pack in crate::openhuman::tools::toolpacks::PACKS {++ for name in pack.tools {++ prose = prose.replace(&format!("skill `{}`, tool `{name}`", pack.id), "");++ }++ }+ for name in &packed {+ prose = prose.replace(&format!("skill `{name}`"), "");+ }+ packed+ .into_iter()+ .filter(|name| prose.contains(&format!("`{name}`")))+ .collect()+}++/// The web channel renames the session, and the block must survive it.+///+/// `PromptContext::agent_id` carries `agent_definition_name`, which the web+/// channel rewrites to `orchestrator_<short_thread>`. A plain `registry.get`+/// on that misses, and the whole withheld-specialist block silently vanishes —+/// which is exactly what the first live capture showed: the routing table was+/// gone from the prompt and nothing had replaced it.+#[test]+fn a_thread_renamed_session_still_resolves_to_its_registry_entry() {+ // The process-global registry is not initialised in unit tests, and+ // initialising it here would leak into every other test in the binary.+ crate::openhuman::agent::harness::definition::AgentDefinitionRegistry::init_global_builtins()+ .expect("builtin agent definitions must load");+ let registry = crate::openhuman::agent::harness::definition::AgentDefinitionRegistry::global()+ .expect("init_global_builtins publishes the registry");++ let exact = resolve_definition(registry, "orchestrator").expect("exact id must resolve");+ assert_eq!(exact.id, "orchestrator");++ let renamed = resolve_definition(registry, "orchestrator_thread-captu")+ .expect("a thread-renamed session must resolve to its registry entry");+ assert_eq!(renamed.id, "orchestrator");++ // Not a rename, just a different agent: must not be swallowed by a+ // shorter id that happens to be a prefix.+ assert!(+ resolve_definition(registry, "orchestratorish").is_none(),+ "a name that merely starts with an id is not that agent"+ );+}++/// The generated block must actually render for a real, renamed session.+///+/// The first live capture had every `prompt.md` edit in it and no block, which+/// only a silent early return can produce. Pin the whole path: a renamed agent+/// id, a visible set that withholds the packed delegates, and at least one row+/// naming a real route.+#[test]+fn the_withheld_block_renders_for_a_renamed_session_with_a_filter() {+ crate::openhuman::agent::harness::definition::AgentDefinitionRegistry::init_global_builtins()+ .expect("builtin agent definitions must load");++ // A visible set shaped like the live one: the advertised delegates are in,+ // the packed ones are not.+ let visible: HashSet<String> = ["research", "plan", "ask_docs", "file_read", "goal_complete"]+ .iter()+ .map(|s| s.to_string())+ .collect();+ let mut ctx = ctx_with(&[]);+ ctx.agent_id = "orchestrator_thread-captu";+ ctx.visible_tool_names = &visible;++ let block = render_withheld_specialists(&ctx);+ assert!(+ block.starts_with("## Capabilities not in your tool list"),+ "expected the generated heading, got: {:?}",+ block.chars().take(120).collect::<String>()+ );+ assert!(+ block.contains("skill `documents`, tool `make_presentation`"),+ "a packed delegate must render with its route:\n{block}"+ );+}++/// The row text must be one readable sentence, not a cut parenthetical.+///+/// `mcp_agent`'s `when_to_use` opens "…an ALREADY-CONNECTED MCP server (e.g.+/// `gmail`)…", and a naive split on ". " ends the row at "(e.g." — which is+/// what the first live capture rendered.+#[test]+fn a_row_is_not_cut_at_an_abbreviation() {+ assert_eq!(+ first_sentence("Calls tools on a connected server (e.g. gmail). Then reports back."),+ "Calls tools on a connected server (e.g. gmail).",+ );+ // A genuine boundary still ends the row.+ assert_eq!(+ first_sentence("Builds decks from evidence. Use for pitch-deck requests."),+ "Builds decks from evidence.",+ );+ // No boundary at all: capped, not truncated mid-word by accident.+ let long = "a ".repeat(200);+ assert!(first_sentence(&long).ends_with('…'));+ // Short and unterminated: returned whole.+ assert_eq!(+ first_sentence("Runs installed agent skills"),+ "Runs installed agent skills"+ );+}++/// The generated intro must not carry the source's line-continuation padding.+#[test]+fn the_generated_block_has_no_stray_whitespace_runs() {+ crate::openhuman::agent::harness::definition::AgentDefinitionRegistry::init_global_builtins()+ .expect("builtin agent definitions must load");+ let visible: HashSet<String> = ["research".to_string()].into_iter().collect();+ let mut ctx = ctx_with(&[]);+ ctx.agent_id = "orchestrator";+ ctx.visible_tool_names = &visible;+ let block = render_withheld_specialists(&ctx);+ assert!(!block.is_empty(), "expected a rendered block");+ assert!(+ !block.contains(" "),+ "the block carries doubled spaces from the source literal:\n{block}"+ );+}+++ #[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 --cc src/openhuman/agent/tinyagents/middleware_part_02.rsindex 819078993a,25b0bdb3f0..bf86ae0343--- a/src/openhuman/agent/tinyagents/middleware_part_02.rs+++ b/src/openhuman/agent/tinyagents/middleware_part_02.rs@@@ -561,6 -561,106 +561,112 @@@ 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.++ /// Render a `use_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.++ /// that holds the session — `UseSkillTool` is built once per registry and++ /// has no idea who is calling it. Only the disclosure half is rendered here:++ /// a call that names a `tool` is the execution half, which++ /// `channel_permission_block` has already gated and the tool's own++ /// `execute` dispatches. Returns `None` when there is nothing to scope (a++ /// tool named, 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> {++ if crate::openhuman::tools::toolpacks::named_tool(&call.arguments).is_some() {++ return None;++ }+ 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.diff --cc src/openhuman/agent/tinyagents/middleware_part_03.rsindex 525c60e61d,ab78fe001f..e7e76df8cb--- a/src/openhuman/agent/tinyagents/middleware_part_03.rs+++ b/src/openhuman/agent/tinyagents/middleware_part_03.rs@@@ -90,6 -90,20 +90,22 @@@ impl ToolMiddleware<()> for ToolPolicyM}));}- // `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.++ // `use_skill`'s disclosure half (a `skill` with no `tool`) 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. The execution half falls through:++ // `render_skill_for_session` answers `None` for it.+ //+ // Placed AFTER both gates on purpose. Rendering before them would let a- // `load_skill` that the session forbids, or that the policy denies or++ // `use_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 call.name == crate::openhuman::tools::toolpacks::USE_SKILL {+ if let Some(result) = self.render_skill_for_session(&call) {+ return Ok(MiddlewareToolOutcome::Result(result));+ }+ }+next.run(ctx, state, call).await}}diff --cc src/openhuman/agent/tinyagents/middleware_tests_part_04_tests.rsindex 0000000000,97e5b2819d..190a9179f1mode 000000,100644..100644--- a/src/openhuman/agent/tinyagents/middleware_tests_part_04_tests.rs+++ b/src/openhuman/agent/tinyagents/middleware_tests_part_04_tests.rs@@@ -1,0 -1,351 +1,369 @@@+ 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::toolpacks::{append_pack_tools, bind_pack_registry, USE_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,++/// a `build_workflow` delegate, but may only call the delegate and the pack++/// tool — 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"]++ allowed_tool_names: ["build_workflow", 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(),++ decisions: [allow("build_workflow"), 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() {++async fn a_use_skill_listing_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");++ .render_skill_for_session(&call(USE_SKILL, json!({ "skill": "workflows" })))++ .expect("a use_skill call naming a skill and no tool 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+ );+ }+++/// The middleware renders the *disclosure* half only. A `use_skill` call that++/// names a `tool` is the execution half: it has already passed++/// `channel_permission_block`, and rendering a listing in its place would turn++/// every packed-tool call into a menu. That call must fall through to the++/// tool's own `execute`.++#[tokio::test]++async fn a_use_skill_call_that_names_a_tool_is_not_rendered_as_a_listing() {++ let mw = non_owner_middleware();++ assert!(++ mw.render_skill_for_session(&call(++ USE_SKILL,++ json!({ "skill": "workflows", "tool": "build_workflow" }),++ ))++ .is_none(),++ "the execution half must reach the tool, not the listing"++ );++ // An empty `tool` is the disclosure half — the same rule `named_tool` applies.++ assert!(++ mw.render_skill_for_session(&call(++ USE_SKILL,++ json!({ "skill": "workflows", "tool": "" }),++ ))++ .is_some(),++ "an empty tool name is a listing request, not a call"++ );++}+++ /// 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(),++ allowed_tool_names: [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(),++ decisions: [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 --cc src/openhuman/tools/ops_tests_part_01_tests.rsindex a54ed8dba0,fd9dea35ad..a7ae7c5b2f--- a/src/openhuman/tools/ops_tests_part_01_tests.rs+++ b/src/openhuman/tools/ops_tests_part_01_tests.rs@@@ -159,6 -159,111 +159,116 @@@ fn all_tools_includes_spawn_parallel_ag);}+ #[test]+ fn every_packed_tool_name_resolves_to_a_registered_tool() {+ // A pack advertises a menu. `render_pack_filtered` skips a name it cannot+ // resolve (tools.rs "a pack may name a tool this build compiled out"), so a+ // stale entry does not error — the listing is just quietly short, and any+ // prompt that instructs the agent to call it describes a tool that will+ // never appear in its schema. The `crypto` pack carried five such names+ // (`wallet_balances`, `wallet_network_defaults`, `wallet_supported_assets`,+ // `wallet_encode_erc20_transfer`, `wallet_execute_prepared`) whose backing+ // functions exist only as `wallet.*` RPC methods, never as agent tools.+ //+ // Packs whose tools sit behind a non-default Cargo feature are skipped+ // entirely — see `pack_is_assertable` below. Within an asserted pack every+ // name must resolve.+ let tmp = TempDir::new().unwrap();+ let security = Arc::new(SecurityPolicy::default());+ let browser = BrowserConfig {+ enabled: false,+ allowed_domains: vec![],+ session_name: None,+ ..BrowserConfig::default()+ };+ let http = crate::openhuman::config::HttpRequestConfig::default();+ let cfg = test_config(&tmp);++ let tools = all_tools(+ Arc::new(Config::default()),+ &security,+ AuditLogger::disabled(),+ &browser,+ &http,+ tmp.path(),+ &HashMap::new(),+ &cfg,+ );+ let registered: std::collections::HashSet<&str> = tools.iter().map(|t| t.name()).collect();++ // Delegation tools are synthesised per-session from each agent's+ // `delegate_name`, not built by `all_tools`, so they are legitimately+ // absent here. `owners` holds agent ids (`crypto_agent`); the names that+ // appear in `tools` are delegate names (`do_crypto`), so resolve them from+ // the agent registry rather than from `owners`.+ //+ // `.expect`, not `.unwrap_or_default()`: an empty delegate set would make+ // EVERY pack delegate (`do_crypto`, `build_workflow`, `run_skill`, …) report+ // as missing, so a registry that failed to load would surface as a list of+ // phantom names — the exact failure this test exists to report, raised for+ // the wrong reason. `load_builtins` documents that built-in TOML is baked+ // into the binary and must always parse, so an `Err` here is a broken+ // invariant worth failing loudly on rather than absorbing.+ let delegates: std::collections::HashSet<String> =+ crate::openhuman::agent::registry::agents::load_builtins()+ .expect("built-in agent registry must load; without it every pack delegate would be reported as a phantom name")+ .into_iter()+ .filter_map(|d| d.delegate_name)+ .collect();++ // `PACKS` is unconditional, but most packs' tools are behind Cargo features+ // that are NOT in `default` — `flows`, `mcp`, `skills`, `web3`, `documents`,+ // `voice`. Under a partial feature set "missing" means "compiled out", not+ // "stale", and asserting there reports the pack's REAL tools as missing.+ // That is what the `Rust Feature-Gate Smoke (gates off)` lane caught twice.+ //+ // A stale name is a property of the `PACKS` table, not of the build, so+ // checking it in one fully-featured configuration is sufficient. The product+ // lane runs with all of these on, which is where a stale entry is caught.+ //+ // Deliberately ONE condition rather than a per-pack feature map: a map has+ // to be updated every time a pack becomes gated, and the failure mode of+ // forgetting is a confusing red in an unrelated lane rather than a clear+ // signal here.+ if !cfg!(all(+ feature = "flows",+ feature = "mcp",+ feature = "skills",+ feature = "web3",+ feature = "documents",+ feature = "voice",+ )) {+ return;+ }++ let mut missing: Vec<String> = Vec::new();+ for pack in crate::openhuman::tools::toolpacks::PACKS {- // Registered only once the user is signed in to Composio- // (`all_composio_agent_tools` returns an empty vec otherwise,- // `integrations/composio/tools_part_03.rs:320-323`) — runtime auth- // state no unit test can satisfy, in any feature configuration.- if pack.id == "composio" {++ // Registered only once the user is signed in: `composio`'s tools come++ // from `all_composio_agent_tools`, which returns an empty vec without++ // a session (`integrations/composio/tools_part_03.rs:320-323`), and++ // `storage` / `media` are built behind `integrations::build_client`,++ // which needs a session token (`file_storage/tools_part_02.rs`,++ // `media/generation/tools.rs`). Runtime auth state no unit test can++ // satisfy, in any feature configuration. Every name in those three is++ // a real tool in the source it is built from, verified by hand at the++ // time each pack was added — that is the check this skip replaces.++ if matches!(pack.id, "composio" | "storage" | "media") {+ continue;+ }+ for name in pack.tools {+ if registered.contains(name) || delegates.contains(*name) {+ continue;+ }+ missing.push(format!("{}::{}", pack.id, name));+ }+ }+ assert!(+ missing.is_empty(),+ "every tool named in a pack must resolve to a registered tool (or be a \+ delegate name); these do not: {missing:?}"+ );+ }+#[test]fn all_tools_always_registers_curl() {// Regression guard: `curl` is always registered (gated only bydiff --cc src/openhuman/tools/toolpacks/mod.rsindex 0c6429d677,29ec710eb3..c97b075889--- a/src/openhuman/tools/toolpacks/mod.rs+++ b/src/openhuman/tools/toolpacks/mod.rs@@@ -29,12 -28,15 +29,18 @@@ pub mod toolspub mod types;pub use groups::{GroupMode, ToolGroups, GROUP_COUNT};-pub use ops::{append_pack_tools, bind_pack_registry, strip_packed_from_visible};+pub use ops::{+ append_pack_tools, bind_pack_registry, bind_synthesized_pack_registry,+ strip_packed_from_visible,+};- pub use registry::{all_packed_tool_names, pack, pack_for_tool, PACKS};- pub use tools::{PackRegistryHandle, USE_SKILL};+ pub use registry::{+ all_packed_tool_names, callable_pack_ids, pack, pack_for_tool, pack_index_markdown_filtered,+ PACKS,+ };+ pub use tools::{- render_pack_filtered, route_sentence, scope_load_skill_spec, PackRegistryHandle, LOAD_SKILL,++ named_tool, render_pack_filtered, route_sentence, scope_use_skill_spec, PackRegistryHandle,+ USE_SKILL,+ };pub use types::ToolPack;#[cfg(test)]diff --cc src/openhuman/tools/toolpacks/registry.rsindex 3666ced599,f095ffc478..4ac4ff9345--- a/src/openhuman/tools/toolpacks/registry.rs+++ b/src/openhuman/tools/toolpacks/registry.rs@@@ -381,11 -256,27 +381,27 @@@ pub fn packed_tool_names_for_agent(agen.collect()}-/// The always-on index: one line per pack, rendered into `load_skill`'s own+/// The always-on index: one line per pack, rendered into `use_skill`'s own/// description so the model can pick a pack without a round trip.pub fn pack_index_markdown() -> String {+ pack_index_markdown_filtered(&|_| true)+ }++ /// The pack index, limited to packs this session can call at least one tool in.+ ///+ /// A pack with nothing callable is not an answer to "which skills can I load",+ /// and advertising it costs a round trip: the model loads it, learns it cannot+ /// use it, and comes back. The capability does not disappear — a pack's owners+ /// reach the model through their own `delegate_*` tools, whose `when_to_use`+ /// descriptions are already on the wire and are what the model should call+ /// anyway. Keeping the pack listed here would duplicate that routing on every+ /// single turn.+ pub fn pack_index_markdown_filtered(is_callable: &dyn Fn(&str) -> bool) -> String {let mut out = String::new();for p in PACKS {+ if !p.tools.iter().any(|t| is_callable(t)) {+ continue;+ }out.push_str(&format!("- `{}` — {}\n", p.id, p.summary));}outdiff --cc src/openhuman/tools/toolpacks/toolpacks_tests.rsindex 057bcfb7c9,090c291613..990b71a527--- a/src/openhuman/tools/toolpacks/toolpacks_tests.rs+++ b/src/openhuman/tools/toolpacks/toolpacks_tests.rs@@@ -733,3 -541,96 +747,96 @@@ fn rebinding_a_pack_handle_repoints_it_"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 handle = crate::openhuman::tools::traits::pack_registry_handle(find(&tools, USE_SKILL))++ .expect("use_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 handle = crate::openhuman::tools::traits::pack_registry_handle(find(&tools, USE_SKILL))++ .expect("use_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 --cc src/openhuman/tools/toolpacks/toolpacks_tests_part_02_tests.rsindex 0000000000,9fb0fe7ab7..f5060bf94amode 000000,100644..100644--- a/src/openhuman/tools/toolpacks/toolpacks_tests_part_02_tests.rs+++ b/src/openhuman/tools/toolpacks/toolpacks_tests_part_02_tests.rs@@@ -1,0 -1,178 +1,178 @@@+ //! Tool-pack advertisement: the index the model reads, and the disclosure /+ //! execution distinction the whole pack mechanism rests on.++ use super::*;++ // ── the index must agree with the gate too ──────────────────────────────────+-/// A spec shaped like the one `LoadSkillTool` publishes.-fn load_skill_spec() -> crate::openhuman::tools::traits::ToolSpec {++/// A spec shaped like the one `UseSkillTool` publishes.++fn use_skill_spec() -> crate::openhuman::tools::traits::ToolSpec {+ let tools = registry_with_all(&["build_workflow"]);- let tool = find(&tools, LOAD_SKILL);++ let tool = find(&tools, USE_SKILL);+ crate::openhuman::tools::traits::ToolSpec {+ name: tool.name().to_string(),+ description: tool.description().to_string(),+ parameters: tool.parameters_schema(),+ }+ }++ /// The landing was fixed first; this is the invitation. A pack the session can+ /// call nothing in must not be advertised as loadable — the model would go,+ /// find out, and come back, which is a wasted round trip on every turn it is+ /// tempted.+ #[test]+ fn the_index_drops_a_pack_this_session_can_call_nothing_in() {- let mut spec = load_skill_spec();++ let mut spec = use_skill_spec();+ assert!(+ spec.description.contains("`system`"),+ "precondition: the unscoped index advertises every pack"+ );++ // Only the workflows pack is reachable.+ let workflows = pack("workflows").expect("workflows pack");- let kept = scope_load_skill_spec(&mut spec, &|name| workflows.tools.contains(&name));++ let kept = scope_use_skill_spec(&mut spec, &|name| workflows.tools.contains(&name));+ assert!(+ kept,- "workflows is callable, so load_skill stays on the wire"++ "workflows is callable, so use_skill stays on the wire"+ );++ assert!(+ spec.description.contains("`workflows`"),+ "a reachable pack must still be offered: {}",+ spec.description+ );+ for dead in ["`system`", "`crypto`", "`audio`", "`documents`"] {+ assert!(+ !spec.description.contains(dead),+ "{dead} has no callable tool here and must not be advertised: {}",+ spec.description+ );+ }+ }++ /// The schema is the stronger half: an unusable pack becomes unrepresentable,+ /// not merely discouraged in prose.+ #[test]+ fn the_skill_enum_offers_only_reachable_packs() {- let mut spec = load_skill_spec();++ let mut spec = use_skill_spec();+ let workflows = pack("workflows").expect("workflows pack");- scope_load_skill_spec(&mut spec, &|name| workflows.tools.contains(&name));++ scope_use_skill_spec(&mut spec, &|name| workflows.tools.contains(&name));++ let values = spec+ .parameters+ .pointer("/properties/skill/enum")+ .and_then(Value::as_array)+ .expect("the skill enum survives scoping")+ .iter()+ .filter_map(Value::as_str)+ .collect::<Vec<_>>();+ assert_eq!(+ values,+ vec!["workflows"],+ "the enum must name exactly the reachable packs"+ );+ }++ /// An empty index and an empty enum are not a tool. The caller is told to drop-/// `load_skill` rather than ship one that can do nothing.++/// `use_skill` rather than ship one that can do nothing.+ #[test]-fn a_session_that_can_reach_no_pack_loses_load_skill() {- let mut spec = load_skill_spec();++fn a_session_that_can_reach_no_pack_loses_use_skill() {++ let mut spec = use_skill_spec();+ assert!(- !scope_load_skill_spec(&mut spec, &|_| false),- "with nothing reachable, load_skill must be dropped, not emptied"++ !scope_use_skill_spec(&mut spec, &|_| false),++ "with nothing reachable, use_skill must be dropped, not emptied"+ );+ }++ /// Scoping must not quietly cost more context than it saves — the index is+ /// charged to every turn.+ #[test]+ fn scoping_the_index_only_ever_shrinks_it() {- let mut spec = load_skill_spec();++ let mut spec = use_skill_spec();+ let before = spec.description.len();+ let workflows = pack("workflows").expect("workflows pack");- scope_load_skill_spec(&mut spec, &|name| workflows.tools.contains(&name));++ scope_use_skill_spec(&mut spec, &|name| workflows.tools.contains(&name));+ assert!(+ spec.description.len() < before,+ "scoped index ({}) must be smaller than the full one ({before})",+ spec.description.len()+ );+ }++ /// **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 --cc src/openhuman/tools/toolpacks/tools.rsindex 51fe312455,9c694c509e..d2ac19a97e--- a/src/openhuman/tools/toolpacks/tools.rs+++ b/src/openhuman/tools/toolpacks/tools.rs@@@ -6,9 -6,12 +6,11 @@@ use async_trait::async_traituse serde_json::{json, Value};use super::registry;- use crate::openhuman::tools::traits::{PermissionLevel, Tool, ToolCallOptions, ToolResult};+ use crate::openhuman::tools::traits::{+ PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolSpec,+ };use tinytools::ToolRunContext;-pub const LOAD_SKILL: &str = "load_skill";pub const USE_SKILL: &str = "use_skill";/// An `Arc`-shared, owned view of the tool registry a pack tool lives in.@@@ -123,14 -74,39 +125,39 @@@ 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 {+ // Scoped too: offering a hallucinating model a pack it cannot use is the+ // same wrong turn the advertised index used to take, one error later.return Err(format!("Unknown skill `{skill}`. Available:\n{}",- registry::pack_index_markdown()+ registry::pack_index_markdown_filtered(is_callable)));};- let Some(tools) = handle.tools() else {+ if handle.registries().is_empty() {return Err("The skill registry is not available in this session; the tools in this skill \cannot be loaded."@@@ -150,10 -126,15 +177,16 @@@// A pack may name a tool this build compiled out (feature gate) or that// this agent never had. Rendering the ones that exist beats failing the// whole load.- let Some(tool) = tools.iter().find(|t| t.name() == *name) else {+ let Some((tools, idx)) = handle.find(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;+ }+ let tool = &tools[idx];found += 1;out.push_str(&format!("## `{}`\n\n{}\n\n",@@@ -180,33 -166,150 +218,112 @@@Ok(out)}-/// The "go here instead" sentence shared by the `load_skill` listing and the++/// The "go here instead" sentence shared by the `use_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, "")+ }+-/// Rewrite `load_skill`'s advertised spec to match what this session can do.++/// Rewrite `use_skill`'s advertised spec to match what this session can do.+ ///-/// The description is built once in [`LoadSkillTool::new`], before any session++/// The description is built once in [`UseSkillTool::new`], before any session+ /// exists, so every agent was told all ten packs were loadable — including ones+ /// it can call nothing in. Post-#(routing fix) that costs one wasted round trip+ /// instead of a dead turn; it should cost zero.+ ///+ /// Both halves are rewritten, and the schema is the stronger one: narrowing the+ /// `skill` enum makes an unusable pack *unrepresentable* rather than merely+ /// discouraged in prose, and a shorter enum is fewer tokens, not more.+ ///+ /// Returns `false` when this session can call nothing in any pack — the caller-/// should then drop `load_skill` / `use_skill` from the wire entirely, because-/// an empty index and an empty enum are not a tool.-pub fn scope_load_skill_spec(spec: &mut ToolSpec, is_callable: &dyn Fn(&str) -> bool) -> bool {++/// should then drop `use_skill` from the wire entirely, because an empty index++/// and an empty enum are not a tool.++pub fn scope_use_skill_spec(spec: &mut ToolSpec, is_callable: &dyn Fn(&str) -> bool) -> bool {+ let ids = registry::callable_pack_ids(is_callable);+ if ids.is_empty() {+ return false;+ }+ if let Some(index) = spec.description.find("\n\nSkills:\n") {+ spec.description.truncate(index);+ spec.description.push_str("\n\nSkills:\n");+ spec.description+ .push_str(®istry::pack_index_markdown_filtered(is_callable));+ }+ if let Some(enum_slot) = spec+ .parameters+ .pointer_mut("/properties/skill/enum")+ .filter(|v| v.is_array())+ {+ *enum_slot = Value::Array(+ ids.iter()+ .map(|id| Value::String((*id).to_string()))+ .collect(),+ );+ }+ true+ }+fn skill_enum() -> Vec<&'static str> {registry::PACKS.iter().map(|p| p.id).collect()}-/// Renders a pack's tool schemas into the conversation on demand.-pub struct LoadSkillTool {- handle: PackRegistryHandle,- description: String,-}--impl LoadSkillTool {- pub fn new(handle: PackRegistryHandle) -> Self {- let description = format!(- "Load a skill's tools into this conversation. Their names, descriptions and argument \- schemas are NOT in your context until you do. Call this before `use_skill` for any \- skill you have not already loaded in this conversation.\n\nSkills:\n{}",- registry::pack_index_markdown()- );- Self {- handle,- description,- }- }-}--#[async_trait]-impl Tool for LoadSkillTool {- fn name(&self) -> &str {- LOAD_SKILL- }-- fn description(&self) -> &str {- &self.description- }-- fn parameters_schema(&self) -> Value {- json!({- "type": "object",- "properties": {- "skill": { "type": "string", "enum": skill_enum(), "description": "Skill to load." }- },- "required": ["skill"]- })- }-- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {- let Some(skill) = args.get("skill").and_then(Value::as_str) else {- return Ok(ToolResult::error("`skill` is required."));- };- Ok(match render_pack(skill, &self.handle) {- Ok(text) => ToolResult::success(text),- Err(message) => ToolResult::error(message),- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::ReadOnly- }-- /// The registry handle rides on the vocabulary's erased host extension:- /// `PackRegistryHandle` is this host's concept, and `tinytools` has no- /// business naming it. `traits::pack_registry_handle` reads it back.- fn host_extension(&self) -> Option<&(dyn std::any::Any + Send + Sync)> {- Some(&self.handle)- }+/// The tool named in `args`, if the caller named one at all.+///+/// An absent (or empty) `tool` is not a malformed call: it is the disclosure+/// half of this tool, and the distinction decides both which branch+/// [`UseSkillTool::execute_with_context`] takes and what permission level the- /// call is gated at.- fn named_tool(args: &Value) -> Option<&str> {++/// call is gated at. Public because the policy middleware has to draw the same++/// line — it intercepts the disclosure half to scope the listing to the session++/// and lets the execution half through to its gate — and two spellings of "did++/// the caller name a tool" would be two chances to disagree.++pub fn named_tool(args: &Value) -> Option<&str> {+ args.get("tool")+ .and_then(Value::as_str)+ .filter(|name| !name.is_empty())}-/// Executes a tool belonging to a pack.+/// The one always-on tool that stands in for every packed tool.+///+/// It is both halves of the pack seam. Called with a `skill` alone it renders+/// that pack's tool schemas into the conversation; called with a `skill` and a+/// `tool` it executes that tool. These were two tools — `load_skill` and+/// `use_skill` — until the pack index that each carried in its own description+/// made the pair spend 3.3 kB of every single turn saying one list twice, and+/// made the first call of any packed tool a mandatory two-call round trip.+/// A model that learned the retired name gets the harness's "unknown tool"+/// recovery result (#4249) and retries against the schema it can actually see,+/// so no alias is carried for it.////// **Permission forwarding is load-bearing.** The harness gates a call on the/// tool's `permission_level_with_args`, so a proxy reporting its own level would