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(symphony): 优化集群模式下symphony技能编排工具调用
lin-xiaoyu3a49d495d9be
diff --git a/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py b/jiuwenswarm/agents/harness/common/prompt/prompt_builder.pyindex 63a7d63f5e..016357ab98 100644--- a/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py+++ b/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py@@ -2,7 +2,7 @@import sysfrom enum import IntEnumfrom pathlib import Path-from typing import Any, Optional+from typing import Optionalfrom openjiuwen.harness.prompts import SystemPromptBuilder, PromptSection, resolve_languagefrom jiuwenswarm.agents.harness.common.prompt.shell_environment import build_shell_environment_prompt@@ -21,45 +21,6 @@ def _get_config_dir() -> "Path":return get_user_workspace_dir() / "config"-def _symphony_routing_prompt(config_base: dict[str, Any] | None = None) -> str:- try:- from jiuwenswarm.symphony.config import load_symphony_config-- config = (- load_symphony_config()- if config_base is None- else load_symphony_config(config_base)- )- if not config.enabled:- return ""- except Exception:- return ""- return """-## Symphony Routing--When the user says to use skill(s) or 技能, or when you judge that skill-capabilities, skill chaining, skill ordering, or a specialized toolchain could-help complete the task, you MUST call `symphony_compose_score` with the original-user task as `query` before answering.-When installed-skill retrieval is available and can narrow the search space,-use `skill_branch_peek` / `skill_branch_explore` to shortlist candidate skills-first, then pass the selected `worker_id` values as-`symphony_compose_score.candidate_skill_ids`. Do not inspect skill folders-manually or choose the execution chain yourself; Symphony owns ordering and-graph composition. After it returns, present its returned `content` directly to-the user. If Symphony reports missing inputs, ask for those inputs.--If Symphony reports no suitable candidates, a missing capability, or caveats-that point to a skill gap, use `search_skill` to discover external skills. When-installing a discovered skill is appropriate, call `install_skill`; after a-successful install, call `symphony_refresh_score` and then call-`symphony_compose_score` again with the original user task.--For clearly ordinary tasks that do not benefit from skill capabilities, continue-normally without Symphony.-"""--class PromptPriority(IntEnum):"""Named prompt section priorities for general agent builder."""@@ -172,7 +133,6 @@ After completing a system task, notify the user via a reply.def _identity_prompt(language: str,- config_base: dict[str, Any] | None = None,) -> PromptSection:config_dir = _get_config_dir()workspace_dir = get_agent_workspace_dir()@@ -181,7 +141,6 @@ def _identity_prompt(todo_dir = get_deepagent_todo_dir()os_type = sys.platformshell_env_prompt = build_shell_environment_prompt(language, os_type)- symphony_routing_prompt = _symphony_routing_prompt(config_base)if language == "cn":content = f"""你是一个私人智能体,由 JiuwenSwarm 创建。像一个有温度的人类助手一样与用户互动。@@ -199,7 +158,6 @@ def _identity_prompt(| `{memory_dir}` | 持久化记忆 | 将其视为你记忆的一部分,随时查阅 || `{skills_dir}` | 技能库 | 可随时翻阅、调用,不可修改 || `{todo_dir}` | 待办事项 | 记录用户请求的任务,每次请求后会更新 |-{symphony_routing_prompt}## 配置信息@@ -277,7 +235,6 @@ Everything starts from the `.jiuwenswarm` directory.| `{memory_dir}` | Persistent memory | Treat it as part of your memory; consult it anytime || `{skills_dir}` | Skill library | Read and invoke freely; do not modify || `{todo_dir}` | Todo list | Records tasks from user requests; updated after each request |-{symphony_routing_prompt}## Configuration@@ -350,7 +307,6 @@ When the `send_file_to_user` tool is available in your tool list, you **must** pdef build_agent_identity_prompt(language: str,- config_base: dict[str, Any] | None = None,) -> str:"""Build the system prompt for the general (non-code) agent.@@ -360,7 +316,7 @@ def build_agent_identity_prompt(resolved_language = resolve_language(language)builder = SystemPromptBuilder(language=resolved_language)- builder.add_section(_identity_prompt(resolved_language, config_base))+ builder.add_section(_identity_prompt(resolved_language))return builder.build()diff --git a/jiuwenswarm/agents/harness/common/rails/__init__.py b/jiuwenswarm/agents/harness/common/rails/__init__.pyindex b58dac113b..45ad5a7e21 100644--- a/jiuwenswarm/agents/harness/common/rails/__init__.py+++ b/jiuwenswarm/agents/harness/common/rails/__init__.py@@ -10,6 +10,9 @@ from jiuwenswarm.agents.harness.common.rails.avatar_rail import AvatarPromptRailfrom jiuwenswarm.agents.harness.common.rails.project_memory_rail import ProjectMemoryRailfrom jiuwenswarm.agents.harness.common.rails.response_prompt_rail import ResponsePromptRailfrom jiuwenswarm.agents.harness.common.rails.runtime_prompt_rail import RuntimePromptRail+from jiuwenswarm.agents.harness.common.rails.symphony_orchestration_prompt_rail import (+ SymphonyOrchestrationPromptRail,+)from jiuwenswarm.agents.harness.team.rails.team_member_skill_toolkit_rail import (MemberSkillToolkitRail,)@@ -25,6 +28,7 @@ __all__ = ["ProjectMemoryRail","ResponsePromptRail","RuntimePromptRail",+ "SymphonyOrchestrationPromptRail","MemberSkillToolkitRail","StructuredAskUserRail",]diff --git a/jiuwenswarm/agents/harness/common/rails/symphony_orchestration_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/symphony_orchestration_prompt_rail.pynew file mode 100644index 0000000000..9a13a12a52--- /dev/null+++ b/jiuwenswarm/agents/harness/common/rails/symphony_orchestration_prompt_rail.py@@ -0,0 +1,141 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Prompt rail for Symphony orchestration guidance."""++from __future__ import annotations++from typing import Any, Callable++from openjiuwen.core.single_agent.rail.base import AgentCallbackContext+from openjiuwen.harness.prompts import PromptSection+from openjiuwen.harness.rails.base import DeepAgentRail++_ConfigBaseProvider = (+ dict[str, Any] | Callable[[], dict[str, Any] | None] | None+)+++def _render_symphony_orchestration_prompt(+ config_base: dict[str, Any] | None = None,+) -> str:+ try:+ from jiuwenswarm.symphony.config import load_symphony_config++ config = (+ load_symphony_config()+ if config_base is None+ else load_symphony_config(config_base)+ )+ if not config.enabled:+ return ""+ except Exception:+ return ""+ return """+## Symphony Orchestration++When the user says to use skill(s) or 技能, or when you judge that skill+capabilities, skill chaining, skill ordering, or a specialized toolchain could+help complete the task, you MUST call `symphony_compose_score` with the original+user task as `query` before answering.+When installed-skill retrieval is available and can narrow the search space,+use `skill_branch_peek` / `skill_branch_explore` to shortlist candidate skills+first, then pass the selected `worker_id` values as+`symphony_compose_score.candidate_skill_ids`. Do not inspect skill folders+manually or choose the execution chain yourself; Symphony owns ordering and+graph composition. After it returns, present its returned `content` directly to+the user. If Symphony reports missing inputs, ask for those inputs.++If Symphony reports no suitable candidates, a missing capability, or caveats+that point to a skill gap, use `search_skill` to discover external skills. When+installing a discovered skill is appropriate, call `install_skill`; after a+successful install, call `symphony_refresh_score` and then call+`symphony_compose_score` again with the original user task.++For clearly ordinary tasks that do not benefit from skill capabilities, continue+normally without Symphony.+"""+++class SymphonyOrchestrationPromptRail(DeepAgentRail):+ """Inject Symphony orchestration guidance only when the tool is available."""++ priority = 98+ SECTION_NAME = "symphony_orchestration"+ SECTION_PRIORITY = 42+ COMPOSE_TOOL_NAME = "symphony_compose_score"++ def __init__(self, *, config_base: _ConfigBaseProvider = None) -> None:+ super().__init__()+ self._config_base = config_base+ self.system_prompt_builder = None++ def init(self, agent: Any) -> None:+ self.system_prompt_builder = getattr(agent, "system_prompt_builder", None)++ def uninit(self, agent: Any) -> None:+ _ = agent+ if self.system_prompt_builder is not None:+ self.system_prompt_builder.remove_section(self.SECTION_NAME)+ self.system_prompt_builder = None++ async def before_model_call(self, ctx: AgentCallbackContext) -> None:+ if self.system_prompt_builder is None:+ return++ if not self._has_compose_tool(ctx):+ self.system_prompt_builder.remove_section(self.SECTION_NAME)+ return++ language = getattr(self.system_prompt_builder, "language", "cn") or "cn"+ content = _render_symphony_orchestration_prompt(+ self._resolve_config_base(),+ )+ if not content.strip():+ self.system_prompt_builder.remove_section(self.SECTION_NAME)+ return++ self.system_prompt_builder.add_section(+ PromptSection(+ name=self.SECTION_NAME,+ content={language: content},+ priority=self.SECTION_PRIORITY,+ )+ )++ @classmethod+ def _has_compose_tool(cls, ctx: AgentCallbackContext) -> bool:+ inputs = getattr(ctx, "inputs", None)+ tools = getattr(inputs, "tools", None)+ if not tools:+ return False+ return any(+ cls._model_tool_name(tool) == cls.COMPOSE_TOOL_NAME+ for tool in tools+ )++ @staticmethod+ def _model_tool_name(tool: Any) -> str:+ if isinstance(tool, dict):+ function = tool.get("function")+ if isinstance(function, dict):+ return str(function.get("name", "") or "")+ return str(tool.get("name", "") or "")+ function = getattr(tool, "function", None)+ if isinstance(function, dict):+ return str(function.get("name", "") or "")+ function_name = getattr(function, "name", None)+ if function_name is not None:+ return str(function_name)+ name = getattr(tool, "name", None)+ if name is not None:+ return str(name)+ card = getattr(tool, "card", None)+ return str(getattr(card, "name", "") or "")++ def _resolve_config_base(self) -> dict[str, Any] | None:+ if callable(self._config_base):+ return self._config_base()+ return self._config_base+++__all__ = ["SymphonyOrchestrationPromptRail"]diff --git a/jiuwenswarm/agents/swarm/config_specs.py b/jiuwenswarm/agents/swarm/config_specs.pyindex ac3d565e45..60e7f808f0 100644--- a/jiuwenswarm/agents/swarm/config_specs.py+++ b/jiuwenswarm/agents/swarm/config_specs.py@@ -69,6 +69,7 @@ _COMMON_RAIL_NAMES: tuple[str, ...] = (registry.CONTEXT_PROCESSOR,registry.PLUGIN_RAILS,registry.SKILL_RETRIEVAL_PROMPT,+ registry.SYMPHONY_ORCHESTRATION_PROMPT,)# Tools common to both roles. Each element self-gates on config, so all are@@ -115,6 +116,7 @@ _CODE_RAIL_NAMES: tuple[str, ...] = (registry.USER_HOOKS,registry.CODE_SKILL_USE,registry.SKILL_RETRIEVAL_PROMPT,+ registry.SYMPHONY_ORCHESTRATION_PROMPT,)# Rails shared with the team profile, appended to the code profile.diff --git a/jiuwenswarm/agents/swarm/providers/member_rails.py b/jiuwenswarm/agents/swarm/providers/member_rails.pyindex 9086efaf8f..59b224ec12 100644--- a/jiuwenswarm/agents/swarm/providers/member_rails.py+++ b/jiuwenswarm/agents/swarm/providers/member_rails.py@@ -38,6 +38,9 @@ from jiuwenswarm.agents.harness.common.rails.runtime_prompt_rail import (from jiuwenswarm.agents.harness.common.rails.skill_retrieval_prompt_rail import (SkillRetrievalPromptRail,)+from jiuwenswarm.agents.harness.common.rails.symphony_orchestration_prompt_rail import (+ SymphonyOrchestrationPromptRail,+)from jiuwenswarm.agents.harness.team.rails.team_skill_storage_policy_rail import (TeamSkillStoragePolicyRail,)@@ -61,6 +64,7 @@ TEAM_WORKSPACE_REPORT_PATH = "swarm.team_workspace_report_path"CONTEXT_PROCESSOR = "swarm.context_processor"PLUGIN_RAILS = "swarm.plugin_rails"SKILL_RETRIEVAL_PROMPT = "swarm.skill_retrieval_prompt"+SYMPHONY_ORCHESTRATION_PROMPT = "swarm.symphony_orchestration_prompt"TEAM_PERMISSION_POLICY = "swarm.team_permission_policy"@@ -106,6 +110,22 @@ def _build_skill_retrieval_prompt_rail()+@harness_element(+ kind=ElementKind.RAIL,+ name=SYMPHONY_ORCHESTRATION_PROMPT,+ description="Leader-only prompt guidance for Symphony orchestration.",+)+def _build_symphony_orchestration_prompt_rail(+ params: dict[str, Any],+ context: SwarmBuildContext,+) -> SymphonyOrchestrationPromptRail | None:+ """Build the Symphony orchestration prompt rail for the team leader."""+ _ = params+ if getattr(context, "role", "") != "leader":+ return None+ return SymphonyOrchestrationPromptRail()++class RuntimePromptInput(ConstructionInput):"""Construction inputs for the member runtime prompt rail."""@@ -399,6 +419,7 @@ __all__ = ["CONTEXT_PROCESSOR","PLUGIN_RAILS","SKILL_RETRIEVAL_PROMPT",+ "SYMPHONY_ORCHESTRATION_PROMPT","TEAM_PERMISSION","TEAM_PERMISSION_POLICY",]diff --git a/jiuwenswarm/agents/swarm/registry.py b/jiuwenswarm/agents/swarm/registry.pyindex 59f6132b58..32c37a37fc 100644--- a/jiuwenswarm/agents/swarm/registry.py+++ b/jiuwenswarm/agents/swarm/registry.py@@ -84,6 +84,7 @@ TEAM_WORKSPACE_REPORT_PATH = _member_rails.TEAM_WORKSPACE_REPORT_PATHCONTEXT_PROCESSOR = _member_rails.CONTEXT_PROCESSORPLUGIN_RAILS = _member_rails.PLUGIN_RAILSSKILL_RETRIEVAL_PROMPT = _member_rails.SKILL_RETRIEVAL_PROMPT+SYMPHONY_ORCHESTRATION_PROMPT = _member_rails.SYMPHONY_ORCHESTRATION_PROMPTTEAM_PERMISSION = _member_rails.TEAM_PERMISSIONTEAM_PERMISSION_POLICY = _member_rails.TEAM_PERMISSION_POLICYTEAM_SKILL_EVOLUTION = _evolution_rails.TEAM_SKILL_EVOLUTION@@ -209,6 +210,7 @@ __all__ = ["CONTEXT_PROCESSOR","PLUGIN_RAILS","SKILL_RETRIEVAL_PROMPT",+ "SYMPHONY_ORCHESTRATION_PROMPT","TEAM_PERMISSION","TEAM_PERMISSION_POLICY","TEAM_SKILL_EVOLUTION",diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex b55e1c4fc3..fb5a085636 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -128,6 +128,7 @@ from jiuwenswarm.agents.harness.common.rails import (ResponsePromptRail,RuntimePromptRail,StructuredAskUserRail,+ SymphonyOrchestrationPromptRail,)from jiuwenswarm.agents.harness.common.rails.execution_guard import (CircuitBreakerRail,@@ -602,6 +603,7 @@ class JiuWenSwarmDeepAdapter:self._model: Model | None = Noneself._model_client_config: ModelClientConfig | None = Noneself._model_request_config: ModelRequestConfig | None = None+ self._config_base_cache: dict[str, Any] | None = Noneself._config_cache: dict[str, Any] = {}self._filesystem_rail: SysOperationRail | None = Noneself._skill_rail: SkillUseRail | None = None@@ -671,6 +673,7 @@ class JiuWenSwarmDeepAdapter:self._paid_search_tool: WebPaidSearchTool | None = Noneself._symphony_tools: list[Any] = []self._symphony_tools_registered: bool = False+ self._symphony_orchestration_prompt_rail = Noneself._skill_retrieval_tools_registered: bool = Falseself._skill_retrieval_tools: list[Any] = []self._skill_retrieval_prompt_rail: SkillRetrievalPromptRail | None = None@@ -3713,6 +3716,21 @@ class JiuWenSwarmDeepAdapter:except (AttributeError, TypeError):pass+ def _build_symphony_orchestration_prompt_rail(+ self,+ ) -> SymphonyOrchestrationPromptRail | None:+ """Build dynamic Symphony orchestration prompt guidance."""+ try:+ return SymphonyOrchestrationPromptRail(+ config_base=lambda: self._config_base_cache,+ )+ except Exception as exc:+ logger.warning(+ "[JiuWenSwarmDeepAdapter] SymphonyOrchestrationPromptRail create failed: %s",+ exc,+ )+ return None+def _build_agent_rails(self, config: dict[str, Any], config_base: dict[str, Any], *, mode: str = "agent.plan") -> list[Any]:@@ -3789,6 +3807,13 @@ class JiuWenSwarmDeepAdapter:3 if self._filesystem_rail_enabled_for_profile() else 2,_RailBuildInfo("_skill_retrieval_prompt_rail", self._build_skill_retrieval_prompt_rail),)+ rail_infos.insert(+ 4 if self._filesystem_rail_enabled_for_profile() else 3,+ _RailBuildInfo(+ "_symphony_orchestration_prompt_rail",+ self._build_symphony_orchestration_prompt_rail,+ ),+ )if isinstance(mode, str) and mode.startswith("agent"):rail_infos.append(_RailBuildInfo("_ask_user_rail", self._build_structured_ask_user_rail))@@ -3895,7 +3920,6 @@ class JiuWenSwarmDeepAdapter:card=agent_card,system_prompt=build_agent_identity_prompt(language=self._resolve_prompt_language(),- config_base=config_base,),context_engine_config=_deep_agent_context_engine_config(config),enable_task_loop=self._resolve_enable_task_loop(config, config_base),@@ -4233,6 +4257,7 @@ class JiuWenSwarmDeepAdapter:self._instance_overrides = dict(config or {}) if isinstance(config, dict) else {}load_dotenv(dotenv_path=get_env_file(), override=True)config_base = get_config()+ self._config_base_cache = config_base.copy()self._refresh_multimodal_configs(config_base)config = config_base.get("react", {}).copy()self._config_cache = config.copy()@@ -4273,7 +4298,6 @@ class JiuWenSwarmDeepAdapter:card=agent_card,system_prompt=build_agent_identity_prompt(language=self._resolve_prompt_language(),- config_base=config_base,),tools=tool_cards if tool_cards else [],subagents=configured_subagents,@@ -4426,6 +4450,7 @@ class JiuWenSwarmDeepAdapter:else:config_base = resolve_env_vars(config_base)+ self._config_base_cache = config_base.copy()self._refresh_multimodal_configs(config_base)config = config_base.get("react", {}).copy()self._config_cache = config.copy()diff --git a/tests/agents/swarm/test_swarm_assembly.py b/tests/agents/swarm/test_swarm_assembly.pyindex ab36bea77e..5a6ecb031c 100644--- a/tests/agents/swarm/test_swarm_assembly.py+++ b/tests/agents/swarm/test_swarm_assembly.py@@ -104,6 +104,7 @@ _COMMON_RAIL_NAMES: frozenset[str] = frozenset(registry.CONTEXT_PROCESSOR,registry.PLUGIN_RAILS,registry.SKILL_RETRIEVAL_PROMPT,+ registry.SYMPHONY_ORCHESTRATION_PROMPT,registry.MEMBER_SKILL_TOOLKIT,})@@ -399,9 +400,9 @@ def test_build_member_capability_specs_rail_names(assert _COMMON_RAIL_NAMES <= rail_namesassert extra_rails <= rail_names- # The common set has exactly 15 entries; the role adds only its explicit+ # The common set has exactly 16 entries; the role adds only its explicit# extra rails on top.- assert len(_COMMON_RAIL_NAMES) == 15+ assert len(_COMMON_RAIL_NAMES) == 16assert rail_names == _COMMON_RAIL_NAMES | extra_rails# No DeepAgent is involved; every entry is a plain declarative RailSpec.assert all(isinstance(spec, RailSpec) for spec in rails_specs)@@ -1041,6 +1042,34 @@ def test_symphony_toolkit_respects_disabled_config(assert tools.build_symphony_toolkit({}, SwarmBuildContext(role="leader")) == []+def test_symphony_orchestration_prompt_provider_is_leader_only() -> None:+ """Only the leader gets the Symphony orchestration prompt rail."""+ factory = resolve_factory(+ get_catalog()[registry.SYMPHONY_ORCHESTRATION_PROMPT].factory_ref,+ )++ leader_rail = factory({}, SwarmBuildContext(role="leader"))+ teammate_rail = factory({}, SwarmBuildContext(role="teammate"))++ assert type(leader_rail).__name__ == "SymphonyOrchestrationPromptRail"+ assert teammate_rail is None+++def test_team_leader_spec_includes_symphony_orchestration_prompt() -> None:+ """The team leader spec declares the Symphony orchestration prompt provider."""+ spec = build_member_deep_agent_spec(+ {"symphony": {"enabled": True}},+ "team",+ "leader",+ DeepAgentSpec(),+ )++ assert any(+ rail.type == registry.SYMPHONY_ORCHESTRATION_PROMPT+ for rail in (spec.rails or [])+ )++def test_vision_model_config_params_gating(monkeypatch: pytest.MonkeyPatch) -> None:"""Vision config params are empty without a dedicated model, filled when complete."""assert tools.vision_model_config_params({}) == {}@@ -1340,6 +1369,7 @@ _EXPECTED_CODE_RAIL_NAMES: frozenset[str] = frozenset(registry.USER_HOOKS,registry.CODE_SKILL_USE,registry.SKILL_RETRIEVAL_PROMPT,+ registry.SYMPHONY_ORCHESTRATION_PROMPT,registry.CODE_CONFIRM_INTERRUPT,registry.MEMBER_SKILL_TOOLKIT,registry.TEAM_WORKSPACE_REPORT_PATH,diff --git a/tests/unit_tests/agentserver/test_agentserver_modes.py b/tests/unit_tests/agentserver/test_agentserver_modes.pyindex 12b468245a..f1b2084ea3 100644--- a/tests/unit_tests/agentserver/test_agentserver_modes.py+++ b/tests/unit_tests/agentserver/test_agentserver_modes.py@@ -1165,6 +1165,7 @@ def test_deep_adapter_build_agent_rails_adds_ask_user_for_agent_modes(monkeypatcadapter = JiuWenSwarmDeepAdapter()ask_user_rail = object()+ orchestration_rail = object()monkeypatch.setattr(adapter, "_filesystem_rail_enabled_for_profile", lambda: False)monkeypatch.setattr(adapter, "_build_runtime_prompt_rail", lambda: None)@@ -1178,6 +1179,7 @@ def test_deep_adapter_build_agent_rails_adds_ask_user_for_agent_modes(monkeypatcmonkeypatch.setattr(adapter, "_build_subagent_rail", lambda: None)monkeypatch.setattr(adapter, "_build_skill_rail", lambda **_kwargs: None)monkeypatch.setattr(adapter, "_build_skill_retrieval_prompt_rail", lambda: None)+ monkeypatch.setattr(adapter, "_build_symphony_orchestration_prompt_rail", lambda: orchestration_rail)monkeypatch.setattr(adapter, "_build_structured_ask_user_rail", lambda: ask_user_rail)monkeypatch.setattr(interface_deep_module, "build_permission_rail", lambda **_kwargs: None)monkeypatch.setattr(interface_deep_module, "_build_context_processor_rail", lambda **_kwargs: None)@@ -1186,6 +1188,8 @@ def test_deep_adapter_build_agent_rails_adds_ask_user_for_agent_modes(monkeypatcplan_rails = adapter._build_agent_rails({}, {"models": {}}, mode="agent.plan") # pylint: disable=protected-accessfast_rails = adapter._build_agent_rails({}, {"models": {}}, mode="agent.fast") # pylint: disable=protected-access+ assert orchestration_rail in plan_rails+ assert orchestration_rail in fast_railsassert ask_user_rail in plan_railsassert ask_user_rail in fast_railsdiff --git a/tests/unit_tests/agentserver/test_system_prompt_restructure.py b/tests/unit_tests/agentserver/test_system_prompt_restructure.pyindex af8c314404..690f8389a5 100644--- a/tests/unit_tests/agentserver/test_system_prompt_restructure.py+++ b/tests/unit_tests/agentserver/test_system_prompt_restructure.py@@ -14,10 +14,15 @@ from openjiuwen.harness.prompts import PromptSection, SystemPromptBuilderfrom jiuwenswarm.common import utils as _utils_modfrom jiuwenswarm.server.runtime.agent_adapter import interface_deep as interface_modulefrom jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenSwarmDeepAdapter-from jiuwenswarm.agents.harness.common.prompt.prompt_builder import build_agent_identity_prompt+from jiuwenswarm.agents.harness.common.prompt.prompt_builder import (+ build_agent_identity_prompt,+)from jiuwenswarm.agents.harness.common.rails import skill_retrieval_prompt_rail as _skill_retrieval_prompt_modfrom jiuwenswarm.agents.harness.common.rails.runtime_prompt_rail import RuntimePromptRailfrom jiuwenswarm.agents.harness.common.rails.skill_retrieval_prompt_rail import SkillRetrievalPromptRail+from jiuwenswarm.agents.harness.common.rails.symphony_orchestration_prompt_rail import (+ SymphonyOrchestrationPromptRail,+)class _TestableJiuWenSwarmDeepAdapter(JiuWenSwarmDeepAdapter):@@ -96,50 +101,140 @@ class _FakeRuntimeInstance:self.ability_manager = _FakeAbilityManager()-def test_build_agent_identity_prompt_contains_identity_section_only(monkeypatch):+def test_build_agent_identity_prompt_contains_identity_section_only():+ prompt = build_agent_identity_prompt(language="zh")++ assert "# 你的家" in prompt+ assert "## Symphony Orchestration" not in prompt+ assert "`symphony_compose_score`" not in prompt+ assert "# 消息说明" not in prompt+++async def test_symphony_orchestration_prompt_rail_respects_config_snapshot():+ enabled_builder = SystemPromptBuilder(language="cn")+ enabled_agent = _FakeAgent(enabled_builder)+ enabled_ctx = AgentCallbackContext(+ agent=enabled_agent,+ inputs=SimpleNamespace(+ tools=[SimpleNamespace(name="symphony_compose_score")],+ ),+ session=_FakeSession(),+ extra={},+ )+ enabled_rail = SymphonyOrchestrationPromptRail(+ config_base={"symphony": {"enabled": True}},+ )+ enabled_rail.init(enabled_agent)+ await enabled_rail.before_model_call(enabled_ctx)++ disabled_builder = SystemPromptBuilder(language="cn")+ disabled_agent = _FakeAgent(disabled_builder)+ disabled_ctx = AgentCallbackContext(+ agent=disabled_agent,+ inputs=SimpleNamespace(+ tools=[SimpleNamespace(name="symphony_compose_score")],+ ),+ session=_FakeSession(),+ extra={},+ )+ disabled_rail = SymphonyOrchestrationPromptRail(+ config_base={"symphony": {"enabled": False}},+ )+ disabled_rail.init(disabled_agent)+ await disabled_rail.before_model_call(disabled_ctx)++ enabled_prompt = enabled_builder.build()+ disabled_prompt = disabled_builder.build()+ assert "## Symphony Orchestration" in enabled_prompt+ assert "`symphony_compose_score`" in enabled_prompt+ assert "## Symphony Orchestration" not in disabled_prompt+ assert "`symphony_compose_score`" not in disabled_prompt+++async def test_symphony_orchestration_prompt_rail_injects_when_tool_visible(+ monkeypatch,+):monkeypatch.setattr("jiuwenswarm.symphony.config.load_symphony_config",lambda: SimpleNamespace(enabled=True),)- prompt = build_agent_identity_prompt(language="zh")- prompt_inline = " ".join(prompt.split())+ builder = SystemPromptBuilder(language="cn")+ agent = _FakeAgent(builder)+ ctx = AgentCallbackContext(+ agent=agent,+ inputs=SimpleNamespace(+ tools=[SimpleNamespace(name="symphony_compose_score")],+ ),+ session=_FakeSession(),+ extra={},+ )- assert "# 你的家" in prompt- assert "## Symphony Routing" in prompt+ rail = SymphonyOrchestrationPromptRail()+ rail.init(agent)+ await rail.before_model_call(ctx)++ prompt = builder.build()+ assert "## Symphony Orchestration" in promptassert "`symphony_compose_score`" in prompt- assert "skill capabilities, skill chaining, skill ordering" in prompt_inline- assert "use `search_skill` to discover external skills" in prompt_inline- assert "call `symphony_refresh_score`" in prompt_inline- assert "present its returned `content` directly" in prompt- assert "# 消息说明" not in prompt-def test_build_agent_identity_prompt_omits_symphony_when_disabled(monkeypatch):+async def test_symphony_orchestration_prompt_rail_clears_when_unavailable(+ monkeypatch,+):monkeypatch.setattr("jiuwenswarm.symphony.config.load_symphony_config",- lambda: SimpleNamespace(enabled=False),+ lambda: SimpleNamespace(enabled=True),+ )+ builder = SystemPromptBuilder(language="cn")+ builder.add_section(+ PromptSection(+ name="symphony_orchestration",+ content={"cn": "stale orchestration prompt"},+ priority=42,+ )+ )+ agent = _FakeAgent(builder)+ ctx = AgentCallbackContext(+ agent=agent,+ inputs=SimpleNamespace(tools=[SimpleNamespace(name="other_tool")]),+ session=_FakeSession(),+ extra={},)- prompt = build_agent_identity_prompt(language="zh")+ rail = SymphonyOrchestrationPromptRail()+ rail.init(agent)+ await rail.before_model_call(ctx)- assert "## Symphony Routing" not in prompt- assert "`symphony_compose_score`" not in prompt+ assert "stale orchestration prompt" not in builder.build()-def test_build_agent_identity_prompt_respects_config_snapshot():- enabled_prompt = build_agent_identity_prompt(- language="zh",- config_base={"symphony": {"enabled": True}},+async def test_symphony_orchestration_prompt_rail_clears_when_disabled(+ monkeypatch,+):+ monkeypatch.setattr(+ "jiuwenswarm.symphony.config.load_symphony_config",+ lambda: SimpleNamespace(enabled=False),)- disabled_prompt = build_agent_identity_prompt(- language="zh",- config_base={"symphony": {"enabled": False}},+ builder = SystemPromptBuilder(language="cn")+ agent = _FakeAgent(builder)+ ctx = AgentCallbackContext(+ agent=agent,+ inputs=SimpleNamespace(+ tools=[SimpleNamespace(name="symphony_compose_score")],+ ),+ session=_FakeSession(),+ extra={},)- assert "## Symphony Routing" in enabled_prompt- assert "`symphony_compose_score`" in enabled_prompt- assert "## Symphony Routing" not in disabled_prompt- assert "`symphony_compose_score`" not in disabled_prompt+ rail = SymphonyOrchestrationPromptRail()+ rail.init(agent)+ await rail.before_model_call(ctx)++ assert "## Symphony Orchestration" not in builder.build()def test_deep_adapter_syncs_symphony_tools_from_config_snapshot(monkeypatch):