Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

fix(symphony): Fix the issue of floating cards generated during orchestration

lin-xiaoyue2901630df7b
diff --git a/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py b/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py
index 60d97d198b..bebabaa579 100644
--- a/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py
+++ b/jiuwenswarm/agents/harness/common/prompt/prompt_builder.py
@@ -31,14 +31,23 @@ def _symphony_routing_prompt() -> str:
return """
## Symphony Routing
-When the user says to use skill(s) or 技能 to complete a task, you MUST call
-`symphony_compose_score` with the original user task as `query` before answering.
+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.
Do not manually list skill names, inspect skill folders, choose a skill chain,
-or recommend skills before calling `symphony_compose_score`. After it returns, present its returned `content` or `markdown` directly to the user. If Symphony reports
-missing inputs, ask for those inputs.
-
-For ordinary tasks that do not ask to use installed skills, continue normally
-without Symphony.
+or recommend skills before calling `symphony_compose_score`. After it returns,
+present its returned `content` or `markdown` 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.
"""
diff --git a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
index f71bda8f20..0e765b7ecb 100644
--- a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
@@ -35,10 +35,6 @@ from openjiuwen.harness.workspace.workspace import WorkspaceNode
from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (
convert_interactions_to_ask_user_question,
)
-from jiuwenswarm.agents.harness.common.tools.symphony_status_events import (
- begin_symphony_status_events,
- reset_symphony_status_events,
-)
from jiuwenswarm.common.utils import logger
_TODO_TOOL_NAMES = frozenset(["todo_create", "todo_get", "todo_list", "todo_modify"])
@@ -80,6 +76,8 @@ def _copy_symphony_result_fields(
"display_format",
"mermaid",
"summary",
+ "continue_after_display",
+ "followup_action",
):
if key in raw_output:
payload[key] = raw_output[key]
@@ -280,7 +278,6 @@ 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_status_tokens: dict[str, Any] = {}
def init(self, agent: Any) -> None:
self._deep_agent = agent
@@ -523,14 +520,6 @@ class JiuSwarmStreamEventRail(DeepAgentRail):
tc = ctx.inputs.tool_call
await self._emit_tool_call(session, tc)
await self._emit_tool_update(session, tc, status="in_progress")
- tool_name = str(getattr(tc, "name", "") or "").strip()
- if tool_name == "symphony_compose_score":
- token = begin_symphony_status_events(
- session,
- str(getattr(tc, "id", "") or ""),
- )
- if token is not None:
- self._symphony_status_tokens[str(getattr(tc, "id", ""))] = token
# Track in-flight tool call for cancellation
tc_id = getattr(tc, "id", "")
if tc_id:
@@ -556,11 +545,7 @@ class JiuSwarmStreamEventRail(DeepAgentRail):
self._inflight_tool_calls.pop(tc_id, None)
await self._emit_tool_result(session, tc, ctx.inputs.tool_result)
- await self._emit_symphony_direct_display(session, tc, ctx.inputs.tool_result)
- if tc_id:
- reset_symphony_status_events(
- self._symphony_status_tokens.pop(tc_id, None)
- )
+ self._request_symphony_force_finish(ctx, tc, ctx.inputs.tool_result)
await self._emit_ask_user_question_if_interrupted(
session,
tc,
@@ -644,8 +629,8 @@ class JiuSwarmStreamEventRail(DeepAgentRail):
logger.debug("tool_result emit failed", exc_info=True)
@staticmethod
- async def _emit_symphony_direct_display(
- session: Session,
+ def _request_symphony_force_finish(
+ ctx: AgentCallbackContext,
tool_call: Any,
result: Any,
) -> None:
@@ -655,25 +640,12 @@ class JiuSwarmStreamEventRail(DeepAgentRail):
content = _symphony_direct_display_content(result)
if not content:
return
- payload: dict[str, Any] = {
- "content": content,
- "source": "symphony_compose_score",
- "direct_display": True,
- }
- if isinstance(result, dict):
- for key in ("display_format", "mermaid", "score_status", "score_build"):
- if key in result:
- payload[key] = result[key]
- try:
- await session.write_stream(
- OutputSchema(
- type="chat.final",
- index=0,
- payload=payload,
- )
- )
- except Exception:
- logger.debug("symphony direct display emit failed", exc_info=True)
+ if (
+ isinstance(result, dict)
+ and _boolish_true(result.get("continue_after_display"))
+ ):
+ return
+ ctx.request_force_finish({"output": content, "result_type": "answer"})
@staticmethod
async def _emit_ask_user_question_if_interrupted(
diff --git a/jiuwenswarm/agents/harness/common/tools/symphony_status_events.py b/jiuwenswarm/agents/harness/common/tools/symphony_status_events.py
deleted file mode 100644
index 31d906c61f..0000000000
--- a/jiuwenswarm/agents/harness/common/tools/symphony_status_events.py
+++ /dev/null
@@ -1,83 +0,0 @@
-"""Frontend-visible Symphony planning status events."""
-
-from __future__ import annotations
-
-from contextvars import ContextVar, Token
-from dataclasses import dataclass
-from typing import Any
-
-from openjiuwen.core.session.agent import Session
-from openjiuwen.core.session.stream import OutputSchema
-
-from jiuwenswarm.common.utils import logger
-
-
-@dataclass(frozen=True)
-class SymphonyStatusContext:
- session: Session
- operation_id: str
-
-
-_CURRENT_CONTEXT: ContextVar[SymphonyStatusContext | None] = ContextVar(
- "symphony_status_context",
- default=None,
-)
-
-
-def begin_symphony_status_events(
- session: Session | None,
- operation_id: str,
-) -> Token[SymphonyStatusContext | None] | None:
- event_id = str(operation_id or "").strip()
- if session is None or not event_id:
- return None
- return _CURRENT_CONTEXT.set(
- SymphonyStatusContext(session=session, operation_id=event_id)
- )
-
-
-def reset_symphony_status_events(
- token: Token[SymphonyStatusContext | None] | None,
-) -> None:
- if token is None:
- return
- try:
- _CURRENT_CONTEXT.reset(token)
- except Exception:
- logger.debug("failed to reset Symphony status context", exc_info=True)
-
-
-async def emit_symphony_status(
- phase: str,
- content: str,
- *,
- status: str = "in_progress",
- detail: str | None = None,
-) -> None:
- context = _CURRENT_CONTEXT.get()
- if context is None:
- return
- phase_text = str(phase or "").strip()
- content_text = str(content or "").strip()
- if not phase_text or not content_text:
- return
- payload: dict[str, Any] = {
- "source": "symphony_compose_score",
- "operation_id": context.operation_id,
- "phase": phase_text,
- "content": content_text,
- "status": str(status or "").strip() or "in_progress",
- }
- detail_text = str(detail or "").strip()
- if detail_text:
- payload["detail"] = detail_text
- try:
- await context.session.write_stream(
- OutputSchema(
- type="chat.symphony_status",
- index=0,
- payload=payload,
- )
- )
- except Exception:
- logger.debug("Symphony status event emit failed", exc_info=True)
diff --git a/jiuwenswarm/agents/harness/common/tools/symphony_toolkits.py b/jiuwenswarm/agents/harness/common/tools/symphony_toolkits.py
index eaf401106f..6f6b79a855 100644
--- a/jiuwenswarm/agents/harness/common/tools/symphony_toolkits.py
+++ b/jiuwenswarm/agents/harness/common/tools/symphony_toolkits.py
@@ -11,9 +11,6 @@ from openjiuwen.core.foundation.tool import LocalFunction, Tool, ToolCard
from jiuwenswarm.extensions.registry import ExtensionRegistry
from jiuwenswarm.symphony.config import load_symphony_config
-from jiuwenswarm.agents.harness.common.tools.symphony_status_events import (
- emit_symphony_status,
-)
logger = logging.getLogger(__name__)
@@ -150,6 +147,61 @@ class SymphonyToolkit:
payload.setdefault("display_format", "markdown")
payload.setdefault("direct_display", True)
+ @staticmethod
+ def _primary_plan(payload: dict[str, Any]) -> dict[str, Any]:
+ for key in ("recommended_plans", "plans"):
+ plans = payload.get(key)
+ if not isinstance(plans, list):
+ continue
+ for plan in plans:
+ if isinstance(plan, dict):
+ return plan
+ return {}
+
+ @classmethod
+ def _planning_payload(cls, payload: dict[str, Any]) -> dict[str, Any]:
+ result = payload.get("result")
+ return result if isinstance(result, dict) else payload
+
+ @classmethod
+ 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()
+ missing_inputs = (
+ plan.get("missing_inputs")
+ or planning_payload.get("missing_inputs")
+ or []
+ )
+ if status == "needs_input" or missing_inputs:
+ return False
+ if status == "no_plan":
+ return True
+
+ steps = plan.get("steps") if isinstance(plan, dict) else []
+ execution_graph = planning_payload.get("execution_graph")
+ if not isinstance(execution_graph, dict):
+ execution_graph = payload.get("execution_graph")
+ graph_nodes = (
+ execution_graph.get("nodes")
+ if isinstance(execution_graph, dict)
+ else []
+ )
+ return not steps and not graph_nodes
+
+ @classmethod
+ def _attach_followup_control(cls, payload: dict[str, Any]) -> None:
+ if cls._needs_external_skill_discovery(payload):
+ payload["continue_after_display"] = True
+ payload["followup_action"] = "external_skill_discovery"
+ return
+ payload.setdefault("continue_after_display", False)
+
@staticmethod
def _failure_detail(payload: dict[str, Any], fallback: str) -> str:
return str(
@@ -160,42 +212,22 @@ class SymphonyToolkit:
).strip()
async def plan(self, query: str, mode: str | None = None) -> dict[str, Any]:
- await emit_symphony_status(
- "checking_score",
- "正在读取 Symphony 总谱...",
- )
status = await self.score_status()
if not status.get("success"):
detail = self._failure_detail(status, "symphony.score_status failed")
- await emit_symphony_status(
- "checking_score",
- f"Symphony 总谱读取失败: {detail}",
- status="failed",
- detail=detail,
- )
return {
"success": False,
- "detail": "symphony.score_status failed before planning",
+ "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):
- await emit_symphony_status(
- "building_score",
- "正在构建 Symphony 总谱...",
- )
update = await self.refresh_score()
if not update.get("success"):
detail = self._failure_detail(update, "symphony.build_score failed")
- await emit_symphony_status(
- "building_score",
- f"Symphony 总谱构建失败: {detail}",
- status="failed",
- detail=detail,
- )
return {
"success": False,
- "detail": "symphony.build_score failed before planning",
+ "detail": f"symphony.build_score failed before planning: {detail}",
"score_status": status,
"score_build": update,
}
@@ -206,23 +238,12 @@ class SymphonyToolkit:
mode_text = str(mode or "").strip()
if mode_text:
params["mode"] = mode_text
- await emit_symphony_status(
- "planning",
- "正在编排技能执行乐谱...",
- )
payload = await self._call_rpc("symphony.plan", params)
if isinstance(payload, dict):
- if payload.get("success") is False:
- detail = self._failure_detail(payload, "symphony.plan failed")
- await emit_symphony_status(
- "planning",
- f"Symphony 技能执行计划生成失败: {detail}",
- status="failed",
- detail=detail,
- )
payload.setdefault("score_status", status)
if update is not None:
payload.setdefault("score_build", update)
+ self._attach_followup_control(payload)
self._attach_display_payload(payload, status, update)
return payload
@@ -269,20 +290,24 @@ class SymphonyToolkit:
"symphony_compose_score",
(
"MUST call before answering when the user says to use skill(s) "
- "or 技能 to complete a task. Do not manually list skill names "
- "or choose a skill chain before calling this tool. This is the "
- "Symphony entrypoint: it reads the score, "
- "refreshes stale or missing scores, then composes the skill execution graph. "
+ "or 技能, or when skill capabilities, skill chaining, skill ordering, "
+ "or a specialized toolchain could help complete the task. Do not manually "
+ "list skill names or choose a skill chain before calling this tool. This is "
+ "the Symphony entrypoint: it reads the score, refreshes stale or missing "
+ "scores, then composes the skill execution graph. If no suitable candidates "
+ "or a missing capability is reported, use search_skill to discover external "
+ "skills; when installing a discovered skill is appropriate, call install_skill, "
+ "then call symphony_refresh_score and retry this tool with the original query. "
"After it returns, present its content/markdown result directly to the user; "
"do not call individual skill tools just to manually recreate the plan. "
- "Do not use for ordinary single-step tasks that do not ask to use installed skills."
+ "Skip only clearly ordinary tasks that do not benefit from skill capabilities."
),
{
"type": "object",
"properties": {
"query": {
"type": "string",
- "description": "The original user task to complete with currently installed skills.",
+ "description": "The original user task to complete with skill capabilities.",
},
"mode": {
"type": "string",
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx
index 0da74735d0..10f00a6bce 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx
@@ -1,5 +1,6 @@
import { useEffect, useLayoutEffect, useMemo, useState, useRef, type ReactNode } from "react";
import { createPortal } from "react-dom";
+import { Music2 } from "lucide-react";
import { useTranslation } from 'react-i18next';
import { useChatStore, useSessionStore } from '../../stores';
import type { ModelEntry } from '../../types';
@@ -285,6 +286,10 @@ const FREE_SEARCH_KEYS = new Set([...FREE_SEARCH_BOOLEAN_KEYS]);
const HIDDEN_CONFIG_KEYS = new Set(["free_search_proxy_url"]);
const MEMORY_KEYS = new Set(["memory_forbidden_enabled", "memory_forbidden_description"]);
const A2UI_KEYS = new Set(["a2ui_enabled"]);
+const SYMPHONY_BOOLEAN_KEYS = new Set(["symphony_enabled"]);
+const SYMPHONY_KEYS = new Set([
+ ...SYMPHONY_BOOLEAN_KEYS,
+]);
const SKILL_RETRIEVAL_BOOLEAN_KEYS = new Set([
"skill_retrieval_enabled",
"skill_retrieval_compact_codes_enabled",
@@ -320,6 +325,7 @@ function classifyKey(key: string): string {
if (FREE_SEARCH_KEYS.has(key)) return "free_search";
if (MEMORY_KEYS.has(key)) return "memory";
if (A2UI_KEYS.has(key)) return "a2ui";
+ if (SYMPHONY_KEYS.has(key)) return "symphony";
if (SKILL_RETRIEVAL_KEYS.has(key)) return "skill_retrieval";
if (key === "context_engine_enabled" || key === "kv_cache_affinity_enabled") return "context_engine";
if (key === "permissions_enabled") return "permissions";
@@ -424,6 +430,9 @@ function getGroupIcon(tag: string) {
</svg>
);
}
+ if (tag === "symphony") {
+ return <Music2 className="w-3.5 h-3.5" strokeWidth={1.8} />;
+ }
if (tag === "skill_retrieval") {
return (
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={1.8}>
@@ -454,6 +463,7 @@ function getGroupToneClass(tag: string): string {
if (tag === "context_engine") return "text-sky-500 bg-sky-500/10 border-sky-500/20";
if (tag === "permissions") return "text-rose-500 bg-rose-500/10 border-rose-500/20";
if (tag === "a2ui") return "text-fuchsia-500 bg-fuchsia-500/10 border-fuchsia-500/20";
+ if (tag === "symphony") return "text-amber-500 bg-amber-500/10 border-amber-500/20";
if (tag === "skill_retrieval") return "text-emerald-500 bg-emerald-500/10 border-emerald-500/20";
if (tag === "email") return "text-emerald-500 bg-emerald-500/10 border-emerald-500/20";
return "text-text-muted bg-secondary/70 border-border";
@@ -479,6 +489,7 @@ function isBooleanKey(key: string): boolean {
key === "permissions_enabled" ||
key === "memory_forbidden_enabled" ||
key === "a2ui_enabled" ||
+ SYMPHONY_BOOLEAN_KEYS.has(key) ||
SKILL_RETRIEVAL_BOOLEAN_KEYS.has(key)
);
}
@@ -498,6 +509,7 @@ function getBooleanKeyLabel(key: string, t: (key: string) => string): string {
permissions_enabled: t('config.booleanLabels.enabled'),
memory_forbidden_enabled: t('config.booleanLabels.enabled'),
a2ui_enabled: t('config.booleanLabels.enabled'),
+ symphony_enabled: t('config.booleanLabels.enabled'),
skill_retrieval_enabled: t('config.booleanLabels.enabled'),
skill_retrieval_compact_codes_enabled: t('config.booleanLabels.skillRetrievalCompact'),
skill_retrieval_flatten_tree: t('config.booleanLabels.skillRetrievalFlat'),
@@ -543,6 +555,7 @@ function getGroupMeta(t: (key: string) => string): Record<string, { label: strin
context_engine: { label: t('config.groups.contextEngine.label'), order: 8, hint: t('config.groups.contextEngine.hint') },
permissions: { label: t('config.groups.permissions.label'), order: 9, hint: t('config.groups.permissions.hint') },
a2ui: { label: t('config.groups.a2ui.label'), order: 10, hint: t('config.groups.a2ui.hint') },
+ symphony: { label: t('config.groups.symphony.label'), order: 10.4, hint: t('config.groups.symphony.hint') },
skill_retrieval: { label: t('config.groups.skillRetrieval.label'), order: 10.5, hint: t('config.groups.skillRetrieval.hint') },
memory: { label: t('config.groups.memory.label'), order: 11, hint: t('config.groups.memory.hint') },
email: { label: t('config.groups.email.label'), order: 12, hint: t('config.groups.email.hint') },
@@ -566,6 +579,7 @@ const KEY_DISPLAY_I18N: Record<string, string> = {
name: "config.keys.agentName",
model: "config.keys.agentModel",
skills: "config.keys.agentSkills",
+ symphony_enabled: "config.keys.symphonyEnabled",
skill_retrieval_enabled: "config.keys.skillRetrievalEnabled",
skill_retrieval_build_branching_factor: "config.keys.skillRetrievalBuildBranchingFactor",
skill_retrieval_build_max_depth: "config.keys.skillRetrievalBuildMaxDepth",
@@ -595,6 +609,7 @@ const KEY_SORT_PRIORITY: Record<string, number> = {
skill_create: 1,
free_search_ddg_enabled: 0,
free_search_bing_enabled: 1,
+ symphony_enabled: 0,
skill_retrieval_enabled: 0,
skill_retrieval_build_branching_factor: 10,
skill_retrieval_build_max_depth: 11,
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
index 84ef6b5ae6..9633e62f53 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
@@ -690,6 +690,7 @@
"teamMemberPersona": "Persona",
"teamMemberPromptHint": "Prompt Hint",
"teamMemberAgentKey": "Agent Key",
+ "symphonyEnabled": "Enable Skill Symphony",
"skillRetrievalEnabled": "Enable skill retrieval",
"skillRetrievalBuildBranchingFactor": "Tree branching factor",
"skillRetrievalBuildMaxDepth": "Max tree depth",
@@ -794,6 +795,7 @@
"contextEngine": { "label": "Context Compression", "hint": "Enable or disable dialogue context compression" },
"permissions": { "label": "Tool Safety Guardrail", "hint": "Enable or disable permission checks for tool calls" },
"a2ui": { "label": "A2UI", "hint": "Enable or disable generated UI rendering and A2UI runtime prompts." },
+ "symphony": { "label": "Skill Symphony", "hint": "Master switch for Skill Symphony orchestration" },
"skillRetrieval": { "label": "Agentic Skill Retrieval", "hint": "Agentic skill retrieval for larger sets of installed skills" },
"memory": { "label": "Memory Sensitive Info Filter", "hint": "Configure sensitive content types forbidden from memory" },
"email": { "label": "Email Settings", "hint": "Email account and token settings" },
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
index 6acdf70ab0..7e8d3422c0 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
@@ -689,6 +689,7 @@
"teamMemberPersona": "人设",
"teamMemberPromptHint": "提示词",
"teamMemberAgentKey": "Agent Key",
+ "symphonyEnabled": "启用技能交响乐",
"skillRetrievalEnabled": "启用技能检索",
"skillRetrievalBuildBranchingFactor": "树分支数",
"skillRetrievalBuildMaxDepth": "最大树深",
@@ -793,6 +794,7 @@
"contextEngine": { "label": "上下文压缩", "hint": "控制对话上下文是否启用压缩" },
"permissions": { "label": "工具安全护栏", "hint": "控制工具调用时的权限检查" },
"a2ui": { "label": "A2UI", "hint": "开启或关闭生成式界面渲染与 A2UI 运行时提示词" },
+ "symphony": { "label": "技能交响乐", "hint": "控制技能交响乐编排能力总开关" },
"skillRetrieval": { "label": "Agentic技能检索", "hint": "适用于较大规模已安装技能场景下的 Agentic 技能检索" },
"memory": { "label": "记忆系统敏感信息过滤", "hint": "配置禁止写入记忆的敏感信息类型" },
"email": { "label": "邮箱配置", "hint": "邮件账号与令牌参数" },
diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.py
index cb07975c94..27ae944fd2 100644
--- a/jiuwenswarm/common/config.py
+++ b/jiuwenswarm/common/config.py
@@ -257,30 +257,33 @@ def update_kv_cache_affinity_enabled_in_config(value: bool) -> None:
dump_yaml_round_trip(CONFIG_YAML_PATH, data)
-def update_skill_retrieval_in_config(updates: dict[str, Any]) -> None:
- """更新 symphony.skill_retrieval 配置段并写回。"""
+def _merge_config_dict(target: dict[str, Any], patch: dict[str, Any]) -> None:
+ for key, value in patch.items():
+ if isinstance(value, dict):
+ child = target.get(key)
+ if not isinstance(child, dict):
+ child = {}
+ target[key] = child
+ _merge_config_dict(child, value)
+ else:
+ target[key] = value
+
+
+def update_symphony_in_config(updates: dict[str, Any]) -> None:
+ """更新 symphony 配置段并写回。"""
data = load_yaml_round_trip(CONFIG_YAML_PATH)
if "symphony" not in data or data["symphony"] is None:
data["symphony"] = {}
symphony = data["symphony"]
- if "skill_retrieval" not in symphony or symphony["skill_retrieval"] is None:
- symphony["skill_retrieval"] = {}
-
- def merge_dict(target: dict[str, Any], patch: dict[str, Any]) -> None:
- for key, value in patch.items():
- if isinstance(value, dict):
- child = target.get(key)
- if not isinstance(child, dict):
- child = {}
- target[key] = child
- merge_dict(child, value)
- else:
- target[key] = value
-
- merge_dict(symphony["skill_retrieval"], updates)
+ _merge_config_dict(symphony, updates)
dump_yaml_round_trip(CONFIG_YAML_PATH, data)
+def update_skill_retrieval_in_config(updates: dict[str, Any]) -> None:
+ """更新 symphony.skill_retrieval 配置段并写回。"""
+ update_symphony_in_config({"skill_retrieval": updates})
+
+
def update_permissions_enabled_in_config(value: bool) -> None:
"""更新 permissions.enabled(工具安全护栏开关)并写回。"""
data = load_yaml_round_trip(CONFIG_YAML_PATH)
diff --git a/jiuwenswarm/common/e2a/acp/session_updates.py b/jiuwenswarm/common/e2a/acp/session_updates.py
index e212b6424b..fd240b0499 100644
--- a/jiuwenswarm/common/e2a/acp/session_updates.py
+++ b/jiuwenswarm/common/e2a/acp/session_updates.py
@@ -104,15 +104,17 @@ def build_acp_session_update(
state: AcpSessionUpdateState,
) -> dict[str, Any] | None:
event_type = msg.event_type
+ if event_type == EventType.CHAT_SYMPHONY_STATUS:
+ return None
+
if event_type in (
EventType.CHAT_DELTA,
EventType.CHAT_REASONING,
- EventType.CHAT_SYMPHONY_STATUS,
):
text = str(payload.get("content", "") or "")
if not text:
return None
- if event_type != EventType.CHAT_SYMPHONY_STATUS and is_reasoning_event(
+ if is_reasoning_event(
event_type,
payload,
):
diff --git a/jiuwenswarm/extensions/symphony/skills/symphony-assistant/SKILL.md b/jiuwenswarm/extensions/symphony/skills/symphony-assistant/SKILL.md
index a016b6819f..92a7f6284c 100644
--- a/jiuwenswarm/extensions/symphony/skills/symphony-assistant/SKILL.md
+++ b/jiuwenswarm/extensions/symphony/skills/symphony-assistant/SKILL.md
@@ -1,6 +1,6 @@
---
name: symphony-assistant
-description: Must use first when the user asks to use skill(s) or 技能 to complete a task.
+description: Must use first when skill capabilities may help complete a task.
allowed_tools:
- symphony_compose_score
- symphony_read_score
@@ -9,20 +9,22 @@ allowed_tools:
# Symphony Assistant
-Use this skill when a task should be completed by selecting, combining, or ordering currently installed skills.
+Use this skill when a task may benefit from selecting, combining, ordering, or discovering skill capabilities.
## Workflow
-1. If the user says to use skill(s) or 技能, always call `symphony_compose_score` with the original user task as `query`.
+1. 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. Do not manually list skill folders, list skill names, or choose a skill chain before calling `symphony_compose_score`.
3. Treat `symphony_compose_score` as the only planning entrypoint: it reads the Symphony score, refreshes missing or stale scores, and returns the Mermaid/Markdown execution graph.
4. The `symphony_compose_score` result may already be displayed directly to the user; otherwise, present its returned `content` or `markdown` directly.
5. Treat the returned plan, Mermaid graph, missing inputs, and caveats as the source of truth.
6. Do not call individual skill tools just to manually recreate or verify the Symphony plan.
7. If Symphony reports missing inputs, ask the user for those inputs instead of inventing them.
-8. For ordinary tasks that do not ask to use installed skills, do not use Symphony.
+8. 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.
+9. For clearly ordinary tasks that do not benefit from skill capabilities, do not use Symphony.
## Notes
- `symphony_compose_score` reads the current Symphony score, refreshes it when missing or stale, and then plans the skill execution graph.
+- External skills must first be discovered and installed through the skill tools, then added to the score with `symphony_refresh_score`, before they can participate in Symphony planning.
- Use `symphony_read_score` and `symphony_refresh_score` directly only when the user explicitly asks to read or refresh the Symphony score.
diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
index 766c978454..d892e2d361 100644
--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
@@ -35,7 +35,7 @@ from jiuwenswarm.common.config import (
update_preferred_language_in_config,
update_context_engine_enabled_in_config,
update_kv_cache_affinity_enabled_in_config,
- update_skill_retrieval_in_config,
+ update_symphony_in_config,
update_permissions_enabled_in_config,
update_memory_forbidden_enabled_in_config,
update_memory_forbidden_description_in_config,
@@ -435,22 +435,66 @@ _CONFIG_YAML_KEYS = frozenset({
"a2ui_enabled",
})
-_SKILL_RETRIEVAL_CONFIG_SPECS: dict[str, tuple[tuple[str, ...], str, Any]] = {
- "skill_retrieval_enabled": (("enabled",), "bool", False),
- "skill_retrieval_build_branching_factor": (("build", "branching_factor"), "int", 128),
- "skill_retrieval_build_max_depth": (("build", "max_depth"), "int", 6),
- "skill_retrieval_build_root_categories": (("build", "root_categories"), "str", ""),
- "skill_retrieval_build_max_workers": (("build", "max_workers"), "int", 2),
- "skill_retrieval_build_request_timeout_seconds": (("build", "request_timeout_seconds"), "float", 420.0),
- "skill_retrieval_retrieve_top_k": (("retrieve", "top_k"), "int", 10),
- "skill_retrieval_compact_codes_enabled": (("retrieve", "compact_codes_enabled"), "bool", False),
- "skill_retrieval_flatten_tree": (("retrieve", "flatten_tree"), "bool", False),
- "skill_retrieval_retrieve_max_exposure_depth": (("retrieve", "max_exposure_depth"), "int", 99),
- "skill_retrieval_retrieve_max_branch_choices": (("retrieve", "max_branch_choices"), "int", 2),
- "skill_retrieval_retrieve_max_parallel_branches": (("retrieve", "max_parallel_branches"), "int", 2),
- "skill_retrieval_retrieve_request_timeout_seconds": (("retrieve", "request_timeout_seconds"), "float", 120.0),
+_SYMPHONY_CONFIG_SPECS: dict[str, tuple[tuple[str, ...], str, Any]] = {
+ "symphony_enabled": (("enabled",), "bool", False),
+ "skill_retrieval_enabled": (("skill_retrieval", "enabled"), "bool", False),
+ "skill_retrieval_build_branching_factor": (
+ ("skill_retrieval", "build", "branching_factor"),
+ "int",
+ 128,
+ ),
+ "skill_retrieval_build_max_depth": (("skill_retrieval", "build", "max_depth"), "int", 6),
+ "skill_retrieval_build_root_categories": (
+ ("skill_retrieval", "build", "root_categories"),
+ "str",
+ "",
+ ),
+ "skill_retrieval_build_max_workers": (("skill_retrieval", "build", "max_workers"), "int", 2),
+ "skill_retrieval_build_request_timeout_seconds": (
+ ("skill_retrieval", "build", "request_timeout_seconds"),
+ "float",
+ 420.0,
+ ),
+ "skill_retrieval_retrieve_top_k": (("skill_retrieval", "retrieve", "top_k"), "int", 10),
+ "skill_retrieval_compact_codes_enabled": (
+ ("skill_retrieval", "retrieve", "compact_codes_enabled"),
+ "bool",
+ False,
+ ),
+ "skill_retrieval_flatten_tree": (
+ ("skill_retrieval", "retrieve", "flatten_tree"),
+ "bool",
+ False,
+ ),
+ "skill_retrieval_retrieve_max_exposure_depth": (
+ ("skill_retrieval", "retrieve", "max_exposure_depth"),
+ "int",
+ 99,
+ ),
+ "skill_retrieval_retrieve_max_branch_choices": (
+ ("skill_retrieval", "retrieve", "max_branch_choices"),
+ "int",
+ 2,
+ ),
+ "skill_retrieval_retrieve_max_parallel_branches": (
+ ("skill_retrieval", "retrieve", "max_parallel_branches"),
+ "int",
+ 2,
+ ),
+ "skill_retrieval_retrieve_request_timeout_seconds": (
+ ("skill_retrieval", "retrieve", "request_timeout_seconds"),
+ "float",
+ 120.0,
+ ),
+}
+_SYMPHONY_CONFIG_KEYS = tuple(_SYMPHONY_CONFIG_SPECS.keys())
+_SKILL_RETRIEVAL_CONFIG_KEYS = frozenset(
+ key for key in _SYMPHONY_CONFIG_KEYS if key.startswith("skill_retrieval_")
+)
+_SKILL_RETRIEVAL_CONFIG_SPECS = {
+ key: spec for key, spec in _SYMPHONY_CONFIG_SPECS.items()
+ if key in _SKILL_RETRIEVAL_CONFIG_KEYS
}
-_SKILL_RETRIEVAL_CONFIG_KEYS = frozenset(_SKILL_RETRIEVAL_CONFIG_SPECS.keys())
def _coerce_config_panel_value(value: Any, value_type: str, default: Any) -> Any:
@@ -489,12 +533,11 @@ def _get_nested_config_value(source: dict[str, Any], path: tuple[str, ...], defa
return default if current is None else current
-def _flatten_skill_retrieval_for_config_panel(raw: dict[str, Any]) -> dict[str, str]:
+def _flatten_symphony_for_config_panel(raw: dict[str, Any]) -> dict[str, str]:
symphony = raw.get("symphony") if isinstance(raw.get("symphony"), dict) else {}
- section = symphony.get("skill_retrieval") if isinstance(symphony.get("skill_retrieval"), dict) else {}
flat: dict[str, str] = {}
- for key, (path, value_type, default) in _SKILL_RETRIEVAL_CONFIG_SPECS.items():
- value = _get_nested_config_value(section, path, default)
+ for key, (path, value_type, default) in _SYMPHONY_CONFIG_SPECS.items():
+ value = _get_nested_config_value(symphony, path, default)
if value_type == "bool":
flat[key] = "true" if bool(value) else "false"
else:
@@ -502,9 +545,14 @@ def _flatten_skill_retrieval_for_config_panel(raw: dict[str, Any]) -> dict[str,
return flat
-def _build_skill_retrieval_config_update(params: dict[str, Any]) -> dict[str, Any]:
+def _flatten_skill_retrieval_for_config_panel(raw: dict[str, Any]) -> dict[str, str]:
+ flat = _flatten_symphony_for_config_panel(raw)
+ return {key: value for key, value in flat.items() if key in _SKILL_RETRIEVAL_CONFIG_KEYS}
+
+
+def _build_symphony_config_update(params: dict[str, Any]) -> dict[str, Any]:
updates: dict[str, Any] = {}
- for key, (path, value_type, default) in _SKILL_RETRIEVAL_CONFIG_SPECS.items():
+ for key, (path, value_type, default) in _SYMPHONY_CONFIG_SPECS.items():
if key not in params:
continue
value = _coerce_config_panel_value(params[key], value_type, default)
@@ -512,6 +560,12 @@ def _build_skill_retrieval_config_update(params: dict[str, Any]) -> dict[str, An
return updates
+def _build_skill_retrieval_config_update(params: dict[str, Any]) -> dict[str, Any]:
+ updates = _build_symphony_config_update(params)
+ section = updates.get("skill_retrieval")
+ return section if isinstance(section, dict) else {}
+
+
def _flatten_modes_team_for_config_panel(raw: dict[str, Any]) -> dict[str, str]:
"""Return the legacy flat fields consumed by the web config panel."""
modes = raw.get("modes")
@@ -771,7 +825,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
memory_desc = memory_cfg.get("description") or {}
payload["memory_forbidden_description"] = memory_desc
payload.update(get_a2ui_config_payload(raw))
- payload.update(_flatten_skill_retrieval_for_config_panel(raw))
+ payload.update(_flatten_symphony_for_config_panel(raw))
if not payload.get("free_search_ddg_enabled"):
payload["free_search_ddg_enabled"] = "false"
if not payload.get("free_search_bing_enabled"):
@@ -787,7 +841,7 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
payload.setdefault("memory_forbidden_description", "")
for key, value in get_default_a2ui_config_payload().items():
payload.setdefault(key, value)
- for key, (_, value_type, default) in _SKILL_RETRIEVAL_CONFIG_SPECS.items():
+ for key, (_, value_type, default) in _SYMPHONY_CONFIG_SPECS.items():
if value_type == "bool":
default_text = "true" if default else "false"
else:
@@ -900,13 +954,13 @@ def _register_web_handlers(bind: WebHandlersBindParams) -> None:
except Exception as e: # noqa: BLE001
logger.warning("[config.set] 写回 config.yaml 失败 %s: %s", param_key, e)
- skill_retrieval_updates = _build_skill_retrieval_config_update(params)
- if skill_retrieval_updates:
+ symphony_updates = _build_symphony_config_update(params)
+ if symphony_updates:
try:
- update_skill_retrieval_in_config(skill_retrieval_updates)
- yaml_updated.extend(k for k in _SKILL_RETRIEVAL_CONFIG_KEYS if k in params)
+ update_symphony_in_config(symphony_updates)
+ yaml_updated.extend(k for k in _SYMPHONY_CONFIG_KEYS if k in params)
except Exception as e:
- logger.warning("[config.set] 写回 skill_retrieval 失败: %s", e)
+ logger.warning("[config.set] 写回 symphony 失败: %s", e)
for env_key, value in env_updates.items():
os.environ[env_key] = value
diff --git a/jiuwenswarm/symphony/fingerprint/extract/extractor.py b/jiuwenswarm/symphony/fingerprint/extract/extractor.py
index 7e2d8f7164..25726701f6 100644
--- a/jiuwenswarm/symphony/fingerprint/extract/extractor.py
+++ b/jiuwenswarm/symphony/fingerprint/extract/extractor.py
@@ -279,8 +279,14 @@ example, textResult[].translateText may become translated_text with type text.
If the document says to send, show, return, or provide something in markdown,
markdown delivery instructions must be represented as markdown outputs.
-Use name for the semantic role and type for the data format or carrier that is
-passed between Skills.
+Use name for the semantic role and type for the artifact kind or concrete
+format that is passed between Skills. For media resources, prefer the media
+artifact type even when the runtime value is a URL, local path, file reference,
+base64 string, or bytes string. For example, imageUrl, translated_image_url,
+and image base64 should use type=image. audio_url, audioUrl, audio_file_path,
+and audio base64 should use type=audio. video_url, videoUrl, video_path, and
+mp4_url should use type=video. Use type=url for ordinary links, webpages,
+download links, or non-media remote references.
Prefer these type values:
text, markdown, json, csv, table, yaml, xml, pdf, html, docx, pptx, xlsx,
@@ -288,7 +294,10 @@ image, png, jpg, svg, webp, gif, audio, video, file, path, url, code,
archive, unknown.
For example, a PDF paper should use name=paper and type=pdf. A markdown
-summary should use name=summary and type=markdown.
+summary should use name=summary and type=markdown. A generated image URL should
+use name=image or translated_image_url and type=image, with URL details in the
+description. Generated audio/video URLs should similarly use type=audio or
+type=video, not type=url.
Use input and output names as canonical semantic vocab terms for graph linking. Prefer
short noun roles such as query, topic, url, paper, summary, report, table,
diff --git a/jiuwenswarm/symphony/fingerprint/models.py b/jiuwenswarm/symphony/fingerprint/models.py
index e4a0fdbf1e..b92e03ffc8 100644
--- a/jiuwenswarm/symphony/fingerprint/models.py
+++ b/jiuwenswarm/symphony/fingerprint/models.py
@@ -159,8 +159,10 @@ class NormalizationConfig:
`name` and `type` have different roles:
- `name` is the I/O semantic term used by graph construction.
- - `type` is the data format or carrier, such as text, pdf, csv,
- or markdown.
+ - `type` is the artifact kind or concrete format, such as text, pdf, csv,
+ markdown, image, audio, or video. Media resources should keep the media
+ artifact type even when carried as a URL, local path, file reference,
+ base64 string, or bytes string.
"""
# Dynamic vocabulary version for normalized I/O semantic names.
diff --git a/jiuwenswarm/symphony/fingerprint/normalize/data_types.py b/jiuwenswarm/symphony/fingerprint/normalize/data_types.py
index 93e78c2c86..f9fd0362a3 100644
--- a/jiuwenswarm/symphony/fingerprint/normalize/data_types.py
+++ b/jiuwenswarm/symphony/fingerprint/normalize/data_types.py
@@ -3,7 +3,7 @@
from __future__ import annotations
from dataclasses import dataclass
-from typing import List
+from typing import List, Optional
from jiuwenswarm.symphony.fingerprint.models import (
ExtractionDiagnostic,
@@ -21,6 +21,72 @@ from jiuwenswarm.symphony.fingerprint.normalize.decisions import (
)
from jiuwenswarm.symphony.fingerprint.utils import normalize_token
+_MEDIA_REFERENCE_CARRIER_TYPES = frozenset({"file", "path", "text", "url"})
+_MEDIA_ARTIFACT_NAME_TERMS = {
+ "image": frozenset(
+ {
+ "image",
+ "imageurl",
+ "photo",
+ "picture",
+ "poster",
+ "screenshot",
+ }
+ ),
+ "audio": frozenset(
+ {
+ "audio",
+ "audio_file",
+ "audio_path",
+ "audio_url",
+ "audiourl",
+ "m4a",
+ "mp3",
+ "music",
+ "recording",
+ "sound",
+ "speech",
+ "track",
+ "voice",
+ "wav",
+ }
+ ),
+ "video": frozenset(
+ {
+ "animation",
+ "clip",
+ "footage",
+ "mov",
+ "movie",
+ "mp4",
+ "video",
+ "video_file",
+ "video_path",
+ "video_url",
+ "videourl",
+ "webm",
+ }
+ ),
+}
+_NON_ARTIFACT_MEDIA_NAME_TERMS = frozenset(
+ {
+ "alt",
+ "analysis",
+ "caption",
+ "description",
+ "language",
+ "metadata",
+ "prompt",
+ "query",
+ "subtitle",
+ "text",
+ "transcript",
+ }
+)
+_TEXT_MEDIA_REFERENCE_DESCRIPTION_TERMS = frozenset(
+ {"base64", "bytes", "file", "local", "path", "url"}
+)
+
@dataclass(frozen=True)
class DataTypeNormalizationContext:
@@ -34,7 +100,7 @@ class DataTypeNormalizationContext:
class DataTypeNormalizer:
- """Normalize artifact carrier/format types against DataTypeVocabulary."""
+ """Normalize artifact kind/concrete format types against DataTypeVocabulary."""
def __init__(
self,
@@ -87,6 +153,35 @@ class DataTypeNormalizer:
)
return inferred.data_type
if resolution.normalized_value is not None:
+ media_override = _media_artifact_type_override(
+ resolution.normalized_value,
+ context,
+ )
+ if media_override is not None:
+ self.recorder.record(
+ context.decisions,
+ skill_id=context.skill_id,
+ path=str(context.manifest.folder.path),
+ direction=context.direction,
+ field="type",
+ raw_value=raw_type,
+ token=token,
+ normalized_value=media_override,
+ method="semantic_media_override",
+ vocab="data_type_vocab",
+ vocab_version=self.vocabulary.version,
+ confidence=0.9,
+ details={
+ "original_type": resolution.normalized_value,
+ "io_name": context.io_name,
+ "media_type": media_override,
+ "reason": (
+ f"I/O name denotes a single {media_override} artifact; raw "
+ "carrier type is preserved in the description."
+ ),
+ },
+ )
+ return media_override
self.recorder.record(
context.decisions,
skill_id=context.skill_id,
@@ -221,3 +316,45 @@ class DataTypeNormalizer:
"evidence": inferred.evidence,
},
)
+
+
+def _media_artifact_type_override(
+ normalized_type: str,
+ context: DataTypeNormalizationContext,
+) -> Optional[str]:
+ if normalized_type not in _MEDIA_REFERENCE_CARRIER_TYPES:
+ return None
+ media_type = _single_media_artifact_type_from_name(context.io_name)
+ if media_type is None:
+ return None
+ if normalized_type == "text" and not _text_description_can_carry_media(
+ context.description,
+ ):
+ return None
+ return media_type
+
+
+def _single_media_artifact_type_from_name(io_name: str) -> Optional[str]:
+ token = normalize_token(io_name)
+ if not token:
+ return None
+
+ parts = set(token.split("_"))
+ matches = []
+ for media_type, terms in _MEDIA_ARTIFACT_NAME_TERMS.items():
+ if token in terms:
+ matches.append(media_type)
+ continue
+ if parts & terms and not parts & _NON_ARTIFACT_MEDIA_NAME_TERMS:
+ matches.append(media_type)
+ if len(matches) != 1:
+ return None
+ return matches[0]
+
+
+def _text_description_can_carry_media(description: str) -> bool:
+ token = normalize_token(description)
+ if not token:
+ return False
+ parts = set(token.split("_"))
+ return bool(parts & _TEXT_MEDIA_REFERENCE_DESCRIPTION_TERMS)
diff --git a/jiuwenswarm/symphony/graph/candidates/generator.py b/jiuwenswarm/symphony/graph/candidates/generator.py
index 767dbf6996..c130ad21f8 100644
--- a/jiuwenswarm/symphony/graph/candidates/generator.py
+++ b/jiuwenswarm/symphony/graph/candidates/generator.py
@@ -603,7 +603,7 @@ def _can_feed_by_type(output_type: str, input_type: str) -> bool:
def _can_feed_by_remote_reference(output: ArtifactSpec, parameter: ParameterSpec) -> bool:
if output.type != "url":
return False
- if parameter.type not in {"file", "image"}:
+ if parameter.type not in {"file", "image", "text"}:
return False
return _accepts_remote_reference(parameter)
diff --git a/jiuwenswarm/symphony/orchestration/planning/__init__.py b/jiuwenswarm/symphony/orchestration/planning/__init__.py
index ed0267edb2..79f73d6eac 100644
--- a/jiuwenswarm/symphony/orchestration/planning/__init__.py
+++ b/jiuwenswarm/symphony/orchestration/planning/__init__.py
@@ -2,6 +2,8 @@
from jiuwenswarm.symphony.orchestration.planning.models import (
ArtifactRef,
+ GroundedQuery,
+ GroundingClient,
InferredInput,
OrchestrationPlan,
PlanStep,
@@ -16,6 +18,8 @@ from jiuwenswarm.symphony.orchestration.planning.plan_builder import (
__all__ = [
"ArtifactRef",
+ "GroundedQuery",
+ "GroundingClient",
"InferredInput",
"OrchestrationPlan",
"PlanStep",
diff --git a/jiuwenswarm/symphony/orchestration/planning/fast.py b/jiuwenswarm/symphony/orchestration/planning/fast.py
index c075a05b65..1aa2355f3b 100644
--- a/jiuwenswarm/symphony/orchestration/planning/fast.py
+++ b/jiuwenswarm/symphony/orchestration/planning/fast.py
@@ -3,7 +3,7 @@
from __future__ import annotations
import json
-from typing import Any
+from typing import Any, Sequence
from jiuwenswarm.symphony.llm import LLMConfig, create_llm_client, llm_usage_context
from jiuwenswarm.symphony.orchestration.artifacts import ScoreArtifacts
@@ -59,12 +59,17 @@ class FastOneShotPlanner:
llm_client: Any | None,
min_edge_confidence: float,
top_k: int,
+ candidate_skill_ids: Sequence[str] | None = None,
) -> 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.candidate_skill_ids = self._normalize_candidate_skill_ids(
+ candidate_skill_ids,
+ known_skill_ids=set(artifacts.skill_by_id),
+ )
async def plan(self, query: str) -> dict[str, Any]:
client = self._client()
@@ -137,21 +142,14 @@ class FastOneShotPlanner:
return create_llm_client(self.llm_config)
def _candidate_subgraph(self) -> dict[str, Any]:
+ if self.candidate_skill_ids:
+ return self._retrieval_candidate_subgraph()
+ return self._default_candidate_subgraph()
+
+ def _default_candidate_subgraph(self) -> dict[str, Any]:
skill_by_id = self.artifacts.skill_by_id
- 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)
+ sorted_edges = self._sorted_eligible_edges()
selected: set[str] = set()
- sorted_edges = sorted(
- filtered_edges,
- key=lambda item: (
- -float(item.get("confidence") or 0.0),
- str(item.get("source") or ""),
- str(item.get("target") or ""),
- ),
- )
for edge in sorted_edges:
for key in ("source", "target"):
edge_skill_id = skill_id(edge.get(key))
@@ -202,6 +200,69 @@ class FastOneShotPlanner:
):
filtered_candidate_edges.append(edge)
candidate_edges = filtered_candidate_edges
+ return self._subgraph_payload(selected, candidate_edges)
+
+ def _retrieval_candidate_subgraph(self) -> dict[str, Any]:
+ skill_by_id = self.artifacts.skill_by_id
+ sorted_edges = self._sorted_eligible_edges()
+ selected: set[str] = set()
+
+ def add_skill(current_skill_id: str) -> None:
+ if (
+ current_skill_id in skill_by_id
+ and current_skill_id not in selected
+ and len(selected) < FAST_PLANNER_MAX_SKILLS
+ ):
+ selected.add(current_skill_id)
+
+ for current_skill_id in self.candidate_skill_ids:
+ add_skill(current_skill_id)
+ if not selected:
+ return self._default_candidate_subgraph()
+
+ seed_ids = set(selected)
+ for edge in sorted_edges:
+ source_id = skill_id(edge.get("source"))
+ target_id = skill_id(edge.get("target"))
+ if source_id not in seed_ids and target_id not in seed_ids:
+ continue
+ add_skill(source_id)
+ add_skill(target_id)
+ if len(selected) >= FAST_PLANNER_MAX_SKILLS:
+ break
+
+ candidate_edges = []
+ for edge in sorted_edges:
+ if (
+ skill_id(edge.get("source")) in selected
+ and skill_id(edge.get("target")) in selected
+ ):
+ candidate_edges.append(edge)
+ if len(candidate_edges) >= FAST_PLANNER_MAX_EDGES:
+ break
+ return self._subgraph_payload(selected, candidate_edges)
+
+ 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 ""),
+ ),
+ )
+
+ def _subgraph_payload(
+ self,
+ selected: set[str],
+ candidate_edges: list[dict[str, Any]],
+ ) -> dict[str, Any]:
+ skill_by_id = self.artifacts.skill_by_id
skill_payloads = [
self._skill_payload(skill_by_id[current_skill_id])
for current_skill_id in sorted(selected)
@@ -486,3 +547,25 @@ 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 None
diff --git a/jiuwenswarm/symphony/orchestration/planning/plan_builder.py b/jiuwenswarm/symphony/orchestration/planning/plan_builder.py
index f7c8fb9a16..e67431d548 100644
--- a/jiuwenswarm/symphony/orchestration/planning/plan_builder.py
+++ b/jiuwenswarm/symphony/orchestration/planning/plan_builder.py
@@ -212,9 +212,17 @@ def compose_plan_group(plans: list[OrchestrationPlan]) -> OrchestrationPlan:
for step in plan.steps:
steps_by_id.setdefault(step.skill_id, step)
for edge in plan.can_feed_edges:
- key = (str(edge.get("source_id") or ""), str(edge.get("target_id") or ""))
+ key = (
+ edge_endpoint_id(edge, "source"),
+ edge_endpoint_id(edge, "target"),
+ )
if key[0] and key[1]:
- edges_by_key.setdefault(key, edge)
+ 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:
@@ -257,6 +265,16 @@ def compose_plan_group(plans: list[OrchestrationPlan]) -> OrchestrationPlan:
)
+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]],
@@ -272,7 +290,11 @@ def topological_step_ids(
incoming[target_id] += 1
queue = deque(
- sorted(current_skill_id for current_skill_id, count in incoming.items() if count == 0)
+ sorted(
+ current_skill_id
+ for current_skill_id, count in incoming.items()
+ if count == 0
+ )
)
ordered: list[str] = []
while queue:
diff --git a/jiuwenswarm/symphony/orchestration/service.py b/jiuwenswarm/symphony/orchestration/service.py
index 4b98b1199a..78258f768e 100644
--- a/jiuwenswarm/symphony/orchestration/service.py
+++ b/jiuwenswarm/symphony/orchestration/service.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import asyncio
from pathlib import Path
from typing import Any
@@ -10,6 +11,9 @@ from jiuwenswarm.symphony.llm import LLMConfig
from jiuwenswarm.symphony.orchestration import load_score_artifacts
from jiuwenswarm.symphony.orchestration.execution_graph import build_execution_graph
from jiuwenswarm.symphony.orchestration.planning.fast import FastOneShotPlanner
+from jiuwenswarm.symphony.orchestration.skill_retrieval import (
+ select_orchestration_skill_candidates,
+)
from jiuwenswarm.symphony.orchestration.planning.utils import clamp
@@ -31,17 +35,28 @@ async def plan_from_score(
top_k = orchestration_config.top_k
max_depth = orchestration_config.max_depth
min_edge_confidence = orchestration_config.min_edge_confidence
- artifacts = load_score_artifacts(score_dir)
-
- if orchestration_config is not None and orchestration_config.mode != "fast":
- raise ValueError(f"Unsupported orchestration mode: {orchestration_config.mode}")
+ mode = orchestration_config.mode if orchestration_config is not None else "fast"
+ artifacts = load_score_artifacts(score_dir)
+ if mode != "fast":
+ raise ValueError(f"Unsupported orchestration mode: {mode}")
+
+ skill_retrieval = await asyncio.to_thread(
+ select_orchestration_skill_candidates,
+ query=query,
+ artifacts=artifacts,
+ )
+ candidate_skill_ids = (
+ skill_retrieval.candidate_skill_ids if skill_retrieval.used else None
+ )
result = await FastOneShotPlanner(
artifacts,
llm_config=llm_config,
llm_client=llm_client,
min_edge_confidence=clamp(min_edge_confidence),
top_k=max(1, int(top_k)),
+ candidate_skill_ids=candidate_skill_ids,
).plan(query)
+ result["skill_retrieval"] = skill_retrieval.to_dict()
result["execution_graph"] = build_execution_graph(result, artifacts)
return result
diff --git a/jiuwenswarm/symphony/orchestration/skill_retrieval.py b/jiuwenswarm/symphony/orchestration/skill_retrieval.py
new file mode 100644
index 0000000000..807f0439c7
--- /dev/null
+++ b/jiuwenswarm/symphony/orchestration/skill_retrieval.py
@@ -0,0 +1,201 @@
+"""Skill retrieval candidate narrowing for Symphony orchestration."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Iterable
+
+from jiuwenswarm.symphony.orchestration.artifacts import ScoreArtifacts
+from jiuwenswarm.symphony.skill_retrieval.config import load_settings
+from jiuwenswarm.symphony.skill_retrieval.retrieve_service import (
+ run_structured_skill_retrieve,
+)
+
+
+@dataclass(frozen=True)
+class OrchestrationSkillRetrievalSelection:
+ enabled: bool
+ used: bool = False
+ candidate_skill_ids: tuple[str, ...] = ()
+ fallback_reason: str = ""
+ candidate_records: tuple[dict[str, Any], ...] = field(default_factory=tuple)
+
+ @property
+ def candidate_count(self) -> int:
+ return len(self.candidate_skill_ids)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "enabled": self.enabled,
+ "used": self.used,
+ "candidate_skill_ids": list(self.candidate_skill_ids),
+ "candidate_count": self.candidate_count,
+ "fallback_reason": self.fallback_reason,
+ "candidate_records": [dict(record) for record in self.candidate_records],
+ }
+
+
+def select_orchestration_skill_candidates(
+ *,
+ query: str,
+ artifacts: ScoreArtifacts,
+) -> OrchestrationSkillRetrievalSelection:
+ settings = load_settings()
+ if not settings.enabled:
+ return OrchestrationSkillRetrievalSelection(enabled=False)
+
+ try:
+ status = _skill_retrieval_status()
+ except Exception as exc: # noqa: BLE001
+ return _fallback(f"skill retrieval status failed: {exc}")
+ if not bool(status.get("index_exists")):
+ return _fallback("skill retrieval index does not exist")
+ if not bool(status.get("fresh")):
+ return _fallback("skill retrieval index is stale")
+ if (
+ not str(settings.llm.model or "").strip()
+ or not str(settings.llm.api_key or "").strip()
+ ):
+ return _fallback("skill retrieval LLM config is missing")
+
+ raw_index_dir = str(status.get("index_dir") or "").strip()
+ if not raw_index_dir:
+ return _fallback("skill retrieval index path is empty")
+ index_dir = Path(raw_index_dir).expanduser()
+
+ try:
+ result = run_structured_skill_retrieve(
+ settings=settings,
+ index_dir=index_dir,
+ query=str(query or "").strip(),
+ )
+ except Exception as exc: # noqa: BLE001
+ return _fallback(f"skill retrieval failed: {exc}")
+
+ known_skill_ids = set(artifacts.skill_by_id)
+ candidate_records = _simplify_candidate_records(
+ getattr(result, "candidate_records", ()),
+ known_skill_ids=known_skill_ids,
+ )
+ candidate_skill_ids = _candidate_skill_ids_from_result(
+ result,
+ known_skill_ids=known_skill_ids,
+ )
+ if not candidate_skill_ids:
+ return OrchestrationSkillRetrievalSelection(
+ enabled=True,
+ fallback_reason="skill retrieval returned no candidates present in current score",
+ candidate_records=tuple(candidate_records),
+ )
+
+ return OrchestrationSkillRetrievalSelection(
+ enabled=True,
+ used=True,
+ candidate_skill_ids=tuple(candidate_skill_ids),
+ candidate_records=tuple(candidate_records),
+ )
+
+
+def _fallback(reason: str) -> OrchestrationSkillRetrievalSelection:
+ return OrchestrationSkillRetrievalSelection(
+ enabled=True,
+ fallback_reason=str(reason or "").strip(),
+ )
+
+
+def _skill_retrieval_status() -> dict[str, Any]:
+ from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
+ from jiuwenswarm.symphony.skill_retrieval.index_service import SkillIndexService
+
+ return SkillIndexService(SkillManager()).status()
+
+
+def _candidate_skill_ids_from_result(
+ result: Any,
+ *,
+ known_skill_ids: set[str],
+) -> list[str]:
+ output: list[str] = []
+ seen: set[str] = set()
+ records = getattr(result, "candidate_records", ()) or ()
+ for record in records:
+ if not isinstance(record, dict):
+ continue
+ _append_known_candidate_ids(
+ _candidate_id_values(record),
+ known_skill_ids=known_skill_ids,
+ output=output,
+ seen=seen,
+ )
+
+ payloads = getattr(result, "payloads", ()) or ()
+ _append_known_candidate_ids(
+ (str(payload or "").strip() for payload in payloads),
+ known_skill_ids=known_skill_ids,
+ output=output,
+ seen=seen,
+ )
+ return output
+
+
+def _append_known_candidate_ids(
+ values: Iterable[str],
+ *,
+ known_skill_ids: set[str],
+ output: list[str],
+ seen: set[str],
+) -> None:
+ for value in values:
+ candidate_id = str(value or "").strip()
+ if (
+ not candidate_id
+ or candidate_id in seen
+ or candidate_id not in known_skill_ids
+ ):
+ continue
+ seen.add(candidate_id)
+ output.append(candidate_id)
+
+
+def _candidate_id_values(record: dict[str, Any]) -> Iterable[str]:
+ for key in ("worker_id", "resolved_payload"):
+ value = str(record.get(key) or "").strip()
+ if value:
+ yield value
+
+
+def _simplify_candidate_records(
+ records: Iterable[Any],
+ *,
+ known_skill_ids: set[str],
+) -> list[dict[str, Any]]:
+ output: list[dict[str, Any]] = []
+ for record in records:
+ if not isinstance(record, dict):
+ continue
+ skill_id = next(
+ (
+ value
+ for value in _candidate_id_values(record)
+ if value in known_skill_ids
+ ),
+ "",
+ )
+ simplified = {
+ "rank": record.get("rank"),
+ "skill_id": skill_id,
+ "worker_id": record.get("worker_id"),
+ "resolved_payload": record.get("resolved_payload"),
+ "skill_name": record.get("skill_name"),
+ "score": record.get("score"),
+ "source": record.get("source"),
+ }
+ output.append(
+ {
+ key: value
+ for key, value in simplified.items()
+ if value not in (None, "")
+ }
+ )
+ return output
diff --git a/jiuwenswarm/symphony/skill_retrieval/retrieve_service.py b/jiuwenswarm/symphony/skill_retrieval/retrieve_service.py
index 5b87624ee4..73d2745226 100644
--- a/jiuwenswarm/symphony/skill_retrieval/retrieve_service.py
+++ b/jiuwenswarm/symphony/skill_retrieval/retrieve_service.py
@@ -81,46 +81,57 @@ class SkillRetrieveService:
@staticmethod
def _run_dispatch_retrieve(*, settings: Any, index_dir: Path, query: str) -> Any:
- with dispatch_import_path():
- from retrieval.service.models import (
- GenerationConfig,
- OpenAIClientConfig,
- RenderConfig,
- RequestConfig,
- RetrieverConfig,
- TraversalConfig,
- )
- from retrieval.service.retriever import Retriever
-
- retrieve = settings.retrieve
- config = RetrieverConfig(
- top_k=retrieve.top_k,
- llm_client_config=OpenAIClientConfig(
- model=settings.llm.model,
- api_key=settings.llm.api_key,
- base_url=settings.llm.base_url,
- seed=settings.llm.seed,
- ),
- traversal_config=TraversalConfig(
- max_branch_choices=retrieve.max_branch_choices,
- max_parallel_branches=retrieve.max_parallel_branches,
- enable_parallel_branches=True,
- ),
- render_config=RenderConfig(
- compact_codes_enabled=retrieve.compact_codes_enabled,
- flatten_tree=retrieve.flatten_tree,
- max_exposure_depth=retrieve.max_exposure_depth,
- ),
- generation_config=GenerationConfig(
- max_tokens=retrieve.max_tokens,
- request_timeout_seconds=retrieve.request_timeout_seconds,
- ),
+ return run_structured_skill_retrieve(
+ settings=settings,
+ index_dir=index_dir,
+ query=query,
+ )
+
+
+def run_structured_skill_retrieve(*, settings: Any, index_dir: Path, query: str) -> Any:
+ with dispatch_import_path():
+ from retrieval.service.models import (
+ GenerationConfig,
+ OpenAIClientConfig,
+ RenderConfig,
+ RequestConfig,
+ RetrieverConfig,
+ TraversalConfig,
+ )
+ from retrieval.service.retriever import Retriever
+
+ retrieve = settings.retrieve
+ config = RetrieverConfig(
+ top_k=retrieve.top_k,
+ llm_client_config=OpenAIClientConfig(
+ model=settings.llm.model,
+ api_key=settings.llm.api_key,
+ base_url=settings.llm.base_url,
+ seed=settings.llm.seed,
+ ),
+ traversal_config=TraversalConfig(
+ max_branch_choices=retrieve.max_branch_choices,
+ max_parallel_branches=retrieve.max_parallel_branches,
+ enable_parallel_branches=True,
+ ),
+ render_config=RenderConfig(
+ compact_codes_enabled=retrieve.compact_codes_enabled,
+ flatten_tree=retrieve.flatten_tree,
+ max_exposure_depth=retrieve.max_exposure_depth,
+ ),
+ generation_config=GenerationConfig(
+ max_tokens=retrieve.max_tokens,
+ request_timeout_seconds=retrieve.request_timeout_seconds,
+ ),
+ )
+ retriever = Retriever.from_index(index_dir, config=config)
+ try:
+ return retriever.search_details(
+ query,
+ search_config=RequestConfig(top_k=retrieve.top_k),
)
- retriever = Retriever.from_index(index_dir, config=config)
- try:
- return retriever.search_details(query, search_config=RequestConfig(top_k=retrieve.top_k))
- finally:
- retriever.close()
+ finally:
+ retriever.close()
def _load_catalog(index_dir: Path) -> dict[str, dict[str, Any]]:
diff --git a/tests/unit_tests/agentserver/test_agentserver_acp.py b/tests/unit_tests/agentserver/test_agentserver_acp.py
index b48be5a9b8..7b1cdee4e3 100644
--- a/tests/unit_tests/agentserver/test_agentserver_acp.py
+++ b/tests/unit_tests/agentserver/test_agentserver_acp.py
@@ -238,7 +238,7 @@ def test_parse_stream_chunk_preserves_symphony_status_payload():
"source": "symphony_compose_score",
"operation_id": "call-1",
"phase": "checking_score",
- "content": "正在读取 Symphony 总谱...",
+ "content": "Symphony status",
"status": "in_progress",
},
)
@@ -249,7 +249,7 @@ def test_parse_stream_chunk_preserves_symphony_status_payload():
"source": "symphony_compose_score",
"operation_id": "call-1",
"phase": "checking_score",
- "content": "正在读取 Symphony 总谱...",
+ "content": "Symphony status",
"status": "in_progress",
}
@@ -263,7 +263,7 @@ def test_interface_deep_parse_stream_chunk_preserves_symphony_status_payload():
"source": "symphony_compose_score",
"operation_id": "call-1",
"phase": "planning",
- "content": "正在编排技能执行乐谱...",
+ "content": "Symphony planning status",
"status": "in_progress",
},
)
@@ -274,7 +274,7 @@ def test_interface_deep_parse_stream_chunk_preserves_symphony_status_payload():
"source": "symphony_compose_score",
"operation_id": "call-1",
"phase": "planning",
- "content": "正在编排技能执行乐谱...",
+ "content": "Symphony planning status",
"status": "in_progress",
}
diff --git a/tests/unit_tests/agentserver/test_stream_event_rail_symphony.py b/tests/unit_tests/agentserver/test_stream_event_rail_symphony.py
index 717fc3a608..91b6ee8e1a 100644
--- a/tests/unit_tests/agentserver/test_stream_event_rail_symphony.py
+++ b/tests/unit_tests/agentserver/test_stream_event_rail_symphony.py
@@ -7,9 +7,6 @@ from openjiuwen.core.single_agent.rail.base import ToolCallInputs
from jiuwenswarm.agents.harness.common.rails.stream_event_rail import (
JiuSwarmStreamEventRail,
)
-from jiuwenswarm.agents.harness.common.tools.symphony_status_events import (
- emit_symphony_status,
-)
class _StreamSession:
@@ -27,6 +24,7 @@ def _ctx(
tool_result=None,
):
tool_call = SimpleNamespace(id=tool_call_id, name=tool_name, arguments={})
+ force_finish_requests = []
return SimpleNamespace(
session=session,
inputs=ToolCallInputs(
@@ -37,36 +35,32 @@ def _ctx(
),
extra={},
exception=None,
+ request_force_finish=force_finish_requests.append,
+ force_finish_requests=force_finish_requests,
)
@pytest.mark.asyncio
-async def test_stream_event_rail_enables_symphony_status_events_for_plan_tool():
+async def test_stream_event_rail_does_not_enable_symphony_status_events_for_plan_tool():
rail = JiuSwarmStreamEventRail()
session = _StreamSession()
ctx = _ctx(session, "symphony_compose_score", tool_call_id="parent-call")
await rail.before_tool_call(ctx)
- await emit_symphony_status("checking_score", "正在读取 Symphony 总谱...")
status_events = [
chunk
for chunk in session.chunks
if chunk.type == "chat.symphony_status"
]
- assert len(status_events) == 1
- assert status_events[0].payload["operation_id"] == "parent-call"
- assert status_events[0].payload["phase"] == "checking_score"
+ assert status_events == []
await rail.after_tool_call(ctx)
- chunk_count_after_cleanup = len(session.chunks)
- await emit_symphony_status("planning", "正在编排技能执行乐谱...")
-
- assert len(session.chunks) == chunk_count_after_cleanup
+ assert not any(chunk.type == "chat.symphony_status" for chunk in session.chunks)
@pytest.mark.asyncio
-async def test_stream_event_rail_directly_displays_symphony_compose_score_result():
+async def test_stream_event_rail_force_finishes_symphony_compose_score_result():
rail = JiuSwarmStreamEventRail()
session = _StreamSession()
result = {
@@ -95,10 +89,38 @@ async def test_stream_event_rail_directly_displays_symphony_compose_score_result
assert tool_results[0]["score_status"] == result["score_status"]
assert tool_results[0]["direct_display"] is True
direct_messages = [chunk for chunk in session.chunks if chunk.type == "chat.final"]
- assert len(direct_messages) == 1
- assert direct_messages[0].payload["content"] == result["content"]
- assert direct_messages[0].payload["mermaid"] == result["mermaid"]
- assert direct_messages[0].payload["score_status"] == result["score_status"]
+ assert direct_messages == []
+ assert ctx.force_finish_requests == [
+ {"output": result["content"], "result_type": "answer"}
+ ]
+
+
+async def test_stream_event_rail_continues_after_symphony_skill_gap_result():
+ rail = JiuSwarmStreamEventRail()
+ session = _StreamSession()
+ result = {
+ "success": True,
+ "direct_display": True,
+ "display_format": "markdown",
+ "content": "## Symphony plan\n\nNo suitable skill found.",
+ "continue_after_display": True,
+ "followup_action": "external_skill_discovery",
+ }
+ ctx = _ctx(session, "symphony_compose_score", tool_result=result)
+
+ await rail.before_tool_call(ctx)
+ await rail.after_tool_call(ctx)
+
+ tool_results = [
+ chunk.payload.get("tool_result")
+ for chunk in session.chunks
+ if chunk.type == "tool_result"
+ ]
+ assert tool_results[0]["continue_after_display"] is True
+ assert tool_results[0]["followup_action"] == "external_skill_discovery"
+ assert not any(chunk.type == "chat.final" for chunk in session.chunks)
+ assert ctx.force_finish_requests == []
@pytest.mark.asyncio
@@ -108,7 +130,7 @@ async def test_stream_event_rail_does_not_enable_symphony_status_events_for_othe
ctx = _ctx(session, "todo_list")
await rail.before_tool_call(ctx)
- chunk_count_after_top_level_call = len(session.chunks)
- await emit_symphony_status("checking_score", "正在读取 Symphony 总谱...")
+ await rail.after_tool_call(ctx)
- assert len(session.chunks) == chunk_count_after_top_level_call
+ assert not any(chunk.type == "chat.symphony_status" for chunk in session.chunks)
+ assert ctx.force_finish_requests == []
diff --git a/tests/unit_tests/agentserver/test_system_prompt_restructure.py b/tests/unit_tests/agentserver/test_system_prompt_restructure.py
index 0288e10052..a19361d196 100644
--- a/tests/unit_tests/agentserver/test_system_prompt_restructure.py
+++ b/tests/unit_tests/agentserver/test_system_prompt_restructure.py
@@ -46,10 +46,14 @@ def test_build_agent_identity_prompt_contains_identity_section_only(monkeypatch)
lambda: SimpleNamespace(enabled=True),
)
prompt = build_agent_identity_prompt(language="zh")
+ prompt_inline = " ".join(prompt.split())
assert "# 你的家" in prompt
assert "## Symphony Routing" in prompt
assert "`symphony_compose_score`" in prompt
+ assert "skill capabilities, skill chaining, skill ordering" in prompt_inline
+ assert "use `search_skill` to discover external skills" in prompt_inline
+ assert "call `symphony_refresh_score`" in prompt_inline
assert "present its returned `content` or" in prompt
assert "# 消息说明" not in prompt
diff --git a/tests/unit_tests/channel/test_web_channel_symphony_status.py b/tests/unit_tests/channel/test_web_channel_symphony_status.py
index 87c8a5f11d..ef2f6bce0a 100644
--- a/tests/unit_tests/channel/test_web_channel_symphony_status.py
+++ b/tests/unit_tests/channel/test_web_channel_symphony_status.py
@@ -37,7 +37,7 @@ async def test_web_channel_preserves_symphony_status_payload():
"source": "symphony_compose_score",
"operation_id": "call-1",
"phase": "checking_score",
- "content": "正在读取 Symphony 总谱...",
+ "content": "Symphony status",
"status": "in_progress",
},
event_type=EventType.CHAT_SYMPHONY_STATUS,
@@ -52,7 +52,7 @@ async def test_web_channel_preserves_symphony_status_payload():
"source": "symphony_compose_score",
"operation_id": "call-1",
"phase": "checking_score",
- "content": "正在读取 Symphony 总谱...",
+ "content": "Symphony status",
"status": "in_progress",
"session_id": "sess-1",
},
diff --git a/tests/unit_tests/e2a/test_acp_session_updates.py b/tests/unit_tests/e2a/test_acp_session_updates.py
index 28ba8e3d34..fb8596ab8e 100644
--- a/tests/unit_tests/e2a/test_acp_session_updates.py
+++ b/tests/unit_tests/e2a/test_acp_session_updates.py
@@ -79,7 +79,7 @@ def test_build_acp_session_update_maps_chat_reasoning_to_agent_thought_chunk():
assert isinstance(state.thought_message_id, str)
-def test_build_acp_session_update_maps_symphony_status_to_agent_message_chunk():
+def test_build_acp_session_update_ignores_symphony_status():
state = _build_state()
update = build_acp_session_update(
_build_message(EventType.CHAT_SYMPHONY_STATUS),
@@ -87,18 +87,14 @@ def test_build_acp_session_update_maps_symphony_status_to_agent_message_chunk():
"source": "symphony_compose_score",
"operation_id": "call-1",
"phase": "checking_score",
- "content": "正在读取 Symphony 总谱...",
+ "content": "Symphony status",
"status": "in_progress",
},
state,
)
- assert update == {
- "sessionUpdate": "agent_message_chunk",
- "messageId": state.assistant_message_id,
- "content": {"type": "text", "text": "正在读取 Symphony 总谱..."},
- }
- assert isinstance(state.assistant_message_id, str)
+ assert update is None
+ assert state.assistant_message_id is None
def test_build_acp_session_update_keeps_reasoning_consistent_between_delta_and_reasoning():
diff --git a/tests/unit_tests/symphony/test_config.py b/tests/unit_tests/symphony/test_config.py
index d3793b79ea..30691f7392 100644
--- a/tests/unit_tests/symphony/test_config.py
+++ b/tests/unit_tests/symphony/test_config.py
@@ -90,16 +90,7 @@ def test_symphony_config_normalizes_values(monkeypatch, tmp_path):
assert cfg.enabled is True
[email protected]("mode", ["", None])
-def test_symphony_config_uses_fast_mode_default(mode):
- cfg = symphony_config.symphony_config_from_dict(
- {"orchestration": {"mode": mode}}
- )
-
- assert cfg.orchestration.mode == "fast"
-
-
[email protected]("mode", ["fast"])
[email protected]("mode", ["fast", "", None])
def test_symphony_config_accepts_fast_mode_aliases(mode):
cfg = symphony_config.symphony_config_from_dict(
{"orchestration": {"mode": mode}}
diff --git a/tests/unit_tests/symphony/test_extension.py b/tests/unit_tests/symphony/test_extension.py
index e079e00fa0..b922fb2e38 100644
--- a/tests/unit_tests/symphony/test_extension.py
+++ b/tests/unit_tests/symphony/test_extension.py
@@ -46,6 +46,10 @@ def test_symphony_skill_metadata():
assert "- symphony_compose_score" in content
assert "- symphony_read_score" in content
assert "- symphony_refresh_score" in content
+ assert "skill capabilities, skill chaining, skill ordering" in content
+ assert "use `search_skill` to discover external skills" in content
+ assert "call `symphony_refresh_score`" in content
+ assert "currently installed skills" not in content
assert "instead of inventing them" in content
@@ -150,7 +154,7 @@ def test_plan_uses_requested_fast_mode(monkeypatch, tmp_path):
assert seen["orchestration_config"].mode == "fast"
-def test_plan_rejects_non_fast_requested_mode(monkeypatch, tmp_path):
+def test_plan_rejects_requested_beam_mode(monkeypatch, tmp_path):
configured_score_dir = tmp_path / "configured"
monkeypatch.setattr(
"jiuwenswarm.extensions.symphony.extension.load_symphony_config",
@@ -165,7 +169,7 @@ def test_plan_rejects_non_fast_requested_mode(monkeypatch, tmp_path):
assert result["success"] is False
assert result["mode"] == "fast"
- assert "Unsupported Symphony orchestration mode" in result["detail"]
+ assert "Unsupported Symphony orchestration mode: beam" in result["detail"]
def test_plan_presentation_uses_recommended_plan(monkeypatch, tmp_path):
diff --git a/tests/unit_tests/symphony/test_graph_exact_io.py b/tests/unit_tests/symphony/test_graph_exact_io.py
index ef64c90e47..cdb0b537cc 100644
--- a/tests/unit_tests/symphony/test_graph_exact_io.py
+++ b/tests/unit_tests/symphony/test_graph_exact_io.py
@@ -256,6 +256,74 @@ def test_candidate_generator_emits_remote_reference_candidate_for_url_file_like_
]
+def test_candidate_generator_emits_remote_reference_candidate_for_url_text_input():
+ candidates = _candidates(
+ _skill(
+ "source",
+ outputs=[
+ ArtifactSpec(
+ name="translated_image_url",
+ type="url",
+ description="URL of the translated image.",
+ )
+ ],
+ ),
+ _skill(
+ "target",
+ inputs=[
+ ParameterSpec(
+ name="image_url",
+ type="text",
+ description="Public image URL to process.",
+ )
+ ],
+ ),
+ )
+
+ assert len(candidates) == 1
+ candidate = candidates[0]
+ assert candidate.source_id == "source"
+ assert candidate.target_id == "target"
+ assert "semantic_overlap_match" in candidate.candidate_methods
+ evidence = candidate.evidence["directions"]["source->target"]
+ assert evidence["port_mappings"][0]["source_output"] == "translated_image_url"
+ assert evidence["port_mappings"][0]["target_input"] == "image_url"
+
+
+def test_candidate_generator_emits_image_artifact_candidate():
+ candidates = _candidates(
+ _skill(
+ "source",
+ outputs=[
+ ArtifactSpec(
+ name="translated_image_url",
+ type="image",
+ description="URL of the translated image.",
+ )
+ ],
+ ),
+ _skill(
+ "target",
+ inputs=[
+ ParameterSpec(
+ name="image",
+ type="image",
+ description="Image input to process.",
+ )
+ ],
+ ),
+ )
+
+ assert len(candidates) == 1
+ candidate = candidates[0]
+ assert candidate.source_id == "source"
+ assert candidate.target_id == "target"
+ assert "semantic_overlap_match" in candidate.candidate_methods
+ evidence = candidate.evidence["directions"]["source->target"]
+ assert evidence["port_mappings"][0]["source_output"] == "translated_image_url"
+ assert evidence["port_mappings"][0]["target_input"] == "image"
+
+
def test_candidate_generator_emits_remote_reference_for_explicit_url_descriptions():
for description in ("accepts remote URL", "download URL"):
candidates = _candidates(
diff --git a/tests/unit_tests/symphony/test_graph_service.py b/tests/unit_tests/symphony/test_graph_service.py
index c703c6bb35..d3f6076c96 100644
--- a/tests/unit_tests/symphony/test_graph_service.py
+++ b/tests/unit_tests/symphony/test_graph_service.py
@@ -1186,6 +1186,68 @@ async def test_normalizer_batch_size_one_uses_single_skill_batches(tmp_path):
assert resolver.calls == [[["first_result"]], [["second_result"]]]
+async def test_normalizer_overrides_single_image_reference_types(tmp_path):
+ normalizer = SkillFingerprintNormalizer(io_name_resolver=_CreateNewIONameResolver())
+
+ result = await normalizer.normalize_single(
+ _raw_manifest(tmp_path, "image-skill"),
+ ExtractedSkillSchema(
+ inputs=[
+ ParameterSpec(
+ name="imageUrl",
+ type="url",
+ description="Public image URL to process.",
+ ),
+ ParameterSpec(
+ name="image",
+ type="text",
+ description="图片输入,可以是图片 URL、本地文件路径或图片 BASE64 编码数据。",
+ ),
+ ParameterSpec(
+ name="source_language",
+ type="text",
+ required=False,
+ description="Source language of the text in the image.",
+ ),
+ ParameterSpec(
+ name="homepage_url",
+ type="url",
+ description="Public product homepage URL.",
+ ),
+ ParameterSpec(
+ name="download_url",
+ type="url",
+ description="Download URL for a file artifact.",
+ ),
+ ],
+ outputs=[
+ ArtifactSpec(
+ name="translated_image_url",
+ type="url",
+ description="URL of the translated image.",
+ )
+ ],
+ ),
+ )
+
+ input_types = {item.name: item.type for item in result.fingerprint.inputs}
+ output_types = {item.name: item.type for item in result.fingerprint.outputs}
+ assert input_types["imageurl"] == "image"
+ assert input_types["image"] == "image"
+ assert input_types["source_language"] == "text"
+ assert input_types["homepage_url"] == "url"
+ assert input_types["download_url"] == "url"
+ assert output_types["translated_image_url"] == "image"
+ override_decisions = [
+ decision
+ for decision in result.decisions
+ if decision.field == "type" and decision.method == "semantic_media_override"
+ ]
+ assert {decision.normalized_value for decision in override_decisions} == {"image"}
+ assert {decision.raw_value for decision in override_decisions} == {"url", "text"}
+
+
@pytest.mark.asyncio
async def test_normalizer_resolves_single_skill_candidates_together(tmp_path):
resolver = _CreateNewIONameResolver()
diff --git a/tests/unit_tests/symphony/test_planning_modules.py b/tests/unit_tests/symphony/test_planning_modules.py
index 476978f42c..1b57b5b8a2 100644
--- a/tests/unit_tests/symphony/test_planning_modules.py
+++ b/tests/unit_tests/symphony/test_planning_modules.py
@@ -6,6 +6,7 @@ from jiuwenswarm.symphony.orchestration.planning.models import (
SearchState,
)
from jiuwenswarm.symphony.orchestration.planning.plan_builder import (
+ compose_dag_plans,
compose_plan_group,
plan_stages,
state_to_plan,
@@ -132,6 +133,45 @@ def test_compose_plan_group_merges_steps_edges_and_reorders_by_dependencies():
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}
+ ]
+
+
def _step(skill_id: str) -> PlanStep:
return PlanStep(
skill_id=skill_id,
diff --git a/tests/unit_tests/symphony/test_service.py b/tests/unit_tests/symphony/test_service.py
index 3f3cebf776..b0ad6c5869 100644
--- a/tests/unit_tests/symphony/test_service.py
+++ b/tests/unit_tests/symphony/test_service.py
@@ -1,10 +1,14 @@
import json
+from types import SimpleNamespace
import pytest
from jiuwenswarm.symphony.config import SymphonyOrchestrationConfig
from jiuwenswarm.symphony.orchestration import service
from jiuwenswarm.symphony.orchestration.artifacts import ScoreArtifacts
+from jiuwenswarm.symphony.orchestration.skill_retrieval import (
+ OrchestrationSkillRetrievalSelection,
+)
class _FakeLLMClient:
@@ -284,9 +288,78 @@ async def test_plan_from_score_fast_rejects_low_confidence_edge_once(
assert "illegal can_feed edges" in result["detail"]
-async def test_plan_from_score_rejects_non_fast_mode(monkeypatch, tmp_path):
+async def test_plan_from_score_fast_uses_retrieved_candidates_and_neighbors(
+ monkeypatch,
+ tmp_path,
+):
artifacts = _artifacts(tmp_path)
+ artifacts.skills.extend(
+ [
+ {
+ "id": "skill-d",
+ "name": "Delta Skill",
+ "description": "Unrelated high-confidence source.",
+ "inputs": [],
+ "outputs": [{"name": "delta", "type": "markdown"}],
+ },
+ {
+ "id": "skill-e",
+ "name": "Echo Skill",
+ "description": "Unrelated high-confidence target.",
+ "inputs": [{"name": "delta", "type": "markdown"}],
+ "outputs": [{"name": "echo", "type": "markdown"}],
+ },
+ ]
+ )
+ artifacts.graph["edges"].append(
+ {
+ "type": "can_feed",
+ "source": "skill-d",
+ "target": "skill-e",
+ "confidence": 0.99,
+ "method": "llm",
+ "evidence": {"reasons": ["unrelated"]},
+ }
+ )
+ llm = _FakeLLMClient(
+ {
+ "title": "Retrieved fast plan",
+ "status": "ready",
+ "steps": [{"skill_id": "skill-b", "reason": "Retrieved seed."}],
+ "can_feed_edges": [],
+ }
+ )
+ monkeypatch.setattr(service, "load_score_artifacts", lambda score_dir: artifacts)
+ monkeypatch.setattr(
+ service,
+ "select_orchestration_skill_candidates",
+ lambda **kwargs: OrchestrationSkillRetrievalSelection(
+ enabled=True,
+ used=True,
+ candidate_skill_ids=("skill-b",),
+ ),
+ )
+ result = await service.plan_from_score(
+ tmp_path,
+ "use beta",
+ llm_client=llm,
+ orchestration_config=SymphonyOrchestrationConfig(
+ mode="fast",
+ min_edge_confidence=0.7,
+ ),
+ )
+
+ prompt_payload = json.loads(llm.calls[0]["user_content"])
+ prompt_skill_ids = {skill["id"] for skill in prompt_payload["skills"]}
+ assert prompt_skill_ids == {"skill-a", "skill-b", "skill-c"}
+ assert "skill-d" not in prompt_skill_ids
+ assert result["skill_retrieval"]["used"] is True
+ assert result["skill_retrieval"]["candidate_skill_ids"] == ["skill-b"]
+
+
+async def test_plan_from_score_rejects_non_fast_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"):
@@ -295,10 +368,191 @@ async def test_plan_from_score_rejects_non_fast_mode(monkeypatch, tmp_path):
"beam plan",
llm_client=object(),
ranker=object(),
- orchestration_config=SymphonyOrchestrationConfig(
- mode="beam",
- top_k=2,
- max_depth=5,
- min_edge_confidence=0.7,
- ),
+ orchestration_config=SymphonyOrchestrationConfig(mode="beam"),
)
+
+
+def test_orchestration_skill_retrieval_filters_unknown_ids(
+ monkeypatch,
+ tmp_path,
+):
+ from jiuwenswarm.symphony.orchestration import skill_retrieval as retrieval_module
+
+ artifacts = _artifacts(tmp_path)
+ settings = SimpleNamespace(
+ enabled=True,
+ llm=SimpleNamespace(model="model", api_key="key"),
+ retrieve=SimpleNamespace(top_k=2),
+ )
+ result = SimpleNamespace(
+ candidate_records=[
+ {"rank": 1, "worker_id": "missing-skill", "score": 0.9},
+ {"rank": 2, "worker_id": "skill-b", "score": 0.8},
+ ],
+ payloads=["missing-skill", "skill-b"],
+ )
+ monkeypatch.setattr(retrieval_module, "load_settings", lambda: settings)
+ monkeypatch.setattr(
+ retrieval_module,
+ "_skill_retrieval_status",
+ lambda: {
+ "index_exists": True,
+ "fresh": True,
+ "index_dir": str(tmp_path),
+ },
+ )
+ monkeypatch.setattr(
+ retrieval_module,
+ "run_structured_skill_retrieve",
+ lambda **kwargs: result,
+ )
+
+ selection = retrieval_module.select_orchestration_skill_candidates(
+ query="use beta",
+ artifacts=artifacts,
+ )
+
+ assert selection.used is True
+ assert selection.candidate_skill_ids == ("skill-b",)
+ assert selection.candidate_count == 1
+
+
+def test_orchestration_skill_retrieval_falls_back_when_all_ids_are_stale(
+ monkeypatch,
+ tmp_path,
+):
+ from jiuwenswarm.symphony.orchestration import skill_retrieval as retrieval_module
+
+ artifacts = _artifacts(tmp_path)
+ settings = SimpleNamespace(
+ enabled=True,
+ llm=SimpleNamespace(model="model", api_key="key"),
+ retrieve=SimpleNamespace(top_k=1),
+ )
+ result = SimpleNamespace(
+ candidate_records=[{"rank": 1, "worker_id": "missing-skill"}],
+ payloads=["missing-skill"],
+ )
+ monkeypatch.setattr(retrieval_module, "load_settings", lambda: settings)
+ monkeypatch.setattr(
+ retrieval_module,
+ "_skill_retrieval_status",
+ lambda: {
+ "index_exists": True,
+ "fresh": True,
+ "index_dir": str(tmp_path),
+ },
+ )
+ monkeypatch.setattr(
+ retrieval_module,
+ "run_structured_skill_retrieve",
+ lambda **kwargs: result,
+ )
+
+ selection = retrieval_module.select_orchestration_skill_candidates(
+ query="use beta",
+ artifacts=artifacts,
+ )
+
+ assert selection.used is False
+ assert selection.candidate_skill_ids == ()
+ assert "no candidates present" in selection.fallback_reason
+
+
+def test_orchestration_skill_retrieval_falls_back_when_index_missing(
+ monkeypatch,
+ tmp_path,
+):
+ from jiuwenswarm.symphony.orchestration import skill_retrieval as retrieval_module
+
+ artifacts = _artifacts(tmp_path)
+ settings = SimpleNamespace(
+ enabled=True,
+ llm=SimpleNamespace(model="model", api_key="key"),
+ )
+ monkeypatch.setattr(retrieval_module, "load_settings", lambda: settings)
+ monkeypatch.setattr(
+ retrieval_module,
+ "_skill_retrieval_status",
+ lambda: {"index_exists": False, "fresh": False},
+ )
+
+ selection = retrieval_module.select_orchestration_skill_candidates(
+ query="use beta",
+ artifacts=artifacts,
+ )
+
+ assert selection.used is False
+ assert selection.fallback_reason == "skill retrieval index does not exist"
+
+
+def test_orchestration_skill_retrieval_falls_back_when_llm_config_missing(
+ monkeypatch,
+ tmp_path,
+):
+ from jiuwenswarm.symphony.orchestration import skill_retrieval as retrieval_module
+
+ artifacts = _artifacts(tmp_path)
+ settings = SimpleNamespace(
+ enabled=True,
+ llm=SimpleNamespace(model="", api_key=""),
+ )
+ monkeypatch.setattr(retrieval_module, "load_settings", lambda: settings)
+ monkeypatch.setattr(
+ retrieval_module,
+ "_skill_retrieval_status",
+ lambda: {
+ "index_exists": True,
+ "fresh": True,
+ "index_dir": str(tmp_path),
+ },
+ )
+
+ selection = retrieval_module.select_orchestration_skill_candidates(
+ query="use beta",
+ artifacts=artifacts,
+ )
+
+ assert selection.used is False
+ assert selection.fallback_reason == "skill retrieval LLM config is missing"
+
+
+def test_orchestration_skill_retrieval_falls_back_when_retrieve_raises(
+ monkeypatch,
+ tmp_path,
+):
+ from jiuwenswarm.symphony.orchestration import skill_retrieval as retrieval_module
+
+ artifacts = _artifacts(tmp_path)
+ settings = SimpleNamespace(
+ enabled=True,
+ llm=SimpleNamespace(model="model", api_key="key"),
+ )
+
+ def raise_retrieve(**kwargs):
+ del kwargs
+ raise RuntimeError("boom")
+
+ monkeypatch.setattr(retrieval_module, "load_settings", lambda: settings)
+ monkeypatch.setattr(
+ retrieval_module,
+ "_skill_retrieval_status",
+ lambda: {
+ "index_exists": True,
+ "fresh": True,
+ "index_dir": str(tmp_path),
+ },
+ )
+ monkeypatch.setattr(
+ retrieval_module,
+ "run_structured_skill_retrieve",
+ raise_retrieve,
+ )
+
+ selection = retrieval_module.select_orchestration_skill_candidates(
+ query="use beta",
+ artifacts=artifacts,
+ )
+
+ assert selection.used is False
+ assert selection.fallback_reason == "skill retrieval failed: boom"
diff --git a/tests/unit_tests/symphony/test_toolkit.py b/tests/unit_tests/symphony/test_toolkit.py
index 42cab23819..c9a8440ec6 100644
--- a/tests/unit_tests/symphony/test_toolkit.py
+++ b/tests/unit_tests/symphony/test_toolkit.py
@@ -4,10 +4,6 @@ from types import SimpleNamespace
from jiuwenswarm.agents.harness.common.tools.symphony_toolkits import (
SymphonyToolkit,
)
-from jiuwenswarm.agents.harness.common.tools.symphony_status_events import (
- begin_symphony_status_events,
- reset_symphony_status_events,
-)
from jiuwenswarm.extensions.registry import ExtensionRegistry
@@ -20,14 +16,6 @@ class _CallbackFramework:
return None
-class _StreamSession:
- def __init__(self):
- self.chunks = []
-
- async def write_stream(self, chunk):
- self.chunks.append(chunk)
-
-
def setup_function():
ExtensionRegistry.reset_instance()
@@ -140,13 +128,12 @@ def test_toolkit_plan_refreshes_stale_score_before_planning():
assert "Update: `succeeded`" in result["content"]
-def test_toolkit_plan_emits_status_events_for_fresh_score():
+def test_toolkit_plan_succeeds_for_fresh_score():
registry = ExtensionRegistry.create_instance(
callback_framework=_CallbackFramework(),
config={},
logger=object(),
)
- session = _StreamSession()
registry.register_rpc_handler(
"symphony.score_status",
lambda _params, request=None: {"success": True, "exists": True, "stale": False},
@@ -156,34 +143,17 @@ def test_toolkit_plan_emits_status_events_for_fresh_score():
lambda params, request=None: {"success": True, "params": params},
)
- token = begin_symphony_status_events(session, "parent-call")
- try:
- result = asyncio.run(SymphonyToolkit().plan("compose installed skills"))
- finally:
- reset_symphony_status_events(token)
+ result = asyncio.run(SymphonyToolkit().plan("compose installed skills"))
assert result["success"] is True
- assert [chunk.type for chunk in session.chunks] == [
- "chat.symphony_status",
- "chat.symphony_status",
- ]
- payloads = [chunk.payload for chunk in session.chunks]
- assert [payload["phase"] for payload in payloads] == [
- "checking_score",
- "planning",
- ]
- assert all(payload["source"] == "symphony_compose_score" for payload in payloads)
- assert all(payload["operation_id"] == "parent-call" for payload in payloads)
- assert all(payload["status"] == "in_progress" for payload in payloads)
-
-
-def test_toolkit_plan_emits_refresh_status_for_stale_score():
+
+
+def test_toolkit_plan_succeeds_after_refreshing_stale_score():
registry = ExtensionRegistry.create_instance(
callback_framework=_CallbackFramework(),
config={},
logger=object(),
)
- session = _StreamSession()
registry.register_rpc_handler(
"symphony.score_status",
lambda _params, request=None: {"success": True, "exists": True, "stale": True},
@@ -197,48 +167,22 @@ def test_toolkit_plan_emits_refresh_status_for_stale_score():
lambda params, request=None: {"success": True, "params": params},
)
- token = begin_symphony_status_events(session, "parent-call")
- try:
- result = asyncio.run(SymphonyToolkit().plan("compose installed skills"))
- finally:
- reset_symphony_status_events(token)
+ result = asyncio.run(SymphonyToolkit().plan("compose installed skills"))
assert result["success"] is True
- assert [chunk.type for chunk in session.chunks] == [
- "chat.symphony_status",
- "chat.symphony_status",
- "chat.symphony_status",
- ]
- assert [chunk.payload["phase"] for chunk in session.chunks] == [
- "checking_score",
- "building_score",
- "planning",
- ]
-
-
-def test_toolkit_plan_emits_failed_status_before_stopping():
+
+
+def test_toolkit_plan_returns_failure_when_score_status_fails():
ExtensionRegistry.create_instance(
callback_framework=_CallbackFramework(),
config={},
logger=object(),
)
- session = _StreamSession()
- token = begin_symphony_status_events(session, "parent-call")
- try:
- result = asyncio.run(SymphonyToolkit().plan("compose installed skills"))
- finally:
- reset_symphony_status_events(token)
+ result = asyncio.run(SymphonyToolkit().plan("compose installed skills"))
assert result["success"] is False
- assert [chunk.type for chunk in session.chunks] == [
- "chat.symphony_status",
- "chat.symphony_status",
- ]
- result_payload = session.chunks[-1].payload
- assert result_payload["phase"] == "checking_score"
- assert result_payload["status"] == "failed"
- assert "symphony.score_status" in result_payload["detail"]
+ assert "symphony.score_status" in result["detail"]
def test_toolkit_plan_preserves_plan_markdown_after_score_summary():
@@ -279,6 +223,99 @@ def test_toolkit_plan_preserves_plan_markdown_after_score_summary():
assert result["summary"] == result["content"]
+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
+
+
+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"},
+ },
+ )
+
+ result = asyncio.run(SymphonyToolkit().plan("compose missing skill plan"))
+
+ assert result["continue_after_display"] is True
+ assert result["followup_action"] == "external_skill_discovery"
+
+
+def test_toolkit_needs_input_does_not_continue_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": "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(),
@@ -321,3 +358,12 @@ def test_toolkit_get_tools_respects_symphony_enabled(monkeypatch):
if tool.card.name == "symphony_compose_score"
)
assert compose_tool.card.input_params["properties"]["mode"]["enum"] == ["fast"]
+ description = compose_tool.card.description
+ assert "skill capabilities, skill chaining, skill ordering" 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"]
+ )
diff --git a/tests/unit_tests/test_app_web_handlers.py b/tests/unit_tests/test_app_web_handlers.py
index dff2ff3726..572d2d20b0 100644
--- a/tests/unit_tests/test_app_web_handlers.py
+++ b/tests/unit_tests/test_app_web_handlers.py
@@ -5,6 +5,7 @@ import pytest
from jiuwenswarm.gateway.channel_manager.web.app_web_handlers import (
WebHandlersBindParams,
_flatten_modes_team_for_config_panel,
+ _flatten_symphony_for_config_panel,
_register_web_handlers,
)
@@ -129,3 +130,79 @@ def test_config_panel_flatten_reads_standalone_agent_registry():
assert flat["agent_skills_0"] == "coding"
assert flat["agent_max_iterations_0"] == "12"
assert flat["agent_completion_timeout_0"] == "34"
+
+
+def test_config_panel_flatten_reads_symphony_enabled_and_skill_retrieval():
+ raw = {
+ "symphony": {
+ "enabled": True,
+ "orchestration": {"mode": "fast"},
+ "skill_retrieval": {
+ "enabled": True,
+ "build": {"branching_factor": 64},
+ "retrieve": {"top_k": 5, "flatten_tree": True},
+ },
+ }
+ }
+
+ flat = _flatten_symphony_for_config_panel(raw)
+
+ assert flat["symphony_enabled"] == "true"
+ assert "symphony_orchestration_mode" not in flat
+ assert flat["skill_retrieval_enabled"] == "true"
+ assert flat["skill_retrieval_build_branching_factor"] == "64"
+ assert flat["skill_retrieval_retrieve_top_k"] == "5"
+ assert flat["skill_retrieval_flatten_tree"] == "true"
+
+
+async def test_config_set_routes_symphony_payload_to_config_helper(monkeypatch):
+ channel = FakeWebChannel()
+ recorded: list[dict] = []
+
+ _register_web_handlers(WebHandlersBindParams(channel=channel))
+
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.channel_manager.web.app_web_handlers.get_config_raw",
+ lambda: {"preferred_language": "zh"},
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.channel_manager.web.app_web_handlers.get_config",
+ lambda: {"symphony": {}},
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.gateway.channel_manager.web.app_web_handlers.update_symphony_in_config",
+ lambda updates: recorded.append(updates),
+ )
+
+ await channel.methods["config.set"](
+ object(),
+ "req-3",
+ {
+ "symphony_enabled": "true",
+ "skill_retrieval_enabled": "false",
+ "skill_retrieval_retrieve_top_k": "7",
+ },
+ "sess-3",
+ )
+
+ assert recorded == [
+ {
+ "enabled": True,
+ "skill_retrieval": {"enabled": False, "retrieve": {"top_k": 7}},
+ }
+ ]
+ assert channel.responses[-1] == {
+ "id": "req-3",
+ "ok": True,
+ "payload": {
+ "updated": [
+ "symphony_enabled",
+ "skill_retrieval_enabled",
+ "skill_retrieval_retrieve_top_k",
+ ],
+ "applied_without_restart": True,
+ },
+ "error": None,
+ "code": None,
+ }