Skip to content

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(code): mount ProgressiveToolRail so first model call filters MCP schemas

NickFuryXXX38327bb83bb9
diff --git a/docs/en/Harness.md b/docs/en/Harness.md
index d2ea42929f..e5fb8ddcaf 100644
--- a/docs/en/Harness.md
+++ b/docs/en/Harness.md
@@ -109,7 +109,11 @@ For the full built-in tool index, see [3.12 Built-in Capabilities Index](#312-bu
`SysOperationRail` registers file, shell, and optional code tools. All system operations execute through a shared `SysOperation`, so local execution, sandboxing, working-directory restriction, and permission control are handled consistently.
-When the tool set is large, `ProgressiveToolRail` provides progressive tool disclosure: the model sees only meta tools and basic tools by default, then uses `tool_search` to search for tools and `load_tools` to load the tools needed for the current session. This reduces context noise and lowers the chance of misusing high-risk tools.
+When the tool set is large, `ProgressiveToolRail` follows `react.tool_lazy_load`: the model sees eager tools, discovers deferred tools through `tools_search`, and calls them through `invoke_tool`. This keeps full tool schemas out of the initial context. `enabled` controls the switch; `enable_for_models` controls the model whitelist.
+
+Code.normal/code.plan mount this rail when the session is first created and preserve the same policy on config reload. Code.team follows ordinary team behavior: neither creation nor reload adds this rail, and reload retires any previously mis-mounted instance, preserving direct access to collaboration and workspace tools. Single-agent code adds `lsp`, `coding_memory_read/write/edit`, `switch_mode`, `enter_plan_mode`, and `exit_plan_mode` to its eager list. Mode filtering, skill gates, and disabled-tool policy still control final visibility. Non-eager request-scoped MCP tools remain deferred and use the current request's allowlist when invoked. Subagent behavior remains separately controlled by `tool_lazy_load.subagents`. Ordinary agent/team behavior is unchanged; large MCP catalogs can still exceed a team member's context window.
+
+On first creation, the code adapter treats `None`, empty strings, and whitespace as normal; matching ignores case and surrounding whitespace. Parameterless `create_instance()` rebuilds after skill or plugin installation preserve the saved profile when sub-mode is `None`, passing it to the current rail assembly and future session adapters. Explicit normal or whitespace switches back to normal. Initial assembly passes the effective sub-mode to the lazy-loading builder; config reload falls back to the saved `_session_instance_sub_mode`, so team adds no such rail on full or partial reloads. Each code mount emits one adapter mount log, using `[JiuwenSwarmCodeAdapter] ProgressiveToolRail mounted` with the normalized sub-mode and progressive/skill-gate-only state.
Permission governance is composed of `PermissionEngine` and `PermissionInterruptRail`. `PermissionEngine` evaluates allow / ask / deny policies, while `PermissionInterruptRail` intercepts every tool call before execution and handles direct allow, direct deny, HITL confirmation, "allow once", and "always allow" flows. Shell commands go through AST analysis, and external path checks are combined with the current decision using the stricter result.
diff --git a/docs/zh/Harness.md b/docs/zh/Harness.md
index 2262fda523..1c4b123dc3 100644
--- a/docs/zh/Harness.md
+++ b/docs/zh/Harness.md
@@ -110,7 +110,11 @@ Tool & Execution 是 Harness 把模型意图落到真实环境的执行层。工
`SysOperationRail` 注册文件、Shell 和可选 code tool。所有系统操作通过共享 `SysOperation` 执行,从而统一接入本地执行、沙箱、工作目录限制和权限控制。
-当工具集很大时,`ProgressiveToolRail` 负责渐进式工具暴露:模型默认只看到元工具和基础工具,再通过 `tool_search` 搜索工具,通过 `load_tools` 加载当前 session 需要的工具,减少上下文噪声和误用高风险工具的概率。
+当工具集很大时,`ProgressiveToolRail` 按 `react.tool_lazy_load` 配置渐进式暴露工具:模型默认只看到 eager 工具,再通过 `tools_search` 搜索工具、`invoke_tool` 按需调用,避免全量工具 schema 占满上下文。`enabled` 和 `enable_for_models` 分别控制总开关与模型白名单。
+
+code.normal/code.plan 从会话首次创建起即挂载该 rail,热重载沿用同一策略;code.team 对齐普通 team,首建和热重载均不新增该 rail,历史误挂实例会在重载时注销,保留协作及工作区工具的直接可见性。LSP(`lsp`)、`coding_memory_read/write/edit`、`switch_mode`、`enter_plan_mode`、`exit_plan_mode` 在单 agent code 中补入 eager 名单;最终可见性仍受模式、技能门控及禁用工具策略约束。非 eager 的请求级 MCP 工具进入延迟池,按当前请求的 allowlist 调用;子代理继续由 `tool_lazy_load.subagents` 独立控制。普通 agent/team 的行为不变;team 成员携带大量 MCP schema 的上下文风险仍存在。
+
+code 适配器的首次创建将 `None`、空字符串及纯空白按 normal 处理,忽略大小写和首尾空格。技能或插件安装触发无参 `create_instance()` 重建时,`sub_mode=None` 保留已保存的 profile,并传给本次 rail 装配和后续 session 子适配器;显式传入 normal 或空白可切回 normal。首建将有效 sub_mode 显式传给懒加载 builder,配置热重载未传时使用 `_session_instance_sub_mode`;team 在完整及部分配置重载时均不会新增该 rail。每次 code 挂载只输出一条适配器挂载日志,使用 `[JiuwenSwarmCodeAdapter] ProgressiveToolRail mounted`,包含规范化 sub_mode 与 progressive/skill-gate-only 状态。
权限治理由 `PermissionEngine` 和 `PermissionInterruptRail` 组成。`PermissionEngine` 负责 allow / ask / deny 策略评估,`PermissionInterruptRail` 负责在工具调用前拦截所有工具,执行直接放行、直接拒绝、HITL 确认、“允许一次”和“总是允许”等流程。Shell 命令会经过 AST 分析,外部路径检查会与当前决策取更严格结果。
diff --git a/jiuwenswarm/server/docs/specs/S_03_runtime-agent-management.md b/jiuwenswarm/server/docs/specs/S_03_runtime-agent-management.md
index d9378cd690..b6bf78faf6 100644
--- a/jiuwenswarm/server/docs/specs/S_03_runtime-agent-management.md
+++ b/jiuwenswarm/server/docs/specs/S_03_runtime-agent-management.md
@@ -7,7 +7,7 @@
| 类型 | spec |
| 编号 / slug | S_03 / runtime-agent-management |
| 关联模块 | jiuwenswarm/server/runtime/{agent_manager.py, tenant_agent_pool.py, agent_warm_pool.py, agent_adapter/, a2ui/, debug_trace/, session/, skill/, workspace/, agent_config_service.py, prewarm.py, proactive_adapter.py, team_binding_store.py, team_entity_store.py, team_snapshot_refresh.py} |
-| 最近一次修订日期 | 2026-10-15 |
+| 最近一次修订日期 | 2026-10-22 |
| 关联 feature | 暂无 |
## 范围 / 边界
@@ -45,6 +45,7 @@
8. **skilldev 流水线 11 阶段顺序固定**:init → plan → generate → desc_optimize → test_design → test_run → evaluate → improve → package → validate。pipeline.py 是编排真源,不要在 service.py 里硬改顺序。
9. **AgentManager 单进程单默认实例**:非 enterprise 进程内至多一个裸 AgentManager(由 AgentWebSocketServer 构造),不要在其他模块私自 AgentManager()。
10. **企业版冷加载 best-effort**:每个 `reload_*_from_gateway_db` 调用失败只记 warning,不阻断 AgentServer 启动——用户配置 PVC 缺表或缺字段不应让进程起不来。
+11. **code.normal/plan 首建与重载共享工具懒加载策略**:首次创建的 None/空白 sub_mode 默认 normal;后续 `create_instance(sub_mode=None)` 沿用保存的 profile,并把有效 sub_mode 传入 rail 装配及后续 session 子 adapter,显式 normal/空白可切回 normal。首建按入参规范化后的 sub_mode 排队并显式传给 builder,配置热重载未传该参数时使用 `_session_instance_sub_mode`;仅 normal/plan 装配 `ProgressiveToolRail`。code.team 对齐普通 team,首建和完整/部分重载均不新增该 rail;历史误挂实例在 configure 成功后注销。单 agent 复用 `react.tool_lazy_load` 的开关、模型白名单及请求级 MCP allowlist,配置缺省重载保持既有 rail;编码记忆、LSP、模式切换与计划审批工具保持 eager,最终可见性仍受模式、技能门控及 `disabled_tools` 约束。一次 code 挂载仅记录一条带 `[JiuwenSwarmCodeAdapter]` 和规范化 sub_mode 的适配器日志。普通 agent/team 的装配、日志及重载策略不因此改变。
## 接口契约
@@ -165,6 +166,7 @@ UsageReconciler: start_usage_reconciler()(启动周期回收)
## 修改检查单
- **新增 agent_adapter 接口** → 确认归哪一路(deep/code/flash)→ AgentWebSocketServer._resolve_adapter 里加分支 → 默认路径 fallback 里跑双接口一致性测试。
+- **改 code 工具装配或懒加载策略** → 验证首次模型调用已过滤大量 MCP schema、编码工具仍可见、deferred 工具可搜索调用;确认关闭开关、模型白名单、禁用工具及热重载替换行为。
- **改 AgentWarmPool WarmKey 结构** → 同步 sync() 里的重建条件 → 排除 acp/a2a 分支不被意外打破 → 跑预热池一致性测试。
- **改 prewarm 阶段** → 确认阶段 3 仍是独立 fire-and-forget,不被阶段 1/2 兜底 await 阻塞 → mock_model 默认 True 不消耗 token。
- **增删 skilldev 阶段** → pipeline.py 编排顺序同步 → service.py 的 stage 实例化清单同步 → 阶段 base.py 接口签名不变。
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
index 41e183fc0d..734318f3b7 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
@@ -58,6 +58,7 @@ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import (
_deep_agent_kv_cache_affinity_config,
_optional_enable_subagent_runtime,
_resolve_instance_config_base,
+ build_progressive_tool_rail_from_config,
parse_int,
)
from jiuwenswarm.agents.harness.code.prompt.code_prompt_builder import (
@@ -74,6 +75,7 @@ from jiuwenswarm.agents.harness.common.rails import (
StructuredAskUserRail,
)
from jiuwenswarm.agents.harness.common.memory.config import is_memory_enabled
+from jiuwenswarm.agents.harness.common.rails.progressive_tool_rail import ProgressiveToolRail
from jiuwenswarm.agents.harness.common.memory.external_memory_config import (
get_office_ace_user_profile_config,
)
@@ -283,6 +285,24 @@ genuinely blocked.
</system-reminder>"""
+# Code prompts refer to these tools directly. Keep their schemas available
+# without requiring discovery, including after the shared config reload path.
+_CODE_EAGER_TOOLS = (
+ "lsp",
+ "coding_memory_read",
+ "coding_memory_write",
+ "coding_memory_edit",
+ "switch_mode",
+ "enter_plan_mode",
+ "exit_plan_mode",
+)
+
+
+def _normalize_code_sub_mode(sub_mode: str | None) -> str:
+ """Keep creation and reload profile checks identical, including defaults."""
+ return str(sub_mode or "normal").strip().lower() or "normal"
+
+
# 名字 → 构建方法映射(rail/tool 名字与类方法名对照)
_RAIL_BUILD_NAMES: dict[str, str] = {
"SysOperationRail": "_build_filesystem_rail",
@@ -539,7 +559,11 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
# coding_memory/.
self._session_instance_config = dict(config or {}) if isinstance(config, dict) else None
self._session_instance_mode = mode
- self._session_instance_sub_mode = sub_mode
+ # Skill/plugin installs rebuild through the facade with sub_mode=None.
+ # Preserve the profile and pass it to this build as well as new sessions.
+ if sub_mode is not None:
+ self._session_instance_sub_mode = sub_mode
+ sub_mode = self._session_instance_sub_mode
await self.set_checkpoint()
@@ -748,7 +772,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
_RailBuildInfo("_code_plan_approval_rail", self._build_plan_approval_rail),
]
- normalized_sub_mode = str(sub_mode or "normal").strip().lower() or "normal"
+ normalized_sub_mode = _normalize_code_sub_mode(sub_mode)
# The CodeAdapter may be rebuilt through JiuWenSwarm.create_instance(),
# whose compatibility default is mode="agent" even when this adapter
# already owns a Code session. Sub-mode is the reliable profile key:
@@ -813,6 +837,18 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
rail_name,
)
+ # Filter single-agent MCP schemas from the first turn. Team members
+ # need their collaboration/workspace tools directly visible; their
+ # tool policy belongs to the team assembly path.
+ if normalized_sub_mode in {"normal", "plan"}:
+ rail_infos.append(
+ _RailBuildInfo(
+ "_progressive_tool_rail",
+ self._build_progressive_tool_rail,
+ {"config": config, "sub_mode": normalized_sub_mode},
+ )
+ )
+
# Keep the unified react.disabled_tools policy consistent with agent
# mode. Its low priority makes it run after fixed and dynamic rails
# have registered their tools.
@@ -826,6 +862,35 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
return self._instantiate_rails(rail_infos, config_base)
+ def _build_progressive_tool_rail(
+ self, config: dict[str, Any], *, sub_mode: str | None = None
+ ) -> ProgressiveToolRail | None:
+ """Share lazy-loading policy while preserving code's direct tools."""
+ # Creation passes its profile explicitly; reload uses the saved one.
+ # Returning None also retires a rail mounted by an older version.
+ normalized_sub_mode = _normalize_code_sub_mode(
+ sub_mode if sub_mode is not None else self._session_instance_sub_mode
+ )
+ if normalized_sub_mode not in {"normal", "plan"}:
+ return None
+ # Reuse the common policy factory; emit only the code adapter mount log.
+ rail = build_progressive_tool_rail_from_config(
+ config,
+ language=self._resolve_runtime_language(),
+ 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:
+ rail.eager_tools = list(dict.fromkeys([*rail.eager_tools, *_CODE_EAGER_TOOLS]))
+ logger.info(
+ "[JiuwenSwarmCodeAdapter] ProgressiveToolRail mounted mode=%s sub_mode=%s",
+ "progressive" if rail.enabled else "skill-gate-only",
+ normalized_sub_mode,
+ )
+ return rail
+
# ─── Code 专属 Rail 构建 ────────────────
def _build_filesystem_rail(self) -> SysOperationRail | None:
@@ -1359,6 +1424,13 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
CodeAgentRail 和 PlanApprovalInterruptRail 不在其中。覆盖此方法确保 config reload
时这些 rail 被正确重新初始化。
"""
+ if (
+ _normalize_code_sub_mode(self._session_instance_sub_mode) not in {"normal", "plan"}
+ and "tool_lazy_load" not in config
+ ):
+ # Partial reloads normally preserve this rail. Code team profiles
+ # must still retire historical mis-mounts, without mutating config.
+ config = {**config, "tool_lazy_load": {}}
rails_list, rails_to_unregister = super()._get_current_agent_rails(
config, config_base
)
@@ -1708,6 +1780,8 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
force_english_runtime_prompt: bool = True,
) -> None:
"""Apply the code runtime profile to a team member DeepAgent."""
+ self._session_instance_mode = "code"
+ self._session_instance_sub_mode = "team"
if skill_manager is not None and hasattr(self, "set_skill_manager"):
self.set_skill_manager(skill_manager)
@@ -1794,7 +1868,6 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
setattr(agent, "_jiuwenswarm_adapter_mode", "code")
setattr(agent, "_jiuwenswarm_code_project_dir", self._project_dir or self._workspace_dir)
setattr(agent, "_jiuwenswarm_project_dir", self._project_dir or self._workspace_dir)
- setattr(agent, "_jiuwenswarm_code_team_member", True)
logger.info(
"[JiuwenSwarmCodeAdapter] configured team member as code profile: "
diff --git a/tests/unit_tests/agentserver/test_code_adapter_progressive_tools.py b/tests/unit_tests/agentserver/test_code_adapter_progressive_tools.py
new file mode 100644
index 0000000000..9d595a3ce0
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_code_adapter_progressive_tools.py
@@ -0,0 +1,421 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.
+
+"""Code sessions must filter large tool catalogs from their first model call."""
+
+import asyncio
+import logging
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from openjiuwen.core.foundation.tool import ToolCard
+
+from jiuwenswarm.agents.harness.common.rails.progressive_tool_rail import ProgressiveToolRail
+from jiuwenswarm.agents.harness.common.tools.invoke_tool_tool import InvokeToolInput
+from jiuwenswarm.agents.harness.common.tools.tools_search_tool import ToolsSearchInput
+from jiuwenswarm.server.runtime.agent_adapter.interface_code import JiuwenSwarmCodeAdapter
+
+
+CODE_TOOLS = [
+ "lsp",
+ "coding_memory_read",
+ "coding_memory_write",
+ "coding_memory_edit",
+ "switch_mode",
+ "enter_plan_mode",
+ "exit_plan_mode",
+]
+
+SINGLE_SUB_MODES = [None, "", " \t ", "normal", "plan"]
+TEAM_SUB_MODES = ["team", "TEAM", " team "]
+
+
+def _tool_policy_rails(monkeypatch, config, sub_mode, adapter=None):
+ if adapter is None:
+ adapter = JiuwenSwarmCodeAdapter()
+ adapter._session_instance_sub_mode = sub_mode
+ instantiate = adapter._instantiate_rails
+
+ def build_tool_policy(infos, base):
+ # Keep the production rail plan and instantiation; unrelated rails may
+ # start LSP/model services and are outside this regression's boundary.
+ return instantiate(
+ [info for info in infos if info.attr_name == "_progressive_tool_rail"],
+ base,
+ )
+
+ monkeypatch.setattr(adapter, "_instantiate_rails", build_tool_policy)
+ monkeypatch.setattr(adapter, "_load_extra_rails_from_env", lambda: [])
+ monkeypatch.setattr(adapter, "_bind_checkpointer_to_rails", lambda: None)
+ rails = adapter._build_agent_rails(config, {}, sub_mode=sub_mode)
+ return adapter, rails
+
+
+def _profile_adapter(monkeypatch):
+ adapter = JiuwenSwarmCodeAdapter()
+ monkeypatch.setattr(adapter, "set_checkpoint", AsyncMock())
+ monkeypatch.setattr(adapter, "_refresh_multimodal_configs", MagicMock())
+ monkeypatch.setattr(adapter, "_skip_own_instance_build", lambda: True)
+ return adapter
+
+
[email protected]("sub_mode", SINGLE_SUB_MODES + TEAM_SUB_MODES)
+async def test_facade_parameterless_rebuild_preserves_profile_and_child_create_args(monkeypatch, sub_mode):
+ from jiuwenswarm.server.runtime.agent_adapter.interface import JiuWenSwarm
+
+ adapter = _profile_adapter(monkeypatch)
+ base = {"react": {"tool_lazy_load": {"enabled": True, "eager_tools": ["read_file"]}}}
+ await adapter.create_instance(sub_mode=sub_mode, config_base=base)
+ facade = object.__new__(JiuWenSwarm)
+ facade._adapter_mode = "code"
+ facade._sdk_name = "test"
+ facade._session_manager = SimpleNamespace(has_active_tasks=lambda: False)
+ monkeypatch.setattr(facade, "_ensure_adapter", lambda **kwargs: adapter)
+ monkeypatch.setattr(adapter, "try_start_dreaming", AsyncMock())
+ # Covers the real no-argument call used by skill/plugin installation.
+ for _ in range(2):
+ await facade.create_instance()
+ await asyncio.sleep(0)
+ assert adapter._session_instance_sub_mode == sub_mode
+ _, rails = _tool_policy_rails(monkeypatch, base["react"], sub_mode, adapter)
+ assert sum(isinstance(rail, ProgressiveToolRail) for rail in rails) == int(sub_mode in SINGLE_SUB_MODES)
+
+ child = SimpleNamespace(create_instance=AsyncMock(side_effect=RuntimeError("captured child create")))
+ monkeypatch.setattr(adapter, "_new_session_scoped_adapter", lambda *args, **kwargs: child)
+ with pytest.raises(RuntimeError, match="captured child create"):
+ await adapter._get_or_create_session_adapter("after-rebuild")
+ assert child.create_instance.call_args.kwargs["sub_mode"] == sub_mode
+
+
[email protected]("sub_mode", ["normal", "plan", "team"])
+async def test_rebuild_passes_retained_profile_to_initial_rail_plan(monkeypatch, sub_mode):
+ adapter = _profile_adapter(monkeypatch)
+ await adapter.create_instance(sub_mode=sub_mode, config_base={"react": {}})
+ monkeypatch.setattr(adapter, "_skip_own_instance_build", lambda: False)
+ monkeypatch.setattr(adapter, "_create_model", lambda *args: object())
+ monkeypatch.setattr(adapter, "_get_tool_cards", AsyncMock(return_value=[]))
+ assembly = MagicMock(side_effect=RuntimeError("captured rail assembly"))
+ monkeypatch.setattr(adapter, "_build_agent_rails", assembly)
+ with pytest.raises(RuntimeError, match="captured rail assembly"):
+ await adapter.create_instance(config_base={"react": {}})
+ assert adapter._session_instance_sub_mode == sub_mode
+ assert assembly.call_args.kwargs["sub_mode"] == sub_mode
+
+
[email protected]("sub_mode", ["normal", "plan", "", " \t "])
+async def test_explicit_profile_overrides_saved_team_on_rebuild(monkeypatch, sub_mode):
+ adapter = _profile_adapter(monkeypatch)
+ await adapter.create_instance(sub_mode="team", config_base={"react": {}})
+ await adapter.create_instance(sub_mode=sub_mode, config_base={"react": {}})
+ assert adapter._session_instance_sub_mode == sub_mode
+ _, rails = _tool_policy_rails(monkeypatch, {"tool_lazy_load": {"enabled": True}}, sub_mode, adapter)
+ assert sum(isinstance(rail, ProgressiveToolRail) for rail in rails) == 1
+
+
[email protected]("requested_mode", ["normal", "plan"])
+def test_initial_rail_plan_uses_explicit_profile_when_saved_profile_differs(monkeypatch, requested_mode):
+ adapter = JiuwenSwarmCodeAdapter()
+ adapter._session_instance_sub_mode = "team"
+ _, rails = _tool_policy_rails(
+ monkeypatch, {"tool_lazy_load": {"enabled": True}}, requested_mode, adapter,
+ )
+ assert sum(isinstance(rail, ProgressiveToolRail) for rail in rails) == 1
+ assert adapter._session_instance_sub_mode == "team"
+
+
[email protected]("sub_mode", SINGLE_SUB_MODES + TEAM_SUB_MODES)
[email protected]("enabled", [False, True])
+async def test_create_instance_records_profile_and_builds_matching_policy(
+ monkeypatch, caplog, sub_mode, enabled,
+):
+ config = {"tool_lazy_load": {"enabled": enabled, "enable_for_models": ["glm"]}}
+ adapter = JiuwenSwarmCodeAdapter()
+ monkeypatch.setattr(adapter, "set_checkpoint", AsyncMock())
+ monkeypatch.setattr(adapter, "_refresh_multimodal_configs", MagicMock())
+ # Exercise the real create-instance state setup without starting services.
+ monkeypatch.setattr(adapter, "_skip_own_instance_build", lambda: True)
+ await adapter.create_instance(mode="code", sub_mode=sub_mode, config_base={"react": config})
+ assert adapter._session_instance_sub_mode == sub_mode
+ assert adapter._instance is None
+
+ with caplog.at_level(logging.INFO):
+ adapter, rails = _tool_policy_rails(monkeypatch, config, sub_mode, adapter)
+ single = sub_mode in SINGLE_SUB_MODES
+ assert sum(isinstance(rail, ProgressiveToolRail) for rail in rails) == int(single)
+ messages = [
+ record.getMessage()
+ for record in caplog.records
+ if "ProgressiveToolRail mounted" in record.getMessage()
+ ]
+ if single:
+ assert adapter._progressive_tool_rail.enabled is enabled
+ assert len(messages) == 1
+ assert "[JiuwenSwarmCodeAdapter]" in messages[0]
+ assert f"mode={'progressive' if enabled else 'skill-gate-only'}" in messages[0]
+ assert f"sub_mode={'plan' if sub_mode == 'plan' else 'normal'}" in messages[0]
+ else:
+ assert adapter._progressive_tool_rail is None
+ assert messages == []
+
+
+def _initial_rail(monkeypatch, config, sub_mode="normal"):
+ adapter, rails = _tool_policy_rails(monkeypatch, config, sub_mode)
+ rail = adapter._progressive_tool_rail
+ assert rail is not None
+ assert rails.count(rail) == 1
+ return adapter, rail
+
+
+def _card(name, description="tool description"):
+ return ToolCard(id=f"id-{name}", name=name, description=description, input_params={})
+
+
+def _context(rail, cards, model_name="glm-5"):
+ agent = SimpleNamespace(
+ model_name=model_name,
+ ability_manager=SimpleNamespace(list=lambda: list(cards)),
+ system_prompt_builder=None,
+ )
+ rail.init(agent)
+ return SimpleNamespace(agent=agent, inputs=SimpleNamespace(tools=list(cards)))
+
+
[email protected]("sub_mode", ["team", "TEAM", " team "])
+async def test_team_profile_keeps_collaboration_and_workspace_tools_direct(monkeypatch, sub_mode):
+ config = {
+ "tool_lazy_load": {
+ "enabled": True, "enable_for_models": ["glm"], "eager_tools": ["read_file"]
+ }
+ }
+ adapter, rails = _tool_policy_rails(monkeypatch, config, sub_mode)
+ cards = [_card(name) for name in (
+ "send_message", "create_task", "read_file", "web_fetch_webpage",
+ "user_todos", "skill_retrieval",
+ )]
+ agent = SimpleNamespace(
+ model_name="glm-5",
+ ability_manager=SimpleNamespace(list=lambda: list(cards)),
+ system_prompt_builder=None,
+ )
+ ctx = SimpleNamespace(agent=agent, inputs=SimpleNamespace(tools=list(cards)))
+ for rail in rails:
+ if isinstance(rail, ProgressiveToolRail):
+ rail.init(agent)
+ await rail.before_model_call(ctx)
+
+ assert ctx.inputs.tools == cards
+ assert adapter._progressive_tool_rail is None
+
+
[email protected]("enabled", [None, False, True])
[email protected]("has_stale_rail", [False, True])
[email protected]("sub_mode", TEAM_SUB_MODES)
+def test_team_reload_plan_does_not_mount_progressive_rail(
+ monkeypatch, enabled, has_stale_rail, sub_mode,
+):
+ config = (
+ {"tool_lazy_load": {"enabled": enabled, "enable_for_models": ["glm"]}}
+ if enabled is not None else {}
+ )
+ adapter = JiuwenSwarmCodeAdapter()
+ adapter._session_instance_sub_mode = sub_mode
+ adapter._instance = SimpleNamespace()
+ adapter._code_agent_rail = None
+ adapter._code_plan_approval_rail = None
+ old = ProgressiveToolRail(eager_tools=["read_file"]) if has_stale_rail else None
+ adapter._progressive_tool_rail = old
+ for builder in (
+ "_build_skill_rail", "_build_skill_credential_injection_rail",
+ "_build_skill_active_state_rail", "_update_permission_rail",
+ ):
+ monkeypatch.setattr(adapter, builder, MagicMock(return_value=None))
+
+ rails, retired = adapter._get_current_agent_rails(config, {"react": config})
+
+ assert not any(isinstance(rail, ProgressiveToolRail) for rail in rails)
+ assert retired == ([old] if old is not None else [])
+ if enabled is None:
+ assert "tool_lazy_load" not in config
+
+
[email protected]("has_stale_rail", [False, True])
[email protected]("enabled", [None, False, True])
[email protected]("sub_mode", SINGLE_SUB_MODES + TEAM_SUB_MODES)
+async def test_config_reload_matches_profile_and_cleans_historical_team_rail(
+ monkeypatch, has_stale_rail, enabled, sub_mode,
+):
+ config = (
+ {} if enabled is None else
+ {"tool_lazy_load": {"enabled": enabled, "enable_for_models": ["glm"],
+ "eager_tools": ["read_file"]}}
+ )
+ adapter = JiuwenSwarmCodeAdapter()
+ adapter._session_instance_sub_mode = sub_mode
+ adapter._code_agent_rail = None
+ adapter._code_plan_approval_rail = None
+ instance = SimpleNamespace(
+ configure=MagicMock(), ensure_initialized=AsyncMock(), unregister_rail=AsyncMock(),
+ )
+ adapter._instance = instance
+ old = ProgressiveToolRail(eager_tools=["read_file"]) if has_stale_rail else None
+ adapter._progressive_tool_rail = old
+
+ async def apply_snapshot(*args):
+ adapter._config_cache = config.copy()
+ adapter._config_base_cache = {"react": config}
+ return adapter._config_base_cache
+
+ monkeypatch.setattr(adapter, "_apply_reload_config_snapshot", apply_snapshot)
+ monkeypatch.setattr(adapter, "_bind_request_env_overlay", lambda *args: (None, None, None))
+ monkeypatch.setattr(adapter, "_create_model", lambda *args: object())
+ monkeypatch.setattr(adapter, "_make_deep_agent_config", lambda **kwargs: SimpleNamespace(**kwargs))
+ monkeypatch.setattr(adapter, "_omit_unchanged_reload_fields", lambda *args: ({}, {}))
+ for name in (
+ "_build_skill_rail", "_build_skill_credential_injection_rail",
+ "_build_skill_active_state_rail", "_update_permission_rail",
+ "_sync_multimodal_tools_for_runtime", "_sync_paid_search_tool_for_runtime",
+ "_sync_symphony_tools_for_runtime", "_sync_skill_retrieval_tools_for_runtime",
+ "_restore_omitted_reload_fields", "_commit_reload_fingerprints",
+ "_sync_active_evolution_review_agent_after_reload", "_rebind_late_read_rails_to_local",
+ ):
+ monkeypatch.setattr(adapter, name, MagicMock(return_value=None))
+ for name in (
+ "load_user_rails", "_sync_skill_retrieval_prompt_rail_for_runtime",
+ "_reconcile_evolution_rails", "_sync_mcp_servers_for_runtime",
+ "_fan_out_reload_to_session_adapters", "_handle_memory_rail_by_config",
+ "_handle_external_memory_rail_by_config", "_handle_office_ace_user_profile_rail_by_config",
+ ):
+ monkeypatch.setattr(adapter, name, AsyncMock())
+
+ single = sub_mode in SINGLE_SUB_MODES
+ # A second reload must preserve the profile, including after stale cleanup.
+ for _ in range(2):
+ result = await adapter.reload_agent_config({"react": config})
+ assert result.applied is True
+ rails = instance.configure.call_args.args[0].rails
+ policies = [rail for rail in rails if isinstance(rail, ProgressiveToolRail)]
+ if single:
+ if enabled is None:
+ assert adapter._progressive_tool_rail is old
+ assert policies == []
+ assert config == {} # Partial reload input remains untouched.
+ else:
+ assert policies == [adapter._progressive_tool_rail]
+ assert adapter._progressive_tool_rail is not old
+ assert adapter._progressive_tool_rail.enabled is enabled
+ assert set(CODE_TOOLS) <= set(adapter._progressive_tool_rail.eager_tools)
+ else:
+ assert adapter._progressive_tool_rail is None
+ assert policies == []
+ if not single:
+ cards = [_card(name) for name in ("read_file", "send_message", "web_fetch_webpage")]
+ ctx = SimpleNamespace(inputs=SimpleNamespace(tools=list(cards)))
+ for rail in rails:
+ await rail.before_model_call(ctx)
+ assert ctx.inputs.tools == cards
+ assert adapter._session_instance_sub_mode == sub_mode
+ if old is not None and not single:
+ instance.unregister_rail.assert_awaited_once_with(old)
+ else:
+ instance.unregister_rail.assert_not_awaited()
+
+
[email protected]("sub_mode", ["normal", "plan"])
+async def test_first_call_filters_large_mcp_catalog_and_preserves_coding_tools(monkeypatch, sub_mode):
+ config = {
+ "tool_lazy_load": {
+ "enabled": True, "enable_for_models": ["glm"], "eager_tools": ["read_file"]
+ }
+ }
+ adapter, rail = _initial_rail(monkeypatch, config, sub_mode)
+ eager = [_card(name) for name in ["tools_search", "invoke_tool", "read_file", *CODE_TOOLS]]
+ deferred = [_card(f"wps_{i}", "large schema description " * 200) for i in range(666)]
+ ctx = _context(rail, eager + deferred)
+ adapter._sync_office_claw_allowlist_to_progressive_rail(
+ [card.id for card in deferred],
+ delivery_thread_id="thread-code",
+ invocation_id="turn-code",
+ )
+
+ await rail.before_model_call(ctx)
+
+ assert {tool.name for tool in ctx.inputs.tools} == {tool.name for tool in eager}
+ assert len(rail._cached_deferred_tool_infos) == 666
+ assert rail._office_claw_active_tool_ids == frozenset(card.id for card in deferred)
+ assert sum(len(t.description) for t in ctx.inputs.tools) < 1000
+ target = SimpleNamespace(card=deferred[-1], invoke=AsyncMock(return_value="wps-result"))
+ monkeypatch.setattr(
+ rail, "_lookup_tool_instance",
+ lambda tool_id: target if tool_id == target.card.id else None,
+ )
+ result = await rail._search_tools(None, ToolsSearchInput(tool_name="wps_665"))
+ assert result["success"] is True
+ result = await rail._invoke_target_tool(
+ None, InvokeToolInput(tool_name="wps_665", arguments={})
+ )
+ assert result["success"] is True
+ target.invoke.assert_awaited_once()
+
+
[email protected]("enabled,model_name", [(False, "glm-5"), (True, "other-model")])
+async def test_config_switch_and_model_whitelist_remain_effective(monkeypatch, enabled, model_name):
+ _, rail = _initial_rail(monkeypatch, {
+ "tool_lazy_load": {"enabled": enabled, "enable_for_models": ["glm"], "eager_tools": []}
+ })
+ cards = [_card("read_file"), _card("wps_deferred")]
+ ctx = _context(rail, cards, model_name)
+ await rail.before_model_call(ctx)
+ assert ctx.inputs.tools == cards
+
+
+def test_reload_replaces_rail_once_and_keeps_code_eager_policy(monkeypatch):
+ config = {"tool_lazy_load": {"enabled": True, "eager_tools": ["read_file"]}}
+ adapter, old = _initial_rail(monkeypatch, config)
+ adapter._code_agent_rail = None
+ adapter._code_plan_approval_rail = None
+ adapter._active_office_claw_mcp = SimpleNamespace(
+ tool_ids=("id-wps_1",), invocation_id="turn-code",
+ tool_instances=[SimpleNamespace(_params={"env": {"OFFICE_CLAW_THREAD_ID": "thread-code"}})],
+ )
+ for builder in (
+ "_build_skill_rail", "_build_skill_credential_injection_rail",
+ "_build_skill_active_state_rail",
+ ):
+ monkeypatch.setattr(adapter, builder, lambda *args, **kwargs: None)
+ monkeypatch.setattr(adapter, "_update_permission_rail", lambda *args: None)
+ rails, retired = adapter._get_current_agent_rails(config, {"react": config})
+ replacement = adapter._progressive_tool_rail
+ assert replacement is not old
+ assert rails.count(replacement) == 1
+ assert old not in rails
+ assert retired == [] # configure replaces the old rail of the same type.
+ assert set(CODE_TOOLS) <= set(replacement.eager_tools)
+ assert replacement._office_claw_active_tool_ids == frozenset({"id-wps_1"})
+ assert replacement._office_claw_delivery_thread_id == "thread-code"
+ assert replacement._office_claw_invocation_id == "turn-code"
+ assert config["tool_lazy_load"]["eager_tools"] == ["read_file"]
+
+
+async def test_code_eager_additions_do_not_bypass_disabled_tools(monkeypatch):
+ _, rail = _initial_rail(monkeypatch, {
+ "tool_lazy_load": {"enabled": True, "eager_tools": []},
+ "disabled_tools": ["coding_memory_write", "wps_disabled"],
+ })
+ cards = [_card("coding_memory_read"), _card("coding_memory_write"), _card("wps_disabled")]
+ ctx = _context(rail, cards)
+ await rail.before_model_call(ctx)
+ assert [tool.name for tool in ctx.inputs.tools] == ["coding_memory_read"]
+ assert rail._cached_deferred_tool_infos == []
+ result = await rail._invoke_target_tool(
+ None, InvokeToolInput(tool_name="wps_disabled", arguments={})
+ )
+ assert result["success"] is False