JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix:深度研究精简版没有生效
jdfff6118e7e2ad0e
diff --git a/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py b/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.pyindex b13fd9d88a..ae615f7e4e 100644--- a/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/progressive_tool_rail.py@@ -1,8 +1,9 @@# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-"""Progressive tool rail - fixed tools schema with deferred tool access.+"""Progressive tool rail - stable base schema with deferred tool access.- eager_tools: always visible in the model tools schema+- skill-gated tools: direct-visible only while their required skill is active- deferred_tools: registered at runtime but hidden from schema; accessed viatools_search + invoke_tool- disabled_tools / DisabledToolsRail: excluded from schema, navigation,@@ -14,8 +15,9 @@ Fixed schema maximizes LLM prefix caching while keeping rarely used tools reachafrom __future__ import annotationsimport logging+from collections.abc import Callable, Iterable, Iterator, Mappingfrom contextlib import ExitStack, contextmanager, nullcontext-from typing import Any, Callable, Iterable, Iterator+from typing import Anyimport anyiofrom openjiuwen.core.runner import Runner@@ -25,14 +27,14 @@ from openjiuwen.harness.prompts import PromptSectionfrom openjiuwen.harness.prompts.sections import SectionNamefrom openjiuwen.harness.rails.base import DeepAgentRail-from jiuwenswarm.agents.harness.common.tools.tools_search_tool import (- ToolsSearchInput,- ToolsSearchTool,-)from jiuwenswarm.agents.harness.common.tools.invoke_tool_tool import (InvokeToolInput,InvokeToolTool,)+from jiuwenswarm.agents.harness.common.tools.tools_search_tool import (+ ToolsSearchInput,+ ToolsSearchTool,+)from jiuwenswarm.common.mcp_config import (OFFICE_CLAW_EXPECTED_TOOL_IDS_KWARG,bind_active_office_claw_mcp_tools,@@ -56,6 +58,7 @@ def _office_claw_tool_env_value(tool: Any, key: str) -> str:logger = logging.getLogger(__name__)_LOG_PREFIX = "[ProgressiveToolRail]"+_REQUIRED_SKILL_KEY = "required_skill"_EAGER_DEEPRESEARCH_BINDINGS_KEY = "__eager_deepresearch_bindings__"_DEEPRESEARCH_CONTEXT_TOOLS = frozenset({"deepresearch_execute",@@ -90,13 +93,35 @@ def _json_safe_value(value: Any) -> Any:return str(value)+def _required_skill_requirement(tool: Any) -> tuple[bool, str | None]:+ """Return whether a ToolCard declares a gate and its valid skill name.++ A missing property preserves the existing eager/deferred behavior. Once the+ property is present, malformed values remain declared but resolve to+ ``None`` so every visibility and execution surface fails closed.+ """+ properties = getattr(tool, "properties", None)+ if not isinstance(properties, Mapping) or _REQUIRED_SKILL_KEY not in properties:+ return False, None+ value = properties.get(_REQUIRED_SKILL_KEY)+ if not isinstance(value, str):+ return True, None+ skill_name = value.strip()+ if not skill_name or skill_name in {".", ".."}:+ return True, None+ if "/" in skill_name or "\\" in skill_name:+ return True, None+ return True, skill_name++class ProgressiveToolRail(DeepAgentRail):- """Progressive tool visibility with a fixed eager-tools schema.+ """Progressive tool visibility with a stable base eager-tools schema.- eager_tools: always visible in the model tools schema+ - skill-gated tools: direct-visible only while their declared skill is active- deferred_tools: registered in ability_manager but hidden from schema;accessed via tools_search (get schema) + invoke_tool (proxy call)- - tools schema never changes, maximizing LLM prefix cache+ - ordinary tool schema stays stable, maximizing LLM prefix cache"""priority = 80@@ -111,6 +136,7 @@ class ProgressiveToolRail(DeepAgentRail):agent_card_id: str | None = None,enable_for_models: list[str] | None = None,deepresearch_context_provider: Callable[[], dict[str, str]] | None = None,+ active_skill_provider: Callable[[], str | None] | None = None,disabled_tools: list[str] | None = None,) -> None:super().__init__()@@ -126,6 +152,7 @@ class ProgressiveToolRail(DeepAgentRail):]self._cached_model_name = ""self._deepresearch_context_provider = deepresearch_context_provider+ self._active_skill_provider = active_skill_providerself._disabled_tools: set[str] = {str(name).strip()for name in (disabled_tools or [])@@ -204,6 +231,110 @@ class ProgressiveToolRail(DeepAgentRail):)return frozenset(name for name in names if name)+ def _current_active_skill(self) -> str | None:+ """Read the session's active skill without trusting provider failures."""+ provider = getattr(self, "_active_skill_provider", None)+ if provider is None:+ return None+ try:+ value = provider()+ except Exception as exc: # noqa: BLE001 - provider failure must fail closed+ logger.warning("%s failed to read active skill: %s", _LOG_PREFIX, exc)+ return None+ if not isinstance(value, str):+ return None+ return value or None++ @staticmethod+ def _tool_by_name(tools: Iterable[Any], tool_name: str) -> Any | None:+ for tool in tools:+ if str(getattr(tool, "name", "") or "") == tool_name:+ return tool+ return None++ def _registered_tool_card(+ self,+ agent: Any,+ tool_name: str,+ ) -> tuple[bool, Any | None]:+ """Return an authoritative registered card without refreshing MCP lists.++ The boolean distinguishes a successful negative lookup from an+ unavailable registry. Callers must fail closed when the registry cannot+ be read; otherwise a transient metadata failure could bypass a gate.+ """+ ability_manager = getattr(agent, "ability_manager", None)+ if ability_manager is None:+ return False, None++ getter = getattr(ability_manager, "get", None)+ if callable(getter):+ try:+ return True, getter(tool_name)+ except Exception as exc: # noqa: BLE001 - lookup failure is deny+ logger.warning(+ "%s failed to get registered tool card name=%s error=%s",+ _LOG_PREFIX,+ tool_name,+ exc,+ )+ return False, None++ lister = getattr(ability_manager, "list", None)+ if callable(lister):+ try:+ return True, self._tool_by_name(lister(), tool_name)+ except Exception as exc: # noqa: BLE001 - lookup failure is deny+ logger.warning(+ "%s failed to list registered tool cards name=%s error=%s",+ _LOG_PREFIX,+ tool_name,+ exc,+ )+ return False, None++ @staticmethod+ def _reject_tool_not_available(ctx: AgentCallbackContext, tool_name: str) -> None:+ """Short-circuit a forged/stale direct call with a normal ToolMessage."""+ from openjiuwen.core.foundation.llm import ToolMessage++ message = (+ f"[TOOL_NOT_AVAILABLE] Tool '{tool_name}' is not available "+ "in the current skill context."+ )+ inputs = getattr(ctx, "inputs", None)+ tool_call = getattr(inputs, "tool_call", None)+ tool_call_id = str(getattr(tool_call, "id", "") or "")+ ctx.extra["_skip_tool"] = True+ inputs.tool_result = message+ inputs.tool_msg = ToolMessage(content=message, tool_call_id=tool_call_id)++ async def _skill_gate_blocks_direct_call(+ self,+ ctx: AgentCallbackContext,+ tool_name: str,+ ) -> bool:+ """Revalidate a declared gate immediately before direct execution."""+ cached_card = self._tool_by_name(+ getattr(self, "_cached_all_tool_infos", ()),+ tool_name,+ )+ agent = self._resolve_runtime_agent(ctx)+ lookup_succeeded, live_card = self._registered_tool_card(agent, tool_name)+ if not lookup_succeeded:+ return True+ declared, required_skill = _required_skill_requirement(+ live_card if live_card is not None else cached_card+ )+ if not declared:+ return False+ return (+ live_card is None+ or tool_name in self._current_disabled_tools()+ or required_skill is None+ or required_skill != self._current_active_skill()+ )+def set_office_claw_active_tool_ids(self,tool_ids: Iterable[str] | None,@@ -421,7 +552,7 @@ class ProgressiveToolRail(DeepAgentRail):return agentasync def before_tool_call(self, ctx: AgentCallbackContext) -> None:- """Bind trusted tenant context for the direct DeepResearch entry."""+ """Enforce skill gates, then bind trusted direct-tool context."""inputs = getattr(ctx, "inputs", None)tool_call = getattr(inputs, "tool_call", None)tool_name = str(@@ -429,6 +560,9 @@ class ProgressiveToolRail(DeepAgentRail):or getattr(tool_call, "name", "")or "").strip()+ if tool_name and await self._skill_gate_blocks_direct_call(ctx, tool_name):+ self._reject_tool_not_available(ctx, tool_name)+ returnif tool_name != "deepresearch_execute":returnmanager = self._bind_deepresearch_context(tool_name)@@ -606,16 +740,15 @@ class ProgressiveToolRail(DeepAgentRail):)async def before_model_call(self, ctx: AgentCallbackContext) -> None:- """Filter tools to eager_tools (minus disabled) and inject navigation."""- if not self._lazy_load_active_for_ctx(ctx):- return-+ """Always enforce skill gates; optionally apply progressive loading."""+ lazy_load_active = self._lazy_load_active_for_ctx(ctx)if getattr(ctx, "agent", None) is not None:self._runtime_agent = ctx.agent- self._resolve_runtime_agent(ctx)- await self._refresh_deferred_tool_cache_if_stale()+ agent = self._resolve_runtime_agent(ctx)+ if lazy_load_active:+ await self._refresh_deferred_tool_cache_if_stale()disabled = self._current_disabled_tools()- if any(+ if lazy_load_active and any(str(getattr(tool, "name", "") or "") in disabledfor tool in self._cached_deferred_tool_infos):@@ -632,14 +765,38 @@ class ProgressiveToolRail(DeepAgentRail):returnoriginal_count = len(tools)+ active_skill = self._current_active_skill()+ active_gated_names: list[str] = []filtered_tools = []for tool in tools:name = str(getattr(tool, "name", "") or "")- if name in self.eager_tools and name not in disabled:+ lookup_succeeded, live_card = self._registered_tool_card(agent, name)+ if not lookup_succeeded or live_card is None:+ continue+ declared, required_skill = _required_skill_requirement(live_card)+ if name in disabled:+ continue+ if declared:+ if (+ live_card is not None+ and required_skill is not None+ and required_skill == active_skill+ ):+ filtered_tools.append(tool)+ if name not in active_gated_names:+ active_gated_names.append(name)+ continue+ if not lazy_load_active or name in self.eager_tools:filtered_tools.append(tool)- # Canonical eager order — never follow ability_manager / MCP rebind order.- # Mid-task send_file_to_user <-> tools_search swaps break LLM prefix cache.- inputs.tools = self._order_tools_by_eager_list(filtered_tools)+ if lazy_load_active:+ # Canonical eager order — never follow ability_manager / MCP rebind order.+ # Mid-task send_file_to_user <-> tools_search swaps break LLM prefix cache.+ inputs.tools = self._order_tools_by_name_list(+ filtered_tools,+ [*self.eager_tools, *active_gated_names],+ )+ else:+ inputs.tools = filtered_toolsinput_tool_names = set()for tool in tools:@@ -658,16 +815,24 @@ class ProgressiveToolRail(DeepAgentRail):sorted(disabled),)- await self._add_navigation_section(ctx)+ if lazy_load_active:+ await self._add_navigation_section(ctx)def _order_tools_by_eager_list(self, tools: list[Any]) -> list[Any]:"""Stable-sort filtered tools to match ``self.eager_tools`` order."""+ return self._order_tools_by_name_list(tools, self.eager_tools)++ @staticmethod+ def _order_tools_by_name_list(+ tools: list[Any], ordered_names: Iterable[str]+ ) -> list[Any]:+ """Stable-sort filtered tools to match an explicit canonical order."""by_name: dict[str, Any] = {}for tool in tools:name = str(getattr(tool, "name", "") or "")if name and name not in by_name:by_name[name] = tool- return [by_name[name] for name in self.eager_tools if name in by_name]+ return [by_name[name] for name in ordered_names if name in by_name]@staticmethoddef _deferred_name_fingerprint(tools: list[Any]) -> frozenset[str]:@@ -891,7 +1056,11 @@ class ProgressiveToolRail(DeepAgentRail):async def _get_all_tool_infos(self, agent: Any = None) -> list[Any]:"""Get navigable tool cards from ability_manager (MCP list kept in sync)."""- resolved = agent or self._runtime_agent or self._deep_agent+ resolved = (+ agent+ or getattr(self, "_runtime_agent", None)+ or getattr(self, "_deep_agent", None)+ )if resolved is None:return []@@ -930,7 +1099,8 @@ class ProgressiveToolRail(DeepAgentRail):deferred_tools = []for tool in all_tools:name = str(getattr(tool, "name", "") or "")- if name not in self.eager_tools and name not in disabled:+ declared, _required_skill = _required_skill_requirement(tool)+ if not declared and name not in self.eager_tools and name not in disabled:deferred_tools.append(tool)self._cached_deferred_tool_infos = deferred_tools@@ -958,6 +1128,17 @@ class ProgressiveToolRail(DeepAgentRail):if str(getattr(tool, "id", "") or "")}+ @staticmethod+ def _required_skill_states(+ tools: list[Any],+ ) -> dict[str, tuple[bool, str | None]]:+ """Return live declaration states so same-id card updates invalidate."""+ return {+ str(getattr(tool, "name", "") or ""): _required_skill_requirement(tool)+ for tool in tools+ if str(getattr(tool, "name", "") or "")+ }+async def _refresh_deferred_tool_cache_if_stale(self) -> None:"""Refresh cache when ability_manager has tools not in cache."""agent = self._resolve_runtime_agent()@@ -975,13 +1156,21 @@ class ProgressiveToolRail(DeepAgentRail):):await self._refresh_deferred_tool_cache(agent)return+ if self._required_skill_states(live_tools) != self._required_skill_states(+ self._cached_all_tool_infos+ ):+ await self._refresh_deferred_tool_cache(agent)+ returndisabled = self._current_disabled_tools()live_deferred = []for tool in live_tools:name = str(getattr(tool, "name", "") or "")- if name not in self.eager_tools and name not in disabled:+ declared, _required_skill = _required_skill_requirement(tool)+ if not declared and name not in self.eager_tools and name not in disabled:live_deferred.append(tool)- if live_deferred and not self._cached_deferred_tool_infos:+ if self._tool_name_set(live_deferred) != self._tool_name_set(+ self._cached_deferred_tool_infos+ ):await self._refresh_deferred_tool_cache(agent)# ------------------------------------------------------------------@@ -1323,17 +1512,34 @@ class ProgressiveToolRail(DeepAgentRail):"tool_name": "",}- if tool_name in self.eager_tools:+ if tool_name in self._current_disabled_tools():return {"success": False,- "error": f"工具 '{tool_name}' 是常驻可见工具,可直接调用,无需通过 invoke_tool。",+ "error": f"工具 '{tool_name}' 已禁用,无法通过 invoke_tool 调用。","tool_name": tool_name,}- if tool_name in self._current_disabled_tools():+ registered_card = self._tool_by_name(+ getattr(self, "_cached_all_tool_infos", ()),+ tool_name,+ )+ if registered_card is None:+ registered_card = self._tool_by_name(+ self._cached_deferred_tool_infos,+ tool_name,+ )+ declared, _required_skill = _required_skill_requirement(registered_card)+ if declared:return {"success": False,- "error": f"工具 '{tool_name}' 已禁用,无法通过 invoke_tool 调用。",+ "error": f"工具 '{tool_name}' 未注册或不在按需可见工具列表中。",+ "tool_name": tool_name,+ }++ if tool_name in self.eager_tools:+ return {+ "success": False,+ "error": f"工具 '{tool_name}' 是常驻可见工具,可直接调用,无需通过 invoke_tool。","tool_name": tool_name,}diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.pyindex 2fa9ac6b12..a4aba5c78c 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py@@ -1055,6 +1055,7 @@ async def deepresearch_execute(deepresearch_execute.card.properties["resilience"] = {"timeout_s": None}+deepresearch_execute.card.properties["required_skill"] = "deepresearch"deepresearch_execute.card.parallel_safe = Falsediff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 3596251796..20c5750451 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -297,6 +297,7 @@ from jiuwenswarm.agents.harness.common.rails.disabled_tools_rail import (from jiuwenswarm.agents.harness.common.rails.skill_active_state import (SkillActiveStateRail,clear_session_skill_state,+ get_session_active_skill,resolve_stale_invoke_limit,)from jiuwenswarm.agents.harness.common.rails.skill_credential_injection_rail import (@@ -1507,20 +1508,20 @@ def build_progressive_tool_rail_from_config(agent_card_id: str | None = None,subagent_kind: str | None = None,deepresearch_context_provider: Callable[[], dict[str, str]] | None = None,+ active_skill_provider: Callable[[], str | None] | None = None,) -> ProgressiveToolRail | None:"""Build ProgressiveToolRail from react.tool_lazy_load config.- Fixed eager-tools schema; deferred tools are reached via tools_search +- invoke_tool. For subagents, set profile="subagent" and configure+ Stable base eager-tools schema; deferred tools are reached via tools_search+ + invoke_tool, while ToolCard skill gates may add direct tools for the+ active session skill. For subagents, set profile="subagent" and configurereact.tool_lazy_load.subagents."""config = react_config if isinstance(react_config, dict) else {}lazy_cfg = config.get("tool_lazy_load") or {}if not isinstance(lazy_cfg, dict):lazy_cfg = {}-- if not lazy_cfg.get("enabled", False):- return None+ lazy_load_enabled = bool(lazy_cfg.get("enabled", False))enable_for_models = _normalize_tool_names(lazy_cfg.get("enable_for_models", []), []@@ -1550,10 +1551,6 @@ def build_progressive_tool_rail_from_config(lazy_cfg.get("eager_tools", _DEFAULT_PROGRESSIVE_EAGER_TOOLS),_DEFAULT_PROGRESSIVE_EAGER_TOOLS,)- # This tool owns native multi-step HITL. It must execute directly;- # invoke_tool would hide the outer call from its lifecycle Rail.- if "deepresearch_execute" not in eager_tools:- eager_tools.insert(2, "deepresearch_execute")eager_tools = _ensure_ttse_consult_eager_tool(eager_tools, config)@@ -1569,8 +1566,10 @@ def build_progressive_tool_rail_from_config()logger.info(- "[ProgressiveToolRail] enabled profile=%s kind=%s eager_tools=%s "+ "[ProgressiveToolRail] mounted lazy_load_enabled=%s profile=%s "+ "kind=%s eager_tools=%s ""agent_id=%s agent_card_id=%s enable_for_models=%s disabled_tools=%s",+ lazy_load_enabled,normalized_profile,subagent_kind or "",eager_tools,@@ -1581,13 +1580,14 @@ def build_progressive_tool_rail_from_config()return ProgressiveToolRail(- enabled=True,+ enabled=lazy_load_enabled,eager_tools=eager_tools,language=normalized_language,agent_id=agent_id,agent_card_id=agent_card_id,enable_for_models=enable_for_models,deepresearch_context_provider=deepresearch_context_provider,+ active_skill_provider=active_skill_provider,disabled_tools=disabled_tools,)@@ -9094,13 +9094,30 @@ class JiuWenSwarmDeepAdapter:agent_id=self._tool_owner_id(),agent_card_id=self._tool_owner_id(),deepresearch_context_provider=self._get_deepresearch_tool_context,+ active_skill_provider=self._get_progressive_active_skill,)if rail is not None:logger.info(- "[JiuWenSwarmDeepAdapter] ProgressiveToolRail enabled (fixed schema mode)"+ "[JiuWenSwarmDeepAdapter] ProgressiveToolRail mounted mode=%s",+ "progressive" if rail.enabled else "skill-gate-only",)return rail+ def _get_progressive_active_skill(self) -> str | None:+ """Return active-skill state for this adapter's current session."""+ session_id = str(self._skill_rail_session_id() or "").strip()+ if not session_id:+ session_id = str(get_runtime_tool_session_id() or "").strip()+ if not session_id:+ session_id = str(+ self._current_request_route.get("session_id") or ""+ ).strip()+ if not session_id:+ session_id = str(+ self._runtime_cron_tool_context.session_id or ""+ ).strip()+ return get_session_active_skill(session_id) if session_id else None+@staticmethoddef _build_disabled_tools_rail(config: dict[str, Any]diff --git a/tests/unit_tests/agentserver/test_agentserver_modes.py b/tests/unit_tests/agentserver/test_agentserver_modes.pyindex fbb58b4c6a..123c29276f 100644--- a/tests/unit_tests/agentserver/test_agentserver_modes.py+++ b/tests/unit_tests/agentserver/test_agentserver_modes.py@@ -67,7 +67,7 @@ def test_progressive_defaults_expose_registered_ask_user_tool():assert rail is not Noneassert "ask_user" in rail.eager_tools- assert "deepresearch_execute" in rail.eager_tools+ assert "deepresearch_execute" not in rail.eager_toolsassert "ask_user_question" not in rail.eager_toolsassert "ttse_consult" not in rail.eager_tools@@ -104,7 +104,6 @@ def test_progressive_legacy_eager_config_exposes_registered_ask_user_tool():assert rail.eager_tools == ["tools_search","invoke_tool",- "deepresearch_execute","read_file","ask_user",]@@ -130,7 +129,6 @@ def test_progressive_eager_tools_keep_ttse_consult_when_inject_enabled():assert rail.eager_tools == ["tools_search","invoke_tool",- "deepresearch_execute","read_file","ttse_consult","skill_acceleration_exec",diff --git a/tests/unit_tests/agentserver/test_progressive_deepresearch_context.py b/tests/unit_tests/agentserver/test_progressive_deepresearch_context.pyindex 9979e1adf0..5f4cd75b12 100644--- a/tests/unit_tests/agentserver/test_progressive_deepresearch_context.py+++ b/tests/unit_tests/agentserver/test_progressive_deepresearch_context.py@@ -192,7 +192,7 @@ async def test_deferred_deepresearch_rebinds_trusted_adapter_context():@pytest.mark.asyncio-async def test_eager_deepresearch_entry_rebinds_trusted_adapter_context():+async def test_skill_activated_deepresearch_entry_rebinds_trusted_adapter_context():service_id = "progressive-eager-service"agent_id = "office"shared_root = "/trusted/office-claw-skills"@@ -201,8 +201,12 @@ async def test_eager_deepresearch_entry_rebinds_trusted_adapter_context():service_id=service_id,agent_id=agent_id,)+ agent = SimpleNamespace(+ ability_manager=SimpleNamespace(list=lambda: [de.deepresearch_execute.card]),+ )rail = ProgressiveToolRail(- eager_tools=["tools_search", "invoke_tool", "deepresearch_execute"],+ eager_tools=["tools_search", "invoke_tool"],+ active_skill_provider=lambda: "deepresearch",deepresearch_context_provider=lambda: {"request_id": "request","channel_id": "officeclaw",@@ -216,6 +220,7 @@ async def test_eager_deepresearch_entry_rebinds_trusted_adapter_context():id="call-1", name="deepresearch_execute", arguments={"query": "q"})ctx = SimpleNamespace(+ agent=agent,inputs=ToolCallInputs(tool_call=tool_call,tool_name="deepresearch_execute",diff --git a/tests/unit_tests/agentserver/test_progressive_rail_reload.py b/tests/unit_tests/agentserver/test_progressive_rail_reload.pyindex 316724c3e1..257a9c7932 100644--- a/tests/unit_tests/agentserver/test_progressive_rail_reload.py+++ b/tests/unit_tests/agentserver/test_progressive_rail_reload.py@@ -49,10 +49,12 @@ def test_reload_plan_does_not_create_progressive_rail_when_config_omits_tool_lazassert adapter._progressive_tool_rail is None-def test_reload_plan_stages_progressive_rail_when_disabled():+def test_reload_plan_keeps_skill_gate_rail_when_lazy_loading_is_disabled():adapter = _rail_plan_adapter()old_rail = MagicMock(name="old-progressive-tool-rail")+ gate_only_rail = SimpleNamespace(enabled=False)adapter._progressive_tool_rail = old_rail+ adapter._build_progressive_tool_rail.return_value = gate_only_railrails, rails_to_unregister = adapter._get_current_agent_rails({"tool_lazy_load": {"enabled": False}},@@ -60,8 +62,9 @@ def test_reload_plan_stages_progressive_rail_when_disabled():)assert old_rail not in rails- assert rails_to_unregister == [old_rail]- assert adapter._progressive_tool_rail is old_rail+ assert gate_only_rail in rails+ assert rails_to_unregister == []+ assert adapter._progressive_tool_rail is gate_only_raildef test_reload_plan_adds_new_progressive_rail_when_enabled():diff --git a/tests/unit_tests/agentserver/test_skill_required_tool_visibility.py b/tests/unit_tests/agentserver/test_skill_required_tool_visibility.pynew file mode 100644index 0000000000..6447bc2dcf--- /dev/null+++ b/tests/unit_tests/agentserver/test_skill_required_tool_visibility.py@@ -0,0 +1,591 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Regression tests for ToolCard-declared skill-gated tools."""++from types import SimpleNamespace+from unittest.mock import AsyncMock+from uuid import uuid4++import pytest+from openjiuwen.core.foundation.llm import ToolMessage+from openjiuwen.core.foundation.llm.schema.tool_call import ToolCall+from openjiuwen.core.foundation.tool import ToolCard+from openjiuwen.core.single_agent.ability_manager import AbilityManager+from openjiuwen.core.single_agent.agent_callback_manager import AgentCallbackManager+from openjiuwen.core.single_agent.rail.base import (+ AgentCallbackContext,+ ToolCallInputs,+)++from jiuwenswarm.agents.harness.common.rails.progressive_tool_rail import (+ ProgressiveToolRail,+)+from jiuwenswarm.agents.harness.common.rails.skill_active_state import (+ SkillActiveStateRail,+ clear_session_skill_state,+)+from jiuwenswarm.agents.harness.common.tools.deepresearch.execution import (+ deepresearch_execute,+)+from jiuwenswarm.agents.harness.common.tools.invoke_tool_tool import (+ InvokeToolInput,+)+from jiuwenswarm.agents.harness.common.tools.tools_search_tool import (+ ToolsSearchInput,+)++_MISSING = object()+++def _card(name: str, required_skill: object = _MISSING) -> ToolCard:+ properties = {}+ if required_skill is not _MISSING:+ properties["required_skill"] = required_skill+ return ToolCard(+ id=f"id-{name}",+ name=name,+ description=f"description-{name}",+ input_params={},+ properties=properties,+ )+++def _agent(cards: list[ToolCard]) -> SimpleNamespace:+ return SimpleNamespace(+ ability_manager=SimpleNamespace(list=lambda: list(cards)),+ system_prompt_builder=None,+ )+++def _model_ctx(agent: SimpleNamespace, cards: list[ToolCard]) -> SimpleNamespace:+ return SimpleNamespace(+ agent=agent,+ inputs=SimpleNamespace(tools=list(cards)),+ )+++def _tool_call_ctx(agent: SimpleNamespace, tool_name: str) -> SimpleNamespace:+ tool_call = SimpleNamespace(id="call-gated", name=tool_name, arguments={})+ return SimpleNamespace(+ agent=agent,+ inputs=ToolCallInputs(+ tool_call=tool_call,+ tool_name=tool_name,+ tool_args={},+ tool_result=None,+ tool_msg=None,+ ),+ extra={},+ )+++def test_main_progressive_builder_does_not_force_skill_gated_tool_eager() -> None:+ """A direct-only HITL tool must not bypass its skill activation gate."""+ pytest.importorskip("google.genai")+ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (+ build_progressive_tool_rail_from_config,+ )++ rail = build_progressive_tool_rail_from_config(+ {+ "tool_lazy_load": {+ "enabled": True,+ "eager_tools": ["read_file"],+ }+ },+ language="cn",+ )++ assert rail is not None+ assert "deepresearch_execute" not in rail.eager_tools+++def test_deepresearch_tool_declares_its_required_skill() -> None:+ assert deepresearch_execute.card.properties["required_skill"] == "deepresearch"+++async def test_gated_tool_moves_from_hidden_to_direct_only_after_activation() -> None:+ active_skill = {"name": None}+ ordinary_eager = _card("read_file")+ ordinary_deferred = _card("ordinary_deferred")+ gated = _card("gated_direct", "research-skill")+ cards = [ordinary_eager, ordinary_deferred, gated]+ agent = _agent(cards)+ navigation_sections: list[object] = []+ agent.system_prompt_builder = SimpleNamespace(+ add_section=navigation_sections.append,+ )+ rail = ProgressiveToolRail(+ eager_tools=["read_file"],+ active_skill_provider=lambda: active_skill["name"],+ )+ rail.init(agent)++ before = _model_ctx(agent, cards)+ await rail.before_model_call(before)++ assert [tool.name for tool in before.inputs.tools] == ["read_file"]+ assert [tool.name for tool in rail._cached_deferred_tool_infos] == [+ "ordinary_deferred"+ ]+ assert navigation_sections+ navigation = str(navigation_sections[0].content)+ assert "ordinary_deferred" in navigation+ assert "gated_direct" not in navigation+ hidden_search = await rail._search_tools(+ None,+ ToolsSearchInput(tool_name="gated_direct"),+ )+ hidden_invoke = await rail._invoke_target_tool(+ None,+ InvokeToolInput(tool_name="gated_direct", arguments={}),+ )+ assert hidden_search["success"] is False+ assert hidden_search["matches"] == []+ assert hidden_invoke["success"] is False++ active_skill["name"] = "research-skill"+ after = _model_ctx(agent, cards)+ await rail.before_model_call(after)++ assert [tool.name for tool in after.inputs.tools] == [+ "read_file",+ "gated_direct",+ ]+ assert [tool.name for tool in rail._cached_deferred_tool_infos] == [+ "ordinary_deferred"+ ]+ still_not_wrapped = await rail._invoke_target_tool(+ None,+ InvokeToolInput(tool_name="gated_direct", arguments={}),+ )+ assert still_not_wrapped["success"] is False+++async def test_missing_required_skill_preserves_existing_visibility() -> None:+ ordinary_eager = _card("ordinary_eager")+ ordinary_deferred = _card("ordinary_deferred")+ cards = [ordinary_eager, ordinary_deferred]+ agent = _agent(cards)+ rail = ProgressiveToolRail(+ eager_tools=["ordinary_eager"],+ active_skill_provider=lambda: None,+ )+ rail.init(agent)++ ctx = _model_ctx(agent, cards)+ await rail.before_model_call(ctx)++ assert [tool.name for tool in ctx.inputs.tools] == ["ordinary_eager"]+ assert [tool.name for tool in rail._cached_deferred_tool_infos] == [+ "ordinary_deferred"+ ]+++ "invalid_required_skill",+ [+ None,+ "",+ " ",+ 42,+ ".",+ "..",+ "../research",+ "research/skill",+ "research\\skill",+ ],+)+async def test_invalid_required_skill_fails_closed_everywhere(+ invalid_required_skill: object,+) -> None:+ gated = _card("invalid_gate", invalid_required_skill)+ agent = _agent([gated])+ rail = ProgressiveToolRail(+ eager_tools=["invalid_gate"],+ active_skill_provider=lambda: str(invalid_required_skill),+ )+ rail.init(agent)++ ctx = _model_ctx(agent, [gated])+ await rail.before_model_call(ctx)+ search = await rail._search_tools(+ None,+ ToolsSearchInput(tool_name="invalid_gate"),+ )+ invoke = await rail._invoke_target_tool(+ None,+ InvokeToolInput(tool_name="invalid_gate", arguments={}),+ )++ assert ctx.inputs.tools == []+ assert rail._cached_deferred_tool_infos == []+ assert search["success"] is False+ assert search["matches"] == []+ assert invoke["success"] is False+++ "required_skill",+ [+ "Research-Skill",+ "research_skill",+ "openJiuwen-DeepSearch",+ ],+)+async def test_required_skill_uses_runtime_skill_name_rules(+ required_skill: str,+) -> None:+ gated = _card("gated_direct", required_skill)+ agent = _agent([gated])+ rail = ProgressiveToolRail(+ eager_tools=[],+ active_skill_provider=lambda: required_skill,+ )+ rail.init(agent)++ ctx = _model_ctx(agent, [gated])+ await rail.before_model_call(ctx)++ assert [tool.name for tool in ctx.inputs.tools] == ["gated_direct"]+++async def test_gate_remains_active_when_lazy_loading_is_disabled() -> None:+ pytest.importorskip("google.genai")+ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (+ build_progressive_tool_rail_from_config,+ )++ gated = _card("gated_direct", "research-skill")+ ordinary = _card("ordinary")+ agent = _agent([gated, ordinary])+ active_skill = {"name": None}+ rail = build_progressive_tool_rail_from_config(+ {"tool_lazy_load": {"enabled": False}},+ language="cn",+ active_skill_provider=lambda: active_skill["name"],+ )++ assert rail is not None+ assert rail.enabled is False+ rail.init(agent)+ ctx = _model_ctx(agent, [gated, ordinary])+ await rail.before_model_call(ctx)++ assert [tool.name for tool in ctx.inputs.tools] == ["ordinary"]++ active_skill["name"] = "research-skill"+ active_ctx = _model_ctx(agent, [gated, ordinary])+ await rail.before_model_call(active_ctx)++ assert [tool.name for tool in active_ctx.inputs.tools] == [+ "gated_direct",+ "ordinary",+ ]+++async def test_gate_remains_active_for_non_allowlisted_model() -> None:+ gated = _card("gated_direct", "research-skill")+ ordinary = _card("ordinary")+ agent = _agent([gated, ordinary])+ agent.model_name = "gpt-6"+ active_skill = {"name": None}+ rail = ProgressiveToolRail(+ eager_tools=[],+ enable_for_models=["glm"],+ active_skill_provider=lambda: active_skill["name"],+ )+ rail.init(agent)++ ctx = _model_ctx(agent, [gated, ordinary])+ await rail.before_model_call(ctx)++ assert [tool.name for tool in ctx.inputs.tools] == ["ordinary"]++ active_skill["name"] = "research-skill"+ active_ctx = _model_ctx(agent, [gated, ordinary])+ await rail.before_model_call(active_ctx)++ assert [tool.name for tool in active_ctx.inputs.tools] == [+ "gated_direct",+ "ordinary",+ ]+++async def test_unregistered_model_tool_is_hidden_when_lazy_loading_is_disabled() -> None:+ registered = _card("registered")+ stale = _card("stale")+ agent = _agent([registered])+ rail = ProgressiveToolRail(enabled=False, eager_tools=[])+ rail.init(agent)+ ctx = _model_ctx(agent, [registered, stale])++ await rail.before_model_call(ctx)++ assert [tool.name for tool in ctx.inputs.tools] == ["registered"]+++async def test_other_skill_and_disabled_override_keep_gated_tool_hidden() -> None:+ gated = _card("gated_direct", "research-skill")+ agent = _agent([gated])++ other_skill = ProgressiveToolRail(+ eager_tools=[],+ active_skill_provider=lambda: "other-skill",+ )+ other_skill.init(agent)+ other_ctx = _model_ctx(agent, [gated])+ await other_skill.before_model_call(other_ctx)+ assert other_ctx.inputs.tools == []++ disabled = ProgressiveToolRail(+ eager_tools=[],+ active_skill_provider=lambda: "research-skill",+ disabled_tools=["gated_direct"],+ )+ disabled.init(agent)+ disabled_ctx = _model_ctx(agent, [gated])+ await disabled.before_model_call(disabled_ctx)+ assert disabled_ctx.inputs.tools == []+++async def test_required_skill_card_in_place_update_invalidates_deferred_cache() -> None:+ active_skill = {"name": "research-skill"}+ original = _card("mutable_tool")+ cards = [original]+ agent = _agent(cards)+ rail = ProgressiveToolRail(+ eager_tools=[],+ active_skill_provider=lambda: active_skill["name"],+ )+ rail.init(agent)+ await rail._refresh_deferred_tool_cache()+ assert [tool.name for tool in rail._cached_deferred_tool_infos] == [+ "mutable_tool"+ ]++ original.properties["required_skill"] = "research-skill"+ await rail._refresh_deferred_tool_cache_if_stale()++ assert rail._cached_deferred_tool_infos == []+ assert rail._cached_all_tool_infos == [original]+++async def test_active_skill_provider_failure_keeps_gated_tool_hidden() -> None:+ gated = _card("gated_direct", "research-skill")+ agent = _agent([gated])++ def _fail_provider() -> str:+ raise RuntimeError("state unavailable")++ rail = ProgressiveToolRail(+ eager_tools=[],+ active_skill_provider=_fail_provider,+ )+ rail.init(agent)+ ctx = _model_ctx(agent, [gated])++ await rail.before_model_call(ctx)++ assert ctx.inputs.tools == []+++async def test_replayed_direct_call_is_skipped_before_tool_implementation(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ gated = _card("gated_direct", "research-skill")+ manager = AbilityManager()+ manager.add(gated)+ callbacks = AgentCallbackManager(f"required-skill-{uuid4().hex}")+ agent = SimpleNamespace(+ ability_manager=manager,+ agent_callback_manager=callbacks,+ card=SimpleNamespace(id="required-skill-agent"),+ )+ rail = ProgressiveToolRail(+ eager_tools=[],+ active_skill_provider=lambda: None,+ )+ await callbacks.register_rail(rail, agent)+ native_execute = AsyncMock(+ return_value=(+ "executed",+ ToolMessage(content="executed", tool_call_id="call-gated"),+ )+ )+ monkeypatch.setattr(manager, "_execute_single_tool_call", native_execute)+ ctx = AgentCallbackContext(agent=agent, extra={})+ call = ToolCall(+ id="call-gated",+ type="function",+ name="gated_direct",+ arguments="{}",+ )++ result, tool_message = (+ await manager.execute(+ ctx,+ call,+ SimpleNamespace(),+ parallel_tool_calls=False,+ )+ )[0]++ native_execute.assert_not_awaited()+ assert str(result).startswith("[TOOL_NOT_AVAILABLE]")+ assert tool_message.content.startswith("[TOOL_NOT_AVAILABLE]")+++async def test_registered_card_list_failure_does_not_bypass_direct_gate() -> None:+ manager = SimpleNamespace(+ list=lambda: (_ for _ in ()).throw(RuntimeError("metadata unavailable")),+ )+ agent = SimpleNamespace(ability_manager=manager)+ rail = ProgressiveToolRail(+ eager_tools=[],+ active_skill_provider=lambda: None,+ )+ rail.init(agent)+ ctx = _tool_call_ctx(agent, "gated_direct")++ await rail.before_tool_call(ctx)++ assert ctx.extra["_skip_tool"] is True+ assert str(ctx.inputs.tool_result).startswith("[TOOL_NOT_AVAILABLE]")+++async def test_registered_card_lookup_failure_fails_closed() -> None:+ manager = SimpleNamespace(+ get=lambda _name: (_ for _ in ()).throw(RuntimeError("lookup unavailable")),+ )+ agent = SimpleNamespace(ability_manager=manager)+ rail = ProgressiveToolRail(+ eager_tools=[],+ active_skill_provider=lambda: None,+ )+ rail.init(agent)+ ctx = _tool_call_ctx(agent, "gated_direct")++ await rail.before_tool_call(ctx)++ assert ctx.extra["_skip_tool"] is True+ assert str(ctx.inputs.tool_result).startswith("[TOOL_NOT_AVAILABLE]")+++async def test_removed_registered_gated_tool_is_rejected_on_replay() -> None:+ gated = _card("gated_direct", "research-skill")+ cards = [gated]+ agent = _agent(cards)+ rail = ProgressiveToolRail(+ eager_tools=[],+ active_skill_provider=lambda: "research-skill",+ )+ rail.init(agent)+ await rail._refresh_deferred_tool_cache()+ cards.clear()+ ctx = _tool_call_ctx(agent, "gated_direct")++ await rail.before_tool_call(ctx)++ assert ctx.extra["_skip_tool"] is True+ assert str(ctx.inputs.tool_result).startswith("[TOOL_NOT_AVAILABLE]")+++async def test_matching_active_skill_allows_registered_direct_call() -> None:+ gated = _card("gated_direct", "research-skill")+ agent = _agent([gated])+ rail = ProgressiveToolRail(+ eager_tools=[],+ active_skill_provider=lambda: "research-skill",+ )+ rail.init(agent)+ ctx = _tool_call_ctx(agent, "gated_direct")++ await rail.before_tool_call(ctx)++ assert "_skip_tool" not in ctx.extra+++async def test_adapter_session_activation_exposes_tool_only_in_that_session() -> None:+ pytest.importorskip("google.genai")+ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (+ JiuWenSwarmDeepAdapter,+ )++ first_session = "required-skill-first"+ second_session = "required-skill-second"+ active_state = SkillActiveStateRail(session_id=first_session)+ activation_call = SimpleNamespace(+ id="call-skill",+ name="skill_tool",+ arguments={"skill_name": "deepresearch"},+ )+ activation_ctx = SimpleNamespace(+ inputs=ToolCallInputs(+ tool_call=activation_call,+ tool_name="skill_tool",+ tool_args={"skill_name": "deepresearch"},+ tool_result="loaded",+ tool_msg=SimpleNamespace(metadata={"skill_name": "deepresearch"}),+ ),+ extra={},+ )++ def _adapter(session_id: str) -> JiuWenSwarmDeepAdapter:+ adapter = object.__new__(JiuWenSwarmDeepAdapter)+ adapter._parent_session_id = session_id+ adapter._is_session_scoped_adapter = True+ adapter._current_request_route = {}+ adapter._runtime_cron_tool_context = SimpleNamespace(session_id=None)+ adapter._resolve_runtime_language = lambda: "cn"+ adapter._tool_owner_id = lambda: f"owner-{session_id}"+ return adapter++ gated = _card("gated_direct", "deepresearch")+ try:+ first_adapter = _adapter(first_session)+ second_adapter = _adapter(second_session)+ first_rail = first_adapter._build_progressive_tool_rail(+ {"tool_lazy_load": {"enabled": True, "eager_tools": []}}+ )+ second_rail = second_adapter._build_progressive_tool_rail(+ {"tool_lazy_load": {"enabled": True, "eager_tools": []}}+ )+ assert first_rail is not None+ assert second_rail is not None+ first_agent = _agent([gated])+ second_agent = _agent([gated])+ first_rail.init(first_agent)+ second_rail.init(second_agent)++ before = _model_ctx(first_agent, [gated])+ await first_rail.before_model_call(before)+ assert before.inputs.tools == []++ await active_state.after_tool_call(activation_ctx)++ first_after = _model_ctx(first_agent, [gated])+ second_after = _model_ctx(second_agent, [gated])+ await first_rail.before_model_call(first_after)+ await second_rail.before_model_call(second_after)+ assert [tool.name for tool in first_after.inputs.tools] == ["gated_direct"]+ assert second_after.inputs.tools == []+ finally:+ clear_session_skill_state(first_session)+ clear_session_skill_state(second_session)