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 inconsistency of skill indexes between the front end and the back end

xutuo4c938ef55717
diff --git a/jiuwenswarm/agents/harness/common/rails/skill_retrieval_prompt_rail.py b/jiuwenswarm/agents/harness/common/rails/skill_retrieval_prompt_rail.py
index cf64d789ac..2a715c4ecb 100644
--- a/jiuwenswarm/agents/harness/common/rails/skill_retrieval_prompt_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/skill_retrieval_prompt_rail.py
@@ -4,14 +4,17 @@ from __future__ import annotations
import asyncio
import logging
-from typing import Any
+from typing import Any, Callable
from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
from openjiuwen.harness.prompts import PromptSection
from openjiuwen.harness.prompts.sections import SectionName
from openjiuwen.harness.rails.base import DeepAgentRail
-from jiuwenswarm.symphony.agent import render_skill_retrieval_prompt
+from jiuwenswarm.symphony.agent import (
+ is_agentic_retrieval_enabled,
+ render_skill_retrieval_prompt_for_visible_skills,
+)
logger = logging.getLogger(__name__)
@@ -25,12 +28,19 @@ class SkillRetrievalPromptRail(DeepAgentRail):
SECTION_NAME = "skill_retrieval"
SECTION_PRIORITY = 41
- def __init__(self, *, manager: Any | None = None) -> None:
+ def __init__(
+ self,
+ *,
+ manager: Any | None = None,
+ visible_skill_names: set[str] | frozenset[str] | Callable[[], set[str] | frozenset[str] | None] | None = None,
+ ) -> None:
super().__init__()
self._manager = manager
+ self._visible_skill_names = visible_skill_names
self._agent = None
self.system_prompt_builder = None
self._hidden_legacy_abilities: dict[str, Any] = {}
+ self._hidden_skills_section: PromptSection | None = None
def init(self, agent: Any) -> None:
self._agent = agent
@@ -38,6 +48,7 @@ class SkillRetrievalPromptRail(DeepAgentRail):
def uninit(self, agent: Any) -> None:
self._restore_legacy_list_skill(agent)
+ self._restore_native_skills_section()
if self.system_prompt_builder is not None:
self.system_prompt_builder.remove_section(self.SECTION_NAME)
self.system_prompt_builder = None
@@ -50,19 +61,20 @@ class SkillRetrievalPromptRail(DeepAgentRail):
if self.system_prompt_builder is None:
self.system_prompt_builder = getattr(agent, "system_prompt_builder", None)
- self._hide_legacy_list_skill()
- self._filter_legacy_list_skill_from_model_inputs(ctx)
+ if not is_agentic_retrieval_enabled():
+ self._disable_agentic_prompt(ctx)
+ return
if self.system_prompt_builder is None:
return
- self.system_prompt_builder.remove_section(SectionName.SKILLS)
language = getattr(self.system_prompt_builder, "language", "cn") or "cn"
try:
content = await asyncio.to_thread(
- render_skill_retrieval_prompt,
+ render_skill_retrieval_prompt_for_visible_skills,
self._manager,
language=language,
+ visible_skill_names=self._resolve_visible_skill_names(),
)
except Exception as exc:
logger.warning("[SkillRetrievalPromptRail] render failed: %s", exc)
@@ -70,8 +82,12 @@ class SkillRetrievalPromptRail(DeepAgentRail):
if not content.strip():
self.system_prompt_builder.remove_section(self.SECTION_NAME)
+ self._restore_native_skills_section()
return
+ self._hide_legacy_list_skill()
+ self._filter_legacy_list_skill_from_model_inputs(ctx)
+ self._hide_native_skills_section()
self.system_prompt_builder.add_section(
PromptSection(
name=self.SECTION_NAME,
@@ -80,11 +96,25 @@ class SkillRetrievalPromptRail(DeepAgentRail):
)
)
+ def _disable_agentic_prompt(self, ctx: AgentCallbackContext) -> None:
+ self._restore_legacy_list_skill(getattr(ctx, "agent", None))
+ self._restore_native_skills_section()
+ if self.system_prompt_builder is not None:
+ self.system_prompt_builder.remove_section(self.SECTION_NAME)
+
+ def _resolve_visible_skill_names(self) -> set[str] | frozenset[str] | None:
+ provider = self._visible_skill_names
+ if callable(provider):
+ return provider()
+ return provider
+
async def after_model_call(self, ctx: AgentCallbackContext) -> None:
self._restore_legacy_list_skill(getattr(ctx, "agent", None))
+ self._restore_native_skills_section()
async def on_model_exception(self, ctx: AgentCallbackContext) -> None:
self._restore_legacy_list_skill(getattr(ctx, "agent", None))
+ self._restore_native_skills_section()
def _hide_legacy_list_skill(self) -> None:
ability_manager = getattr(self._agent, "ability_manager", None)
@@ -121,6 +151,20 @@ class SkillRetrievalPromptRail(DeepAgentRail):
add_ability(card)
self._hidden_legacy_abilities.pop(name, None)
+ def _hide_native_skills_section(self) -> None:
+ if self.system_prompt_builder is None:
+ return
+ if self._hidden_skills_section is None:
+ self._hidden_skills_section = self.system_prompt_builder.get_section(SectionName.SKILLS)
+ self.system_prompt_builder.remove_section(SectionName.SKILLS)
+
+ def _restore_native_skills_section(self) -> None:
+ if self.system_prompt_builder is None or self._hidden_skills_section is None:
+ return
+ if not self.system_prompt_builder.has_section(SectionName.SKILLS):
+ self.system_prompt_builder.add_section(self._hidden_skills_section)
+ self._hidden_skills_section = None
+
@staticmethod
def _filter_legacy_list_skill_from_model_inputs(ctx: AgentCallbackContext) -> None:
inputs = getattr(ctx, "inputs", None)
diff --git a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
index 0c5e199e4a..49459f5004 100644
--- a/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/stream_event_rail.py
@@ -42,6 +42,9 @@ _TODO_TOOL_NAMES = frozenset(["todo_create", "todo_get", "todo_list", "todo_modi
def _structured_tool_result_payload(result: Any) -> Any | None:
+ detailed_output = getattr(result, "detailed_output", None)
+ if detailed_output is not None:
+ return detailed_output
if isinstance(result, (dict, list)):
return result
return None
diff --git a/jiuwenswarm/agents/harness/common/tools/skill_retrieval_toolkits.py b/jiuwenswarm/agents/harness/common/tools/skill_retrieval_toolkits.py
index 9b5d758a1b..b26fb0c212 100644
--- a/jiuwenswarm/agents/harness/common/tools/skill_retrieval_toolkits.py
+++ b/jiuwenswarm/agents/harness/common/tools/skill_retrieval_toolkits.py
@@ -12,7 +12,9 @@ from jiuwenswarm.symphony.agent import (
build_skill_index,
is_agentic_retrieval_enabled,
skill_branch_explore,
+ skill_branch_explore_for_visible_skills,
skill_branch_peek,
+ skill_branch_peek_for_visible_skills,
)
@@ -23,17 +25,45 @@ def is_skill_retrieval_enabled() -> bool:
class SkillRetrievalToolkit:
"""Expose agentic installed-skill tree retrieval to agents."""
- def __init__(self, manager: SkillManager) -> None:
+ def __init__(
+ self,
+ manager: SkillManager,
+ *,
+ visible_skill_names: set[str] | frozenset[str] | Callable[[], set[str] | frozenset[str] | None] | None = None,
+ ) -> None:
self._manager = manager
+ self._visible_skill_names = visible_skill_names
async def skill_index_build(self) -> dict[str, Any]:
return await asyncio.to_thread(build_skill_index, self._manager)
async def skill_branch_peek(self, node_ids: list[str]) -> dict[str, Any]:
- return await asyncio.to_thread(skill_branch_peek, node_ids, self._manager)
+ visible_skill_names = self._resolve_visible_skill_names()
+ if visible_skill_names is None:
+ return await asyncio.to_thread(skill_branch_peek, node_ids, self._manager)
+ return await asyncio.to_thread(
+ skill_branch_peek_for_visible_skills,
+ node_ids,
+ self._manager,
+ visible_skill_names=visible_skill_names,
+ )
async def skill_branch_explore(self, node_ids: list[str]) -> dict[str, Any]:
- return await asyncio.to_thread(skill_branch_explore, node_ids, self._manager)
+ visible_skill_names = self._resolve_visible_skill_names()
+ if visible_skill_names is None:
+ return await asyncio.to_thread(skill_branch_explore, node_ids, self._manager)
+ return await asyncio.to_thread(
+ skill_branch_explore_for_visible_skills,
+ node_ids,
+ self._manager,
+ visible_skill_names=visible_skill_names,
+ )
+
+ def _resolve_visible_skill_names(self) -> set[str] | frozenset[str] | None:
+ provider = self._visible_skill_names
+ if callable(provider):
+ return provider()
+ return provider
def get_tools(self) -> list[Tool]:
def make_tool(name: str, description: str, input_params: dict, func: Callable[..., Any]) -> Tool:
@@ -49,7 +79,7 @@ class SkillRetrievalToolkit:
make_tool(
name="skill_index_build",
description=(
- "Build or refresh the local tree index for installed enabled skills. "
+ "Build or refresh the local tree index for installed skills. "
"Do not call this proactively. First call skill_branch_explore or skill_branch_peek; "
"call skill_index_build only if those tools return a failure result that explicitly "
"says the index is missing or stale and instructs you to build it."
diff --git a/jiuwenswarm/agents/swarm/providers/member_rails.py b/jiuwenswarm/agents/swarm/providers/member_rails.py
index d25f9ca19d..08c1cace0f 100644
--- a/jiuwenswarm/agents/swarm/providers/member_rails.py
+++ b/jiuwenswarm/agents/swarm/providers/member_rails.py
@@ -67,9 +67,9 @@ def _workspace_root(ctx: SwarmBuildContext) -> str | None:
class SkillRetrievalPromptInput(ConstructionInput):
"""Construction inputs for the agentic skill retrieval prompt rail."""
- workspace_root: str | None = context_field(
- resolver=_workspace_root,
- description="Member workspace root; the SkillManager resolves installed skills from it.",
+ global_skills_dir: str | None = context_field(
+ attr="global_skills_dir",
+ description="Global installed skills source directory.",
)
@@ -87,13 +87,17 @@ def _build_skill_retrieval_prompt_rail(
from jiuwenswarm.agents.harness.common.tools.skill_retrieval_toolkits import (
is_skill_retrieval_enabled,
)
+ from jiuwenswarm.agents.swarm.providers.tools import visible_skill_names_for_list_skill
from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
if not is_skill_retrieval_enabled():
return None
- inp = SkillRetrievalPromptInput.resolve(params, context)
- manager = SkillManager(workspace_dir=inp.workspace_root)
- return SkillRetrievalPromptRail(manager=manager)
+ SkillRetrievalPromptInput.resolve(params, context)
+ manager = SkillManager()
+ return SkillRetrievalPromptRail(
+ manager=manager,
+ visible_skill_names=lambda: visible_skill_names_for_list_skill(context),
+ )
class RuntimePromptInput(ConstructionInput):
diff --git a/jiuwenswarm/agents/swarm/providers/tools.py b/jiuwenswarm/agents/swarm/providers/tools.py
index e1436a6df0..34c162a281 100644
--- a/jiuwenswarm/agents/swarm/providers/tools.py
+++ b/jiuwenswarm/agents/swarm/providers/tools.py
@@ -24,9 +24,11 @@ The generic web / vision / audio tools are provided by openjiuwen
from __future__ import annotations
+import json
import logging
import os
-from typing import Any
+from pathlib import Path
+from typing import Any, Callable
from openjiuwen.agent_teams.harness.manifest import (
ConstructionInput,
@@ -94,6 +96,7 @@ VIDEO = "swarm.video"
IMAGE_GEN = "swarm.image_gen"
XIAOYI_PHONE = "swarm.xiaoyi_phone"
CODE_EXTRA_TOOLS = "swarm.code_extra_tools"
+_CODE_MODES = frozenset({"code.team", "team.plan"})
# xiaoyi phone tool objects, gated by ``channels.xiaoyi.phone_tools_enabled``.
_XIAOYI_PHONE_TOOLS = (
@@ -152,6 +155,75 @@ def _workspace_root(ctx: SwarmBuildContext) -> str | None:
return getattr(ctx.workspace, "root_path", None) if ctx.workspace else None
+def _scan_skill_names_from_dirs(skill_dirs: list[str], disabled_skills: set[str]) -> set[str]:
+ names: set[str] = set()
+ for raw_dir in skill_dirs:
+ root = Path(raw_dir).expanduser()
+ if not root.is_dir():
+ continue
+ for child in sorted(root.iterdir(), key=lambda path: path.name.lower()):
+ if not child.is_dir() or child.name.startswith("_") or child.name.startswith("."):
+ continue
+ if child.name in disabled_skills:
+ continue
+ if (child / "SKILL.md").is_file():
+ names.add(child.name)
+ return names
+
+
+def _collect_disabled_skills_from_state(skill_dirs: list[str]) -> set[str]:
+ disabled: set[str] = set()
+ for raw_dir in skill_dirs:
+ state_path = Path(raw_dir).expanduser() / "skills_state.json"
+ if not state_path.is_file():
+ continue
+ try:
+ data = json.loads(state_path.read_text(encoding="utf-8"))
+ except (json.JSONDecodeError, OSError):
+ logger.warning("[swarm.skill_retrieval] failed to read skills state: %s", state_path)
+ continue
+ skill_configs = data.get("skill_configs", {})
+ if not isinstance(skill_configs, dict):
+ continue
+ for name, cfg in skill_configs.items():
+ if isinstance(cfg, dict) and cfg.get("enabled") is False:
+ disabled.add(str(name))
+ return disabled
+
+
+def _list_skill_dirs_for_context(ctx: SwarmBuildContext) -> list[str]:
+ workspace = getattr(ctx, "workspace", None)
+ if workspace is None:
+ return []
+
+ skill_dirs: list[str] = []
+ get_node_path = getattr(workspace, "get_node_path", None)
+ if callable(get_node_path):
+ skills_base = get_node_path("skills")
+ if skills_base:
+ skill_dirs.append(str(skills_base))
+
+ list_team_links = getattr(workspace, "list_team_links", None)
+ if callable(list_team_links):
+ for _team_id, target_path in list_team_links():
+ skill_dirs.append(str(Path(target_path) / "skills"))
+ return skill_dirs
+
+
+def visible_skill_names_for_list_skill(ctx: SwarmBuildContext) -> set[str]:
+ """Return the skill names that the matching SkillUseRail would expose."""
+ if ctx.mode in _CODE_MODES:
+ from jiuwenswarm.common.utils import get_agent_skills_dir
+ from jiuwenswarm.server.runtime.skill import load_execution_disabled_skills
+
+ skill_dirs = [str(Path(ctx.global_skills_dir) if ctx.global_skills_dir else get_agent_skills_dir())]
+ return _scan_skill_names_from_dirs(skill_dirs, set(load_execution_disabled_skills()))
+
+ skill_dirs = _list_skill_dirs_for_context(ctx)
+ disabled_skills = _collect_disabled_skills_from_state(skill_dirs)
+ return _scan_skill_names_from_dirs(skill_dirs, disabled_skills)
+
+
def _parse_int(value: Any, default: int) -> int:
"""Parse an int from a possibly-None/str value, falling back to ``default``."""
try:
@@ -263,14 +335,22 @@ def _build_skill_toolkit_tools(workspace_root: str | None) -> list[Any]:
return []
-def _build_skill_retrieval_tools(workspace_root: str | None) -> list[Any]:
- """Build the installed-skill retrieval tools bound to the member workspace."""
+VisibleSkillNamesProvider = Callable[[], set[str] | frozenset[str] | None]
+
+
+def _build_skill_retrieval_tools(
+ visible_skill_names: set[str] | frozenset[str] | VisibleSkillNamesProvider | None = None,
+) -> list[Any]:
+ """Build installed-skill retrieval tools against the global installed skill root."""
if not is_skill_retrieval_enabled():
logger.info("[swarm.skill_retrieval] skipped: disabled")
return []
try:
- manager = SkillManager(workspace_dir=workspace_root)
- toolkit = SkillRetrievalToolkit(manager=manager)
+ manager = SkillManager()
+ if visible_skill_names is None:
+ toolkit = SkillRetrievalToolkit(manager=manager)
+ else:
+ toolkit = SkillRetrievalToolkit(manager=manager, visible_skill_names=visible_skill_names)
return list(toolkit.get_tools())
except Exception as exc:
logger.warning("[swarm.skill_retrieval] construction failed: %s", exc)
@@ -325,6 +405,15 @@ class SkillToolkitInput(ConstructionInput):
)
+class SkillRetrievalInput(ConstructionInput):
+ """Construction inputs for global installed-skill retrieval tools."""
+
+ global_skills_dir: str | None = context_field(
+ attr="global_skills_dir",
+ description="Global installed skills source directory.",
+ )
+
+
@harness_element(
kind=ElementKind.TOOL,
name=SKILL_TOOLKIT,
@@ -340,13 +429,15 @@ def build_skill_toolkit(params: dict[str, Any], ctx: SwarmBuildContext) -> list[
@harness_element(
kind=ElementKind.TOOL,
name=SKILL_RETRIEVAL,
- description="Agentic installed skill tree retrieval tools bound to the member workspace.",
- input_model=SkillToolkitInput,
+ description="Agentic installed skill tree retrieval tools for globally installed skills.",
+ input_model=SkillRetrievalInput,
)
def build_skill_retrieval(params: dict[str, Any], ctx: SwarmBuildContext) -> list[Any]:
"""Build the whitelist-filtered installed-skill retrieval tools."""
- inp = SkillToolkitInput.resolve(params, ctx)
- return _filter_whitelist(_build_skill_retrieval_tools(inp.workspace_root))
+ SkillRetrievalInput.resolve(params, ctx)
+ return _filter_whitelist(
+ _build_skill_retrieval_tools(lambda: visible_skill_names_for_list_skill(ctx))
+ )
@harness_element(
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx
index fe195a7461..16f8cab167 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ConfigPanel/index.tsx
@@ -283,7 +283,19 @@ const AGENT_KEYS = new Set(["name", "model", "skills"]);
const TEAM_KEYS = new Set(["team_name", "lifecycle", "teammate_mode", "spawn_mode"]);
const FREE_SEARCH_BOOLEAN_KEYS = new Set(["free_search_ddg_enabled", "free_search_bing_enabled"]);
const FREE_SEARCH_KEYS = new Set([...FREE_SEARCH_BOOLEAN_KEYS]);
-const HIDDEN_CONFIG_KEYS = new Set(["free_search_proxy_url"]);
+const HIDDEN_CONFIG_KEYS = new Set([
+ "free_search_proxy_url",
+ "skill_retrieval_build_branching_factor",
+ "skill_retrieval_build_root_categories",
+ "skill_retrieval_build_request_timeout_seconds",
+ "skill_retrieval_build_discovery_seed",
+ "skill_retrieval_build_postprocess_enabled",
+ "skill_retrieval_build_postprocess_max_passes",
+ "skill_retrieval_build_postprocess_min_skills",
+ "skill_retrieval_build_equivalence_enabled",
+ "skill_retrieval_retrieve_compact_codes_enabled",
+ "skill_retrieval_retrieve_flatten_tree",
+]);
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"]);
@@ -292,30 +304,17 @@ const SYMPHONY_KEYS = new Set([
]);
const SKILL_RETRIEVAL_BOOLEAN_KEYS = new Set([
"skill_retrieval_enabled",
- "skill_retrieval_build_postprocess_enabled",
- "skill_retrieval_build_equivalence_enabled",
- "skill_retrieval_retrieve_compact_codes_enabled",
- "skill_retrieval_retrieve_flatten_tree",
]);
const MULTILINE_CONFIG_KEYS = new Set([
"skill_retrieval_build_root_categories",
]);
const SKILL_RETRIEVAL_KEYS = new Set([
"skill_retrieval_enabled",
- "skill_retrieval_build_branching_factor",
"skill_retrieval_build_max_depth",
- "skill_retrieval_build_root_categories",
"skill_retrieval_build_max_workers",
"skill_retrieval_build_max_retries",
- "skill_retrieval_build_request_timeout_seconds",
+ "skill_retrieval_build_total_timeout_seconds",
"skill_retrieval_build_classification_batch_limit",
- "skill_retrieval_build_discovery_seed",
- "skill_retrieval_build_postprocess_enabled",
- "skill_retrieval_build_postprocess_max_passes",
- "skill_retrieval_build_postprocess_min_skills",
- "skill_retrieval_build_equivalence_enabled",
- "skill_retrieval_retrieve_compact_codes_enabled",
- "skill_retrieval_retrieve_flatten_tree",
"skill_retrieval_retrieve_max_exposure_depth",
]);
@@ -597,6 +596,7 @@ const KEY_DISPLAY_I18N: Record<string, string> = {
skill_retrieval_build_max_workers: "config.keys.skillRetrievalBuildMaxWorkers",
skill_retrieval_build_max_retries: "config.keys.skillRetrievalBuildMaxRetries",
skill_retrieval_build_request_timeout_seconds: "config.keys.skillRetrievalBuildTimeout",
+ skill_retrieval_build_total_timeout_seconds: "config.keys.skillRetrievalBuildTotalTimeout",
skill_retrieval_build_classification_batch_limit: "config.keys.skillRetrievalBuildClassificationBatchLimit",
skill_retrieval_build_discovery_seed: "config.keys.skillRetrievalBuildDiscoverySeed",
skill_retrieval_build_postprocess_enabled: "config.keys.skillRetrievalBuildPostprocessEnabled",
@@ -624,21 +624,12 @@ const KEY_SORT_PRIORITY: Record<string, number> = {
free_search_bing_enabled: 1,
symphony_enabled: 0,
skill_retrieval_enabled: 0,
- skill_retrieval_build_branching_factor: 10,
- skill_retrieval_build_max_depth: 11,
- skill_retrieval_build_max_workers: 12,
- skill_retrieval_build_max_retries: 13,
- skill_retrieval_build_request_timeout_seconds: 14,
- skill_retrieval_build_classification_batch_limit: 15,
- skill_retrieval_build_discovery_seed: 16,
- skill_retrieval_build_postprocess_enabled: 17,
- skill_retrieval_build_postprocess_max_passes: 18,
- skill_retrieval_build_postprocess_min_skills: 19,
- skill_retrieval_build_equivalence_enabled: 20,
- skill_retrieval_build_root_categories: 21,
- skill_retrieval_retrieve_compact_codes_enabled: 31,
- skill_retrieval_retrieve_flatten_tree: 32,
- skill_retrieval_retrieve_max_exposure_depth: 33,
+ skill_retrieval_retrieve_max_exposure_depth: 10,
+ skill_retrieval_build_max_depth: 20,
+ skill_retrieval_build_max_workers: 21,
+ skill_retrieval_build_max_retries: 22,
+ skill_retrieval_build_total_timeout_seconds: 23,
+ skill_retrieval_build_classification_batch_limit: 24,
memory_forbidden_enabled: 0,
memory_forbidden_description: 1,
model: 0,
diff --git a/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx
index 61b78447bc..f96a4b7956 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx
@@ -69,10 +69,26 @@ type SkillRetrievalStatus = {
enabled?: boolean;
index_exists?: boolean;
fresh?: boolean;
+ installed_count?: number;
installed_enabled_count?: number;
indexed_count?: number;
built_at?: string;
index_dir?: string;
+ build_status?: string;
+ build_stage?: string;
+ build_message?: string;
+ build_error?: string;
+ build_progress?: number;
+ build_started_at?: string;
+ build_finished_at?: string;
+ build_elapsed_seconds?: number;
+ build_cancel_requested?: boolean;
+ build_logs?: Array<{
+ time?: string;
+ stage?: string;
+ status?: string;
+ message?: string;
+ }>;
};
type SkillRetrievalTreeResponse = {
@@ -288,7 +304,7 @@ function SkillIndexTreeView({
}
export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }: SkillPanelProps) {
- const { t } = useTranslation();
+ const { t, i18n } = useTranslation();
const [activeTab, setActiveTab] = useState<"my" | "marketplace" | "index" | "graph">("my");
const [mySkillsSubTab, setMySkillsSubTab] = useState<"all" | "enabled" | "disabled">("all");
const [marketplaceSubTab, setMarketplaceSubTab] = useState<"builtin" | "swarmskills" | "online">("builtin");
@@ -308,15 +324,15 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
const [message, setMessage] = useState<string | null>(null);
const [messageType, setMessageType] = useState<"success" | "error" | "loading" | null>(null);
const messageTimerRef = useRef<number | null>(null);
+ const retrievalPollRef = useRef<number | null>(null);
+ const retrievalDiscoveryPollRef = useRef<number | null>(null);
const [viewMode, setViewMode] = useState<"list" | "grid">("list");
const [retrievalStatus, setRetrievalStatus] = useState<SkillRetrievalStatus | null>(null);
- const [retrievalQuery, setRetrievalQuery] = useState("");
- const [retrievalResult, setRetrievalResult] = useState("");
const [retrievalTree, setRetrievalTree] = useState("");
const [retrievalTreeNodes, setRetrievalTreeNodes] = useState<SkillIndexNode[]>([]);
const [retrievalTreeCounts, setRetrievalTreeCounts] = useState({ branches: 0, skills: 0 });
const [selectedTreeNodeCid, setSelectedTreeNodeCid] = useState<string | null>(null);
- const [retrievalLoading, setRetrievalLoading] = useState<"idle" | "status" | "tree" | "build" | "search">("idle");
+ const [retrievalLoading, setRetrievalLoading] = useState<"idle" | "status" | "tree" | "build" | "cancel">("idle");
useEffect(() => {
return () => {
@@ -326,6 +342,12 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
if (searchDebounceRef.current !== null) {
window.clearTimeout(searchDebounceRef.current);
}
+ if (retrievalPollRef.current !== null) {
+ window.clearInterval(retrievalPollRef.current);
+ }
+ if (retrievalDiscoveryPollRef.current !== null) {
+ window.clearInterval(retrievalDiscoveryPollRef.current);
+ }
};
}, []);
@@ -534,7 +556,7 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
try {
const data = await webRequest<SkillRetrievalTreeResponse>(
"skills.retrieval.tree",
- withSession()
+ withSession({ language: i18n.language || "cn" })
);
const nodes = Array.isArray(data.nodes) ? data.nodes : [];
setRetrievalTree(data.result || "");
@@ -562,7 +584,7 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
} finally {
setRetrievalLoading((current) => (current === "tree" ? "idle" : current));
}
- }, [withSession]);
+ }, [i18n.language, withSession]);
// 当左边栏切换到技能页面时,或切换到"我的技能"页签时,调用 list 接口
useEffect(() => {
@@ -592,46 +614,94 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
void fetchRetrievalTree();
}, [activeTab, fetchRetrievalStatus, fetchRetrievalTree]);
+ useEffect(() => {
+ const running = retrievalStatus?.build_status === "running";
+ if (activeTab !== "index" || !running) {
+ if (retrievalPollRef.current !== null) {
+ window.clearInterval(retrievalPollRef.current);
+ retrievalPollRef.current = null;
+ }
+ return;
+ }
+ if (retrievalPollRef.current !== null) return;
+ retrievalPollRef.current = window.setInterval(() => {
+ void fetchRetrievalStatus();
+ void fetchRetrievalTree();
+ }, 2000);
+ return () => {
+ if (retrievalPollRef.current !== null) {
+ window.clearInterval(retrievalPollRef.current);
+ retrievalPollRef.current = null;
+ }
+ };
+ }, [activeTab, fetchRetrievalStatus, fetchRetrievalTree, retrievalStatus?.build_status]);
+
+ useEffect(() => {
+ const running = retrievalStatus?.build_status === "running";
+ if (activeTab !== "index" || running) {
+ if (retrievalDiscoveryPollRef.current !== null) {
+ window.clearInterval(retrievalDiscoveryPollRef.current);
+ retrievalDiscoveryPollRef.current = null;
+ }
+ return;
+ }
+ if (retrievalDiscoveryPollRef.current !== null) return;
+ retrievalDiscoveryPollRef.current = window.setInterval(() => {
+ void fetchRetrievalStatus();
+ }, 5000);
+ return () => {
+ if (retrievalDiscoveryPollRef.current !== null) {
+ window.clearInterval(retrievalDiscoveryPollRef.current);
+ retrievalDiscoveryPollRef.current = null;
+ }
+ };
+ }, [activeTab, fetchRetrievalStatus, retrievalStatus?.build_status]);
+
+ useEffect(() => {
+ if (activeTab !== "index") return;
+ if (retrievalStatus?.build_status === "success" || (retrievalStatus?.index_exists && retrievalStatus?.fresh)) {
+ void fetchRetrievalTree();
+ }
+ }, [
+ activeTab,
+ fetchRetrievalTree,
+ retrievalStatus?.build_status,
+ retrievalStatus?.fresh,
+ retrievalStatus?.index_exists,
+ ]);
+
const handleBuildRetrievalIndex = useCallback(async () => {
setRetrievalLoading("build");
- setRetrievalResult("");
try {
- const data = await webRequest<{ success: boolean; result?: string }>(
+ await webRequest<{ success: boolean; result?: string }>(
"skills.retrieval.index_build",
- withSession(),
- { timeoutMs: 31 * 60_000 }
+ withSession({ force: true, source: "web" }),
+ { timeoutMs: 30_000 }
);
- setRetrievalResult(data.result || "");
await fetchRetrievalStatus();
await fetchRetrievalTree();
} catch (error) {
console.error(error);
- setRetrievalResult(error instanceof Error ? error.message : String(error));
} finally {
setRetrievalLoading("idle");
}
}, [fetchRetrievalStatus, fetchRetrievalTree, withSession]);
- const handleSkillRetrieve = useCallback(async () => {
- const query = retrievalQuery.trim();
- if (!query) return;
- setRetrievalLoading("search");
- setRetrievalResult("");
+ const handleCancelRetrievalBuild = useCallback(async () => {
+ setRetrievalLoading("cancel");
try {
- const data = await webRequest<{ success: boolean; result?: string }>(
- "skills.retrieval.search",
- withSession({ query }),
- { timeoutMs: 120_000 }
+ await webRequest<{ success: boolean; result?: string }>(
+ "skills.retrieval.index_cancel",
+ withSession(),
+ { timeoutMs: 30_000 }
);
- setRetrievalResult(data.result || "");
await fetchRetrievalStatus();
} catch (error) {
console.error(error);
- setRetrievalResult(error instanceof Error ? error.message : String(error));
} finally {
setRetrievalLoading("idle");
}
- }, [fetchRetrievalStatus, retrievalQuery, withSession]);
+ }, [fetchRetrievalStatus, withSession]);
const handleOpenSkill = useCallback(
(skillName: string) => {
@@ -1052,12 +1122,23 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
const retrievalStatusText = retrievalStatus
? retrievalStatus.enabled === false
? t('skills.retrieval.disabled')
+ : retrievalStatus.build_status === "running"
+ ? t('skills.retrieval.building')
+ : retrievalStatus.build_status === "failed"
+ ? t('skills.retrieval.buildFailed')
+ : retrievalStatus.build_status === "cancelled"
+ ? t('skills.retrieval.cancelled')
: retrievalStatus.index_exists
? retrievalStatus.fresh
? t('skills.retrieval.ready')
: t('skills.retrieval.stale')
: t('skills.retrieval.missing')
: t('common.loading');
+ const retrievalBuildRunning = retrievalStatus?.build_status === "running";
+ const retrievalBuildProgress = Math.round(Math.max(0, Math.min(1, retrievalStatus?.build_progress ?? 0)) * 100);
+ const retrievalBuildLogs = Array.isArray(retrievalStatus?.build_logs)
+ ? retrievalStatus.build_logs.slice(-6)
+ : [];
return (
<>
{message && messageType === "success" && (
@@ -1225,8 +1306,10 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
{retrievalStatus?.indexed_count != null
? ` · ${t('skills.retrieval.indexedCount', { count: retrievalStatus.indexed_count })}`
: ""}
- {retrievalStatus?.installed_enabled_count != null
- ? ` · ${t('skills.retrieval.enabledCount', { count: retrievalStatus.installed_enabled_count })}`
+ {(retrievalStatus?.installed_count ?? retrievalStatus?.installed_enabled_count) != null
+ ? ` · ${t('skills.retrieval.installedCount', {
+ count: retrievalStatus?.installed_count ?? retrievalStatus?.installed_enabled_count,
+ })}`
: ""}
</div>
</div>
@@ -1234,12 +1317,23 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
<button
onClick={handleBuildRetrievalIndex}
className="px-3 py-1.5 rounded-lg text-sm border border-border hover:bg-secondary transition-colors disabled:opacity-60"
- disabled={retrievalLoading === "build" || retrievalStatus?.enabled === false}
+ disabled={retrievalLoading === "build" || retrievalBuildRunning || retrievalStatus?.enabled === false}
>
{retrievalLoading === "build"
? t('skills.retrieval.building')
: t('skills.retrieval.build')}
</button>
+ {retrievalBuildRunning ? (
+ <button
+ onClick={handleCancelRetrievalBuild}
+ className="px-3 py-1.5 rounded-lg text-sm border border-border hover:bg-secondary transition-colors disabled:opacity-60"
+ disabled={retrievalLoading === "cancel" || retrievalStatus?.build_cancel_requested}
+ >
+ {retrievalLoading === "cancel" || retrievalStatus?.build_cancel_requested
+ ? t('skills.retrieval.cancelling')
+ : t('skills.retrieval.cancel')}
+ </button>
+ ) : null}
<button
onClick={() => {
void fetchRetrievalStatus();
@@ -1254,34 +1348,43 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
</button>
</div>
</div>
- <div className="mt-4 flex items-center gap-2">
- <input
- type="text"
- value={retrievalQuery}
- onChange={(event) => setRetrievalQuery(event.target.value)}
- onKeyDown={(event) => {
- if (event.key === "Enter") {
- handleSkillRetrieve();
- }
- }}
- placeholder={t('skills.retrieval.queryPlaceholder')}
- className="w-full px-3 py-1.5 rounded-lg text-sm bg-secondary border border-border text-text placeholder:text-text-muted"
- />
- <button
- onClick={handleSkillRetrieve}
- className="px-3 py-1.5 rounded-lg text-sm border border-border hover:bg-secondary transition-colors disabled:opacity-60"
- disabled={retrievalLoading === "search" || !retrievalQuery.trim() || retrievalStatus?.enabled === false}
- >
- {retrievalLoading === "search"
- ? t('skills.retrieval.searching')
- : t('skills.retrieval.search')}
- </button>
- </div>
- {retrievalResult && (
- <pre className="mt-3 max-h-64 overflow-auto whitespace-pre-wrap rounded-md bg-secondary p-3 text-xs text-text">
- {retrievalResult}
- </pre>
- )}
+ {(retrievalBuildRunning || retrievalStatus?.build_status === "failed" || retrievalStatus?.build_status === "cancelled") ? (
+ <div className="mt-4 rounded-md border border-border bg-secondary/40 p-3">
+ <div className="flex flex-wrap items-center justify-between gap-2 text-xs">
+ <span className="font-medium text-text-strong">
+ {retrievalStatus?.build_stage || t('skills.retrieval.buildStageUnknown')}
+ </span>
+ <span className="text-text-muted">
+ {t('skills.retrieval.buildProgress', { progress: retrievalBuildProgress })}
+ </span>
+ </div>
+ <div className="mt-2 h-2 overflow-hidden rounded-full bg-secondary">
+ <div
+ className="h-full rounded-full bg-emerald-500 transition-all"
+ style={{ width: `${retrievalBuildProgress}%` }}
+ />
+ </div>
+ {retrievalStatus?.build_message ? (
+ <div className="mt-2 text-xs text-text-muted">
+ {retrievalStatus.build_message}
+ </div>
+ ) : null}
+ {retrievalStatus?.build_error ? (
+ <pre className="mt-2 max-h-32 overflow-auto whitespace-pre-wrap rounded border border-red-500/20 bg-red-500/5 p-2 text-xs text-red-600">
+ {retrievalStatus.build_error}
+ </pre>
+ ) : null}
+ {retrievalBuildLogs.length > 0 ? (
+ <div className="mt-3 space-y-1">
+ {retrievalBuildLogs.map((log, index) => (
+ <div key={`${log.time || index}-${log.stage || ""}`} className="font-mono text-[11px] text-text-muted">
+ [{log.stage || "-"}] {log.message || log.status || ""}
+ </div>
+ ))}
+ </div>
+ ) : null}
+ </div>
+ ) : null}
</div>
<div className="grid flex-1 min-h-0 grid-cols-1 gap-4 lg:grid-cols-[minmax(320px,1fr)_minmax(320px,0.9fr)]">
<div className="rounded-lg border border-border bg-panel p-4 min-h-0 flex flex-col">
diff --git a/jiuwenswarm/channels/web/frontend/src/features/tool-events/toolEventNormalizer.ts b/jiuwenswarm/channels/web/frontend/src/features/tool-events/toolEventNormalizer.ts
index b1551e318c..4ade6f1801 100644
--- a/jiuwenswarm/channels/web/frontend/src/features/tool-events/toolEventNormalizer.ts
+++ b/jiuwenswarm/channels/web/frontend/src/features/tool-events/toolEventNormalizer.ts
@@ -146,9 +146,7 @@ export function normalizeToolResultPayload(payload: UnknownPayload): NormalizedT
: success ? undefined : '❌';
const skillTree =
parseSkillTreePath(toolResultPayload.raw_output) ??
- parseSkillTreePath(toolResultPayload.rawOutput) ??
- parseSkillTreePath(toolResultPayload) ??
- parseSkillTreePath(toolResultPayload.result);
+ parseSkillTreePath(toolResultPayload.rawOutput);
return {
toolName,
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
index be32d587a9..e3552b5363 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
@@ -698,6 +698,7 @@
"skillRetrievalBuildMaxWorkers": "Build workers",
"skillRetrievalBuildMaxRetries": "Build retries",
"skillRetrievalBuildTimeout": "Build request timeout (s)",
+ "skillRetrievalBuildTotalTimeout": "Build total timeout (s, 0 disables)",
"skillRetrievalBuildClassificationBatchLimit": "Classification batch limit",
"skillRetrievalBuildDiscoverySeed": "Discovery seed",
"skillRetrievalBuildPostprocessEnabled": "Enable build postprocess",
@@ -1051,12 +1052,15 @@
"stale": "Index needs update",
"missing": "Index not built",
"indexedCount": "{{count}} indexed",
- "enabledCount": "{{count}} enabled",
+ "installedCount": "{{count}} installed",
"build": "Build Index",
"building": "Building...",
- "search": "Retrieve",
- "searching": "Retrieving...",
- "queryPlaceholder": "Enter a task to retrieve installed skills",
+ "buildFailed": "Build failed",
+ "cancel": "Pause Build",
+ "cancelling": "Pausing...",
+ "cancelled": "Build paused",
+ "buildStageUnknown": "Waiting for build status",
+ "buildProgress": "Progress {{progress}}%",
"treeTitle": "Index Tree",
"treeCount": "{{branches}} branches · {{skills}} skills",
"noTree": "No index tree",
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
index 3f00783549..926847d306 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
@@ -697,6 +697,7 @@
"skillRetrievalBuildMaxWorkers": "构建并发数",
"skillRetrievalBuildMaxRetries": "构建重试次数",
"skillRetrievalBuildTimeout": "构建请求超时(秒)",
+ "skillRetrievalBuildTotalTimeout": "构建总超时(秒,0为不限制)",
"skillRetrievalBuildClassificationBatchLimit": "分类批大小上限",
"skillRetrievalBuildDiscoverySeed": "分支发现随机种子",
"skillRetrievalBuildPostprocessEnabled": "启用构建后处理",
@@ -1050,12 +1051,15 @@
"stale": "索引需要更新",
"missing": "索引未构建",
"indexedCount": "已索引 {{count}} 个",
- "enabledCount": "启用 {{count}} 个",
+ "installedCount": "已安装 {{count}} 个",
"build": "构建索引",
"building": "构建中...",
- "search": "检索",
- "searching": "检索中...",
- "queryPlaceholder": "输入任务需求,检索已安装技能",
+ "buildFailed": "构建失败",
+ "cancel": "暂停构建",
+ "cancelling": "暂停中...",
+ "cancelled": "构建已暂停",
+ "buildStageUnknown": "等待构建状态",
+ "buildProgress": "进度 {{progress}}%",
"treeTitle": "索引树",
"treeCount": "{{branches}} 个分支 · {{skills}} 个技能",
"noTree": "暂无索引树",
diff --git a/jiuwenswarm/common/config.py b/jiuwenswarm/common/config.py
index cecb1c391f..8de632b9b2 100644
--- a/jiuwenswarm/common/config.py
+++ b/jiuwenswarm/common/config.py
@@ -20,26 +20,6 @@ logger = logging.getLogger(__name__)
_CONFIG_MODULE_DIR = Path(__file__).parent
CONFIG_YAML_PATH = get_config_file()
-_SKILL_RETRIEVAL_PUBLIC_BUILD_KEYS = {
- "branching_factor",
- "max_depth",
- "root_categories",
- "max_workers",
- "max_retries",
- "request_timeout_seconds",
- "classification_batch_limit",
- "discovery_seed",
- "postprocess_enabled",
- "postprocess_max_passes",
- "postprocess_min_skills",
- "equivalence_enabled",
-}
-_SKILL_RETRIEVAL_PUBLIC_RETRIEVE_KEYS = {
- "compact_codes_enabled",
- "flatten_tree",
- "max_exposure_depth",
-}
-
# Check if user workspace exists and use it if configured via env
_user_config = os.getenv("JIUWENSWARM_CONFIG_DIR")
if _user_config:
@@ -307,28 +287,7 @@ def update_skill_retrieval_in_config(updates: dict[str, Any]) -> None:
if "skill_retrieval" not in symphony or symphony["skill_retrieval"] is None:
symphony["skill_retrieval"] = {}
section = symphony["skill_retrieval"]
-
- def prune_internal_keys() -> None:
- build = section.get("build")
- if isinstance(build, dict):
- for key in list(build.keys()):
- if key not in _SKILL_RETRIEVAL_PUBLIC_BUILD_KEYS:
- build.pop(key, None)
- if not build:
- section.pop("build", None)
- retrieve = section.get("retrieve")
- if isinstance(retrieve, dict):
- for key in list(retrieve.keys()):
- if key not in _SKILL_RETRIEVAL_PUBLIC_RETRIEVE_KEYS:
- retrieve.pop(key, None)
- if not retrieve:
- section.pop("retrieve", None)
- elif "retrieve" in section:
- section.pop("retrieve", None)
-
- prune_internal_keys()
_merge_config_dict(section, updates)
- prune_internal_keys()
dump_yaml_round_trip(CONFIG_YAML_PATH, data)
diff --git a/jiuwenswarm/common/schema/message.py b/jiuwenswarm/common/schema/message.py
index 88419a1422..0c284fb6fc 100644
--- a/jiuwenswarm/common/schema/message.py
+++ b/jiuwenswarm/common/schema/message.py
@@ -102,6 +102,7 @@ class ReqMethod(Enum):
SKILLS_TEAMSKILLS_HUB_DELETE = "skills.teamskillshub.delete"
SKILLS_RETRIEVAL_STATUS = "skills.retrieval.status"
SKILLS_RETRIEVAL_INDEX_BUILD = "skills.retrieval.index_build"
+ SKILLS_RETRIEVAL_INDEX_CANCEL = "skills.retrieval.index_cancel"
SKILLS_RETRIEVAL_SEARCH = "skills.retrieval.search"
SKILLS_RETRIEVAL_TREE = "skills.retrieval.tree"
SKILLS_EVOLUTION_STATUS = "skills.evolution.status"
diff --git a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
index bdddf7e1dc..688b8b5b9a 100644
--- a/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
+++ b/jiuwenswarm/gateway/channel_manager/web/app_web_handlers.py
@@ -258,6 +258,7 @@ _FORWARD_REQ_METHODS = frozenset({
"skills.teamskillshub.delete",
"skills.retrieval.status",
"skills.retrieval.index_build",
+ "skills.retrieval.index_cancel",
"skills.retrieval.search",
"skills.retrieval.tree",
"skills.evolution.status",
@@ -343,6 +344,7 @@ _FORWARD_NO_LOCAL_HANDLER_METHODS = frozenset({
"skills.teamskillshub.delete",
"skills.retrieval.status",
"skills.retrieval.index_build",
+ "skills.retrieval.index_cancel",
"skills.retrieval.search",
"skills.retrieval.tree",
"skills.evolution.status",
@@ -458,6 +460,7 @@ _SKILL_RETRIEVAL_CONFIG_SPECS: dict[str, tuple[tuple[str, ...], str, Any]] = {
"skill_retrieval_build_max_workers": (("build", "max_workers"), "int", 2),
"skill_retrieval_build_max_retries": (("build", "max_retries"), "non_negative_int", 2),
"skill_retrieval_build_request_timeout_seconds": (("build", "request_timeout_seconds"), "float", 420.0),
+ "skill_retrieval_build_total_timeout_seconds": (("build", "total_timeout_seconds"), "float", 0.0),
"skill_retrieval_build_classification_batch_limit": (("build", "classification_batch_limit"), "int", 32),
"skill_retrieval_build_discovery_seed": (("build", "discovery_seed"), "raw_int", 42),
"skill_retrieval_build_postprocess_enabled": (("build", "postprocess_enabled"), "bool", True),
@@ -466,7 +469,7 @@ _SKILL_RETRIEVAL_CONFIG_SPECS: dict[str, tuple[tuple[str, ...], str, Any]] = {
"skill_retrieval_build_equivalence_enabled": (("build", "equivalence_enabled"), "bool", True),
"skill_retrieval_retrieve_compact_codes_enabled": (("retrieve", "compact_codes_enabled"), "bool", False),
"skill_retrieval_retrieve_flatten_tree": (("retrieve", "flatten_tree"), "bool", False),
- "skill_retrieval_retrieve_max_exposure_depth": (("retrieve", "max_exposure_depth"), "int", 99),
+ "skill_retrieval_retrieve_max_exposure_depth": (("retrieve", "max_exposure_depth"), "int", 1),
}
_SKILL_RETRIEVAL_CONFIG_KEYS = tuple(_SKILL_RETRIEVAL_CONFIG_SPECS.keys())
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index f1f1a2a99c..41b3757241 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -62,7 +62,7 @@ symphony:
retrieve:
compact_codes_enabled: false
flatten_tree: false
- max_exposure_depth: 99
+ max_exposure_depth: 1
# 日志目录:~/.jiuwenswarm/agent/.logs/
# gateway.log / channel.log / agent_server.log 按源码路径分流;full.log 为汇总。
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.py
index 59135e3290..4fb872832b 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py
@@ -142,6 +142,7 @@ _SKILL_ROUTES: dict[ReqMethod, str] = {
ReqMethod.SKILLS_TEAMSKILLS_HUB_DELETE: "handle_skills_team_skills_hub_delete",
ReqMethod.SKILLS_RETRIEVAL_STATUS: "handle_skills_retrieval_status",
ReqMethod.SKILLS_RETRIEVAL_INDEX_BUILD: "handle_skills_retrieval_index_build",
+ ReqMethod.SKILLS_RETRIEVAL_INDEX_CANCEL: "handle_skills_retrieval_index_cancel",
ReqMethod.SKILLS_RETRIEVAL_SEARCH: "handle_skills_retrieval_search",
ReqMethod.SKILLS_RETRIEVAL_TREE: "handle_skills_retrieval_tree",
ReqMethod.SKILLS_EVOLUTION_STATUS: "handle_skills_evolution_status",
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
index 6aa910900a..abe8559b1f 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
@@ -1291,7 +1291,10 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
logger.info("[JiuwenClawCodeAdapter] SkillRetrievalToolkit skipped: disabled")
return None
try:
- skill_retrieval_toolkit = SkillRetrievalToolkit(manager=self._skill_manager)
+ skill_retrieval_toolkit = SkillRetrievalToolkit(
+ manager=self._skill_manager,
+ visible_skill_names=self._visible_skill_names_for_list_skill,
+ )
logger.info(
"[JiuwenClawCodeAdapter] SkillRetrievalToolkit built: tools=%s",
[t.card.name for t in skill_retrieval_toolkit.get_tools()],
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 5ce3c97951..89eeed1d2c 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -1886,6 +1886,27 @@ class JiuWenSwarmDeepAdapter:
)
return SkillUseRail.SKILL_MODE_ALL
+ def _visible_skill_names_for_list_skill(self) -> set[str]:
+ """Return the skill names exposed by the matching SkillUseRail setup."""
+ skills_dir = get_agent_skills_dir()
+ disabled_skills = set(
+ self._skill_manager.list_execution_disabled_skills()
+ if self._skill_manager is not None
+ else []
+ )
+ visible: set[str] = set()
+ try:
+ for child in sorted(skills_dir.iterdir(), key=lambda path: path.name.lower()):
+ if not child.is_dir() or child.name.startswith("_") or child.name.startswith("."):
+ continue
+ if child.name in disabled_skills:
+ continue
+ if (child / "SKILL.md").is_file():
+ visible.add(child.name)
+ except OSError as exc:
+ logger.warning("[JiuWenSwarmDeepAdapter] failed to scan visible skills: %s", exc)
+ return visible
+
@staticmethod
def _build_response_prompt_rail() -> ResponsePromptRail | None:
"""Build ResponsePromptRail so message rules keep priority ordering."""
@@ -2466,7 +2487,10 @@ class JiuWenSwarmDeepAdapter:
if not is_skill_retrieval_enabled():
return None
try:
- return SkillRetrievalPromptRail(manager=self._skill_manager)
+ return SkillRetrievalPromptRail(
+ manager=self._skill_manager,
+ visible_skill_names=self._visible_skill_names_for_list_skill,
+ )
except Exception as exc:
logger.warning("[JiuWenClawDeepAdapter] SkillRetrievalPromptRail create failed: %s", exc)
return None
@@ -2878,7 +2902,10 @@ class JiuWenSwarmDeepAdapter:
if is_skill_retrieval_enabled():
try:
- skill_retrieval_toolkit = SkillRetrievalToolkit(manager=self._skill_manager)
+ skill_retrieval_toolkit = SkillRetrievalToolkit(
+ manager=self._skill_manager,
+ visible_skill_names=self._visible_skill_names_for_list_skill,
+ )
skill_retrieval_tool_names: list[str] = []
for tool in skill_retrieval_toolkit.get_tools():
if not Runner.resource_mgr.get_tool(tool.card.id):
@@ -5799,18 +5826,6 @@ class JiuWenSwarmDeepAdapter:
raw_output = result_info.get("raw_output")
if raw_output is None:
raw_output = result_info.get("rawOutput")
- if raw_output is None and "skill_tree" in result_info:
- raw_output = {}
- for key, value in result_info.items():
- if key not in ("tool_name", "name", "tool_call_id", "toolCallId"):
- raw_output[key] = value
- result_value = result_info.get("result")
- if (
- raw_output is None
- and isinstance(result_value, dict)
- and "skill_tree" in result_value
- ):
- raw_output = result_value
if raw_output is not None:
result_payload["raw_output"] = raw_output
for key in (
diff --git a/jiuwenswarm/server/runtime/skill/skill_manager.py b/jiuwenswarm/server/runtime/skill/skill_manager.py
index 39d90d2177..426d5914a4 100644
--- a/jiuwenswarm/server/runtime/skill/skill_manager.py
+++ b/jiuwenswarm/server/runtime/skill/skill_manager.py
@@ -545,7 +545,16 @@ class SkillManager:
"""构建或复用本地 skill retrieval 索引."""
from jiuwenswarm.symphony.skill_retrieval import build_skill_index
- return await asyncio.to_thread(build_skill_index, self)
+ params = params or {}
+ force = bool(params.get("force", False))
+ source = str(params.get("source") or "web").strip() or "web"
+ return await asyncio.to_thread(build_skill_index, self, force=force, source=source)
+
+ async def handle_skills_retrieval_index_cancel(self, params: dict) -> dict:
+ """请求暂停/取消本地 skill retrieval 索引构建."""
+ from jiuwenswarm.symphony.skill_retrieval import cancel_skill_index_build
+
+ return await asyncio.to_thread(cancel_skill_index_build, self)
async def handle_skills_retrieval_search(self, params: dict) -> dict:
"""基于本地索引检索已安装 skills."""
@@ -558,7 +567,8 @@ class SkillManager:
"""返回本地 skill retrieval 树索引概览."""
from jiuwenswarm.symphony.skill_retrieval import get_skill_retrieval_tree
- return await asyncio.to_thread(get_skill_retrieval_tree, self)
+ language = str((params or {}).get("language") or "cn").strip() or "cn"
+ return await asyncio.to_thread(get_skill_retrieval_tree, self, language=language)
async def handle_skills_evolution_status(self, params: dict) -> dict:
"""检查某个 skill 是否存在 evolutions.json."""
diff --git a/jiuwenswarm/server/utils/stream_utils.py b/jiuwenswarm/server/utils/stream_utils.py
index a570b74947..b7a989f935 100644
--- a/jiuwenswarm/server/utils/stream_utils.py
+++ b/jiuwenswarm/server/utils/stream_utils.py
@@ -272,18 +272,6 @@ def _parse_typed_chunk(chunk: Any, _has_streamed_content: bool) -> dict[str, Any
raw_output = result_info.get("raw_output")
if raw_output is None:
raw_output = result_info.get("rawOutput")
- if raw_output is None and "skill_tree" in result_info:
- raw_output = {}
- for key, value in result_info.items():
- if key not in ("tool_name", "name", "tool_call_id", "toolCallId"):
- raw_output[key] = value
- result_value = result_info.get("result")
- if (
- raw_output is None
- and isinstance(result_value, dict)
- and "skill_tree" in result_value
- ):
- raw_output = result_value
if raw_output is not None:
result_payload["raw_output"] = raw_output
for key in (
diff --git a/jiuwenswarm/symphony/agent/__init__.py b/jiuwenswarm/symphony/agent/__init__.py
index 764b318d44..461563112e 100644
--- a/jiuwenswarm/symphony/agent/__init__.py
+++ b/jiuwenswarm/symphony/agent/__init__.py
@@ -7,15 +7,23 @@ from .agentic_retrieval_toolkit import (
build_skill_index,
is_agentic_retrieval_enabled,
render_skill_retrieval_prompt,
+ render_skill_retrieval_prompt_for_visible_skills,
skill_branch_explore,
+ skill_branch_explore_for_visible_skills,
skill_branch_peek,
+ skill_branch_peek_for_visible_skills,
)
+from .tool_result import AgenticToolResult
__all__ = [
"AgenticRetrievalToolKit",
+ "AgenticToolResult",
"build_skill_index",
"is_agentic_retrieval_enabled",
"render_skill_retrieval_prompt",
+ "render_skill_retrieval_prompt_for_visible_skills",
"skill_branch_explore",
+ "skill_branch_explore_for_visible_skills",
"skill_branch_peek",
+ "skill_branch_peek_for_visible_skills",
]
diff --git a/jiuwenswarm/symphony/agent/agentic_retrieval_toolkit.py b/jiuwenswarm/symphony/agent/agentic_retrieval_toolkit.py
index 29d90c8710..807e21e268 100644
--- a/jiuwenswarm/symphony/agent/agentic_retrieval_toolkit.py
+++ b/jiuwenswarm/symphony/agent/agentic_retrieval_toolkit.py
@@ -19,6 +19,9 @@ from jiuwenswarm.symphony.skill_retrieval.config import RetrieveSettings, load_s
from jiuwenswarm.symphony.skill_retrieval.dispatch_imports import dispatch_import_path
from jiuwenswarm.symphony.skill_retrieval.index_service import SkillIndexService
from jiuwenswarm.symphony.skill_retrieval.markdown import render_disabled
+from jiuwenswarm.symphony.skill_retrieval.api import build_skill_index as start_background_skill_index_build
+
+from .tool_result import AgenticToolResult
@dataclass(frozen=True)
@@ -94,11 +97,13 @@ class AgenticRetrievalToolKit:
loaded_index: Any,
progressive_config: Any,
top_k: int,
+ visible_skill_names: set[str] | frozenset[str] | None = None,
) -> None:
self._loaded_index = loaded_index
self._root = loaded_index.tree_root
self._progressive_config = progressive_config
self._top_k = max(1, int(top_k))
+ self._visible_skill_names = _normalize_visible_skill_names(visible_skill_names)
self._node_by_id: dict[str, Any] = {}
self._path_by_id: dict[str, tuple[str, ...]] = {}
self._stats_by_id: dict[str, _NodeStats] = {}
@@ -108,13 +113,12 @@ class AgenticRetrievalToolKit:
payload = str(getattr(record, "payload", "") or "").strip()
if payload:
self._catalog_by_payload[payload] = record
- self._leaf_ids.add(payload)
worker_id = str(getattr(record, "worker_id", "") or "").strip()
- if worker_id:
- self._leaf_ids.add(worker_id)
name = str(getattr(record, "name", "") or "").strip()
- if name:
- self._leaf_ids.add(name)
+ if self._is_visible_skill(payload, worker_id, name):
+ for value in (payload, worker_id, name):
+ if value:
+ self._leaf_ids.add(value)
self._index_nodes(self._root, ("ROOT",))
self._analyze_node(self._root)
@@ -124,6 +128,7 @@ class AgenticRetrievalToolKit:
index_dir: str | Path,
*,
retrieve_settings: RetrieveSettings | None = None,
+ visible_skill_names: set[str] | frozenset[str] | None = None,
) -> "AgenticRetrievalToolKit":
"""Load an existing symphony skill index from *index_dir*."""
with dispatch_import_path():
@@ -135,6 +140,7 @@ class AgenticRetrievalToolKit:
loaded_index=loaded_index,
progressive_config=progressive_config,
top_k=top_k,
+ visible_skill_names=visible_skill_names,
)
def skill_branch_peek(self, node_ids: Sequence[str]) -> dict[str, Any]:
@@ -304,7 +310,7 @@ class AgenticRetrievalToolKit:
"## 第一层分类",
]
- children = list(getattr(self._root, "children", ()) or [])
+ children = self._visible_child_branches(self._root)
if not children:
lines.append("No first-level branches are available." if language == "en" else "当前索引树没有第一层分支。")
return "\n".join(lines)
@@ -342,7 +348,12 @@ class AgenticRetrievalToolKit:
else:
missing.append(node_id)
else:
- nodes.append(node)
+ if node_id == "ROOT" and default_root:
+ nodes.append(node)
+ elif self._analyze_node(node).skill_count > 0:
+ nodes.append(node)
+ else:
+ missing.append(node_id)
if leaf_ids:
return [], (
@@ -377,18 +388,68 @@ class AgenticRetrievalToolKit:
for item in items:
for attr_name in ("payload", "item_id", "label"):
value = str(getattr(item, attr_name, "") or "").strip()
- if value:
+ if value and self._is_visible_item(item):
self._leaf_ids.add(value)
- branch_count = 1
- skill_count = len(items)
+ skill_count = sum(1 for item in items if self._is_visible_item(item))
+ child_branch_count = 0
for child in tuple(getattr(node, "children", ()) or ()):
child_stats = self._analyze_node(child)
- branch_count += child_stats.branch_count
- skill_count += child_stats.skill_count
+ if child_stats.skill_count > 0:
+ child_branch_count += child_stats.branch_count
+ skill_count += child_stats.skill_count
+ branch_count = 1 + child_branch_count if skill_count > 0 else 0
stats = _NodeStats(branch_count=branch_count, skill_count=skill_count)
self._stats_by_id[node_id] = stats
return stats
+ def _visible_child_branches(self, node: Any) -> list[Any]:
+ return [
+ child
+ for child in list(getattr(node, "children", ()) or [])
+ if self._analyze_node(child).skill_count > 0
+ ]
+
+ def _is_visible_item(self, item: Any) -> bool:
+ return self._is_visible_skill(
+ str(getattr(item, "payload", "") or "").strip(),
+ str(getattr(item, "item_id", "") or "").strip(),
+ str(getattr(item, "label", "") or "").strip(),
+ )
+
+ def _is_visible_resolution(self, resolution: Any | None) -> bool:
+ if resolution is None:
+ return False
+ item = getattr(resolution, "item", None)
+ record = None
+ payload = ""
+ if item is not None:
+ payload = str(getattr(item, "payload", "") or "").strip()
+ record = self._catalog_by_payload.get(payload)
+ worker_id = str(getattr(record, "worker_id", "") if record is not None else "").strip()
+ name = str(getattr(record, "name", "") if record is not None else "").strip()
+ return self._is_visible_skill(
+ payload,
+ worker_id,
+ name,
+ str(getattr(item, "item_id", "") if item is not None else "").strip(),
+ str(getattr(item, "label", "") if item is not None else "").strip(),
+ str(getattr(resolution, "canonical_id", "") or "").strip(),
+ str(getattr(resolution, "label", "") or "").strip(),
+ )
+
+ def _is_visible_skill(self, *values: str) -> bool:
+ visible = self._visible_skill_names
+ if visible is None:
+ return True
+ return any(str(value or "").strip() in visible for value in values)
+
+ def _is_visible_exposed_branch(self, node: Any, resolution: Any | None) -> bool:
+ node_id = _exposed_node_id(node, resolution)
+ indexed_node = self._node_by_id.get(node_id)
+ if indexed_node is None:
+ return True
+ return self._analyze_node(indexed_node).skill_count > 0
+
def _render_peek_node(self, lines: list[str], node: Any) -> None:
node_id = str(getattr(node, "node_id", "") or "ROOT").strip() or "ROOT"
parts = _split_description(str(getattr(node, "description", "") or ""))
@@ -398,7 +459,7 @@ class AgenticRetrievalToolKit:
if parts.dont_select_when:
lines.append(f"avoid: {_compact(parts.dont_select_when, 180)}")
- children = list(getattr(node, "children", ()) or [])
+ children = self._visible_child_branches(node)
if not children:
lines.append("No child branches.")
return
@@ -451,8 +512,20 @@ class AgenticRetrievalToolKit:
children,
resolution_by_canonical_id,
)
+ terminal_children = [
+ child
+ for child in terminal_children
+ if self._is_visible_resolution(_resolution_for_exposed(child, resolution_by_canonical_id))
+ ]
+ branch_children = [
+ child
+ for child in branch_children
+ if self._is_visible_exposed_branch(child, _resolution_for_exposed(child, resolution_by_canonical_id))
+ ]
+ rendered = False
if terminal_children:
+ rendered = True
lines.append("")
lines.append("### skills")
lines.append(
@@ -467,6 +540,7 @@ class AgenticRetrievalToolKit:
self._render_terminal_skill(lines, index=index, resolution=resolution)
for child in branch_children:
+ rendered = True
resolution = _resolution_for_exposed(child, resolution_by_canonical_id)
node_id = _exposed_node_id(child, resolution)
description = (
@@ -482,6 +556,8 @@ class AgenticRetrievalToolKit:
lines.append(f"use: {_compact(parts.select_when, 180)}")
if parts.dont_select_when:
lines.append(f"avoid: {_compact(parts.dont_select_when, 180)}")
+ if not rendered:
+ lines.append("No exposed branches or visible skills.")
def _render_terminal_skill(self, lines: list[str], *, index: int, resolution: Any) -> None:
entry = self._skill_entry_from_resolution(resolution)
@@ -499,7 +575,7 @@ class AgenticRetrievalToolKit:
def _skill_tree_peek_step(self, *, order: int, node: Any) -> dict[str, Any]:
node_id = str(getattr(node, "node_id", "") or "ROOT").strip() or "ROOT"
- children = tuple(getattr(node, "children", ()) or ())
+ children = tuple(self._visible_child_branches(node))
return {
"order": order,
"event_type": "fragment_built",
@@ -532,6 +608,16 @@ class AgenticRetrievalToolKit:
children,
resolution_by_canonical_id,
)
+ terminal_children = [
+ child
+ for child in terminal_children
+ if self._is_visible_resolution(_resolution_for_exposed(child, resolution_by_canonical_id))
+ ]
+ branch_children = [
+ child
+ for child in branch_children
+ if self._is_visible_exposed_branch(child, _resolution_for_exposed(child, resolution_by_canonical_id))
+ ]
branch_ids = [
_named_id(_exposed_node_id(child, _resolution_for_exposed(child, resolution_by_canonical_id)))
for child in branch_children
@@ -657,10 +743,10 @@ class AgenticRetrievalToolKit:
def build_skill_index(manager: Any | None = None) -> dict[str, Any]:
- """Build or reuse the installed-skill retrieval index."""
+ """Start a background build or reuse request for the installed-skill retrieval index."""
resolved_manager = _resolve_manager(manager)
_clear_runtime_caches()
- payload = SkillIndexService(resolved_manager).build_index()
+ payload = start_background_skill_index_build(resolved_manager, force=False, source="tool")
_clear_runtime_caches()
return _tool_payload(
bool(payload.get("success")),
@@ -678,30 +764,66 @@ def is_agentic_retrieval_enabled() -> bool:
def skill_branch_peek(node_ids: Sequence[str], manager: Any | None = None) -> dict[str, Any]:
"""Peek child branch summaries from the current skill tree index."""
+ return skill_branch_peek_for_visible_skills(node_ids, manager=manager, visible_skill_names=None)
+
+
+def skill_branch_peek_for_visible_skills(
+ node_ids: Sequence[str],
+ manager: Any | None = None,
+ *,
+ visible_skill_names: set[str] | frozenset[str] | None = None,
+) -> dict[str, Any]:
+ """Peek child branch summaries within the caller-visible skill set."""
status, settings, _ = _ready_status(manager)
if not status.get("success"):
return _tool_payload(False, str(status.get("result") or ""))
toolkit = _cached_toolkit(
str(status["index_dir"]),
retrieve_settings=settings.retrieve,
+ visible_skill_names=visible_skill_names,
)
return toolkit.skill_branch_peek(node_ids)
def skill_branch_explore(node_ids: Sequence[str], manager: Any | None = None) -> dict[str, Any]:
"""Explore branch nodes using the current disclosure settings."""
+ return skill_branch_explore_for_visible_skills(node_ids, manager=manager, visible_skill_names=None)
+
+
+def skill_branch_explore_for_visible_skills(
+ node_ids: Sequence[str],
+ manager: Any | None = None,
+ *,
+ visible_skill_names: set[str] | frozenset[str] | None = None,
+) -> dict[str, Any]:
+ """Explore branch nodes within the caller-visible skill set."""
status, settings, _ = _ready_status(manager)
if not status.get("success"):
return _tool_payload(False, str(status.get("result") or ""))
toolkit = _cached_toolkit(
str(status["index_dir"]),
retrieve_settings=settings.retrieve,
+ visible_skill_names=visible_skill_names,
)
return toolkit.skill_branch_explore(node_ids)
def render_skill_retrieval_prompt(manager: Any | None = None, *, language: str = "cn") -> str:
"""Render the prompt section used by jiuwenswarm when agentic retrieval is enabled."""
+ return render_skill_retrieval_prompt_for_visible_skills(
+ manager,
+ language=language,
+ visible_skill_names=None,
+ )
+
+
+def render_skill_retrieval_prompt_for_visible_skills(
+ manager: Any | None = None,
+ *,
+ language: str = "cn",
+ visible_skill_names: set[str] | frozenset[str] | None = None,
+) -> str:
+ """Render the agentic retrieval prompt for the caller-visible skill set."""
status, settings, _ = _ready_status(manager, allow_stale=False, prompt_mode=True)
if not status.get("enabled", False):
return ""
@@ -724,6 +846,7 @@ def render_skill_retrieval_prompt(manager: Any | None = None, *, language: str =
toolkit = _cached_toolkit(
str(status["index_dir"]),
retrieve_settings=settings.retrieve,
+ visible_skill_names=visible_skill_names,
)
return toolkit.root_prompt_markdown(language=language)
@@ -758,18 +881,25 @@ def _cached_toolkit(
index_dir: str | Path,
*,
retrieve_settings: RetrieveSettings | None,
+ visible_skill_names: set[str] | frozenset[str] | None,
) -> AgenticRetrievalToolKit:
path = Path(index_dir).expanduser().resolve()
+ visible = _normalize_visible_skill_names(visible_skill_names)
key = (
str(path),
_index_artifact_signature(path),
_retrieve_settings_signature(retrieve_settings),
+ _visible_skill_signature(visible),
)
with _CACHE_LOCK:
entry = _TOOLKIT_CACHE.get(key)
if entry is not None:
return entry.toolkit
- toolkit = AgenticRetrievalToolKit.from_index(path, retrieve_settings=retrieve_settings)
+ toolkit = AgenticRetrievalToolKit.from_index(
+ path,
+ retrieve_settings=retrieve_settings,
+ visible_skill_names=visible,
+ )
_TOOLKIT_CACHE.clear()
_TOOLKIT_CACHE[key] = _ToolkitCacheEntry(toolkit=toolkit)
return toolkit
@@ -853,6 +983,20 @@ def _retrieve_settings_signature(settings: RetrieveSettings | None) -> tuple[Any
return _settings_signature(settings or RetrieveSettings())
+def _normalize_visible_skill_names(
+ visible_skill_names: set[str] | frozenset[str] | None,
+) -> frozenset[str] | None:
+ if visible_skill_names is None:
+ return None
+ return frozenset(str(name or "").strip() for name in visible_skill_names if str(name or "").strip())
+
+
+def _visible_skill_signature(visible_skill_names: frozenset[str] | None) -> tuple[str, ...] | None:
+ if visible_skill_names is None:
+ return None
+ return tuple(sorted(visible_skill_names))
+
+
def _settings_signature(settings: Any) -> tuple[tuple[str, str], ...]:
try:
payload = asdict(settings)
@@ -942,8 +1086,10 @@ def _tool_payload(
) -> dict[str, Any]:
payload: dict[str, Any] = {"success": bool(success), "result": str(result or "")}
if skill_tree is not None:
- payload["skill_tree"] = skill_tree
- return payload
+ detailed_output = dict(payload)
+ detailed_output["skill_tree"] = skill_tree
+ return AgenticToolResult(payload, detailed_output=detailed_output)
+ return AgenticToolResult(payload)
def _agentic_build_result(result: str) -> str:
diff --git a/jiuwenswarm/symphony/agent/tool_result.py b/jiuwenswarm/symphony/agent/tool_result.py
new file mode 100644
index 0000000000..cd32d93c90
--- /dev/null
+++ b/jiuwenswarm/symphony/agent/tool_result.py
@@ -0,0 +1,16 @@
+from __future__ import annotations
+
+from typing import Any
+
+
+class AgenticToolResult(dict[str, Any]):
+ """LLM-facing dict result with optional full output for frontend rendering."""
+
+ def __init__(
+ self,
+ llm_payload: dict[str, Any],
+ *,
+ detailed_output: Any | None = None,
+ ) -> None:
+ super().__init__(llm_payload)
+ self.detailed_output = detailed_output
diff --git a/jiuwenswarm/symphony/indexing/tree/llm_runtime.py b/jiuwenswarm/symphony/indexing/tree/llm_runtime.py
index 805b2879d3..f8f9d5cc86 100644
--- a/jiuwenswarm/symphony/indexing/tree/llm_runtime.py
+++ b/jiuwenswarm/symphony/indexing/tree/llm_runtime.py
@@ -208,6 +208,7 @@ class TreeLLMRuntime:
messages=[{"role": "user", "content": prompt}],
max_tokens=max_tokens,
timeout=mcfg.build.timeout,
+ stream=False,
extra_body=self.merged_extra_body(),
)
finish_reason = response.choices[0].finish_reason
diff --git a/jiuwenswarm/symphony/skill_retrieval/__init__.py b/jiuwenswarm/symphony/skill_retrieval/__init__.py
index 3e0ea12109..9e10eb4962 100644
--- a/jiuwenswarm/symphony/skill_retrieval/__init__.py
+++ b/jiuwenswarm/symphony/skill_retrieval/__init__.py
@@ -1,9 +1,16 @@
"""JiuwenSwarm adapters for dispatch-based installed-skill retrieval."""
-from .api import build_skill_index, get_skill_retrieval_status, get_skill_retrieval_tree, retrieve_skills
+from .api import (
+ build_skill_index,
+ cancel_skill_index_build,
+ get_skill_retrieval_status,
+ get_skill_retrieval_tree,
+ retrieve_skills,
+)
__all__ = [
"build_skill_index",
+ "cancel_skill_index_build",
"get_skill_retrieval_status",
"get_skill_retrieval_tree",
"retrieve_skills",
diff --git a/jiuwenswarm/symphony/skill_retrieval/api.py b/jiuwenswarm/symphony/skill_retrieval/api.py
index f338036da2..2d56699962 100644
--- a/jiuwenswarm/symphony/skill_retrieval/api.py
+++ b/jiuwenswarm/symphony/skill_retrieval/api.py
@@ -3,13 +3,28 @@ from __future__ import annotations
from typing import Any
-def build_skill_index(manager: Any | None = None) -> dict[str, Any]:
+def build_skill_index(
+ manager: Any | None = None,
+ *,
+ force: bool = False,
+ source: str = "tool",
+) -> dict[str, Any]:
from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
- from .index_service import SkillIndexService
+ from .build_coordinator import start_skill_index_build
+
+ resolved_manager = manager or SkillManager()
+ payload = start_skill_index_build(resolved_manager, force=force, source=source)
+ return _tool_payload(payload)
+
+
+def cancel_skill_index_build(manager: Any | None = None) -> dict[str, Any]:
+ from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
+
+ from .build_coordinator import cancel_skill_index_build as cancel_build
resolved_manager = manager or SkillManager()
- payload = SkillIndexService(resolved_manager).build_index()
+ payload = cancel_build(resolved_manager)
return _tool_payload(payload)
@@ -32,13 +47,13 @@ def get_skill_retrieval_status(manager: Any | None = None) -> dict[str, Any]:
return SkillIndexService(resolved_manager).status()
-def get_skill_retrieval_tree(manager: Any | None = None) -> dict[str, Any]:
+def get_skill_retrieval_tree(manager: Any | None = None, *, language: str = "cn") -> dict[str, Any]:
from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
from .index_service import SkillIndexService
resolved_manager = manager or SkillManager()
- return SkillIndexService(resolved_manager).tree()
+ return SkillIndexService(resolved_manager).tree(language=language)
def _tool_payload(payload: dict[str, Any]) -> dict[str, Any]:
diff --git a/jiuwenswarm/symphony/skill_retrieval/build_coordinator.py b/jiuwenswarm/symphony/skill_retrieval/build_coordinator.py
new file mode 100644
index 0000000000..dbc70d5fae
--- /dev/null
+++ b/jiuwenswarm/symphony/skill_retrieval/build_coordinator.py
@@ -0,0 +1,112 @@
+from __future__ import annotations
+
+import threading
+from dataclasses import dataclass
+from typing import Any
+
+from .config import load_settings
+from .index_service import SkillIndexService
+
+
+@dataclass
+class _BuildTask:
+ thread: threading.Thread
+ cancel_event: threading.Event
+ force: bool
+ source: str
+
+
+_TASKS: dict[str, _BuildTask] = {}
+_LOCK = threading.RLock()
+
+
+def start_skill_index_build(
+ manager: Any,
+ *,
+ force: bool = False,
+ source: str = "manual",
+) -> dict[str, Any]:
+ settings = load_settings()
+ key = str(settings.artifact_root)
+ service = SkillIndexService(manager)
+ if not settings.enabled:
+ return {"success": False, "result": service.build_index(force=force, source=source).get("result", "")}
+
+ with _LOCK:
+ existing = _TASKS.get(key)
+ if existing is not None and existing.thread.is_alive():
+ return {
+ "success": True,
+ "background": True,
+ "build_status": "running",
+ "result": (
+ "# Skill Index Build\n\n"
+ "A skill index build is already running in the background. "
+ "Open the Skill Index tab to watch progress."
+ ),
+ }
+ if existing is not None:
+ _TASKS.pop(key, None)
+
+ cancel_event = threading.Event()
+ service.mark_background_started(source=source)
+ thread = threading.Thread(
+ target=_run_build,
+ args=(manager, key, force, source, cancel_event),
+ name="skill-index-build",
+ daemon=True,
+ )
+ _TASKS[key] = _BuildTask(thread=thread, cancel_event=cancel_event, force=force, source=source)
+ thread.start()
+
+ return {
+ "success": True,
+ "background": True,
+ "build_status": "running",
+ "result": (
+ "# Skill Index Build\n\n"
+ "Skill index build started in the background. "
+ "Open the Skill Index tab to watch progress."
+ ),
+ }
+
+
+def cancel_skill_index_build(manager: Any) -> dict[str, Any]:
+ settings = load_settings()
+ key = str(settings.artifact_root)
+ with _LOCK:
+ task = _TASKS.get(key)
+ if task is not None and task.thread.is_alive():
+ task.cancel_event.set()
+ SkillIndexService(manager).request_cancel()
+ return {
+ "success": True,
+ "build_status": "cancel_requested",
+ "result": "# Skill Index Build\n\nCancellation requested.",
+ }
+
+ return {
+ "success": False,
+ "build_status": "idle",
+ "result": "# Skill Index Build\n\nNo running skill index build was found.",
+ }
+
+
+def _run_build(
+ manager: Any,
+ key: str,
+ force: bool,
+ source: str,
+ cancel_event: threading.Event,
+) -> None:
+ try:
+ SkillIndexService(manager).build_index(
+ force=force,
+ source=source,
+ cancel_check=cancel_event.is_set,
+ )
+ finally:
+ with _LOCK:
+ task = _TASKS.get(key)
+ if task is not None and task.cancel_event is cancel_event:
+ _TASKS.pop(key, None)
diff --git a/jiuwenswarm/symphony/skill_retrieval/config.py b/jiuwenswarm/symphony/skill_retrieval/config.py
index de81617217..2fb82769fc 100644
--- a/jiuwenswarm/symphony/skill_retrieval/config.py
+++ b/jiuwenswarm/symphony/skill_retrieval/config.py
@@ -26,6 +26,7 @@ class BuildSettings:
max_workers: int = 2
max_retries: int = 2
request_timeout_seconds: float = 420.0
+ total_timeout_seconds: float = 0.0
classification_batch_limit: int = 32
discovery_seed: int = 42
postprocess_enabled: bool = True
@@ -39,7 +40,7 @@ class RetrieveSettings:
top_k: int = 10
compact_codes_enabled: bool = False
flatten_tree: bool = False
- max_exposure_depth: int = 99
+ max_exposure_depth: int = 1
max_branch_choices: int = 2
max_parallel_branches: int = 2
max_tokens: int = 96
@@ -140,6 +141,7 @@ def _load_build(raw: dict[str, Any]) -> BuildSettings:
max_workers=_as_int(raw.get("max_workers"), 2),
max_retries=_as_non_negative_int(raw.get("max_retries"), 2),
request_timeout_seconds=_as_float(raw.get("request_timeout_seconds"), 420.0),
+ total_timeout_seconds=_as_float(raw.get("total_timeout_seconds"), 0.0),
classification_batch_limit=_as_int(raw.get("classification_batch_limit"), 32),
discovery_seed=_as_raw_int(raw.get("discovery_seed"), 42),
postprocess_enabled=_as_bool(raw.get("postprocess_enabled"), True),
@@ -154,7 +156,7 @@ def _load_retrieve(raw: dict[str, Any]) -> RetrieveSettings:
top_k=_as_int(raw.get("top_k"), 10),
compact_codes_enabled=_as_bool(raw.get("compact_codes_enabled"), False),
flatten_tree=_as_bool(raw.get("flatten_tree"), False),
- max_exposure_depth=_as_int(raw.get("max_exposure_depth"), 99),
+ max_exposure_depth=_as_int(raw.get("max_exposure_depth"), 1),
)
diff --git a/jiuwenswarm/symphony/skill_retrieval/index_service.py b/jiuwenswarm/symphony/skill_retrieval/index_service.py
index e69c0b3c9a..a3d89f2267 100644
--- a/jiuwenswarm/symphony/skill_retrieval/index_service.py
+++ b/jiuwenswarm/symphony/skill_retrieval/index_service.py
@@ -4,6 +4,7 @@ import json
import logging
import shutil
import time
+from contextlib import contextmanager, redirect_stderr, redirect_stdout
from dataclasses import asdict
from datetime import datetime, timezone
from pathlib import Path
@@ -21,6 +22,15 @@ CATALOG_FILENAME = "catalog.jsonl"
MANIFEST_FILENAME = "manifest.json"
STATE_FILENAME = "state.json"
LOGGER = logging.getLogger(__name__)
+BUILD_LOG_LIMIT = 40
+
+
+class SkillIndexBuildCancelled(RuntimeError):
+ pass
+
+
+class SkillIndexBuildTimeout(RuntimeError):
+ pass
class SkillIndexService:
@@ -34,68 +44,146 @@ class SkillIndexService:
state = _read_state(settings)
expected = _expected_fingerprint(inventory, settings)
complete = _is_complete_index(index_dir)
- fresh = complete and state.get("fingerprint") == expected
+ manifest_matches = complete and _manifest_matches_inventory(index_dir, inventory)
+ fresh = complete and manifest_matches and state.get("fingerprint") == expected
+ build_state = _build_state_from_state(state)
return {
"enabled": settings.enabled,
"artifact_root": str(settings.artifact_root),
"index_dir": str(index_dir),
"index_exists": complete,
"fresh": fresh,
+ "installed_count": inventory.count,
"installed_enabled_count": inventory.count,
- "indexed_count": int(state.get("indexed_count") or 0) if complete else 0,
+ "indexed_count": int(state.get("indexed_count") or 0) if complete and manifest_matches else 0,
"built_at": str(state.get("built_at") or ""),
"inventory_fingerprint": inventory.fingerprint,
"fingerprint": str(state.get("fingerprint") or ""),
"build_branching_factor": settings.build.branching_factor,
"build_max_depth": settings.build.max_depth,
"build_request_timeout_seconds": settings.build.request_timeout_seconds,
+ "build_total_timeout_seconds": settings.build.total_timeout_seconds,
+ "build_status": build_state.get("status", "idle"),
+ "build_stage": build_state.get("stage", ""),
+ "build_message": build_state.get("message", ""),
+ "build_error": build_state.get("error", ""),
+ "build_progress": build_state.get("progress", 0.0),
+ "build_started_at": build_state.get("started_at", ""),
+ "build_finished_at": build_state.get("finished_at", ""),
+ "build_elapsed_seconds": build_state.get("elapsed_seconds", 0.0),
+ "build_cancel_requested": bool(build_state.get("cancel_requested", False)),
+ "build_logs": build_state.get("logs", []),
"retrieval_top_k": settings.retrieve.top_k,
"retrieval_compact_codes_enabled": settings.retrieve.compact_codes_enabled,
"retrieval_flatten_tree": settings.retrieve.flatten_tree,
"retrieval_max_exposure_depth": settings.retrieve.max_exposure_depth,
}
- def build_index(self) -> dict[str, Any]:
+ def build_index(
+ self,
+ *,
+ force: bool = False,
+ cancel_check: Any | None = None,
+ source: str = "manual",
+ ) -> dict[str, Any]:
started = time.monotonic()
settings = load_settings()
if not settings.enabled:
return {"success": False, "result": render_disabled()}
+ _write_build_state(
+ settings,
+ status="running",
+ stage="scan",
+ message=f"Scanning installed skills ({source}).",
+ progress=0.05,
+ started_at=_now_iso(),
+ clear_error=True,
+ )
+ self._check_cancel_or_timeout(settings, started, cancel_check, stage="scan")
inventory = scan_skill_inventory(self._manager)
if inventory.count == 0:
_cleanup_index(settings)
+ _write_build_state(
+ settings,
+ status="failed",
+ stage="scan",
+ message="No installed skills were found.",
+ error="No installed skills were found under the agent skills directory.",
+ progress=1.0,
+ finished_at=_now_iso(),
+ elapsed_seconds=time.monotonic() - started,
+ )
return {
"success": False,
"result": render_build_failure(
- "No enabled installed skills were found under the agent skills directory."
+ "No installed skills were found under the agent skills directory."
),
}
settings.artifact_root.mkdir(parents=True, exist_ok=True)
_tmp_dir(settings).mkdir(parents=True, exist_ok=True)
expected = _expected_fingerprint(inventory, settings)
+ state = _read_state(settings)
- recovered = self._recover_index(settings=settings, inventory=inventory, expected_fingerprint=expected)
+ recovered = False
+ if not force:
+ recovered = self._recover_index(
+ settings=settings,
+ inventory=inventory,
+ expected_fingerprint=expected,
+ )
state = _read_state(settings)
- if _is_complete_index(_index_dir(settings)) and state.get("fingerprint") == expected:
+ index_dir = _index_dir(settings)
+ index_complete = _is_complete_index(index_dir)
+ manifest_matches = index_complete and _manifest_matches_inventory(index_dir, inventory)
+ fingerprint_matches = state.get("fingerprint") == expected
+ fresh_index_available = index_complete and manifest_matches and fingerprint_matches
+ if not force and fresh_index_available:
+ _write_build_state(
+ settings,
+ status="success",
+ stage="reuse",
+ message="Existing index is fresh; reused without rebuilding.",
+ progress=1.0,
+ finished_at=_now_iso(),
+ elapsed_seconds=time.monotonic() - started,
+ inventory=inventory,
+ fingerprint=expected,
+ )
return {
"success": True,
"result": render_build_success(
reused=True,
inventory=inventory,
- index_dir=str(_index_dir(settings)),
+ index_dir=str(index_dir),
elapsed_seconds=time.monotonic() - started,
),
"recovered": recovered,
}
if not settings.llm.model or not settings.llm.api_key:
+ if _is_stale_index(settings, inventory, expected):
+ _cleanup_index(settings)
+ error = (
+ "Offline dispatch tree build requires a model and API key. "
+ "Configure `models.defaults[0].model_client_config` or `symphony.skill_retrieval.llm`."
+ )
+ _write_build_state(
+ settings,
+ status="failed",
+ stage="llm_config",
+ message="Build LLM configuration is missing.",
+ error=error,
+ progress=1.0,
+ finished_at=_now_iso(),
+ elapsed_seconds=time.monotonic() - started,
+ inventory=inventory,
+ fingerprint=expected,
+ )
return {
"success": False,
- "result": render_build_failure(
- "Offline dispatch tree build requires a model and API key. "
- "Configure `models.defaults[0].model_client_config` or `symphony.skill_retrieval.llm`."
- ),
+ "result": render_build_failure(error),
}
build_root = (
@@ -104,18 +192,98 @@ class SkillIndexService:
build_index_dir = build_root / "index"
try:
build_index_dir.mkdir(parents=True, exist_ok=True)
- if _is_complete_index(_index_dir(settings)) and state.get("fingerprint") != expected:
- logging.info("execute incremental build")
- self.incremental_build(settings=settings, inventory=inventory, output_dir=build_index_dir)
+ self._check_cancel_or_timeout(settings, started, cancel_check, stage="build")
+ _write_build_state(
+ settings,
+ status="running",
+ stage="build",
+ message="Building dispatch skill tree index.",
+ progress=0.35,
+ inventory=inventory,
+ fingerprint=expected,
+ )
+ if force:
+ LOGGER.info("[skill-index] stage=build status=running detail=force_full_rebuild")
+ self._run_dispatch_build(settings=settings, inventory=inventory, output_dir=build_index_dir)
+ elif index_complete and not fingerprint_matches:
+ LOGGER.info("[skill-index] stage=build status=running detail=incremental")
+ try:
+ self.incremental_build(settings=settings, inventory=inventory, output_dir=build_index_dir)
+ except Exception as exc:
+ LOGGER.info(
+ "[skill-index] stage=build status=running "
+ "detail=incremental_failed_full_rebuild error=%s",
+ exc,
+ )
+ shutil.rmtree(build_index_dir, ignore_errors=True)
+ build_index_dir.mkdir(parents=True, exist_ok=True)
+ self._run_dispatch_build(settings=settings, inventory=inventory, output_dir=build_index_dir)
else:
- logging.info("execute full build")
+ LOGGER.info("[skill-index] stage=build status=running detail=full")
self._run_dispatch_build(settings=settings, inventory=inventory, output_dir=build_index_dir)
+ self._check_cancel_or_timeout(settings, started, cancel_check, stage="publish")
if not _is_complete_index(build_index_dir):
raise RuntimeError("dispatch build finished without complete index artifacts")
+ _write_build_state(
+ settings,
+ status="running",
+ stage="publish",
+ message="Publishing skill retrieval index.",
+ progress=0.9,
+ )
_publish_index(settings=settings, candidate_dir=build_index_dir)
- _write_state(settings, inventory=inventory, fingerprint=expected)
- except Exception as exc:
+ _write_state(
+ settings,
+ inventory=inventory,
+ fingerprint=expected,
+ elapsed_seconds=time.monotonic() - started,
+ )
+ except SkillIndexBuildCancelled as exc:
+ _write_build_state(
+ settings,
+ status="cancelled",
+ stage="cancelled",
+ message=str(exc),
+ progress=1.0,
+ finished_at=_now_iso(),
+ elapsed_seconds=time.monotonic() - started,
+ inventory=inventory,
+ fingerprint=expected,
+ )
+ return {"success": False, "result": render_build_failure(str(exc))}
+ except SkillIndexBuildTimeout as exc:
+ if _is_stale_index(settings, inventory, expected):
+ _cleanup_index(settings)
+ _write_build_state(
+ settings,
+ status="failed",
+ stage="timeout",
+ message="Skill index build timed out.",
+ error=str(exc),
+ progress=1.0,
+ finished_at=_now_iso(),
+ elapsed_seconds=time.monotonic() - started,
+ inventory=inventory,
+ fingerprint=expected,
+ )
return {"success": False, "result": render_build_failure(str(exc))}
+ except Exception as exc:
+ if _is_stale_index(settings, inventory, expected):
+ _cleanup_index(settings)
+ error = _normalize_build_error(exc)
+ _write_build_state(
+ settings,
+ status="failed",
+ stage="failed",
+ message="Skill index build failed.",
+ error=error,
+ progress=1.0,
+ finished_at=_now_iso(),
+ elapsed_seconds=time.monotonic() - started,
+ inventory=inventory,
+ fingerprint=expected,
+ )
+ return {"success": False, "result": render_build_failure(error)}
finally:
if _is_complete_index(_index_dir(settings)) and build_root.exists():
shutil.rmtree(build_root, ignore_errors=True)
@@ -130,6 +298,33 @@ class SkillIndexService:
),
}
+ @staticmethod
+ def request_cancel() -> dict[str, Any]:
+ settings = load_settings()
+ _write_build_state(
+ settings,
+ status="running",
+ stage="cancel_requested",
+ message="Cancellation requested by user.",
+ cancel_requested=True,
+ )
+ return {"success": True, "result": "# Skill Index Build\n\nCancellation requested."}
+
+ @staticmethod
+ def mark_background_started(*, source: str = "manual") -> None:
+ settings = load_settings()
+ if not settings.enabled:
+ return
+ _write_build_state(
+ settings,
+ status="running",
+ stage="queued",
+ message=f"Skill index build queued ({source}).",
+ progress=0.01,
+ started_at=_now_iso(),
+ clear_error=True,
+ )
+
def incremental_build(
self,
*,
@@ -160,42 +355,49 @@ class SkillIndexService:
add_index_path = output_dir.parent / "added-skills"
else:
add_index_path = output_dir
- IndexBuilder.add(
- item_paths=added_paths,
- base_index_dir=existing_index,
- output_dir=add_index_path,
- item_type="skill",
- config=config,
- )
+ with _suppress_dispatch_console():
+ IndexBuilder.add(
+ item_paths=added_paths,
+ base_index_dir=existing_index,
+ output_dir=add_index_path,
+ item_type="skill",
+ config=config,
+ )
if removed_paths:
source = add_index_path if added_paths else existing_index
- IndexBuilder.delete(
- item_paths=removed_paths,
- base_index_dir=source,
- output_dir=output_dir,
- item_type="skill",
- config=config,
- )
+ with _suppress_dispatch_console():
+ IndexBuilder.delete(
+ item_paths=removed_paths,
+ base_index_dir=source,
+ output_dir=output_dir,
+ item_type="skill",
+ config=config,
+ )
finally:
if add_index_path and add_index_path != output_dir:
shutil.rmtree(add_index_path, ignore_errors=True)
- @staticmethod
- def tree() -> dict[str, Any]:
+ def tree(self, *, language: str = "cn") -> dict[str, Any]:
settings = load_settings()
if not settings.enabled:
return {"success": False, "result": render_disabled()}
index_dir = _index_dir(settings)
- if not _is_complete_index(index_dir):
+ inventory = scan_skill_inventory(self._manager)
+ state = _read_state(settings)
+ expected = _expected_fingerprint(inventory, settings)
+ if (
+ not _is_complete_index(index_dir)
+ or not _manifest_matches_inventory(index_dir, inventory)
+ or state.get("fingerprint") != expected
+ ):
return {
"success": False,
- "result": (
- "# Skill Index Tree\n\n"
- "The installed-skill retrieval index has not been built yet.\n\n"
- "Use `skill_index_build` or the web page build button to build the index, "
- "or ignore retrieval and continue with the original jiuwenswarm flow."
- ),
+ "result": _missing_tree_markdown(language),
+ "nodes": [],
+ "branch_count": 0,
+ "leaf_count": 0,
+ "index_dir": str(index_dir),
}
tree_path = index_dir / TREE_INDEX_FILENAME
@@ -241,13 +443,17 @@ class SkillIndexService:
)
build = settings.build
+ llm_config = BuildLLMConfig(
+ model=settings.llm.model,
+ api_key=settings.llm.api_key,
+ base_url=settings.llm.base_url,
+ seed=settings.llm.seed,
+ )
+ for attr in ("stream", "streaming", "enable_streaming"):
+ if hasattr(llm_config, attr):
+ setattr(llm_config, attr, False)
return BuildConfig(
- llm_config=BuildLLMConfig(
- model=settings.llm.model,
- api_key=settings.llm.api_key,
- base_url=settings.llm.base_url,
- seed=settings.llm.seed,
- ),
+ llm_config=llm_config,
taxonomy_config=TaxonomyBuildConfig(
branching_factor=build.branching_factor,
max_depth=build.max_depth,
@@ -267,6 +473,24 @@ class SkillIndexService:
output_config=BuildOutputConfig(generate_html=False),
)
+ @staticmethod
+ def _check_cancel_or_timeout(
+ settings: SkillRetrievalSettings,
+ started: float,
+ cancel_check: Any | None,
+ *,
+ stage: str,
+ ) -> None:
+ state = _read_state(settings)
+ cancel_requested = bool(_build_state_from_state(state).get("cancel_requested", False))
+ if cancel_requested or (callable(cancel_check) and bool(cancel_check())):
+ raise SkillIndexBuildCancelled(f"Skill index build cancelled at stage `{stage}`.")
+ total_timeout = float(settings.build.total_timeout_seconds or 0.0)
+ if total_timeout > 0 and time.monotonic() - started > total_timeout:
+ raise SkillIndexBuildTimeout(
+ f"Skill index build exceeded total timeout {total_timeout:.1f}s at stage `{stage}`."
+ )
+
@staticmethod
def _run_dispatch_build(
*,
@@ -281,12 +505,13 @@ class SkillIndexService:
_ensure_tree_builder_compat(TreeBuilder)
config = SkillIndexService._make_build_config(settings)
- IndexBuilder.build(
- item_paths=inventory.item_paths,
- output_dir=output_dir,
- item_type="skill",
- config=config,
- )
+ with _suppress_dispatch_console():
+ IndexBuilder.build(
+ item_paths=inventory.item_paths,
+ output_dir=output_dir,
+ item_type="skill",
+ config=config,
+ )
@staticmethod
def _recover_index(
@@ -358,6 +583,23 @@ def _record_recovery_failure(candidate: Path, exc: Exception) -> None:
LOGGER.debug("Skipping unusable skill retrieval index recovery candidate %s: %s", candidate, exc)
+class _NullWriter:
+ @staticmethod
+ def write(text: str) -> int:
+ return len(text)
+
+ @staticmethod
+ def flush() -> None:
+ return None
+
+
+@contextmanager
+def _suppress_dispatch_console():
+ sink = _NullWriter()
+ with redirect_stdout(sink), redirect_stderr(sink):
+ yield
+
+
def _tmp_dir(settings: SkillRetrievalSettings) -> Path:
return settings.artifact_root / "tmp"
@@ -381,6 +623,10 @@ def _expected_fingerprint(inventory: SkillInventory, settings: SkillRetrievalSet
return hashlib.sha256(json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8")).hexdigest()
+def expected_index_fingerprint(inventory: SkillInventory, settings: SkillRetrievalSettings) -> str:
+ return _expected_fingerprint(inventory, settings)
+
+
def _read_state(settings: SkillRetrievalSettings) -> dict[str, Any]:
path = _state_file(settings)
if not path.is_file():
@@ -392,18 +638,198 @@ def _read_state(settings: SkillRetrievalSettings) -> dict[str, Any]:
return payload if isinstance(payload, dict) else {}
-def _write_state(settings: SkillRetrievalSettings, *, inventory: SkillInventory, fingerprint: str) -> None:
+def _write_state(
+ settings: SkillRetrievalSettings,
+ *,
+ inventory: SkillInventory,
+ fingerprint: str,
+ elapsed_seconds: float | None = None,
+) -> None:
+ state = _read_state(settings)
+ build_state = _build_state_from_state(state)
+ logs = build_state.get("logs", [])
+ elapsed = (
+ float(elapsed_seconds)
+ if elapsed_seconds is not None
+ else build_state.get("elapsed_seconds", 0.0)
+ )
payload = {
"schema_version": 1,
- "built_at": datetime.now(timezone.utc).isoformat(),
+ "built_at": _now_iso(),
"fingerprint": fingerprint,
"indexed_count": inventory.count,
"index_dir": str(_index_dir(settings)),
"inventory": inventory.to_state_payload(),
+ "build": {
+ "status": "success",
+ "stage": "success",
+ "message": "Skill retrieval index build completed.",
+ "error": "",
+ "progress": 1.0,
+ "started_at": build_state.get("started_at", ""),
+ "finished_at": _now_iso(),
+ "elapsed_seconds": elapsed,
+ "cancel_requested": False,
+ "logs": _append_log(logs, stage="success", status="success", message="Build completed."),
+ },
}
+ settings.artifact_root.mkdir(parents=True, exist_ok=True)
_state_file(settings).write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
+def _write_build_state(
+ settings: SkillRetrievalSettings,
+ *,
+ status: str,
+ stage: str,
+ message: str,
+ error: str | None = None,
+ progress: float | None = None,
+ started_at: str | None = None,
+ finished_at: str | None = None,
+ elapsed_seconds: float | None = None,
+ cancel_requested: bool | None = None,
+ inventory: SkillInventory | None = None,
+ fingerprint: str | None = None,
+ clear_error: bool = False,
+) -> None:
+ settings.artifact_root.mkdir(parents=True, exist_ok=True)
+ state = _read_state(settings)
+ build_state = _build_state_from_state(state)
+ next_build = dict(build_state)
+ next_build.update(
+ {
+ "status": status,
+ "stage": stage,
+ "message": message,
+ "progress": _coerce_progress(progress if progress is not None else next_build.get("progress", 0.0)),
+ }
+ )
+ if error is not None:
+ next_build["error"] = str(error)
+ elif clear_error:
+ next_build["error"] = ""
+ if started_at is not None:
+ next_build["started_at"] = started_at
+ next_build["finished_at"] = ""
+ next_build["elapsed_seconds"] = 0.0
+ next_build["cancel_requested"] = False
+ if finished_at is not None:
+ next_build["finished_at"] = finished_at
+ if elapsed_seconds is not None:
+ next_build["elapsed_seconds"] = float(elapsed_seconds)
+ if cancel_requested is not None:
+ next_build["cancel_requested"] = bool(cancel_requested)
+ next_build["logs"] = _append_log(
+ next_build.get("logs", []),
+ stage=stage,
+ status=status,
+ message=message if error in (None, "") else f"{message} {error}",
+ )
+ state["schema_version"] = int(state.get("schema_version") or 1)
+ if fingerprint:
+ state["fingerprint"] = fingerprint
+ if inventory is not None:
+ state["inventory"] = inventory.to_state_payload()
+ state["indexed_count"] = inventory.count if status == "success" else int(state.get("indexed_count") or 0)
+ state["build"] = next_build
+ _state_file(settings).write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8")
+ LOGGER.info("[skill-index] stage=%s status=%s detail=%s", stage, status, message)
+
+
+def _build_state_from_state(state: dict[str, Any]) -> dict[str, Any]:
+ raw = state.get("build") if isinstance(state, dict) else None
+ if not isinstance(raw, dict):
+ return {
+ "status": "idle",
+ "stage": "",
+ "message": "",
+ "error": "",
+ "progress": 0.0,
+ "started_at": "",
+ "finished_at": "",
+ "elapsed_seconds": 0.0,
+ "cancel_requested": False,
+ "logs": [],
+ }
+ out = dict(raw)
+ out["status"] = str(out.get("status") or "idle")
+ out["stage"] = str(out.get("stage") or "")
+ out["message"] = str(out.get("message") or "")
+ out["error"] = str(out.get("error") or "")
+ out["progress"] = _coerce_progress(out.get("progress", 0.0))
+ out["started_at"] = str(out.get("started_at") or "")
+ out["finished_at"] = str(out.get("finished_at") or "")
+ try:
+ out["elapsed_seconds"] = float(out.get("elapsed_seconds") or 0.0)
+ except (TypeError, ValueError):
+ out["elapsed_seconds"] = 0.0
+ out["cancel_requested"] = bool(out.get("cancel_requested", False))
+ logs = out.get("logs")
+ out["logs"] = logs[-BUILD_LOG_LIMIT:] if isinstance(logs, list) else []
+ return out
+
+
+def _append_log(logs: Any, *, stage: str, status: str, message: str) -> list[dict[str, Any]]:
+ current = list(logs) if isinstance(logs, list) else []
+ current.append(
+ {
+ "time": _now_iso(),
+ "stage": stage,
+ "status": status,
+ "message": str(message or ""),
+ }
+ )
+ return current[-BUILD_LOG_LIMIT:]
+
+
+def _coerce_progress(value: Any) -> float:
+ try:
+ return max(0.0, min(1.0, float(value)))
+ except (TypeError, ValueError):
+ return 0.0
+
+
+def _now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _is_stale_index(settings: SkillRetrievalSettings, inventory: SkillInventory, expected: str) -> bool:
+ index_dir = _index_dir(settings)
+ if not _is_complete_index(index_dir):
+ return False
+ state = _read_state(settings)
+ return not _manifest_matches_inventory(index_dir, inventory) or state.get("fingerprint") != expected
+
+
+def _normalize_build_error(exc: Exception) -> str:
+ text = str(exc)
+ if "set to false for non-streaming calls" in text:
+ return (
+ f"{text}\n\n"
+ "The skill index builder uses non-streaming LLM calls. If this remote model rejects the request, "
+ "check the provider's non-streaming parameter compatibility or use another build model."
+ )
+ return text
+
+
+def _missing_tree_markdown(language: str) -> str:
+ normalized = str(language or "").lower()
+ if normalized.startswith("zh") or normalized.startswith("cn"):
+ return (
+ "# 技能索引树\n\n"
+ "当前没有可用的已安装技能检索索引,或索引已与当前已安装/启用技能不一致。\n\n"
+ "可以点击页面上的“构建索引”重新构建;也可以忽略该能力,继续使用 jiuwenswarm 原有流程。"
+ )
+ return (
+ "# Skill Index Tree\n\n"
+ "No usable installed-skill retrieval index is available, or the index no longer matches the current "
+ "installed/enabled skills.\n\n"
+ "Use the web page build button to rebuild the index, or ignore retrieval and continue with the original "
+ "jiuwenswarm flow."
+ )
+
+
def _is_complete_index(path: Path) -> bool:
return (
(path / TREE_INDEX_FILENAME).is_file()
diff --git a/jiuwenswarm/symphony/skill_retrieval/inventory.py b/jiuwenswarm/symphony/skill_retrieval/inventory.py
index 6bcc06c017..d9bf79771d 100644
--- a/jiuwenswarm/symphony/skill_retrieval/inventory.py
+++ b/jiuwenswarm/symphony/skill_retrieval/inventory.py
@@ -61,8 +61,6 @@ def scan_skill_inventory(manager: Any) -> SkillInventory:
continue
meta, body = _parse_skill_md(skill_file)
name = str(meta.get("name") or child.name).strip() or child.name
- if not _is_enabled(manager, name):
- continue
description = str(meta.get("description") or "").strip() or _first_paragraph(body)
items.append(
SkillInventoryItem(
@@ -118,16 +116,6 @@ def _call_list(manager: Any, method_name: str) -> list[dict[str, Any]]:
return [dict(item) for item in value if isinstance(item, dict)] if isinstance(value, list) else []
-def _is_enabled(manager: Any, name: str) -> bool:
- method = getattr(manager, "get_skill_enabled", None)
- if not callable(method):
- return True
- try:
- return bool(method(name))
- except Exception:
- return True
-
-
def _find_skill_file(skill_dir: Path) -> Path | None:
for filename in ("SKILL.md", "skill.md", "Skill.md"):
candidate = skill_dir / filename
diff --git a/tests/agents/swarm/test_swarm_assembly.py b/tests/agents/swarm/test_swarm_assembly.py
index 322d0f96cb..173f9f7326 100644
--- a/tests/agents/swarm/test_swarm_assembly.py
+++ b/tests/agents/swarm/test_swarm_assembly.py
@@ -27,6 +27,7 @@ from pathlib import Path
import pytest
from openjiuwen.agent_teams.schema import deep_agent_spec as das
+from openjiuwen.agent_teams.harness.manifest import get_catalog, resolve_factory
from openjiuwen.agent_teams.schema.blueprint import LeaderSpec, TeamAgentSpec
from openjiuwen.agent_teams.schema.deep_agent_spec import (
BuiltinToolSpec,
@@ -356,6 +357,74 @@ def test_member_skill_toolkit_carries_selected_skills() -> None:
assert toolkit.params == {"skills": ["alpha", "beta"]}
+def test_swarm_skill_retrieval_tools_use_global_skill_manager(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Skill retrieval indexes globally installed skills, not member workspace skills."""
+ calls: list[str | None] = []
+
+ class FakeSkillManager:
+ def __init__(self, workspace_dir: str | None = None) -> None:
+ calls.append(workspace_dir)
+
+ class FakeToolkit:
+ def __init__(
+ self,
+ manager: FakeSkillManager,
+ visible_skill_names: object | None = None,
+ ) -> None:
+ self.manager = manager
+ self.visible_skill_names = visible_skill_names
+
+ @staticmethod
+ def get_tools() -> list:
+ return []
+
+ monkeypatch.setattr(tools, "is_skill_retrieval_enabled", lambda: True)
+ monkeypatch.setattr(tools, "SkillManager", FakeSkillManager)
+ monkeypatch.setattr(tools, "SkillRetrievalToolkit", FakeToolkit)
+
+ factory = resolve_factory(get_catalog()[registry.SKILL_RETRIEVAL].factory_ref)
+ built = factory({}, SwarmBuildContext())
+
+ assert built == []
+ assert calls == [None]
+
+
+def test_swarm_skill_retrieval_prompt_uses_global_skill_manager(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ """The retrieval prompt must match the same global index as the retrieval tools."""
+ workspace_root = str(tmp_path / "member-workspace")
+ calls: list[str | None] = []
+
+ class FakeSkillManager:
+ def __init__(self, workspace_dir: str | None = None) -> None:
+ calls.append(workspace_dir)
+
+ monkeypatch.setattr(
+ "jiuwenswarm.agents.harness.common.tools.skill_retrieval_toolkits.is_skill_retrieval_enabled",
+ lambda: True,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.skill.skill_manager.SkillManager",
+ FakeSkillManager,
+ )
+
+ factory = resolve_factory(get_catalog()[registry.SKILL_RETRIEVAL_PROMPT].factory_ref)
+ rail = factory(
+ {},
+ SwarmBuildContext(
+ global_skills_dir=str(tmp_path / "global-skills"),
+ workspace=types.SimpleNamespace(root_path=workspace_root),
+ ),
+ )
+
+ assert rail is not None
+ assert calls == [None]
+
+
@pytest.mark.parametrize("role", ["leader", "teammate"])
def test_team_member_deep_agent_spec_uses_agentic_skill_disclosure(role: str) -> None:
"""Chat-team members use lightweight skill exposure when retrieval is enabled."""
diff --git a/tests/symphony/test_agentic_retrieval_toolkit.py b/tests/symphony/test_agentic_retrieval_toolkit.py
index 78dd2e9e43..f9ab32dac2 100644
--- a/tests/symphony/test_agentic_retrieval_toolkit.py
+++ b/tests/symphony/test_agentic_retrieval_toolkit.py
@@ -4,7 +4,10 @@ import sys
import types
from types import SimpleNamespace
-from jiuwenswarm.symphony.agent import AgenticRetrievalToolKit
+import pytest
+
+from jiuwenswarm.symphony.agent import AgenticRetrievalToolKit, AgenticToolResult
+from jiuwenswarm.agents.harness.common.tools import skill_retrieval_toolkits as _toolkit_mod
def _node(
@@ -22,7 +25,7 @@ def _node(
)
-def _toolkit() -> AgenticRetrievalToolKit:
+def _toolkit(visible_skill_names: set[str] | None = None) -> AgenticRetrievalToolKit:
pdf_item = SimpleNamespace(
payload="pdf-reader",
item_id="pdf-reader",
@@ -65,7 +68,22 @@ def _toolkit() -> AgenticRetrievalToolKit:
metadata={"skill_path": "/home/doujzc/.openjiuwen/skills/pdf-reader/SKILL.md"},
)
loaded_index = SimpleNamespace(tree_root=root, catalog_records=[record])
- return AgenticRetrievalToolKit(loaded_index=loaded_index, progressive_config=object(), top_k=5)
+ return AgenticRetrievalToolKit(
+ loaded_index=loaded_index,
+ progressive_config=object(),
+ top_k=5,
+ visible_skill_names=visible_skill_names,
+ )
+
+
+def _skill_tree_from_detailed_output(result: AgenticToolResult) -> dict:
+ assert "skill_tree" not in result
+ assert "skill_tree" not in str(result)
+ detailed_output = result.detailed_output
+ assert isinstance(detailed_output, dict)
+ skill_tree = detailed_output.get("skill_tree")
+ assert isinstance(skill_tree, dict)
+ return skill_tree
def test_skill_branch_peek_returns_branch_summary_only() -> None:
@@ -77,15 +95,18 @@ def test_skill_branch_peek_returns_branch_summary_only() -> None:
assert "## input `ROOT`" in markdown
assert "Root description must not be rendered" not in markdown
assert "1. `OfficeDocs`" in markdown
- assert "2. `SearchResearch`" in markdown
+ assert "SearchResearch" not in markdown
assert "covers: 3 branches, 1 skill" in markdown
assert "SKILL.md" not in markdown
assert "pdf-reader" not in markdown
- assert result["skill_tree"]["query"] == "skill_branch_peek: ROOT"
- assert result["skill_tree"]["candidate_count"] == 0
- assert result["skill_tree"]["steps"][0]["event_type"] == "fragment_built"
- assert result["skill_tree"]["steps"][0]["node_id"] == "ROOT"
- assert result["skill_tree"]["steps"][0]["branches"][0]["id"] == "OfficeDocs"
+ assert isinstance(result, AgenticToolResult)
+ tree = _skill_tree_from_detailed_output(result)
+ assert tree["query"] == "skill_branch_peek: ROOT"
+ assert tree["candidate_count"] == 0
+ assert tree["steps"][0]["event_type"] == "fragment_built"
+ assert tree["steps"][0]["node_id"] == "ROOT"
+ assert tree["steps"][0]["branches"][0]["id"] == "OfficeDocs"
+ assert len(tree["steps"][0]["branches"]) == 1
def test_skill_branch_peek_leaf_and_unknown_errors() -> None:
@@ -185,7 +206,8 @@ def test_skill_branch_explore_renders_next_boundary(monkeypatch) -> None:
assert "SKILL.md" not in markdown
assert "Terminal Skill Candidates" not in markdown
assert "Covers:" not in markdown
- tree = result["skill_tree"]
+ assert isinstance(result, AgenticToolResult)
+ tree = _skill_tree_from_detailed_output(result)
assert tree["query"] == "skill_branch_explore: OfficeDocs.Documents"
assert tree["candidate_count"] == 0
assert [step["event_type"] for step in tree["steps"]] == ["fragment_built", "fragment_continue"]
@@ -259,7 +281,8 @@ def test_skill_branch_explore_renders_terminal_skills_with_read_info(monkeypatch
assert "- Select when:" not in markdown
assert "- Don't select when:" not in markdown
assert "- Read:" not in markdown
- tree = result["skill_tree"]
+ assert isinstance(result, AgenticToolResult)
+ tree = _skill_tree_from_detailed_output(result)
assert tree["query"] == "skill_branch_explore: OfficeDocs.Documents.Pdf"
assert tree["candidate_count"] == 1
assert [step["event_type"] for step in tree["steps"]] == [
@@ -302,6 +325,49 @@ def test_root_prompt_contains_first_level_categories_only() -> None:
assert "- `OfficeDocs`" in markdown
assert "1. `OfficeDocs`" not in markdown
assert "`OfficeDocs`" in markdown
- assert "`SearchResearch`" in markdown
assert "`OfficeDocs.Documents`" not in markdown
assert "pdf-reader" not in markdown
+ assert "`SearchResearch`" not in markdown
+
+
+def test_visible_skill_filter_hides_unavailable_branches() -> None:
+ toolkit = _toolkit(visible_skill_names=set())
+
+ peek = toolkit.skill_branch_peek(["ROOT"])
+ assert peek["success"] is True
+ assert "No child branches." in peek["result"]
+ assert "OfficeDocs" not in peek["result"]
+ assert "pdf-reader" not in peek["result"]
+
+ explore = toolkit.skill_branch_explore(["OfficeDocs"])
+ assert explore["success"] is False
+ assert "Unknown branch node id" in explore["result"]
+
+
+async def test_runtime_toolkit_methods_return_build_and_missing_index_results(monkeypatch) -> None:
+ monkeypatch.setattr(
+ _toolkit_mod,
+ "build_skill_index",
+ lambda manager: {
+ "success": True,
+ "result": "# Skill Index Build\n\nSkill index build started in the background.",
+ },
+ )
+ monkeypatch.setattr(
+ _toolkit_mod,
+ "skill_branch_explore",
+ lambda node_ids, manager: {
+ "success": False,
+ "result": "# Skill Tree Retrieval Unavailable\n\nCall `skill_index_build`.",
+ },
+ )
+ toolkit = _toolkit_mod.SkillRetrievalToolkit(manager=SimpleNamespace())
+
+ build_result = await toolkit.skill_index_build()
+ explore_result = await toolkit.skill_branch_explore(["OfficeDocs"])
+
+ assert build_result["success"] is True
+ assert "started in the background" in build_result["result"]
+ assert explore_result["success"] is False
+ assert "skill_index_build" in explore_result["result"]
diff --git a/tests/symphony/test_skill_retrieval_index_service.py b/tests/symphony/test_skill_retrieval_index_service.py
new file mode 100644
index 0000000000..3d764f4d48
--- /dev/null
+++ b/tests/symphony/test_skill_retrieval_index_service.py
@@ -0,0 +1,311 @@
+from __future__ import annotations
+
+import json
+import threading
+from pathlib import Path
+from types import SimpleNamespace
+
+from jiuwenswarm.symphony.skill_retrieval.build_coordinator import (
+ cancel_skill_index_build,
+ start_skill_index_build,
+)
+from jiuwenswarm.symphony.skill_retrieval.config import (
+ BuildSettings,
+ LLMSettings,
+ RetrieveSettings,
+ SkillRetrievalSettings,
+)
+from jiuwenswarm.symphony.skill_retrieval.index_service import SkillIndexService, expected_index_fingerprint
+from jiuwenswarm.symphony.skill_retrieval.inventory import scan_skill_inventory
+
+
+def _write_skill(root: Path, dirname: str, *, name: str | None = None, description: str = "desc") -> None:
+ skill_dir = root / dirname
+ skill_dir.mkdir(parents=True)
+ skill_name = name or dirname
+ (skill_dir / "SKILL.md").write_text(
+ f"---\nname: {skill_name}\ndescription: {description}\n---\n\nBody\n",
+ encoding="utf-8",
+ )
+
+
+class _InventoryManager:
+ def __init__(self, skills_dir: Path) -> None:
+ self._skills_dir = skills_dir
+
+ @staticmethod
+ def get_local_skills() -> list[dict]:
+ return []
+
+ @staticmethod
+ def get_installed_plugins() -> list[dict]:
+ return [
+ {"name": "disabled-plugin", "enabled": False, "skills": ["disabled-plugin"]},
+ {"name": "enabled-plugin", "enabled": True, "skills": ["enabled-plugin"]},
+ ]
+
+ @staticmethod
+ def get_skill_enabled(name: str) -> bool:
+ return name != "disabled-skill"
+
+
+def test_scan_skill_inventory_includes_all_installed_skills(tmp_path: Path) -> None:
+ skills_dir = tmp_path / "skills"
+ skills_dir.mkdir()
+ _write_skill(skills_dir, "disabled-plugin")
+ _write_skill(skills_dir, "disabled-skill")
+ _write_skill(skills_dir, "enabled-plugin")
+
+ inventory = scan_skill_inventory(_InventoryManager(skills_dir))
+
+ assert [item.name for item in inventory.items] == [
+ "disabled-plugin",
+ "disabled-skill",
+ "enabled-plugin",
+ ]
+
+
+def test_build_index_with_no_skills_clears_stale_index_and_records_failure(monkeypatch, tmp_path: Path) -> None:
+ skills_dir = tmp_path / "skills"
+ skills_dir.mkdir()
+ artifact_root = tmp_path / "artifact"
+ index_dir = artifact_root / "index"
+ index_dir.mkdir(parents=True)
+ (index_dir / "tree_index.yaml").write_text("nodes: []\n", encoding="utf-8")
+ (index_dir / "catalog.jsonl").write_text("", encoding="utf-8")
+ (index_dir / "manifest.json").write_text(json.dumps({"item_paths": ["/old/skill"]}), encoding="utf-8")
+ (artifact_root / "state.json").write_text(
+ json.dumps({"fingerprint": "old", "indexed_count": 1}),
+ encoding="utf-8",
+ )
+ settings = SkillRetrievalSettings(
+ enabled=True,
+ artifact_root=artifact_root,
+ llm=LLMSettings(model="", api_key="", base_url=""),
+ build=BuildSettings(),
+ retrieve=RetrieveSettings(),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.skill_retrieval.index_service.load_settings",
+ lambda: settings,
+ )
+
+ result = SkillIndexService(SimpleNamespace(_skills_dir=skills_dir)).build_index(force=True)
+
+ assert result["success"] is False
+ assert not index_dir.exists()
+ state = json.loads((artifact_root / "state.json").read_text(encoding="utf-8"))
+ assert state["build"]["status"] == "failed"
+ assert "No installed skills" in state["build"]["error"]
+
+
+def test_cancel_without_running_build_does_not_write_cancel_state(monkeypatch, tmp_path: Path) -> None:
+ artifact_root = tmp_path / "artifact"
+ settings = SkillRetrievalSettings(
+ enabled=True,
+ artifact_root=artifact_root,
+ llm=LLMSettings(model="model", api_key="key", base_url=""),
+ build=BuildSettings(),
+ retrieve=RetrieveSettings(),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.skill_retrieval.build_coordinator.load_settings",
+ lambda: settings,
+ )
+
+ result = cancel_skill_index_build(SimpleNamespace(_skills_dir=tmp_path / "skills"))
+
+ assert result["success"] is False
+ assert result["build_status"] == "idle"
+ assert not (artifact_root / "state.json").exists()
+
+
+def test_background_build_marks_shared_state(monkeypatch, tmp_path: Path) -> None:
+ artifact_root = tmp_path / "artifact"
+ settings = SkillRetrievalSettings(
+ enabled=True,
+ artifact_root=artifact_root,
+ llm=LLMSettings(model="model", api_key="key", base_url=""),
+ build=BuildSettings(),
+ retrieve=RetrieveSettings(),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.skill_retrieval.build_coordinator.load_settings",
+ lambda: settings,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.skill_retrieval.index_service.load_settings",
+ lambda: settings,
+ )
+ release = threading.Event()
+ started = threading.Event()
+
+ def fake_build_index(self, *, force=False, cancel_check=None, source="manual"):
+ started.set()
+ release.wait(timeout=1)
+ return {"success": True, "result": "# ok"}
+
+ monkeypatch.setattr(SkillIndexService, "build_index", fake_build_index)
+ manager = SimpleNamespace(_skills_dir=tmp_path / "skills")
+
+ result = start_skill_index_build(manager, force=True, source="web")
+ assert started.wait(timeout=1)
+
+ assert result["success"] is True
+ assert result["background"] is True
+ state = json.loads((artifact_root / "state.json").read_text(encoding="utf-8"))
+ assert state["build"]["status"] == "running"
+ assert state["build"]["stage"] == "queued"
+
+ cancel_result = cancel_skill_index_build(manager)
+ release.set()
+ assert cancel_result["success"] is True
+
+
+def test_force_build_bypasses_fresh_index_reuse(monkeypatch, tmp_path: Path) -> None:
+ skills_dir = tmp_path / "skills"
+ skills_dir.mkdir()
+ _write_skill(skills_dir, "enabled-skill")
+ manager = SimpleNamespace(_skills_dir=skills_dir)
+ artifact_root = tmp_path / "artifact"
+ settings = SkillRetrievalSettings(
+ enabled=True,
+ artifact_root=artifact_root,
+ llm=LLMSettings(model="model", api_key="key", base_url=""),
+ build=BuildSettings(),
+ retrieve=RetrieveSettings(),
+ )
+ inventory = scan_skill_inventory(manager)
+ expected = expected_index_fingerprint(inventory, settings)
+ index_dir = artifact_root / "index"
+ index_dir.mkdir(parents=True)
+ (index_dir / "tree_index.yaml").write_text("nodes: []\n", encoding="utf-8")
+ (index_dir / "catalog.jsonl").write_text("", encoding="utf-8")
+ (index_dir / "manifest.json").write_text(
+ json.dumps({"item_paths": inventory.item_paths}),
+ encoding="utf-8",
+ )
+ (artifact_root / "state.json").write_text(
+ json.dumps({"fingerprint": expected, "indexed_count": inventory.count}),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.skill_retrieval.index_service.load_settings",
+ lambda: settings,
+ )
+ calls: list[str] = []
+
+ def fake_run_dispatch_build(*, settings, inventory, output_dir):
+ calls.append("build")
+ output_dir.mkdir(parents=True, exist_ok=True)
+ (output_dir / "tree_index.yaml").write_text("nodes: []\n", encoding="utf-8")
+ (output_dir / "catalog.jsonl").write_text("", encoding="utf-8")
+ (output_dir / "manifest.json").write_text(
+ json.dumps({"item_paths": inventory.item_paths}),
+ encoding="utf-8",
+ )
+
+ monkeypatch.setattr(SkillIndexService, "_run_dispatch_build", staticmethod(fake_run_dispatch_build))
+
+ result = SkillIndexService(manager).build_index(force=True)
+
+ assert result["success"] is True
+ assert calls == ["build"]
+ state = json.loads((artifact_root / "state.json").read_text(encoding="utf-8"))
+ assert state["build"]["status"] == "success"
+
+
+def test_missing_llm_config_records_failure(monkeypatch, tmp_path: Path) -> None:
+ skills_dir = tmp_path / "skills"
+ skills_dir.mkdir()
+ _write_skill(skills_dir, "enabled-skill")
+ artifact_root = tmp_path / "artifact"
+ settings = SkillRetrievalSettings(
+ enabled=True,
+ artifact_root=artifact_root,
+ llm=LLMSettings(model="", api_key="", base_url=""),
+ build=BuildSettings(),
+ retrieve=RetrieveSettings(),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.skill_retrieval.index_service.load_settings",
+ lambda: settings,
+ )
+
+ result = SkillIndexService(SimpleNamespace(_skills_dir=skills_dir)).build_index(force=True)
+
+ assert result["success"] is False
+ assert "requires a model and API key" in result["result"]
+ state = json.loads((artifact_root / "state.json").read_text(encoding="utf-8"))
+ assert state["build"]["status"] == "failed"
+ assert state["build"]["stage"] == "llm_config"
+
+
+def test_tree_rejects_stale_manifest_and_uses_requested_language(monkeypatch, tmp_path: Path) -> None:
+ skills_dir = tmp_path / "skills"
+ skills_dir.mkdir()
+ _write_skill(skills_dir, "current-skill")
+ artifact_root = tmp_path / "artifact"
+ index_dir = artifact_root / "index"
+ index_dir.mkdir(parents=True)
+ (index_dir / "tree_index.yaml").write_text(
+ "nodes:\n"
+ " - cid: old\n"
+ " type: leaf\n"
+ " worker_id: old-skill\n",
+ encoding="utf-8",
+ )
+ (index_dir / "catalog.jsonl").write_text("", encoding="utf-8")
+ (index_dir / "manifest.json").write_text(json.dumps({"item_paths": ["/old/skill"]}), encoding="utf-8")
+ (artifact_root / "state.json").write_text(json.dumps({"fingerprint": "old"}), encoding="utf-8")
+ settings = SkillRetrievalSettings(
+ enabled=True,
+ artifact_root=artifact_root,
+ llm=LLMSettings(model="model", api_key="key", base_url=""),
+ build=BuildSettings(),
+ retrieve=RetrieveSettings(),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.skill_retrieval.index_service.load_settings",
+ lambda: settings,
+ )
+
+ zh = SkillIndexService(SimpleNamespace(_skills_dir=skills_dir)).tree(language="zh")
+ en = SkillIndexService(SimpleNamespace(_skills_dir=skills_dir)).tree(language="en")
+
+ assert zh["success"] is False
+ assert zh["nodes"] == []
+ assert "技能索引树" in zh["result"]
+ assert en["success"] is False
+ assert en["nodes"] == []
+ assert "Skill Index Tree" in en["result"]
+
+
+def test_build_error_normalizes_non_streaming_remote_model_error(monkeypatch, tmp_path: Path) -> None:
+ skills_dir = tmp_path / "skills"
+ skills_dir.mkdir()
+ _write_skill(skills_dir, "enabled-skill")
+ artifact_root = tmp_path / "artifact"
+ settings = SkillRetrievalSettings(
+ enabled=True,
+ artifact_root=artifact_root,
+ llm=LLMSettings(model="model", api_key="key", base_url=""),
+ build=BuildSettings(),
+ retrieve=RetrieveSettings(),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.skill_retrieval.index_service.load_settings",
+ lambda: settings,
+ )
+
+ def raise_remote_error(*, settings, inventory, output_dir):
+ raise RuntimeError("set to false for non-streaming calls")
+
+ monkeypatch.setattr(SkillIndexService, "_run_dispatch_build", staticmethod(raise_remote_error))
+
+ result = SkillIndexService(SimpleNamespace(_skills_dir=skills_dir)).build_index(force=True)
+
+ assert result["success"] is False
+ assert "non-streaming LLM calls" in result["result"]
+ state = json.loads((artifact_root / "state.json").read_text(encoding="utf-8"))
+ assert "non-streaming LLM calls" in state["build"]["error"]
diff --git a/tests/unit_tests/agentserver/test_agentserver_acp.py b/tests/unit_tests/agentserver/test_agentserver_acp.py
index 9d83e01491..f8f9e158d8 100644
--- a/tests/unit_tests/agentserver/test_agentserver_acp.py
+++ b/tests/unit_tests/agentserver/test_agentserver_acp.py
@@ -230,7 +230,7 @@ def test_interface_deep_parse_stream_chunk_preserves_tool_result_status():
}
-def test_parse_stream_chunk_uses_skill_tree_result_as_raw_output():
+def test_parse_stream_chunk_uses_raw_output_skill_tree_for_frontend():
raw_output = {
"success": True,
"result": "# Skill Branch Explore",
@@ -247,7 +247,8 @@ def test_parse_stream_chunk_uses_skill_tree_result_as_raw_output():
"tool_result": {
"tool_call_id": "call-1",
"tool_name": "skill_branch_explore",
- **raw_output,
+ "result": "# Skill Branch Explore",
+ "raw_output": raw_output,
}
},
)
@@ -259,7 +260,7 @@ def test_parse_stream_chunk_uses_skill_tree_result_as_raw_output():
assert parsed["raw_output"] == raw_output
-def test_interface_deep_parse_stream_chunk_uses_skill_tree_result_as_raw_output():
+def test_interface_deep_parse_stream_chunk_uses_raw_output_skill_tree_for_frontend():
parse_chunk = getattr(interface_deep_module.JiuWenSwarmDeepAdapter, "_parse_stream_chunk")
raw_output = {
"success": True,
@@ -277,7 +278,8 @@ def test_interface_deep_parse_stream_chunk_uses_skill_tree_result_as_raw_output(
"tool_result": {
"tool_call_id": "call-1",
"tool_name": "skill_branch_explore",
- **raw_output,
+ "result": "# Skill Branch Explore",
+ "raw_output": raw_output,
}
},
)
@@ -289,6 +291,45 @@ def test_interface_deep_parse_stream_chunk_uses_skill_tree_result_as_raw_output(
assert parsed["raw_output"] == raw_output
+def test_parse_stream_chunk_does_not_lift_top_level_skill_tree_to_raw_output():
+ parsed = parse_stream_chunk(
+ types.SimpleNamespace(
+ type="tool_result",
+ payload={
+ "tool_result": {
+ "tool_call_id": "call-1",
+ "tool_name": "skill_branch_explore",
+ "result": "# Skill Branch Explore",
+ "skill_tree": {"steps": [{"node_id": "SoftwareEngineering"}]},
+ }
+ },
+ )
+ )
+
+ assert parsed["event_type"] == "chat.tool_result"
+ assert "raw_output" not in parsed
+
+
+def test_interface_deep_parse_stream_chunk_does_not_lift_top_level_skill_tree_to_raw_output():
+ parse_chunk = getattr(interface_deep_module.JiuWenSwarmDeepAdapter, "_parse_stream_chunk")
+ parsed = parse_chunk(
+ types.SimpleNamespace(
+ type="tool_result",
+ payload={
+ "tool_result": {
+ "tool_call_id": "call-1",
+ "tool_name": "skill_branch_explore",
+ "result": "# Skill Branch Explore",
+ "skill_tree": {"steps": [{"node_id": "SoftwareEngineering"}]},
+ }
+ },
+ )
+ )
+
+ assert parsed["event_type"] == "chat.tool_result"
+ assert "raw_output" not in parsed
+
+
def test_parse_stream_chunk_preserves_symphony_status_payload():
parsed = parse_stream_chunk(
types.SimpleNamespace(
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 91b6ee8e1a..859ec6fc51 100644
--- a/tests/unit_tests/agentserver/test_stream_event_rail_symphony.py
+++ b/tests/unit_tests/agentserver/test_stream_event_rail_symphony.py
@@ -7,6 +7,7 @@ from openjiuwen.core.single_agent.rail.base import ToolCallInputs
from jiuwenswarm.agents.harness.common.rails.stream_event_rail import (
JiuSwarmStreamEventRail,
)
+from jiuwenswarm.symphony.agent import AgenticToolResult
class _StreamSession:
@@ -123,6 +124,37 @@ async def test_stream_event_rail_continues_after_symphony_skill_gap_result():
assert ctx.force_finish_requests == []
+async def test_stream_event_rail_uses_agentic_tool_detailed_output_as_raw_output():
+ rail = JiuSwarmStreamEventRail()
+ session = _StreamSession()
+ detailed_output = {
+ "success": True,
+ "result": "# Skill Branch Explore",
+ "skill_tree": {
+ "query": "skill_branch_explore: OfficeDocs",
+ "steps": [{"order": 0, "node_id": "OfficeDocs"}],
+ "candidates": [],
+ },
+ }
+ result = AgenticToolResult(
+ {"success": True, "result": "# Skill Branch Explore"},
+ detailed_output=detailed_output,
+ )
+ ctx = _ctx(session, "skill_branch_explore", 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]["raw_output"] == detailed_output
+ assert "skill_tree" not in tool_results[0]["result"]
+
+
@pytest.mark.asyncio
async def test_stream_event_rail_does_not_enable_symphony_status_events_for_other_tools():
rail = JiuSwarmStreamEventRail()
diff --git a/tests/unit_tests/agentserver/test_system_prompt_restructure.py b/tests/unit_tests/agentserver/test_system_prompt_restructure.py
index 54ce5501e5..4d98ec462f 100644
--- a/tests/unit_tests/agentserver/test_system_prompt_restructure.py
+++ b/tests/unit_tests/agentserver/test_system_prompt_restructure.py
@@ -271,8 +271,13 @@ async def test_runtime_prompt_language_output_prefers_rail_language_over_runtime
async def test_skill_retrieval_prompt_hides_legacy_list_skill(monkeypatch):
monkeypatch.setattr(
_skill_retrieval_prompt_mod,
- "render_skill_retrieval_prompt",
- lambda manager, language: "# Agentic 技能检索\n使用 skill_branch_explore。",
+ "is_agentic_retrieval_enabled",
+ lambda: True,
+ )
+ monkeypatch.setattr(
+ _skill_retrieval_prompt_mod,
+ "render_skill_retrieval_prompt_for_visible_skills",
+ lambda manager, language, visible_skill_names=None: "# Agentic 技能检索\n使用 skill_branch_explore。",
)
builder = SystemPromptBuilder(language="cn")
builder.add_section(PromptSection(name="skills", content={"cn": "旧 list_skill 提示"}, priority=40))
@@ -303,6 +308,100 @@ async def test_skill_retrieval_prompt_hides_legacy_list_skill(monkeypatch):
await rail.after_model_call(ctx)
assert agent.ability_manager.get("list_skill") is not None
+ assert "旧 list_skill 提示" in builder.build()
+
+
+async def test_skill_retrieval_prompt_clears_section_when_disabled(monkeypatch):
+ monkeypatch.setattr(
+ _skill_retrieval_prompt_mod,
+ "is_agentic_retrieval_enabled",
+ lambda: False,
+ )
+ builder = SystemPromptBuilder(language="cn")
+ builder.add_section(PromptSection(name="skill_retrieval", content={"cn": "残留 Agentic 技能检索"}, priority=41))
+ agent = _FakeToolAgent(builder)
+ ctx = AgentCallbackContext(
+ agent=agent,
+ inputs=SimpleNamespace(tools=[SimpleNamespace(name="list_skill")]),
+ session=_FakeSession(),
+ extra={},
+ )
+
+ rail = SkillRetrievalPromptRail()
+ rail.init(agent)
+ await rail.before_model_call(ctx)
+
+ assert [tool.name for tool in ctx.inputs.tools] == ["list_skill"]
+ assert "残留 Agentic 技能检索" not in builder.build()
+ assert agent.ability_manager.get("list_skill") is not None
+
+
+async def test_skill_retrieval_prompt_disabled_restores_hidden_skills_section(monkeypatch):
+ enabled = True
+ monkeypatch.setattr(
+ _skill_retrieval_prompt_mod,
+ "is_agentic_retrieval_enabled",
+ lambda: enabled,
+ )
+ monkeypatch.setattr(
+ _skill_retrieval_prompt_mod,
+ "render_skill_retrieval_prompt_for_visible_skills",
+ lambda manager, language, visible_skill_names=None: "# Agentic 技能检索\n使用 skill_branch_explore。",
+ )
+ builder = SystemPromptBuilder(language="cn")
+ builder.add_section(PromptSection(name="skills", content={"cn": "原生技能提示"}, priority=40))
+ agent = _FakeToolAgent(builder)
+ ctx = AgentCallbackContext(
+ agent=agent,
+ inputs=SimpleNamespace(tools=[SimpleNamespace(name="skill_branch_explore")]),
+ session=_FakeSession(),
+ extra={},
+ )
+
+ rail = SkillRetrievalPromptRail()
+ rail.init(agent)
+ await rail.before_model_call(ctx)
+ assert "原生技能提示" not in builder.build()
+
+ enabled = False
+ await rail.before_model_call(ctx)
+
+ prompt = builder.build()
+ assert "Agentic 技能检索" not in prompt
+ assert "原生技能提示" in prompt
+
+
+async def test_skill_retrieval_prompt_render_empty_restores_native_skills(monkeypatch):
+ monkeypatch.setattr(
+ _skill_retrieval_prompt_mod,
+ "is_agentic_retrieval_enabled",
+ lambda: True,
+ )
+ monkeypatch.setattr(
+ _skill_retrieval_prompt_mod,
+ "render_skill_retrieval_prompt_for_visible_skills",
+ lambda manager, language, visible_skill_names=None: "",
+ )
+ builder = SystemPromptBuilder(language="cn")
+ builder.add_section(PromptSection(name="skills", content={"cn": "原生技能提示"}, priority=40))
+ agent = _FakeToolAgent(builder)
+ ctx = AgentCallbackContext(
+ agent=agent,
+ inputs=SimpleNamespace(tools=[SimpleNamespace(name="list_skill")]),
+ session=_FakeSession(),
+ extra={},
+ )
+
+ rail = SkillRetrievalPromptRail()
+ rail.init(agent)
+ await rail.before_model_call(ctx)
+
+ assert "原生技能提示" in builder.build()
+ assert agent.ability_manager.get("list_skill") is not None
+ assert [tool.name for tool in ctx.inputs.tools] == ["list_skill"]
def test_resolve_skill_mode_accepts_all_and_auto_list(monkeypatch):
@@ -321,6 +420,52 @@ def test_resolve_skill_mode_accepts_all_and_auto_list(monkeypatch):
assert JiuWenSwarmDeepAdapter._resolve_skill_mode({"skill_mode": "all"}) == "auto_list"
+def test_deep_adapter_visible_skill_names_match_list_skill(monkeypatch, tmp_path):
+ for name in ("alpha", "beta", "_internal", ".hidden"):
+ skill_dir = tmp_path / name
+ skill_dir.mkdir()
+ (skill_dir / "SKILL.md").write_text("---\nname: x\n---\n", encoding="utf-8")
+ (tmp_path / "not-a-skill").mkdir()
+
+ adapter = _TestableJiuWenSwarmDeepAdapter()
+ adapter.set_skill_manager(
+ SimpleNamespace(list_execution_disabled_skills=lambda: ["beta"])
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.agent_adapter.interface_deep.get_agent_skills_dir",
+ lambda: tmp_path,
+ )
+
+ assert adapter._visible_skill_names_for_list_skill() == {"alpha"}
+
+
+def test_deep_adapter_skill_retrieval_prompt_uses_visible_skill_provider(monkeypatch):
+ captured: dict[str, object] = {}
+
+ class FakeRail:
+ def __init__(self, *, manager, visible_skill_names):
+ captured["manager"] = manager
+ captured["visible_skill_names"] = visible_skill_names
+
+ manager = SimpleNamespace(list_execution_disabled_skills=lambda: [])
+ adapter = _TestableJiuWenSwarmDeepAdapter()
+ adapter.set_skill_manager(manager)
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.agent_adapter.interface_deep.is_skill_retrieval_enabled",
+ lambda: True,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.agent_adapter.interface_deep.SkillRetrievalPromptRail",
+ FakeRail,
+ )
+
+ rail = adapter._build_skill_retrieval_prompt_rail()
+
+ assert isinstance(rail, FakeRail)
+ assert captured["manager"] is manager
+ assert captured["visible_skill_names"] == adapter._visible_skill_names_for_list_skill
+
+
def test_resolve_enable_task_loop_can_be_called_on_class(monkeypatch):
monkeypatch.delenv("SKILL_CREATE", raising=False)
assert (
diff --git a/tests/unit_tests/test_config.py b/tests/unit_tests/test_config.py
index 0dedf50ea9..39c1011343 100644
--- a/tests/unit_tests/test_config.py
+++ b/tests/unit_tests/test_config.py
@@ -171,7 +171,7 @@ symphony:
assert migrated["symphony"]["fingerprint"]["normalization"]["workers"] == 1
@staticmethod
- def test_update_skill_retrieval_keeps_public_build_and_retrieve_config(
+ def test_update_skill_retrieval_preserves_existing_hidden_config(
monkeypatch: pytest.MonkeyPatch,
temp_config_file: Path,
):
@@ -243,9 +243,12 @@ symphony:
"equivalence_enabled": False,
}
assert section["retrieve"] == {
+ "top_k": 6,
"compact_codes_enabled": True,
"flatten_tree": True,
"max_exposure_depth": 12,
+ "max_branch_choices": 5,
+ "max_parallel_branches": 4,
}