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): 修复前后端一致性问题 & 优化技能树的前端展示效果

xutuo248462eee566
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 2a715c4ecb..e4e51f5b08 100644
--- a/jiuwenswarm/agents/harness/common/rails/skill_retrieval_prompt_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/skill_retrieval_prompt_rail.py
@@ -24,7 +24,10 @@ _LEGACY_LIST_SKILL_TOOL_NAMES = frozenset({"list_skill", "list_skills"})
class SkillRetrievalPromptRail(DeepAgentRail):
"""Inject lightweight skill-tree retrieval guidance into the system prompt."""
- priority = 101
+ # openjiuwen's callback framework executes higher priorities first. Keep this
+ # below SkillUseRail(100) so the native skills section can be hidden after it
+ # is refreshed for the current model call.
+ priority = 99
SECTION_NAME = "skill_retrieval"
SECTION_PRIORITY = 41
diff --git a/jiuwenswarm/agents/swarm/config_specs.py b/jiuwenswarm/agents/swarm/config_specs.py
index 6b61490e24..fe7571765d 100644
--- a/jiuwenswarm/agents/swarm/config_specs.py
+++ b/jiuwenswarm/agents/swarm/config_specs.py
@@ -31,7 +31,6 @@ from openjiuwen.agent_teams.schema.deep_agent_spec import (
RailSpec,
SubAgentSpec,
)
-from openjiuwen.agent_teams.rails.builtin_elements import SKILL_USE as CORE_SKILL_USE
from openjiuwen.core.single_agent import AgentCard
from openjiuwen.harness.prompts import resolve_language
from openjiuwen.harness.rails import SkillUseRail
@@ -223,12 +222,6 @@ def _retrieval_enabled(config: dict[str, Any] | None = None) -> bool:
return False
-def _remove_skill_use_rails_for_agentic_retrieval(rails: list[RailSpec]) -> list[RailSpec]:
- """Remove legacy SkillUseRail when agentic retrieval owns discovery."""
- skill_rail_types = {CORE_SKILL_USE, "skill_use", registry.CODE_SKILL_USE}
- return [rail for rail in rails if rail.type not in skill_rail_types]
-
-
def _additional_directories(config: dict[str, Any]) -> list[str]:
"""Resolve project-memory additional directories from config + env."""
react = _config_section(config, "react")
@@ -555,13 +548,9 @@ def build_member_deep_agent_spec(
merged_tools = list(base_spec.tools or [])
merged_tools.extend(tool_specs)
- retrieval_enabled = _retrieval_enabled(config)
- if retrieval_enabled:
- merged_rails = _remove_skill_use_rails_for_agentic_retrieval(merged_rails)
-
update: dict[str, Any] = {"rails": merged_rails, "tools": merged_tools}
if not _is_code_mode(mode):
- update["enable_skill_discovery"] = not retrieval_enabled
+ update["enable_skill_discovery"] = True
subagent_specs = build_member_subagent_specs(config, mode, role)
if subagent_specs:
diff --git a/jiuwenswarm/agents/swarm/providers/code_rails.py b/jiuwenswarm/agents/swarm/providers/code_rails.py
index be1b919d75..68407c579d 100644
--- a/jiuwenswarm/agents/swarm/providers/code_rails.py
+++ b/jiuwenswarm/agents/swarm/providers/code_rails.py
@@ -416,13 +416,15 @@ def build_code_skill_use(params: dict[str, Any], ctx: SwarmBuildContext) -> Any:
from jiuwenswarm.server.runtime.skill import load_execution_disabled_skills
try:
- if is_skill_retrieval_enabled():
- logger.info("[swarm.code_skill_use] skipped: agentic skill retrieval is enabled")
- return None
inp = CodeSkillUseInput.resolve(params, ctx)
+ skill_mode = (
+ SkillUseRail.SKILL_MODE_AUTO_LIST
+ if is_skill_retrieval_enabled()
+ else inp.skill_mode
+ )
return SkillUseRail(
skills_dir=str(get_agent_skills_dir()),
- skill_mode=inp.skill_mode,
+ skill_mode=skill_mode,
include_tools=inp.include_tools,
disabled_skills=load_execution_disabled_skills(),
)
diff --git a/jiuwenswarm/channels/web/frontend/src/App.tsx b/jiuwenswarm/channels/web/frontend/src/App.tsx
index b33be864ab..e301096efd 100644
--- a/jiuwenswarm/channels/web/frontend/src/App.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/App.tsx
@@ -446,14 +446,19 @@ function AppContent() {
}, [request, t, setAvailableModels]);
useEffect(() => {
- if (!FEATURE_APP_UPDATER_UI || !isConnected || startupUpdateCheckRef.current) {
+ if (!FEATURE_APP_UPDATER_UI || !isConnected || !initialDataLoaded || startupUpdateCheckRef.current) {
return;
}
startupUpdateCheckRef.current = true;
- void request('updater.check', { manual: false }).catch((updateError) => {
- console.warn('Startup updater check failed:', updateError);
- });
- }, [isConnected, request]);
+ const timeoutId = window.setTimeout(() => {
+ void request('updater.check', { manual: false }).catch((updateError) => {
+ console.warn('Startup updater check failed:', updateError);
+ });
+ }, 30000);
+ return () => {
+ window.clearTimeout(timeoutId);
+ };
+ }, [initialDataLoaded, isConnected, request]);
const clearRestartAutoCloseTimer = useCallback(() => {
if (restartAutoCloseTimerRef.current != null) {
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsx
index 1b9d2f8dfd..4f9a9d837a 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/MessageList.tsx
@@ -7,7 +7,7 @@
import { useMemo } from 'react';
import { Message, ToolExecution } from '../../types';
import { MessageItem, getMessageActor } from './MessageItem';
-import { ToolGroupDisplay } from './ToolGroupDisplay';
+import { ToolGroupDisplay, collectViewedSkillIds } from './ToolGroupDisplay';
import { useChatStore, useSessionStore } from '../../stores';
import { isTeamMemberCollaborationMessage } from './teamEventUtils';
import { isA2UIClientEventContent } from '../../features/a2ui/a2uiContent';
@@ -51,6 +51,9 @@ type RenderItem =
key: string;
showAvatar: boolean;
executions: ToolExecution[];
+ collapseSkillTreeWhenContentStarts: boolean;
+ turnId: number;
+ viewedSkillIds: string[];
};
/**
@@ -121,18 +124,22 @@ function isFinalMessage(message: Message): boolean {
function buildRenderItems(items: TimelineItem[], isTeamMode: boolean): RenderItem[] {
const renderItems: RenderItem[] = [];
+ let currentTurnId = 0;
let currentSegment = {
toolExecutions: [] as ToolExecution[],
messages: [] as { key: string; message: Message }[],
};
- const flushCurrentSegment = () => {
+ const flushCurrentSegment = (collapseSkillTreeWhenContentStarts = false) => {
if (currentSegment.toolExecutions.length > 0) {
renderItems.push({
type: 'toolGroup',
key: `tool-group-${currentSegment.toolExecutions[0].toolCallId}`,
showAvatar: true,
executions: currentSegment.toolExecutions,
+ collapseSkillTreeWhenContentStarts,
+ turnId: currentTurnId,
+ viewedSkillIds: [],
});
currentSegment.toolExecutions = [];
}
@@ -147,12 +154,12 @@ function buildRenderItems(items: TimelineItem[], isTeamMode: boolean): RenderIte
currentSegment.messages = [];
};
- const flushSegmentIfPresent = () => {
+ const flushSegmentIfPresent = (collapseSkillTreeWhenContentStarts = false) => {
if (
currentSegment.toolExecutions.length > 0 ||
currentSegment.messages.length > 0
) {
- flushCurrentSegment();
+ flushCurrentSegment(collapseSkillTreeWhenContentStarts);
}
};
@@ -174,11 +181,12 @@ function buildRenderItems(items: TimelineItem[], isTeamMode: boolean): RenderIte
showAvatar: true,
message: item.message,
});
+ currentTurnId += 1;
continue;
}
if (isFinalMessage(item.message)) {
- flushSegmentIfPresent();
+ flushSegmentIfPresent(true);
renderItems.push({
type: 'message',
key: item.key,
@@ -193,6 +201,24 @@ function buildRenderItems(items: TimelineItem[], isTeamMode: boolean): RenderIte
flushSegmentIfPresent();
+ const viewedSkillIdsByTurn = new Map<number, string[]>();
+ for (const renderItem of renderItems) {
+ if (renderItem.type !== 'toolGroup') {
+ continue;
+ }
+ const viewedSkillIds = collectViewedSkillIds(renderItem.executions);
+ if (viewedSkillIds.length === 0) {
+ continue;
+ }
+ const current = viewedSkillIdsByTurn.get(renderItem.turnId) || [];
+ viewedSkillIdsByTurn.set(renderItem.turnId, Array.from(new Set([...current, ...viewedSkillIds])));
+ }
+ for (const renderItem of renderItems) {
+ if (renderItem.type === 'toolGroup') {
+ renderItem.viewedSkillIds = viewedSkillIdsByTurn.get(renderItem.turnId) || [];
+ }
+ }
+
if (!isTeamMode) {
for (const renderItem of renderItems) {
if (renderItem.type === 'toolGroup') {
@@ -258,6 +284,8 @@ export function ChatTimelineList({
executions={item.executions}
showAvatar={item.showAvatar}
teamLayout={isTeamMode}
+ collapseSkillTreeWhenContentStarts={item.collapseSkillTreeWhenContentStarts}
+ viewedSkillIds={item.viewedSkillIds}
/>
);
})}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillTreePath.css b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillTreePath.css
index 966620e427..39146c62ae 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillTreePath.css
+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillTreePath.css
@@ -1,7 +1,7 @@
.skill-path {
margin-top: 6px;
border: 1px solid var(--border);
- border-radius: 12px;
+ border-radius: 10px;
background: var(--card);
overflow: hidden;
}
@@ -11,8 +11,8 @@
display: flex;
align-items: center;
justify-content: space-between;
- gap: 12px;
- padding: 8px 12px;
+ gap: 10px;
+ padding: 7px 10px;
background: var(--panel-strong, var(--bg-elevated));
border: none;
cursor: pointer;
@@ -23,254 +23,242 @@
.skill-path__title {
display: flex;
align-items: center;
- gap: 8px;
+ gap: 7px;
min-width: 0;
}
.skill-path__badge {
flex: none;
- font-size: 12px;
+ font-size: 11px;
font-weight: 600;
- padding: 2px 8px;
+ padding: 2px 7px;
border-radius: 999px;
color: var(--accent, #6366f1);
background: var(--accent-subtle, rgba(99, 102, 241, 0.12));
}
.skill-path__query {
- font-size: 12px;
+ font-size: 11px;
color: var(--muted);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
- max-width: 260px;
+ max-width: 360px;
}
.skill-path__meta {
flex: none;
display: flex;
align-items: center;
- gap: 10px;
+ gap: 8px;
font-size: 11px;
color: var(--muted);
}
-.skill-path__live {
- color: var(--accent, #6366f1);
- font-weight: 600;
- animation: skill-path-pulse 1.1s ease-in-out infinite;
-}
-
-@keyframes skill-path-pulse {
- 0%, 100% { opacity: 1; }
- 50% { opacity: 0.45; }
-}
-
.skill-path__chevron {
display: inline-flex;
width: 16px;
height: 16px;
transition: transform 0.18s ease;
}
+
.skill-path__chevron.is-open {
transform: rotate(180deg);
}
.skill-path__body-wrap {
- padding: 8px 12px 12px;
+ padding: 8px 10px 10px;
}
-.skill-path__flow {
- display: flex;
- flex-direction: column;
- gap: 2px;
+.skill-path-tree {
+ display: block;
}
-.skill-path__empty {
- font-size: 12px;
- color: var(--muted);
- padding: 6px 2px;
+.skill-path-tree__canvas {
+ min-width: 0;
+ max-height: 280px;
+ overflow: auto;
+ padding: 6px;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: var(--bg-elevated);
+}
+
+.skill-path-tree__forest {
+ display: grid;
+ gap: 4px;
+}
+
+.skill-path-tree__row {
+ display: grid;
+ gap: 4px;
+ min-width: 0;
}
-.skill-path__row {
- position: relative;
+.skill-path-tree__node {
+ min-width: 0;
display: flex;
- align-items: flex-start;
- gap: 8px;
- padding: 4px 6px 4px 14px;
+ flex-direction: column;
+ gap: 3px;
+ padding: 6px 8px;
border-radius: 8px;
- opacity: 0;
- transform: translateX(-6px);
- transition: opacity 0.28s ease, transform 0.28s ease;
-}
-.skill-path__row.is-revealed {
- opacity: 1;
- transform: translateX(0);
+ border: 1px solid var(--border);
+ background: var(--card);
+ color: var(--text);
+ text-align: left;
+ transition:
+ border-color 0.16s ease,
+ background-color 0.16s ease,
+ box-shadow 0.16s ease,
+ transform 0.16s ease;
}
-.skill-path__rail {
- position: absolute;
- left: 4px;
- top: 0;
- bottom: 0;
- width: 1px;
- background: var(--border);
+.skill-path-tree__node:hover {
+ border-color: var(--accent, #6366f1);
+ box-shadow: 0 0 0 2px var(--accent-subtle, rgba(99, 102, 241, 0.14));
}
-.skill-path__icon {
- flex: none;
- display: inline-flex;
- align-items: center;
- justify-content: center;
- width: 18px;
- height: 18px;
- border-radius: 999px;
- background: var(--bg-elevated);
- border: 1px solid var(--border);
- color: var(--muted);
- margin-top: 1px;
+.skill-path-tree__node--skill {
+ border-color: rgba(37, 99, 235, 0.32);
+ background: rgba(37, 99, 235, 0.06);
}
-.skill-path__icon svg {
- width: 11px;
- height: 11px;
+
+.skill-path-tree__node--skill.is-viewed {
+ border-color: rgba(16, 185, 129, 0.42);
+ background: rgba(16, 185, 129, 0.08);
}
-.skill-path__icon--select { color: var(--ok, #10b981); border-color: var(--ok, #10b981); }
-.skill-path__icon--descend { color: var(--accent, #6366f1); border-color: var(--accent, #6366f1); }
-.skill-path__icon--complete {
- color: #fff;
- background: var(--ok, #10b981);
- border-color: var(--ok, #10b981);
+
+.skill-path-tree__node.is-peeked {
+ border-style: dashed;
}
-.skill-path__body {
- min-width: 0;
- display: flex;
- flex-direction: column;
- gap: 4px;
+.skill-path-tree__node.is-new {
+ animation: skill-path-node-enter 0.46s ease-out both;
}
-.skill-path__line {
+.skill-path-tree__node-main {
display: flex;
align-items: center;
- gap: 8px;
- flex-wrap: wrap;
+ gap: 6px;
+ min-width: 0;
}
-.skill-path__depth {
+.skill-path-tree__type,
+.skill-path-tree__state {
flex: none;
font-size: 10px;
- font-weight: 600;
- color: var(--muted);
- background: var(--bg-elevated);
- border-radius: 4px;
+ font-weight: 700;
+ line-height: 1.3;
+ letter-spacing: 0;
+}
+
+.skill-path-tree__type {
padding: 1px 5px;
+ border-radius: 999px;
+ color: var(--accent, #6366f1);
+ background: var(--accent-subtle, rgba(99, 102, 241, 0.1));
}
-.skill-path__text {
- font-size: 12.5px;
- color: var(--text);
- line-height: 1.4;
+.skill-path-tree__node--skill .skill-path-tree__type {
+ color: #2563eb;
+ background: rgba(37, 99, 235, 0.12);
}
-.skill-path__chips {
- display: flex;
- flex-wrap: wrap;
- gap: 4px;
+.skill-path-tree__node--skill .skill-path-tree__label {
+ color: #1d4ed8;
}
-.skill-path__chip {
- font-size: 11px;
- line-height: 1.5;
- padding: 1px 7px;
- border-radius: 6px;
- color: var(--text);
- background: var(--bg-elevated);
- border: 1px solid var(--border);
- max-width: 220px;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
+.skill-path-tree__node--skill.is-viewed .skill-path-tree__type {
+ color: #059669;
+ background: rgba(16, 185, 129, 0.14);
}
-.skill-path__chip--leaf {
- color: var(--accent, #6366f1);
- border-color: var(--accent, #6366f1);
- background: var(--accent-subtle, rgba(99, 102, 241, 0.1));
+
+.skill-path-tree__node--skill.is-viewed .skill-path-tree__label {
+ color: #047857;
}
-.skill-path__results {
- margin-top: 10px;
- padding-top: 10px;
- border-top: 1px dashed var(--border);
- opacity: 0;
- transition: opacity 0.3s ease;
+.skill-path-tree__state {
+ color: var(--muted);
+ font-weight: 500;
+ margin-left: auto;
}
-.skill-path__results.is-revealed {
- opacity: 1;
+
+.skill-path-tree__label {
+ min-width: 0;
+ font-size: 12px;
+ font-weight: 650;
+ line-height: 1.3;
+ color: var(--text-strong, var(--text));
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
}
-.skill-path__results-title {
+.skill-path-tree__meta {
font-size: 11px;
- font-weight: 600;
+ line-height: 1.3;
color: var(--muted);
- margin-bottom: 6px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
}
-.skill-path__results-list {
- list-style: none;
- margin: 0;
- padding: 0;
- display: flex;
- flex-direction: column;
+.skill-path-tree__children {
+ display: grid;
gap: 4px;
}
-.skill-path__result {
- display: flex;
- align-items: flex-start;
- gap: 8px;
- padding: 5px 8px;
- border-radius: 8px;
- background: var(--bg-elevated);
- border: 1px solid transparent;
-}
-.skill-path__result.is-top {
- border-color: var(--ok, #10b981);
- background: var(--ok-subtle, rgba(16, 185, 129, 0.1));
-}
-
-.skill-path__result-rank {
- flex: none;
- font-size: 11px;
- font-weight: 700;
+.skill-path-tree__more {
+ width: fit-content;
+ max-width: 100%;
+ margin-left: 14px;
+ padding: 4px 8px;
+ border: 1px dashed var(--border);
+ border-radius: 7px;
+ background: transparent;
color: var(--muted);
- margin-top: 1px;
+ font-size: 11px;
+ cursor: pointer;
}
-.skill-path__result.is-top .skill-path__result-rank {
- color: var(--ok, #10b981);
+
+.skill-path-tree__more:hover {
+ color: var(--accent, #6366f1);
+ border-color: var(--accent, #6366f1);
+ background: var(--accent-subtle, rgba(99, 102, 241, 0.08));
}
-.skill-path__result-main {
- min-width: 0;
- display: flex;
- flex-direction: column;
- gap: 1px;
+@keyframes skill-path-node-enter {
+ 0% {
+ opacity: 0;
+ transform: translateY(-4px);
+ box-shadow: 0 0 0 2px var(--accent-subtle, rgba(99, 102, 241, 0.14));
+ }
+
+ 55% {
+ opacity: 1;
+ transform: translateY(0);
+ box-shadow: 0 0 0 2px var(--accent-subtle, rgba(99, 102, 241, 0.14));
+ }
+
+ 100% {
+ opacity: 1;
+ transform: translateY(0);
+ box-shadow: none;
+ }
}
-.skill-path__result-name {
- font-size: 12.5px;
- font-weight: 600;
- color: var(--text-strong, var(--text));
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
+@media (prefers-reduced-motion: reduce) {
+ .skill-path-tree__node.is-new {
+ animation: none;
+ }
}
-.skill-path__result-desc {
- font-size: 11.5px;
- color: var(--muted);
- line-height: 1.4;
- display: -webkit-box;
- -webkit-line-clamp: 2;
- -webkit-box-orient: vertical;
- overflow: hidden;
+@media (max-width: 860px) {
+ .skill-path__meta {
+ display: none;
+ }
+
+ .skill-path-tree__canvas {
+ max-height: 240px;
+ }
}
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillTreePath.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillTreePath.tsx
index d1cb3f3a16..498fe8173e 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillTreePath.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/SkillTreePath.tsx
@@ -1,181 +1,511 @@
/**
- * SkillTreePath 组件
+ * SkillTreePath
*
- * 当 symphony 技能检索工具在对话中被触发时,把后端下发的
- * 「技能树路径」按遍历顺序逐级回放展示,营造路径流转效果,最终落到命中的技能。
- *
- * 数据来源:工具结果 raw_output.skill_tree(见 types/skillTree.ts)。
- * 纯 SVG/DOM 实现,不引入第三方图表库。
+ * Inline visualization for agentic skill retrieval. A tool group can contain
+ * multiple skill_branch_explore / skill_branch_peek calls; this component folds
+ * them into one horizontal browsing tree.
*/
import { useEffect, useMemo, useRef, useState } from 'react';
import clsx from 'clsx';
-import type { SkillTreePath as SkillTreePathData, SkillTreeStep } from '../../types/skillTree';
+import type {
+ SkillTreeCandidate,
+ SkillTreeNamedId,
+ SkillTreePath as SkillTreePathData,
+} from '../../types/skillTree';
import './SkillTreePath.css';
interface SkillTreePathProps {
- tree: SkillTreePathData;
- /** 流转动画每步间隔(ms),设 0 关闭动画直接全量展示 */
+ tree?: SkillTreePathData;
+ trees?: SkillTreePathData[];
+ autoCollapse?: boolean;
+ viewedSkillIds?: string[];
+ /** Kept for compatibility with the previous path replay component. */
stepIntervalMs?: number;
}
-type StepKind = 'explore' | 'select' | 'descend' | 'complete';
+type BrowseNodeKind = 'branch' | 'skill';
+
+interface BrowseNode {
+ id: string;
+ label: string;
+ kind: BrowseNodeKind;
+ depth: number;
+ parentId?: string;
+ children: string[];
+ sequence: number;
+ exploreCount: number;
+ peekCount: number;
+ selectableCount?: number | null;
+ hiddenBranchIds: Set<string>;
+ candidate?: SkillTreeCandidate;
+}
+
+interface BrowseGraph {
+ nodes: Map<string, BrowseNode>;
+ rootIds: string[];
+ exploreCount: number;
+ peekCount: number;
+ exposedSkillCount: number;
+ foldedBranchCount: number;
+ queryLabel: string;
+}
+
+const MAX_VISIBLE_CHILDREN = 8;
+
+function collectTrees(tree?: SkillTreePathData, trees?: SkillTreePathData[]): SkillTreePathData[] {
+ const result: SkillTreePathData[] = [];
+ if (tree) {
+ result.push(tree);
+ }
+ if (trees) {
+ result.push(...trees.filter(Boolean));
+ }
+ return result;
+}
+
+function normalizeId(value: string | undefined | null, fallback = 'ROOT'): string {
+ const text = String(value || '').trim();
+ return text || fallback;
+}
+
+function normalizeLookupKey(value: string | undefined | null): string {
+ return String(value || '').trim().toLowerCase();
+}
+
+function buildViewedSkillKeySet(viewedSkillIds?: string[]): Set<string> {
+ const out = new Set<string>();
+ for (const id of viewedSkillIds || []) {
+ const key = normalizeLookupKey(id);
+ if (key) {
+ out.add(key);
+ }
+ }
+ return out;
+}
+
+function displayLabel(item: SkillTreeNamedId): string {
+ return item.label || item.id;
+}
+
+function isPeekTree(tree: SkillTreePathData): boolean {
+ return tree.query.toLowerCase().includes('skill_branch_peek');
+}
+
+function isExploreTree(tree: SkillTreePathData): boolean {
+ return tree.query.toLowerCase().includes('skill_branch_explore');
+}
+
+function addCandidateLookup(
+ lookup: Map<string, SkillTreeCandidate>,
+ key: string | undefined,
+ candidate: SkillTreeCandidate
+) {
+ const normalized = normalizeLookupKey(key);
+ if (normalized && !lookup.has(normalized)) {
+ lookup.set(normalized, candidate);
+ }
+}
+
+function buildCandidateLookup(trees: SkillTreePathData[]): Map<string, SkillTreeCandidate> {
+ const lookup = new Map<string, SkillTreeCandidate>();
+ for (const tree of trees) {
+ for (const candidate of tree.candidates || []) {
+ addCandidateLookup(lookup, candidate.worker_id, candidate);
+ addCandidateLookup(lookup, candidate.label, candidate);
+ addCandidateLookup(lookup, candidate.path?.[candidate.path.length - 1], candidate);
+ }
+ }
+ return lookup;
+}
-interface FlowRow {
- key: string;
- step: SkillTreeStep;
- kind: StepKind;
+function buildTouchedBranchIds(trees: SkillTreePathData[]): Set<string> {
+ const ids = new Set<string>();
+ for (const tree of trees) {
+ for (const step of tree.steps || []) {
+ ids.add(normalizeId(step.node_id));
+ }
+ }
+ return ids;
}
-function classifyStep(step: SkillTreeStep): StepKind | null {
- switch (step.event_type) {
- case 'fragment_built':
- return 'explore';
- case 'fragment_selected':
- return 'select';
- case 'fragment_continue':
- return 'descend';
- case 'search_complete':
- return 'complete';
- // reduce_complete 等内部归并事件不展示,避免噪声
- default:
- return null;
+function formatQueryLabel(trees: SkillTreePathData[]): string {
+ if (trees.length === 0) {
+ return '';
+ }
+ if (trees.length === 1) {
+ const query = trees[0].query;
+ const target = query.includes(':') ? query.split(':').slice(1).join(':').trim() : '';
+ if (isExploreTree(trees[0])) {
+ return target ? `展开 ${target}` : '展开分支';
+ }
+ if (isPeekTree(trees[0])) {
+ return target ? `窥探 ${target}` : '窥探分支';
+ }
+ return query;
}
+ const exploreCount = trees.filter(isExploreTree).length;
+ const peekCount = trees.filter(isPeekTree).length;
+ return `${trees.length} 次浏览 · ${exploreCount} 展开 · ${peekCount} 窥探`;
}
-function buildRows(steps: SkillTreeStep[]): FlowRow[] {
- const rows: FlowRow[] = [];
- for (const step of steps) {
- const kind = classifyStep(step);
- if (!kind) continue;
- // 探查节点若只有 0/1 个可选项,信息量低,跳过以突出真正的分支决策
- if (kind === 'explore' && (step.selectable_count ?? 0) <= 1 && step.selected.length === 0) {
- continue;
+function buildBrowseGraph(trees: SkillTreePathData[]): BrowseGraph {
+ const nodes = new Map<string, BrowseNode>();
+ const candidateLookup = buildCandidateLookup(trees);
+ const touchedBranchIds = buildTouchedBranchIds(trees);
+ let sequence = 0;
+ let exploreCount = 0;
+ let peekCount = 0;
+
+ const ensureNode = (
+ id: string,
+ label: string,
+ kind: BrowseNodeKind,
+ depth: number,
+ parentId?: string,
+ candidate?: SkillTreeCandidate
+ ): BrowseNode => {
+ const normalizedId = normalizeId(id);
+ const existing = nodes.get(normalizedId);
+ if (existing) {
+ if (!existing.label && label) {
+ existing.label = label;
+ }
+ if (parentId && !existing.parentId) {
+ existing.parentId = parentId;
+ }
+ if (candidate && !existing.candidate) {
+ existing.candidate = candidate;
+ }
+ existing.depth = Math.min(existing.depth, depth);
+ return existing;
+ }
+ const node: BrowseNode = {
+ id: normalizedId,
+ label: label || normalizedId,
+ kind,
+ depth,
+ parentId,
+ children: [],
+ sequence,
+ exploreCount: 0,
+ peekCount: 0,
+ hiddenBranchIds: new Set<string>(),
+ candidate,
+ };
+ sequence += 1;
+ nodes.set(normalizedId, node);
+ return node;
+ };
+
+ const addChild = (parent: BrowseNode, child: BrowseNode) => {
+ if (!parent.children.includes(child.id)) {
+ parent.children.push(child.id);
+ }
+ if (!child.parentId) {
+ child.parentId = parent.id;
+ }
+ };
+
+ for (const tree of trees) {
+ const treeIsPeek = isPeekTree(tree);
+ const treeIsExplore = isExploreTree(tree);
+ let candidateCursor = 0;
+ for (const step of tree.steps || []) {
+ if (step.event_type !== 'fragment_built') {
+ continue;
+ }
+
+ const stepCandidateCount =
+ typeof step.candidate_count === 'number'
+ ? Math.max(0, step.candidate_count)
+ : 0;
+ const stepCandidates = treeIsExplore
+ ? (tree.candidates || []).slice(candidateCursor, candidateCursor + stepCandidateCount)
+ : [];
+ if (treeIsExplore) {
+ candidateCursor += stepCandidateCount;
+ }
+
+ const node = ensureNode(
+ normalizeId(step.node_id),
+ step.label || step.node_id,
+ 'branch',
+ step.depth
+ );
+ node.selectableCount = step.selectable_count;
+
+ if (treeIsPeek) {
+ node.peekCount += 1;
+ peekCount += 1;
+ continue;
+ }
+
+ if (!treeIsExplore) {
+ continue;
+ }
+
+ node.exploreCount += 1;
+ exploreCount += 1;
+
+ for (const branch of step.branches || []) {
+ const branchId = normalizeId(branch.id);
+ if (!touchedBranchIds.has(branchId)) {
+ node.hiddenBranchIds.add(branchId);
+ continue;
+ }
+ const child = ensureNode(
+ branchId,
+ displayLabel(branch),
+ 'branch',
+ step.depth + 1,
+ node.id
+ );
+ addChild(node, child);
+ }
+
+ for (const [leafIndex, leaf] of (step.leaves || []).entries()) {
+ const leafId = normalizeId(leaf.id, displayLabel(leaf));
+ const candidate =
+ candidateLookup.get(normalizeLookupKey(leafId)) ||
+ candidateLookup.get(normalizeLookupKey(leaf.label)) ||
+ stepCandidates[leafIndex];
+ const child = ensureNode(
+ leafId,
+ candidate?.label || displayLabel(leaf),
+ 'skill',
+ step.depth + 1,
+ node.id,
+ candidate
+ );
+ addChild(node, child);
+ }
}
- rows.push({ key: `${step.order}-${step.event_type}`, step, kind });
}
- return rows;
-}
-
-const KIND_ICON: Record<StepKind, JSX.Element> = {
- explore: (
- <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" aria-hidden="true">
- <circle cx="7" cy="7" r="4.2" />
- <path strokeLinecap="round" d="M10.2 10.2 13 13" />
- </svg>
- ),
- select: (
- <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" aria-hidden="true">
- <path strokeLinecap="round" strokeLinejoin="round" d="M3.5 8.2 6.4 11l6.1-6.4" />
- </svg>
- ),
- descend: (
- <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" aria-hidden="true">
- <path strokeLinecap="round" strokeLinejoin="round" d="M8 3v8.4M4.8 8.6 8 11.8l3.2-3.2" />
- </svg>
- ),
- complete: (
- <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" aria-hidden="true">
- <circle cx="8" cy="8" r="5.2" />
- <path strokeLinecap="round" strokeLinejoin="round" d="M5.6 8.1 7.3 9.8l3.3-3.6" />
- </svg>
- ),
-};
-
-function StepRow({ row, revealed }: { row: FlowRow; revealed: boolean }) {
- const { step, kind } = row;
- const indent = Math.min(step.depth, 6) * 16;
+
+ const rootIds = Array.from(nodes.values())
+ .filter((node) => !node.parentId || !nodes.has(node.parentId))
+ .sort((left, right) => left.sequence - right.sequence)
+ .map((node) => node.id);
+ const exposedSkillCount = Array.from(nodes.values()).filter((node) => node.kind === 'skill').length;
+ const foldedBranchCount = Array.from(nodes.values()).reduce(
+ (total, node) => total + node.hiddenBranchIds.size,
+ 0
+ );
+
+ return {
+ nodes,
+ rootIds,
+ exploreCount,
+ peekCount,
+ exposedSkillCount,
+ foldedBranchCount,
+ queryLabel: formatQueryLabel(trees),
+ };
+}
+
+function nodeStateLabel(node: BrowseNode): string {
+ if (node.kind === 'skill') {
+ return '已披露技能';
+ }
+ if (node.exploreCount > 0) {
+ return '已展开';
+ }
+ if (node.peekCount > 0) {
+ return '已窥探';
+ }
+ return '已披露分支';
+}
+
+function nodeTitle(node: BrowseNode): string {
+ if (node.kind === 'skill') {
+ return node.candidate?.description || node.id;
+ }
+ return node.id;
+}
+
+interface BrowseNodeViewProps {
+ graph: BrowseGraph;
+ nodeId: string;
+ expandedNodeIds: Set<string>;
+ newNodeIds: Set<string>;
+ viewedSkillKeys: Set<string>;
+ onToggleExpanded: (nodeId: string) => void;
+}
+
+function BrowseNodeView({
+ graph,
+ nodeId,
+ expandedNodeIds,
+ newNodeIds,
+ viewedSkillKeys,
+ onToggleExpanded,
+}: BrowseNodeViewProps) {
+ const node = graph.nodes.get(nodeId);
+ if (!node) {
+ return null;
+ }
+
+ const children = node.children
+ .map((id) => graph.nodes.get(id))
+ .filter((child): child is BrowseNode => Boolean(child))
+ .sort((left, right) => left.sequence - right.sequence);
+ const expanded = expandedNodeIds.has(node.id);
+ const visibleChildren = expanded ? children : children.slice(0, MAX_VISIBLE_CHILDREN);
+ const hiddenChildCount = Math.max(0, children.length - visibleChildren.length);
+ const hasChildren = children.length > 0;
+ const hasFoldedBranches = node.hiddenBranchIds.size > 0;
+ const isNewNode = newNodeIds.has(node.id);
+ const isViewedSkill = node.kind === 'skill' && (
+ viewedSkillKeys.has(normalizeLookupKey(node.id)) ||
+ viewedSkillKeys.has(normalizeLookupKey(node.label)) ||
+ viewedSkillKeys.has(normalizeLookupKey(node.candidate?.worker_id)) ||
+ viewedSkillKeys.has(normalizeLookupKey(node.candidate?.label)) ||
+ viewedSkillKeys.has(normalizeLookupKey(node.candidate?.path?.[node.candidate.path.length - 1]))
+ );
+ const nodeMeta = node.kind === 'skill'
+ ? node.candidate?.description || node.candidate?.worker_id || node.id
+ : hasChildren
+ ? `${children.length} 个已展开子项`
+ : hasFoldedBranches
+ ? `${node.hiddenBranchIds.size} 个未查看分支已折叠`
+ : '暂无展开子项';
return (
- <div
- className={clsx('skill-path__row', `skill-path__row--${kind}`, revealed && 'is-revealed')}
- style={{ marginLeft: indent }}
- data-depth={step.depth}
- >
- <span className="skill-path__rail" aria-hidden="true" />
- <span className={clsx('skill-path__icon', `skill-path__icon--${kind}`)}>{KIND_ICON[kind]}</span>
- <span className="skill-path__body">
- <span className="skill-path__line">
- <span className="skill-path__depth">Lv.{step.depth}</span>
- <span className="skill-path__text">{stepText(row)}</span>
- </span>
- {step.selected.length > 0 && (
- <span className="skill-path__chips">
- {step.selected.map((node) => (
- <span key={node.id} className="skill-path__chip" title={node.id}>
- {node.label || node.id}
- </span>
- ))}
- </span>
+ <div className="skill-path-tree__row" style={{ paddingLeft: `${Math.min(node.depth, 6) * 14}px` }}>
+ <div
+ className={clsx(
+ 'skill-path-tree__node',
+ `skill-path-tree__node--${node.kind}`,
+ node.exploreCount > 0 && 'is-explored',
+ node.peekCount > 0 && node.exploreCount === 0 && 'is-peeked',
+ isNewNode && 'is-new',
+ isViewedSkill && 'is-viewed'
)}
- {step.leaves.length > 0 && (
- <span className="skill-path__chips">
- {step.leaves.map((leaf) => (
- <span key={leaf.id} className="skill-path__chip skill-path__chip--leaf" title={leaf.id}>
- {leaf.label || leaf.id}
- </span>
- ))}
+ title={nodeTitle(node)}
+ >
+ <div className="skill-path-tree__node-main">
+ <span className="skill-path-tree__type">
+ {node.kind === 'skill' ? '技能' : '分支'}
</span>
- )}
- </span>
+ <span className="skill-path-tree__label">{node.label}</span>
+ <span className="skill-path-tree__state">
+ {isViewedSkill ? '已查看' : nodeStateLabel(node)}
+ </span>
+ </div>
+ {nodeMeta && <div className="skill-path-tree__meta">{nodeMeta}</div>}
+ </div>
+
+ {hasChildren && (
+ <div className="skill-path-tree__children">
+ {visibleChildren.map((child) => (
+ <BrowseNodeView
+ key={child.id}
+ graph={graph}
+ nodeId={child.id}
+ expandedNodeIds={expandedNodeIds}
+ newNodeIds={newNodeIds}
+ viewedSkillKeys={viewedSkillKeys}
+ onToggleExpanded={onToggleExpanded}
+ />
+ ))}
+ {hiddenChildCount > 0 && (
+ <button
+ type="button"
+ className="skill-path-tree__more"
+ onClick={() => onToggleExpanded(node.id)}
+ >
+ 展开其余 {hiddenChildCount} 项
+ </button>
+ )}
+ {hiddenChildCount === 0 && children.length > MAX_VISIBLE_CHILDREN && (
+ <button
+ type="button"
+ className="skill-path-tree__more"
+ onClick={() => onToggleExpanded(node.id)}
+ >
+ 收起部分子项
+ </button>
+ )}
+ </div>
+ )}
</div>
);
}
-function stepText(row: FlowRow): string {
- const { step, kind } = row;
- const name = step.label || step.node_id || '根节点';
- switch (kind) {
- case 'explore':
- return step.selectable_count != null
- ? `探查「${name}」 · ${step.selectable_count} 个候选分支`
- : `探查「${name}」`;
- case 'select':
- return `在「${name}」选择分支`;
- case 'descend':
- return step.leaves.length > 0 ? '下钻并命中技能叶子' : '下钻到子分支';
- case 'complete':
- return `检索完成 · 命中 ${step.candidate_count ?? 0} 个技能`;
- default:
- return name;
- }
-}
+export function SkillTreePath({
+ tree,
+ trees,
+ autoCollapse = false,
+ viewedSkillIds,
+ stepIntervalMs = 0,
+}: SkillTreePathProps) {
+ void stepIntervalMs;
+ const allTrees = useMemo(() => collectTrees(tree, trees), [tree, trees]);
+ const graph = useMemo(() => buildBrowseGraph(allTrees), [allTrees]);
+ const [accumulatedViewedSkillIds, setAccumulatedViewedSkillIds] = useState<string[]>(() => viewedSkillIds || []);
+ const viewedSkillKeys = useMemo(
+ () => buildViewedSkillKeySet(accumulatedViewedSkillIds),
+ [accumulatedViewedSkillIds]
+ );
+ const [collapsed, setCollapsed] = useState(autoCollapse);
+ const [expandedNodeIds, setExpandedNodeIds] = useState<Set<string>>(() => new Set());
+ const [newNodeIds, setNewNodeIds] = useState<Set<string>>(() => new Set());
+ const previousNodeIdsRef = useRef<Set<string> | null>(null);
-export function SkillTreePath({ tree, stepIntervalMs = 320 }: SkillTreePathProps) {
- const rows = useMemo(() => buildRows(tree.steps), [tree.steps]);
- const [revealCount, setRevealCount] = useState(stepIntervalMs > 0 ? 0 : rows.length);
- const [collapsed, setCollapsed] = useState(false);
- const timerRef = useRef<number | null>(null);
+ useEffect(() => {
+ if (!viewedSkillIds || viewedSkillIds.length === 0) {
+ return;
+ }
+ setAccumulatedViewedSkillIds((current) => {
+ const next = Array.from(new Set([...current, ...viewedSkillIds]));
+ return next.length === current.length ? current : next;
+ });
+ }, [viewedSkillIds]);
+
+ useEffect(() => {
+ if (autoCollapse) {
+ setCollapsed(true);
+ }
+ }, [autoCollapse, graph.queryLabel]);
useEffect(() => {
- if (stepIntervalMs <= 0) {
- setRevealCount(rows.length);
+ const nextNodeIds = new Set(graph.nodes.keys());
+ const previousNodeIds = previousNodeIdsRef.current;
+ previousNodeIdsRef.current = nextNodeIds;
+
+ if (!previousNodeIds) {
return;
}
- setRevealCount(0);
- if (rows.length === 0) return;
- timerRef.current = window.setInterval(() => {
- setRevealCount((current) => {
- if (current >= rows.length) {
- if (timerRef.current != null) {
- window.clearInterval(timerRef.current);
- timerRef.current = null;
- }
- return current;
- }
- return current + 1;
- });
- }, stepIntervalMs);
- return () => {
- if (timerRef.current != null) {
- window.clearInterval(timerRef.current);
- timerRef.current = null;
+
+ const addedNodeIds = Array.from(nextNodeIds).filter((nodeId) => !previousNodeIds.has(nodeId));
+ if (addedNodeIds.length === 0) {
+ setNewNodeIds((current) => (current.size > 0 ? new Set() : current));
+ return;
+ }
+
+ setNewNodeIds(new Set(addedNodeIds));
+ const timer = window.setTimeout(() => {
+ setNewNodeIds((current) => (current.size > 0 ? new Set() : current));
+ }, 520);
+ return () => window.clearTimeout(timer);
+ }, [graph]);
+
+ const toggleExpanded = (nodeId: string) => {
+ setExpandedNodeIds((current) => {
+ const next = new Set(current);
+ if (next.has(nodeId)) {
+ next.delete(nodeId);
+ } else {
+ next.add(nodeId);
}
- };
- }, [rows.length, stepIntervalMs]);
+ return next;
+ });
+ };
- const allRevealed = revealCount >= rows.length;
- const candidates = tree.candidates ?? [];
+ if (allTrees.length === 0 || graph.nodes.size === 0) {
+ return null;
+ }
return (
<div className="skill-path animate-rise" data-testid="skill-tree-path">
@@ -186,13 +516,18 @@ export function SkillTreePath({ tree, stepIntervalMs = 320 }: SkillTreePathProps
aria-expanded={!collapsed}
>
<span className="skill-path__title">
- <span className="skill-path__badge">技能树路径</span>
- {tree.query && <span className="skill-path__query" title={tree.query}>{tree.query}</span>}
+ <span className="skill-path__badge">技能检索树</span>
+ {graph.queryLabel && (
+ <span className="skill-path__query" title={graph.queryLabel}>
+ {graph.queryLabel}
+ </span>
+ )}
</span>
<span className="skill-path__meta">
- {!allRevealed && <span className="skill-path__live">流转中…</span>}
- <span>{tree.candidate_count} 个技能</span>
- {tree.elapsed_ms != null && <span>{Math.round(tree.elapsed_ms)}ms</span>}
+ <span>{graph.exploreCount} 次展开</span>
+ <span>{graph.peekCount} 次窥探</span>
+ <span>{graph.exposedSkillCount} 个披露技能</span>
+ {graph.foldedBranchCount > 0 && <span>{graph.foldedBranchCount} 个分支折叠</span>}
<span className={clsx('skill-path__chevron', !collapsed && 'is-open')} aria-hidden="true">
<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.8">
<path strokeLinecap="round" strokeLinejoin="round" d="m6.5 8 3.5 4 3.5-4" />
@@ -203,39 +538,23 @@ export function SkillTreePath({ tree, stepIntervalMs = 320 }: SkillTreePathProps
{!collapsed && (
<div className="skill-path__body-wrap">
- <div className="skill-path__flow">
- {rows.length === 0 ? (
- <div className="skill-path__empty">未记录到路径遍历步骤。</div>
- ) : (
- rows.map((row, index) => (
- <StepRow key={row.key} row={row} revealed={index < revealCount} />
- ))
- )}
- </div>
-
- {candidates.length > 0 && (
- <div className={clsx('skill-path__results', allRevealed && 'is-revealed')}>
- <div className="skill-path__results-title">命中技能</div>
- <ul className="skill-path__results-list">
- {candidates.map((candidate) => (
- <li
- key={`${candidate.rank}-${candidate.worker_id || candidate.label}`}
- className={clsx('skill-path__result', candidate.selected && 'is-top')}
- >
- <span className="skill-path__result-rank">#{candidate.rank}</span>
- <span className="skill-path__result-main">
- <span className="skill-path__result-name" title={candidate.worker_id}>
- {candidate.label}
- </span>
- {candidate.description && (
- <span className="skill-path__result-desc">{candidate.description}</span>
- )}
- </span>
- </li>
+ <div className="skill-path-tree">
+ <div className="skill-path-tree__canvas">
+ <div className="skill-path-tree__forest">
+ {graph.rootIds.map((rootId) => (
+ <BrowseNodeView
+ key={rootId}
+ graph={graph}
+ nodeId={rootId}
+ expandedNodeIds={expandedNodeIds}
+ newNodeIds={newNodeIds}
+ viewedSkillKeys={viewedSkillKeys}
+ onToggleExpanded={toggleExpanded}
+ />
))}
- </ul>
+ </div>
</div>
- )}
+ </div>
</div>
)}
</div>
diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ToolGroupDisplay.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ToolGroupDisplay.tsx
index 6e15b09f25..5e35d45cce 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ToolGroupDisplay.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/ToolGroupDisplay.tsx
@@ -16,6 +16,8 @@ interface ToolGroupDisplayProps {
executions: ToolExecution[];
showAvatar?: boolean;
teamLayout?: boolean;
+ collapseSkillTreeWhenContentStarts?: boolean;
+ viewedSkillIds?: string[];
}
interface ToolDetailModalProps {
@@ -84,6 +86,67 @@ function getExecutionLabel(execution: ToolExecution, sessionCompletedLabel: stri
return execution.toolCall.name;
}
+function isSkillToolName(name: string): boolean {
+ const normalized = name.trim().toLowerCase();
+ const compact = normalized.replace(/[\s-]+/g, '_');
+ return (
+ compact === 'skill_tool' ||
+ compact.endsWith('.skill_tool') ||
+ compact.endsWith('/skill_tool') ||
+ compact.endsWith(':skill_tool')
+ );
+}
+
+function addViewedSkillName(out: Set<string>, value: unknown) {
+ if (typeof value !== 'string') {
+ return;
+ }
+ const skillName = value.trim();
+ if (skillName) {
+ out.add(skillName);
+ }
+}
+
+function addViewedSkillNameFromArgs(out: Set<string>, args: Record<string, unknown> | null | undefined) {
+ if (!args) {
+ return;
+ }
+ addViewedSkillName(out, args.skill_name);
+ addViewedSkillName(out, args.skillName);
+}
+
+function addViewedSkillNameFromText(out: Set<string>, value: string | undefined) {
+ const text = String(value || '').trim();
+ if (!text) {
+ return;
+ }
+
+ try {
+ const parsed = JSON.parse(text);
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ addViewedSkillNameFromArgs(out, parsed as Record<string, unknown>);
+ return;
+ }
+ } catch {
+ // formatted_args is often a display string, not JSON.
+ }
+
+ const match = text.match(/["']?skill[_-]?name["']?\s*[:=]\s*["']?([^"',}\]\s]+)/i);
+ addViewedSkillName(out, match?.[1]);
+}
+
+export function collectViewedSkillIds(executions: ToolExecution[]): string[] {
+ const out = new Set<string>();
+ executions.forEach((execution) => {
+ if (!isSkillToolName(execution.toolCall.name)) {
+ return;
+ }
+ addViewedSkillNameFromArgs(out, execution.toolCall.arguments);
+ addViewedSkillNameFromText(out, execution.toolCall.formatted_args);
+ });
+ return Array.from(out);
+}
+
function ToolDetailModal({ execution, onClose }: ToolDetailModalProps) {
const { t } = useTranslation();
const { toolCall, result, status } = execution;
@@ -318,6 +381,8 @@ export function ToolGroupDisplay({
executions,
showAvatar = true,
teamLayout = false,
+ collapseSkillTreeWhenContentStarts = false,
+ viewedSkillIds: turnViewedSkillIds = [],
}: ToolGroupDisplayProps) {
const { t } = useTranslation();
const scrollRef = useRef<HTMLDivElement>(null);
@@ -370,6 +435,13 @@ export function ToolGroupDisplay({
const skillTreeExecutions = visibleExecutions.filter(
(execution) => execution.result?.skillTree
);
+ const skillTrees = skillTreeExecutions
+ .map((execution) => execution.result?.skillTree)
+ .filter((tree): tree is NonNullable<typeof tree> => Boolean(tree));
+ const viewedSkillIds = Array.from(new Set([
+ ...turnViewedSkillIds,
+ ...collectViewedSkillIds(executions),
+ ]));
if (visibleExecutions.length === 0) {
return null;
}
@@ -424,9 +496,13 @@ export function ToolGroupDisplay({
)}
</div>
- {skillTreeExecutions.map((execution) => (
- <SkillTreePath key={`skill-tree-${execution.toolCallId}`} tree={execution.result!.skillTree!} />
- ))}
+ {skillTrees.length > 0 && (
+ <SkillTreePath
+ trees={skillTrees}
+ viewedSkillIds={viewedSkillIds}
+ autoCollapse={collapseSkillTreeWhenContentStarts}
+ />
+ )}
</div>
</div>
);
diff --git a/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx b/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx
index f96a4b7956..51865e26d6 100644
--- a/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx
+++ b/jiuwenswarm/channels/web/frontend/src/components/SkillPanel/index.tsx
@@ -19,6 +19,8 @@ import { Switch } from "../Switch";
/** 刷新会 git pull marketplace,略放宽;普通进页单次 RPC 一般很快。 */
const SKILLS_FETCH_TIMEOUT_REFRESH_MS = 60_000;
const SKILLS_FETCH_TIMEOUT_NORMAL_MS = 30_000;
+const SKILL_RETRIEVAL_RUNNING_POLL_MS = 10_000;
+const SKILL_RETRIEVAL_IDLE_POLL_MS = 5 * 60_000;
type SkillItem = {
name: string;
@@ -83,12 +85,14 @@ type SkillRetrievalStatus = {
build_finished_at?: string;
build_elapsed_seconds?: number;
build_cancel_requested?: boolean;
- build_logs?: Array<{
- time?: string;
- stage?: string;
- status?: string;
- message?: string;
- }>;
+ build_logs?: SkillRetrievalBuildLog[];
+};
+
+type SkillRetrievalBuildLog = {
+ time?: string;
+ stage?: string;
+ status?: string;
+ message?: string;
};
type SkillRetrievalTreeResponse = {
@@ -199,6 +203,226 @@ function findSkillIndexNode(nodes: SkillIndexNode[], cid: string | null): SkillI
return nodes.find((node) => node.cid === cid) || null;
}
+type SkillIndexBuildPhaseState = "done" | "active" | "pending" | "failed" | "cancelled";
+
+type SkillIndexBuildPhase = {
+ key: string;
+ title: string;
+ detail: string;
+ state: SkillIndexBuildPhaseState;
+};
+
+function getSkillIndexBuildStageLabel(
+ stage: string | undefined,
+ t: (key: string, options?: Record<string, unknown>) => string
+): string {
+ const key = String(stage || "").trim();
+ if (!key) return t('skills.retrieval.buildStageUnknown');
+ const known: Record<string, string> = {
+ queued: 'queued',
+ scan: 'scan',
+ llm_check: 'llmCheck',
+ build: 'buildTree',
+ publish: 'publish',
+ reuse: 'reuse',
+ success: 'success',
+ failed: 'failed',
+ timeout: 'timeout',
+ llm_config: 'llmConfig',
+ cancelled: 'cancelled',
+ interrupted: 'interrupted',
+ };
+ const mapped = known[key];
+ return mapped ? t(`skills.retrieval.buildStages.${mapped}`) : key;
+}
+
+function getSkillIndexBuildPhaseState(
+ phaseKey: string,
+ currentStage: string,
+ buildStatus: string
+): SkillIndexBuildPhaseState {
+ const order = ["queued", "scan", "llm_check", "build", "publish", "success"];
+ const normalizedStage = order.includes(currentStage)
+ ? currentStage
+ : currentStage === "llm_config"
+ ? "llm_check"
+ : ["failed", "timeout", "interrupted", "cancelled"].includes(currentStage)
+ ? "build"
+ : buildStatus === "success"
+ ? "success"
+ : "queued";
+ const currentIndex = order.indexOf(normalizedStage);
+ const phaseIndex = order.indexOf(phaseKey);
+ if (buildStatus === "failed") {
+ if (phaseKey === normalizedStage) return "failed";
+ if (phaseIndex < currentIndex) return "done";
+ return "pending";
+ }
+ if (buildStatus === "cancelled") {
+ if (phaseKey === normalizedStage) return "cancelled";
+ if (phaseIndex < currentIndex) return "done";
+ return "pending";
+ }
+ if (buildStatus === "success") return "done";
+ if (phaseIndex < currentIndex) return "done";
+ if (phaseIndex === currentIndex) return "active";
+ return "pending";
+}
+
+function buildSkillIndexBuildPhases(
+ status: SkillRetrievalStatus | null,
+ t: (key: string, options?: Record<string, unknown>) => string
+): SkillIndexBuildPhase[] {
+ const buildStatus = String(status?.build_status || "idle");
+ const currentStage = String(status?.build_stage || (buildStatus === "success" ? "success" : "queued"));
+ const installedCount = status?.installed_count ?? status?.installed_enabled_count ?? 0;
+ const indexedCount = status?.indexed_count ?? 0;
+ const base = [
+ {
+ key: "queued",
+ title: t('skills.retrieval.buildPipeline.queued.title'),
+ detail: t('skills.retrieval.buildPipeline.queued.detail'),
+ },
+ {
+ key: "scan",
+ title: t('skills.retrieval.buildPipeline.scan.title'),
+ detail: t('skills.retrieval.buildPipeline.scan.detail', { count: installedCount }),
+ },
+ {
+ key: "llm_check",
+ title: t('skills.retrieval.buildPipeline.llmCheck.title'),
+ detail: t('skills.retrieval.buildPipeline.llmCheck.detail'),
+ },
+ {
+ key: "build",
+ title: t('skills.retrieval.buildPipeline.build.title'),
+ detail: t('skills.retrieval.buildPipeline.build.detail'),
+ },
+ {
+ key: "publish",
+ title: t('skills.retrieval.buildPipeline.publish.title'),
+ detail: t('skills.retrieval.buildPipeline.publish.detail'),
+ },
+ {
+ key: "success",
+ title: t('skills.retrieval.buildPipeline.success.title'),
+ detail: t('skills.retrieval.buildPipeline.success.detail', { count: indexedCount || installedCount }),
+ },
+ ];
+ return base.map((phase) => ({
+ ...phase,
+ state: getSkillIndexBuildPhaseState(phase.key, currentStage, buildStatus),
+ }));
+}
+
+function getBuildPhaseClass(state: SkillIndexBuildPhaseState): string {
+ if (state === "done") return "border-emerald-500/30 bg-emerald-500/10 text-emerald-600";
+ if (state === "active") return "border-sky-500/40 bg-sky-500/10 text-sky-600";
+ if (state === "failed") return "border-red-500/35 bg-red-500/10 text-red-600";
+ if (state === "cancelled") return "border-amber-500/35 bg-amber-500/10 text-amber-600";
+ return "border-border bg-secondary/30 text-text-muted";
+}
+
+function SkillIndexBuildProgressPanel({
+ status,
+ progress,
+ logs,
+ t,
+}: {
+ status: SkillRetrievalStatus | null;
+ progress: number;
+ logs: SkillRetrievalBuildLog[];
+ t: (key: string, options?: Record<string, unknown>) => string;
+}) {
+ const phases = buildSkillIndexBuildPhases(status, t);
+ const stageLabel = getSkillIndexBuildStageLabel(status?.build_stage, t);
+ const isError = status?.build_status === "failed";
+ const showPipeline = status?.build_status !== "success";
+ return (
+ <div className="mt-4 rounded-lg border border-border bg-panel p-4">
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div className="min-w-[220px]">
+ <div className="text-sm font-medium text-text-strong">
+ {t('skills.retrieval.buildMonitorTitle')}
+ </div>
+ <div className="mt-1 text-xs text-text-muted">
+ {t('skills.retrieval.buildMonitorSubtitle', { stage: stageLabel })}
+ </div>
+ </div>
+ <div className="grid grid-cols-3 gap-2 text-xs">
+ <div className="rounded-md border border-border bg-secondary/40 px-3 py-2">
+ <div className="text-text-muted">{t('skills.retrieval.buildMetric.progress')}</div>
+ <div className="mt-1 font-medium text-text-strong">{progress}%</div>
+ </div>
+ <div className="rounded-md border border-border bg-secondary/40 px-3 py-2">
+ <div className="text-text-muted">{t('skills.retrieval.buildMetric.skills')}</div>
+ <div className="mt-1 font-medium text-text-strong">
+ {status?.installed_count ?? status?.installed_enabled_count ?? 0}
+ </div>
+ </div>
+ <div className="rounded-md border border-border bg-secondary/40 px-3 py-2">
+ <div className="text-text-muted">{t('skills.retrieval.buildMetric.indexed')}</div>
+ <div className="mt-1 font-medium text-text-strong">{status?.indexed_count ?? 0}</div>
+ </div>
+ </div>
+ </div>
+
+ <div className="mt-4 h-2 overflow-hidden rounded-full bg-secondary">
+ <div
+ className={`h-full rounded-full transition-all ${isError ? "bg-red-500" : "bg-emerald-500"}`}
+ style={{ width: `${progress}%` }}
+ />
+ </div>
+
+ {showPipeline ? (
+ <div className="mt-4 grid gap-4">
+ <div className="rounded-md border border-border bg-secondary/30 p-3">
+ <div className="mb-3 text-xs font-medium uppercase tracking-wide text-text-muted">
+ {t('skills.retrieval.buildPipelineTitle')}
+ </div>
+ <div className="space-y-2">
+ {phases.map((phase, index) => (
+ <div key={phase.key} className={`rounded-md border px-3 py-2 ${getBuildPhaseClass(phase.state)}`}>
+ <div className="flex items-center gap-2">
+ <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full border border-current text-[10px]">
+ {index + 1}
+ </span>
+ <span className="min-w-0 truncate text-xs font-medium">{phase.title}</span>
+ <span className="ml-auto text-[10px] uppercase opacity-70">
+ {t(`skills.retrieval.buildPhaseState.${phase.state}`)}
+ </span>
+ </div>
+ <div className="mt-1 pl-7 text-[11px] leading-5 opacity-80">{phase.detail}</div>
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ ) : null}
+ {status?.build_message ? (
+ <div className="mt-3 rounded-md border border-border bg-secondary/30 px-3 py-2 text-xs text-text-muted">
+ {status.build_message}
+ </div>
+ ) : null}
+ {status?.build_error ? (
+ <pre className="mt-3 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">
+ {status.build_error}
+ </pre>
+ ) : null}
+ {logs.length > 0 ? (
+ <div className="mt-3 grid gap-1 text-[11px] text-text-muted">
+ {logs.slice(-5).map((log, index) => (
+ <div key={`${log.time || index}-${log.stage || ""}`} className="flex min-w-0 gap-2">
+ <span className="shrink-0 font-mono text-text-muted/70">[{log.stage || "-"}]</span>
+ <span className="min-w-0 truncate">{log.message || log.status || ""}</span>
+ </div>
+ ))}
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
function SkillIndexTreeView({
roots,
selectedCid,
@@ -326,6 +550,7 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
const messageTimerRef = useRef<number | null>(null);
const retrievalPollRef = useRef<number | null>(null);
const retrievalDiscoveryPollRef = useRef<number | null>(null);
+ const retrievalStatusRequestRef = useRef(0);
const [viewMode, setViewMode] = useState<"list" | "grid">("list");
const [retrievalStatus, setRetrievalStatus] = useState<SkillRetrievalStatus | null>(null);
const [retrievalTree, setRetrievalTree] = useState("");
@@ -536,23 +761,32 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
[withSession]
);
- const fetchRetrievalStatus = useCallback(async () => {
- setRetrievalLoading((current) => (current === "idle" ? "status" : current));
+ const fetchRetrievalStatus = useCallback(async (options?: { silent?: boolean }) => {
+ const requestId = ++retrievalStatusRequestRef.current;
+ if (!options?.silent) {
+ setRetrievalLoading((current) => (current === "idle" ? "status" : current));
+ }
try {
const data = await webRequest<SkillRetrievalStatus>(
"skills.retrieval.status",
withSession()
);
- setRetrievalStatus(data);
+ if (requestId === retrievalStatusRequestRef.current) {
+ setRetrievalStatus(data);
+ }
} catch (error) {
console.error('Failed to load skill retrieval status:', error);
} finally {
- setRetrievalLoading((current) => (current === "status" ? "idle" : current));
+ if (!options?.silent) {
+ setRetrievalLoading((current) => (current === "status" ? "idle" : current));
+ }
}
}, [withSession]);
- const fetchRetrievalTree = useCallback(async () => {
- setRetrievalLoading((current) => (current === "idle" ? "tree" : current));
+ const fetchRetrievalTree = useCallback(async (options?: { silent?: boolean }) => {
+ if (!options?.silent) {
+ setRetrievalLoading((current) => (current === "idle" ? "tree" : current));
+ }
try {
const data = await webRequest<SkillRetrievalTreeResponse>(
"skills.retrieval.tree",
@@ -582,7 +816,9 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
setRetrievalTreeCounts({ branches: 0, skills: 0 });
setSelectedTreeNodeCid(null);
} finally {
- setRetrievalLoading((current) => (current === "tree" ? "idle" : current));
+ if (!options?.silent) {
+ setRetrievalLoading((current) => (current === "tree" ? "idle" : current));
+ }
}
}, [i18n.language, withSession]);
@@ -615,8 +851,9 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
}, [activeTab, fetchRetrievalStatus, fetchRetrievalTree]);
useEffect(() => {
+ const disabled = retrievalStatus?.enabled === false;
const running = retrievalStatus?.build_status === "running";
- if (activeTab !== "index" || !running) {
+ if (activeTab !== "index" || disabled || !running) {
if (retrievalPollRef.current !== null) {
window.clearInterval(retrievalPollRef.current);
retrievalPollRef.current = null;
@@ -625,20 +862,20 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
}
if (retrievalPollRef.current !== null) return;
retrievalPollRef.current = window.setInterval(() => {
- void fetchRetrievalStatus();
- void fetchRetrievalTree();
- }, 2000);
+ void fetchRetrievalStatus({ silent: true });
+ }, SKILL_RETRIEVAL_RUNNING_POLL_MS);
return () => {
if (retrievalPollRef.current !== null) {
window.clearInterval(retrievalPollRef.current);
retrievalPollRef.current = null;
}
};
- }, [activeTab, fetchRetrievalStatus, fetchRetrievalTree, retrievalStatus?.build_status]);
+ }, [activeTab, fetchRetrievalStatus, fetchRetrievalTree, retrievalStatus?.build_status, retrievalStatus?.enabled]);
useEffect(() => {
+ const disabled = retrievalStatus?.enabled === false;
const running = retrievalStatus?.build_status === "running";
- if (activeTab !== "index" || running) {
+ if (activeTab !== "index" || disabled || running) {
if (retrievalDiscoveryPollRef.current !== null) {
window.clearInterval(retrievalDiscoveryPollRef.current);
retrievalDiscoveryPollRef.current = null;
@@ -647,15 +884,15 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
}
if (retrievalDiscoveryPollRef.current !== null) return;
retrievalDiscoveryPollRef.current = window.setInterval(() => {
- void fetchRetrievalStatus();
- }, 5000);
+ void fetchRetrievalStatus({ silent: true });
+ }, SKILL_RETRIEVAL_IDLE_POLL_MS);
return () => {
if (retrievalDiscoveryPollRef.current !== null) {
window.clearInterval(retrievalDiscoveryPollRef.current);
retrievalDiscoveryPollRef.current = null;
}
};
- }, [activeTab, fetchRetrievalStatus, retrievalStatus?.build_status]);
+ }, [activeTab, fetchRetrievalStatus, retrievalStatus?.build_status, retrievalStatus?.enabled]);
useEffect(() => {
if (activeTab !== "index") return;
@@ -670,12 +907,12 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
retrievalStatus?.index_exists,
]);
- const handleBuildRetrievalIndex = useCallback(async () => {
+ const handleBuildRetrievalIndex = useCallback(async (force = false) => {
setRetrievalLoading("build");
try {
await webRequest<{ success: boolean; result?: string }>(
"skills.retrieval.index_build",
- withSession({ force: true, source: "web" }),
+ withSession({ force, source: "web" }),
{ timeoutMs: 30_000 }
);
await fetchRetrievalStatus();
@@ -1137,8 +1374,17 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
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)
+ ? retrievalStatus.build_logs.slice(-12)
: [];
+ const retrievalHasBuildInfo = Boolean(
+ retrievalStatus
+ && retrievalStatus.enabled !== false
+ && (
+ retrievalBuildRunning
+ || ["success", "failed", "cancelled"].includes(String(retrievalStatus.build_status || ""))
+ || retrievalBuildLogs.length > 0
+ )
+ );
return (
<>
{message && messageType === "success" && (
@@ -1294,7 +1540,7 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
</div>
{activeTab === "index" ? (
- <div className="mt-4 flex flex-col flex-1 min-h-0 gap-4">
+ <div className="mt-4 flex flex-col flex-1 min-h-0 gap-4 overflow-y-auto pr-2">
<div className="rounded-lg border border-border bg-panel p-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="min-w-[220px]">
@@ -1315,7 +1561,7 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
</div>
<div className="flex items-center gap-2">
<button
- onClick={handleBuildRetrievalIndex}
+ onClick={() => void handleBuildRetrievalIndex(false)}
className="px-3 py-1.5 rounded-lg text-sm border border-border hover:bg-secondary transition-colors disabled:opacity-60"
disabled={retrievalLoading === "build" || retrievalBuildRunning || retrievalStatus?.enabled === false}
>
@@ -1323,13 +1569,24 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
? t('skills.retrieval.building')
: t('skills.retrieval.build')}
</button>
+ {retrievalStatus?.index_exists ? (
+ <button
+ onClick={() => void handleBuildRetrievalIndex(true)}
+ className="px-3 py-1.5 rounded-lg text-sm border border-border hover:bg-secondary transition-colors disabled:opacity-60"
+ disabled={retrievalLoading === "build" || retrievalBuildRunning || retrievalStatus?.enabled === false}
+ >
+ {retrievalLoading === "build"
+ ? t('skills.retrieval.building')
+ : t('skills.retrieval.fullRebuild')}
+ </button>
+ ) : null}
{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}
+ disabled={retrievalLoading === "cancel"}
>
- {retrievalLoading === "cancel" || retrievalStatus?.build_cancel_requested
+ {retrievalLoading === "cancel"
? t('skills.retrieval.cancelling')
: t('skills.retrieval.cancel')}
</button>
@@ -1348,42 +1605,13 @@ export function SkillPanel({ sessionId, onNavigateToConfig, isActive = false }:
</button>
</div>
</div>
- {(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>
+ {retrievalHasBuildInfo ? (
+ <SkillIndexBuildProgressPanel
+ status={retrievalStatus}
+ progress={retrievalBuildProgress}
+ logs={retrievalBuildLogs}
+ t={t}
+ />
) : 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)]">
diff --git a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
index 11331be787..e5b75119a3 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/en.json
@@ -1054,13 +1054,69 @@
"indexedCount": "{{count}} indexed",
"installedCount": "{{count}} installed",
"build": "Build Index",
+ "fullRebuild": "Full Rebuild",
"building": "Building...",
"buildFailed": "Build failed",
- "cancel": "Pause Build",
- "cancelling": "Pausing...",
- "cancelled": "Build paused",
+ "cancel": "Cancel Build",
+ "cancelling": "Cancelling...",
+ "cancelled": "Build cancelled",
"buildStageUnknown": "Waiting for build status",
"buildProgress": "Progress {{progress}}%",
+ "buildMonitorTitle": "Build Progress",
+ "buildMonitorSubtitle": "Current stage: {{stage}}",
+ "buildPipelineTitle": "Index Build Flow",
+ "buildMetric": {
+ "progress": "Progress",
+ "skills": "Skills",
+ "indexed": "Indexed"
+ },
+ "buildPipeline": {
+ "queued": {
+ "title": "Prepare Build",
+ "detail": "Create temporary output directories and resolve build configuration and index paths."
+ },
+ "scan": {
+ "title": "Scan Installed Skills",
+ "detail": "Read {{count}} installed and enabled skills, then extract name, description, and SKILL.md."
+ },
+ "llmCheck": {
+ "title": "Check Model Connectivity",
+ "detail": "Send a lightweight request with the current model configuration before building the index."
+ },
+ "build": {
+ "title": "Build Skill Tree",
+ "detail": "Group skills by capability, classify them into branches, generate branch descriptions, and write the tree."
+ },
+ "publish": {
+ "title": "Publish Artifacts",
+ "detail": "Validate tree_index.yaml, catalog.jsonl, and manifest.json, then replace the live index directory."
+ },
+ "success": {
+ "title": "Index Ready",
+ "detail": "{{count}} skills are available for Agentic skill retrieval."
+ }
+ },
+ "buildPhaseState": {
+ "done": "Done",
+ "active": "Current",
+ "pending": "Pending",
+ "failed": "Failed",
+ "cancelled": "Cancelled"
+ },
+ "buildStages": {
+ "queued": "Queued",
+ "scan": "Scanning skills",
+ "llmCheck": "Checking model connectivity",
+ "buildTree": "Building skill tree",
+ "publish": "Publishing index",
+ "reuse": "Reusing index",
+ "success": "Build complete",
+ "failed": "Build failed",
+ "timeout": "Build timed out",
+ "llmConfig": "Model config",
+ "cancelled": "Cancelled",
+ "interrupted": "Interrupted"
+ },
"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 75bd783080..79774d533a 100644
--- a/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
+++ b/jiuwenswarm/channels/web/frontend/src/i18n/locales/zh.json
@@ -1053,13 +1053,69 @@
"indexedCount": "已索引 {{count}} 个",
"installedCount": "已安装 {{count}} 个",
"build": "构建索引",
+ "fullRebuild": "全量重新构建",
"building": "构建中...",
"buildFailed": "构建失败",
- "cancel": "暂停构建",
- "cancelling": "暂停中...",
- "cancelled": "构建已暂停",
+ "cancel": "取消构建",
+ "cancelling": "取消中...",
+ "cancelled": "构建已取消",
"buildStageUnknown": "等待构建状态",
"buildProgress": "进度 {{progress}}%",
+ "buildMonitorTitle": "构建进度",
+ "buildMonitorSubtitle": "当前阶段:{{stage}}",
+ "buildPipelineTitle": "索引构建流程",
+ "buildMetric": {
+ "progress": "进度",
+ "skills": "技能",
+ "indexed": "索引"
+ },
+ "buildPipeline": {
+ "queued": {
+ "title": "准备构建任务",
+ "detail": "创建临时输出目录,解析构建配置和索引路径。"
+ },
+ "scan": {
+ "title": "扫描已安装技能",
+ "detail": "读取 {{count}} 个已安装且启用的技能,提取名称、描述和 SKILL.md。"
+ },
+ "llmCheck": {
+ "title": "检查模型连接",
+ "detail": "使用当前模型配置发送轻量请求,确认构建模型可访问。"
+ },
+ "build": {
+ "title": "构建技能树",
+ "detail": "根据技能能力进行分组、分类和分支描述生成,并写入树结构。"
+ },
+ "publish": {
+ "title": "发布索引产物",
+ "detail": "校验 tree_index.yaml、catalog.jsonl、manifest.json,并替换线上索引目录。"
+ },
+ "success": {
+ "title": "索引就绪",
+ "detail": "{{count}} 个技能可用于 Agentic 技能检索。"
+ }
+ },
+ "buildPhaseState": {
+ "done": "完成",
+ "active": "当前",
+ "pending": "等待",
+ "failed": "失败",
+ "cancelled": "取消"
+ },
+ "buildStages": {
+ "queued": "任务排队",
+ "scan": "扫描技能",
+ "llmCheck": "检查模型连接",
+ "buildTree": "构建技能树",
+ "publish": "发布索引",
+ "reuse": "复用索引",
+ "success": "构建完成",
+ "failed": "构建失败",
+ "timeout": "构建超时",
+ "llmConfig": "模型配置",
+ "cancelled": "已取消",
+ "interrupted": "构建中断"
+ },
"treeTitle": "索引树",
"treeCount": "{{branches}} 个分支 · {{skills}} 个技能",
"noTree": "暂无索引树",
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index 86c12ace72..e38f829397 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -58,7 +58,7 @@ symphony:
postprocess_enabled: true
postprocess_max_passes: 1
postprocess_min_skills: 6
- equivalence_enabled: true
+ equivalence_enabled: false
retrieve:
compact_codes_enabled: false
flatten_tree: false
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
index 413a44c9d1..a7ddb663a1 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py
@@ -63,9 +63,7 @@ from jiuwenswarm.agents.harness.common.rails import (
)
from jiuwenswarm.agents.harness.common.memory.config import get_memory_mode
from jiuwenswarm.agents.harness.common.tools import (
- SkillRetrievalToolkit,
SkillToolkit,
- is_skill_retrieval_enabled,
)
from jiuwenswarm.agents.harness.common.tools.acp_chat import acp_chat
from jiuwenswarm.common.config import get_config
@@ -1287,21 +1285,33 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):
logger.warning("[JiuwenSwarmCodeAdapter] skill_toolkit build failed: %s", exc)
return None
+ def _skill_retrieval_tools_enabled_for_runtime(
+ self,
+ config_base: dict[str, Any] | None = None,
+ ) -> bool:
+ """Respect code-mode configured tools during runtime skill retrieval sync."""
+ if not super()._skill_retrieval_tools_enabled_for_runtime(config_base):
+ return False
+ config = config_base if isinstance(config_base, dict) else get_config()
+ configured_tools = config.get("modes", {}).get("code", {}).get("tools") or []
+ return "skill_retrieval" in configured_tools
+
def _build_skill_retrieval_toolkit(self, agent_id: str) -> list[Any] | None:
"""构建 SkillRetrievalToolkit 工具(不注册到 Runner,由 _get_tool_cards 统一注册)."""
- if not is_skill_retrieval_enabled():
+ if not self._skill_retrieval_tools_enabled_for_runtime():
logger.info("[JiuwenSwarmCodeAdapter] SkillRetrievalToolkit skipped: disabled")
return None
try:
- skill_retrieval_toolkit = SkillRetrievalToolkit(
- manager=self._skill_manager,
- visible_skill_names=self._visible_skill_names_for_list_skill,
- )
+ tools = self._create_skill_retrieval_tools()
+ if not tools:
+ return None
+ self._skill_retrieval_tools = tools
+ self._skill_retrieval_tools_registered = bool(tools)
logger.info(
"[JiuwenSwarmCodeAdapter] SkillRetrievalToolkit built: tools=%s",
- [t.card.name for t in skill_retrieval_toolkit.get_tools()],
+ [tool.card.name for tool in tools],
)
- return skill_retrieval_toolkit.get_tools()
+ return tools
except Exception as exc:
logger.warning("[JiuwenSwarmCodeAdapter] skill_retrieval build failed: %s", exc)
return None
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index 6ad0f1a4b7..0ce1d47496 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -304,6 +304,13 @@ _ACP_BLOCKED_DEFAULT_TOOL_NAMES = frozenset(
}
)
_PLACEHOLDER_API_BASES = frozenset({"https://example.com/compatible-mode/v1"})
+_SKILL_RETRIEVAL_TOOL_NAMES = frozenset(
+ {
+ "skill_index_build",
+ "skill_branch_explore",
+ "skill_branch_peek",
+ }
+)
def _get_skill_create_enabled(config: dict[str, Any] | None) -> bool:
@@ -594,6 +601,9 @@ class JiuWenSwarmDeepAdapter:
self._paid_search_tool: WebPaidSearchTool | None = None
self._symphony_tools: list[Any] = []
self._symphony_tools_registered: bool = False
+ self._skill_retrieval_tools_registered: bool = False
+ self._skill_retrieval_tools: list[Any] = []
+ self._skill_retrieval_prompt_rail: SkillRetrievalPromptRail | None = None
self._skill_manager: SkillManager | None = None
self._a2x_client: Any | None = None
self._a2x_config: dict[str, Any] = {}
@@ -1655,6 +1665,118 @@ class JiuWenSwarmDeepAdapter:
if (item.card.name if hasattr(item, "card") else item.name) not in tool_names
]
+ def _drop_tool_names_from_runtime(self, tool_names: set[str] | frozenset[str]) -> None:
+ """Best-effort removal for tool cards that may predate tracked tool instances."""
+ if not tool_names:
+ return
+ card_ids = set(tool_names)
+ for item in self._tool_cards or []:
+ card = item.card if hasattr(item, "card") else item
+ if getattr(card, "name", None) in tool_names:
+ card_ids.add(getattr(card, "id", None) or card.name)
+ self._prune_tool_cards(set(tool_names))
+ if self._instance is not None and hasattr(self._instance, "ability_manager"):
+ for tool_name in tool_names:
+ try:
+ self._instance.ability_manager.remove(tool_name)
+ except Exception:
+ logger.debug(
+ "[JiuWenSwarmDeepAdapter] ability remove skipped for %s",
+ tool_name,
+ exc_info=True,
+ )
+ for tool_id in card_ids:
+ try:
+ Runner.resource_mgr.remove_tool(tool_id)
+ except Exception:
+ logger.debug(
+ "[JiuWenSwarmDeepAdapter] resource remove skipped for %s",
+ tool_id,
+ exc_info=True,
+ )
+
+ def _create_skill_retrieval_tools(self) -> list[Any]:
+ """Create Agentic skill retrieval tools using the current visible-skill provider."""
+ if not is_skill_retrieval_enabled():
+ logger.info("[JiuWenSwarmDeepAdapter] SkillRetrievalToolkit skipped: disabled")
+ return []
+ skill_retrieval_toolkit = SkillRetrievalToolkit(
+ manager=self._skill_manager,
+ visible_skill_names=self._visible_skill_names_for_list_skill,
+ )
+ tools = skill_retrieval_toolkit.get_tools()
+ logger.info(
+ "[JiuWenSwarmDeepAdapter] SkillRetrievalToolkit built: tools=%s",
+ [tool.card.name for tool in tools],
+ )
+ return tools
+
+ @staticmethod
+ def _skill_retrieval_tools_enabled_for_runtime(
+ config_base: dict[str, Any] | None = None,
+ ) -> bool:
+ """Return whether runtime tool sync should expose Agentic skill retrieval tools."""
+ return is_skill_retrieval_enabled()
+
+ def _sync_skill_retrieval_tools_for_runtime(
+ self,
+ config_base: dict[str, Any] | None = None,
+ ) -> None:
+ """Sync Agentic skill retrieval tool registration after config reload."""
+ enabled = self._skill_retrieval_tools_enabled_for_runtime(config_base)
+ tools, registered = self._sync_tool_group(
+ current_tools=self._skill_retrieval_tools,
+ registered=self._skill_retrieval_tools_registered,
+ enabled=enabled,
+ create_fn=self._create_skill_retrieval_tools,
+ warn_label="skill retrieval tools",
+ )
+ self._skill_retrieval_tools = tools
+ self._skill_retrieval_tools_registered = registered
+ if not enabled:
+ self._drop_tool_names_from_runtime(_SKILL_RETRIEVAL_TOOL_NAMES)
+
+ async def _sync_skill_retrieval_prompt_rail_for_runtime(
+ self,
+ config_base: dict[str, Any] | None = None,
+ ) -> None:
+ """Sync Agentic skill retrieval prompt rail after config reload."""
+ if self._instance is None:
+ return
+
+ enabled = self._skill_retrieval_tools_enabled_for_runtime(config_base)
+ rail = self._skill_retrieval_prompt_rail
+ if enabled:
+ if rail is not None:
+ return
+ rail = self._build_skill_retrieval_prompt_rail()
+ if rail is None:
+ return
+ try:
+ await self._instance.register_rail(rail)
+ except Exception as exc:
+ self._skill_retrieval_prompt_rail = None
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] SkillRetrievalPromptRail reload failed: %s",
+ exc,
+ )
+ return
+ self._skill_retrieval_prompt_rail = rail
+ logger.info("[JiuWenSwarmDeepAdapter] SkillRetrievalPromptRail registered")
+ return
+
+ if rail is None:
+ return
+ try:
+ await self._instance.unregister_rail(rail)
+ except Exception as exc:
+ logger.warning(
+ "[JiuWenSwarmDeepAdapter] SkillRetrievalPromptRail unregister failed: %s",
+ exc,
+ )
+ finally:
+ self._skill_retrieval_prompt_rail = None
+
def _sync_multimodal_tools_for_runtime(self) -> None:
"""Sync multimodal tool registration after config reload."""
agent_id = self._instance.card.id if self._instance else None
@@ -2294,12 +2416,6 @@ class JiuWenSwarmDeepAdapter:
self, config: dict[str, Any], include_tools: bool = False
) -> SkillUseRail | None:
"""Build SkillUseRail."""
- if is_skill_retrieval_enabled():
- logger.info(
- "[JiuWenSwarmDeepAdapter] SkillUseRail skipped: "
- "agentic skill retrieval is enabled"
- )
- return None
try:
skill_mode = self._resolve_skill_mode(config)
logger.info("[JiuWenSwarmDeepAdapter] current skill_mode: %s", skill_mode)
@@ -2810,25 +2926,25 @@ class JiuWenSwarmDeepAdapter:
False,
)
- if is_skill_retrieval_enabled():
- self._skill_rail = None
+ # Reuse existing SkillUseRail to preserve dynamically loaded skills
+ # from activate_package() / load_harness_config(). When agentic
+ # retrieval is enabled, _resolve_skill_mode() forces AUTO_LIST; the
+ # SkillRetrievalPromptRail then hides list_skill and the native skills
+ # prompt while keeping skill_tool/read_file available.
+ if self._skill_rail is None:
+ self._skill_rail = self._build_skill_rail(
+ config,
+ include_tools=self._skill_include_tools_for_profile(),
+ )
else:
- # Reuse existing SkillUseRail to preserve dynamically loaded skills
- # from activate_package() / load_harness_config()
- if self._skill_rail is None:
- self._skill_rail = self._build_skill_rail(
- config,
- include_tools=self._skill_include_tools_for_profile(),
- )
- else:
- # Update existing rail's skill_mode if changed
- new_skill_mode = self._resolve_skill_mode(config)
- if self._skill_rail.skill_mode != new_skill_mode:
- self._skill_rail.skill_mode = new_skill_mode
- # Update disabled_skills
- new_disabled = self._skill_manager.list_execution_disabled_skills()
- if self._skill_rail.disabled_skills != new_disabled:
- self._skill_rail.disabled_skills = new_disabled
+ # Update existing rail's skill_mode if changed.
+ new_skill_mode = self._resolve_skill_mode(config)
+ if self._skill_rail.skill_mode != new_skill_mode:
+ self._skill_rail.skill_mode = new_skill_mode
+ # Update disabled_skills.
+ new_disabled = self._skill_manager.list_execution_disabled_skills()
+ if self._skill_rail.disabled_skills != new_disabled:
+ self._skill_rail.disabled_skills = new_disabled
if not self._filesystem_rail_enabled_for_profile():
self._filesystem_rail = None
@@ -2998,23 +3114,25 @@ class JiuWenSwarmDeepAdapter:
if is_skill_retrieval_enabled():
try:
- skill_retrieval_toolkit = SkillRetrievalToolkit(
- manager=self._skill_manager,
- visible_skill_names=self._visible_skill_names_for_list_skill,
- )
+ self._skill_retrieval_tools = self._create_skill_retrieval_tools()
skill_retrieval_tool_names: list[str] = []
- for tool in skill_retrieval_toolkit.get_tools():
+ for tool in self._skill_retrieval_tools:
if not Runner.resource_mgr.get_tool(tool.card.id):
Runner.resource_mgr.add_tool(tool)
tool_cards.append(tool.card)
skill_retrieval_tool_names.append(tool.card.name)
+ self._skill_retrieval_tools_registered = bool(self._skill_retrieval_tools)
logger.info(
"[JiuWenSwarmDeepAdapter] SkillRetrievalToolkit registered: tools=%s",
skill_retrieval_tool_names,
)
except Exception as exc:
+ self._skill_retrieval_tools = []
+ self._skill_retrieval_tools_registered = False
logger.warning("[JiuWenSwarmDeepAdapter] skill retrieval tools registration failed: %s", exc)
else:
+ self._skill_retrieval_tools = []
+ self._skill_retrieval_tools_registered = False
logger.info("[JiuWenSwarmDeepAdapter] SkillRetrievalToolkit skipped: disabled")
try:
@@ -3264,6 +3382,8 @@ class JiuWenSwarmDeepAdapter:
self._sync_multimodal_tools_for_runtime()
self._sync_paid_search_tool_for_runtime()
self._sync_symphony_tools_for_runtime(config_base)
+ self._sync_skill_retrieval_tools_for_runtime(config_base)
+ await self._sync_skill_retrieval_prompt_rail_for_runtime(config_base)
if not self._filesystem_rail_enabled_for_profile() and self._filesystem_rail is not None:
try:
diff --git a/jiuwenswarm/server/runtime/skill/skill_manager.py b/jiuwenswarm/server/runtime/skill/skill_manager.py
index 426d5914a4..4b596d5ace 100644
--- a/jiuwenswarm/server/runtime/skill/skill_manager.py
+++ b/jiuwenswarm/server/runtime/skill/skill_manager.py
@@ -543,15 +543,15 @@ class SkillManager:
async def handle_skills_retrieval_index_build(self, params: dict) -> dict:
"""构建或复用本地 skill retrieval 索引."""
- from jiuwenswarm.symphony.skill_retrieval import build_skill_index
+ from jiuwenswarm.symphony.skill_retrieval.build_coordinator import start_skill_index_build
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)
+ return await asyncio.to_thread(start_skill_index_build, self, force=force, source=source)
async def handle_skills_retrieval_index_cancel(self, params: dict) -> dict:
- """请求暂停/取消本地 skill retrieval 索引构建."""
+ """请求取消本地 skill retrieval 索引构建."""
from jiuwenswarm.symphony.skill_retrieval import cancel_skill_index_build
return await asyncio.to_thread(cancel_skill_index_build, self)
diff --git a/jiuwenswarm/symphony/agent/agentic_retrieval_toolkit.py b/jiuwenswarm/symphony/agent/agentic_retrieval_toolkit.py
index 807e21e268..c3701c81a9 100644
--- a/jiuwenswarm/symphony/agent/agentic_retrieval_toolkit.py
+++ b/jiuwenswarm/symphony/agent/agentic_retrieval_toolkit.py
@@ -19,7 +19,7 @@ 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 jiuwenswarm.symphony.skill_retrieval.api import build_skill_index as build_skill_index_blocking
from .tool_result import AgenticToolResult
@@ -743,10 +743,10 @@ class AgenticRetrievalToolKit:
def build_skill_index(manager: Any | None = None) -> dict[str, Any]:
- """Start a background build or reuse request for the installed-skill retrieval index."""
+ """Build or reuse the installed-skill retrieval index before the agent continues."""
resolved_manager = _resolve_manager(manager)
_clear_runtime_caches()
- payload = start_background_skill_index_build(resolved_manager, force=False, source="tool")
+ payload = build_skill_index_blocking(resolved_manager, force=False, source="tool")
_clear_runtime_caches()
return _tool_payload(
bool(payload.get("success")),
diff --git a/jiuwenswarm/symphony/indexing/tree/builder.py b/jiuwenswarm/symphony/indexing/tree/builder.py
index 6f58324e9f..b10e542b24 100644
--- a/jiuwenswarm/symphony/indexing/tree/builder.py
+++ b/jiuwenswarm/symphony/indexing/tree/builder.py
@@ -491,6 +491,7 @@ class TreeBuilder:
child_groups = future.result()
except Exception as exc:
console.print(f"[red]Error processing {job.node.id}: {exc}[/red]")
+ raise RuntimeError(f"Skill tree node processing failed for '{job.node.id}': {exc}") from exc
else:
for child_group in child_groups:
pending_nodes.append(self._queue_child_node(child_group, depth=job.depth + 1))
diff --git a/jiuwenswarm/symphony/indexing/tree/grouping.py b/jiuwenswarm/symphony/indexing/tree/grouping.py
index 623a135bb7..e32bd050d3 100644
--- a/jiuwenswarm/symphony/indexing/tree/grouping.py
+++ b/jiuwenswarm/symphony/indexing/tree/grouping.py
@@ -155,6 +155,7 @@ class TreeGroupingEngine:
assignments.update(future.result())
except Exception as exc:
console.print(f"[red]Classification batch failed: {exc}[/red]")
+ raise RuntimeError(f"Skill classification batch failed: {exc}") from exc
return assignments
@staticmethod
@@ -318,6 +319,7 @@ class TreeGroupingEngine:
payload = future.result()
except Exception as exc:
console.print(f"[red]Discovery batch failed: {exc}[/red]")
+ raise RuntimeError(f"Skill group discovery batch failed: {exc}") from exc
else:
if payload:
collected.append((future_map[future], payload))
diff --git a/jiuwenswarm/symphony/indexing/tree/llm_runtime.py b/jiuwenswarm/symphony/indexing/tree/llm_runtime.py
index f8f9d5cc86..12e81709c1 100644
--- a/jiuwenswarm/symphony/indexing/tree/llm_runtime.py
+++ b/jiuwenswarm/symphony/indexing/tree/llm_runtime.py
@@ -227,10 +227,13 @@ class TreeLLMRuntime:
)
else:
thread_local.truncated = False
+ content = response.choices[0].message.content
+ if not content:
+ raise RuntimeError("empty response from skill index build model")
with counter_lock:
_set_builder_attr(builder, "_consecutive_failures", 0)
self.record_cache_observation(None)
- return response.choices[0].message.content or "{}"
+ return content
except Exception as e:
if AuthenticationError is not None and isinstance(e, AuthenticationError):
console.print("[red]Authentication failed - check API key[/red]")
@@ -251,7 +254,9 @@ class TreeLLMRuntime:
_set_builder_attr(builder, "_consecutive_failures", consecutive_failures)
if consecutive_failures >= builder.max_consecutive_failures:
raise RuntimeError(f"Circuit breaker: {consecutive_failures} consecutive LLM failures") from e
- return "{}"
+ raise RuntimeError(
+ f"Skill index build model call exceeded the model context window: {e}"
+ ) from e
is_transient = (
(APITimeoutError is not None and isinstance(e, APITimeoutError))
or (APIConnectionError is not None and isinstance(e, APIConnectionError))
@@ -267,7 +272,7 @@ class TreeLLMRuntime:
_set_builder_attr(builder, "_consecutive_failures", consecutive_failures)
if consecutive_failures >= builder.max_consecutive_failures:
raise RuntimeError(f"Circuit breaker: {consecutive_failures} consecutive LLM failures") from e
- return "{}"
+ raise RuntimeError(f"Skill index build model call failed: {e}") from e
def call_llm_json(self, prompt: str, max_retries: int = 3, is_retry: bool = False) -> dict:
builder = self._builder
@@ -277,17 +282,20 @@ class TreeLLMRuntime:
while attempts_remaining > 0:
thread_local.truncated = False
response = self.call_llm(prompt, is_retry=is_retry or attempt_index > 0)
- parsed = parse_json_from_response(response, default={})
+ if getattr(thread_local, "truncated", False):
+ raise RuntimeError(
+ "Skill index build model output was truncated before a complete JSON object was produced."
+ )
+ parse_failed = object()
+ parsed = parse_json_from_response(response, default=parse_failed)
if isinstance(parsed, dict):
return parsed
- if getattr(thread_local, "truncated", False):
- console.print("[yellow]Skipping retry because the model output was truncated[/yellow]")
- return {}
console.print(
f"[yellow]Expected a JSON object but received {type(parsed).__name__} "
f"(attempt {attempt_index + 1}/{max_retries})[/yellow]"
)
attempt_index += 1
attempts_remaining -= 1
- console.print("[red]All retries exhausted, returning empty dict[/red]")
- return {}
+ raise RuntimeError(
+ f"Skill index build model did not return a valid JSON object after {max_retries} attempts."
+ )
diff --git a/jiuwenswarm/symphony/skill_retrieval/api.py b/jiuwenswarm/symphony/skill_retrieval/api.py
index 2d56699962..ba89ca8890 100644
--- a/jiuwenswarm/symphony/skill_retrieval/api.py
+++ b/jiuwenswarm/symphony/skill_retrieval/api.py
@@ -1,7 +1,13 @@
from __future__ import annotations
+import logging
+import threading
from typing import Any
+LOGGER = logging.getLogger(__name__)
+_STARTUP_REPAIR_LOCK = threading.Lock()
+_STARTUP_REPAIR_DONE = False
+
def build_skill_index(
manager: Any | None = None,
@@ -9,16 +15,18 @@ def build_skill_index(
force: bool = False,
source: str = "tool",
) -> dict[str, Any]:
+ _repair_interrupted_build_state_once()
from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
- from .build_coordinator import start_skill_index_build
+ from .build_coordinator import build_skill_index_and_wait
resolved_manager = manager or SkillManager()
- payload = start_skill_index_build(resolved_manager, force=force, source=source)
+ payload = build_skill_index_and_wait(resolved_manager, force=force, source=source)
return _tool_payload(payload)
def cancel_skill_index_build(manager: Any | None = None) -> dict[str, Any]:
+ _repair_interrupted_build_state_once()
from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
from .build_coordinator import cancel_skill_index_build as cancel_build
@@ -29,6 +37,7 @@ def cancel_skill_index_build(manager: Any | None = None) -> dict[str, Any]:
def retrieve_skills(query: str, manager: Any | None = None) -> dict[str, Any]:
+ _repair_interrupted_build_state_once()
from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
from .retrieve_service import SkillRetrieveService
@@ -39,6 +48,7 @@ def retrieve_skills(query: str, manager: Any | None = None) -> dict[str, Any]:
def get_skill_retrieval_status(manager: Any | None = None) -> dict[str, Any]:
+ _repair_interrupted_build_state_once()
from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
from .index_service import SkillIndexService
@@ -48,6 +58,7 @@ def get_skill_retrieval_status(manager: Any | None = None) -> dict[str, Any]:
def get_skill_retrieval_tree(manager: Any | None = None, *, language: str = "cn") -> dict[str, Any]:
+ _repair_interrupted_build_state_once()
from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager
from .index_service import SkillIndexService
@@ -65,3 +76,23 @@ def _tool_payload(payload: dict[str, Any]) -> dict[str, Any]:
if isinstance(skill_tree, dict):
out["skill_tree"] = skill_tree
return out
+
+
+def _repair_interrupted_build_state_once() -> None:
+ global _STARTUP_REPAIR_DONE
+
+ if _STARTUP_REPAIR_DONE:
+ return
+ with _STARTUP_REPAIR_LOCK:
+ if _STARTUP_REPAIR_DONE:
+ return
+ _STARTUP_REPAIR_DONE = True
+
+ try:
+ from .build_coordinator import has_active_skill_index_build
+ from .index_service import repair_interrupted_build_state
+
+ if not has_active_skill_index_build() and repair_interrupted_build_state():
+ LOGGER.info("[skill-index] repaired interrupted build state")
+ except Exception as exc:
+ LOGGER.warning("[skill-index] failed to repair interrupted build state: %s", exc)
diff --git a/jiuwenswarm/symphony/skill_retrieval/build_coordinator.py b/jiuwenswarm/symphony/skill_retrieval/build_coordinator.py
index dbc70d5fae..3296ae8af2 100644
--- a/jiuwenswarm/symphony/skill_retrieval/build_coordinator.py
+++ b/jiuwenswarm/symphony/skill_retrieval/build_coordinator.py
@@ -20,6 +20,19 @@ _TASKS: dict[str, _BuildTask] = {}
_LOCK = threading.RLock()
+def has_active_skill_index_build() -> bool:
+ settings = load_settings()
+ key = str(settings.artifact_root)
+ with _LOCK:
+ task = _TASKS.get(key)
+ if task is None:
+ return False
+ if task.thread.is_alive() and not task.cancel_event.is_set():
+ return True
+ _TASKS.pop(key, None)
+ return False
+
+
def start_skill_index_build(
manager: Any,
*,
@@ -34,7 +47,7 @@ def start_skill_index_build(
with _LOCK:
existing = _TASKS.get(key)
- if existing is not None and existing.thread.is_alive():
+ if existing is not None and existing.thread.is_alive() and not existing.cancel_event.is_set():
return {
"success": True,
"background": True,
@@ -71,6 +84,30 @@ def start_skill_index_build(
}
+def build_skill_index_and_wait(
+ manager: Any,
+ *,
+ force: bool = False,
+ source: str = "tool",
+) -> dict[str, Any]:
+ """Start or reuse the shared background build, then wait for its final state."""
+ started = start_skill_index_build(manager, force=force, source=source)
+ if not started.get("background"):
+ return started
+
+ settings = load_settings()
+ key = str(settings.artifact_root)
+ while True:
+ with _LOCK:
+ task = _TASKS.get(key)
+ if task is None:
+ break
+ task.thread.join(timeout=0.2)
+ if not task.thread.is_alive():
+ break
+ return _build_result_from_status(manager)
+
+
def cancel_skill_index_build(manager: Any) -> dict[str, Any]:
settings = load_settings()
key = str(settings.artifact_root)
@@ -79,9 +116,10 @@ def cancel_skill_index_build(manager: Any) -> dict[str, Any]:
if task is not None and task.thread.is_alive():
task.cancel_event.set()
SkillIndexService(manager).request_cancel()
+ _TASKS.pop(key, None)
return {
"success": True,
- "build_status": "cancel_requested",
+ "build_status": "cancelled",
"result": "# Skill Index Build\n\nCancellation requested.",
}
@@ -110,3 +148,30 @@ def _run_build(
task = _TASKS.get(key)
if task is not None and task.cancel_event is cancel_event:
_TASKS.pop(key, None)
+
+
+def _build_result_from_status(manager: Any) -> dict[str, Any]:
+ status = SkillIndexService(manager).status()
+ build_status = str(status.get("build_status") or "idle")
+ if build_status == "success" or (status.get("index_exists") and status.get("fresh")):
+ return {
+ "success": True,
+ "build_status": build_status,
+ "result": (
+ "# Skill Index Build\n\n"
+ "Skill index build completed. You can now call `skill_branch_explore` "
+ "or `skill_branch_peek` to inspect installed skills."
+ ),
+ }
+ if build_status == "cancelled":
+ return {
+ "success": False,
+ "build_status": build_status,
+ "result": "# Skill Index Build\n\nSkill index build was cancelled.",
+ }
+ reason = str(status.get("build_error") or status.get("build_message") or "Skill index build did not complete.")
+ return {
+ "success": False,
+ "build_status": build_status,
+ "result": f"# Skill Index Build\n\nSkill index build failed.\n\n{reason}",
+ }
diff --git a/jiuwenswarm/symphony/skill_retrieval/index_service.py b/jiuwenswarm/symphony/skill_retrieval/index_service.py
index a3d89f2267..6dd46332d8 100644
--- a/jiuwenswarm/symphony/skill_retrieval/index_service.py
+++ b/jiuwenswarm/symphony/skill_retrieval/index_service.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import json
import logging
import shutil
+import threading
import time
from contextlib import contextmanager, redirect_stderr, redirect_stdout
from dataclasses import asdict
@@ -23,6 +24,11 @@ MANIFEST_FILENAME = "manifest.json"
STATE_FILENAME = "state.json"
LOGGER = logging.getLogger(__name__)
BUILD_LOG_LIMIT = 40
+TREE_BUILD_PROGRESS_START = 0.35
+TREE_BUILD_PROGRESS_END = 0.85
+TREE_BUILD_PROGRESS_MIN_INTERVAL_SECONDS = 1.0
+TREE_BUILD_PROGRESS_MIN_DELTA = 0.01
+TREE_BUILD_PROGRESS_LLM_HINT_LIMIT = 0.12
class SkillIndexBuildCancelled(RuntimeError):
@@ -47,6 +53,8 @@ class SkillIndexService:
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)
+ if build_state.get("status") == "success" and not fresh:
+ build_state = _stale_success_build_state()
return {
"enabled": settings.enabled,
"artifact_root": str(settings.artifact_root),
@@ -56,9 +64,9 @@ class SkillIndexService:
"installed_count": inventory.count,
"installed_enabled_count": inventory.count,
"indexed_count": int(state.get("indexed_count") or 0) if complete and manifest_matches else 0,
- "built_at": str(state.get("built_at") or ""),
+ "built_at": str(state.get("built_at") or "") if complete else "",
"inventory_fingerprint": inventory.fingerprint,
- "fingerprint": str(state.get("fingerprint") or ""),
+ "fingerprint": str(state.get("fingerprint") or "") if complete else "",
"build_branching_factor": settings.build.branching_factor,
"build_max_depth": settings.build.max_depth,
"build_request_timeout_seconds": settings.build.request_timeout_seconds,
@@ -95,10 +103,11 @@ class SkillIndexService:
settings,
status="running",
stage="scan",
- message=f"Scanning installed skills ({source}).",
+ message="Scanning installed skills.",
progress=0.05,
started_at=_now_iso(),
clear_error=True,
+ clear_logs=True,
)
self._check_cancel_or_timeout(settings, started, cancel_check, stage="scan")
inventory = scan_skill_inventory(self._manager)
@@ -166,7 +175,7 @@ class SkillIndexService:
if _is_stale_index(settings, inventory, expected):
_cleanup_index(settings)
error = (
- "Offline dispatch tree build requires a model and API key. "
+ "Offline skill tree build requires a model and API key. "
"Configure `models.defaults[0].model_client_config` or `symphony.skill_retrieval.llm`."
)
_write_build_state(
@@ -191,39 +200,53 @@ class SkillIndexService:
)
build_index_dir = build_root / "index"
try:
+ _write_build_state(
+ settings,
+ status="running",
+ stage="llm_check",
+ message="Checking skill index build model connectivity.",
+ progress=0.2,
+ inventory=inventory,
+ fingerprint=expected,
+ )
+ self._check_cancel_or_timeout(settings, started, cancel_check, stage="llm_check")
+ self._check_build_llm_access(settings)
build_index_dir.mkdir(parents=True, exist_ok=True)
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.",
+ message="Building installed skill tree index.",
progress=0.35,
inventory=inventory,
fingerprint=expected,
)
if force:
- LOGGER.info("[skill-index] stage=build status=running detail=force_full_rebuild")
+ LOGGER.info(
+ "[skill-index] stage=build status=running "
+ "detail=Starting full rebuild because force rebuild was requested."
+ )
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")
+ LOGGER.info("[skill-index] stage=build status=running detail=Starting incremental rebuild.")
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",
+ "detail=Incremental rebuild failed; falling back to 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:
- LOGGER.info("[skill-index] stage=build status=running detail=full")
+ LOGGER.info("[skill-index] stage=build status=running detail=Starting full rebuild.")
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")
+ raise RuntimeError("skill index build finished without complete index artifacts")
_write_build_state(
settings,
status="running",
@@ -303,10 +326,12 @@ class SkillIndexService:
settings = load_settings()
_write_build_state(
settings,
- status="running",
- stage="cancel_requested",
- message="Cancellation requested by user.",
- cancel_requested=True,
+ status="cancelled",
+ stage="cancelled",
+ message="Skill index build cancellation requested by user.",
+ progress=1.0,
+ finished_at=_now_iso(),
+ cancel_requested=False,
)
return {"success": True, "result": "# Skill Index Build\n\nCancellation requested."}
@@ -319,10 +344,11 @@ class SkillIndexService:
settings,
status="running",
stage="queued",
- message=f"Skill index build queued ({source}).",
+ message="Skill index build queued.",
progress=0.01,
started_at=_now_iso(),
clear_error=True,
+ clear_logs=True,
)
def incremental_build(
@@ -348,31 +374,35 @@ class SkillIndexService:
add_index_path: Path | None = None
try:
with dispatch_import_path():
+ from indexing.tree.builder import TreeBuilder
from indexing.workflows.index_builder import IndexBuilder
+
+ _ensure_tree_builder_compat(TreeBuilder)
config = self._make_build_config(settings)
- if added_paths:
+ with _capture_tree_build_progress(TreeBuilder, settings=settings, inventory=inventory):
+ if added_paths:
+ if removed_paths:
+ add_index_path = output_dir.parent / "added-skills"
+ else:
+ add_index_path = output_dir
+ 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:
- add_index_path = output_dir.parent / "added-skills"
- else:
- add_index_path = output_dir
- 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
- with _suppress_dispatch_console():
- IndexBuilder.delete(
- item_paths=removed_paths,
- base_index_dir=source,
- output_dir=output_dir,
- item_type="skill",
- config=config,
- )
+ source = add_index_path if added_paths else existing_index
+ 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)
@@ -506,12 +536,46 @@ class SkillIndexService:
config = SkillIndexService._make_build_config(settings)
with _suppress_dispatch_console():
- IndexBuilder.build(
- item_paths=inventory.item_paths,
- output_dir=output_dir,
- item_type="skill",
- config=config,
- )
+ with _capture_tree_build_progress(TreeBuilder, settings=settings, inventory=inventory):
+ IndexBuilder.build(
+ item_paths=inventory.item_paths,
+ output_dir=output_dir,
+ item_type="skill",
+ config=config,
+ )
+
+ @staticmethod
+ def _check_build_llm_access(settings: SkillRetrievalSettings) -> None:
+ try:
+ from openai import OpenAI
+ except ModuleNotFoundError as exc:
+ raise RuntimeError("The openai package is required to build the skill index.") from exc
+
+ client = OpenAI(
+ api_key=settings.llm.api_key,
+ base_url=settings.llm.base_url or None,
+ )
+ try:
+ client.chat.completions.create(
+ model=settings.llm.model,
+ messages=[
+ {
+ "role": "user",
+ "content": "Reply with OK. This is a connectivity check before building a local skill index.",
+ }
+ ],
+ max_tokens=8,
+ timeout=settings.build.request_timeout_seconds,
+ stream=False,
+ extra_body={
+ "thinking": {"type": "disabled"},
+ "chat_template_kwargs": {"enable_thinking": False},
+ "temperature": 0.0,
+ "top_p": 1.0,
+ },
+ )
+ except Exception as exc:
+ raise RuntimeError(f"Skill index build model is not reachable or rejected the request: {exc}") from exc
@staticmethod
def _recover_index(
@@ -537,13 +601,10 @@ class SkillIndexService:
def _cleanup_index(settings: SkillRetrievalSettings) -> None:
- """Remove existing index and state when no skills are available."""
+ """Remove existing index artifacts while preserving build state for UI reporting."""
index_dir = _index_dir(settings)
if index_dir.exists():
shutil.rmtree(index_dir, ignore_errors=True)
- state_file = _state_file(settings)
- if state_file.exists():
- state_file.unlink()
def _index_dir(settings: SkillRetrievalSettings) -> Path:
@@ -579,6 +640,103 @@ def _write_tree_yaml(tree_builder: Any, tree_dict: dict[str, Any]) -> None:
writer.write_yaml(tree_dict)
+@contextmanager
+def _capture_tree_build_progress(
+ tree_builder_cls: type,
+ *,
+ settings: SkillRetrievalSettings,
+ inventory: SkillInventory,
+):
+ original_tree_progress = getattr(tree_builder_cls, "_tree_progress", None)
+ if not callable(original_tree_progress):
+ yield
+ return
+
+ reporter = _SkillTreeBuildProgressReporter(settings=settings, total=inventory.count)
+
+ def wrapped_tree_progress(builder: Any, *args: Any, **kwargs: Any) -> Any:
+ progress = original_tree_progress(builder, *args, **kwargs)
+ return _TreeProgressProxy(progress, reporter)
+
+ setattr(tree_builder_cls, "_tree_progress", wrapped_tree_progress)
+ try:
+ yield
+ finally:
+ setattr(tree_builder_cls, "_tree_progress", original_tree_progress)
+
+
+class _TreeProgressProxy:
+ def __init__(self, progress: Any, reporter: "_SkillTreeBuildProgressReporter") -> None:
+ self._progress = progress
+ self._reporter = reporter
+
+ def __enter__(self) -> "_TreeProgressProxy":
+ self._progress.__enter__()
+ return self
+
+ def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> Any:
+ return self._progress.__exit__(exc_type, exc, tb)
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._progress, name)
+
+ def update(self, task_id: Any, *args: Any, **kwargs: Any) -> Any:
+ result = self._progress.update(task_id, *args, **kwargs)
+ self._reporter.record_update(kwargs)
+ return result
+
+
+class _SkillTreeBuildProgressReporter:
+ def __init__(self, *, settings: SkillRetrievalSettings, total: int) -> None:
+ self._settings = settings
+ self._total = max(0, int(total or 0))
+ self._leaf = 0
+ self._llm = 0
+ self._pending = 0
+ self._last_write = 0.0
+ self._last_progress = TREE_BUILD_PROGRESS_START
+ self._lock = threading.Lock()
+
+ def record_update(self, fields: dict[str, Any]) -> None:
+ if not fields:
+ return
+ with self._lock:
+ if "leaf" in fields:
+ self._leaf = max(self._leaf, _coerce_nonnegative_int(fields.get("leaf")))
+ elif "completed" in fields:
+ self._leaf = max(self._leaf, _coerce_nonnegative_int(fields.get("completed")))
+ if "llm" in fields:
+ self._llm = max(self._llm, _coerce_nonnegative_int(fields.get("llm")))
+ if "pending" in fields:
+ self._pending = _coerce_nonnegative_int(fields.get("pending"))
+ self._maybe_write()
+
+ def _maybe_write(self) -> None:
+ state = _read_state(self._settings)
+ build_state = _build_state_from_state(state)
+ if build_state.get("status") != "running" or build_state.get("stage") != "build":
+ return
+
+ now = time.monotonic()
+ current_progress = _coerce_progress(build_state.get("progress", 0.0))
+ progress = max(current_progress, self._last_progress, self._compute_progress())
+ progress = min(TREE_BUILD_PROGRESS_END, max(TREE_BUILD_PROGRESS_START, progress))
+ progress_changed = progress - self._last_progress >= TREE_BUILD_PROGRESS_MIN_DELTA
+ interval_elapsed = now - self._last_write >= TREE_BUILD_PROGRESS_MIN_INTERVAL_SECONDS
+ if not progress_changed or not interval_elapsed:
+ return
+
+ _write_build_progress(self._settings, progress=progress)
+ self._last_write = now
+ self._last_progress = progress
+
+ def _compute_progress(self) -> float:
+ leaf_ratio = min(1.0, self._leaf / self._total) if self._total > 0 else 0.0
+ llm_hint = min(TREE_BUILD_PROGRESS_LLM_HINT_LIMIT, self._llm * 0.01)
+ effective_ratio = max(leaf_ratio, llm_hint)
+ return TREE_BUILD_PROGRESS_START + (TREE_BUILD_PROGRESS_END - TREE_BUILD_PROGRESS_START) * effective_ratio
+
+
def _record_recovery_failure(candidate: Path, exc: Exception) -> None:
LOGGER.debug("Skipping unusable skill retrieval index recovery candidate %s: %s", candidate, exc)
@@ -627,6 +785,21 @@ def expected_index_fingerprint(inventory: SkillInventory, settings: SkillRetriev
return _expected_fingerprint(inventory, settings)
+def _stale_success_build_state() -> dict[str, Any]:
+ return {
+ "status": "idle",
+ "stage": "",
+ "message": "No usable skill index is available. Rebuild the index to use Agentic skill retrieval.",
+ "error": "",
+ "progress": 0.0,
+ "started_at": "",
+ "finished_at": "",
+ "elapsed_seconds": 0.0,
+ "cancel_requested": False,
+ "logs": [],
+ }
+
+
def _read_state(settings: SkillRetrievalSettings) -> dict[str, Any]:
path = _state_file(settings)
if not path.is_file():
@@ -692,6 +865,7 @@ def _write_build_state(
inventory: SkillInventory | None = None,
fingerprint: str | None = None,
clear_error: bool = False,
+ clear_logs: bool = False,
) -> None:
settings.artifact_root.mkdir(parents=True, exist_ok=True)
state = _read_state(settings)
@@ -720,14 +894,15 @@ def _write_build_state(
next_build["elapsed_seconds"] = float(elapsed_seconds)
if cancel_requested is not None:
next_build["cancel_requested"] = bool(cancel_requested)
+ logs = [] if clear_logs else next_build.get("logs", [])
next_build["logs"] = _append_log(
- next_build.get("logs", []),
+ 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:
+ if fingerprint and status == "success":
state["fingerprint"] = fingerprint
if inventory is not None:
state["inventory"] = inventory.to_state_payload()
@@ -737,6 +912,40 @@ def _write_build_state(
LOGGER.info("[skill-index] stage=%s status=%s detail=%s", stage, status, message)
+def repair_interrupted_build_state() -> bool:
+ settings = load_settings()
+ build_state = _build_state_from_state(_read_state(settings))
+ if build_state.get("status") != "running":
+ return False
+
+ message = "Previous skill index build was interrupted before it completed. Rebuild the index to continue."
+ _write_build_state(
+ settings,
+ status="failed",
+ stage="interrupted",
+ message=message,
+ error=message,
+ progress=1.0,
+ finished_at=_now_iso(),
+ cancel_requested=False,
+ )
+ return True
+
+
+def _write_build_progress(settings: SkillRetrievalSettings, *, progress: float) -> None:
+ state = _read_state(settings)
+ build_state = _build_state_from_state(state)
+ if build_state.get("status") != "running" or build_state.get("stage") != "build":
+ return
+ next_progress = _coerce_progress(progress)
+ if next_progress <= _coerce_progress(build_state.get("progress", 0.0)):
+ return
+ build_state["progress"] = next_progress
+ state["build"] = build_state
+ settings.artifact_root.mkdir(parents=True, exist_ok=True)
+ _state_file(settings).write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8")
+
+
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):
@@ -790,6 +999,13 @@ def _coerce_progress(value: Any) -> float:
return 0.0
+def _coerce_nonnegative_int(value: Any) -> int:
+ try:
+ return max(0, int(value))
+ except (TypeError, ValueError):
+ return 0
+
+
def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
@@ -817,12 +1033,10 @@ 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 "
diff --git a/jiuwenswarm/symphony/skill_retrieval/markdown.py b/jiuwenswarm/symphony/skill_retrieval/markdown.py
index ced5631d41..a15c018bae 100644
--- a/jiuwenswarm/symphony/skill_retrieval/markdown.py
+++ b/jiuwenswarm/symphony/skill_retrieval/markdown.py
@@ -72,18 +72,18 @@ def render_retrieve_success(
f"- Index directory: `{index_dir}`",
f"- Indexed skills: {indexed_count}",
f"- Retrieved candidates: {len(records)}",
- f"- Dispatch settings: {settings_summary}",
+ f"- Retrieval settings: {settings_summary}",
]
elapsed = getattr(result, "elapsed_ms", None)
if elapsed is not None:
- lines.append(f"- Dispatch elapsed: {float(elapsed):.0f}ms")
+ lines.append(f"- Retrieval elapsed: {float(elapsed):.0f}ms")
summary_lines = getattr(result, "summary_lines", None) or []
if summary_lines:
- lines.extend(["", "## Dispatch Summary"])
+ lines.extend(["", "## Retrieval Summary"])
lines.extend(f"- {line}" for line in summary_lines[:10])
lines.extend(["", "## Retrieved Skills"])
if not records:
- lines.append("No relevant installed skills were returned by dispatch.")
+ lines.append("No relevant installed skills were returned by retrieval.")
else:
for index, record in enumerate(records, start=1):
worker_id = str(record.get("worker_id") or record.get("resolved_payload") or "").strip()
diff --git a/jiuwenswarm/symphony/skill_retrieval/retrieve_service.py b/jiuwenswarm/symphony/skill_retrieval/retrieve_service.py
index 73d2745226..c130a30e7d 100644
--- a/jiuwenswarm/symphony/skill_retrieval/retrieve_service.py
+++ b/jiuwenswarm/symphony/skill_retrieval/retrieve_service.py
@@ -47,7 +47,7 @@ class SkillRetrieveService:
return {
"success": False,
"result": render_retrieve_failure(
- "Dispatch retrieval requires a model and API key. "
+ "Skill retrieval requires a model and API key. "
"Configure `models.defaults[0].model_client_config` or `symphony.skill_retrieval.llm`."
),
}
diff --git a/tests/agents/swarm/test_swarm_assembly.py b/tests/agents/swarm/test_swarm_assembly.py
index d8212497a2..d08cce2514 100644
--- a/tests/agents/swarm/test_swarm_assembly.py
+++ b/tests/agents/swarm/test_swarm_assembly.py
@@ -37,6 +37,7 @@ from openjiuwen.agent_teams.schema.deep_agent_spec import (
)
from openjiuwen.core.single_agent.rail.base import AgentCallbackContext, AgentRail, ToolCallInputs
from openjiuwen.harness.prompts.builder import SystemPromptBuilder
+from openjiuwen.harness.rails import SkillUseRail
from jiuwenswarm.agents.swarm import (
SwarmBuildContext,
@@ -435,16 +436,41 @@ def test_swarm_skill_retrieval_prompt_uses_global_skill_manager(
assert calls == [None]
+def test_code_skill_use_rail_kept_as_auto_list_when_retrieval_enabled(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ """Agentic retrieval hides list_skill later, but skill_tool stays available."""
+ monkeypatch.setattr(
+ "jiuwenswarm.agents.harness.common.tools.skill_retrieval_toolkits.is_skill_retrieval_enabled",
+ lambda: True,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.common.utils.get_agent_skills_dir",
+ lambda: tmp_path,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.server.runtime.skill.load_execution_disabled_skills",
+ lambda: [],
+ )
+
+ rail = code_rails.build_code_skill_use(
+ {"skill_mode": SkillUseRail.SKILL_MODE_ALL},
+ SwarmBuildContext(),
+ )
+
+ assert isinstance(rail, SkillUseRail)
+ assert rail.skill_mode == SkillUseRail.SKILL_MODE_AUTO_LIST
+
+
@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."""
+ """Chat-team members keep skill_tool while retrieval owns discovery."""
base = DeepAgentSpec(enable_skill_discovery=False)
spec = build_member_deep_agent_spec(_agentic_retrieval_config(), "team", role, base)
- rail_names = {rail.type for rail in (spec.rails or [])}
- assert spec.enable_skill_discovery is False
- assert "core.skill_use" not in rail_names
+ assert spec.enable_skill_discovery is True
@pytest.mark.parametrize("role", ["leader", "teammate"])
@@ -458,15 +484,15 @@ def test_team_member_deep_agent_spec_keeps_core_skill_discovery_when_retrieval_d
@pytest.mark.parametrize("mode", ["code.team", "team.plan"])
-def test_code_member_deep_agent_spec_omits_skill_use_rail_when_retrieval_enabled(mode: str) -> None:
- """Code profiles also let agentic retrieval own skill discovery."""
+def test_code_member_deep_agent_spec_keeps_skill_use_rail_when_retrieval_enabled(mode: str) -> None:
+ """Code profiles keep skill_tool while retrieval owns discovery."""
base = DeepAgentSpec(enable_skill_discovery=False)
spec = build_member_deep_agent_spec(_agentic_retrieval_config(), mode, "leader", base)
rail_names = {rail.type for rail in (spec.rails or [])}
assert spec.enable_skill_discovery is False
- assert registry.CODE_SKILL_USE not in rail_names
+ assert registry.CODE_SKILL_USE in rail_names
@pytest.mark.parametrize("mode", ["code.team", "team.plan"])
diff --git a/tests/symphony/test_agentic_retrieval_toolkit.py b/tests/symphony/test_agentic_retrieval_toolkit.py
index f9ab32dac2..0ec2d138fb 100644
--- a/tests/symphony/test_agentic_retrieval_toolkit.py
+++ b/tests/symphony/test_agentic_retrieval_toolkit.py
@@ -351,7 +351,7 @@ async def test_runtime_toolkit_methods_return_build_and_missing_index_results(mo
"build_skill_index",
lambda manager: {
"success": True,
- "result": "# Skill Index Build\n\nSkill index build started in the background.",
+ "result": "# Skill Retrieval Index\n\nThe index is ready.",
},
)
monkeypatch.setattr(
@@ -368,6 +368,6 @@ async def test_runtime_toolkit_methods_return_build_and_missing_index_results(mo
explore_result = await toolkit.skill_branch_explore(["OfficeDocs"])
assert build_result["success"] is True
- assert "started in the background" in build_result["result"]
+ assert "index is ready" 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
index 3d764f4d48..ea19d4d0f5 100644
--- a/tests/symphony/test_skill_retrieval_index_service.py
+++ b/tests/symphony/test_skill_retrieval_index_service.py
@@ -9,6 +9,8 @@ from jiuwenswarm.symphony.skill_retrieval.build_coordinator import (
cancel_skill_index_build,
start_skill_index_build,
)
+from jiuwenswarm.symphony.skill_retrieval import api as skill_retrieval_api
+from jiuwenswarm.symphony.skill_retrieval.api import build_skill_index
from jiuwenswarm.symphony.skill_retrieval.config import (
BuildSettings,
LLMSettings,
@@ -160,6 +162,11 @@ def test_background_build_marks_shared_state(monkeypatch, tmp_path: Path) -> Non
cancel_result = cancel_skill_index_build(manager)
release.set()
assert cancel_result["success"] is True
+ assert cancel_result["build_status"] == "cancelled"
+ state = json.loads((artifact_root / "state.json").read_text(encoding="utf-8"))
+ assert state["build"]["status"] == "cancelled"
+ assert state["build"]["stage"] == "cancelled"
+ assert state["build"]["cancel_requested"] is False
def test_force_build_bypasses_fresh_index_reuse(monkeypatch, tmp_path: Path) -> None:
@@ -193,6 +200,7 @@ def test_force_build_bypasses_fresh_index_reuse(monkeypatch, tmp_path: Path) ->
"jiuwenswarm.symphony.skill_retrieval.index_service.load_settings",
lambda: settings,
)
+ monkeypatch.setattr(SkillIndexService, "_check_build_llm_access", staticmethod(lambda settings: None))
calls: list[str] = []
def fake_run_dispatch_build(*, settings, inventory, output_dir):
@@ -241,6 +249,213 @@ def test_missing_llm_config_records_failure(monkeypatch, tmp_path: Path) -> None
assert state["build"]["stage"] == "llm_config"
+def test_build_fails_when_llm_access_check_fails(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="bad-key", base_url="https://example.invalid"),
+ build=BuildSettings(),
+ retrieve=RetrieveSettings(),
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.skill_retrieval.index_service.load_settings",
+ lambda: settings,
+ )
+
+ def fail_llm_access(settings):
+ raise RuntimeError("Skill index build model is not reachable or rejected the request: unauthorized")
+
+ monkeypatch.setattr(SkillIndexService, "_check_build_llm_access", staticmethod(fail_llm_access))
+
+ result = SkillIndexService(SimpleNamespace(_skills_dir=skills_dir)).build_index(force=True)
+
+ assert result["success"] is False
+ assert "not reachable" in result["result"]
+ assert not (artifact_root / "index").exists()
+ state = json.loads((artifact_root / "state.json").read_text(encoding="utf-8"))
+ assert state["build"]["status"] == "failed"
+ assert state["build"]["stage"] == "failed"
+ assert "not reachable" in state["build"]["error"]
+
+
+def test_status_ignores_success_state_when_index_artifacts_are_deleted(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(),
+ )
+ inventory = scan_skill_inventory(SimpleNamespace(_skills_dir=skills_dir))
+ artifact_root.mkdir(parents=True)
+ (artifact_root / "state.json").write_text(
+ json.dumps(
+ {
+ "fingerprint": expected_index_fingerprint(inventory, settings),
+ "indexed_count": inventory.count,
+ "build": {"status": "success", "stage": "success", "progress": 1.0},
+ }
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.skill_retrieval.index_service.load_settings",
+ lambda: settings,
+ )
+
+ status = SkillIndexService(SimpleNamespace(_skills_dir=skills_dir)).status()
+ tree = SkillIndexService(SimpleNamespace(_skills_dir=skills_dir)).tree(language="zh")
+
+ assert status["index_exists"] is False
+ assert status["fresh"] is False
+ assert status["build_status"] == "idle"
+ assert status["build_logs"] == []
+ assert "No usable skill index" in status["build_message"]
+ assert tree["success"] is False
+ assert tree["nodes"] == []
+
+
+def test_api_status_repairs_interrupted_running_state(monkeypatch, tmp_path: Path) -> None:
+ skills_dir = tmp_path / "skills"
+ skills_dir.mkdir()
+ artifact_root = tmp_path / "artifact"
+ artifact_root.mkdir()
+ (artifact_root / "state.json").write_text(
+ json.dumps({"build": {"status": "running", "stage": "build", "progress": 0.5}}),
+ 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(skill_retrieval_api, "_STARTUP_REPAIR_DONE", False)
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.skill_retrieval.build_coordinator.load_settings",
+ lambda: settings,
+ )
+ monkeypatch.setattr(
+ "jiuwenswarm.symphony.skill_retrieval.index_service.load_settings",
+ lambda: settings,
+ )
+
+ status = skill_retrieval_api.get_skill_retrieval_status(SimpleNamespace(_skills_dir=skills_dir))
+
+ assert status["build_status"] == "failed"
+ assert status["build_stage"] == "interrupted"
+ assert "interrupted" in status["build_error"]
+
+
+def test_api_status_keeps_active_build_running(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(skill_retrieval_api, "_STARTUP_REPAIR_DONE", False)
+ 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()
+ manager = SimpleNamespace(_skills_dir=tmp_path / "skills")
+
+ 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)
+
+ start_skill_index_build(manager, force=True, source="web")
+ assert started.wait(timeout=1)
+ status = skill_retrieval_api.get_skill_retrieval_status(manager)
+ release.set()
+
+ assert status["build_status"] == "running"
+ assert status["build_stage"] == "queued"
+
+
+def test_build_skill_index_api_waits_for_shared_background_build(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,
+ )
+ calls: list[tuple[bool, str]] = []
+ started = threading.Event()
+ release = threading.Event()
+ manager = SimpleNamespace(_skills_dir=tmp_path / "skills")
+
+ def fake_build_index(self, *, force=False, cancel_check=None, source="tool"):
+ calls.append((force, source))
+ started.set()
+ release.wait(timeout=1)
+ return {"success": True, "result": "# Skill Retrieval Index\n\nDone."}
+
+ monkeypatch.setattr(SkillIndexService, "build_index", fake_build_index)
+ monkeypatch.setattr(
+ SkillIndexService,
+ "status",
+ lambda self: {"build_status": "success", "index_exists": True, "fresh": True},
+ )
+
+ web_result = start_skill_index_build(manager, force=True, source="web")
+ assert started.wait(timeout=1)
+ state = json.loads((artifact_root / "state.json").read_text(encoding="utf-8"))
+ assert web_result["build_status"] == "running"
+ assert state["build"]["status"] == "running"
+
+ result_box: list[dict] = []
+ tool_thread = threading.Thread(
+ target=lambda: result_box.append(build_skill_index(manager, force=True, source="tool"))
+ )
+ tool_thread.start()
+ release.set()
+ tool_thread.join(timeout=1)
+
+ assert result_box == [
+ {
+ "success": True,
+ "result": (
+ "# Skill Index Build\n\n"
+ "Skill index build completed. You can now call `skill_branch_explore` "
+ "or `skill_branch_peek` to inspect installed skills."
+ ),
+ }
+ ]
+ assert calls == [(True, "web")]
+
+
def test_tree_rejects_stale_manifest_and_uses_requested_language(monkeypatch, tmp_path: Path) -> None:
skills_dir = tmp_path / "skills"
skills_dir.mkdir()
@@ -275,10 +490,12 @@ def test_tree_rejects_stale_manifest_and_uses_requested_language(monkeypatch, tm
assert zh["success"] is False
assert zh["nodes"] == []
- assert "技能索引树" in zh["result"]
+ assert "# 技能索引树" not in zh["result"]
+ assert "当前没有可用" in zh["result"]
assert en["success"] is False
assert en["nodes"] == []
- assert "Skill Index Tree" in en["result"]
+ assert "# Skill Index Tree" not in en["result"]
+ assert "No usable" in en["result"]
def test_build_error_normalizes_non_streaming_remote_model_error(monkeypatch, tmp_path: Path) -> None:
@@ -297,6 +514,7 @@ def test_build_error_normalizes_non_streaming_remote_model_error(monkeypatch, tm
"jiuwenswarm.symphony.skill_retrieval.index_service.load_settings",
lambda: settings,
)
+ monkeypatch.setattr(SkillIndexService, "_check_build_llm_access", staticmethod(lambda settings: None))
def raise_remote_error(*, settings, inventory, output_dir):
raise RuntimeError("set to false for non-streaming calls")
diff --git a/tests/symphony/test_tree_llm_runtime.py b/tests/symphony/test_tree_llm_runtime.py
new file mode 100644
index 0000000000..09ccf23db6
--- /dev/null
+++ b/tests/symphony/test_tree_llm_runtime.py
@@ -0,0 +1,88 @@
+from __future__ import annotations
+
+import threading
+from types import SimpleNamespace
+
+import pytest
+
+from jiuwenswarm.symphony.skill_retrieval.dispatch_imports import dispatch_import_path
+
+
+class _FailingCompletions:
+ def __init__(self) -> None:
+ self.calls = 0
+
+ def create(self, **kwargs):
+ self.calls += 1
+ raise RuntimeError("invalid api key")
+
+
+class _StaticCompletions:
+ def __init__(self, content: str, *, finish_reason: str = "stop") -> None:
+ self.content = content
+ self.finish_reason = finish_reason
+ self.calls = 0
+
+ def create(self, **kwargs):
+ self.calls += 1
+ message = SimpleNamespace(content=self.content)
+ choice = SimpleNamespace(finish_reason=self.finish_reason, message=message)
+ return SimpleNamespace(choices=[choice])
+
+
+def _fake_builder(completions: object) -> SimpleNamespace:
+ return SimpleNamespace(
+ DEFAULT_CONTEXT_WINDOW=128000,
+ DEFAULT_MAX_OUTPUT_TOKENS=32768,
+ model="fake-model",
+ _client=SimpleNamespace(chat=SimpleNamespace(completions=completions)),
+ _manager_config=SimpleNamespace(build=SimpleNamespace(num_retries=2, timeout=1.0)),
+ _llm_seed=None,
+ _max_output_tokens_cache=None,
+ _counter_lock=threading.Lock(),
+ _llm_calls=0,
+ _retry_calls=0,
+ _cache_hits=0,
+ _cache_misses=0,
+ _cache_unknown=0,
+ _prompt_fingerprints=set(),
+ _progress=None,
+ _progress_task=None,
+ _llm_semaphore=threading.Semaphore(1),
+ _thread_local=threading.local(),
+ _consecutive_failures=0,
+ max_consecutive_failures=5,
+ )
+
+
+def test_tree_llm_runtime_raises_on_model_failure() -> None:
+ with dispatch_import_path():
+ from indexing.tree.llm_runtime import TreeLLMRuntime
+
+ completions = _FailingCompletions()
+ builder = _fake_builder(completions)
+
+ with pytest.raises(RuntimeError, match="model call failed"):
+ TreeLLMRuntime(builder).call_llm("build a skill tree")
+
+ assert completions.calls == 1
+
+
+def test_tree_llm_runtime_raises_after_invalid_json_retries() -> None:
+ with dispatch_import_path():
+ from indexing.tree.llm_runtime import TreeLLMRuntime
+
+ completions = _StaticCompletions("not json")
+ with pytest.raises(RuntimeError, match="valid JSON object"):
+ TreeLLMRuntime(_fake_builder(completions)).call_llm_json("build a skill tree", max_retries=2)
+
+ assert completions.calls == 2
+
+
+def test_tree_llm_runtime_raises_on_truncated_json() -> None:
+ with dispatch_import_path():
+ from indexing.tree.llm_runtime import TreeLLMRuntime
+
+ completions = _StaticCompletions('{"groups": {}', finish_reason="length")
+ with pytest.raises(RuntimeError, match="truncated"):
+ TreeLLMRuntime(_fake_builder(completions)).call_llm_json("build a skill tree")
diff --git a/tests/unit_tests/agentserver/test_system_prompt_restructure.py b/tests/unit_tests/agentserver/test_system_prompt_restructure.py
index 878b0aa601..904bab2ebf 100644
--- a/tests/unit_tests/agentserver/test_system_prompt_restructure.py
+++ b/tests/unit_tests/agentserver/test_system_prompt_restructure.py
@@ -5,6 +5,7 @@ import pytest
from openjiuwen.core.foundation.llm import Model
from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
+from openjiuwen.harness.rails.skills.skill_use_rail import SkillUseRail
from openjiuwen.harness.prompts.prompt_attachment_manager import (
PromptAttachmentManager,
)
@@ -52,6 +53,13 @@ class _FakeAbilityManager:
self.added: list[str] = []
self.removed: list[str] = []
+ def add_ability(self, card, tool=None):
+ self._items[card.name] = card
+ return SimpleNamespace(added=True)
+
+ def remove_ability(self, name: str):
+ return self._items.pop(name, None)
+
def get(self, name: str):
return self._items.get(name)
@@ -406,6 +414,56 @@ async def test_skill_retrieval_prompt_hides_legacy_list_skill(monkeypatch):
assert "旧 list_skill 提示" in builder.build()
+async def test_skill_retrieval_prompt_hides_native_skill_prompt_after_skill_use_rail(
+ monkeypatch,
+ tmp_path,
+):
+ 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: "# Agentic 技能检索\n使用 skill_branch_explore。",
+ )
+ builder = SystemPromptBuilder(language="cn")
+ agent = _FakeToolAgent(builder)
+ agent.card = SimpleNamespace(id="test-agent")
+ agent.deep_config = SimpleNamespace(enable_read_image_multimodal=False)
+ ctx = AgentCallbackContext(
+ agent=agent,
+ inputs=SimpleNamespace(
+ tools=[
+ SimpleNamespace(name="list_skill"),
+ SimpleNamespace(name="skill_branch_explore"),
+ ],
+ ),
+ session=_FakeSession(),
+ extra={},
+ )
+ skill_rail = SkillUseRail(
+ str(tmp_path),
+ skill_mode=SkillUseRail.SKILL_MODE_AUTO_LIST,
+ include_tools=False,
+ )
+ retrieval_rail = SkillRetrievalPromptRail()
+ skill_rail.init(agent)
+ retrieval_rail.init(agent)
+
+ rails = sorted([skill_rail, retrieval_rail], key=lambda rail: rail.priority, reverse=True)
+ await rails[0].before_model_call(ctx)
+ await rails[1].before_model_call(ctx)
+
+ prompt = builder.build()
+ assert "需要时先调用 list_skill 查看可用技能" not in prompt
+ assert "# 技能" not in prompt
+ assert "Agentic 技能检索" in prompt
+ assert [tool.name for tool in ctx.inputs.tools] == ["skill_branch_explore"]
+
+
@pytest.mark.asyncio
async def test_skill_retrieval_prompt_clears_section_when_disabled(monkeypatch):
monkeypatch.setattr(
@@ -561,6 +619,71 @@ def test_deep_adapter_skill_retrieval_prompt_uses_visible_skill_provider(monkeyp
assert captured["visible_skill_names"] == adapter._visible_skill_names_for_list_skill
+async def test_deep_adapter_skill_retrieval_prompt_rail_sync_hot_toggles(monkeypatch):
+ registered: list[object] = []
+ unregistered: list[object] = []
+
+ class FakeDeepAgent:
+ async def register_rail(self, rail):
+ registered.append(rail)
+
+ async def unregister_rail(self, rail):
+ unregistered.append(rail)
+
+ adapter = _TestableJiuWenSwarmDeepAdapter()
+ adapter._instance = FakeDeepAgent()
+ rail = SimpleNamespace(name="skill_retrieval_prompt")
+ monkeypatch.setattr(adapter, "_build_skill_retrieval_prompt_rail", lambda: rail)
+ monkeypatch.setattr(
+ adapter,
+ "_skill_retrieval_tools_enabled_for_runtime",
+ lambda config_base=None: True,
+ )
+
+ await adapter._sync_skill_retrieval_prompt_rail_for_runtime()
+ await adapter._sync_skill_retrieval_prompt_rail_for_runtime()
+
+ assert adapter._skill_retrieval_prompt_rail is rail
+ assert registered == [rail]
+ assert unregistered == []
+
+ monkeypatch.setattr(
+ adapter,
+ "_skill_retrieval_tools_enabled_for_runtime",
+ lambda config_base=None: False,
+ )
+
+ await adapter._sync_skill_retrieval_prompt_rail_for_runtime()
+
+ assert adapter._skill_retrieval_prompt_rail is None
+ assert unregistered == [rail]
+
+
+def test_code_adapter_skill_retrieval_sync_respects_configured_tools(monkeypatch):
+ from jiuwenswarm.server.runtime.agent_adapter.interface_code import JiuwenSwarmCodeAdapter
+
+ adapter = JiuwenSwarmCodeAdapter()
+ monkeypatch.setattr(
+ interface_module,
+ "is_skill_retrieval_enabled",
+ lambda: True,
+ )
+
+ assert (
+ adapter._skill_retrieval_tools_enabled_for_runtime(
+ {"modes": {"code": {"tools": ["skill_toolkit"]}}}
+ )
+ is False
+ )
+ assert (
+ adapter._skill_retrieval_tools_enabled_for_runtime(
+ {"modes": {"code": {"tools": ["skill_toolkit", "skill_retrieval"]}}}
+ )
+ is True
+ )
+
+
def test_resolve_enable_task_loop_can_be_called_on_class(monkeypatch):
monkeypatch.delenv("SKILL_CREATE", raising=False)
assert (