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
feat(symphony): Symphony 能力编排支持双向束搜索
lin-xiaoyu74e44dd397c0
diff --git a/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml b/deploy/yuanrong/conf/gateway-config-yuanrong.template.yamlindex 6e63e65d23..ec8d5af356 100644--- a/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml+++ b/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml@@ -38,7 +38,10 @@ symphony:min_edge_confidence: 0.1orchestration:+ # fast is the default one-shot path; beam enables bidirectional search.mode: fast+ # Beam-only candidate count retained after each search round.+ top_k: 3max_depth: 4min_edge_confidence: 0.3diff --git a/jiuwenswarm/agents/harness/common/rails/__init__.py b/jiuwenswarm/agents/harness/common/rails/__init__.pyindex 45ad5a7e21..3c88f9cda7 100644--- a/jiuwenswarm/agents/harness/common/rails/__init__.py+++ b/jiuwenswarm/agents/harness/common/rails/__init__.py@@ -10,8 +10,8 @@ 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.common.rails.symphony import (+ SymphonyOrchestrationRail,)from jiuwenswarm.agents.harness.team.rails.team_member_skill_toolkit_rail import (MemberSkillToolkitRail,@@ -28,7 +28,7 @@ __all__ = ["ProjectMemoryRail","ResponsePromptRail","RuntimePromptRail",- "SymphonyOrchestrationPromptRail",+ "SymphonyOrchestrationRail","MemberSkillToolkitRail","StructuredAskUserRail",]diff --git a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.pyindex 97024a806a..7ea5d59423 100644--- a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py@@ -37,6 +37,9 @@ from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers importfrom jiuwenswarm.agents.harness.common.prompt.user_prompt_builder import (strip_image_content_from_model_context,)+from jiuwenswarm.agents.harness.common.rails.symphony import (+ SymphonyToolStreamHandler,+)from jiuwenswarm.common.utils import logger_TODO_TOOL_NAMES = frozenset(["todo_create", "todo_get", "todo_list", "todo_modify"])@@ -51,43 +54,6 @@ def _structured_tool_result_payload(result: Any) -> Any | None:return None-def _symphony_direct_display_content(result: Any) -> str:- if not isinstance(result, dict):- return ""- if not bool(result.get("direct_display", False)):- return ""- presentation = result.get("presentation")- presentation_markdown = (- presentation.get("markdown") if isinstance(presentation, dict) else None- )- rendered = (- result.get("content")- or result.get("markdown")- or presentation_markdown- )- return rendered.strip() if isinstance(rendered, str) else ""---def _copy_symphony_result_fields(- payload: dict[str, Any],- raw_output: Any,-) -> None:- if not isinstance(raw_output, dict):- return- for key in (- "score_status",- "score_build",- "direct_display",- "display_format",- "mermaid",- "summary",- "continue_after_display",- "followup_action",- ):- if key in raw_output:- payload[key] = raw_output[key]--def _parse_tool_call_arguments(tool_call: Any) -> dict[str, Any]:raw_args = getattr(tool_call, "arguments", None) if tool_call else Noneif isinstance(raw_args, dict):@@ -283,6 +249,7 @@ class JiuSwarmStreamEventRail(DeepAgentRail):# Store cancelled tool info for interrupt response (per-session to avoid# cross-session leakage in concurrent collect→get→clear sequences).self._cancelled_tool_results: dict[str, list[dict[str, Any]]] = {}+ self._symphony_stream_handler = SymphonyToolStreamHandler()def init(self, agent: Any) -> None:self._deep_agent = agent@@ -649,6 +616,7 @@ class JiuSwarmStreamEventRail(DeepAgentRail):tc = ctx.inputs.tool_callawait self._emit_tool_call(session, tc)await self._emit_tool_update(session, tc, status="in_progress")+ self._symphony_stream_handler.bind_progress(ctx, session, tc)# Track in-flight tool call for cancellationtc_id = getattr(tc, "id", "")if tc_id:@@ -669,12 +637,17 @@ class JiuSwarmStreamEventRail(DeepAgentRail):tc = ctx.inputs.tool_calltc_id = getattr(tc, "id", "")+ self._symphony_stream_handler.reset_progress(ctx)# Remove from in-flight tracking on completionif tc_id:self._inflight_tool_calls.pop(tc_id, None)await self._emit_tool_result(session, tc, ctx.inputs.tool_result)- self._request_symphony_force_finish(ctx, tc, ctx.inputs.tool_result)+ self._symphony_stream_handler.request_force_finish(+ ctx,+ tc,+ ctx.inputs.tool_result,+ )await self._emit_ask_user_question_if_interrupted(session,tc,@@ -727,8 +700,12 @@ class JiuSwarmStreamEventRail(DeepAgentRail):except Exception:logger.debug("tool_call emit failed", exc_info=True)- @staticmethod- async def _emit_tool_result(session: Session, tool_call: Any, result: Any) -> None:+ async def _emit_tool_result(+ self,+ session: Session,+ tool_call: Any,+ result: Any,+ ) -> None:try:raw_output = _structured_tool_result_payload(result)tool_result_payload = {@@ -738,7 +715,11 @@ class JiuSwarmStreamEventRail(DeepAgentRail):}if raw_output is not None:tool_result_payload["raw_output"] = raw_output- _copy_symphony_result_fields(tool_result_payload, raw_output)+ self._symphony_stream_handler.enrich_result_payload(+ tool_call,+ tool_result_payload,+ raw_output,+ )error_state = _infer_tool_result_error(raw_output if raw_output is not None else result)if error_state is not None:tool_result_payload["success"] = not error_state@@ -757,25 +738,6 @@ class JiuSwarmStreamEventRail(DeepAgentRail):except Exception:logger.debug("tool_result emit failed", exc_info=True)- @staticmethod- def _request_symphony_force_finish(- ctx: AgentCallbackContext,- tool_call: Any,- result: Any,- ) -> None:- tool_name = str(getattr(tool_call, "name", "") if tool_call else "").strip()- if tool_name != "symphony_compose_score":- return- content = _symphony_direct_display_content(result)- if not content:- return- if (- isinstance(result, dict)- and _boolish_true(result.get("continue_after_display"))- ):- return- ctx.request_force_finish({"output": content, "result_type": "answer"})-@staticmethodasync def _emit_ask_user_question_if_interrupted(session: Session,diff --git a/jiuwenswarm/agents/harness/common/rails/symphony/__init__.py b/jiuwenswarm/agents/harness/common/rails/symphony/__init__.pynew file mode 100644index 0000000000..54e727144b--- /dev/null+++ b/jiuwenswarm/agents/harness/common/rails/symphony/__init__.py@@ -0,0 +1,10 @@+"""Symphony-specific agent rails and stream lifecycle helpers."""++from jiuwenswarm.agents.harness.common.rails.symphony.orchestration_rail import (+ SymphonyOrchestrationRail,+)+from jiuwenswarm.agents.harness.common.rails.symphony.tool_stream_events import (+ SymphonyToolStreamHandler,+)++__all__ = ["SymphonyOrchestrationRail", "SymphonyToolStreamHandler"]diff --git a/jiuwenswarm/agents/harness/common/rails/symphony/orchestration_rail.py b/jiuwenswarm/agents/harness/common/rails/symphony/orchestration_rail.pynew file mode 100644index 0000000000..999e914a30--- /dev/null+++ b/jiuwenswarm/agents/harness/common/rails/symphony/orchestration_rail.py@@ -0,0 +1,221 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Prompt and candidate lifecycle rail for Symphony orchestration."""++from __future__ import annotations++from typing import Any, Callable++from openjiuwen.core.single_agent.rail.base import (+ AgentCallbackContext,+ ToolCallInputs,+)+from openjiuwen.harness.prompts import PromptSection+from openjiuwen.harness.rails.base import DeepAgentRail++_ConfigBaseProvider = dict[str, Any] | Callable[[], dict[str, Any] | None] | None+_SHORTLIST_EXTRA_KEY = "symphony_candidate_skill_ids"+++class SymphonyOrchestrationRail(DeepAgentRail):+ """Manage Symphony guidance, candidate injection, and viewed Skills."""++ 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:+ self._sync_orchestration_guidance(ctx)++ async def before_tool_call(self, ctx: AgentCallbackContext) -> None:+ self._inject_shortlisted_candidates(ctx)++ async def after_tool_call(self, ctx: AgentCallbackContext) -> None:+ self._remember_successful_skill_view(ctx)++ def _sync_orchestration_guidance(self, ctx: AgentCallbackContext) -> None:+ builder = self.system_prompt_builder+ if builder is None:+ return+ if not self._has_compose_tool(ctx) or not self._orchestration_enabled():+ builder.remove_section(self.SECTION_NAME)+ return++ language = getattr(builder, "language", "cn") or "cn"+ builder.add_section(+ PromptSection(+ name=self.SECTION_NAME,+ content={language: self._build_orchestration_guidance()},+ priority=self.SECTION_PRIORITY,+ )+ )++ def _inject_shortlisted_candidates(+ self,+ ctx: AgentCallbackContext,+ ) -> None:+ if not isinstance(ctx.inputs, ToolCallInputs):+ return+ if self._tool_name(ctx.inputs) != self.COMPOSE_TOOL_NAME:+ return++ args = self._tool_args(ctx.inputs)+ if "candidate_skill_ids" in args:+ return+ shortlisted = self._shortlisted_skill_ids(ctx)+ if not shortlisted:+ return++ args["candidate_skill_ids"] = shortlisted+ ctx.inputs.tool_args = args+ if ctx.inputs.tool_call is not None:+ ctx.inputs.tool_call.arguments = args++ def _remember_successful_skill_view(+ self,+ ctx: AgentCallbackContext,+ ) -> None:+ if not isinstance(ctx.inputs, ToolCallInputs):+ return+ if not self._is_skill_tool(self._tool_name(ctx.inputs)):+ return+ if ctx.exception is not None:+ return+ if self._tool_result_failed(ctx.inputs.tool_result):+ return++ args = self._tool_args(ctx.inputs)+ skill_name = str(args.get("skill_name") or args.get("skillName") or "").strip()+ if not skill_name:+ return+ shortlisted = self._shortlisted_skill_ids(ctx)+ if skill_name not in shortlisted:+ shortlisted.append(skill_name)+ ctx.extra[_SHORTLIST_EXTRA_KEY] = shortlisted++ def _orchestration_enabled(self) -> bool:+ try:+ from jiuwenswarm.symphony.config import load_symphony_config++ config_base = self._resolve_config_base()+ config = (+ load_symphony_config()+ if config_base is None+ else load_symphony_config(config_base)+ )+ except Exception:+ return False+ return bool(config.enabled)++ @staticmethod+ def _build_orchestration_guidance() -> str:+ 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 you identify, inspect, or recommend installed Skills that are relevant to+the task, you MUST pass their exact identifiers or names as+`symphony_compose_score.candidate_skill_ids`. Do not omit this field after+selecting candidate Skills. Do not 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.+"""++ @staticmethod+ def _tool_name(inputs: ToolCallInputs) -> str:+ return str(+ inputs.tool_name or getattr(inputs.tool_call, "name", "") or ""+ ).strip()++ @staticmethod+ def _is_skill_tool(name: str) -> bool:+ return str(name or "").strip().lower() == "skill_tool"++ @staticmethod+ def _tool_args(inputs: ToolCallInputs) -> dict[str, Any]:+ if isinstance(inputs.tool_args, dict):+ return dict(inputs.tool_args)+ raw_args = getattr(inputs.tool_call, "arguments", None)+ if isinstance(raw_args, dict):+ return dict(raw_args)+ return {}++ @staticmethod+ def _tool_result_failed(result: Any) -> bool:+ if not isinstance(result, dict):+ return False+ if result.get("success") is False:+ return True+ return str(result.get("status") or "").strip().lower() == "error"++ @staticmethod+ def _shortlisted_skill_ids(ctx: AgentCallbackContext) -> list[str]:+ values = ctx.extra.get(_SHORTLIST_EXTRA_KEY)+ if not isinstance(values, list):+ return []+ return [str(value).strip() for value in values if str(value).strip()]++ @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__ = ["SymphonyOrchestrationRail"]diff --git a/jiuwenswarm/agents/harness/common/rails/symphony/tool_stream_events.py b/jiuwenswarm/agents/harness/common/rails/symphony/tool_stream_events.pynew file mode 100644index 0000000000..5c6f59102b--- /dev/null+++ b/jiuwenswarm/agents/harness/common/rails/symphony/tool_stream_events.py@@ -0,0 +1,131 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Streaming lifecycle support for Symphony orchestration tools."""++from __future__ import annotations++from typing import Any++from openjiuwen.core.session.agent import Session+from openjiuwen.core.session.stream import OutputSchema+from openjiuwen.core.single_agent.rail.base import AgentCallbackContext++from jiuwenswarm.agents.harness.common.tool_progress_context import (+ bind_tool_progress,+ reset_tool_progress,+)+from jiuwenswarm.common.utils import logger+++class SymphonyToolStreamHandler:+ """Own Symphony-specific stream progress and completion behavior."""++ COMPOSE_TOOL_NAME = "symphony_compose_score"+ _PROGRESS_TOKEN_KEY = "_symphony_tool_progress_token"+ _RESULT_FIELDS = (+ "score_status",+ "score_build",+ "direct_display",+ "continue_after_display",+ "followup_action",+ )++ @classmethod+ def matches(cls, tool_call: Any) -> bool:+ return cls._tool_name(tool_call) == cls.COMPOSE_TOOL_NAME++ def bind_progress(+ self,+ ctx: AgentCallbackContext,+ session: Session,+ tool_call: Any,+ ) -> None:+ if not self.matches(tool_call):+ return++ async def progress_callback(event: dict[str, Any]) -> None:+ await self._emit_progress(session, tool_call, event)++ ctx.extra[self._PROGRESS_TOKEN_KEY] = bind_tool_progress(progress_callback)++ def reset_progress(self, ctx: AgentCallbackContext) -> None:+ reset_tool_progress(ctx.extra.pop(self._PROGRESS_TOKEN_KEY, None))++ def enrich_result_payload(+ self,+ tool_call: Any,+ payload: dict[str, Any],+ raw_output: Any,+ ) -> None:+ if not self.matches(tool_call) or not isinstance(raw_output, dict):+ return+ for key in self._RESULT_FIELDS:+ if key in raw_output:+ payload[key] = raw_output[key]++ def request_force_finish(+ self,+ ctx: AgentCallbackContext,+ tool_call: Any,+ result: Any,+ ) -> None:+ if not self.matches(tool_call):+ return+ content = self._direct_display_content(result)+ if not content or self._continues_after_display(result):+ return+ ctx.request_force_finish({"output": content, "result_type": "answer"})++ @staticmethod+ def _direct_display_content(result: Any) -> str:+ if not isinstance(result, dict) or not bool(result.get("direct_display")):+ return ""+ rendered = result.get("content")+ return rendered.strip() if isinstance(rendered, str) else ""++ @staticmethod+ def _continues_after_display(result: Any) -> bool:+ if not isinstance(result, dict):+ return False+ value = result.get("continue_after_display")+ if isinstance(value, bool):+ return value+ if isinstance(value, (int, float)):+ return value != 0+ return str(value or "").strip().lower() in {"1", "true", "yes", "on"}++ @staticmethod+ def _tool_name(tool_call: Any) -> str:+ return str(getattr(tool_call, "name", "") if tool_call else "").strip()++ @staticmethod+ async def _emit_progress(+ session: Session,+ tool_call: Any,+ event: dict[str, Any],+ ) -> None:+ if not isinstance(event.get("graph"), dict):+ return+ try:+ await session.write_stream(+ OutputSchema(+ type="tool_update",+ index=0,+ payload={+ "tool_update": {+ "tool_name": getattr(tool_call, "name", ""),+ "tool_call_id": getattr(tool_call, "id", ""),+ "status": "in_progress",+ "beam_search_event": event,+ }+ },+ )+ )+ except Exception:+ logger.debug(+ "Symphony tool progress emit failed",+ exc_info=True,+ )+++__all__ = ["SymphonyToolStreamHandler"]diff --git a/jiuwenswarm/agents/harness/common/rails/symphony_orchestration_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/symphony_orchestration_prompt_rail.pydeleted file mode 100644index 9a13a12a52..0000000000--- a/jiuwenswarm/agents/harness/common/rails/symphony_orchestration_prompt_rail.py+++ /dev/null@@ -1,141 +0,0 @@-# 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/harness/common/tool_progress_context.py b/jiuwenswarm/agents/harness/common/tool_progress_context.pynew file mode 100644index 0000000000..1c4f8384a0--- /dev/null+++ b/jiuwenswarm/agents/harness/common/tool_progress_context.py@@ -0,0 +1,26 @@+"""Task-local progress callback for long-running agent tools."""++from __future__ import annotations++from contextvars import ContextVar, Token+from typing import Any, Awaitable, Callable++ToolProgressCallback = Callable[[dict[str, Any]], Awaitable[None]]++_CURRENT_TOOL_PROGRESS: ContextVar[ToolProgressCallback | None] = ContextVar(+ "current_tool_progress",+ default=None,+)+++def bind_tool_progress(callback: ToolProgressCallback) -> Token:+ return _CURRENT_TOOL_PROGRESS.set(callback)+++def current_tool_progress() -> ToolProgressCallback | None:+ return _CURRENT_TOOL_PROGRESS.get()+++def reset_tool_progress(token: Token | None) -> None:+ if token is not None:+ _CURRENT_TOOL_PROGRESS.reset(token)diff --git a/jiuwenswarm/agents/harness/common/tools/symphony_toolkits.py b/jiuwenswarm/agents/harness/common/tools/symphony_toolkits.pyindex 09308f5bd2..d715cc94da 100644--- a/jiuwenswarm/agents/harness/common/tools/symphony_toolkits.py+++ b/jiuwenswarm/agents/harness/common/tools/symphony_toolkits.py@@ -4,24 +4,20 @@ from __future__ import annotationsimport asyncioimport inspect-import jsonimport logging-from pathlib import Path+from types import SimpleNamespacefrom typing import Any, Callablefrom openjiuwen.core.foundation.tool import LocalFunction, Tool, ToolCardfrom jiuwenswarm.extensions.registry import ExtensionRegistry-from jiuwenswarm.symphony.config import load_symphony_config-from jiuwenswarm.symphony.score_storage import (- CURRENT_POINTER_FILENAME,- resolve_score_artifact_dir,+from jiuwenswarm.agents.harness.common.tool_progress_context import (+ current_tool_progress,)+from jiuwenswarm.symphony.config import load_symphony_configlogger = logging.getLogger(__name__)-_SKILL_RETRIEVAL_CANDIDATE_RECORD_LIMIT = 10-class SymphonyToolkit:"""Expose Symphony extension RPC methods as model-callable tools."""@@ -53,7 +49,13 @@ class SymphonyToolkit:timeout_s = self._resolve_timeout_s()try:- result = handler(params, request=None)+ progress_callback = current_tool_progress()+ request = None+ if progress_callback is not None:+ request = SimpleNamespace(+ metadata={"symphony_progress_callback": progress_callback}+ )+ result = handler(params, request=request)payload = await asyncio.wait_for(result if inspect.isawaitable(result) else _return_value(result),timeout=timeout_s,@@ -64,7 +66,11 @@ class SymphonyToolkit:logger.exception("Symphony RPC failed: %s", method)return {"success": False, "detail": f"{method}: {exc}"}- return payload if isinstance(payload, dict) else {"success": True, "result": payload}+ return (+ payload+ if isinstance(payload, dict)+ else {"success": True, "result": payload}+ )@staticmethoddef _disabled_payload(method: str) -> dict[str, Any]:@@ -85,100 +91,6 @@ class SymphonyToolkit:return self._disabled_payload("symphony.build_score")return await self._call_rpc("symphony.build_score", {})- @staticmethod- def _score_needs_build(status: dict[str, Any]) -> bool:- if not bool(status.get("exists", False)):- return True- if bool(status.get("stale", False)):- return True- for key in ("added_count", "changed_count", "removed_count"):- try:- if int(status.get(key) or 0) > 0:- return True- except (TypeError, ValueError):- continue- return False-- @staticmethod- def _score_summary_markdown(- status: dict[str, Any],- update: dict[str, Any] | None,- ) -> str:- lines = ["## Symphony score", ""]- if status.get("success"):- state = "stale" if status.get("stale") else "fresh"- if not status.get("exists"):- state = "missing"- reason = str(status.get("reason") or "").strip()- lines.append(f"- Status: `{state}`")- if reason:- lines.append(f"- Detail: {reason}")- for key, label in (- ("added_count", "Added"),- ("changed_count", "Changed"),- ("removed_count", "Removed"),- ):- value = status.get(key)- if value not in (None, ""):- lines.append(f"- {label}: `{value}`")- else:- detail = str(status.get("detail") or "score status failed").strip()- lines.append("- Status: `failed`")- lines.append(f"- Detail: {detail}")- if update is not None:- if update.get("rebuilt") is False:- lines.append("- Update: `not required`")- created_at = str(update.get("score_created_at") or "").strip()- if created_at:- lines.append(f"- Score created: `{created_at}`")- return "\n".join(lines)-- update_state = "succeeded" if update.get("success") else "failed"- lines.append(f"- Update: `{update_state}`")- detail = str(update.get("detail") or update.get("reason") or "").strip()- if detail:- lines.append(f"- Update detail: {detail}")- created_at = str(update.get("score_created_at") or "").strip()- if created_at:- lines.append(f"- Score created: `{created_at}`")- total_tokens = update.get("llm_total_tokens")- if total_tokens not in (None, ""):- lines.append(f"- Build tokens: `{total_tokens}`")- else:- lines.append("- Update: `not required`")- return "\n".join(lines)-- @staticmethod- def _attach_display_payload(- payload: dict[str, Any],- status: dict[str, Any],- update: dict[str, Any] | None,- ) -> None:- del status, update- presentation = payload.get("presentation")- presentation_markdown = (- presentation.get("markdown") if isinstance(presentation, dict) else None- )- presentation_mermaid = (- presentation.get("mermaid") if isinstance(presentation, dict) else None- )- rendered = (- payload.get("content")- or payload.get("markdown")- or presentation_markdown- )- mermaid = payload.get("mermaid") or presentation_mermaid- if isinstance(mermaid, str) and mermaid.strip():- payload.setdefault("mermaid", mermaid.strip())- if not isinstance(rendered, str):- rendered = ""- rendered = rendered.strip()- payload["content"] = rendered- payload["markdown"] = rendered- payload["summary"] = rendered- payload.setdefault("display_format", "markdown")- payload.setdefault("direct_display", True)-@classmethoddef _compact_plan_payload(cls, payload: dict[str, Any]) -> dict[str, Any]:planning_payload = cls._planning_payload(payload)@@ -188,9 +100,7 @@ class SymphonyToolkit:for key in ("disabled","content",- "mermaid","direct_display",- "display_format","continue_after_display","followup_action",):@@ -207,28 +117,22 @@ class SymphonyToolkit:compact["reason"] = reasonscore_status = payload.get("score_status")- if isinstance(score_status, dict):- compact["score_status"] = cls._compact_score_status(score_status)-score_build = payload.get("score_build")- if isinstance(score_build, dict):+ if not bool(compact["success"]) and isinstance(score_status, dict):+ compact["score_status"] = cls._compact_score_status(score_status)+ if isinstance(score_build, dict) and (+ not bool(compact["success"]) or score_build.get("rebuilt") is True+ ):compact["score_build"] = cls._compact_score_build(score_build)- elif isinstance(score_status, dict):- compact["score_build"] = cls._score_build_summary(score_status, None)- skill_retrieval = planning_payload.get("skill_retrieval")- if not isinstance(skill_retrieval, dict):- skill_retrieval = payload.get("skill_retrieval")- if isinstance(skill_retrieval, dict):- compact["skill_retrieval"] = cls._compact_skill_retrieval(skill_retrieval)+ beam_search = planning_payload.get("beam_search")+ if isinstance(beam_search, dict):+ compact["beam_search"] = cls._compact_beam_search(beam_search)plan = cls._compact_plan(cls._primary_plan(planning_payload))if plan:compact["plan"] = plan- metrics = cls._compact_metrics(payload, planning_payload)- if metrics:- compact["metrics"] = metricsreturn compact@staticmethod@@ -282,69 +186,6 @@ class SymphonyToolkit:compact["llm_total_tokens"] = total_tokensreturn compact- @classmethod- def _score_build_summary(- cls,- status: dict[str, Any],- update: dict[str, Any] | None,- ) -> dict[str, Any]:- if isinstance(update, dict):- compact = cls._compact_score_build(update)- if update.get("success") is not False:- metadata = cls._score_metadata(status, update)- for key, value in metadata.items():- compact.setdefault(key, value)- return compact-- if not status.get("success"):- reason = "score_status_failed"- elif cls._score_needs_build(status):- reason = "not_run"- else:- reason = "not_required"- return {- "rebuilt": False,- "reason": reason,- **cls._score_metadata(status, None),- }-- @staticmethod- def _score_metadata(- status: dict[str, Any],- update: dict[str, Any] | None,- ) -> dict[str, Any]:- score_dir = ""- if isinstance(update, dict):- score_dir = str(update.get("score_dir") or "").strip()- if not score_dir:- score_dir = str(status.get("score_dir") or "").strip()- if not score_dir:- return {}-- root = Path(score_dir)- metadata: dict[str, Any] = {}- pointer_path = root / CURRENT_POINTER_FILENAME- if pointer_path.is_file():- try:- pointer = json.loads(pointer_path.read_text(encoding="utf-8"))- except (OSError, json.JSONDecodeError):- pointer = {}- if isinstance(pointer, dict):- version = str(pointer.get("version") or "").strip()- if version:- metadata["version"] = version-- try:- manifest_path = resolve_score_artifact_dir(root) / "score_manifest.json"- manifest = json.loads(manifest_path.read_text(encoding="utf-8"))- except (OSError, ValueError):- manifest = {}- if isinstance(manifest, dict):- created_at = str(manifest.get("created_at") or "").strip()- if created_at:- metadata["score_created_at"] = created_at- return metadata-@staticmethoddef _llm_total_tokens(token_usage: Any) -> int:if not isinstance(token_usage, dict):@@ -367,33 +208,46 @@ class SymphonyToolkit:)@classmethod- def _compact_skill_retrieval(cls, payload: dict[str, Any]) -> dict[str, Any]:+ def _compact_beam_search(cls, payload: dict[str, Any]) -> dict[str, Any]:compact = _copy_compact_fields(payload,(- "enabled",- "source",- "used",- "candidate_skill_ids",- "candidate_count",- "fallback_reason",+ "language",+ "round_index",),- keep_empty=("fallback_reason",),)- records = payload.get("candidate_records")- if isinstance(records, list):- compact["candidate_records"] = [- cls._compact_candidate_record(record)- for record in records[:_SKILL_RETRIEVAL_CANDIDATE_RECORD_LIMIT]- if isinstance(record, dict)+ graph = payload.get("graph")+ if isinstance(graph, dict):+ compact["graph"] = cls._compact_beam_graph(graph)+ return compact++ @classmethod+ def _compact_beam_graph(cls, graph: dict[str, Any]) -> dict[str, Any]:+ compact: dict[str, Any] = {}+ nodes = graph.get("nodes")+ if isinstance(nodes, list):+ compact["nodes"] = [+ cls._compact_beam_node(node) for node in nodes if isinstance(node, dict)+ ]+ edges = graph.get("edges")+ if isinstance(edges, list):+ compact["edges"] = [+ cls._compact_beam_edge(edge) for edge in edges if isinstance(edge, dict)]return compact@staticmethod- def _compact_candidate_record(record: dict[str, Any]) -> dict[str, Any]:+ def _compact_beam_node(node: dict[str, Any]) -> dict[str, Any]:+ return _copy_compact_fields(+ node,+ ("id", "label", "status", "seed"),+ )++ @staticmethod+ def _compact_beam_edge(edge: dict[str, Any]) -> dict[str, Any]:return _copy_compact_fields(- record,- ("rank", "skill_id", "skill_name", "score", "source"),+ edge,+ ("source", "target", "status"),)@classmethod@@ -438,8 +292,6 @@ class SymphonyToolkit:compact["source_id"] = sourceif target not in (None, ""):compact["target_id"] = target- if "confidence" in edge:- compact["confidence"] = edge.get("confidence")method = edge.get("method")if method not in (None, ""):compact["method"] = method@@ -448,25 +300,6 @@ class SymphonyToolkit:compact["reason"] = reasonreturn compact- @staticmethod- def _compact_metrics(- payload: dict[str, Any],- planning_payload: dict[str, Any],- ) -> dict[str, Any]:- metrics = _copy_compact_fields(- planning_payload,- (- "planning_mode",- "llm_call_count",- "candidate_skill_count",- "candidate_edge_count",- ),- )- mode = payload.get("mode") or planning_payload.get("mode")- if mode not in (None, ""):- metrics["mode"] = mode- return metrics-@staticmethoddef _primary_plan(payload: dict[str, Any]) -> dict[str, Any]:for key in ("recommended_plans", "plans"):@@ -487,16 +320,18 @@ class SymphonyToolkit:def _needs_external_skill_discovery(cls, payload: dict[str, Any]) -> bool:planning_payload = cls._planning_payload(payload)plan = cls._primary_plan(planning_payload)- status = str(- plan.get("status")- or planning_payload.get("status")- or payload.get("status")- or ""- ).strip().lower()+ status = (+ str(+ plan.get("status")+ or planning_payload.get("status")+ or payload.get("status")+ or ""+ )+ .strip()+ .lower()+ )missing_inputs = (- plan.get("missing_inputs")- or planning_payload.get("missing_inputs")- or []+ plan.get("missing_inputs") or planning_payload.get("missing_inputs") or [])if status == "needs_input" or missing_inputs:return False@@ -508,9 +343,7 @@ class SymphonyToolkit:if not isinstance(execution_graph, dict):execution_graph = payload.get("execution_graph")graph_nodes = (- execution_graph.get("nodes")- if isinstance(execution_graph, dict)- else []+ execution_graph.get("nodes") if isinstance(execution_graph, dict) else [])return not steps and not graph_nodes@@ -539,30 +372,7 @@ class SymphonyToolkit:) -> dict[str, Any]:if not self.is_enabled():return self._compact_plan_payload(self._disabled_payload("symphony.plan"))- status = await self.score_status()- if not status.get("success"):- detail = self._failure_detail(status, "symphony.score_status failed")- return self._compact_plan_payload({- "success": False,- "detail": f"symphony.score_status failed before planning: {detail}",- "score_status": status,- })- update: dict[str, Any] | None = None- if status.get("success") and self._score_needs_build(status):- update = await self.refresh_score()- if not update.get("success"):- detail = self._failure_detail(update, "symphony.build_score failed")- return self._compact_plan_payload({- "success": False,- "detail": f"symphony.build_score failed before planning: {detail}",- "score_status": status,- "score_build": self._score_build_summary(status, update),- })- score_build = self._score_build_summary(status, update)-- params: dict[str, Any] = {- "query": str(query or "").strip(),- }+ params: dict[str, Any] = {"query": str(query or "").strip()}mode_text = str(mode or "").strip()if mode_text:params["mode"] = mode_text@@ -573,10 +383,7 @@ class SymphonyToolkit:params["candidate_skill_ids"] = normalized_candidate_skill_idspayload = await self._call_rpc("symphony.plan", params)if isinstance(payload, dict):- payload.setdefault("score_status", status)- payload["score_build"] = score_buildself._attach_followup_control(payload)- self._attach_display_payload(payload, status, score_build)return self._compact_plan_payload(payload)return payload@@ -626,9 +433,10 @@ class SymphonyToolkit:("MUST call before answering when the user says to use skill(s) ""or 技能, or when skill capabilities, skill chaining, skill ordering, "- "or a specialized toolchain could help complete the task. Use skill_branch_peek "- "and skill_branch_explore first when installed-skill retrieval can narrow "- "the candidate skills, then pass returned worker_id values as candidate_skill_ids. "+ "or a specialized toolchain could help complete the task. When you identify, "+ "inspect, or recommend installed Skills that are relevant to the task, you MUST "+ "pass their exact identifiers or names as candidate_skill_ids. Do not omit "+ "candidate_skill_ids after selecting candidate Skills. ""This is the Symphony composition entrypoint: it reads the score, refreshes stale ""or missing scores, then composes the skill execution graph from the provided ""candidates or a default score subgraph. If no suitable candidates or a missing "@@ -648,19 +456,24 @@ class SymphonyToolkit:},"mode": {"type": "string",- "enum": ["fast"],+ "enum": ["fast", "beam"],"description": (- "Optional planning mode. The current Symphony runtime "- "supports fast planning only."+ "Optional planning mode. Use fast for simple tasks, "+ "short execution chains, or when candidate skills are "+ "already clear; fast is the default. Use beam for "+ "complex multi-step tasks, tasks with multiple possible "+ "skill paths, or when prerequisite skills need to be "+ "discovered through bidirectional search."),},"candidate_skill_ids": {"type": "array","items": {"type": "string"},"description": (- "Optional installed skill worker_id values returned by "- "skill_branch_explore. When provided, Symphony composes "- "from these candidate skills and their eligible neighbors."+ "Optional identifiers or exact names of the installed Skills "+ "you consider most relevant to the user's task. When relevant "+ "Skills have already been identified, provide them here so "+ "Symphony uses them and their eligible neighbors as seeds."),},},@@ -678,16 +491,13 @@ async def _return_value(value: Any) -> Any:def _copy_compact_fields(payload: dict[str, Any],keys: tuple[str, ...],- *,- keep_empty: tuple[str, ...] = (),) -> dict[str, Any]:compact: dict[str, Any] = {}- keep_empty_set = set(keep_empty)for key in keys:if key not in payload:continuevalue = payload[key]- if key not in keep_empty_set and value in (None, "", [], {}):+ if value in (None, "", [], {}):continuecompact[key] = valuereturn compactdiff --git a/jiuwenswarm/agents/swarm/providers/member_rails.py b/jiuwenswarm/agents/swarm/providers/member_rails.pyindex 2f33ccd145..f5b4786421 100644--- a/jiuwenswarm/agents/swarm/providers/member_rails.py+++ b/jiuwenswarm/agents/swarm/providers/member_rails.py@@ -38,8 +38,8 @@ 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.common.rails.symphony import (+ SymphonyOrchestrationRail,)from jiuwenswarm.agents.harness.team.rails.team_skill_storage_policy_rail import (TeamSkillStoragePolicyRail,@@ -115,15 +115,15 @@ def _build_skill_retrieval_prompt_rail(name=SYMPHONY_ORCHESTRATION_PROMPT,description="Leader-only prompt guidance for Symphony orchestration.",)-def _build_symphony_orchestration_prompt_rail(+def _build_symphony_orchestration_rail(params: dict[str, Any],context: SwarmBuildContext,-) -> SymphonyOrchestrationPromptRail | None:+) -> SymphonyOrchestrationRail | None:"""Build the Symphony orchestration prompt rail for the team leader."""_ = paramsif getattr(context, "role", "") != "leader":return None- return SymphonyOrchestrationPromptRail()+ return SymphonyOrchestrationRail()class RuntimePromptInput(ConstructionInput):diff --git a/jiuwenswarm/agents/swarm/providers/tools.py b/jiuwenswarm/agents/swarm/providers/tools.pyindex 9ff7836293..27f392fe59 100644--- a/jiuwenswarm/agents/swarm/providers/tools.py+++ b/jiuwenswarm/agents/swarm/providers/tools.py@@ -404,7 +404,8 @@ def _build_symphony_tools(ctx: SwarmBuildContext) -> list[Any]:if getattr(ctx, "role", "") != "leader":return []try:- return list(SymphonyToolkit().get_tools(get_config()))+ config = ctx.config or get_config()+ return list(SymphonyToolkit().get_tools(config))except Exception as exc:logger.warning("[swarm.symphony_toolkit] construction failed: %s", exc)return []diff --git a/jiuwenswarm/channels/web/frontend/package.json b/jiuwenswarm/channels/web/frontend/package.jsonindex 9f09e48d5d..04830a57cb 100644--- a/jiuwenswarm/channels/web/frontend/package.json+++ b/jiuwenswarm/channels/web/frontend/package.json@@ -9,6 +9,7 @@"dev": "vite","build": "tsc && vite build","test:openai-account-model-state": "tsc src/components/ConfigPanel/openaiAccountModelState.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/openai-account-model-state --skipLibCheck && node --test tests/openaiAccountModelState.test.mjs",+ "test:tool-result-lifecycle": "tsc src/stores/toolResultLifecycle.ts --target ES2020 --module ES2020 --moduleResolution Bundler --rootDir src --outDir node_modules/.cache/tool-result-lifecycle --skipLibCheck --noEmitOnError && node --test tests/toolResultLifecycle.test.mjs","lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0","preview": "vite preview"},diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/BeamSearchTree.css b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/BeamSearchTree.cssnew file mode 100644index 0000000000..57df99e77b--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/BeamSearchTree.css@@ -0,0 +1,354 @@+.beam-tree {+ margin-top: 6px;+ overflow: hidden;+ border: 1px solid var(--color-border-default);+ border-radius: 10px;+ background: var(--color-surface-card);+}++.beam-tree__header {+ display: flex;+ width: 100%;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+ padding: 7px 10px;+ color: var(--color-text-primary);+ background: var(--color-surface-panel-strong, var(--color-surface-elevated));+ border: 0;+ cursor: pointer;+ text-align: left;+}++.beam-tree__title,+.beam-tree__meta {+ display: flex;+ min-width: 0;+ align-items: center;+ gap: 7px;+ font-size: 11px;+}++.beam-tree__badge {+ flex: none;+ padding: 2px 7px;+ border-radius: 999px;+ color: var(--color-action-primary, #6366f1);+ background: var(--color-action-primary-subtle, rgba(99, 102, 241, 0.12));+ font-weight: 600;+}++.beam-tree__stage,+.beam-tree__meta {+ color: var(--color-text-secondary);+}++.beam-tree__stage {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.beam-tree__meta {+ flex: none;+ white-space: nowrap;+}++.beam-tree__chevron,+.beam-tree__more-chevron {+ flex: none;+ transition: transform 160ms ease;+}++.beam-tree__chevron.is-open,+.beam-tree__more-chevron.is-open {+ transform: rotate(180deg);+}++.beam-tree__body {+ max-height: 360px;+ overflow: auto;+ padding: 8px 10px 10px;+ border-top: 1px solid var(--color-border-default);+ background: var(--color-surface-elevated);+}++.beam-tree__forest {+ display: grid;+ gap: 6px;+}++.beam-tree__branch,+.beam-tree__child {+ min-width: 0;+}++.beam-tree__node {+ min-width: 0;+ min-height: 38px;+ display: flex;+ align-items: center;+ padding: 6px 8px;+ border: 1px solid var(--color-border-default);+ border-radius: 8px;+ background: var(--color-surface-card);+ color: var(--color-text-primary);+ animation: beam-tree-node-enter 240ms ease-out both;+}++.beam-tree__node-main {+ display: flex;+ width: 100%;+ min-width: 0;+ align-items: center;+ gap: 6px;+}++.beam-tree__type {+ flex: none;+ padding: 1px 5px;+ border-radius: 999px;+ color: #2563eb;+ background: rgba(37, 99, 235, 0.12);+ font-size: 10px;+ font-weight: 700;+ line-height: 1.3;+}++.beam-tree__label {+ min-width: 0;+ overflow: hidden;+ color: #1d4ed8;+ font-size: 12px;+ font-weight: 650;+ line-height: 1.3;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.beam-tree__state {+ flex: none;+ margin-left: auto;+ color: var(--color-text-secondary);+ font-size: 10px;+ line-height: 1.3;+ white-space: nowrap;+}++.beam-tree__node.is-seed {+ border-color: rgba(37, 99, 235, 0.38);+ background: rgba(37, 99, 235, 0.07);+}++.beam-tree__node.is-pending {+ border-color: rgba(99, 102, 241, 0.42);+ box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.08);+ animation: beam-tree-node-enter 240ms ease-out both, beam-tree-pending 1.8s ease-in-out infinite;+}++.beam-tree__node.is-selected {+ border-color: rgba(16, 185, 129, 0.42);+ background: rgba(16, 185, 129, 0.08);+}++.beam-tree__node.is-selected .beam-tree__type,+.beam-tree__node.is-final .beam-tree__type {+ color: #047857;+ background: rgba(16, 185, 129, 0.14);+}++.beam-tree__node.is-selected .beam-tree__label {+ color: #047857;+}++.beam-tree__node.is-rejected {+ border-color: var(--color-border-default);+ background: var(--color-surface-panel-strong, rgba(148, 163, 184, 0.08));+ opacity: 0.62;+}++.beam-tree__node.is-rejected .beam-tree__type,+.beam-tree__node.is-rejected .beam-tree__label,+.beam-tree__node.is-rejected .beam-tree__state {+ color: var(--color-text-secondary);+}++.beam-tree__node.is-rejected .beam-tree__type {+ background: rgba(148, 163, 184, 0.14);+}++.beam-tree__node.is-final {+ border-color: rgba(124, 58, 237, 0.48);+ background: rgba(124, 58, 237, 0.08);+ box-shadow: inset 3px 0 0 rgba(124, 58, 237, 0.72);+}++.beam-tree__node.is-final .beam-tree__type {+ color: #6d28d9;+ background: rgba(124, 58, 237, 0.14);+}++.beam-tree__node.is-final .beam-tree__label {+ color: #6d28d9;+}++.beam-tree__children {+ position: relative;+ display: grid;+ gap: 4px;+ margin-left: 18px;+ padding-top: 4px;+ padding-left: 14px;+ border-left: 1px solid var(--color-border-default);+}++.beam-tree__child {+ position: relative;+}++.beam-tree__child::before {+ position: absolute;+ top: 18px;+ left: -14px;+ width: 12px;+ border-top: 1px solid var(--color-border-default);+ content: '';+}++.beam-tree__child::after {+ position: absolute;+ top: 15px;+ left: -4px;+ width: 0;+ height: 0;+ border-top: 3px solid transparent;+ border-bottom: 3px solid transparent;+ border-left: 4px solid var(--color-text-secondary);+ content: '';+}++.beam-tree__merge {+ min-width: 0;+ min-height: 32px;+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 5px 8px;+ overflow: hidden;+ border: 1px dashed var(--color-border-default);+ border-radius: 8px;+ background: var(--color-surface-card);+ color: var(--color-text-secondary);+ font-size: 11px;+}++.beam-tree__merge span {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.beam-tree__merge.is-selected,+.beam-tree__merge.is-final {+ border-color: rgba(16, 185, 129, 0.34);+ color: #047857;+}++.beam-tree__merge.is-rejected {+ opacity: 0.58;+}++.beam-tree__more {+ width: fit-content;+ max-width: 100%;+ display: inline-flex;+ align-items: center;+ gap: 5px;+ padding: 4px 8px;+ border: 1px dashed var(--color-border-default);+ border-radius: 7px;+ background: transparent;+ color: var(--color-text-secondary);+ cursor: pointer;+ font-size: 11px;+}++.beam-tree__more:hover {+ border-color: var(--color-action-primary, #6366f1);+ background: var(--color-action-primary-subtle, rgba(99, 102, 241, 0.08));+ color: var(--color-action-primary, #6366f1);+}++.beam-tree__empty {+ padding: 12px;+ color: var(--color-text-secondary);+ font-size: 11px;+ text-align: center;+}++@keyframes beam-tree-node-enter {+ from {+ opacity: 0;+ transform: translateY(-3px);+ }++ to {+ opacity: 1;+ transform: translateY(0);+ }+}++@keyframes beam-tree-pending {+ 0%,+ 100% {+ box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.06);+ }++ 50% {+ box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.16);+ }+}++@media (max-width: 640px) {+ .beam-tree__header {+ align-items: flex-start;+ }++ .beam-tree__stage {+ display: none;+ }++ .beam-tree__meta {+ max-width: calc(100% - 72px);+ justify-content: flex-end;+ overflow: hidden;+ font-size: 10px;+ text-overflow: ellipsis;+ }++ .beam-tree__children {+ margin-left: 10px;+ padding-left: 10px;+ }++ .beam-tree__child::before {+ left: -10px;+ width: 8px;+ }++ .beam-tree__child::after {+ left: -4px;+ }+}++@media (prefers-reduced-motion: reduce) {+ .beam-tree__node,+ .beam-tree__node.is-pending {+ animation: none;+ }++ .beam-tree__chevron,+ .beam-tree__more-chevron {+ transition: none;+ }+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/BeamSearchTree.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/BeamSearchTree.tsxnew file mode 100644index 0000000000..b86e324104--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/BeamSearchTree.tsx@@ -0,0 +1,225 @@+import { useMemo, useState } from 'react';+import clsx from 'clsx';+import { ChevronDown, GitMerge } from 'lucide-react';+import type { BeamSearchNode, BeamSearchProgress } from '../../types/beamSearch';+import {+ buildBeamTree,+ type BeamTreeMergeEntry,+ type BeamTreeNodeEntry,+} from './beamSearchTreeModel';+import './BeamSearchTree.css';+import { useProcessTreeCollapse } from './useProcessTreeCollapse';++const MAX_VISIBLE_REJECTED_CHILDREN = 4;++interface BeamTreeCopy {+ title: string;+ seedStage: string;+ round: (roundIndex: number) => string;+ summary: (total: number, selected: number, rejected: number) => string;+ skillType: string;+ seedType: string;+ statuses: Record<BeamSearchNode['status'], string>;+ mergeTo: (label: string) => string;+ showRejected: (count: number) => string;+ hideRejected: string;+ empty: string;+}++const COPY: Record<BeamSearchProgress['language'], BeamTreeCopy> = {+ cn: {+ title: '技能编排',+ seedStage: '种子确认',+ round: (roundIndex) => `第 ${roundIndex} 轮`,+ summary: (total, selected, rejected) =>+ `${total} 个技能 · ${selected} 个入选 · ${rejected} 个未入选`,+ skillType: '技能',+ seedType: '种子',+ statuses: {+ seed: '种子技能',+ pending: '判断中',+ selected: '已入选',+ rejected: '未入选',+ final: '最终方案',+ },+ mergeTo: (label) => `汇合到 ${label}`,+ showRejected: (count) => `还有 ${count} 个未入选技能`,+ hideRejected: '收起未入选技能',+ empty: '正在准备候选技能',+ },+ en: {+ title: 'Skill orchestration',+ seedStage: 'Seeds ready',+ round: (roundIndex) => `Round ${roundIndex}`,+ summary: (total, selected, rejected) =>+ `${total} skills · ${selected} selected · ${rejected} rejected`,+ skillType: 'Skill',+ seedType: 'Seed',+ statuses: {+ seed: 'Seed skill',+ pending: 'Judging',+ selected: 'Selected',+ rejected: 'Rejected',+ final: 'Final plan',+ },+ mergeTo: (label) => `Merges into ${label}`,+ showRejected: (count) => `${count} more rejected skills`,+ hideRejected: 'Hide rejected skills',+ empty: 'Preparing candidate skills',+ },+};++function BeamMergeReference({ entry, copy }: {+ entry: BeamTreeMergeEntry;+ copy: BeamTreeCopy;+}) {+ const label = entry.node.label || entry.node.id;+ return (+ <div+ className={clsx('beam-tree__merge', `is-${entry.node.status}`)}+ title={copy.mergeTo(label)}+ data-testid={`beam-tree-merge-${entry.node.id}`}+ >+ <GitMerge size={13} aria-hidden="true" />+ <span>{copy.mergeTo(label)}</span>+ </div>+ );+}++function BeamTreeNodeCard({ entry, copy }: {+ entry: BeamTreeNodeEntry;+ copy: BeamTreeCopy;+}) {+ const node = entry.node;+ const label = node.label || node.id;+ return (+ <div+ className={clsx('beam-tree__node', `is-${node.status}`)}+ title={label}+ data-testid={`beam-tree-node-${node.id}`}+ >+ <div className="beam-tree__node-main">+ <span className="beam-tree__type">+ {node.status === 'seed' ? copy.seedType : copy.skillType}+ </span>+ <span className="beam-tree__label">{label}</span>+ <span className="beam-tree__state">{copy.statuses[node.status]}</span>+ </div>+ </div>+ );+}++function BeamTreeBranch({ entry, copy }: {+ entry: BeamTreeNodeEntry;+ copy: BeamTreeCopy;+}) {+ const [showAllRejected, setShowAllRejected] = useState(false);+ let rejectedSeen = 0;+ const hiddenRejectedCount = entry.children.reduce((count, child) => (+ child.node.status === 'rejected' ? count + 1 : count+ ), 0) - MAX_VISIBLE_REJECTED_CHILDREN;+ const visibleChildren = entry.children.filter((child) => {+ if (child.node.status !== 'rejected' || showAllRejected) return true;+ rejectedSeen += 1;+ return rejectedSeen <= MAX_VISIBLE_REJECTED_CHILDREN;+ });++ return (+ <div className="beam-tree__branch">+ <BeamTreeNodeCard entry={entry} copy={copy} />+ {(visibleChildren.length > 0 || hiddenRejectedCount > 0) && (+ <div className="beam-tree__children">+ {visibleChildren.map((child, index) => (+ <div+ className="beam-tree__child"+ key={`${entry.node.id}-${child.kind}-${child.node.id}-${index}`}+ >+ {child.kind === 'merge' ? (+ <BeamMergeReference entry={child} copy={copy} />+ ) : (+ <BeamTreeBranch entry={child} copy={copy} />+ )}+ </div>+ ))}+ {hiddenRejectedCount > 0 && (+ <button+ type="button"+ className="beam-tree__more"+ onClick={() => setShowAllRejected((value) => !value)}+ aria-expanded={showAllRejected}+ >+ <span>+ {showAllRejected+ ? copy.hideRejected+ : copy.showRejected(hiddenRejectedCount)}+ </span>+ <ChevronDown+ size={13}+ className={clsx('beam-tree__more-chevron', showAllRejected && 'is-open')}+ aria-hidden="true"+ />+ </button>+ )}+ </div>+ )}+ </div>+ );+}++interface BeamSearchTreeProps {+ progress: BeamSearchProgress;+ autoCollapse?: boolean;+}++export function BeamSearchTree({+ progress,+ autoCollapse = false,+}: BeamSearchTreeProps) {+ const [collapsed, setCollapsed] = useProcessTreeCollapse(autoCollapse);+ const model = useMemo(() => buildBeamTree(progress), [progress]);+ const copy = COPY[progress.language];+ const selected = progress.graph.nodes.filter(+ (node) => node.status === 'selected' || node.status === 'final'+ ).length;+ const rejected = progress.graph.nodes.filter((node) => node.status === 'rejected').length;+ const stage = progress.roundIndex > 0+ ? copy.round(progress.roundIndex)+ : copy.seedStage;++ return (+ <section className="beam-tree animate-rise" data-testid="beam-search-tree">+ <button+ type="button"+ className="beam-tree__header"+ onClick={() => setCollapsed((value) => !value)}+ aria-expanded={!collapsed}+ >+ <span className="beam-tree__title">+ <span className="beam-tree__badge">{copy.title}</span>+ <span className="beam-tree__stage">{stage}</span>+ </span>+ <span className="beam-tree__meta">+ {copy.summary(model.nodeCount, selected, rejected)}+ <ChevronDown+ className={clsx('beam-tree__chevron', !collapsed && 'is-open')}+ size={14}+ aria-hidden="true"+ />+ </span>+ </button>+ {!collapsed && (+ <div className="beam-tree__body">+ {model.roots.length > 0 ? (+ <div className="beam-tree__forest">+ {model.roots.map((root) => (+ <BeamTreeBranch key={root.node.id} entry={root} copy={copy} />+ ))}+ </div>+ ) : (+ <div className="beam-tree__empty">{copy.empty}</div>+ )}+ </div>+ )}+ </section>+ );+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillTreePath.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillTreePath.tsxindex 498fe8173e..8b5bf06fa9 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillTreePath.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillTreePath.tsx@@ -14,6 +14,7 @@ import type {SkillTreePath as SkillTreePathData,} from '../../types/skillTree';import './SkillTreePath.css';+import { useProcessTreeCollapse } from './useProcessTreeCollapse';interface SkillTreePathProps {tree?: SkillTreePathData;@@ -448,7 +449,10 @@ export function SkillTreePath({() => buildViewedSkillKeySet(accumulatedViewedSkillIds),[accumulatedViewedSkillIds]);- const [collapsed, setCollapsed] = useState(autoCollapse);+ const [collapsed, setCollapsed] = useProcessTreeCollapse(+ autoCollapse,+ graph.queryLabel+ );const [expandedNodeIds, setExpandedNodeIds] = useState<Set<string>>(() => new Set());const [newNodeIds, setNewNodeIds] = useState<Set<string>>(() => new Set());const previousNodeIdsRef = useRef<Set<string> | null>(null);@@ -463,12 +467,6 @@ export function SkillTreePath({});}, [viewedSkillIds]);- useEffect(() => {- if (autoCollapse) {- setCollapsed(true);- }- }, [autoCollapse, graph.queryLabel]);-useEffect(() => {const nextNodeIds = new Set(graph.nodes.keys());const previousNodeIds = previousNodeIdsRef.current;diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ToolGroupDisplay.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ToolGroupDisplay.tsxindex 82fe64ea89..5f7d0a6e76 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ToolGroupDisplay.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ToolGroupDisplay.tsx@@ -11,6 +11,7 @@ import { ToolExecution } from '../../types';import { formatToolArguments, formatToolResult } from '../../utils';import { TeamMemberAvatar } from '../TeamMemberAvatar';import { SkillTreePath } from './SkillTreePath';+import { BeamSearchTree } from './BeamSearchTree';interface ToolGroupDisplayProps {executions: ToolExecution[];@@ -67,6 +68,9 @@ function isExecutionSuccessful(execution: ToolExecution) {}function getExecutionTone(execution: ToolExecution): ToolStatusTone {+ if (execution.status === 'pending') {+ return 'pending';+ }if (isExecutionSuccessful(execution)) {return 'success';}@@ -440,6 +444,10 @@ export function ToolGroupDisplay({const skillTrees = skillTreeExecutions.map((execution) => execution.result?.skillTree).filter((tree): tree is NonNullable<typeof tree> => Boolean(tree));+ const beamSearch = [...visibleExecutions]+ .reverse()+ .find((execution) => execution.result?.beamSearch)+ ?.result?.beamSearch;const viewedSkillIds = Array.from(new Set([...turnViewedSkillIds,...collectViewedSkillIds(executions),@@ -514,6 +522,12 @@ export function ToolGroupDisplay({autoCollapse={collapseSkillTreeWhenContentStarts}/>)}+ {beamSearch && (+ <BeamSearchTree+ progress={beamSearch}+ autoCollapse={collapseSkillTreeWhenContentStarts}+ />+ )}</div></div>);diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/beamSearchTreeModel.ts b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/beamSearchTreeModel.tsnew file mode 100644index 0000000000..f4dd8203fd--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/beamSearchTreeModel.ts@@ -0,0 +1,114 @@+import type {+ BeamSearchEdge,+ BeamSearchNode,+ BeamSearchProgress,+} from '../../types/beamSearch';++export interface BeamTreeNodeEntry {+ kind: 'node';+ node: BeamSearchNode;+ children: BeamTreeEntry[];+}++export interface BeamTreeMergeEntry {+ kind: 'merge';+ node: BeamSearchNode;+}++export type BeamTreeEntry = BeamTreeNodeEntry | BeamTreeMergeEntry;++export interface BeamTreeModel {+ roots: BeamTreeNodeEntry[];+ nodeCount: number;+}++function compareNodes(left: BeamSearchNode, right: BeamSearchNode): number {+ return (left.label || left.id).localeCompare(right.label || right.id) ||+ left.id.localeCompare(right.id);+}++function compareEdges(+ left: BeamSearchEdge,+ right: BeamSearchEdge,+ nodes: Map<string, BeamSearchNode>+): number {+ const leftNode = nodes.get(left.target);+ const rightNode = nodes.get(right.target);+ if (leftNode && rightNode) {+ const nodeOrder = compareNodes(leftNode, rightNode);+ if (nodeOrder !== 0) return nodeOrder;+ }+ return left.target.localeCompare(right.target) || left.source.localeCompare(right.source);+}++export function buildBeamTree(progress: BeamSearchProgress): BeamTreeModel {+ const nodes = new Map<string, BeamSearchNode>();+ for (const node of progress.graph.nodes) {+ if (node?.id && !nodes.has(node.id)) nodes.set(node.id, node);+ }++ const outgoing = new Map<string, BeamSearchEdge[]>();+ const incomingCount = new Map<string, number>();+ const edgeKeys = new Set<string>();+ for (const edge of progress.graph.edges) {+ if (!nodes.has(edge.source) || !nodes.has(edge.target) || edge.source === edge.target) {+ continue;+ }+ const edgeKey = `${edge.source}\u0000${edge.target}`;+ if (edgeKeys.has(edgeKey)) continue;+ edgeKeys.add(edgeKey);+ const sourceEdges = outgoing.get(edge.source) ?? [];+ sourceEdges.push(edge);+ outgoing.set(edge.source, sourceEdges);+ incomingCount.set(edge.target, (incomingCount.get(edge.target) ?? 0) + 1);+ }+ for (const edges of outgoing.values()) {+ edges.sort((left, right) => compareEdges(left, right, nodes));+ }++ const sortedNodes = [...nodes.values()].sort(compareNodes);+ const seedIds = sortedNodes+ .filter((node) => node.seed === true || node.status === 'seed')+ .map((node) => node.id);+ const seedIdSet = new Set(seedIds);+ const rootIds = [+ ...seedIds,+ ...sortedNodes+ .filter((node) => !seedIdSet.has(node.id) && !incomingCount.has(node.id))+ .map((node) => node.id),+ ];+ const reservedRoots = new Set(rootIds);+ const claimed = new Set<string>();++ const visit = (+ nodeId: string,+ active: Set<string>,+ allowReservedRoot = false+ ): BeamTreeEntry | null => {+ const node = nodes.get(nodeId);+ if (!node) return null;+ if (active.has(nodeId) || claimed.has(nodeId) ||+ (!allowReservedRoot && reservedRoots.has(nodeId))) {+ return { kind: 'merge', node };+ }++ claimed.add(nodeId);+ const nextActive = new Set(active);+ nextActive.add(nodeId);+ const children = (outgoing.get(nodeId) ?? [])+ .map((edge) => visit(edge.target, nextActive))+ .filter((entry): entry is BeamTreeEntry => entry !== null);+ return { kind: 'node', node, children };+ };++ const roots: BeamTreeNodeEntry[] = [];+ const appendRoot = (nodeId: string) => {+ if (claimed.has(nodeId)) return;+ const entry = visit(nodeId, new Set(), true);+ if (entry?.kind === 'node') roots.push(entry);+ };+ rootIds.forEach(appendRoot);+ sortedNodes.forEach((node) => appendRoot(node.id));++ return { roots, nodeCount: nodes.size };+}diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/useProcessTreeCollapse.ts b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/useProcessTreeCollapse.tsnew file mode 100644index 0000000000..521c8c7b0e--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/useProcessTreeCollapse.ts@@ -0,0 +1,13 @@+import { useEffect, useState } from 'react';++export function useProcessTreeCollapse(autoCollapse: boolean, resetKey = '') {+ const [collapsed, setCollapsed] = useState(autoCollapse);++ useEffect(() => {+ if (autoCollapse) {+ setCollapsed(true);+ }+ }, [autoCollapse, resetKey]);++ return [collapsed, setCollapsed] as const;+}diff --git a/jiuwenswarm/channels/web/frontend/src/features/tool-events/toolEventNormalizer.ts b/jiuwenswarm/channels/web/frontend/src/features/tool-events/toolEventNormalizer.tsindex 4ade6f1801..5c2349e92a 100644--- a/jiuwenswarm/channels/web/frontend/src/features/tool-events/toolEventNormalizer.ts+++ b/jiuwenswarm/channels/web/frontend/src/features/tool-events/toolEventNormalizer.ts@@ -1,4 +1,8 @@import { parseSkillTreePath, type SkillTreePath } from '../../types/skillTree';+import {+ parseBeamSearchProgress,+ type BeamSearchProgress,+} from '../../types/beamSearch';type UnknownPayload = Record<string, unknown>;@@ -78,6 +82,13 @@ export interface NormalizedToolResult {success: boolean;summary?: string;skillTree?: SkillTreePath;+ beamSearch?: BeamSearchProgress;+}++export interface NormalizedToolUpdate {+ toolName: string;+ toolCallId?: string;+ beamSearch?: BeamSearchProgress;}export function normalizeToolCallPayload(payload: UnknownPayload): NormalizedToolCall {@@ -147,6 +158,8 @@ export function normalizeToolResultPayload(payload: UnknownPayload): NormalizedTconst skillTree =parseSkillTreePath(toolResultPayload.raw_output) ??parseSkillTreePath(toolResultPayload.rawOutput);+ const beamSearch =+ parseBeamSearchProgress(rawOutputRecord?.beam_search);return {toolName,@@ -155,5 +168,16 @@ export function normalizeToolResultPayload(payload: UnknownPayload): NormalizedTsuccess,summary,skillTree,+ beamSearch,+ };+}++export function normalizeToolUpdatePayload(payload: UnknownPayload): NormalizedToolUpdate {+ const update = asRecord(payload.tool_update) ?? payload;+ return {+ toolName:+ (typeof update.tool_name === 'string' && update.tool_name) || 'unknown',+ toolCallId: resolveToolCallId(update, payload),+ beamSearch: parseBeamSearchProgress(update.beam_search_event),};}diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.tsindex c22e335c85..f4d1bbb7e9 100644--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts@@ -50,6 +50,7 @@ import {import {normalizeToolCallPayload,normalizeToolResultPayload,+ normalizeToolUpdatePayload,} from '../features/tool-events/toolEventNormalizer';import { findActiveTeamLeaderMessage as findActiveTeamLeaderMessageInTurn } from '../features/teamLeaderMessages';@@ -2007,6 +2008,16 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {applyTeamTaskToolCall(sessionId, toolCall);}}),+ webClient.on('chat.tool_update', ({ payload }) => {+ const sessionId = resolveEventSessionId(payload);+ if (!sessionId) return;+ const update = normalizeToolUpdatePayload(payload);+ if (!update.toolCallId || !update.beamSearch) return;+ useChatStore.getState().updateToolProgress(sessionId, update.toolCallId, {+ toolName: update.toolName,+ beamSearch: update.beamSearch,+ });+ }),webClient.on('chat.tool_result', ({ payload }) => {const sessionId = resolveEventSessionId(payload);if (!sessionId) return;diff --git a/jiuwenswarm/channels/web/frontend/src/services/webClient.ts b/jiuwenswarm/channels/web/frontend/src/services/webClient.tsindex 96823d7133..13d9b7036f 100644--- a/jiuwenswarm/channels/web/frontend/src/services/webClient.ts+++ b/jiuwenswarm/channels/web/frontend/src/services/webClient.ts@@ -31,6 +31,7 @@ const LEGACY_EVENT_MAP: Record<string, string> = {media_content: 'chat.media',file_content: 'chat.file',tool_call: 'chat.tool_call',+ tool_update: 'chat.tool_update',tool_result: 'chat.tool_result',error: 'chat.error',interrupt_result: 'chat.interrupt_result',diff --git a/jiuwenswarm/channels/web/frontend/src/stores/chatStore.ts b/jiuwenswarm/channels/web/frontend/src/stores/chatStore.tsindex d03089cd62..92b64fb715 100644--- a/jiuwenswarm/channels/web/frontend/src/stores/chatStore.ts+++ b/jiuwenswarm/channels/web/frontend/src/stores/chatStore.ts@@ -23,6 +23,10 @@ import {TodoItem,} from '../types';import { useTodoStore } from './todoStore';+import {+ mergeToolResultProgress,+ shouldDropToolResult,+} from './toolResultLifecycle';const TOOL_TIMEOUT_MS = 12_000_000;const EVOLUTION_STATUS_END_VISIBLE_MS = 3_000;@@ -192,6 +196,7 @@ interface ChatState {setSwitchingMode: (sessionId: string, switching: boolean) => void;setNewSession: (sessionId: string, isNew: boolean) => void;addToolCall: (sessionId: string, toolCall: ToolCall, options?: { startedAt?: string; requestId?: string }) => void;+ updateToolProgress: (sessionId: string, toolCallId: string, progress: Partial<ToolResult>) => void;addToolResult: (sessionId: string, toolResult: ToolResult, options?: { updatedAt?: string }) => void;markTimedOutExecutions: (sessionId: string) => void;updateSubtask: (sessionId: string, payload: SubtaskUpdatePayload) => void;@@ -741,9 +746,11 @@ export const useChatStore = create<ChatState>((set, get) => ({const duplicatedOrphan = nextOrphanResults.get(incomingToolCallId);if (duplicatedOrphan &&- duplicatedOrphan.result === toolResult.result &&- duplicatedOrphan.success === toolResult.success &&- (duplicatedOrphan.summary || '') === (toolResult.summary || '')+ shouldDropToolResult(+ resolveExecutionStatus(duplicatedOrphan),+ duplicatedOrphan,+ toolResult+ )) {const nextDropped = runtime.toolMetrics.toolResultDedupDropped + 1;if (import.meta.env.DEV && (nextDropped === 1 || nextDropped % 10 === 0)) {@@ -774,39 +781,44 @@ export const useChatStore = create<ChatState>((set, get) => ({};}- if (existingExecution.result) {- const duplicated =- existingExecution.result.result === toolResult.result &&- existingExecution.result.success === toolResult.success &&- (existingExecution.result.summary || '') === (toolResult.summary || '');- if (duplicated) {- const nextDropped = runtime.toolMetrics.toolResultDedupDropped + 1;- if (import.meta.env.DEV && (nextDropped === 1 || nextDropped % 10 === 0)) {- console.debug('[ws][metrics] toolResultDedupDropped', {- count: nextDropped,- reason: 'execution duplicate',- });- }- return {- runtimes: {- ...state.runtimes,- [sessionId]: {- ...runtime,- toolMetrics: {- ...runtime.toolMetrics,- toolResultDedupDropped: nextDropped,- },+ const mergedToolResult = mergeToolResultProgress(+ existingExecution.result,+ toolResult+ );+ const nextStatus = resolveExecutionStatus(mergedToolResult);++ if (+ shouldDropToolResult(+ existingExecution.status,+ existingExecution.result,+ mergedToolResult+ )+ ) {+ const nextDropped = runtime.toolMetrics.toolResultDedupDropped + 1;+ if (import.meta.env.DEV && (nextDropped === 1 || nextDropped % 10 === 0)) {+ console.debug('[ws][metrics] toolResultDedupDropped', {+ count: nextDropped,+ reason: 'execution duplicate',+ });+ }+ return {+ runtimes: {+ ...state.runtimes,+ [sessionId]: {+ ...runtime,+ toolMetrics: {+ ...runtime.toolMetrics,+ toolResultDedupDropped: nextDropped,},},- };- }+ },+ };}const nextExecutions = new Map(runtime.toolExecutions);- const nextStatus = resolveExecutionStatus(toolResult);nextExecutions.set(incomingToolCallId, {...existingExecution,- result: toolResult,+ result: mergedToolResult,status: nextStatus,updatedAt,resultArrivedAfterTimeout:@@ -821,6 +833,36 @@ export const useChatStore = create<ChatState>((set, get) => ({});},+ updateToolProgress: (sessionId, toolCallId, progress) => {+ if (!toolCallId) return;+ set((state) => {+ const runtime = state.runtimes[sessionId];+ if (!runtime) return state;+ const execution = runtime.toolExecutions.get(toolCallId);+ if (!execution) return state;+ const nextExecutions = new Map(runtime.toolExecutions);+ nextExecutions.set(toolCallId, {+ ...execution,+ result: {+ toolName: execution.toolCall.name,+ result: '',+ success: true,+ toolCallId,+ ...execution.result,+ ...progress,+ },+ status: 'pending',+ updatedAt: new Date().toISOString(),+ });+ return {+ runtimes: {+ ...state.runtimes,+ [sessionId]: { ...runtime, toolExecutions: nextExecutions },+ },+ };+ });+ },+markTimedOutExecutions: (sessionId) => {const now = Date.now();set((state) => {diff --git a/jiuwenswarm/channels/web/frontend/src/stores/toolResultLifecycle.ts b/jiuwenswarm/channels/web/frontend/src/stores/toolResultLifecycle.tsnew file mode 100644index 0000000000..c361074390--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/stores/toolResultLifecycle.ts@@ -0,0 +1,25 @@+import { ToolExecutionStatus, ToolResult } from '../types';++export function mergeToolResultProgress(existing: ToolResult | undefined, incoming: ToolResult): ToolResult {+ if (incoming.beamSearch || !existing?.beamSearch) {+ return incoming;+ }+ return {+ ...incoming,+ beamSearch: existing.beamSearch,+ };+}++function hasSameResultData(existing: ToolResult, incoming: ToolResult): boolean {+ return (+ existing.result === incoming.result &&+ existing.success === incoming.success &&+ (existing.summary || '') === (incoming.summary || '') &&+ existing.beamSearch === incoming.beamSearch+ );+}++export function shouldDropToolResult(currentStatus: ToolExecutionStatus, existing: ToolResult | undefined, incoming: ToolResult): boolean {+ const finalStatus: ToolExecutionStatus = incoming.success ? 'completed' : 'error';+ return currentStatus === finalStatus && existing !== undefined && hasSameResultData(existing, incoming);+}diff --git a/jiuwenswarm/channels/web/frontend/src/types/beamSearch.ts b/jiuwenswarm/channels/web/frontend/src/types/beamSearch.tsnew file mode 100644index 0000000000..1e8474cf10--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/src/types/beamSearch.ts@@ -0,0 +1,48 @@+export type BeamNodeStatus = 'seed' | 'pending' | 'selected' | 'rejected' | 'final';++export interface BeamSearchNode {+ id: string;+ label: string;+ status: BeamNodeStatus;+ seed?: boolean;+}++export interface BeamSearchEdge {+ source: string;+ target: string;+ status: BeamNodeStatus;+}++export interface BeamSearchGraph {+ nodes: BeamSearchNode[];+ edges: BeamSearchEdge[];+}++export interface BeamSearchProgress {+ language: 'cn' | 'en';+ roundIndex: number;+ graph: BeamSearchGraph;+}++function asRecord(value: unknown): Record<string, unknown> | null {+ return value && typeof value === 'object'+ ? value as Record<string, unknown>+ : null;+}++export function parseBeamSearchProgress(raw: unknown): BeamSearchProgress | undefined {+ const record = asRecord(raw);+ if (!record) return undefined;+ const graph = asRecord(record.graph);+ if (!graph || !Array.isArray(graph.nodes) || !Array.isArray(graph.edges)) {+ return undefined;+ }+ return {+ language: record.language === 'en' ? 'en' : 'cn',+ roundIndex: typeof record.round_index === 'number' ? record.round_index : 0,+ graph: {+ nodes: graph.nodes as BeamSearchNode[],+ edges: graph.edges as BeamSearchEdge[],+ },+ };+}diff --git a/jiuwenswarm/channels/web/frontend/src/types/index.ts b/jiuwenswarm/channels/web/frontend/src/types/index.tsindex a97cd47e6b..d40c05a940 100644--- a/jiuwenswarm/channels/web/frontend/src/types/index.ts+++ b/jiuwenswarm/channels/web/frontend/src/types/index.ts@@ -4,6 +4,7 @@export * from './message';export * from './skillTree';+export * from './beamSearch';export * from './todo';export * from './websocket';export * from '../features/workspace/projectTypes';diff --git a/jiuwenswarm/channels/web/frontend/src/types/message.ts b/jiuwenswarm/channels/web/frontend/src/types/message.tsindex 030abb8bf9..e5ba1dcb7a 100644--- a/jiuwenswarm/channels/web/frontend/src/types/message.ts+++ b/jiuwenswarm/channels/web/frontend/src/types/message.ts@@ -3,6 +3,7 @@*/import type { SkillTreePath } from './skillTree';+import type { BeamSearchProgress } from './beamSearch';export type MessageRole = 'user' | 'assistant' | 'system' | 'tool';@@ -97,6 +98,7 @@ export interface ToolResult {summary?: string; // 结果摘要// agentic search(symphony 技能检索)下发的技能树路径,用于内联回放路径流转skillTree?: SkillTreePath;+ beamSearch?: BeamSearchProgress;}export type ToolExecutionStatus = 'pending' | 'timeout' | 'completed' | 'error';diff --git a/jiuwenswarm/channels/web/frontend/tests/toolResultLifecycle.test.mjs b/jiuwenswarm/channels/web/frontend/tests/toolResultLifecycle.test.mjsnew file mode 100644index 0000000000..ee34045594--- /dev/null+++ b/jiuwenswarm/channels/web/frontend/tests/toolResultLifecycle.test.mjs@@ -0,0 +1,54 @@+import assert from 'node:assert/strict';+import test from 'node:test';++import { mergeToolResultProgress, shouldDropToolResult } from '../node_modules/.cache/tool-result-lifecycle/stores/toolResultLifecycle.js';++const result = (overrides = {}) => ({+ toolName: 'example_tool',+ toolCallId: 'call-1',+ result: 'done',+ success: true,+ ...overrides,+});++test('ordinary tool result is returned unchanged', () => {+ const incoming = result();++ assert.equal(mergeToolResultProgress(result({ result: '' }), incoming), incoming);+});++test('final result inherits the last streamed beam graph when omitted', () => {+ const beamSearch = { roundIndex: 2, graph: { nodes: [], edges: [] } };+ const incoming = result({ toolName: 'symphony_compose_score' });++ assert.deepEqual(mergeToolResultProgress(result({ beamSearch }), incoming), { ...incoming, beamSearch });+});++test('final beam graph replaces the streamed graph', () => {+ const streamed = { roundIndex: 1, graph: { nodes: [], edges: [] } };+ const final = { roundIndex: 2, graph: { nodes: [], edges: [] } };+ const incoming = result({ beamSearch: final });++ assert.equal(mergeToolResultProgress(result({ beamSearch: streamed }), incoming), incoming);+});++test('pending execution is not dropped when identical final result arrives', () => {+ const finalResult = result();++ assert.equal(shouldDropToolResult('pending', finalResult, finalResult), false);+ assert.equal(shouldDropToolResult('completed', finalResult, finalResult), true);+});++test('pending execution is not dropped when an error result arrives', () => {+ const errorResult = result({ success: false });++ assert.equal(shouldDropToolResult('pending', errorResult, errorResult), false);+ assert.equal(shouldDropToolResult('error', errorResult, errorResult), true);+});++test('beam graph participates in duplicate detection', () => {+ const first = result({ beamSearch: { roundIndex: 1, graph: { nodes: [], edges: [] } } });+ const second = result({ beamSearch: { roundIndex: 2, graph: { nodes: [], edges: [] } } });++ assert.equal(shouldDropToolResult('completed', first, second), false);+});diff --git a/jiuwenswarm/extensions/symphony/extension.py b/jiuwenswarm/extensions/symphony/extension.pyindex 67fac5e20d..e6f278232b 100644--- a/jiuwenswarm/extensions/symphony/extension.py+++ b/jiuwenswarm/extensions/symphony/extension.py@@ -20,6 +20,10 @@ from jiuwenswarm.symphony.build import score_statusfrom jiuwenswarm.symphony.orchestration import load_score_artifactsfrom jiuwenswarm.symphony.orchestration.artifacts import filter_disabled_score_artifactsfrom jiuwenswarm.symphony.orchestration.execution_graph import select_primary_plan+from jiuwenswarm.symphony.orchestration.language import (+ default_plan_title,+ resolve_orchestration_language,+)from jiuwenswarm.symphony.orchestration.service import plan_from_scorefrom jiuwenswarm.symphony.score_storage import resolve_score_artifact_dir@@ -97,7 +101,9 @@ class SymphonyExtension(BaseExtension):request: Any = None,) -> dict[str, Any]:params = params or {}- return await self._build_score(params, request, force=_param_bool(params.get("force")))+ return await self._build_score(+ params, request, force=_param_bool(params.get("force"))+ )async def pause_build(self,@@ -131,7 +137,9 @@ class SymphonyExtension(BaseExtension):payload.update(_build_log_payload(score_dir))return payload- async def graph(self, params: dict[str, Any] | None = None, request: Any = None) -> dict[str, Any]:+ async def graph(+ self, params: dict[str, Any] | None = None, request: Any = None+ ) -> dict[str, Any]:del params, requestconfig = load_symphony_config()score_dir = config.paths.score_dir@@ -166,8 +174,9 @@ class SymphonyExtension(BaseExtension):return await asyncio.to_thread(load)- async def plan(self, params: dict[str, Any] | None = None, request: Any = None) -> dict[str, Any]:- del request+ async def plan(+ self, params: dict[str, Any] | None = None, request: Any = None+ ) -> dict[str, Any]:params = params or {}query = str(params.get("query") or "").strip()if not query:@@ -175,6 +184,9 @@ class SymphonyExtension(BaseExtension):candidate_skill_ids = _candidate_skill_ids_from_params(params.get("candidate_skill_ids"))+ language = resolve_orchestration_language(+ get_config().get("preferred_language", "zh")+ )config = load_symphony_config()score_dir = config.paths.score_dirorchestration_config = config.orchestration@@ -197,12 +209,30 @@ class SymphonyExtension(BaseExtension):mode=requested_orchestration_config.mode,)- try:- load_score_artifacts(score_dir)- except FileNotFoundError as exc:- payload = _missing_artifacts_payload(score_dir, exc)- payload.update(_build_log_payload(score_dir))- return payload+ status = await self.score_status(request=request)+ if not status.get("success"):+ return {+ "success": False,+ "detail": "symphony.score_status failed before planning",+ "score_status": status,+ }+ if _score_needs_build(status):+ score_build = await self.build_score(request=request)+ score_build["rebuilt"] = True+ if not score_build.get("success"):+ return {+ "success": False,+ "detail": "symphony.build_score failed before planning",+ "score_status": status,+ "score_build": score_build,+ }+ else:+ score_build = {+ "success": True,+ "rebuilt": False,+ "reason": "not_required",+ }+ progress_callback = _beam_progress_callback(request)payload = await plan_from_score(score_dir,query,@@ -210,6 +240,8 @@ class SymphonyExtension(BaseExtension):orchestration_config=orchestration_config,candidate_skill_ids=candidate_skill_ids,disabled_skill_names=load_execution_disabled_skills(),+ progress_callback=progress_callback,+ language=language,)if payload.get("success") is False:return {@@ -217,23 +249,22 @@ class SymphonyExtension(BaseExtension):"score_dir": str(score_dir),"query": query,"mode": orchestration_config.mode,+ "language": language,+ "score_status": status,+ "score_build": score_build,**payload,}- preferred_language = str(- get_config().get("preferred_language") or "zh"- ).strip().lower()- presentation = _build_presentation(payload, language=preferred_language)+ presentation = _build_presentation(payload, language=language)return {"success": True,"score_dir": str(score_dir),"query": query,"mode": orchestration_config.mode,+ "language": language,"content": presentation["markdown"],- "markdown": presentation["markdown"],- "mermaid": presentation["mermaid"],"direct_display": True,- "display_format": "markdown",- "presentation": presentation,+ "score_status": status,+ "score_build": score_build,"result": payload,}@@ -252,7 +283,11 @@ class SymphonyExtension(BaseExtension):current_task = asyncio.current_task()async with self._build_guard:active_task = self._active_build_task- if active_task is not None and active_task is not current_task and not active_task.done():+ if (+ active_task is not None+ and active_task is not current_task+ and not active_task.done()+ ):payload = {"success": False,"score_dir": str(score_dir),@@ -320,7 +355,21 @@ async def register_extensions(registry):return [extension]-def _missing_artifacts_payload(score_dir: Path, exc: FileNotFoundError) -> dict[str, Any]:+def _score_needs_build(status: dict[str, Any]) -> bool:+ if not bool(status.get("exists", False)) or bool(status.get("stale", False)):+ return True+ for key in ("added_count", "changed_count", "removed_count"):+ try:+ if int(status.get(key) or 0) > 0:+ return True+ except (TypeError, ValueError):+ continue+ return False+++def _missing_artifacts_payload(+ score_dir: Path, exc: FileNotFoundError+) -> dict[str, Any]:return {"success": False,"score_dir": str(score_dir),@@ -339,6 +388,39 @@ def _param_bool(value: Any, default: bool = False) -> bool:return bool(value)+def _beam_progress_callback(request: Any):+ async def callback(event: dict[str, Any]) -> None:+ await _emit_beam_progress_event(request, event)++ return callback+++async def _emit_beam_progress_event(request: Any, event: dict[str, Any]) -> None:+ if request is None:+ return+ payload = {+ "event_type": "symphony.beam_search.update",+ "beam_search_event": event,+ }+ metadata = getattr(request, "metadata", None)+ if isinstance(metadata, dict):+ metadata_callback = metadata.get("symphony_progress_callback")+ if callable(metadata_callback):+ result = metadata_callback(event)+ if asyncio.iscoroutine(result):+ await result+ return++ for name in ("write_stream", "send_event", "send_stream"):+ writer = getattr(request, name, None)+ if not callable(writer):+ continue+ result = writer(payload)+ if asyncio.iscoroutine(result):+ await result+ return++_BUILD_STAGE_LABELS = {"update.start": "开始构建技能总谱","update.pause_requested": "正在暂停技能总谱构建",@@ -492,12 +574,18 @@ def _latest_effective_build_log_entry(entries: list[dict[str, Any]]) -> dict[strif not entries:return {}for entry in reversed(entries):- if str(entry.get("stage") or "") in {"update.done", "update.failed", "update.paused"}:+ if str(entry.get("stage") or "") in {+ "update.done",+ "update.failed",+ "update.paused",+ }:return entryreturn entries[-1]-def _build_token_usage_payload(score_dir: Path, entries: list[dict[str, Any]]) -> dict[str, Any]:+def _build_token_usage_payload(+ score_dir: Path, entries: list[dict[str, Any]]+) -> dict[str, Any]:status = _build_progress(entries).get("status")if status == "running":current = _current_token_usage_summary()@@ -611,10 +699,10 @@ def _compact_details(details: dict[str, Any]) -> str:def _build_presentation(payload: dict[str, Any],*,- language: str = "zh",+ language: str = "cn",) -> dict[str, str]:plan = select_primary_plan(payload)- title = str(plan.get("title") or "Symphony plan").strip()+ title = str(plan.get("title") or default_plan_title(language)).strip()mermaid = _plan_to_mermaid(plan, payload.get("execution_graph") or {})lines = [f"## {title}",@@ -656,12 +744,16 @@ def _plan_to_mermaid(plan: dict[str, Any], graph: dict[str, Any]) -> str:if target and target not in node_ids:node_ids.append(target)if not node_ids:- return "flowchart LR\n none[\"No Symphony plan\"]"+ return 'flowchart LR\n none["No Symphony plan"]'- node_keys = {node_id: f"N{index}" for index, node_id in enumerate(node_ids, start=1)}+ node_keys = {+ node_id: f"N{index}" for index, node_id in enumerate(node_ids, start=1)+ }lines = ["flowchart LR"]for node_id in node_ids:- lines.append(f' {node_keys[node_id]}["{_mermaid_escape(labels.get(node_id) or node_id)}"]')+ lines.append(+ f' {node_keys[node_id]}["{_mermaid_escape(labels.get(node_id) or node_id)}"]'+ )for edge in edges or []:source = str(edge.get("source") or "")target = str(edge.get("target") or "")diff --git a/jiuwenswarm/extensions/symphony/skills/symphony-assistant/SKILL.md b/jiuwenswarm/extensions/symphony/skills/symphony-assistant/SKILL.mdindex 2d262c0174..52d11c66b9 100644--- a/jiuwenswarm/extensions/symphony/skills/symphony-assistant/SKILL.md+++ b/jiuwenswarm/extensions/symphony/skills/symphony-assistant/SKILL.md@@ -17,15 +17,16 @@ Use this skill when a task may benefit from selecting, combining, ordering, or d## Workflow1. If the user says to use skill(s) or 技能, or if skill capabilities, skill chaining, skill ordering, or a specialized toolchain could help, always call `symphony_compose_score` with the original user task as `query`.-2. When installed-skill retrieval is available and can narrow the search space, use `skill_branch_peek` / `skill_branch_explore` first, then pass selected candidate `worker_id` values as `symphony_compose_score.candidate_skill_ids`.-3. Do not manually inspect skill folders or choose the execution chain yourself; Symphony owns ordering and graph composition.-4. Treat `symphony_compose_score` as the planning entrypoint: it reads the Symphony score, refreshes missing or stale scores, and returns the user-facing plan Markdown and Mermaid execution graph.-5. The `symphony_compose_score` result may already be displayed directly to the user; otherwise, present its returned `content` directly.-6. Treat the returned plan, Mermaid graph, structured missing inputs, and caveats as the source of truth.-7. Do not call individual skill tools just to manually recreate or verify the Symphony plan.-8. If Symphony reports missing inputs, ask the user for those inputs instead of inventing them.-9. 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.-10. For clearly ordinary tasks that do not benefit from skill capabilities, do not use Symphony.+2. When you identify, inspect, or recommend installed Skills that are relevant to the task, pass their exact identifiers or names as `symphony_compose_score.candidate_skill_ids`. Do not omit this field after selecting candidate Skills.+3. Select the planning mode from task complexity: use `fast` for simple tasks, short execution chains, or clear candidate skills; use `beam` for complex multi-step tasks, multiple possible skill paths, or tasks that require discovering prerequisite skills through bidirectional search. Omit `mode` to use the configured default.+4. Do not manually inspect skill folders or choose the execution chain yourself; Symphony owns ordering and graph composition.+5. Treat `symphony_compose_score` as the planning entrypoint: it reads the Symphony score, refreshes missing or stale scores, and returns the user-facing plan Markdown and Mermaid execution graph.+6. The `symphony_compose_score` result may already be displayed directly to the user; otherwise, present its returned `content` directly.+7. Treat the returned plan, Mermaid graph, structured missing inputs, and caveats as the source of truth.+8. Do not call individual skill tools just to manually recreate or verify the Symphony plan.+9. If Symphony reports missing inputs, ask the user for those inputs instead of inventing them.+10. 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.+11. For clearly ordinary tasks that do not benefit from skill capabilities, do not use Symphony.## Notesdiff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yamlindex f925e9f905..5898754900 100644--- a/jiuwenswarm/resources/config.yaml+++ b/jiuwenswarm/resources/config.yaml@@ -38,7 +38,10 @@ symphony:min_edge_confidence: 0.1orchestration:+ # fast is the default one-shot path; beam enables bidirectional search.mode: fast+ # Beam-only candidate count retained after each search round.+ top_k: 3max_depth: 4min_edge_confidence: 0.3diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex 1ada7eee63..4124c6a70a 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -11,6 +11,7 @@from __future__ import annotationsimport asyncio+from dataclasses import replaceimport inspectimport jsonimport logging@@ -1479,6 +1480,75 @@ class JiuWenSwarm:metadata=request.metadata,)+ async def _handle_symphony_request_stream(+ self,+ request: AgentRequest,+ ) -> AsyncIterator[AgentResponseChunk]:+ """Stream Symphony RPC progress events, then the final RPC payload."""+ if request.req_method not in _SYMPHONY_METHODS:+ return++ queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue()++ async def progress_callback(event: dict[str, Any]) -> None:+ await queue.put(event)++ metadata = dict(request.metadata or {})+ metadata["symphony_progress_callback"] = progress_callback+ stream_request = replace(request, metadata=metadata)+ task = asyncio.create_task(self._handle_symphony_request(stream_request))++ try:+ while not task.done() or not queue.empty():+ try:+ event = await asyncio.wait_for(queue.get(), timeout=0.1)+ except asyncio.TimeoutError:+ continue+ yield AgentResponseChunk(+ request_id=request.request_id,+ channel_id=request.channel_id,+ payload={+ "event_type": event.get("type")+ or "symphony.beam_search.update",+ "beam_search_event": event,+ },+ is_complete=False,+ )+ response = await task+ except Exception as exc:+ logger.exception("[JiuWenSwarm] Symphony stream failed: %s", exc)+ yield AgentResponseChunk(+ request_id=request.request_id,+ channel_id=request.channel_id,+ payload={"event_type": "chat.error", "error": str(exc)},+ is_complete=False,+ )+ yield AgentResponseChunk(+ request_id=request.request_id,+ channel_id=request.channel_id,+ payload=None,+ is_complete=True,+ )+ return++ payload = dict(response.payload or {}) if response is not None else {}+ payload.setdefault(+ "event_type",+ f"{request.req_method.value if request.req_method else 'symphony'}.result",+ )+ yield AgentResponseChunk(+ request_id=request.request_id,+ channel_id=request.channel_id,+ payload=payload,+ is_complete=False,+ )+ yield AgentResponseChunk(+ request_id=request.request_id,+ channel_id=request.channel_id,+ payload=None,+ is_complete=True,+ )+async def _process_interrupt(self, request: AgentRequest) -> AgentResponse:"""处理 interrupt 请求.@@ -1935,7 +2005,12 @@ class JiuWenSwarm:channel_id=request.channel_id,payload={"event_type": "skilldev.error", "error": str(exc)},is_complete=True,- )+ )+ return++ if request.req_method in _SYMPHONY_METHODS:+ async for chunk in self._handle_symphony_request_stream(request):+ yield chunkreturn# 无状态 RPC(skills / plugins / symphony)不需要 adapter,diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 4ede7ebec9..d97e42205e 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -142,7 +142,7 @@ from jiuwenswarm.agents.harness.common.rails import (ResponsePromptRail,RuntimePromptRail,StructuredAskUserRail,- SymphonyOrchestrationPromptRail,+ SymphonyOrchestrationRail,)from jiuwenswarm.agents.harness.common.rails.execution_guard import (CircuitBreakerRail,@@ -780,7 +780,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 = None+ self._symphony_orchestration_rail = Noneself._skill_retrieval_tools_registered: bool = Falseself._skill_retrieval_tools: list[Any] = []self._skill_retrieval_prompt_rail: SkillRetrievalPromptRail | None = None@@ -3840,17 +3840,17 @@ class JiuWenSwarmDeepAdapter:except (AttributeError, TypeError):pass- def _build_symphony_orchestration_prompt_rail(+ def _build_symphony_orchestration_rail(self,- ) -> SymphonyOrchestrationPromptRail | None:+ ) -> SymphonyOrchestrationRail | None:"""Build dynamic Symphony orchestration prompt guidance."""try:- return SymphonyOrchestrationPromptRail(+ return SymphonyOrchestrationRail(config_base=lambda: self._config_base_cache,)except Exception as exc:logger.warning(- "[JiuWenSwarmDeepAdapter] SymphonyOrchestrationPromptRail create failed: %s",+ "[JiuWenSwarmDeepAdapter] SymphonyOrchestrationRail create failed: %s",exc,)return None@@ -3934,8 +3934,8 @@ class JiuWenSwarmDeepAdapter:rail_infos.insert(4 if self._filesystem_rail_enabled_for_profile() else 3,_RailBuildInfo(- "_symphony_orchestration_prompt_rail",- self._build_symphony_orchestration_prompt_rail,+ "_symphony_orchestration_rail",+ self._build_symphony_orchestration_rail,),)if isinstance(mode, str) and mode.startswith("agent"):diff --git a/jiuwenswarm/symphony/config.py b/jiuwenswarm/symphony/config.pyindex dfe609384a..09c859f76a 100644--- a/jiuwenswarm/symphony/config.py+++ b/jiuwenswarm/symphony/config.py@@ -27,6 +27,7 @@ DEFAULT_BUILD_MIN_EDGE_CONFIDENCE = 0.7DEFAULT_SYMPHONY_ENABLED = FalseDEFAULT_ORCHESTRATION_MODE = "fast"+DEFAULT_ORCHESTRATION_TOP_K = 3DEFAULT_ORCHESTRATION_MAX_DEPTH = 4DEFAULT_ORCHESTRATION_MIN_EDGE_CONFIDENCE = 0.7@@ -77,6 +78,7 @@ class SymphonyBuildConfig:@dataclass(frozen=True)class SymphonyOrchestrationConfig:mode: str = DEFAULT_ORCHESTRATION_MODE+ top_k: int = DEFAULT_ORCHESTRATION_TOP_Kmax_depth: int = DEFAULT_ORCHESTRATION_MAX_DEPTHmin_edge_confidence: float = DEFAULT_ORCHESTRATION_MIN_EDGE_CONFIDENCE@@ -199,6 +201,10 @@ def symphony_config_from_dict(raw: dict[str, Any] | None) -> SymphonyConfig:orchestration.get("mode"),DEFAULT_ORCHESTRATION_MODE,),+ top_k=_positive_int(+ orchestration.get("top_k"),+ DEFAULT_ORCHESTRATION_TOP_K,+ ),max_depth=_positive_int(orchestration.get("max_depth"),DEFAULT_ORCHESTRATION_MAX_DEPTH,@@ -277,6 +283,6 @@ def _orchestration_mode(value: Any, default: str) -> str:text = str(value or "").strip().lower()if not text:return default- if text == "fast":- return "fast"+ if text in {"fast", "beam"}:+ return textraise ValueError(f"Unsupported Symphony orchestration mode: {value}")diff --git a/jiuwenswarm/symphony/orchestration/__init__.py b/jiuwenswarm/symphony/orchestration/__init__.pyindex a1ecd2f481..fed1bf8e67 100644--- a/jiuwenswarm/symphony/orchestration/__init__.py+++ b/jiuwenswarm/symphony/orchestration/__init__.py@@ -6,8 +6,6 @@ from jiuwenswarm.symphony.orchestration.artifacts import ()from jiuwenswarm.symphony.orchestration.planning.models import (ArtifactRef,- GroundedQuery,- InferredInput,OrchestrationPlan,PlanStep,)@@ -15,8 +13,6 @@ from jiuwenswarm.symphony.orchestration.planning.models import (__all__ = ["ArtifactRef","ScoreArtifacts",- "GroundedQuery",- "InferredInput","OrchestrationPlan","PlanStep","load_score_artifacts",diff --git a/jiuwenswarm/symphony/orchestration/language.py b/jiuwenswarm/symphony/orchestration/language.pynew file mode 100644index 0000000000..58d462de1a--- /dev/null+++ b/jiuwenswarm/symphony/orchestration/language.py@@ -0,0 +1,55 @@+"""Language helpers for user-facing Symphony orchestration output."""++from __future__ import annotations++from typing import Any++DEFAULT_ORCHESTRATION_LANGUAGE = "cn"+SUPPORTED_ORCHESTRATION_LANGUAGES = frozenset({"cn", "en"})+++def resolve_orchestration_language(value: Any = None) -> str:+ """Normalize runtime language to the Symphony ``cn | en`` contract."""++ raw = str(value or "").strip().lower()+ if raw == "zh":+ raw = "cn"+ if raw not in SUPPORTED_ORCHESTRATION_LANGUAGES:+ return DEFAULT_ORCHESTRATION_LANGUAGE+ return raw+++def planner_language_instruction(language: str) -> str:+ """Build the shared LLM output-language instruction."""++ normalized = resolve_orchestration_language(language)+ target = "Simplified Chinese" if normalized == "cn" else "English"+ return (+ f"Write all user-visible natural-language fields in {target}. "+ "Keep Skill IDs, original Skill names, status values, enum values, and "+ "structured field names exactly as provided; do not translate them."+ )+++def default_plan_title(language: str) -> str:+ """Return the localized presentation fallback title."""++ if resolve_orchestration_language(language) == "en":+ return "Symphony plan"+ return "Symphony 编排计划"+++def default_fast_no_plan_title(language: str) -> str:+ """Return the localized fast-planner no-plan title."""++ if resolve_orchestration_language(language) == "en":+ return "No Symphony fast plan"+ return "未生成 Symphony 快速编排计划"+++def default_beam_plan_title(language: str) -> str:+ """Return the localized Beam planner fallback title."""++ if resolve_orchestration_language(language) == "en":+ return "Symphony beam plan"+ return "Symphony 束搜索编排计划"diff --git a/jiuwenswarm/symphony/orchestration/planning/__init__.py b/jiuwenswarm/symphony/orchestration/planning/__init__.pyindex 79f73d6eac..6b8a343c27 100644--- a/jiuwenswarm/symphony/orchestration/planning/__init__.py+++ b/jiuwenswarm/symphony/orchestration/planning/__init__.py@@ -2,30 +2,18 @@from jiuwenswarm.symphony.orchestration.planning.models import (ArtifactRef,- GroundedQuery,- GroundingClient,- InferredInput,OrchestrationPlan,PlanStep,)+from jiuwenswarm.symphony.orchestration.planning.beam import BidirectionalBeamPlannerfrom jiuwenswarm.symphony.orchestration.planning.fast import FastOneShotPlanner-from jiuwenswarm.symphony.orchestration.planning.plan_builder import (- compose_dag_plans,- compose_plan_group,- dedupe_plans,- edge_plan_item,-)+from jiuwenswarm.symphony.orchestration.planning.plan_builder import edge_plan_item__all__ = ["ArtifactRef",- "GroundedQuery",- "GroundingClient",- "InferredInput","OrchestrationPlan","PlanStep",+ "BidirectionalBeamPlanner","FastOneShotPlanner",- "compose_dag_plans",- "compose_plan_group",- "dedupe_plans","edge_plan_item",]diff --git a/jiuwenswarm/symphony/orchestration/planning/beam.py b/jiuwenswarm/symphony/orchestration/planning/beam.pynew file mode 100644index 0000000000..e4a01c1b4e--- /dev/null+++ b/jiuwenswarm/symphony/orchestration/planning/beam.py@@ -0,0 +1,1615 @@+"""Bidirectional beam planner for Symphony score orchestration."""++from __future__ import annotations++import asyncio+import hashlib+import json+import logging+import mimetypes+import re+from collections import defaultdict+from dataclasses import dataclass+from typing import Any, Awaitable, Callable, Iterable, Sequence++from jiuwenswarm.symphony.llm import LLMConfig, create_llm_client, llm_usage_context+from jiuwenswarm.symphony.orchestration.artifacts import ScoreArtifacts+from jiuwenswarm.symphony.orchestration.language import (+ default_beam_plan_title,+ planner_language_instruction,+)+from jiuwenswarm.symphony.orchestration.planning.models import (+ OrchestrationPlan,+ SearchState,+)+from jiuwenswarm.symphony.orchestration.planning.plan_builder import (+ build_incoming_edges,+ build_outgoing_edges,+ edge_plan_item,+ state_to_plan,+)+from jiuwenswarm.symphony.orchestration.planning.utils import (+ eligible_can_feed_edges,+ normalize_known_skill_ids,+ skill_id,+ skill_payload,+)++SEMANTIC_SCORE_THRESHOLD = 0.5+SEED_BASELINE_SCORE = 0.5+DEFAULT_MAX_CONCURRENT_JUDGES = 3+BEAM_DEFAULT_MAX_SKILLS = 40+BeamProgressCallback = Callable[[dict[str, Any]], Awaitable[None] | None]+logger = logging.getLogger(__name__)+_EXPLICIT_FILE_EXTENSION_RE = re.compile(+ r"(?<![A-Za-z0-9])[\w.-]+\.([A-Za-z0-9]{1,12})\b"+)+_MIME_TO_OUTPUT_TYPE = {+ "application/json": "json",+ "application/msword": "docx",+ "application/pdf": "pdf",+ "application/vnd.ms-excel": "xlsx",+ "application/vnd.ms-powerpoint": "pptx",+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": (+ "pptx"+ ),+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",+ "text/csv": "csv",+ "text/html": "html",+}+for _extension, _mime_type in {+ ".doc": "application/msword",+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ ".ppt": "application/vnd.ms-powerpoint",+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",+ ".xls": "application/vnd.ms-excel",+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+}.items():+ mimetypes.add_type(_mime_type, _extension)++BEAM_JUDGE_SYSTEM_PROMPT = """You are Symphony's bidirectional beam expansion judge.+Return strict JSON only.++You receive:+- The user's query.+- The current Skill being expanded.+- A search direction: forward or backward.+- Candidate Skills already validated by existing can_feed edges.++Task:+- Score each candidate from 0.0 to 1.0 for usefulness to the user's query and+ the local Skill chain represented by the current Skill and search direction.+- Treat data dependency as already validated; do not judge edge feasibility.+- Do not invent Skills, inputs, outputs, or edge relationships.++Schema:+{+ "judgements": [+ {"candidate_id": "candidate-id", "score": 0.0, "reason": "short reason"}+ ]+}+"""++BEAM_FINAL_RERANK_SYSTEM_PROMPT = """You are a final task orchestration reranker.+Return strict JSON only.++You receive the user's query, candidate plans produced by bidirectional beam+search, a candidate Skill pool, and the existing can_feed edges available among+those Skills.++Task:+- Select the best plan for completing the user's task.+- Candidate plans are references, not hard constraints. You may combine Skills+ from different plans or remove duplicate-function Skills.+- Use only Skill IDs from candidate_skill_pool.+- Use only edges from candidate_can_feed_edges. Skills without a dependency edge+ may remain parallel steps in the same plan.+- Preserve distinct Skills needed for multi-stage or multi-deliverable tasks.+- Prefer the shortest plan that covers the user's intent.+- Do not invent Skills, inputs, outputs, dependencies, or artifacts.+- Keep each reason <= 50 Chinese characters or <= 12 English words.++Schema:+{+ "selected_plan_index": 1,+ "reason": "short reason",+ "steps": [+ {"skill_id": "skill-a", "reason": "short reason"}+ ],+ "can_feed_edges": [+ {"source_id": "skill-a", "target_id": "skill-b"}+ ]+}+"""+++@dataclass(frozen=True)+class BeamState:+ """One bidirectional beam search state."""++ skill_ids: tuple[str, ...]+ edge_indices: tuple[int, ...]+ semantic_scores: tuple[float, ...]+ score_reasons: tuple[str, ...]+ seed_skill_ids: tuple[str, ...]+ last_direction: str++ @property+ def depth(self) -> int:+ return len(self.skill_ids)++ @property+ def head(self) -> str:+ return self.skill_ids[0]++ @property+ def tail(self) -> str:+ return self.skill_ids[-1]++ def to_search_state(self) -> SearchState:+ return SearchState(+ skill_ids=self.skill_ids,+ edges=self.edge_indices,+ score_reasons=self.score_reasons,+ )+++@dataclass(frozen=True)+class NeighborExpansion:+ """A single adjacent Skill candidate to be judged."""++ candidate_id: str+ state: BeamState+ direction: str+ current_skill_id: str+ candidate_skill_id: str+ edge_index: int+++@dataclass(frozen=True)+class SemanticJudgement:+ """LLM judgement for one neighbor expansion."""++ candidate_id: str+ score: float+ reason: str+++_GRAPH_STATUS_PRIORITY = {+ "pending": 0,+ "rejected": 1,+ "seed": 2,+ "selected": 3,+ "final": 4,+}+++class BeamSearchGraph:+ """Lightweight search graph for user-facing beam progress."""++ def __init__(+ self,+ skill_by_id: dict[str, dict[str, Any]],+ ) -> None:+ self.skill_by_id = skill_by_id+ self.nodes: dict[str, dict[str, Any]] = {}+ self.graph_edges: dict[str, dict[str, Any]] = {}++ def add_seed(self, current_skill_id: str) -> None:+ self._ensure_node(current_skill_id, status="seed", seed=True)++ def add_candidate(self, expansion: NeighborExpansion) -> None:+ self._ensure_node(+ expansion.current_skill_id,+ status="seed" if self._is_seed(expansion.current_skill_id) else "selected",+ )+ self._ensure_node(+ expansion.candidate_skill_id,+ status="pending",+ )+ self._ensure_edge(expansion, status="pending")++ def apply_judgement(+ self,+ expansion: NeighborExpansion,+ judgement: SemanticJudgement,+ ) -> None:+ status = (+ "selected" if judgement.score >= SEMANTIC_SCORE_THRESHOLD else "rejected"+ )+ self._ensure_node(+ expansion.candidate_skill_id,+ status=status,+ )+ self._ensure_edge(expansion, status=status)++ def mark_final_plan(self, plan: dict[str, Any]) -> None:+ for step in plan.get("steps") or []:+ if not isinstance(step, dict):+ continue+ current_skill_id = str(step.get("skill_id") or "").strip()+ if not current_skill_id:+ continue+ self._ensure_node(current_skill_id, status="final")+ for edge in plan.get("can_feed_edges") or []:+ if not isinstance(edge, dict):+ continue+ source_id = str(edge.get("source_id") or edge.get("source") or "").strip()+ target_id = str(edge.get("target_id") or edge.get("target") or "").strip()+ edge_id = self._existing_edge_id(source_id, target_id)+ if not edge_id:+ continue+ self.graph_edges[edge_id]["status"] = _dominant_status(+ str(self.graph_edges[edge_id].get("status") or ""),+ "final",+ )++ def snapshot(self) -> dict[str, Any]:+ nodes = []+ for node in self.nodes.values():+ nodes.append(+ {+ "id": node["id"],+ "label": node["label"],+ "status": node["status"],+ "seed": bool(node.get("seed")),+ }+ )+ edges = [_copy_public_graph_edge(edge) for edge in self.graph_edges.values()]+ return {"nodes": nodes, "edges": edges}++ def _ensure_node(+ self,+ current_skill_id: str,+ *,+ status: str,+ seed: bool = False,+ ) -> None:+ node = self.nodes.get(current_skill_id)+ if node is None:+ node = {+ "id": current_skill_id,+ "label": _skill_label(self.skill_by_id.get(current_skill_id, {})),+ "status": status,+ "seed": seed,+ }+ self.nodes[current_skill_id] = node+ else:+ node["status"] = _dominant_status(str(node.get("status") or ""), status)+ node["seed"] = bool(node.get("seed")) or seed+ return node++ def _ensure_edge(+ self,+ expansion: NeighborExpansion,+ *,+ status: str,+ ) -> dict[str, Any]:+ source_id = expansion.current_skill_id+ target_id = expansion.candidate_skill_id+ edge_id = f"{source_id}->{target_id}"+ graph_edge = self.graph_edges.get(edge_id)+ if graph_edge is None:+ graph_edge = {+ "id": edge_id,+ "source": source_id,+ "target": target_id,+ "status": status,+ }+ self.graph_edges[edge_id] = graph_edge+ else:+ graph_edge["status"] = _dominant_status(+ str(graph_edge.get("status") or ""),+ status,+ )++ def _existing_edge_id(self, source_id: str, target_id: str) -> str:+ forward_id = f"{source_id}->{target_id}"+ if forward_id in self.graph_edges:+ return forward_id+ backward_id = f"{target_id}->{source_id}"+ if backward_id in self.graph_edges:+ return backward_id+ return ""++ def _is_seed(self, current_skill_id: str) -> bool:+ node = self.nodes.get(current_skill_id)+ return bool(node and node.get("seed"))+++class BidirectionalBeamPlanner:+ """Build candidate plans through semantic bidirectional beam search."""++ def __init__(+ self,+ artifacts: ScoreArtifacts,+ *,+ llm_config: LLMConfig | None,+ llm_client: Any | None,+ min_edge_confidence: float,+ top_k: int,+ max_depth: int,+ candidate_skill_ids: Sequence[str] | None = None,+ max_concurrent_judges: int = DEFAULT_MAX_CONCURRENT_JUDGES,+ progress_callback: BeamProgressCallback | None = None,+ language: str = "cn",+ ) -> None:+ self.artifacts = artifacts+ self.llm_config = llm_config+ self.llm_client = llm_client+ self.min_edge_confidence = min_edge_confidence+ self.top_k = max(1, int(top_k))+ self.max_depth = max(1, int(max_depth))+ self.max_concurrent_judges = max(1, int(max_concurrent_judges))+ self.skill_by_id = artifacts.skill_by_id+ self.candidate_skill_ids = normalize_known_skill_ids(+ candidate_skill_ids,+ known_skill_ids=set(self.skill_by_id),+ )+ self.progress_callback = progress_callback+ self.language = language+ self.eligible_edges = self._sorted_eligible_edges()+ self._beam_graph = BeamSearchGraph(self.skill_by_id)+ self.outgoing_edges = build_outgoing_edges(self.eligible_edges)+ self.incoming_edges = build_incoming_edges(self.eligible_edges)+ self._judgement_cache: dict[tuple[str, str, str, str], SemanticJudgement] = {}+ self._cache_hits = 0+ self._cache_misses = 0+ self._judge_semaphore = asyncio.Semaphore(self.max_concurrent_judges)+ self._llm_call_count = 0+ self._final_rerank_call_count = 0+ self._judge_failures: list[str] = []+ self.required_output_types: frozenset[str] = frozenset()+ self._current_expansions: dict[str, NeighborExpansion] = {}+ self._current_expansion_aliases: dict[str, list[str]] = {}++ async def plan(self, query: str) -> dict[str, Any]:+ self._reset_beam_progress()+ self._final_rerank_call_count = 0+ self.required_output_types = _required_output_types_from_query(query)+ query_signature = _query_signature(query)+ frontier = self._initial_states()+ all_states = list(frontier)+ seed_skill_ids = tuple(state.skill_ids[0] for state in frontier)+ for current_skill_id in seed_skill_ids:+ self._beam_graph.add_seed(current_skill_id)+ await self._emit_beam_event(+ "started",+ round_index=0,+ graph=self._beam_graph.snapshot(),+ )+ round_index = 0++ for _round in range(max(0, self.max_depth - 1)):+ groups, cached = self._expansion_groups(query_signature, frontier)+ found = self._record_candidates_found()+ if found:+ await self._emit_beam_event(+ "candidates_found",+ round_index=_round + 1,+ graph=self._beam_graph.snapshot(),+ )+ if not groups and not cached:+ break+ fresh = await self._judge_groups(query, groups)+ fresh = self._apply_judgement_aliases(fresh)+ for candidate_id, judgement in fresh.items():+ expansion = self._expansion_by_id(candidate_id)+ if expansion is not None:+ self._cache_set(query_signature, expansion, judgement)+ judgements = {**cached, **fresh}+ judged = self._record_candidates_judged(judgements)+ if judged:+ await self._emit_beam_event(+ "candidates_judged",+ round_index=_round + 1,+ graph=self._beam_graph.snapshot(),+ )+ next_states = self._apply_judgements(judgements)+ if not next_states:+ await self._emit_beam_event(+ "graph_merged",+ round_index=_round + 1,+ graph=self._beam_graph.snapshot(),+ )+ round_index = _round + 1+ break+ retained = self._rank_and_trim(next_states, limit=self.top_k)+ all_states = retained+ frontier = retained+ round_index = _round + 1+ await self._emit_beam_event(+ "graph_merged",+ round_index=_round + 1,+ graph=self._beam_graph.snapshot(),+ )++ final_states = self._merge_converged_states(all_states)+ plans = self._plans_from_states(final_states)[: self.top_k]+ recommended_plans = [self._plan_payload(plan, query=query) for plan in plans]+ final_rerank = await self._final_rerank_plans(+ query=query,+ recommended_plans=recommended_plans,+ seed_skill_ids=seed_skill_ids,+ )+ recommended_plans = final_rerank["recommended_plans"]+ final_plan = recommended_plans[0] if recommended_plans else {}+ self._beam_graph.mark_final_plan(final_plan)+ await self._emit_beam_event(+ "completed",+ round_index=round_index,+ graph=self._beam_graph.snapshot(),+ )+ status = recommended_plans[0]["status"] if recommended_plans else "no_plan"+ reason = recommended_plans[0].get("reason", "") if recommended_plans else ""+ unique_skill_ids = {+ current_skill_id+ for state in all_states+ for current_skill_id in state.skill_ids+ }+ return {+ "query": query,+ "language": self.language,+ "score_dir": str(self.artifacts.score_dir),+ "planning_mode": "bidirectional_beam",+ "llm_call_count": self._llm_call_count + self._final_rerank_call_count,+ "candidate_skill_count": len(unique_skill_ids),+ "candidate_edge_count": len(self.eligible_edges),+ "plans": recommended_plans,+ "recommended_plans": recommended_plans,+ "ranking_mode": "bidirectional_beam",+ "beam_search": {+ "mode": "bidirectional_beam",+ "language": self.language,+ "round_index": round_index,+ "graph": self._beam_graph.snapshot(),+ },+ "decision": {+ "mode": "bidirectional_beam",+ "strategy": "semantic_bidirectional_beam",+ "validated_count": len(recommended_plans),+ "candidate_count": len(unique_skill_ids),+ "judge_llm_call_count": self._llm_call_count,+ "judge_cache_hits": self._cache_hits,+ "judge_cache_misses": self._cache_misses,+ "final_rerank": {+ "applied": final_rerank["applied"],+ "llm_call_count": self._final_rerank_call_count,+ "cross_plan_skill_merge": final_rerank["cross_plan_skill_merge"],+ "error": final_rerank["error"],+ },+ },+ "validation": {+ "valid": True,+ "details": self._judge_failures[:10],+ },+ "status": status,+ "reason": reason,+ }++ async def judge_expansions(+ self,+ query: str,+ expansions: list[NeighborExpansion],+ ) -> dict[str, SemanticJudgement]:+ if not expansions:+ return {}++ first = expansions[0]+ current_skill = self.skill_by_id.get(first.current_skill_id, {})+ payload = {+ "query": query,+ "direction": first.direction,+ "current_skill": skill_payload(current_skill),+ "candidates": [+ self._candidate_payload(expansion) for expansion in expansions+ ],+ }+ with llm_usage_context("orchestration", "bidirectional_beam_judgement"):+ raw = await self._client().complete_json_async(+ system_prompt=(+ f"{BEAM_JUDGE_SYSTEM_PROMPT}\n"+ f"{planner_language_instruction(self.language)}"+ ),+ user_content=json.dumps(payload, ensure_ascii=False),+ error_context="Symphony bidirectional beam judgement",+ )+ data = json.loads(raw)+ items = data.get("judgements") if isinstance(data, dict) else data+ if not isinstance(items, list):+ return {}++ known_ids = {expansion.candidate_id for expansion in expansions}+ judgements: dict[str, SemanticJudgement] = {}+ for item in items:+ if not isinstance(item, dict):+ continue+ candidate_id = str(item.get("candidate_id") or "").strip()+ if candidate_id not in known_ids:+ continue+ score = _clamp_score(item.get("score"))+ judgements[candidate_id] = SemanticJudgement(+ candidate_id=candidate_id,+ score=score,+ reason=str(item.get("reason") or "").strip(),+ )+ return judgements++ async def _final_rerank_plans(+ self,+ *,+ query: str,+ recommended_plans: list[dict[str, Any]],+ seed_skill_ids: tuple[str, ...],+ ) -> dict[str, Any]:+ base = {+ "applied": False,+ "error": "",+ "cross_plan_skill_merge": False,+ "recommended_plans": recommended_plans[: self.top_k],+ }+ if not recommended_plans:+ return base++ payload = self._final_rerank_payload(+ query=query,+ recommended_plans=recommended_plans,+ seed_skill_ids=seed_skill_ids,+ )+ self._final_rerank_call_count += 1+ try:+ with llm_usage_context("orchestration", "beam_final_rerank"):+ raw = await self._client().complete_json_async(+ system_prompt=(+ f"{BEAM_FINAL_RERANK_SYSTEM_PROMPT}\n"+ f"{planner_language_instruction(self.language)}"+ ),+ user_content=json.dumps(payload, ensure_ascii=False),+ error_context="Symphony beam final rerank",+ request_overrides={+ "extra_body": {"thinking": {"type": "disabled"}}+ },+ )+ selection = json.loads(raw)+ except Exception as exc:+ return {**base, "error": f"{type(exc).__name__}: {exc}"}+ if not isinstance(selection, dict):+ return {**base, "error": "Final rerank returned non-object JSON."}++ materialized = self._materialize_final_rerank(+ selection,+ query=query,+ recommended_plans=recommended_plans,+ )+ if not materialized["valid"]:+ return {**base, "error": materialized["detail"]}++ primary_plan = materialized["plan"]+ output = [primary_plan]+ seen = {_dict_plan_signature(primary_plan)}+ for plan in recommended_plans:+ signature = _dict_plan_signature(plan)+ if signature in seen:+ continue+ output.append(plan)+ seen.add(signature)+ if len(output) >= self.top_k:+ break+ return {+ **base,+ "applied": True,+ "cross_plan_skill_merge": materialized["cross_plan_skill_merge"],+ "recommended_plans": output,+ }++ def _final_rerank_payload(+ self,+ *,+ query: str,+ recommended_plans: list[dict[str, Any]],+ seed_skill_ids: tuple[str, ...],+ ) -> dict[str, Any]:+ candidate_skill_ids = _candidate_plan_skill_ids(recommended_plans)+ return {+ "query": query,+ "required_output_types": sorted(self.required_output_types),+ "candidate_skill_pool": self._candidate_skill_pool_for_rerank(+ candidate_skill_ids,+ seed_skill_ids=seed_skill_ids,+ ),+ "candidate_can_feed_edges": self._candidate_edges_for_rerank(+ candidate_skill_ids+ ),+ "candidate_plans": [+ self._compact_plan_for_rerank(plan, plan_index=index)+ for index, plan in enumerate(recommended_plans, start=1)+ ],+ }++ def _candidate_skill_pool_for_rerank(+ self,+ candidate_skill_ids: set[str],+ *,+ seed_skill_ids: tuple[str, ...],+ ) -> list[dict[str, Any]]:+ seed_skill_id_set = set(seed_skill_ids)+ output = []+ for current_skill_id in sorted(candidate_skill_ids):+ skill = self.skill_by_id.get(current_skill_id)+ if not skill:+ continue+ output.append(+ {+ **skill_payload(skill),+ "is_seed": current_skill_id in seed_skill_id_set,+ "outputs": [+ {+ "name": str(item.get("name") or ""),+ "type": str(item.get("type") or "unknown"),+ }+ for item in skill.get("outputs") or []+ if isinstance(item, dict) and item.get("name")+ ],+ }+ )+ return output++ def _candidate_edges_for_rerank(+ self,+ candidate_skill_ids: set[str],+ ) -> list[dict[str, Any]]:+ output = []+ for edge in self.eligible_edges:+ source_id = skill_id(edge.get("source"))+ target_id = skill_id(edge.get("target"))+ if source_id not in candidate_skill_ids:+ continue+ if target_id not in candidate_skill_ids:+ continue+ output.append(+ {+ "source_id": source_id,+ "target_id": target_id,+ "confidence": edge.get("confidence"),+ }+ )+ return output++ @staticmethod+ def _compact_plan_for_rerank(+ plan: dict[str, Any],+ *,+ plan_index: int,+ ) -> dict[str, Any]:+ return {+ "plan_index": plan_index,+ "skills": list(_dict_plan_signature(plan)),+ "missing_input_count": len(plan.get("missing_inputs") or []),+ "status": plan.get("status"),+ }++ def _materialize_final_rerank(+ self,+ selection: dict[str, Any],+ *,+ query: str,+ recommended_plans: list[dict[str, Any]],+ ) -> dict[str, Any]:+ selected_index = _positive_int(selection.get("selected_plan_index")) or 1+ selected_index = min(selected_index, len(recommended_plans))++ selected_plan = recommended_plans[selected_index - 1]+ raw_steps = selection.get("steps")+ if raw_steps is None:+ return {+ "valid": True,+ "detail": "",+ "cross_plan_skill_merge": False,+ "plan": {+ **selected_plan,+ "reason": _short_text(str(selection.get("reason") or ""))+ or selected_plan.get("reason", ""),+ "source": "bidirectional_beam_final_rerank",+ },+ }++ allowed_skill_ids = _candidate_plan_skill_ids(recommended_plans)+ step_ids = []+ for current_skill_id in _normalize_rerank_step_ids(raw_steps):+ if current_skill_id not in allowed_skill_ids:+ continue+ if current_skill_id not in self.skill_by_id:+ continue+ step_ids.append(current_skill_id)+ if not step_ids:+ return {+ "valid": True,+ "detail": "",+ "cross_plan_skill_merge": False,+ "plan": selected_plan,+ }++ edge_result = _normalize_rerank_edges(selection.get("can_feed_edges"))+ selected_edges = edge_result["edges"]+ if selection.get("can_feed_edges") is None:+ selected_edges = self._default_rerank_edges(step_ids)+ step_set = set(step_ids)+ eligible_edge_keys = {+ (skill_id(edge.get("source")), skill_id(edge.get("target")))+ for edge in self.eligible_edges+ }+ order = {+ current_skill_id: index for index, current_skill_id in enumerate(step_ids)+ }+ filtered_edges = []+ for edge in selected_edges:+ if edge[0] not in step_set or edge[1] not in step_set:+ continue+ if edge not in eligible_edge_keys:+ continue+ if order[edge[0]] >= order[edge[1]]:+ continue+ filtered_edges.append(edge)+ selected_edges = filtered_edges++ return {+ "valid": True,+ "detail": "",+ "cross_plan_skill_merge": not set(step_ids)+ <= set(_dict_plan_signature(selected_plan)),+ "plan": self._final_rerank_plan_payload(+ selection,+ query=query,+ step_ids=step_ids,+ selected_edges=selected_edges,+ recommended_plans=recommended_plans,+ ),+ }++ def _default_rerank_edges(+ self,+ step_ids: list[str],+ ) -> list[tuple[str, str]]:+ order = {+ current_skill_id: index for index, current_skill_id in enumerate(step_ids)+ }+ output = []+ for item in self.eligible_edges:+ edge = (skill_id(item.get("source")), skill_id(item.get("target")))+ if (+ edge[0] in order+ and edge[1] in order+ and order[edge[0]] < order[edge[1]]+ ):+ output.append(edge)+ return output++ def _final_rerank_plan_payload(+ self,+ selection: dict[str, Any],+ *,+ query: str,+ step_ids: list[str],+ selected_edges: list[tuple[str, str]],+ recommended_plans: list[dict[str, Any]],+ ) -> dict[str, Any]:+ source_steps = _plan_steps_by_skill(recommended_plans)+ step_reasons = _step_reasons_by_skill(selection.get("steps"))+ steps = []+ produced_artifacts = []+ for index, current_skill_id in enumerate(step_ids, start=1):+ skill = self.skill_by_id[current_skill_id]+ source_step = source_steps.get(current_skill_id, {})+ outputs = list(skill.get("outputs") or [])+ produced_artifacts.extend(+ {+ "name": item.get("name"),+ "type": item.get("type") or "unknown",+ "source": "skill_output",+ }+ for item in outputs+ if isinstance(item, dict) and item.get("name")+ )+ steps.append(+ {+ "step": index,+ "skill_id": current_skill_id,+ "name": str(skill.get("name") or current_skill_id),+ "inputs": list(skill.get("inputs") or []),+ "outputs": outputs,+ "missing_inputs": list(source_step.get("missing_inputs") or []),+ "filled_inputs": list(source_step.get("filled_inputs") or []),+ "reason": step_reasons.get(current_skill_id, ""),+ }+ )+ raw_missing_inputs = []+ for step in steps:+ for item in step.get("missing_inputs") or []:+ if isinstance(item, dict):+ raw_missing_inputs.append(item)+ missing_inputs = _dedupe_dict_items(raw_missing_inputs)+ edge_by_key = {+ (skill_id(edge.get("source")), skill_id(edge.get("target"))): edge+ for edge in self.eligible_edges+ }+ edge_items = [edge_plan_item(edge_by_key[edge]) for edge in selected_edges]+ status = "needs_input" if missing_inputs else "ready"+ reason = _short_text(str(selection.get("reason") or ""))+ return {+ "title": _query_plan_title(query, language=self.language),+ "status": status,+ "steps": steps,+ "stages": _rerank_plan_stages(steps, edge_items),+ "produced_artifacts": _dedupe_dict_items(produced_artifacts),+ "missing_inputs": missing_inputs,+ "can_feed_edges": edge_items,+ "reason": reason,+ "reasons": [reason] if reason else [],+ "plan_classification": (+ "executable"+ if status == "ready"+ else "structurally_valid_but_incomplete"+ ),+ "connectivity_trace": ["can_feed"] if edge_items else [],+ "source": "bidirectional_beam_final_rerank",+ }++ def _client(self) -> Any:+ if self.llm_client is not None:+ return self.llm_client+ if self.llm_config is None:+ raise ValueError(+ "beam Symphony planning requires llm_config or llm_client."+ )+ self.llm_client = create_llm_client(self.llm_config)+ return self.llm_client++ async def _judge_groups(+ self,+ query: str,+ groups: list[list[NeighborExpansion]],+ ) -> dict[str, SemanticJudgement]:+ tasks = [self._judge_group(query, group) for group in groups if group]+ if not tasks:+ return {}+ output: dict[str, SemanticJudgement] = {}+ for result in await asyncio.gather(*tasks):+ output.update(result)+ return output++ async def _judge_group(+ self,+ query: str,+ group: list[NeighborExpansion],+ ) -> dict[str, SemanticJudgement]:+ async with self._judge_semaphore:+ self._llm_call_count += 1+ try:+ return await self.judge_expansions(query, group)+ except Exception as exc:+ candidates = ", ".join(item.candidate_id for item in group[:5])+ self._judge_failures.append(+ f"beam judge failed for candidates [{candidates}]: {exc}"+ )+ return {}++ @staticmethod+ def _cache_key(+ query_signature: str,+ expansion: NeighborExpansion,+ ) -> tuple[str, str, str, str]:+ return (+ query_signature,+ expansion.direction,+ expansion.current_skill_id,+ expansion.candidate_skill_id,+ )++ def _cache_get(+ self,+ query_signature: str,+ expansion: NeighborExpansion,+ ) -> SemanticJudgement | None:+ cached = self._judgement_cache.get(self._cache_key(query_signature, expansion))+ if cached is None:+ self._cache_misses += 1+ else:+ self._cache_hits += 1+ return cached++ def _cache_set(+ self,+ query_signature: str,+ expansion: NeighborExpansion,+ judgement: SemanticJudgement,+ ) -> None:+ self._judgement_cache[self._cache_key(query_signature, expansion)] = judgement++ def _initial_states(self) -> list[BeamState]:+ seeds = self.candidate_skill_ids or self._default_seed_skill_ids()+ states = [+ BeamState(+ skill_ids=(current_skill_id,),+ edge_indices=(),+ semantic_scores=(),+ score_reasons=(),+ seed_skill_ids=tuple(seeds),+ last_direction="seed",+ )+ for current_skill_id in seeds+ if current_skill_id in self.skill_by_id+ ]+ return self._rank_and_trim(states, limit=self.top_k)++ def _default_seed_skill_ids(self) -> tuple[str, ...]:+ output: list[str] = []+ seen: set[str] = set()+ for edge in self.eligible_edges:+ for key in ("source", "target"):+ current_skill_id = skill_id(edge.get(key))+ if (+ current_skill_id+ and current_skill_id in self.skill_by_id+ and current_skill_id not in seen+ ):+ seen.add(current_skill_id)+ output.append(current_skill_id)+ if len(output) >= BEAM_DEFAULT_MAX_SKILLS:+ return tuple(output)+ if output:+ return tuple(output)+ for skill in self.artifacts.skills[:BEAM_DEFAULT_MAX_SKILLS]:+ current_skill_id = str(skill.get("id") or "").strip()+ if current_skill_id:+ output.append(current_skill_id)+ return tuple(output)++ def _expansion_groups(+ self,+ query_signature: str,+ states: list[BeamState],+ ) -> tuple[list[list[NeighborExpansion]], dict[str, SemanticJudgement]]:+ groups: list[list[NeighborExpansion]] = []+ cached: dict[str, SemanticJudgement] = {}+ current_expansions: dict[str, NeighborExpansion] = {}+ pending_keys: dict[tuple[str, str, str], str] = {}+ aliases: dict[str, list[str]] = defaultdict(list)+ for state in states:+ for direction, current_skill_id in (+ ("forward", state.tail),+ ("backward", state.head),+ ):+ expansions = self._neighbor_expansions(+ state=state,+ direction=direction,+ current_skill_id=current_skill_id,+ )+ misses = []+ for expansion in expansions:+ current_expansions[expansion.candidate_id] = expansion+ judgement = self._cache_get(query_signature, expansion)+ if judgement is None:+ misses.append(expansion)+ else:+ cached[expansion.candidate_id] = judgement+ if misses:+ deduped_misses = []+ for expansion in misses:+ key = self._cache_key(query_signature, expansion)+ existing_candidate_id = pending_keys.get(key)+ if existing_candidate_id is not None:+ aliases[existing_candidate_id].append(+ expansion.candidate_id+ )+ continue+ pending_keys[key] = expansion.candidate_id+ deduped_misses.append(expansion)+ if deduped_misses:+ groups.append(deduped_misses)+ self._current_expansions = current_expansions+ self._current_expansion_aliases = aliases+ return groups, cached++ def _apply_judgement_aliases(+ self,+ judgements: dict[str, SemanticJudgement],+ ) -> dict[str, SemanticJudgement]:+ output = dict(judgements)+ for source_id, alias_ids in self._current_expansion_aliases.items():+ judgement = judgements.get(source_id)+ if judgement is None:+ continue+ for alias_id in alias_ids:+ output[alias_id] = SemanticJudgement(+ candidate_id=alias_id,+ score=judgement.score,+ reason=judgement.reason,+ )+ return output++ def _neighbor_expansions(+ self,+ *,+ state: BeamState,+ direction: str,+ current_skill_id: str,+ ) -> list[NeighborExpansion]:+ if state.depth >= self.max_depth:+ return []+ edge_indices = (+ self.outgoing_edges.get(current_skill_id, [])+ if direction == "forward"+ else self.incoming_edges.get(current_skill_id, [])+ )+ expansions = []+ for edge_index in edge_indices:+ edge = self.eligible_edges[edge_index]+ candidate_skill_id = (+ skill_id(edge.get("target"))+ if direction == "forward"+ else skill_id(edge.get("source"))+ )+ if (+ not candidate_skill_id+ or candidate_skill_id not in self.skill_by_id+ or candidate_skill_id in state.skill_ids+ ):+ continue+ expansions.append(+ NeighborExpansion(+ candidate_id=(+ f"{direction}:{edge_index}:"+ f"{_state_signature(state)}:{candidate_skill_id}"+ ),+ state=state,+ direction=direction,+ current_skill_id=current_skill_id,+ candidate_skill_id=candidate_skill_id,+ edge_index=edge_index,+ )+ )+ return expansions++ def _apply_judgements(+ self,+ judgements: dict[str, SemanticJudgement],+ ) -> list[BeamState]:+ output = []+ for candidate_id, judgement in judgements.items():+ if judgement.score < SEMANTIC_SCORE_THRESHOLD:+ continue+ expansion = self._expansion_by_id(candidate_id)+ if expansion is None:+ continue+ state = expansion.state+ if expansion.direction == "forward":+ skill_ids = (*state.skill_ids, expansion.candidate_skill_id)+ edge_indices = (*state.edge_indices, expansion.edge_index)+ else:+ skill_ids = (expansion.candidate_skill_id, *state.skill_ids)+ edge_indices = (expansion.edge_index, *state.edge_indices)+ output.append(+ BeamState(+ skill_ids=skill_ids,+ edge_indices=edge_indices,+ semantic_scores=(*state.semantic_scores, judgement.score),+ score_reasons=_append_unique(+ state.score_reasons,+ judgement.reason,+ ),+ seed_skill_ids=state.seed_skill_ids,+ last_direction=expansion.direction,+ )+ )+ return output++ def _expansion_by_id(self, candidate_id: str) -> NeighborExpansion | None:+ return self._current_expansions.get(candidate_id)++ def _reset_beam_progress(self) -> None:+ self._beam_graph = BeamSearchGraph(self.skill_by_id)++ async def _emit_beam_event(+ self,+ event: str,+ *,+ round_index: int,+ graph: dict[str, Any],+ ) -> None:+ item = {+ "event": event,+ "language": self.language,+ "round_index": round_index,+ "graph": graph,+ }+ if self.progress_callback is None:+ return+ try:+ result = self.progress_callback(item)+ if asyncio.iscoroutine(result):+ await result+ except Exception as exc:+ logger.debug("beam progress callback failed: %s", exc)++ def _record_candidates_found(self) -> bool:+ expansions = _sorted_expansions(self._current_expansions.values())+ for expansion in expansions:+ self._beam_graph.add_candidate(expansion)+ return bool(expansions)++ def _record_candidates_judged(+ self,+ judgements: dict[str, SemanticJudgement],+ ) -> bool:+ found = False+ for candidate_id in sorted(judgements):+ expansion = self._expansion_by_id(candidate_id)+ if expansion is None:+ continue+ self._beam_graph.apply_judgement(+ expansion,+ judgements[candidate_id],+ )+ found = True+ return found++ def _plans_from_states(self, states: list[BeamState]) -> list[OrchestrationPlan]:+ state_plans = [+ (+ state,+ state_to_plan(+ state=state.to_search_state(),+ seed_skill_ids=state.seed_skill_ids,+ skill_by_id=self.skill_by_id,+ can_feed_edges=self.eligible_edges,+ ),+ )+ for state in states+ if state.skill_ids+ ]+ state_plans.sort(+ key=lambda item: (+ -self._state_score(item[0], plan=item[1]),+ len(item[1].missing_inputs),+ len(item[1].steps),+ tuple(step.skill_id for step in item[1].steps),+ )+ )+ return [plan for _state, plan in state_plans]++ def _merge_converged_states(self, states: list[BeamState]) -> list[BeamState]:+ deduped = self._dedupe_states(states)+ merged = list(deduped)+ directional_groups = (+ _group_states(+ [state for state in deduped if state.last_direction == "forward"],+ lambda state: state.tail,+ ),+ _group_states(+ [state for state in deduped if state.last_direction == "backward"],+ lambda state: state.head,+ ),+ )+ for groups in directional_groups:+ for group in groups:+ if len(group) < 2:+ continue+ merged_state = self._merge_state_group(group)+ if merged_state is not None:+ merged.append(merged_state)+ return self._dedupe_states(merged)++ def _merge_state_group(self, states: list[BeamState]) -> BeamState | None:+ skill_ids = {current for state in states for current in state.skill_ids}+ edge_indices = tuple(+ sorted(+ {edge_index for state in states for edge_index in state.edge_indices}+ )+ )+ ordered = self._topological_order(skill_ids, edge_indices)+ if ordered is None:+ return None+ seed_skill_ids = tuple(+ dict.fromkeys(+ current for state in states for current in state.seed_skill_ids+ )+ )+ semantic_scores = tuple(+ score for state in states for score in state.semantic_scores+ )+ unique_reasons = []+ for state in states:+ for reason in state.score_reasons:+ if reason and reason not in unique_reasons:+ unique_reasons.append(reason)+ reasons = tuple(unique_reasons)+ return BeamState(+ skill_ids=tuple(ordered),+ edge_indices=edge_indices,+ semantic_scores=semantic_scores,+ score_reasons=reasons[:8],+ seed_skill_ids=seed_skill_ids,+ last_direction=states[0].last_direction,+ )++ def _topological_order(+ self,+ skill_ids: set[str],+ edge_indices: tuple[int, ...],+ ) -> list[str] | None:+ incoming = {current_skill_id: 0 for current_skill_id in skill_ids}+ outgoing: dict[str, list[str]] = defaultdict(list)+ for edge_index in edge_indices:+ edge = self.eligible_edges[edge_index]+ source_id = skill_id(edge.get("source"))+ target_id = skill_id(edge.get("target"))+ if source_id not in skill_ids or target_id not in skill_ids:+ continue+ outgoing[source_id].append(target_id)+ incoming[target_id] += 1++ ready = sorted(+ current_skill_id+ for current_skill_id, count in incoming.items()+ if count == 0+ )+ ordered = []+ while ready:+ current_skill_id = ready.pop(0)+ ordered.append(current_skill_id)+ for target_id in sorted(outgoing.get(current_skill_id, [])):+ incoming[target_id] -= 1+ if incoming[target_id] == 0:+ ready.append(target_id)+ ready.sort()+ if len(ordered) != len(skill_ids):+ return None+ return ordered++ def _dedupe_states(self, states: list[BeamState]) -> list[BeamState]:+ deduped: dict[tuple[tuple[str, ...], tuple[int, ...]], BeamState] = {}+ for state in states:+ key = (state.skill_ids, tuple(sorted(state.edge_indices)))+ existing = deduped.get(key)+ if existing is None or self._state_score(state) > self._state_score(+ existing+ ):+ deduped[key] = state+ return list(deduped.values())++ def _rank_and_trim(+ self,+ states: list[BeamState],+ *,+ limit: int,+ ) -> list[BeamState]:+ ranked = []+ for state in self._dedupe_states(states):+ plan = self._state_plan(state)+ ranked.append(+ (state, self._state_score(state, plan=plan), len(plan.missing_inputs))+ )+ ranked.sort(+ key=lambda item: (+ -item[1],+ item[2],+ len(item[0].skill_ids),+ item[0].skill_ids,+ item[0].edge_indices,+ )+ )+ return [state for state, _score, _missing in ranked[:limit]]++ def _state_score(+ self,+ state: BeamState,+ *,+ plan: OrchestrationPlan | None = None,+ ) -> float:+ plan = plan or self._state_plan(state)+ semantic_score = (+ sum(state.semantic_scores) / len(state.semantic_scores)+ if state.semantic_scores+ else SEED_BASELINE_SCORE+ )+ edge_confidence = self._state_edge_confidence(state)+ input_coverage = self._input_coverage(plan)+ depth_penalty = max(0, len(state.skill_ids) - 1)+ return (+ 0.45 * semantic_score+ + 0.25 * edge_confidence+ + 0.20 * input_coverage+ - 0.03 * depth_penalty+ )++ def _state_plan(self, state: BeamState) -> OrchestrationPlan:+ return state_to_plan(+ state=state.to_search_state(),+ seed_skill_ids=state.seed_skill_ids,+ skill_by_id=self.skill_by_id,+ can_feed_edges=self.eligible_edges,+ )++ def _state_edge_confidence(self, state: BeamState) -> float:+ if not state.edge_indices:+ return 1.0+ values = [+ float(self.eligible_edges[index].get("confidence") or 0.0)+ for index in state.edge_indices+ ]+ return sum(values) / len(values)++ @staticmethod+ def _input_coverage(plan: OrchestrationPlan) -> float:+ required = 0+ for step in plan.steps:+ required += sum(1 for item in step.inputs if item.get("required", True))+ if required <= 0:+ return 1.0+ missing = len(plan.missing_inputs)+ return max(0.0, min(1.0, (required - missing) / required))++ def _candidate_payload(self, expansion: NeighborExpansion) -> dict[str, Any]:+ return {+ "candidate_id": expansion.candidate_id,+ "skill": skill_payload(self.skill_by_id[expansion.candidate_skill_id]),+ }++ def _sorted_eligible_edges(self) -> list[dict[str, Any]]:+ return eligible_can_feed_edges(+ self.artifacts.graph.get("edges", []),+ known_skill_ids=set(self.skill_by_id),+ min_confidence=self.min_edge_confidence,+ )++ def _plan_payload(self, plan: OrchestrationPlan, *, query: str) -> dict[str, Any]:+ payload = plan.to_dict()+ title = _query_plan_title(query, language=self.language)+ reason = "; ".join(plan.reasons[:3])+ payload.update(+ {+ "title": title,+ "reason": reason,+ "plan_classification": (+ "executable"+ if plan.status == "ready"+ else "structurally_valid_but_incomplete"+ ),+ "connectivity_trace": (["can_feed"] if plan.can_feed_edges else []),+ "source": "bidirectional_beam",+ }+ )+ return payload+++def _query_signature(query: str) -> str:+ normalized = " ".join(str(query or "").strip().lower().split())+ return hashlib.sha1(normalized.encode("utf-8")).hexdigest()+++def _state_signature(state: BeamState) -> str:+ payload = {+ "skills": state.skill_ids,+ "edges": state.edge_indices,+ "last_direction": state.last_direction,+ }+ return hashlib.sha1(+ json.dumps(payload, sort_keys=True, default=str).encode("utf-8")+ ).hexdigest()[:10]+++def _dict_plan_signature(plan: dict[str, Any]) -> tuple[str, ...]:+ return tuple(+ str(step.get("skill_id") or "").strip()+ for step in plan.get("steps") or []+ if isinstance(step, dict) and str(step.get("skill_id") or "").strip()+ )+++def _candidate_plan_skill_ids(plans: list[dict[str, Any]]) -> set[str]:+ return {+ current_skill_id+ for plan in plans+ for current_skill_id in _dict_plan_signature(plan)+ }+++def _normalize_rerank_step_ids(raw_steps: Any) -> list[str]:+ if not isinstance(raw_steps, list):+ return []+ output = []+ for item in raw_steps:+ current_skill_id = skill_id(+ item.get("skill_id") if isinstance(item, dict) else item+ ).strip()+ if current_skill_id and current_skill_id not in output:+ output.append(current_skill_id)+ return output+++def _normalize_rerank_edges(raw_edges: Any) -> dict[str, Any]:+ edges: list[tuple[str, str]] = []+ if not isinstance(raw_edges, list):+ return {"edges": edges}+ seen = set()+ for item in raw_edges:+ if not isinstance(item, dict):+ continue+ source_id = skill_id(item.get("source_id") or item.get("source")).strip()+ target_id = skill_id(item.get("target_id") or item.get("target")).strip()+ edge = (source_id, target_id)+ if not source_id or not target_id:+ continue+ if source_id == target_id or edge in seen:+ continue+ seen.add(edge)+ edges.append(edge)+ return {"edges": edges}+++def _positive_int(value: Any) -> int | None:+ try:+ parsed = int(value)+ except (TypeError, ValueError):+ return None+ return parsed if parsed > 0 else None+++def _short_text(value: str, *, max_chars: int = 80) -> str:+ text = " ".join(str(value or "").split())+ if len(text) <= max_chars:+ return text+ return text[:max_chars].rstrip()+++def _plan_steps_by_skill(+ plans: list[dict[str, Any]],+) -> dict[str, dict[str, Any]]:+ output = {}+ for plan in plans:+ for step in plan.get("steps") or []:+ if not isinstance(step, dict):+ continue+ current_skill_id = str(step.get("skill_id") or "").strip()+ if current_skill_id:+ output.setdefault(current_skill_id, step)+ return output+++def _step_reasons_by_skill(raw_steps: Any) -> dict[str, str]:+ if not isinstance(raw_steps, list):+ return {}+ output = {}+ for item in raw_steps:+ if not isinstance(item, dict):+ continue+ current_skill_id = skill_id(item.get("skill_id")).strip()+ if current_skill_id:+ output[current_skill_id] = _short_text(str(item.get("reason") or ""))+ return output+++def _dedupe_dict_items(items: Iterable[dict[str, Any]]) -> list[dict[str, Any]]:+ output = []+ seen = set()+ for item in items:+ key = json.dumps(item, ensure_ascii=False, sort_keys=True, default=str)+ if key in seen:+ continue+ seen.add(key)+ output.append(item)+ return output+++def _rerank_plan_stages(+ steps: list[dict[str, Any]],+ edges: list[dict[str, Any]],+) -> list[dict[str, Any]]:+ step_by_id = {str(step.get("skill_id") or ""): step for step in steps}+ incoming = {current_skill_id: set() for current_skill_id in step_by_id}+ for edge in edges:+ source_id = str(edge.get("source_id") or "")+ target_id = str(edge.get("target_id") or "")+ if source_id in step_by_id and target_id in incoming:+ incoming[target_id].add(source_id)+ remaining = list(step_by_id)+ completed = set()+ stages = []+ while remaining:+ ready = [+ current_skill_id+ for current_skill_id in remaining+ if incoming[current_skill_id] <= completed+ ]+ if not ready:+ ready = [remaining[0]]+ stages.append(+ {+ "stage": len(stages) + 1,+ "skills": [step_by_id[current_skill_id] for current_skill_id in ready],+ }+ )+ completed.update(ready)+ remaining = [item for item in remaining if item not in completed]+ return stages+++def _required_output_types_from_query(query: str) -> frozenset[str]:+ output_types = set()+ for match in _EXPLICIT_FILE_EXTENSION_RE.finditer(str(query or "")):+ normalized = str(match.group(1) or "").strip().lower().lstrip(".")+ mime_type, _encoding = mimetypes.guess_type(f"file.{normalized}")+ if mime_type in _MIME_TO_OUTPUT_TYPE:+ output_types.add(_MIME_TO_OUTPUT_TYPE[mime_type])+ elif mime_type and mime_type.startswith("image/"):+ output_types.add("image")+ return frozenset(output_types)+++def _clamp_score(value: Any) -> float:+ try:+ parsed = float(value)+ except (TypeError, ValueError):+ return 0.0+ return max(0.0, min(1.0, parsed))+++def _query_plan_title(query: str, *, language: str) -> str:+ title = " ".join(str(query or "").split())+ if not title:+ return default_beam_plan_title(language)+ if len(title) <= 80:+ return title+ return f"{title[:77].rstrip()}..."+++def _append_unique(values: tuple[str, ...], value: str) -> tuple[str, ...]:+ text = str(value or "").strip()+ if not text or text in values:+ return values+ return (*values, text)+++def _group_states(+ states: list[BeamState],+ key_fn: Callable[[BeamState], str],+) -> list[list[BeamState]]:+ grouped: dict[str, list[BeamState]] = defaultdict(list)+ for state in states:+ grouped[str(key_fn(state))].append(state)+ return list(grouped.values())+++def _dominant_status(current: str, incoming: str) -> str:+ current_priority = _GRAPH_STATUS_PRIORITY.get(current, -1)+ incoming_priority = _GRAPH_STATUS_PRIORITY.get(incoming, -1)+ return incoming if incoming_priority >= current_priority else current+++def _copy_public_graph_edge(edge: dict[str, Any]) -> dict[str, Any]:+ return {+ "source": edge.get("source"),+ "target": edge.get("target"),+ "status": edge.get("status"),+ }+++def _skill_label(skill: dict[str, Any]) -> str:+ current_skill_id = str(skill.get("id") or "").strip()+ return str(skill.get("name") or current_skill_id).strip() or current_skill_id+++def _sorted_expansions(+ expansions: Sequence[NeighborExpansion],+) -> list[NeighborExpansion]:+ return sorted(+ expansions,+ key=lambda item: (+ item.direction,+ item.current_skill_id,+ item.candidate_skill_id,+ item.edge_index,+ item.candidate_id,+ ),+ )diff --git a/jiuwenswarm/symphony/orchestration/planning/fast.py b/jiuwenswarm/symphony/orchestration/planning/fast.pyindex d662953625..ccfdcbb55d 100644--- a/jiuwenswarm/symphony/orchestration/planning/fast.py+++ b/jiuwenswarm/symphony/orchestration/planning/fast.py@@ -9,8 +9,17 @@ from typing import Any, Sequencefrom jiuwenswarm.symphony.llm import LLMConfig, create_llm_client, llm_usage_contextfrom jiuwenswarm.symphony.orchestration.artifacts import ScoreArtifacts+from jiuwenswarm.symphony.orchestration.language import (+ default_fast_no_plan_title,+ planner_language_instruction,+)from jiuwenswarm.symphony.orchestration.planning.plan_builder import edge_plan_item-from jiuwenswarm.symphony.orchestration.planning.utils import skill_id+from jiuwenswarm.symphony.orchestration.planning.utils import (+ eligible_can_feed_edges,+ normalize_known_skill_ids,+ skill_id,+ skill_payload,+)FAST_PLANNER_SYSTEM_PROMPT = """You are Symphony's fast Skill planner.Return strict JSON only.@@ -68,13 +77,15 @@ class FastOneShotPlanner:min_edge_confidence: float,max_depth: int = 4,candidate_skill_ids: Sequence[str] | None = None,+ language: str = "cn",) -> None:self.artifacts = artifactsself.llm_config = llm_configself.llm_client = llm_clientself.min_edge_confidence = min_edge_confidenceself.max_depth = max(1, int(max_depth))- self.candidate_skill_ids = self._normalize_candidate_skill_ids(+ self.language = language+ self.candidate_skill_ids = normalize_known_skill_ids(candidate_skill_ids,known_skill_ids=set(artifacts.skill_by_id),)@@ -89,7 +100,10 @@ class FastOneShotPlanner:}with llm_usage_context("orchestration", "one_shot_fast_planning"):raw = await client.complete_json_async(- system_prompt=FAST_PLANNER_SYSTEM_PROMPT,+ system_prompt=(+ f"{FAST_PLANNER_SYSTEM_PROMPT}\n"+ f"{planner_language_instruction(self.language)}"+ ),user_content=json.dumps(prompt_payload, ensure_ascii=False),error_context="Symphony one-shot fast planning",request_overrides={@@ -99,6 +113,7 @@ class FastOneShotPlanner:base = {"query": query,+ "language": self.language,"score_dir": str(self.artifacts.score_dir),"planning_mode": "one_shot_fast","llm_call_count": 1,@@ -313,18 +328,10 @@ class FastOneShotPlanner:return []def _sorted_eligible_edges(self) -> list[dict[str, Any]]:- filtered_edges = []- for edge in self.artifacts.graph.get("edges", []):- edge_confidence = float(edge.get("confidence") or 0.0)- if edge.get("type") == "can_feed" and edge_confidence >= self.min_edge_confidence:- filtered_edges.append(edge)- return sorted(- filtered_edges,- key=lambda item: (- -float(item.get("confidence") or 0.0),- str(item.get("source") or ""),- str(item.get("target") or ""),- ),+ return eligible_can_feed_edges(+ self.artifacts.graph.get("edges", []),+ known_skill_ids=set(self.artifacts.skill_by_id),+ min_confidence=self.min_edge_confidence,)def _subgraph_payload(@@ -334,7 +341,7 @@ class FastOneShotPlanner:) -> dict[str, Any]:skill_by_id = self.artifacts.skill_by_idskill_payloads = [- self._skill_payload(skill_by_id[current_skill_id])+ skill_payload(skill_by_id[current_skill_id])for current_skill_id in selectedif current_skill_id in skill_by_id]@@ -420,7 +427,8 @@ class FastOneShotPlanner:"detail": "","plan": {"title": str(- selection.get("title") or "No Symphony fast plan"+ selection.get("title")+ or default_fast_no_plan_title(self.language)).strip(),"status": "no_plan","steps": [],@@ -604,15 +612,6 @@ class FastOneShotPlanner:payload["error"] = str(exc)return payload- @staticmethod- def _skill_payload(skill: dict[str, Any]) -> dict[str, Any]:- current_skill_id = str(skill.get("id") or "")- return {- "id": current_skill_id,- "name": str(skill.get("name") or current_skill_id),- "description": str(skill.get("description") or "")[:800],- }-@staticmethoddef _edge_payload(edge: dict[str, Any]) -> dict[str, Any]:return {@@ -723,25 +722,3 @@ class FastOneShotPlanner:):return str(item.get("reason") or "").strip()return ""-- @staticmethod- def _normalize_candidate_skill_ids(- values: Sequence[str] | None,- *,- known_skill_ids: set[str],- ) -> tuple[str, ...] | None:- if values is None:- return None- output = []- seen = set()- for value in values:- current_skill_id = str(value or "").strip()- if (- not current_skill_id- or current_skill_id in seen- or current_skill_id not in known_skill_ids- ):- continue- seen.add(current_skill_id)- output.append(current_skill_id)- return tuple(output) if output else Nonediff --git a/jiuwenswarm/symphony/orchestration/planning/input_matching.py b/jiuwenswarm/symphony/orchestration/planning/input_matching.pyindex ebbea1a67c..ea7b062c38 100644--- a/jiuwenswarm/symphony/orchestration/planning/input_matching.py+++ b/jiuwenswarm/symphony/orchestration/planning/input_matching.py@@ -1,127 +1,25 @@-"""Input and artifact matching helpers for orchestration plans."""+"""Input and output matching helpers for Beam plans."""from __future__ import annotationsfrom typing import Any, Iterable-from jiuwenswarm.symphony.orchestration.planning.models import (- ArtifactRef,- InferredInput,- PlanStep,-)---def input_coverage_score(- skill: dict[str, Any],- available: Iterable[tuple[str, str]],- *,- inferred_inputs: list[InferredInput] | None = None,-) -> float:- required = [- (str(item.get("name")), str(item.get("type") or "unknown"))- for item in skill.get("inputs", [])- if item.get("required", True) and item.get("name")- ]- if not required:- return 1.0- available_set = set(available)- inferred_set = inferred_input_keys(str(skill.get("id") or ""), inferred_inputs or [])- matched = 0- for item in required:- if artifact_matches(item, available_set) or inferred_input_matches(- item,- inferred_set,- ):- matched += 1- return matched / len(required)---def consumed_user_artifact_count(- steps: list[PlanStep],- artifacts: list[ArtifactRef],-) -> int:- explicit = {- artifact.key- for artifact in artifacts- if artifact.source != "implicit_query"- }- if not steps or not explicit:- return 0- consumed = 0- for item in steps[0].inputs:- expected = (str(item.get("name")), str(item.get("type") or "unknown"))- if artifact_matches(expected, explicit):- consumed += 1- return consumed-def missing_inputs(skill: dict[str, Any],available: Iterable[tuple[str, str]],- *,- inferred_inputs: list[InferredInput] | None = None,) -> list[dict[str, Any]]:available_set = set(available)- inferred_set = inferred_input_keys(str(skill.get("id") or ""), inferred_inputs or [])missing = []for item in skill.get("inputs", []):if not item.get("required", True):continueexpected = (str(item.get("name")), str(item.get("type") or "unknown"))- if not artifact_matches(expected, available_set) and not inferred_input_matches(- expected,- inferred_set,- ):+ if not artifact_matches(expected, available_set):missing.append({"name": expected[0], "type": expected[1]})return missing-def filled_inputs(- skill: dict[str, Any],- inferred_inputs: list[InferredInput],-) -> list[dict[str, Any]]:- skill_id_ = str(skill.get("id") or "")- input_keys = {- (str(item.get("name")), str(item.get("type") or "unknown"))- for item in skill.get("inputs", [])- if item.get("name")- }- filled = []- for inferred_input in inferred_inputs:- if inferred_input.skill_id != skill_id_:- continue- if inferred_input_matches((inferred_input.name, inferred_input.type), input_keys):- filled.append(inferred_input.to_dict())- return filled---def inferred_input_keys(- skill_id_: str,- inferred_inputs: list[InferredInput],-) -> set[tuple[str, str]]:- return {- (item.name, item.type)- for item in inferred_inputs- if item.skill_id == skill_id_- }---def inferred_input_matches(- expected: tuple[str, str],- inferred: set[tuple[str, str]],-) -> bool:- name, type_ = expected- return any(- candidate_name == name- and (- candidate_type == type_- or candidate_type == "unknown"- or type_ == "unknown"- )- for candidate_name, candidate_type in inferred- )--def artifact_matches(expected: tuple[str, str],available: set[tuple[str, str]],@@ -135,44 +33,6 @@ def artifact_matches()-def edge_feeds_missing_inputs(- *,- edge: dict[str, Any],- source: dict[str, Any],- target: dict[str, Any],- missing_keys: set[tuple[str, str]],-) -> bool:- if not missing_keys:- return False- evidence = edge.get("evidence") or {}- supporting_fields = evidence.get("supporting_fields") or {}- target_input_names = {- str(item)- for item in supporting_fields.get("target_inputs", [])- if str(item).strip()- }- target_input_names.update(- str(mapping.get("target_input"))- for mapping in supporting_fields.get("port_mappings", [])- if isinstance(mapping, dict) and mapping.get("target_input")- )- missing_names = {name for name, _ in missing_keys}- if target_input_names & missing_names:- return True-- source_outputs = output_keys(source)- target_inputs = {- (str(item.get("name")), str(item.get("type") or "unknown"))- for item in target.get("inputs", [])- if item.get("name")- }- return any(- missing_key in target_inputs- and artifact_matches(missing_key, set(source_outputs))- for missing_key in missing_keys- )--def output_keys(skill: dict[str, Any]) -> frozenset[tuple[str, str]]:return frozenset((str(item.get("name")), str(item.get("type") or "unknown"))diff --git a/jiuwenswarm/symphony/orchestration/planning/models.py b/jiuwenswarm/symphony/orchestration/planning/models.pyindex 4460f4a0e4..83db03a143 100644--- a/jiuwenswarm/symphony/orchestration/planning/models.py+++ b/jiuwenswarm/symphony/orchestration/planning/models.py@@ -3,7 +3,7 @@from __future__ import annotationsfrom dataclasses import dataclass, field-from typing import Any, Protocol+from typing import Any@dataclass(frozen=True)@@ -22,52 +22,6 @@ class ArtifactRef:return {"name": self.name, "type": self.type, "source": self.source}-@dataclass(frozen=True)-class InferredInput:- """A skill input value inferred from the user request."""-- skill_id: str- name: str- type: str = "unknown"- value: Any = None- source: str = "llm_grounding"-- @property- def key(self) -> tuple[str, str, str]:- return (self.skill_id, self.name, self.type)-- def to_dict(self) -> dict[str, Any]:- return {- "skill_id": self.skill_id,- "name": self.name,- "type": self.type,- "value": self.value,- "source": self.source,- }---@dataclass(frozen=True)-class GroundedQuery:- """User query grounded into known artifacts and seed Skills."""-- query: str- available_artifacts: list[ArtifactRef]- inferred_inputs: list[InferredInput] = field(default_factory=list)- seed_skill_ids: tuple[str, ...] = ()-- def to_dict(self) -> dict[str, Any]:- return {- "query": self.query,- "available_artifacts": [- artifact.to_dict() for artifact in self.available_artifacts- ],- "inferred_inputs": [- inferred_input.to_dict() for inferred_input in self.inferred_inputs- ],- "seed_skill_ids": list(self.seed_skill_ids),- }--@dataclass(frozen=True)class PlanStep:"""One Skill call in a candidate orchestration plan."""@@ -128,25 +82,10 @@ class OrchestrationPlan:}-class GroundingClient(Protocol):- """Minimal JSON completion interface used by Skill orchestration."""-- async def complete_json_async(- self,- *,- system_prompt: str,- user_content: str,- timeout: int | None = None,- error_context: str = "LLM",- ) -> str:- ...--@dataclass(frozen=True)class SearchState:"""Internal forward-search state."""skill_ids: tuple[str, ...]- available: frozenset[tuple[str, str]]edges: tuple[int, ...]score_reasons: tuple[str, ...] = ()diff --git a/jiuwenswarm/symphony/orchestration/planning/plan_builder.py b/jiuwenswarm/symphony/orchestration/planning/plan_builder.pyindex e67431d548..38b0946975 100644--- a/jiuwenswarm/symphony/orchestration/planning/plan_builder.py+++ b/jiuwenswarm/symphony/orchestration/planning/plan_builder.py@@ -1,19 +1,16 @@-"""Build and compose concrete orchestration plans from search state."""+"""Build concrete orchestration plans from Beam search state."""from __future__ import annotations-from collections import defaultdict, deque+from collections import defaultdictfrom typing import Anyfrom jiuwenswarm.symphony.orchestration.planning.input_matching import (- consumed_user_artifact_count,- filled_inputs,missing_inputs,output_keys,)from jiuwenswarm.symphony.orchestration.planning.models import (ArtifactRef,- GroundedQuery,OrchestrationPlan,PlanStep,SearchState,@@ -24,24 +21,18 @@ from jiuwenswarm.symphony.orchestration.planning.utils import skill_iddef state_to_plan(*,state: SearchState,- grounded: GroundedQuery,+ seed_skill_ids: tuple[str, ...],skill_by_id: dict[str, dict[str, Any]],can_feed_edges: list[dict[str, Any]],) -> OrchestrationPlan:- available = set(state.available)+ available: set[tuple[str, str]] = set()steps: list[PlanStep] = []all_missing: list[dict[str, Any]] = []produced: set[tuple[str, str]] = set()- reasons: list[str] = []for current_skill_id in state.skill_ids:skill = skill_by_id[current_skill_id]- filled = filled_inputs(skill, grounded.inferred_inputs)- missing = missing_inputs(- skill,- available,- inferred_inputs=grounded.inferred_inputs,- )+ missing = missing_inputs(skill, available)all_missing.extend({**item, "skill_id": current_skill_id} for item in missing)outputs = output_keys(skill)produced.update(outputs)@@ -59,11 +50,8 @@ def state_to_plan(for item in skill.get("outputs", [])],missing_inputs=missing,- filled_inputs=filled,))- if current_skill_id in grounded.seed_skill_ids:- reasons.append(f"{current_skill_id} selected as a seed skill")edges = [can_feed_edges[index] for index in state.edges]edge_confidence = (@@ -71,10 +59,6 @@ def state_to_plan(if edgeselse 1.0)- goal_score = plan_goal_score(- skill_ids=state.skill_ids,- seed_skill_ids=grounded.seed_skill_ids,- )status = "ready" if not all_missing else "needs_input"return OrchestrationPlan(steps=steps,@@ -84,14 +68,11 @@ def state_to_plan(],missing_inputs=all_missing,can_feed_edges=[edge_plan_item(edge) for edge in edges],- goal_score=goal_score,+ goal_score=sum(10.0 for item in state.skill_ids if item in seed_skill_ids),edge_confidence=edge_confidence,- consumed_user_artifacts=consumed_user_artifact_count(- steps,- grounded.available_artifacts,- ),+ consumed_user_artifacts=0,status=status,- reasons=[*reasons, *state.score_reasons][:8],+ reasons=list(state.score_reasons[:8]),)@@ -109,205 +90,6 @@ def build_incoming_edges(edges: list[dict[str, Any]]) -> dict[str, list[int]]:return incoming-def plan_goal_score(- *,- skill_ids: tuple[str, ...],- seed_skill_ids: tuple[str, ...] = (),-) -> float:- return sum(- seed_skill_score(current_skill_id, seed_skill_ids=seed_skill_ids)- for current_skill_id in skill_ids- )---def seed_skill_score(skill_id_: str, *, seed_skill_ids: tuple[str, ...]) -> float:- return 10.0 if skill_id_ in seed_skill_ids else 0.0---def dedupe_plans(plans: list[OrchestrationPlan]) -> list[OrchestrationPlan]:- deduped: dict[tuple[str, ...], OrchestrationPlan] = {}- for plan in plans:- key = tuple(step.skill_id for step in plan.steps)- existing = deduped.get(key)- if existing is None or plan.goal_score > existing.goal_score:- deduped[key] = plan- return list(deduped.values())---def compose_dag_plans(- path_plans: list[OrchestrationPlan],- *,- max_plans: int,-) -> list[OrchestrationPlan]:- composed: list[OrchestrationPlan] = []- composed.extend(compose_overlapping_path_plans(path_plans, max_plans=max_plans))-- groups: dict[str, list[OrchestrationPlan]] = defaultdict(list)- for plan in path_plans:- if plan.steps:- groups[plan.steps[0].skill_id].append(plan)-- for group in groups.values():- branch_plans = [plan for plan in group if len(plan.steps) > 1]- if len(branch_plans) < 2:- continue- composed.append(compose_plan_group(branch_plans))-- return dedupe_plans([*composed, *path_plans])[: max_plans * 2]---def compose_overlapping_path_plans(- path_plans: list[OrchestrationPlan],- *,- max_plans: int,-) -> list[OrchestrationPlan]:- output: list[OrchestrationPlan] = []- seen: set[tuple[str, ...]] = set()- for left in path_plans:- left_ids = tuple(step.skill_id for step in left.steps)- if len(left_ids) < 2:- continue- for right in path_plans:- if left is right:- continue- right_ids = tuple(step.skill_id for step in right.steps)- if len(right_ids) < 2:- continue- overlap = path_overlap_size(left_ids, right_ids)- if overlap <= 0:- continue- stitched_ids = (*left_ids, *right_ids[overlap:])- if len(stitched_ids) <= max(len(left_ids), len(right_ids)):- continue- if len(set(stitched_ids)) != len(stitched_ids):- continue- if stitched_ids in seen:- continue- seen.add(stitched_ids)- output.append(compose_plan_group([left, right]))- if len(output) >= max(1, max_plans):- return output- return output---def path_overlap_size(- left: tuple[str, ...],- right: tuple[str, ...],-) -> int:- max_overlap = min(len(left), len(right)) - 1- for size in range(max_overlap, 0, -1):- if left[-size:] == right[:size]:- return size- return 0---def compose_plan_group(plans: list[OrchestrationPlan]) -> OrchestrationPlan:- steps_by_id: dict[str, PlanStep] = {}- edges_by_key: dict[tuple[str, str], dict[str, Any]] = {}- produced_by_key: dict[tuple[str, str], ArtifactRef] = {}- missing_by_key: dict[tuple[str, str, str], dict[str, Any]] = {}- reasons: list[str] = []-- for plan in plans:- for step in plan.steps:- steps_by_id.setdefault(step.skill_id, step)- for edge in plan.can_feed_edges:- key = (- edge_endpoint_id(edge, "source"),- edge_endpoint_id(edge, "target"),- )- if key[0] and key[1]:- existing = edges_by_key.get(key)- if (- existing is None- or edge_confidence_value(edge) > edge_confidence_value(existing)- ):- edges_by_key[key] = edge- for artifact in plan.produced_artifacts:- produced_by_key.setdefault(artifact.key, artifact)- for item in plan.missing_inputs:- key = (- str(item.get("skill_id") or ""),- str(item.get("name") or ""),- str(item.get("type") or "unknown"),- )- missing_by_key.setdefault(key, dict(item))- for reason in plan.reasons:- if reason not in reasons:- reasons.append(reason)-- ordered_step_ids = topological_step_ids(- set(steps_by_id),- list(edges_by_key.values()),- )- steps = []- for current_skill_id in ordered_step_ids:- step = steps_by_id.get(current_skill_id)- if step is not None:- steps.append(step)- missing_inputs_list = list(missing_by_key.values())- edge_confidence = (- sum(float(edge.get("confidence") or 0.0) for edge in edges_by_key.values())- / len(edges_by_key)- if edges_by_key- else 1.0- )- return OrchestrationPlan(- steps=steps,- produced_artifacts=list(produced_by_key.values()),- missing_inputs=missing_inputs_list,- can_feed_edges=list(edges_by_key.values()),- goal_score=sum(plan.goal_score for plan in plans),- edge_confidence=edge_confidence,- consumed_user_artifacts=max(plan.consumed_user_artifacts for plan in plans),- status="ready" if not missing_inputs_list else "needs_input",- reasons=reasons[:8],- )---def edge_endpoint_id(edge: dict[str, Any], side: str) -> str:- if side == "source":- return skill_id(edge.get("source_id") or edge.get("source"))- return skill_id(edge.get("target_id") or edge.get("target"))---def edge_confidence_value(edge: dict[str, Any]) -> float:- return float(edge.get("confidence") or 0.0)---def topological_step_ids(- skill_ids: set[str],- edges: list[dict[str, Any]],-) -> list[str]:- incoming = {current_skill_id: 0 for current_skill_id in skill_ids}- outgoing: dict[str, list[str]] = defaultdict(list)- for edge in edges:- source_id = str(edge.get("source_id") or "")- target_id = str(edge.get("target_id") or "")- if source_id not in skill_ids or target_id not in skill_ids:- continue- outgoing[source_id].append(target_id)- incoming[target_id] += 1-- queue = deque(- sorted(- current_skill_id- for current_skill_id, count in incoming.items()- if count == 0- )- )- ordered: list[str] = []- while queue:- current_skill_id = queue.popleft()- ordered.append(current_skill_id)- for target_id in sorted(outgoing.get(current_skill_id, [])):- incoming[target_id] -= 1- if incoming[target_id] == 0:- queue.append(target_id)- ordered.extend(sorted(skill_ids - set(ordered)))- return ordered--def plan_stages(steps: list[PlanStep],edges: list[dict[str, Any]],@@ -337,8 +119,7 @@ def plan_stages({"stage": len(stages) + 1,"skills": [- step_by_id[current_skill_id].to_dict()- for current_skill_id in ready+ step_by_id[current_skill_id].to_dict() for current_skill_id in ready],})diff --git a/jiuwenswarm/symphony/orchestration/planning/utils.py b/jiuwenswarm/symphony/orchestration/planning/utils.pyindex 8cbc5d5a65..166893d578 100644--- a/jiuwenswarm/symphony/orchestration/planning/utils.py+++ b/jiuwenswarm/symphony/orchestration/planning/utils.py@@ -3,7 +3,7 @@from __future__ import annotations-from typing import Any+from typing import Any, Sequencedef skill_id(node_id: Any) -> str:@@ -13,3 +13,60 @@ def skill_id(node_id: Any) -> str:def clamp(value: float) -> float:return max(0.0, min(1.0, float(value)))+++def skill_payload(skill: dict[str, Any]) -> dict[str, Any]:+ current_skill_id = str(skill.get("id") or "")+ return {+ "id": current_skill_id,+ "name": str(skill.get("name") or current_skill_id),+ "description": str(skill.get("description") or "")[:800],+ }+++def eligible_can_feed_edges(+ edges: Sequence[dict[str, Any]],+ *,+ known_skill_ids: set[str],+ min_confidence: float,+) -> list[dict[str, Any]]:+ eligible = []+ for edge in edges:+ source_id = skill_id(edge.get("source"))+ target_id = skill_id(edge.get("target"))+ if edge.get("type") != "can_feed":+ continue+ if float(edge.get("confidence") or 0.0) < min_confidence:+ continue+ if source_id not in known_skill_ids or target_id not in known_skill_ids:+ continue+ eligible.append(edge)+ return sorted(+ eligible,+ key=lambda item: (+ -float(item.get("confidence") or 0.0),+ skill_id(item.get("source")),+ skill_id(item.get("target")),+ ),+ )+++def normalize_known_skill_ids(+ values: Sequence[str] | None,+ *,+ known_skill_ids: set[str],+) -> tuple[str, ...] | None:+ if values is None:+ return None+ output = []+ seen = set()+ for value in values:+ current_skill_id = str(value or "").strip()+ if (+ current_skill_id+ and current_skill_id not in seen+ and current_skill_id in known_skill_ids+ ):+ seen.add(current_skill_id)+ output.append(current_skill_id)+ return tuple(output) if output else Nonediff --git a/jiuwenswarm/symphony/orchestration/service.py b/jiuwenswarm/symphony/orchestration/service.pyindex 31ac18f43d..bb31fe280f 100644--- a/jiuwenswarm/symphony/orchestration/service.py+++ b/jiuwenswarm/symphony/orchestration/service.py@@ -12,6 +12,7 @@ from jiuwenswarm.symphony.orchestration.artifacts import (load_score_artifacts,)from jiuwenswarm.symphony.orchestration.execution_graph import build_execution_graph+from jiuwenswarm.symphony.orchestration.planning.beam import BidirectionalBeamPlannerfrom jiuwenswarm.symphony.orchestration.planning.fast import FastOneShotPlannerfrom jiuwenswarm.symphony.orchestration.planning.utils import clamp@@ -21,16 +22,21 @@ async def plan_from_score(query: str,llm_config: LLMConfig | None = None,*,+ top_k: int = 3,max_depth: int = 4,min_edge_confidence: float = 0.7,llm_client: Any | None = None,orchestration_config: SymphonyOrchestrationConfig | None = None,candidate_skill_ids: Sequence[str] | None = None,disabled_skill_names: Sequence[str] | None = None,+ progress_callback: Any | None = None,+ language: str = "cn",) -> dict[str, Any]:"""Run online planning from an existing Symphony score."""if orchestration_config is not None:+ top_k = orchestration_config.top_k+ max_depth = orchestration_config.max_depthmin_edge_confidence = orchestration_config.min_edge_confidencemode = orchestration_config.mode if orchestration_config is not None else "fast"@@ -38,24 +44,36 @@ async def plan_from_score(load_score_artifacts(score_dir),disabled_skill_names,)- if mode != "fast":+ if mode not in {"fast", "beam"}:raise ValueError(f"Unsupported orchestration mode: {mode}")selected_candidate_skill_ids, skill_retrieval = _input_candidate_summary(candidate_skill_ids,- known_skill_ids=set(artifacts.skill_by_id),+ skills=artifacts.skills,)- result = await FastOneShotPlanner(- artifacts,- llm_config=llm_config,- llm_client=llm_client,- min_edge_confidence=clamp(min_edge_confidence),- max_depth=max(- 1,- int(orchestration_config.max_depth if orchestration_config else max_depth),- ),- candidate_skill_ids=selected_candidate_skill_ids,- ).plan(query)+ if mode == "beam":+ result = await BidirectionalBeamPlanner(+ artifacts,+ llm_config=llm_config,+ llm_client=llm_client,+ min_edge_confidence=clamp(min_edge_confidence),+ top_k=max(1, int(top_k)),+ max_depth=max(1, int(max_depth)),+ candidate_skill_ids=selected_candidate_skill_ids,+ progress_callback=progress_callback,+ language=language,+ ).plan(query)+ else:+ result = await FastOneShotPlanner(+ artifacts,+ llm_config=llm_config,+ llm_client=llm_client,+ min_edge_confidence=clamp(min_edge_confidence),+ max_depth=max(1, int(max_depth)),+ candidate_skill_ids=selected_candidate_skill_ids,+ language=language,+ ).plan(query)+ result["language"] = languageresult["skill_retrieval"] = skill_retrievalresult["execution_graph"] = build_execution_graph(result, artifacts)return result@@ -64,14 +82,10 @@ async def plan_from_score(def _input_candidate_summary(values: Sequence[str] | None,*,- known_skill_ids: set[str],+ skills: Sequence[dict[str, Any]],) -> tuple[tuple[str, ...] | None, dict[str, Any]]:normalized = _normalize_candidate_skill_ids(values)- selected = tuple(- current_skill_id- for current_skill_id in normalized- if current_skill_id in known_skill_ids- )+ selected = _resolve_candidate_skill_ids(normalized, skills)fallback_reason = ""if values is None:fallback_reason = "candidate_skill_ids not provided"@@ -89,6 +103,37 @@ def _input_candidate_summary(}+def _resolve_candidate_skill_ids(+ values: Sequence[str],+ skills: Sequence[dict[str, Any]],+) -> tuple[str, ...]:+ known_skill_ids = {+ str(skill.get("id") or "").strip()+ for skill in skills+ if str(skill.get("id") or "").strip()+ }+ skill_ids_by_name: dict[str, set[str]] = {}+ for skill in skills:+ current_skill_id = str(skill.get("id") or "").strip()+ name = str(skill.get("name") or "").strip()+ if current_skill_id and name:+ skill_ids_by_name.setdefault(name, set()).add(current_skill_id)++ selected: list[str] = []+ seen: set[str] = set()+ for value in values:+ current_skill_id = value if value in known_skill_ids else ""+ if not current_skill_id:+ matching_ids = skill_ids_by_name.get(value, set())+ if len(matching_ids) == 1:+ current_skill_id = next(iter(matching_ids))+ if not current_skill_id or current_skill_id in seen:+ continue+ seen.add(current_skill_id)+ selected.append(current_skill_id)+ return tuple(selected)++def _normalize_candidate_skill_ids(values: Sequence[str] | None) -> tuple[str, ...]:if values is None:return ()diff --git a/tests/agents/swarm/test_swarm_assembly.py b/tests/agents/swarm/test_swarm_assembly.pyindex cadcdbe05f..95e72ac326 100644--- a/tests/agents/swarm/test_swarm_assembly.py+++ b/tests/agents/swarm/test_swarm_assembly.py@@ -1061,7 +1061,7 @@ def test_symphony_orchestration_prompt_provider_is_leader_only() -> None:leader_rail = factory({}, SwarmBuildContext(role="leader"))teammate_rail = factory({}, SwarmBuildContext(role="teammate"))- assert type(leader_rail).__name__ == "SymphonyOrchestrationPromptRail"+ assert type(leader_rail).__name__ == "SymphonyOrchestrationRail"assert teammate_rail is Nonediff --git a/tests/unit_tests/agentserver/test_agentserver_modes.py b/tests/unit_tests/agentserver/test_agentserver_modes.pyindex d054603312..ee9ce05f78 100644--- a/tests/unit_tests/agentserver/test_agentserver_modes.py+++ b/tests/unit_tests/agentserver/test_agentserver_modes.py@@ -1184,7 +1184,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_symphony_orchestration_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)diff --git a/tests/unit_tests/agentserver/test_stream_event_rail_symphony.py b/tests/unit_tests/agentserver/test_stream_event_rail_symphony.pyindex 724d5a284e..94e32f9260 100644--- a/tests/unit_tests/agentserver/test_stream_event_rail_symphony.py+++ b/tests/unit_tests/agentserver/test_stream_event_rail_symphony.py@@ -8,6 +8,12 @@ from openjiuwen.core.single_agent.rail.base import ToolCallInputsfrom jiuwenswarm.agents.harness.common.rails.stream_event_rail import (JiuSwarmStreamEventRail,)+from jiuwenswarm.agents.harness.common.rails.symphony import (+ SymphonyToolStreamHandler,+)+from jiuwenswarm.agents.harness.common.tool_progress_context import (+ current_tool_progress,+)from jiuwenswarm.symphony.agent import AgenticToolResult@@ -35,6 +41,13 @@ class _ModelContext:self.messages.append(message)+def test_symphony_tool_stream_handler_matches_only_compose_tool():+ handler = SymphonyToolStreamHandler()++ assert handler.matches(SimpleNamespace(name="symphony_compose_score"))+ assert not handler.matches(SimpleNamespace(name="todo_list"))++def _ctx(session,tool_name: str,@@ -138,6 +151,33 @@ async def test_stream_event_rail_does_not_enable_symphony_status_events_for_planassert not any(chunk.type == "chat.symphony_status" for chunk in session.chunks)+async def test_stream_event_rail_emits_beam_progress_as_tool_update():+ rail = JiuSwarmStreamEventRail()+ session = _StreamSession()+ ctx = _ctx(session, "symphony_compose_score", tool_call_id="beam-call")++ await rail.before_tool_call(ctx)+ callback = current_tool_progress()+ assert callback is not None+ await callback({+ "event": "started",+ "language": "cn",+ "round_index": 0,+ "graph": {+ "nodes": [{"id": "seed", "label": "Seed", "status": "seed"}],+ "edges": [],+ },+ })++ updates = [chunk for chunk in session.chunks if chunk.type == "tool_update"]+ assert updates[-1].payload["tool_update"]["tool_call_id"] == "beam-call"+ assert updates[-1].payload["tool_update"]["beam_search_event"]["event"] == "started"++ await rail.after_tool_call(ctx)+ assert current_tool_progress() is None++@pytest.mark.asyncioasync def test_stream_event_rail_force_finishes_symphony_compose_score_result():rail = JiuSwarmStreamEventRail()@@ -145,11 +185,16 @@ async def test_stream_event_rail_force_finishes_symphony_compose_score_result():result = {"success": True,"direct_display": True,- "display_format": "markdown","content": "## Symphony plan\n\n```mermaid\nflowchart LR\n A --> B\n```",- "mermaid": "flowchart LR\n A --> B","score_status": {"success": True, "exists": True, "stale": False},"score_build": {"rebuilt": False, "reason": "not_required"},+ "beam_search": {+ "round_index": 2,+ "graph": {+ "nodes": [{"id": "skill-a", "status": "final"}],+ "edges": [],+ },+ },}ctx = _ctx(session, "symphony_compose_score", tool_result=result)@@ -168,6 +213,8 @@ async def test_stream_event_rail_force_finishes_symphony_compose_score_result():assert tool_results[0]["raw_output"] == resultassert tool_results[0]["score_status"] == result["score_status"]assert tool_results[0]["score_build"] == result["score_build"]+ assert "beam_search" not in tool_results[0]+ assert tool_results[0]["raw_output"]["beam_search"] == result["beam_search"]assert tool_results[0]["direct_display"] is Truedirect_messages = [chunk for chunk in session.chunks if chunk.type == "chat.final"]assert direct_messages == []diff --git a/tests/unit_tests/agentserver/test_system_prompt_restructure.py b/tests/unit_tests/agentserver/test_system_prompt_restructure.pyindex 05c4481a95..ee03671826 100644--- a/tests/unit_tests/agentserver/test_system_prompt_restructure.py+++ b/tests/unit_tests/agentserver/test_system_prompt_restructure.py@@ -4,7 +4,10 @@ from unittest.mock import patchimport pytestfrom openjiuwen.core.foundation.llm import Model-from openjiuwen.core.single_agent.rail.base import AgentCallbackContext+from openjiuwen.core.single_agent.rail.base import (+ AgentCallbackContext,+ ToolCallInputs,+)from openjiuwen.harness.rails.skills.skill_use_rail import SkillUseRailfrom openjiuwen.harness.prompts.prompt_attachment_manager import (PromptAttachmentManager,@@ -20,8 +23,8 @@ from jiuwenswarm.agents.harness.common.prompt.prompt_builder import (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,+from jiuwenswarm.agents.harness.common.rails.symphony import (+ SymphonyOrchestrationRail,)@@ -101,6 +104,30 @@ class _FakeRuntimeInstance:self.ability_manager = _FakeAbilityManager()+def _tool_call_ctx(+ tool_name: str,+ args: dict,+ *,+ extra: dict | None = None,+ result: object | None = None,+):+ tool_call = SimpleNamespace(+ id=f"{tool_name}-call",+ name=tool_name,+ arguments=dict(args),+ )+ return SimpleNamespace(+ inputs=ToolCallInputs(+ tool_call=tool_call,+ tool_name=tool_name,+ tool_args=dict(args),+ tool_result={"success": True} if result is None else result,+ ),+ extra={} if extra is None else extra,+ exception=None,+ )++def test_build_agent_identity_prompt_contains_identity_section_only():prompt = build_agent_identity_prompt(language="zh")@@ -111,7 +138,7 @@ def test_build_agent_identity_prompt_contains_identity_section_only():@pytest.mark.asyncio-async def test_symphony_orchestration_prompt_rail_respects_config_snapshot():+async def test_symphony_orchestration_rail_respects_config_snapshot():enabled_builder = SystemPromptBuilder(language="cn")enabled_agent = _FakeAgent(enabled_builder)enabled_ctx = AgentCallbackContext(@@ -122,7 +149,7 @@ async def test_symphony_orchestration_prompt_rail_respects_config_snapshot():session=_FakeSession(),extra={},)- enabled_rail = SymphonyOrchestrationPromptRail(+ enabled_rail = SymphonyOrchestrationRail(config_base={"symphony": {"enabled": True}},)enabled_rail.init(enabled_agent)@@ -138,7 +165,7 @@ async def test_symphony_orchestration_prompt_rail_respects_config_snapshot():session=_FakeSession(),extra={},)- disabled_rail = SymphonyOrchestrationPromptRail(+ disabled_rail = SymphonyOrchestrationRail(config_base={"symphony": {"enabled": False}},)disabled_rail.init(disabled_agent)@@ -153,7 +180,7 @@ async def test_symphony_orchestration_prompt_rail_respects_config_snapshot():@pytest.mark.asyncio-async def test_symphony_orchestration_prompt_rail_injects_when_tool_visible(+async def test_symphony_orchestration_rail_injects_when_tool_visible(monkeypatch,):monkeypatch.setattr(@@ -171,17 +198,125 @@ async def test_symphony_orchestration_prompt_rail_injects_when_tool_visible(extra={},)- rail = SymphonyOrchestrationPromptRail()+ rail = SymphonyOrchestrationRail()rail.init(agent)await rail.before_model_call(ctx)prompt = builder.build()assert "## Symphony Orchestration" in promptassert "`symphony_compose_score`" in prompt+ assert "exact identifiers or names" in prompt+ assert "Do not omit this field" in prompt+ assert "skill_branch_explore" not in prompt+++async def test_symphony_orchestration_rail_backfills_viewed_skills():+ rail = SymphonyOrchestrationRail()+ invocation_extra: dict = {}++ for skill_name in (+ "creating-financial-models",+ "xlsx",+ "creating-financial-models",+ ):+ await rail.after_tool_call(+ _tool_call_ctx(+ "skill_tool",+ {"skill_name": skill_name},+ extra=invocation_extra,+ )+ )++ compose_ctx = _tool_call_ctx(+ "symphony_compose_score",+ {"query": "build a financial model"},+ extra=invocation_extra,+ )+ await rail.before_tool_call(compose_ctx)++ expected = ["creating-financial-models", "xlsx"]+ assert compose_ctx.inputs.tool_args["candidate_skill_ids"] == expected+ assert compose_ctx.inputs.tool_call.arguments["candidate_skill_ids"] == expected+++async def test_symphony_orchestration_rail_preserves_explicit_candidates():+ rail = SymphonyOrchestrationRail()+ invocation_extra: dict = {}+ await rail.after_tool_call(+ _tool_call_ctx(+ "skill_tool",+ {"skill_name": "viewed-skill"},+ extra=invocation_extra,+ )+ )+ compose_ctx = _tool_call_ctx(+ "symphony_compose_score",+ {"query": "task", "candidate_skill_ids": ["explicit-skill"]},+ extra=invocation_extra,+ )++ await rail.before_tool_call(compose_ctx)++ assert compose_ctx.inputs.tool_args["candidate_skill_ids"] == [+ "explicit-skill"+ ]+++async def test_symphony_orchestration_rail_does_not_reuse_other_invocation():+ rail = SymphonyOrchestrationRail()+ await rail.after_tool_call(+ _tool_call_ctx(+ "skill_tool",+ {"skill_name": "previous-skill"},+ extra={},+ )+ )+ compose_ctx = _tool_call_ctx(+ "symphony_compose_score",+ {"query": "new task"},+ extra={},+ )++ await rail.before_tool_call(compose_ctx)++ assert "candidate_skill_ids" not in compose_ctx.inputs.tool_args+++async def test_symphony_orchestration_rail_ignores_disclosure_and_failed_views():+ rail = SymphonyOrchestrationRail()+ invocation_extra: dict = {}+ await rail.after_tool_call(+ _tool_call_ctx(+ "skill_branch_explore",+ {"node_ids": ["FinanceBusiness"]},+ extra=invocation_extra,+ )+ )+ await rail.after_tool_call(+ _tool_call_ctx(+ "skill_tool",+ {"skill_name": "failed-skill"},+ extra=invocation_extra,+ result={"success": False},+ )+ )+ compose_ctx = _tool_call_ctx(+ "symphony_compose_score",+ {"query": "task"},+ extra=invocation_extra,+ )++ await rail.before_tool_call(compose_ctx)++ assert "candidate_skill_ids" not in compose_ctx.inputs.tool_args@pytest.mark.asyncio-async def test_symphony_orchestration_prompt_rail_clears_when_unavailable(+async def test_symphony_orchestration_rail_clears_when_unavailable(monkeypatch,):monkeypatch.setattr(@@ -204,7 +339,7 @@ async def test_symphony_orchestration_prompt_rail_clears_when_unavailable(extra={},)- rail = SymphonyOrchestrationPromptRail()+ rail = SymphonyOrchestrationRail()rail.init(agent)await rail.before_model_call(ctx)@@ -212,7 +347,7 @@ async def test_symphony_orchestration_prompt_rail_clears_when_unavailable(@pytest.mark.asyncio-async def test_symphony_orchestration_prompt_rail_clears_when_disabled(+async def test_symphony_orchestration_rail_clears_when_disabled(monkeypatch,):monkeypatch.setattr(@@ -230,7 +365,7 @@ async def test_symphony_orchestration_prompt_rail_clears_when_disabled(extra={},)- rail = SymphonyOrchestrationPromptRail()+ rail = SymphonyOrchestrationRail()rail.init(agent)await rail.before_model_call(ctx)diff --git a/tests/unit_tests/symphony/test_beam_planner.py b/tests/unit_tests/symphony/test_beam_planner.pynew file mode 100644index 0000000000..df5473febb--- /dev/null+++ b/tests/unit_tests/symphony/test_beam_planner.py@@ -0,0 +1,604 @@+import asyncio+import json++from jiuwenswarm.symphony.orchestration.artifacts import ScoreArtifacts+from jiuwenswarm.symphony.orchestration.planning.beam import (+ BidirectionalBeamPlanner,+)+++class _FakeBeamLLM:+ def __init__(+ self,+ scores: dict[str, float],+ *,+ delay: float = 0.0,+ rerank_selection: dict | list | None = None,+ ) -> None:+ self.scores = scores+ self.delay = delay+ self.rerank_selection = rerank_selection or {"selected_plan_index": 1}+ self.calls = []+ self.active = 0+ self.max_active = 0++ async def complete_json_async(self, **kwargs):+ self.calls.append(kwargs)+ self.active += 1+ self.max_active = max(self.max_active, self.active)+ try:+ if self.delay:+ await asyncio.sleep(self.delay)+ payload = json.loads(kwargs["user_content"])+ if "candidate_plans" in payload:+ return json.dumps(self.rerank_selection)+ return json.dumps(+ {+ "judgements": [+ {+ "candidate_id": candidate["candidate_id"],+ "score": self.scores.get(candidate["skill"]["id"], 0.9),+ "reason": f"{candidate['skill']['id']} is useful",+ }+ for candidate in payload["candidates"]+ ]+ }+ )+ finally:+ self.active -= 1++ @property+ def judge_calls(self):+ return [+ call+ for call in self.calls+ if "candidates" in json.loads(call["user_content"])+ ]++ @property+ def rerank_calls(self):+ return [+ call+ for call in self.calls+ if "candidate_plans" in json.loads(call["user_content"])+ ]+++async def test_beam_batches_outgoing_neighbors_and_filters_low_scores(tmp_path):+ artifacts = _artifacts(+ tmp_path,+ edges=[+ _edge("skill-a", "skill-b", confidence=0.91),+ _edge("skill-a", "skill-c", confidence=0.88),+ _edge("skill-a", "skill-d", confidence=0.2),+ ],+ )+ llm = _FakeBeamLLM({"skill-b": 0.9, "skill-c": 0.4})++ result = await _planner(+ artifacts,+ llm,+ top_k=2,+ max_depth=2,+ candidate_skill_ids=["skill-a"],+ ).plan("compose an alpha plan")++ assert result["planning_mode"] == "bidirectional_beam"+ assert result["llm_call_count"] == 2+ assert result["decision"]["judge_llm_call_count"] == 1+ assert result["recommended_plans"][0]["title"] == "compose an alpha plan"+ assert result["beam_search"]["round_index"] == 1+ graph_nodes = {item["id"]: item for item in result["beam_search"]["graph"]["nodes"]}+ assert graph_nodes["skill-a"]["status"] == "final"+ assert graph_nodes["skill-a"]["seed"] is True+ assert graph_nodes["skill-b"]["status"] == "final"+ assert graph_nodes["skill-c"]["status"] == "rejected"+ payload = json.loads(llm.judge_calls[0]["user_content"])+ assert set(payload) == {+ "query",+ "direction",+ "current_skill",+ "candidates",+ }+ assert payload["direction"] == "forward"+ assert [item["skill"]["id"] for item in payload["candidates"]] == [+ "skill-b",+ "skill-c",+ ]+ assert all(set(item) == {"candidate_id", "skill"} for item in payload["candidates"])+ assert (+ "Write all user-visible natural-language fields in Simplified Chinese"+ in (llm.judge_calls[0]["system_prompt"])+ )+ assert _plan_signatures(result) == {("skill-a", "skill-b")}+++async def test_beam_scores_incoming_neighbors_for_backward_expansion(tmp_path):+ artifacts = _artifacts(+ tmp_path,+ edges=[+ _edge("skill-a", "skill-c", confidence=0.91),+ _edge("skill-b", "skill-c", confidence=0.89),+ ],+ )+ llm = _FakeBeamLLM({"skill-a": 0.8, "skill-b": 0.9})++ result = await _planner(+ artifacts,+ llm,+ top_k=2,+ max_depth=2,+ candidate_skill_ids=["skill-c"],+ ).plan("prepare the final output")++ payload = json.loads(llm.judge_calls[0]["user_content"])+ assert payload["direction"] == "backward"+ assert {item["skill"]["id"] for item in payload["candidates"]} == {+ "skill-a",+ "skill-b",+ }+ assert _plan_signatures(result) == {+ ("skill-a", "skill-c"),+ ("skill-b", "skill-c"),+ }+++async def test_beam_reuses_same_round_judgement_for_duplicate_skill_edge(tmp_path):+ artifacts = _artifacts(+ tmp_path,+ edges=[+ _edge("skill-a", "skill-shared", confidence=0.91),+ _edge("skill-c", "skill-shared", confidence=0.9),+ _edge("skill-shared", "skill-d", confidence=0.89),+ ],+ )+ llm = _FakeBeamLLM({"skill-shared": 0.9, "skill-d": 0.95})++ result = await _planner(+ artifacts,+ llm,+ top_k=2,+ max_depth=3,+ candidate_skill_ids=["skill-a", "skill-c"],+ ).plan("finish through the shared skill")++ assert result["llm_call_count"] == 4+ assert len(llm.judge_calls) == 3+ assert len(llm.rerank_calls) == 1+ first_round_current_skills = {+ json.loads(call["user_content"])["current_skill"]["id"]+ for call in llm.judge_calls[:2]+ }+ assert first_round_current_skills == {"skill-a", "skill-c"}+ final_payload = json.loads(llm.judge_calls[-1]["user_content"])+ assert [item["skill"]["id"] for item in final_payload["candidates"]] == ["skill-d"]+ assert result["decision"]["judge_cache_misses"] >= 3+ assert any("skill-d" in signature for signature in _plan_signatures(result))+++async def test_beam_judges_same_candidate_separately_by_direction(tmp_path):+ artifacts = _artifacts(+ tmp_path,+ edges=[+ _edge("skill-a", "skill-shared", confidence=0.91),+ _edge("skill-shared", "skill-b", confidence=0.9),+ ],+ )+ llm = _FakeBeamLLM({"skill-shared": 0.9})++ result = await _planner(+ artifacts,+ llm,+ top_k=2,+ max_depth=2,+ candidate_skill_ids=["skill-a", "skill-b"],+ ).plan("use the shared skill")++ shared_calls = [+ json.loads(call["user_content"])+ for call in llm.judge_calls+ if any(+ candidate["skill"]["id"] == "skill-shared"+ for candidate in json.loads(call["user_content"])["candidates"]+ )+ ]+ assert result["llm_call_count"] == 3+ assert {payload["direction"] for payload in shared_calls} == {+ "forward",+ "backward",+ }+++async def test_beam_limits_concurrent_judge_requests(tmp_path):+ artifacts = _artifacts(+ tmp_path,+ edges=[+ _edge("skill-a", "skill-b", confidence=0.91),+ _edge("skill-c", "skill-d", confidence=0.9),+ _edge("skill-e", "skill-f", confidence=0.89),+ ],+ )+ llm = _FakeBeamLLM(+ {"skill-b": 0.9, "skill-d": 0.9, "skill-f": 0.9},+ delay=0.02,+ )++ result = await _planner(+ artifacts,+ llm,+ top_k=3,+ max_depth=2,+ candidate_skill_ids=["skill-a", "skill-c", "skill-e"],+ ).plan("run several independent branches")++ assert result["llm_call_count"] == 4+ assert llm.max_active == 3+++async def test_beam_merges_converging_paths_into_dag_plan(tmp_path):+ artifacts = _artifacts(+ tmp_path,+ edges=[+ _edge("skill-a", "skill-c", confidence=0.91),+ _edge("skill-b", "skill-c", confidence=0.9),+ ],+ )+ llm = _FakeBeamLLM({"skill-c": 0.9})++ result = await _planner(+ artifacts,+ llm,+ top_k=3,+ max_depth=2,+ candidate_skill_ids=["skill-a", "skill-b"],+ ).plan("merge two preparation skills")++ assert ("skill-a", "skill-b", "skill-c") in _plan_signatures(result)+ merged = next(+ plan+ for plan in result["recommended_plans"]+ if tuple(step["skill_id"] for step in plan["steps"])+ == ("skill-a", "skill-b", "skill-c")+ )+ assert {+ (edge["source_id"], edge["target_id"]) for edge in merged["can_feed_edges"]+ } == {("skill-a", "skill-c"), ("skill-b", "skill-c")}+ graph = result["beam_search"]["graph"]+ assert sorted(node["id"] for node in graph["nodes"]) == [+ "skill-a",+ "skill-b",+ "skill-c",+ ]+ assert {(edge["source"], edge["target"]) for edge in graph["edges"]} == {+ ("skill-a", "skill-c"),+ ("skill-b", "skill-c"),+ }+ assert {edge["status"] for edge in graph["edges"]} == {"final", "selected"}+++async def test_beam_keeps_diverging_paths_as_separate_plans(tmp_path):+ artifacts = _artifacts(+ tmp_path,+ edges=[+ _edge("skill-a", "skill-b", confidence=0.91),+ _edge("skill-a", "skill-c", confidence=0.9),+ ],+ )+ llm = _FakeBeamLLM({"skill-b": 0.9, "skill-c": 0.9})++ result = await _planner(+ artifacts,+ llm,+ top_k=3,+ max_depth=2,+ candidate_skill_ids=["skill-a"],+ ).plan("choose one downstream path")++ assert _plan_signatures(result) == {+ ("skill-a", "skill-b"),+ ("skill-a", "skill-c"),+ }+++async def test_beam_final_rerank_selects_second_plan(tmp_path):+ artifacts = _artifacts(+ tmp_path,+ edges=[+ _edge("skill-a", "skill-b", confidence=0.91),+ _edge("skill-a", "skill-c", confidence=0.9),+ ],+ )+ llm = _FakeBeamLLM(+ {"skill-b": 0.9, "skill-c": 0.9},+ rerank_selection={+ "selected_plan_index": 2,+ "reason": "skill c better matches the task",+ },+ )++ result = await _planner(+ artifacts,+ llm,+ top_k=2,+ max_depth=2,+ candidate_skill_ids=["skill-a"],+ ).plan("choose the best downstream skill")++ assert tuple(+ step["skill_id"] for step in result["recommended_plans"][0]["steps"]+ ) == ("skill-a", "skill-c")+ assert result["decision"]["final_rerank"] == {+ "applied": True,+ "llm_call_count": 1,+ "cross_plan_skill_merge": False,+ "error": "",+ }+ rerank_payload = json.loads(llm.rerank_calls[0]["user_content"])+ assert set(rerank_payload) == {+ "query",+ "required_output_types",+ "candidate_skill_pool",+ "candidate_can_feed_edges",+ "candidate_plans",+ }+ assert {item["id"] for item in rerank_payload["candidate_skill_pool"]} == {+ "skill-a",+ "skill-b",+ "skill-c",+ }+ assert {+ (edge["source_id"], edge["target_id"])+ for edge in rerank_payload["candidate_can_feed_edges"]+ } == {("skill-a", "skill-b"), ("skill-a", "skill-c")}+++async def test_beam_final_rerank_merges_paths_without_seed_guard(tmp_path):+ artifacts = _artifacts(+ tmp_path,+ edges=[+ _edge("skill-a", "skill-b", confidence=0.91),+ _edge("skill-a", "skill-c", confidence=0.9),+ ],+ )+ llm = _FakeBeamLLM(+ {"skill-b": 0.9, "skill-c": 0.9},+ rerank_selection={+ "selected_plan_index": 1,+ "reason": "both delivery skills are required",+ "steps": [+ {"skill_id": "skill-b", "reason": "first deliverable"},+ {"skill_id": "skill-c", "reason": "second deliverable"},+ ],+ "can_feed_edges": [],+ },+ )++ result = await _planner(+ artifacts,+ llm,+ top_k=2,+ max_depth=2,+ candidate_skill_ids=["skill-a"],+ ).plan("produce two independent deliverables")++ primary = result["recommended_plans"][0]+ assert tuple(step["skill_id"] for step in primary["steps"]) == (+ "skill-b",+ "skill-c",+ )+ assert primary["can_feed_edges"] == []+ assert [step["skill_id"] for step in primary["stages"][0]["skills"]] == [+ "skill-b",+ "skill-c",+ ]+ assert primary["source"] == "bidirectional_beam_final_rerank"+ assert result["decision"]["final_rerank"]["cross_plan_skill_merge"] is True+++async def test_beam_final_rerank_drops_unknown_items_without_rejecting(tmp_path):+ artifacts = _artifacts(+ tmp_path,+ edges=[_edge("skill-a", "skill-b", confidence=0.91)],+ )+ llm = _FakeBeamLLM(+ {"skill-b": 0.9},+ rerank_selection={+ "steps": ["unknown-skill", "skill-a", "skill-b"],+ "can_feed_edges": [+ {"source_id": "skill-b", "target_id": "skill-a"},+ {"source_id": "skill-a", "target_id": "skill-b"},+ ],+ },+ )++ result = await _planner(+ artifacts,+ llm,+ top_k=1,+ max_depth=2,+ candidate_skill_ids=["skill-a"],+ ).plan("compose a plan")++ primary = result["recommended_plans"][0]+ assert tuple(step["skill_id"] for step in primary["steps"]) == (+ "skill-a",+ "skill-b",+ )+ assert [+ (edge["source_id"], edge["target_id"]) for edge in primary["can_feed_edges"]+ ] == [("skill-a", "skill-b")]+ assert result["decision"]["final_rerank"]["applied"] is True+ assert result["decision"]["final_rerank"]["error"] == ""+++async def test_beam_final_rerank_malformed_response_falls_back(tmp_path):+ artifacts = _artifacts(+ tmp_path,+ edges=[_edge("skill-a", "skill-b", confidence=0.91)],+ )+ llm = _FakeBeamLLM(+ {"skill-b": 0.9},+ rerank_selection=["not", "an", "object"],+ )++ result = await _planner(+ artifacts,+ llm,+ top_k=1,+ max_depth=2,+ candidate_skill_ids=["skill-a"],+ ).plan("compose a plan")++ assert _plan_signatures(result) == {("skill-a", "skill-b")}+ assert result["decision"]["final_rerank"]["applied"] is False+ assert (+ result["decision"]["final_rerank"]["error"]+ == "Final rerank returned non-object JSON."+ )+++async def test_beam_progress_callback_receives_lightweight_graph_events(tmp_path):+ artifacts = _artifacts(+ tmp_path,+ edges=[+ _edge("skill-a", "skill-b", confidence=0.91),+ _edge("skill-a", "skill-c", confidence=0.88),+ ],+ )+ llm = _FakeBeamLLM({"skill-b": 0.9, "skill-c": 0.4})+ events = []++ async def progress_callback(event):+ events.append(event)++ result = await _planner(+ artifacts,+ llm,+ top_k=2,+ max_depth=2,+ candidate_skill_ids=["skill-a"],+ progress_callback=progress_callback,+ ).plan("compose an alpha plan")++ assert [event["event"] for event in events] == [+ "started",+ "candidates_found",+ "candidates_judged",+ "graph_merged",+ "completed",+ ]+ assert result["language"] == "cn"+ assert result["beam_search"]["language"] == "cn"+ assert all(event["language"] == "cn" for event in events)+ assert all(+ set(event) == {"event", "language", "round_index", "graph"} for event in events+ )+ judged_nodes = {node["id"]: node for node in events[2]["graph"]["nodes"]}+ assert judged_nodes["skill-b"]["status"] == "selected"+ assert judged_nodes["skill-c"]["status"] == "rejected"+++async def test_beam_judge_reason_uses_english_without_seed_copy(tmp_path):+ artifacts = _artifacts(+ tmp_path,+ edges=[_edge("skill-a", "skill-b", confidence=0.91)],+ )+ llm = _FakeBeamLLM({"skill-b": 0.9})++ result = await _planner(+ artifacts,+ llm,+ top_k=1,+ max_depth=2,+ candidate_skill_ids=["skill-a"],+ language="en",+ ).plan("compose a plan")++ prompt = llm.calls[0]+ payload = json.loads(prompt["user_content"])+ assert "language" not in payload+ assert "language_instruction" not in payload+ assert "state" not in payload+ assert (+ "Write all user-visible natural-language fields in English"+ in (prompt["system_prompt"])+ )+ assert result["reason"] == "skill-b is useful"+++def _planner(+ artifacts: ScoreArtifacts,+ llm: _FakeBeamLLM,+ *,+ top_k: int,+ max_depth: int,+ candidate_skill_ids: list[str],+ progress_callback=None,+ language="cn",+) -> BidirectionalBeamPlanner:+ return BidirectionalBeamPlanner(+ artifacts,+ llm_config=None,+ llm_client=llm,+ min_edge_confidence=0.7,+ top_k=top_k,+ max_depth=max_depth,+ candidate_skill_ids=candidate_skill_ids,+ progress_callback=progress_callback,+ language=language,+ )+++def _artifacts(+ tmp_path,+ *,+ edges: list[dict[str, object]],+) -> ScoreArtifacts:+ skill_ids = sorted(+ {endpoint for edge in edges for endpoint in (edge["source"], edge["target"])}+ )+ return ScoreArtifacts(+ score_dir=tmp_path,+ manifest={},+ skills=[+ {+ "id": current_skill_id,+ "name": current_skill_id.replace("-", " ").title(),+ "description": f"{current_skill_id} description",+ "inputs": [{"name": "input", "type": "text", "required": True}],+ "outputs": [{"name": current_skill_id, "type": "text"}],+ }+ for current_skill_id in skill_ids+ ],+ graph={"edges": edges},+ lookup={},+ )+++def _edge(+ source: str,+ target: str,+ *,+ confidence: float,+) -> dict[str, object]:+ return {+ "type": "can_feed",+ "source": source,+ "target": target,+ "confidence": confidence,+ "method": "llm",+ "evidence": {+ "reasons": [f"{source} feeds {target}"],+ "supporting_fields": {+ "source_outputs": [source],+ "target_inputs": ["input"],+ },+ },+ }+++def _plan_signatures(result: dict[str, object]) -> set[tuple[str, ...]]:+ return {+ tuple(step["skill_id"] for step in plan["steps"])+ for plan in result["recommended_plans"]+ }diff --git a/tests/unit_tests/symphony/test_config.py b/tests/unit_tests/symphony/test_config.pyindex cf972698a8..9842c5d018 100644--- a/tests/unit_tests/symphony/test_config.py+++ b/tests/unit_tests/symphony/test_config.py@@ -88,16 +88,16 @@ def test_symphony_config_normalizes_values(monkeypatch, tmp_path):assert cfg.enabled is True[email protected]("mode", ["fast", "", None])-def test_symphony_config_accepts_fast_mode_aliases(mode):[email protected]("mode", ["fast", "beam", "", None])+def test_symphony_config_accepts_supported_orchestration_modes(mode):cfg = symphony_config.symphony_config_from_dict({"orchestration": {"mode": mode}})- assert cfg.orchestration.mode == "fast"+ assert cfg.orchestration.mode == (mode or "fast")[email protected]("mode", ["beam", "default", "graph", "unknown", "quick"])[email protected]("mode", ["default", "graph", "unknown", "quick"])def test_symphony_config_rejects_non_llm_orchestration_modes(mode):with pytest.raises(ValueError, match="Unsupported Symphony orchestration mode"):symphony_config.symphony_config_from_dict(diff --git a/tests/unit_tests/symphony/test_extension.py b/tests/unit_tests/symphony/test_extension.pyindex 83c2bfc0a5..f5946b8a0d 100644--- a/tests/unit_tests/symphony/test_extension.py+++ b/tests/unit_tests/symphony/test_extension.py@@ -1,6 +1,7 @@import asyncioimport jsonfrom pathlib import Path+from types import SimpleNamespaceimport pytest@@ -30,6 +31,12 @@ def _use_chinese_preferred_language(monkeypatch):lambda: {"preferred_language": "zh"},)+ async def fresh_score(self, params=None, request=None):+ del self, params, request+ return {"success": True, "exists": True, "stale": False}++ monkeypatch.setattr(SymphonyExtension, "score_status", fresh_score)+class _Registry:def __init__(self):@@ -52,7 +59,9 @@ def test_extension_registers_rpc_handlers():def test_symphony_skill_metadata():- skill_md = Path("jiuwenswarm/extensions/symphony/skills/symphony-assistant/SKILL.md")+ skill_md = Path(+ "jiuwenswarm/extensions/symphony/skills/symphony-assistant/SKILL.md"+ )content = skill_md.read_text(encoding="utf-8")assert "name: symphony-assistant" in content@@ -75,10 +84,56 @@ def test_extension_requires_query():assert "query is required" in result["detail"]+def test_plan_refreshes_stale_score_in_extension(monkeypatch, tmp_path):+ extension = SymphonyExtension()+ calls = []++ async def stale_status(params=None, request=None):+ del params, request+ calls.append("status")+ return {"success": True, "exists": True, "stale": True}++ async def build_score(params=None, request=None):+ del params, request+ calls.append("build")+ return {"success": True}++ async def plan_from_score(*args, **kwargs):+ del args, kwargs+ calls.append("plan")+ return {"status": "ready", "recommended_plans": []}++ monkeypatch.setattr(extension, "score_status", stale_status)+ monkeypatch.setattr(extension, "build_score", build_score)+ monkeypatch.setattr(+ "jiuwenswarm.extensions.symphony.extension.plan_from_score",+ plan_from_score,+ )+ monkeypatch.setattr(+ "jiuwenswarm.extensions.symphony.extension.load_symphony_config",+ lambda: symphony_config_from_dict(+ {"paths": {"score_dir": str(tmp_path / "score")}}+ ),+ )+ monkeypatch.setattr(+ "jiuwenswarm.extensions.symphony.extension.LLMConfig.from_default_model",+ lambda: object(),+ )++ result = asyncio.run(extension.plan({"query": "compose"}))++ assert calls == ["status", "build", "plan"]+ assert result["score_build"] == {"success": True, "rebuilt": True}++def test_plan_uses_llm_plan_from_score(monkeypatch, tmp_path):configured_score_dir = tmp_path / "configured"llm_config = object()seen = {}+ monkeypatch.setattr(+ "jiuwenswarm.extensions.symphony.extension.get_config",+ lambda: {"preferred_language": "zh"},+ )monkeypatch.setattr("jiuwenswarm.extensions.symphony.extension.load_symphony_config",lambda: symphony_config_from_dict(@@ -121,11 +176,95 @@ def test_plan_uses_llm_plan_from_score(monkeypatch, tmp_path):assert result["success"] is Trueassert result["mode"] == "fast"assert result["direct_display"] is True- assert result["display_format"] == "markdown"+ assert "display_format" not in resultassert seen["score_dir"] == configured_score_dir.resolve()assert seen["query"] == "do work"assert seen["llm_config"] is llm_configassert "orchestration_config" in seen["kwargs"]+ assert seen["kwargs"]["language"] == "cn"+++def test_plan_ignores_internal_language_parameter(monkeypatch, tmp_path):+ configured_score_dir = tmp_path / "configured"+ seen = {}+ monkeypatch.setattr(+ "jiuwenswarm.extensions.symphony.extension.load_symphony_config",+ lambda: symphony_config_from_dict(+ {"paths": {"score_dir": str(configured_score_dir)}}+ ),+ )+ monkeypatch.setattr(+ "jiuwenswarm.extensions.symphony.extension.load_score_artifacts",+ lambda score_dir: {"score_dir": str(score_dir)},+ )+ monkeypatch.setattr(+ "jiuwenswarm.extensions.symphony.extension.LLMConfig.from_default_model",+ lambda: object(),+ )++ async def fake_plan_from_score(*args, **kwargs):+ del args+ seen.update(kwargs)+ return {+ "status": "ready",+ "recommended_plans": [],+ "execution_graph": {"edges": []},+ }++ monkeypatch.setattr(+ "jiuwenswarm.extensions.symphony.extension.plan_from_score",+ fake_plan_from_score,+ )++ result = asyncio.run(+ SymphonyExtension().plan({"query": "do work", "language": "en"})+ )++ assert result["language"] == "cn"+ assert result["content"].startswith("## Symphony 编排计划")+ assert seen["language"] == "cn"+++def test_plan_resolves_language_from_runtime_config(monkeypatch, tmp_path):+ configured_score_dir = tmp_path / "configured"+ seen = {}+ monkeypatch.setattr(+ "jiuwenswarm.extensions.symphony.extension.get_config",+ lambda: {"preferred_language": "en"},+ )+ monkeypatch.setattr(+ "jiuwenswarm.extensions.symphony.extension.load_symphony_config",+ lambda: symphony_config_from_dict(+ {"paths": {"score_dir": str(configured_score_dir)}}+ ),+ )+ monkeypatch.setattr(+ "jiuwenswarm.extensions.symphony.extension.load_score_artifacts",+ lambda score_dir: {"score_dir": str(score_dir)},+ )+ monkeypatch.setattr(+ "jiuwenswarm.extensions.symphony.extension.LLMConfig.from_default_model",+ lambda: object(),+ )++ async def fake_plan_from_score(*args, **kwargs):+ del args+ seen.update(kwargs)+ return {+ "status": "ready",+ "recommended_plans": [],+ "execution_graph": {"edges": []},+ }++ monkeypatch.setattr(+ "jiuwenswarm.extensions.symphony.extension.plan_from_score",+ fake_plan_from_score,+ )++ result = asyncio.run(SymphonyExtension().plan({"query": "do work"}))++ assert result["language"] == "en"+ assert seen["language"] == "en"def test_plan_uses_requested_fast_mode(monkeypatch, tmp_path):@@ -160,9 +299,7 @@ def test_plan_uses_requested_fast_mode(monkeypatch, tmp_path):fake_plan_from_score,)- result = asyncio.run(- SymphonyExtension().plan({"query": "do work", "mode": "fast"})- )+ result = asyncio.run(SymphonyExtension().plan({"query": "do work", "mode": "fast"}))assert result["success"] is Trueassert result["mode"] == "fast"@@ -290,22 +427,106 @@ def test_graph_filters_disabled_skills_from_visual_payload(monkeypatch, tmp_path}-def test_plan_rejects_requested_beam_mode(monkeypatch, tmp_path):+def test_plan_uses_requested_beam_mode(monkeypatch, tmp_path):configured_score_dir = tmp_path / "configured"+ seen = {}monkeypatch.setattr("jiuwenswarm.extensions.symphony.extension.load_symphony_config",lambda: symphony_config_from_dict({"paths": {"score_dir": str(configured_score_dir)}}),)+ monkeypatch.setattr(+ "jiuwenswarm.extensions.symphony.extension.load_score_artifacts",+ lambda score_dir: {"score_dir": str(score_dir)},+ )+ monkeypatch.setattr(+ "jiuwenswarm.extensions.symphony.extension.LLMConfig.from_default_model",+ lambda: object(),+ )++ async def fake_plan_from_score(score_dir, query, received_llm_config, **kwargs):+ del score_dir, query, received_llm_config+ seen["orchestration_config"] = kwargs["orchestration_config"]+ return {+ "status": "ready",+ "recommended_plans": [],+ "execution_graph": {"edges": []},+ }++ monkeypatch.setattr(+ "jiuwenswarm.extensions.symphony.extension.plan_from_score",+ fake_plan_from_score,+ )++ result = asyncio.run(SymphonyExtension().plan({"query": "do work", "mode": "beam"}))++ assert result["success"] is True+ assert result["mode"] == "beam"+ assert seen["orchestration_config"].mode == "beam"+++def test_plan_streams_beam_progress_events(monkeypatch, tmp_path):+ configured_score_dir = tmp_path / "configured"+ events = []+ monkeypatch.setattr(+ "jiuwenswarm.extensions.symphony.extension.load_symphony_config",+ lambda: symphony_config_from_dict(+ {+ "paths": {"score_dir": str(configured_score_dir)},+ "orchestration": {"mode": "beam"},+ }+ ),+ )+ monkeypatch.setattr(+ "jiuwenswarm.extensions.symphony.extension.load_score_artifacts",+ lambda score_dir: {"score_dir": str(score_dir)},+ )+ monkeypatch.setattr(+ "jiuwenswarm.extensions.symphony.extension.LLMConfig.from_default_model",+ lambda: object(),+ )++ async def fake_plan_from_score(score_dir, query, received_llm_config, **kwargs):+ del score_dir, query, received_llm_config+ await kwargs["progress_callback"](+ {+ "event": "started",+ "language": "en",+ "round_index": 0,+ "graph": {"nodes": [], "edges": []},+ }+ )+ return {+ "status": "ready",+ "recommended_plans": [],+ "execution_graph": {"edges": []},+ "beam_search": {"graph": {"nodes": [], "edges": []}},+ }++ monkeypatch.setattr(+ "jiuwenswarm.extensions.symphony.extension.plan_from_score",+ fake_plan_from_score,+ )+ request = SimpleNamespace(+ metadata={+ "symphony_progress_callback": lambda event: events.append(event),+ }+ )result = asyncio.run(- SymphonyExtension().plan({"query": "do work", "mode": "beam"})+ SymphonyExtension().plan({"query": "do work", "mode": "beam"}, request))- assert result["success"] is False- assert result["mode"] == "fast"- assert "Unsupported Symphony orchestration mode: beam" in result["detail"]+ assert result["success"] is True+ assert events == [+ {+ "event": "started",+ "language": "en",+ "round_index": 0,+ "graph": {"nodes": [], "edges": []},+ }+ ]def test_plan_presentation_uses_recommended_plan(monkeypatch, tmp_path):@@ -363,6 +584,44 @@ def test_plan_presentation_uses_recommended_plan(monkeypatch, tmp_path):}]},+ "beam_search": {+ "language": "cn",+ "round_index": 1,+ "graph": {+ "nodes": [+ {+ "id": "skill-1",+ "label": "Skill 1",+ "status": "final",+ "seed": True,+ },+ {+ "id": "skill-2",+ "label": "Skill 2",+ "status": "final",+ "seed": False,+ },+ {+ "id": "skill-3",+ "label": "Skill 3",+ "status": "rejected",+ "seed": False,+ },+ ],+ "edges": [+ {+ "source": "skill-1",+ "target": "skill-2",+ "status": "final",+ },+ {+ "source": "skill-1",+ "target": "skill-3",+ "status": "rejected",+ },+ ],+ },+ },}monkeypatch.setattr(@@ -374,13 +633,17 @@ def test_plan_presentation_uses_recommended_plan(monkeypatch, tmp_path):assert result["success"] is Trueassert "## Recommended Plan" in result["content"]- assert result["markdown"] == result["content"]+ assert "markdown" not in resultassert result["direct_display"] is True- assert result["display_format"] == "markdown"+ assert "display_format" not in resultassert "Status:" not in result["content"]assert result["result"]["recommended_plans"][0]["status"] == "ready"assert "Best match." in result["content"]assert result["content"].endswith("是否按照上述编排结果执行?")+ assert "## Beam search" not in result["content"]+ assert "classDef rejected" not in result["content"]+ assert "score `0.91`" not in result["content"]+ assert "strong can_feed match" not in result["content"]assert "Missing inputs:" not in result["content"]assert "收件邮箱地址" not in result["content"]assert "imap-smtp-email" not in result["content"]@@ -396,19 +659,13 @@ def test_plan_presentation_uses_recommended_plan(monkeypatch, tmp_path):result["result"]["recommended_plans"][0]["can_feed_edges"][0]["confidence"]== 0.91)- assert 'N1["Skill 1"]' in result["mermaid"]- assert "N1 --> N2" in result["mermaid"]- assert "-->|" not in result["mermaid"]- assert "0.91" not in result["mermaid"]+ assert 'N1["Skill 1"]' in result["content"]+ assert "N1 --> N2" in result["content"]def test_plan_presentation_does_not_ask_to_execute_empty_plan():presentation = _build_presentation(- {- "recommended_plans": [- {"title": "Empty Plan", "status": "ready", "steps": []}- ]- }+ {"recommended_plans": [{"title": "Empty Plan", "status": "ready", "steps": []}]})assert "是否按照上述编排结果执行?" not in presentation["markdown"]@@ -435,11 +692,7 @@ def test_plan_presentation_asks_to_execute_in_english():def test_plan_presentation_does_not_ask_to_execute_no_plan():presentation = _build_presentation(- {- "recommended_plans": [- {"title": "No Plan", "status": "no_plan", "steps": []}- ]- }+ {"recommended_plans": [{"title": "No Plan", "status": "no_plan", "steps": []}]})assert "是否按照上述编排结果执行?" not in presentation["markdown"]@@ -482,7 +735,9 @@ def test_build_score_awaits_service_and_records_build_log(monkeypatch, tmp_path)async def fake_build_score(*args, **kwargs):seen["args"] = argsseen["kwargs"] = kwargs- kwargs["build_log"]("fingerprint.extract.start", current=1, total=1, path="skill-1")+ kwargs["build_log"](+ "fingerprint.extract.start", current=1, total=1, path="skill-1"+ )return _Result()monkeypatch.setattr(diff --git a/tests/unit_tests/symphony/test_language.py b/tests/unit_tests/symphony/test_language.pynew file mode 100644index 0000000000..1fa7ee3f6c--- /dev/null+++ b/tests/unit_tests/symphony/test_language.py@@ -0,0 +1,20 @@+from jiuwenswarm.symphony.orchestration.language import (+ default_plan_title,+ resolve_orchestration_language,+)+++def test_resolve_orchestration_language_maps_config_values() -> None:+ assert resolve_orchestration_language("zh") == "cn"+ assert resolve_orchestration_language("cn") == "cn"+ assert resolve_orchestration_language("en") == "en"+++def test_resolve_orchestration_language_falls_back_to_chinese() -> None:+ assert resolve_orchestration_language("fr") == "cn"+ assert resolve_orchestration_language(None) == "cn"+++def test_deterministic_copy_uses_selected_language() -> None:+ assert default_plan_title("cn") == "Symphony 编排计划"+ assert default_plan_title("en") == "Symphony plan"diff --git a/tests/unit_tests/symphony/test_planning_modules.py b/tests/unit_tests/symphony/test_planning_modules.pyindex 1b57b5b8a2..6f0e10757c 100644--- a/tests/unit_tests/symphony/test_planning_modules.py+++ b/tests/unit_tests/symphony/test_planning_modules.py@@ -1,25 +1,16 @@from jiuwenswarm.symphony.orchestration.planning.models import (ArtifactRef,- GroundedQuery,- OrchestrationPlan,PlanStep,SearchState,)from jiuwenswarm.symphony.orchestration.planning.plan_builder import (- compose_dag_plans,- compose_plan_group,plan_stages,state_to_plan,- topological_step_ids,)-def test_plan_stages_and_topological_sort_parallelize_roots():- steps = [- _step("review"),- _step("draft"),- _step("publish"),- ]+def test_plan_stages_parallelizes_roots():+ steps = [_step("review"), _step("draft"), _step("publish")]edges = [{"source_id": "draft", "target_id": "publish"},{"source_id": "review", "target_id": "publish"},@@ -27,15 +18,10 @@ def test_plan_stages_and_topological_sort_parallelize_roots():stages = plan_stages(steps, edges)- assert topological_step_ids({"draft", "review", "publish"}, edges) == [- "draft",- "review",- "publish",+ assert [[skill["skill_id"] for skill in stage["skills"]] for stage in stages] == [+ ["draft", "review"],+ ["publish"],]- assert [- [skill["skill_id"] for skill in stage["skills"]]- for stage in stages- ] == [["draft", "review"], ["publish"]]def test_state_to_plan_projects_inputs_outputs_and_edge_metadata():@@ -73,103 +59,24 @@ def test_state_to_plan_projects_inputs_outputs_and_edge_metadata():]plan = state_to_plan(- state=SearchState(- skill_ids=("draft", "review"),- available=frozenset({("brief", "text")}),- edges=(0,),- ),- grounded=GroundedQuery(- query="make a reviewed draft",- available_artifacts=[ArtifactRef(name="brief", type="text")],- seed_skill_ids=("review",),- ),+ state=SearchState(skill_ids=("draft", "review"), edges=(0,)),+ seed_skill_ids=("review",),skill_by_id=skills,can_feed_edges=edges,)- assert plan.status == "ready"+ assert plan.status == "needs_input"assert [step.skill_id for step in plan.steps] == ["draft", "review"]- assert plan.missing_inputs == []- assert plan.consumed_user_artifacts == 1+ assert plan.missing_inputs == [+ {"name": "brief", "type": "text", "skill_id": "draft"}+ ]+ assert plan.consumed_user_artifacts == 0assert plan.produced_artifacts == [ArtifactRef(name="draft", type="markdown", source="skill_output"),ArtifactRef(name="review", type="markdown", source="skill_output"),]- assert plan.can_feed_edges == [- {- "source_id": "draft",- "target_id": "review",- "confidence": 0.92,- "method": "llm",- "port_mappings": [{"source_output": "draft", "target_input": "draft"}],- "source_outputs": ["draft"],- "target_inputs": ["draft"],- "reasons": ["draft feeds review"],- }- ]---def test_compose_plan_group_merges_steps_edges_and_reorders_by_dependencies():- draft = _step("draft")- review = _step("review")- publish = _step("publish")- left = _plan(- [publish, draft],- [{"source_id": "draft", "target_id": "publish", "confidence": 0.8}],- )- right = _plan(- [review, draft],- [{"source_id": "draft", "target_id": "review", "confidence": 0.9}],- )-- composed = compose_plan_group([left, right])-- assert [step.skill_id for step in composed.steps] == [- "draft",- "publish",- "review",- ]- assert round(composed.edge_confidence, 2) == 0.85- assert composed.status == "ready"---def test_compose_dag_plans_keeps_unrelated_seed_plans_separate():- left = _plan(- [_step("draft"), _step("review")],- [{"source_id": "draft", "target_id": "review", "confidence": 0.8}],- )- right = _plan(- [_step("outline"), _step("publish")],- [{"source_id": "outline", "target_id": "publish", "confidence": 0.9}],- )-- composed_plans = compose_dag_plans([left, right], max_plans=10)-- signatures = {- tuple(step.skill_id for step in plan.steps) for plan in composed_plans- }- assert signatures == {("draft", "review"), ("outline", "publish")}---def test_compose_dag_plans_dedupes_edges_by_highest_confidence():- low_confidence = _plan(- [_step("draft"), _step("review")],- [{"source_id": "draft", "target_id": "review", "confidence": 0.4}],- )- high_confidence = _plan(- [_step("draft"), _step("review")],- [{"source_id": "draft", "target_id": "review", "confidence": 0.9}],- )-- composed_plans = compose_dag_plans(- [low_confidence, high_confidence],- max_plans=10,- )-- assert len(composed_plans) == 1- assert composed_plans[0].can_feed_edges == [- {"source_id": "draft", "target_id": "review", "confidence": 0.9}- ]+ assert plan.can_feed_edges[0]["source_id"] == "draft"+ assert plan.can_feed_edges[0]["target_id"] == "review"def _step(skill_id: str) -> PlanStep:@@ -179,20 +86,3 @@ def _step(skill_id: str) -> PlanStep:inputs=[],outputs=[],)---def _plan(- steps: list[PlanStep],- edges: list[dict[str, object]],-) -> OrchestrationPlan:- return OrchestrationPlan(- steps=steps,- produced_artifacts=[],- missing_inputs=[],- can_feed_edges=edges,- goal_score=1.0,- edge_confidence=1.0,- consumed_user_artifacts=0,- status="ready",- reasons=[],- )diff --git a/tests/unit_tests/symphony/test_service.py b/tests/unit_tests/symphony/test_service.pyindex de33034c8e..56279f8398 100644--- a/tests/unit_tests/symphony/test_service.py+++ b/tests/unit_tests/symphony/test_service.py@@ -118,10 +118,12 @@ async def test_plan_from_score_fast_uses_one_shot_planner(monkeypatch, tmp_path)mode="fast",min_edge_confidence=0.7,),+ language="en",)assert len(llm.calls) == 1assert result["planning_mode"] == "one_shot_fast"+ assert result["language"] == "en"assert result["llm_call_count"] == 1assert result["recommended_plans"][0]["title"] == "Fast plan"assert result["recommended_plans"][0]["steps"][0]["inputs"] == [@@ -134,6 +136,14 @@ async def test_plan_from_score_fast_uses_one_shot_planner(monkeypatch, tmp_path)prompt_payload = json.loads(llm.calls[0]["user_content"])assert set(prompt_payload) == {"query", "skills", "can_feed_edges"}+ assert "language" not in prompt_payload+ assert "planning_instructions" not in prompt_payload+ assert "Write all user-visible natural-language fields in English" in (+ llm.calls[0]["system_prompt"]+ )+ assert "Keep Skill IDs, original Skill names, status values" in (+ llm.calls[0]["system_prompt"]+ )assert prompt_payload["can_feed_edges"] == [{"source_id": "skill-a",@@ -467,6 +477,76 @@ async def test_plan_from_score_fast_without_candidates_uses_default_subgraph(}+async def test_plan_from_score_resolves_unique_skill_names(+ monkeypatch,+ tmp_path,+):+ artifacts = _artifacts(tmp_path)+ llm = _FakeLLMClient(+ {+ "title": "Named candidate plan",+ "status": "ready",+ "steps": [{"skill_id": "skill-b", "reason": "Named seed."}],+ "can_feed_edges": [],+ }+ )+ monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)++ result = await service.plan_from_score(+ tmp_path,+ "use beta",+ llm_client=llm,+ orchestration_config=SymphonyOrchestrationConfig(mode="fast"),+ candidate_skill_ids=["Beta Skill", "skill-a", "Beta Skill"],+ )++ assert result["skill_retrieval"]["candidate_skill_ids"] == [+ "skill-b",+ "skill-a",+ ]+++async def test_plan_from_score_does_not_guess_ambiguous_skill_names(+ monkeypatch,+ tmp_path,+):+ artifacts = _artifacts(tmp_path)+ artifacts.skills.append(+ {+ "id": "skill-beta-copy",+ "name": "Beta Skill",+ "description": "Another skill with the same display name.",+ "inputs": [],+ "outputs": [],+ }+ )+ llm = _FakeLLMClient(+ {+ "title": "Fallback plan",+ "status": "ready",+ "steps": [{"skill_id": "skill-a", "reason": "Fallback."}],+ "can_feed_edges": [],+ }+ )+ monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)++ result = await service.plan_from_score(+ tmp_path,+ "use beta",+ llm_client=llm,+ orchestration_config=SymphonyOrchestrationConfig(mode="fast"),+ candidate_skill_ids=["Beta Skill"],+ )++ assert result["skill_retrieval"] == {+ "source": "input",+ "used": False,+ "candidate_skill_ids": [],+ "candidate_count": 0,+ "fallback_reason": "candidate_skill_ids did not match current score",+ }++@pytest.mark.parametrize(("candidate_skill_ids", "fallback_reason"),[@@ -518,16 +598,60 @@ async def test_plan_from_score_fast_falls_back_for_empty_or_unknown_candidates(}-async def test_plan_from_score_rejects_non_fast_mode(monkeypatch, tmp_path):+async def test_plan_from_score_beam_uses_bidirectional_planner(monkeypatch, tmp_path):+ artifacts = _artifacts(tmp_path)+ seen = {}++ class FakeBeamPlanner:+ def __init__(self, artifacts_arg, **kwargs):+ seen["artifacts"] = artifacts_arg+ seen["kwargs"] = kwargs++ async def plan(self, query):+ seen["query"] = query+ return {+ "planning_mode": "bidirectional_beam",+ "recommended_plans": [],+ "plans": [],+ "status": "no_plan",+ }++ monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)+ monkeypatch.setattr(service, "BidirectionalBeamPlanner", FakeBeamPlanner)++ result = await service.plan_from_score(+ tmp_path,+ "beam plan",+ llm_client=object(),+ orchestration_config=SymphonyOrchestrationConfig(+ mode="beam",+ top_k=2,+ max_depth=3,+ min_edge_confidence=0.7,+ ),+ candidate_skill_ids=["skill-a", "unknown"],+ )++ assert result["planning_mode"] == "bidirectional_beam"+ assert result["execution_graph"]["nodes"] == []+ assert result["skill_retrieval"]["candidate_skill_ids"] == ["skill-a"]+ assert seen["artifacts"] is artifacts+ assert seen["query"] == "beam plan"+ assert seen["kwargs"]["top_k"] == 2+ assert seen["kwargs"]["max_depth"] == 3+ assert seen["kwargs"]["candidate_skill_ids"] == ("skill-a",)+++async def test_plan_from_score_rejects_unknown_mode(monkeypatch, tmp_path):artifacts = _artifacts(tmp_path)monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)with pytest.raises(ValueError, match="Unsupported orchestration mode"):await service.plan_from_score(tmp_path,- "beam plan",+ "graph plan",llm_client=object(),- orchestration_config=SymphonyOrchestrationConfig(mode="beam"),+ orchestration_config=SymphonyOrchestrationConfig(mode="graph"),)@@ -837,8 +961,6 @@ async def test_fast_plan_rejects_invalid_inferred_edges(assert result["success"] is Falseassert detail in result["detail"]--async def test_fast_plan_drops_single_step_self_loop_edge(monkeypatch, tmp_path):artifacts = _artifacts(tmp_path)llm = _FakeLLMClient(diff --git a/tests/unit_tests/symphony/test_toolkit.py b/tests/unit_tests/symphony/test_toolkit.pyindex 86facfc6e2..7ff843cf88 100644--- a/tests/unit_tests/symphony/test_toolkit.py+++ b/tests/unit_tests/symphony/test_toolkit.py@@ -1,9 +1,12 @@import asyncio-import jsonfrom types import SimpleNamespaceimport pytest+from jiuwenswarm.agents.harness.common.tool_progress_context import (+ bind_tool_progress,+ reset_tool_progress,+)from jiuwenswarm.agents.harness.common.tools.symphony_toolkits import (SymphonyToolkit,)@@ -30,11 +33,9 @@ def teardown_function():@pytest.fixture(autouse=True)def enabled_symphony_config(monkeypatch):def fake_load_symphony_config(config=None):- if isinstance(config, dict):- raw = config.get("symphony")- if isinstance(raw, dict) and "enabled" in raw:- return SimpleNamespace(enabled=bool(raw["enabled"]))- return SimpleNamespace(enabled=True)+ raw = config.get("symphony") if isinstance(config, dict) else None+ enabled = raw.get("enabled", True) if isinstance(raw, dict) else True+ return SimpleNamespace(enabled=bool(enabled))monkeypatch.setattr("jiuwenswarm.agents.harness.common.tools.symphony_toolkits.load_symphony_config",@@ -42,780 +43,182 @@ def enabled_symphony_config(monkeypatch):)-def _write_score_metadata(- tmp_path,- *,- version="score-v1",- created_at="2026-06-13T10:00:00+00:00",-):- score_dir = tmp_path / "score"- version_dir = score_dir / "versions" / version- version_dir.mkdir(parents=True)- (score_dir / "current.json").write_text(- json.dumps(- {- "schema_version": "Symphony-score-pointer-v1",- "version": version,- "path": f"versions/{version}",- }- ),- encoding="utf-8",- )- (version_dir / "score_manifest.json").write_text(- json.dumps({"created_at": created_at}),- encoding="utf-8",- )- return score_dir---def test_toolkit_calls_rpc_handler():- registry = ExtensionRegistry.create_instance(+def _registry() -> ExtensionRegistry:+ return ExtensionRegistry.create_instance(callback_framework=_CallbackFramework(),config={},logger=object(),)- seen = {}-- async def handler(params, request=None):- seen.update(params)- return {- "success": True,- "params": params,- "presentation": {- "markdown": "## Recommended Plan\n\nUse installed skills.",- "mermaid": "flowchart LR\n A",- },- }- registry.register_rpc_handler("symphony.plan", handler)- registry.register_rpc_handler(- "symphony.score_status",- lambda _params, request=None: {"success": True, "exists": True, "stale": False},- )- result = asyncio.run(SymphonyToolkit().plan("use installed skills"))-- assert result["success"] is True- assert result["score_status"] == {"success": True, "exists": True, "stale": False}- assert result["score_build"] == {"rebuilt": False, "reason": "not_required"}- assert result["content"].startswith("## Recommended Plan")- assert "## Symphony score" not in result["content"]- assert "Status: `fresh`" not in result["content"]- assert "Update: `not required`" not in result["content"]- for key in ("params", "result", "presentation", "markdown", "summary"):- assert key not in result- assert seen["query"] == "use installed skills"---def test_toolkit_passes_fast_mode_to_rpc_handler():- registry = ExtensionRegistry.create_instance(- callback_framework=_CallbackFramework(),- config={},- logger=object(),- )- seen = {}+def test_plan_calls_compose_rpc_once_without_language():+ registry = _registry()+ calls = []async def handler(params, request=None):del request- seen.update(params)- return {"success": True, "params": params}+ calls.append(params)+ return {"success": True, "content": "## Plan", "direct_display": True}registry.register_rpc_handler("symphony.plan", handler)- registry.register_rpc_handler(- "symphony.score_status",- lambda _params, request=None: {"success": True, "exists": True, "stale": False},- )- result = asyncio.run(SymphonyToolkit().plan("use installed skills", mode="fast"))+ result = asyncio.run(SymphonyToolkit().plan("use installed skills"))- assert result["success"] is True- assert "params" not in result- assert seen["mode"] == "fast"+ assert calls == [{"query": "use installed skills"}]+ assert result == {+ "success": True,+ "content": "## Plan",+ "direct_display": True,+ "continue_after_display": True,+ "followup_action": "external_skill_discovery",+ }-def test_toolkit_passes_candidate_skill_ids_to_rpc_handler():- registry = ExtensionRegistry.create_instance(- callback_framework=_CallbackFramework(),- config={},- logger=object(),- )+def test_plan_passes_mode_and_deduplicated_candidates():+ registry = _registry()seen = {}async def handler(params, request=None):del requestseen.update(params)- return {"success": True, "params": params}+ return {"success": True}registry.register_rpc_handler("symphony.plan", handler)- registry.register_rpc_handler(- "symphony.score_status",- lambda _params, request=None: {"success": True, "exists": True, "stale": False},- )- result = asyncio.run(+ asyncio.run(SymphonyToolkit().plan(- "use installed skills",- candidate_skill_ids=[" skill-a ", "", "skill-a", "skill-b"],+ "compose",+ mode="beam",+ candidate_skill_ids=["skill-a", "skill-a", "Skill B"],))- assert result["success"] is True- assert "params" not in result- assert seen["candidate_skill_ids"] == ["skill-a", "skill-b"]+ assert seen == {+ "query": "compose",+ "mode": "beam",+ "candidate_skill_ids": ["skill-a", "Skill B"],+ }-def test_toolkit_reports_missing_handler():- ExtensionRegistry.create_instance(- callback_framework=_CallbackFramework(),- config={},- logger=object(),- )+def test_plan_preserves_progress_callback_on_extension_request():+ registry = _registry()+ events = []- result = asyncio.run(SymphonyToolkit().score_status())+ async def handler(params, request=None):+ del params+ callback = request.metadata["symphony_progress_callback"]+ await callback({"event": "started", "graph": {"nodes": [], "edges": []}})+ return {"success": True}- assert result["success"] is False- assert "symphony.score_status" in result["detail"]+ registry.register_rpc_handler("symphony.plan", handler)+ token = bind_tool_progress(events.append)+ try:+ asyncio.run(SymphonyToolkit().plan("compose", mode="beam"))+ finally:+ reset_tool_progress(token)+ assert events == [{"event": "started", "graph": {"nodes": [], "edges": []}}]-def test_toolkit_plan_refreshes_stale_score_before_planning():- registry = ExtensionRegistry.create_instance(- callback_framework=_CallbackFramework(),- config={},- logger=object(),- )- calls = []- async def score_status(params, request=None):- del params, request- calls.append("score_status")- return {"success": True, "exists": True, "stale": True}+def test_plan_returns_compact_plan_and_beam_graph():+ registry = _registry()- async def build_score(params, request=None):+ async def handler(params, request=None):del params, request- calls.append("build_score")return {"success": True,- "updated": True,- "llm_token_usage": {"total": {"total_tokens": 123}},- "build_progress": {- "stage": "update.done",- "label": "done",- "percent": 100,- "status": "success",- "current": 1,- "total": 1,- "ts": "drop-me",- "llm_token_usage": {"total": {"total_tokens": 123}},+ "content": "## Beam Plan",+ "result": {+ "beam_search": {+ "language": "cn",+ "round_index": 2,+ "graph": {+ "nodes": [+ {+ "id": "skill-a",+ "label": "Skill A",+ "status": "final",+ "seed": True,+ "unused": "drop",+ }+ ],+ "edges": [],+ },+ },+ "recommended_plans": [+ {+ "title": "Plan",+ "status": "ready",+ "steps": [{"skill_id": "skill-a", "name": "Skill A"}],+ "can_feed_edges": [],+ "missing_inputs": [],+ }+ ],},}- async def plan(params, request=None):- del request- calls.append("plan")- return {- "success": True,- "params": params,- "presentation": {- "markdown": "## Recommended Plan\n\nUse refreshed score.",- "mermaid": "flowchart LR\n A",- },- }-- registry.register_rpc_handler("symphony.score_status", score_status)- registry.register_rpc_handler("symphony.build_score", build_score)- registry.register_rpc_handler("symphony.plan", plan)-- result = asyncio.run(SymphonyToolkit().plan("compose installed skills"))-- assert calls == ["score_status", "build_score", "plan"]- assert result["success"] is True- assert result["score_build"] == {- "rebuilt": True,- "success": True,- "build_progress": {- "stage": "update.done",- "label": "done",- "percent": 100,- "status": "success",- "current": 1,- "total": 1,- },- "llm_total_tokens": 123,- }- assert result["content"].startswith("## Recommended Plan")- assert "Status: `stale`" not in result["content"]- assert "Update: `succeeded`" not in result["content"]- assert "Build tokens: `123`" not in result["content"]---def test_toolkit_plan_succeeds_for_fresh_score(tmp_path):- registry = ExtensionRegistry.create_instance(- callback_framework=_CallbackFramework(),- config={},- logger=object(),- )- score_dir = _write_score_metadata(tmp_path)- registry.register_rpc_handler(- "symphony.score_status",- lambda _params, request=None: {- "success": True,- "score_dir": str(score_dir),- "exists": True,- "stale": False,- "build_progress": {- "stage": "update.done",- "label": "done",- "percent": 100,- "status": "success",- "llm_token_usage": {"total": {"total_tokens": 999}},- },- "llm_token_usage": {"total": {"total_tokens": 999}},- },- )- registry.register_rpc_handler(- "symphony.plan",- lambda params, request=None: {- "success": True,- "params": params,- "presentation": {- "markdown": "## Recommended Plan\n\nUse fresh score.",- "mermaid": "flowchart LR\n A",- },- },- )-- result = asyncio.run(SymphonyToolkit().plan("compose installed skills"))-- assert result["success"] is True- assert result["score_build"] == {- "rebuilt": False,- "reason": "not_required",- "version": "score-v1",- "score_created_at": "2026-06-13T10:00:00+00:00",- }- assert "build_progress" not in result["score_status"]- assert "llm_token_usage" not in result["score_status"]- assert "llm_total_tokens" not in result["score_build"]- assert result["content"].startswith("## Recommended Plan")- assert "Score created: `2026-06-13T10:00:00+00:00`" not in result["content"]---def test_toolkit_plan_succeeds_after_refreshing_stale_score():- registry = ExtensionRegistry.create_instance(- callback_framework=_CallbackFramework(),- config={},- logger=object(),- )- registry.register_rpc_handler(- "symphony.score_status",- lambda _params, request=None: {"success": True, "exists": True, "stale": True},- )- registry.register_rpc_handler(- "symphony.build_score",- lambda _params, request=None: {"success": True, "updated": True},- )- registry.register_rpc_handler(- "symphony.plan",- lambda params, request=None: {"success": True, "params": params},- )-- result = asyncio.run(SymphonyToolkit().plan("compose installed skills"))-- assert result["success"] is True---def test_toolkit_plan_returns_compact_failure_when_score_build_fails():- registry = ExtensionRegistry.create_instance(- callback_framework=_CallbackFramework(),- config={},- logger=object(),- )- registry.register_rpc_handler(- "symphony.score_status",- lambda _params, request=None: {"success": True, "exists": True, "stale": True},- )- registry.register_rpc_handler(- "symphony.build_score",- lambda _params, request=None: {- "success": False,- "detail": "build failed",- "llm_token_usage": {"total": {"total_tokens": 999}},- "build_progress": {- "stage": "update.failed",- "label": "failed",- "percent": 100,- "status": "error",- "llm_token_usage": {"total": {"total_tokens": 999}},- },- },- )-- result = asyncio.run(SymphonyToolkit().plan("compose installed skills"))-- assert result["success"] is False- assert result["score_build"] == {- "rebuilt": True,- "success": False,- "detail": "build failed",- "build_progress": {- "stage": "update.failed",- "label": "failed",- "percent": 100,- "status": "error",- },- }- assert "llm_token_usage" not in result["score_build"]- assert "llm_total_tokens" not in result["score_build"]---def test_toolkit_plan_returns_failure_when_score_status_fails():- ExtensionRegistry.create_instance(- callback_framework=_CallbackFramework(),- config={},- logger=object(),- )-- result = asyncio.run(SymphonyToolkit().plan("compose installed skills"))-- assert result["success"] is False- assert "symphony.score_status" in result["detail"]---def test_toolkit_plan_preserves_display_content_after_score_summary():- registry = ExtensionRegistry.create_instance(- callback_framework=_CallbackFramework(),- config={},- logger=object(),- )- registry.register_rpc_handler(- "symphony.score_status",- lambda _params, request=None: {- "success": True,- "exists": True,- "stale": False,- "reason": "up to date",- },- )- registry.register_rpc_handler(- "symphony.plan",- lambda _params, request=None: {- "success": True,- "presentation": {- "markdown": (- "## Recommended Plan\n\nUse skill A, then skill B.\n\n"- "是否按照上述编排结果执行?"- ),- "mermaid": "flowchart LR\n A --> B",- },- },- )-- result = asyncio.run(SymphonyToolkit().plan("compose installed skills"))-- assert result["direct_display"] is True- assert result["display_format"] == "markdown"- assert result["content"].startswith("## Recommended Plan")- assert result["content"].endswith("是否按照上述编排结果执行?")- assert "## Symphony score" not in result["content"]- assert "Detail: up to date" not in result["content"]- assert result["mermaid"] == "flowchart LR\n A --> B"- for key in ("result", "presentation", "markdown", "summary"):- assert key not in result---def test_toolkit_complete_plan_defaults_to_force_finish_display():- registry = ExtensionRegistry.create_instance(- callback_framework=_CallbackFramework(),- config={},- logger=object(),- )- registry.register_rpc_handler(- "symphony.score_status",- lambda _params, request=None: {"success": True, "exists": True, "stale": False},- )- registry.register_rpc_handler(- "symphony.plan",- lambda _params, request=None: {- "success": True,- "status": "ready",- "recommended_plans": [- {- "status": "ready",- "steps": [{"skill_id": "skill-a"}],- "missing_inputs": [],- }- ],- "execution_graph": {"nodes": [{"id": "skill-a"}]},- "presentation": {"markdown": "## Plan", "mermaid": "flowchart LR\n A"},- },- )-- result = asyncio.run(SymphonyToolkit().plan("compose skill plan"))-- assert result["continue_after_display"] is False- assert "followup_action" not in result-+ registry.register_rpc_handler("symphony.plan", handler)-def test_toolkit_plan_returns_compact_plan_and_skill_retrieval():- registry = ExtensionRegistry.create_instance(- callback_framework=_CallbackFramework(),- config={},- logger=object(),- )- candidate_records = [- {- "rank": index,- "skill_id": f"skill-{index}",- "worker_id": f"worker-{index}",- "resolved_payload": f"skill-{index}",- "skill_name": f"Skill {index}",- "score": 1.0 - index / 100,- "source": "structured_retrieval",- "extra": "drop",- }- for index in range(12)- ]+ result = asyncio.run(SymphonyToolkit().plan("compose", mode="beam"))- registry.register_rpc_handler(- "symphony.score_status",- lambda _params, request=None: {- "success": True,- "score_dir": "drop-me",- "exists": True,- "stale": False,- "skill_count": 12,- "build_progress": {- "stage": "graph.resolve.progress",- "label": "Resolving",- "percent": 72,- "status": "running",- "current": 7,- "total": 10,- "ts": "drop-me",- "llm_token_usage": {"total": {"total_tokens": 456}},- },- },- )- registry.register_rpc_handler(- "symphony.plan",- lambda params, request=None: {- "success": True,- "score_dir": "drop-me",- "query": "drop me",- "mode": params.get("mode"),- "planning_mode": "one_shot_fast",- "llm_call_count": 1,- "candidate_skill_count": 2,- "candidate_edge_count": 1,- "status": "ready",- "recommended_plans": [+ assert result["beam_search"] == {+ "language": "cn",+ "round_index": 2,+ "graph": {+ "nodes": [{- "title": "Compact Plan",- "status": "ready",- "reason": "Use this plan.",- "steps": [- {- "step": 1,- "skill_id": "skill-1",- "name": "Skill 1",- "inputs": [{"name": "brief", "type": "text"}],- "outputs": [{"name": "draft", "type": "markdown"}],- "reason": "matches request",- "extra": "drop",- }- ],- "can_feed_edges": [- {- "source_id": "skill-1",- "target_id": "skill-2",- "confidence": 0.91,- "evidence": {"drop": True},- }- ],- "missing_inputs": [- {"skill_id": "skill-1", "name": "brief", "type": "text"}- ],- "produced_artifacts": [{"name": "draft", "type": "markdown"}],+ "id": "skill-a",+ "label": "Skill A",+ "status": "final",+ "seed": True,}],- "skill_retrieval": {- "source": "input",- "used": True,- "candidate_skill_ids": ["skill-1", "skill-2"],- "candidate_count": 2,- "fallback_reason": "",- "candidate_records": candidate_records,- },- "validation": {"valid": True, "drop": "debug details"},- "execution_graph": {- "nodes": [{"id": "skill-1", "description": "drop"}],- "edges": [{"source": "skill-1", "target": "skill-2"}],- },- "presentation": {- "markdown": "## Compact Plan\n\nUse Skill 1.",- "mermaid": "flowchart LR\n A",- },+ "edges": [],},- )-- result = asyncio.run(- SymphonyToolkit().plan("compose compact skill plan", mode="fast")- )-- assert result["success"] is True- assert "## Compact Plan" in result["content"]- assert result["mermaid"] == "flowchart LR\n A"- for key in (- "result",- "presentation",- "markdown",- "summary",- "score_dir",- "query",- "execution_graph",- "validation",- ):- assert key not in result- assert result["plan"] == {- "title": "Compact Plan",- "status": "ready",- "reason": "Use this plan.",- "steps": [- {- "step": 1,- "skill_id": "skill-1",- "reason": "matches request",- "name": "Skill 1",- }- ],- "can_feed_edges": [- {"source_id": "skill-1", "target_id": "skill-2", "confidence": 0.91}- ],- "missing_inputs": [- {"skill_id": "skill-1", "name": "brief", "type": "text"}- ],- }- assert result["metrics"] == {- "planning_mode": "one_shot_fast",- "llm_call_count": 1,- "candidate_skill_count": 2,- "candidate_edge_count": 1,- "mode": "fast",- }- skill_retrieval = result["skill_retrieval"]- assert "build_progress" not in result["score_status"]- assert result["score_build"] == {"rebuilt": False, "reason": "not_required"}- assert skill_retrieval["source"] == "input"- assert skill_retrieval["candidate_skill_ids"] == ["skill-1", "skill-2"]- assert skill_retrieval["candidate_count"] == 2- assert len(skill_retrieval["candidate_records"]) == 10- assert skill_retrieval["candidate_records"][0] == {- "rank": 0,- "skill_id": "skill-0",- "skill_name": "Skill 0",- "score": 1.0,- "source": "structured_retrieval",- }- assert "worker_id" not in skill_retrieval["candidate_records"][0]- assert "resolved_payload" not in skill_retrieval["candidate_records"][0]---def test_toolkit_compacts_inferred_edge_provenance():- edge = SymphonyToolkit._compact_can_feed_edge(- {- "source_id": "skill-a",- "target_id": "skill-b",- "confidence": None,- "method": "fast_llm_inferred",- "reason": "LLM connected retrieved candidates.",- "port_mappings": [],- }- )-- assert edge == {- "source_id": "skill-a",- "target_id": "skill-b",- "confidence": None,- "method": "fast_llm_inferred",- "reason": "LLM connected retrieved candidates.",}+ assert result["plan"]["steps"] == [+ {"step": 1, "skill_id": "skill-a", "name": "Skill A"}+ ]+ assert "result" not in result-def test_toolkit_no_plan_continues_for_skill_discovery():- registry = ExtensionRegistry.create_instance(- callback_framework=_CallbackFramework(),- config={},- logger=object(),- )- registry.register_rpc_handler(- "symphony.score_status",- lambda _params, request=None: {"success": True, "exists": True, "stale": False},- )- registry.register_rpc_handler(- "symphony.plan",- lambda _params, request=None: {- "success": True,- "status": "no_plan",- "recommended_plans": [{"status": "no_plan", "steps": []}],- "execution_graph": {"nodes": []},- "presentation": {"markdown": "## No plan", "mermaid": "flowchart LR\n none"},- },- )+def test_plan_reports_missing_rpc_handler():+ _registry()- result = asyncio.run(SymphonyToolkit().plan("compose missing skill plan"))+ result = asyncio.run(SymphonyToolkit().plan("compose"))- assert result["continue_after_display"] is True- assert result["followup_action"] == "external_skill_discovery"+ assert result["success"] is False+ assert "handler not registered" in result["detail"]-def test_toolkit_needs_input_does_not_continue_for_skill_discovery():- registry = ExtensionRegistry.create_instance(- callback_framework=_CallbackFramework(),- config={},- logger=object(),- )+def test_status_and_refresh_remain_explicit_tools():+ registry = _registry()registry.register_rpc_handler("symphony.score_status",- lambda _params, request=None: {"success": True, "exists": True, "stale": False},+ lambda params, request=None: {"success": True, "exists": True},)registry.register_rpc_handler(- "symphony.plan",- lambda _params, request=None: {- "success": True,- "status": "needs_input",- "recommended_plans": [- {- "status": "needs_input",- "steps": [],- "missing_inputs": [{"name": "brief", "type": "text"}],- }- ],- "execution_graph": {"nodes": []},- "presentation": {"markdown": "## Need input", "mermaid": "flowchart LR\n none"},- },- )-- result = asyncio.run(SymphonyToolkit().plan("compose skill plan"))-- assert result["continue_after_display"] is False- assert "followup_action" not in result---def test_toolkit_plan_stops_when_score_status_fails():- registry = ExtensionRegistry.create_instance(- callback_framework=_CallbackFramework(),- config={},- logger=object(),- )- calls = []-- async def plan(params, request=None):- del params, request- calls.append("plan")- return {"success": True}-- registry.register_rpc_handler("symphony.plan", plan)-- result = asyncio.run(SymphonyToolkit().plan("compose installed skills"))-- assert result["success"] is False- assert "symphony.score_status failed" in result["detail"]- assert calls == []---def test_toolkit_execution_respects_latest_disabled_config(monkeypatch):- registry = ExtensionRegistry.create_instance(- callback_framework=_CallbackFramework(),- config={},- logger=object(),- )- calls = []-- async def score_status(params, request=None):- del params, request- calls.append("score_status")- return {"success": True, "exists": True, "stale": False}-- async def build_score(params, request=None):- del params, request- calls.append("build_score")- return {"success": True}-- async def plan(params, request=None):- del params, request- calls.append("plan")- return {"success": True}-- registry.register_rpc_handler("symphony.score_status", score_status)- registry.register_rpc_handler("symphony.build_score", build_score)- registry.register_rpc_handler("symphony.plan", plan)- monkeypatch.setattr(- "jiuwenswarm.agents.harness.common.tools.symphony_toolkits.load_symphony_config",- lambda config=None: SimpleNamespace(enabled=False),- )-- status = asyncio.run(SymphonyToolkit().score_status())- refresh = asyncio.run(SymphonyToolkit().refresh_score())- result = asyncio.run(SymphonyToolkit().plan("compose installed skills"))-- assert status["success"] is False- assert status["disabled"] is True- assert refresh["success"] is False- assert refresh["disabled"] is True- assert result["success"] is False- assert result["disabled"] is True- assert "symphony.enabled=false" in result["detail"]- assert calls == []---def test_toolkit_get_tools_respects_symphony_enabled(monkeypatch):- monkeypatch.setattr(- "jiuwenswarm.agents.harness.common.tools.symphony_toolkits.load_symphony_config",- lambda: SimpleNamespace(enabled=False),+ "symphony.build_score",+ lambda params, request=None: {"success": True, "rebuilt": True},)- assert SymphonyToolkit().get_tools() == []+ assert asyncio.run(SymphonyToolkit().score_status())["exists"] is True+ assert asyncio.run(SymphonyToolkit().refresh_score())["rebuilt"] is True- monkeypatch.setattr(- "jiuwenswarm.agents.harness.common.tools.symphony_toolkits.load_symphony_config",- lambda: SimpleNamespace(enabled=True),- )- tool_names = [tool.card.name for tool in SymphonyToolkit().get_tools()]- assert "symphony_compose_score" in tool_names+def test_get_tools_describes_fast_and_beam_without_language():compose_tool = next(- tool for tool in SymphonyToolkit().get_tools()+ tool+ for tool in SymphonyToolkit().get_tools()if tool.card.name == "symphony_compose_score")- assert compose_tool.card.input_params["properties"]["mode"]["enum"] == ["fast"]- assert compose_tool.card.input_params["properties"]["candidate_skill_ids"] == {- "type": "array",- "items": {"type": "string"},- "description": (- "Optional installed skill worker_id values returned by "- "skill_branch_explore. When provided, Symphony composes "- "from these candidate skills and their eligible neighbors."- ),- }- description = compose_tool.card.description- assert "skill capabilities, skill chaining, skill ordering" in description- assert "skill_branch_explore" in description- assert "candidate_skill_ids" in description- assert "search_skill to discover external skills" in description- assert "install_skill" in description- assert "symphony_refresh_score" in description- assert "currently installed skills" not in description- assert "currently installed skills" not in (- compose_tool.card.input_params["properties"]["query"]["description"]- )+ properties = compose_tool.card.input_params["properties"]+ assert properties["mode"]["enum"] == ["fast", "beam"]+ assert "language" not in properties+ assert "most relevant" in properties["candidate_skill_ids"]["description"]+ assert "fast is the default" in properties["mode"]["description"]-def test_toolkit_get_tools_respects_config_snapshot():- assert SymphonyToolkit().get_tools({"symphony": {"enabled": False}}) == []-- tool_names = [- tool.card.name- for tool in SymphonyToolkit().get_tools({"symphony": {"enabled": True}})- ]- assert "symphony_compose_score" in tool_names+def test_disabled_config_hides_tools():+ assert SymphonyToolkit().get_tools({"symphony": {"enabled": False}}) == []