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(evolution): adapt skill evolution commands and triggers
z2tngb1e076967ad5
diff --git a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.pyindex 42b4703047..52a658e47b 100644--- a/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py+++ b/jiuwenswarm/agents/harness/common/rails/interrupt/interrupt_helpers.py@@ -13,6 +13,12 @@ from typing import Anyfrom jiuwenswarm.common.utils import logger+SKILL_EVOLUTION_APPROVAL_SCHEMA = "openjiuwen.skill_evolution_approval.v1"+SKILL_EVOLUTION_APPROVAL_TOOL_KINDS = {+ "evolve_skill_experiences": "evolve",+ "simplify_skill_experiences": "simplify",+}+def build_permission_rail(config: dict[str, Any],@@ -491,6 +497,9 @@ def convert_interactions_to_ask_user_question(state_outputs: list) -> dict | Nonpayload["plan_path"] = plan_pathif plan_slug:payload["plan_slug"] = plan_slug+ structured_approval = _classify_structured_approval(value_obj, question_data)+ if structured_approval:+ payload.update(structured_approval)return payloadreturn None@@ -566,20 +575,85 @@ def _build_multi_questions(questions_data: list) -> list:for q in questions_data:raw_options = q.get("options", [])if raw_options:- options = [{"label": opt["label"], "description": opt.get("description", "")}- for opt in raw_options]+ options = [_normalize_question_option(opt) for opt in raw_options if isinstance(opt, dict)]options.append({"label": "Other", "description": "Custom input"})else:options = []- questions.append({+ question_payload = {"question": q["question"],"header": q["header"],"options": options,"multi_select": q.get("multi_select", False),- })+ }+ questions.append(question_payload)return questions+def _extract_ui_options(value_obj: Any) -> list[dict[str, Any]]:+ options = getattr(value_obj, "ui_options", None) if hasattr(value_obj, "ui_options") else None+ if options is None and isinstance(value_obj, dict):+ options = value_obj.get("ui_options")+ return [item for item in options or [] if isinstance(item, dict)]+++def _extract_tool_name(value_obj: Any) -> str:+ if hasattr(value_obj, "tool_name"):+ return str(getattr(value_obj, "tool_name", "") or "")+ if isinstance(value_obj, dict):+ return str(value_obj.get("tool_name") or "")+ return ""+++def _normalize_question_option(option: dict[str, Any]) -> dict[str, Any]:+ normalized = {+ "label": str(option.get("label") or option.get("value") or "").strip(),+ "description": str(option.get("description") or "").strip(),+ }+ value = option.get("value")+ if isinstance(value, str) and value:+ normalized["value"] = value+ return normalized+++def _default_interrupt_options() -> list[dict[str, str]]:+ return [+ {"label": "本次允许", "description": "仅本次授权执行"},+ {"label": "总是允许", "description": "记住该规则,以后自动放行"},+ {"label": "拒绝", "description": "拒绝执行此工具"},+ ]+++def _question_options_from_ui_options(value_obj: Any) -> list[dict[str, Any]]:+ options = []+ for option in _extract_ui_options(value_obj):+ normalized = _normalize_question_option(option)+ if normalized["label"]:+ options.append(normalized)+ return options or _default_interrupt_options()+++def _classify_structured_approval(+ value_obj: Any,+ question_data: dict[str, Any],+) -> dict[str, Any] | None:+ del question_data+ tool_name = _extract_tool_name(value_obj)+ if tool_name not in SKILL_EVOLUTION_APPROVAL_TOOL_KINDS:+ return None+ approval_kind = SKILL_EVOLUTION_APPROVAL_TOOL_KINDS[tool_name]++ return {+ "source": "skill_evolution_approval",+ "approval_schema": SKILL_EVOLUTION_APPROVAL_SCHEMA,+ "evolution_meta": {+ "event_kind": "approval",+ "rail_kind": "regular",+ "approval_kind": approval_kind,+ "approval_transport": "interrupt",+ },+ }++def extract_question_from_interaction(payload: Any) -> dict | None:"""Extract question info from a single interaction payload.@@ -622,10 +696,5 @@ def extract_question_from_interaction(payload: Any) -> dict | None:return {"question": message,"header": header,- "options": [- {"label": "本次允许", "description": "仅本次授权执行"},- {"label": "总是允许", "description": "记住该规则,以后自动放行"},- {"label": "拒绝", "description": "拒绝执行此工具"},- ],- "multi_select": False,+ "options": _question_options_from_ui_options(value_obj),}diff --git a/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py b/jiuwenswarm/agents/harness/team/team_runtime_inheritance.pyindex d2925e0a6f..25e279cd93 100644--- a/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py+++ b/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py@@ -18,11 +18,13 @@ from openjiuwen.harness.rails import (SysOperationRail,HeartbeatRail,SecurityRail,+ EvolutionInterruptRail,SkillEvolutionRail,TaskPlanningRail,TeamSkillEvolutionRail,TeamSkillCreateRail,)+from openjiuwen.harness.rails.evolution import EvolutionReviewRuntimefrom openjiuwen.harness.rails.context_engineer import ContextProcessorRailfrom jiuwenswarm.agents.harness.common.rails.avatar_rail import AvatarPromptRail@@ -74,6 +76,7 @@ RAIL_WHITELIST = frozenset({"SysOperationRail","TeamSkillEvolutionRail","TeamSkillCreateRail",+ "EvolutionInterruptRail","SkillEvolutionRail","TeamWorkspaceReportPathRail","ContextProcessorRail",@@ -149,9 +152,6 @@ def build_member_rails(runtime = runtime or RuntimeInfo()team_workspace = team_workspace or TeamWorkspaceInfo()- # 从 dataclass 提取参数- agent_name = member_info.agent_name- model_name = member_info.model_namerole = member_info.rolechannel = runtime.channellanguage = runtime.language@@ -248,10 +248,12 @@ def build_member_rails(llm_model, actual_model_name = build_evolution_llm()evolution_auto_scan = get_evolution_auto_scan_enabled(config)bound_team_trajectory_registry = team_trajectory_registry if team_id else None+ review_runtime = EvolutionReviewRuntime()team_skill_rail = TeamSkillEvolutionRail(skills_dir=team_ws_skills_dir,llm=llm_model,model=actual_model_name,+ review_runtime=review_runtime,language=language,trajectory_source=bound_team_trajectory_registry,trajectory_sink=bound_team_trajectory_registry,@@ -261,6 +263,14 @@ def build_member_rails(team_id=team_id,disabled_skills=load_execution_disabled_skills(),)+ rails_list.append(+ EvolutionInterruptRail(+ review_runtime=review_runtime,+ submission_service=team_skill_rail.experience_manager.experience_submission_service,+ auto_save=False,+ language=language,+ )+ )rails_list.append(team_skill_rail)logger.info("[TeamRuntime] TeamSkillEvolutionRail created: skills_dir=%s, "@@ -293,13 +303,27 @@ def build_member_rails(# Non-leader: SkillEvolutionRail for member skill self-evolution.if role != "leader" and team_ws_skills_dir:+ review_runtime = EvolutionReviewRuntime()evo_rail = build_skill_evolution_rail(skills_dir=team_ws_skills_dir,config=config,team_trajectory_sink=team_trajectory_registry,team_id=team_id,+ review_runtime=review_runtime,)if evo_rail is not None:+ try:+ rails_list.append(+ EvolutionInterruptRail(+ review_runtime=review_runtime,+ submission_service=evo_rail.experience_manager.experience_submission_service,+ auto_save=True,+ language=language,+ )+ )+ logger.info("[TeamRuntime] EvolutionInterruptRail created for member skill evolution")+ except Exception as exc:+ logger.warning("[TeamRuntime] EvolutionInterruptRail failed: %s", exc, exc_info=True)rails_list.append(evo_rail)# Context compression rail for all members (leader + teammates).@@ -495,6 +519,7 @@ def build_skill_evolution_rail(config: dict[str, Any] | None = None,team_trajectory_sink: Any | None = None,team_id: str | None = None,+ review_runtime: EvolutionReviewRuntime | None = None,) -> Any | None:"""为 Team member 构造 SkillEvolutionRail.@@ -508,11 +533,13 @@ def build_skill_evolution_rail(try:llm, model_name = build_evolution_llm(config)evolution_auto_scan = get_evolution_auto_scan_enabled(config)+ review_runtime = review_runtime or EvolutionReviewRuntime()rail = SkillEvolutionRail(skills_dir=skills_dir,llm=llm,model=model_name,+ review_runtime=review_runtime,auto_scan=evolution_auto_scan,auto_save=True,disabled_skills=load_execution_disabled_skills(),diff --git a/jiuwenswarm/agents/swarm/providers/evolution_rails.py b/jiuwenswarm/agents/swarm/providers/evolution_rails.pyindex e9ba34a5d4..eea676b789 100644--- a/jiuwenswarm/agents/swarm/providers/evolution_rails.py+++ b/jiuwenswarm/agents/swarm/providers/evolution_rails.py@@ -30,10 +30,12 @@ from openjiuwen.agent_teams.harness.manifest import (param_field,)from openjiuwen.harness.rails import (+ EvolutionInterruptRail,SkillEvolutionRail,TeamSkillCreateRail,TeamSkillEvolutionRail,)+from openjiuwen.harness.rails.evolution import EvolutionReviewRuntimefrom jiuwenswarm.agents.swarm.context import SwarmBuildContextfrom jiuwenswarm.server.runtime.skill import load_execution_disabled_skills@@ -44,6 +46,7 @@ logger = logging.getLogger(__name__)TEAM_SKILL_EVOLUTION = "swarm.team_skill_evolution"TEAM_SKILL_CREATE = "swarm.team_skill_create"MEMBER_SKILL_EVOLUTION = "swarm.member_skill_evolution"+EVOLUTION_INTERRUPT = "swarm.evolution_interrupt"def _build_team_workspace_info(@@ -346,6 +349,33 @@ def _build_evolution_llm_from(model_config: dict[str, Any]) -> tuple[Any, str]:), model_name+def _build_evolution_approval_stack(+ rail: SkillEvolutionRail,+ *,+ review_runtime: EvolutionReviewRuntime,+ auto_save: bool,+ language: str,+) -> list[Any]:+ """Return the approval interrupt plus evolution rail in registration order."""+ return [+ EvolutionInterruptRail(+ review_runtime=review_runtime,+ submission_service=rail.approval_submission_service,+ auto_save=auto_save,+ language=language,+ ),+ rail,+ ]+++harness_element(+ kind=ElementKind.RAIL,+ name=EVOLUTION_INTERRUPT,+ description="Active Skill evolution mutation approval interrupt rail.",+ builder=EvolutionInterruptRail,+)++class TeamSkillEvolutionInput(ConstructionInput):"""Construction inputs for the leader team skill-evolution rail."""@@ -388,7 +418,7 @@ class TeamSkillEvolutionInput(ConstructionInput):def build_team_skill_evolution_rail(params: dict[str, Any],ctx: SwarmBuildContext,-) -> SwarmTeamSkillEvolutionRail | None:+) -> list[Any]:"""Build the leader-only team skill evolution rail from the config source.Mirrors the leader branch of the legacy ``build_member_rails``: builds the@@ -401,12 +431,13 @@ def build_team_skill_evolution_rail(ctx: The per-member build context.Returns:- A ``SwarmTeamSkillEvolutionRail`` for the leader, or ``None`` when the- member is not the leader or no team skills directory is configured.+ ``[EvolutionInterruptRail, SwarmTeamSkillEvolutionRail]`` for the leader,+ or ``[]`` when the member is not the leader or no team skills directory+ is configured."""# Cheap gate before resolving (avoids building the evolution LLM for non-leaders).if ctx.role != "leader" or not ctx.team_skills_dir:- return None+ return []try:inp = TeamSkillEvolutionInput.resolve(params, ctx)@@ -415,10 +446,12 @@ def build_team_skill_evolution_rail(inp.evolution_model_config)bound_registry = inp.trajectory_registry if inp.team_id else None+ review_runtime = EvolutionReviewRuntime()rail = SwarmTeamSkillEvolutionRail(inp.team_skills_dir,llm=llm_model,model=actual_model_name,+ review_runtime=review_runtime,language=inp.language,trajectory_source=bound_registry,trajectory_sink=bound_registry,@@ -443,12 +476,17 @@ def build_team_skill_evolution_rail(actual_model_name,inp.auto_scan,)- return rail+ return _build_evolution_approval_stack(+ rail,+ review_runtime=review_runtime,+ auto_save=False,+ language=inp.language,+ )except Exception as exc:logger.warning("[swarm.team_skill_evolution] build failed: %s", exc, exc_info=True)- return None+ return []class TeamSkillCreateInput(ConstructionInput):@@ -549,6 +587,9 @@ class MemberSkillEvolutionInput(ConstructionInput):team_skills_dir: str | None = context_field(attr="team_skills_dir", description="Team shared skills directory.")+ language: str = context_field(+ attr="language", default="cn", description="Member language code."+ )trajectory_registry: Any = context_field(attr="trajectory_registry", description="Per-team trajectory registry.")@@ -571,7 +612,7 @@ class MemberSkillEvolutionInput(ConstructionInput):def build_member_skill_evolution_rail(params: dict[str, Any],ctx: SwarmBuildContext,-) -> SwarmMemberSkillEvolutionRail | None:+) -> list[Any]:"""Build the teammate-only member skill evolution rail from the config source.Replicates ``build_skill_evolution_rail`` (auto-scan, ``auto_save=True``,@@ -584,22 +625,26 @@ def build_member_skill_evolution_rail(ctx: The per-member build context.Returns:- A ``SwarmMemberSkillEvolutionRail`` for non-leader members, or ``None``- when the member is the leader or no team skills directory is configured.+ ``[EvolutionInterruptRail, SwarmMemberSkillEvolutionRail]`` for non-leader+ members, or ``[]`` when the member is the leader or no team skills+ directory is configured."""# Cheap gate before resolving (avoids building the evolution LLM for the leader).if ctx.role == "leader" or not ctx.team_skills_dir:- return None+ return []try:inp = MemberSkillEvolutionInput.resolve(params, ctx)llm_model, actual_model_name = _build_evolution_llm_from(inp.evolution_model_config)+ review_runtime = EvolutionReviewRuntime()rail = SwarmMemberSkillEvolutionRail(inp.team_skills_dir,llm=llm_model,model=actual_model_name,+ review_runtime=review_runtime,+ language=inp.language,auto_scan=inp.auto_scan,auto_save=True,disabled_skills=load_execution_disabled_skills(),@@ -618,15 +663,21 @@ def build_member_skill_evolution_rail(inp.auto_scan,inp.trajectory_registry is not None and bool(inp.team_id),)- return rail+ return _build_evolution_approval_stack(+ rail,+ review_runtime=review_runtime,+ auto_save=True,+ language=inp.language,+ )except Exception as exc:logger.warning("[swarm.member_skill_evolution] build failed: %s", exc, exc_info=True)- return None+ return []__all__ = [+ "EVOLUTION_INTERRUPT","TEAM_SKILL_EVOLUTION","TEAM_SKILL_CREATE","MEMBER_SKILL_EVOLUTION",diff --git a/jiuwenswarm/agents/swarm/registry.py b/jiuwenswarm/agents/swarm/registry.pyindex 0b68637ffd..4d499ab864 100644--- a/jiuwenswarm/agents/swarm/registry.py+++ b/jiuwenswarm/agents/swarm/registry.py@@ -27,6 +27,7 @@ from openjiuwen.agent_teams.rails.builtin_elements import (HEARTBEAT as _OJ_HEARTBEAT,LSP as _OJ_LSP,SECURITY as _OJ_SECURITY,+ SUBAGENT as _OJ_SUBAGENT,SYS_OPERATION as _OJ_SYS_OPERATION,TASK_PLANNING as _OJ_TASK_PLANNING,VISION as _OJ_VISION,@@ -86,6 +87,7 @@ SKILL_RETRIEVAL_PROMPT = _member_rails.SKILL_RETRIEVAL_PROMPTTEAM_SKILL_EVOLUTION = _evolution_rails.TEAM_SKILL_EVOLUTIONTEAM_SKILL_CREATE = _evolution_rails.TEAM_SKILL_CREATEMEMBER_SKILL_EVOLUTION = _evolution_rails.MEMBER_SKILL_EVOLUTION+EVOLUTION_INTERRUPT = _evolution_rails.EVOLUTION_INTERRUPT# Code-mode (code.team / team.plan) swarm-owned rail provider names.CODE_EXTRA_TOOLS = _tools.CODE_EXTRA_TOOLS@@ -116,6 +118,7 @@ AVATAR_PROMPT = _builtin_rails.AVATAR_PROMPT# Generic rails provided + registered by openjiuwen (referenced by bare name).SYS_OPERATION = _OJ_SYS_OPERATIONTASK_PLANNING = _OJ_TASK_PLANNING+SUBAGENT = _OJ_SUBAGENTSECURITY = _OJ_SECURITYHEARTBEAT = _OJ_HEARTBEATCODE_LSP = _OJ_LSPdiff --git a/jiuwenswarm/channels/tui/frontend/src/app-state.ts b/jiuwenswarm/channels/tui/frontend/src/app-state.tsindex 5de5bb2c8b..86c811a46a 100644--- a/jiuwenswarm/channels/tui/frontend/src/app-state.ts+++ b/jiuwenswarm/channels/tui/frontend/src/app-state.ts@@ -1272,12 +1272,18 @@ export class CliPiAppState {return;}const source = this.pendingQuestion.source;-- if (+ const approvalTransport =+ this.pendingQuestion.evolutionMeta &&+ typeof this.pendingQuestion.evolutionMeta.approval_transport === "string"+ ? this.pendingQuestion.evolutionMeta.approval_transport+ : undefined;+ const shouldResumeInterrupt =source === "permission_interrupt" ||source === "confirm_interrupt" ||- source === "ask_user_interrupt"- ) {+ source === "ask_user_interrupt" ||+ (source === "skill_evolution_approval" && approvalTransport === "interrupt");++ if (shouldResumeInterrupt) {const resumeMode = this.pendingQuestion.resumeMode ?? this.mode;this.sendEventOnly("chat.send",diff --git a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InlineQuestionCard.tsx b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InlineQuestionCard.tsxindex 69081b699d..b0b39d2ec8 100644--- a/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InlineQuestionCard.tsx+++ b/jiuwenswarm/channels/web/frontend/src/components/ChatPanel/InlineQuestionCard.tsx@@ -11,7 +11,7 @@import { useState, useCallback, useMemo, useEffect } from 'react';import { useTranslation } from 'react-i18next';import { useChatStore } from '../../stores';-import { UserAnswer, QuestionOption } from '../../types';+import { UserAnswer, QuestionOption, Question } from '../../types';import ReactMarkdown from 'react-markdown';import remarkGfm from 'remark-gfm';@@ -19,6 +19,14 @@ interface InlineQuestionCardProps {onSubmit: (requestId: string, answers: UserAnswer[], source?: string) => void;}+function ApprovalQuestionContent({ question }: { question: Question }) {+ return (+ <ReactMarkdown remarkPlugins={[remarkGfm]}>+ {question.question}+ </ReactMarkdown>+ );+}+export function InlineQuestionCard({ onSubmit }: InlineQuestionCardProps) {const { t } = useTranslation();const { pendingQuestion, setPendingQuestion } = useChatStore();@@ -209,9 +217,7 @@ export function InlineQuestionCard({ onSubmit }: InlineQuestionCardProps) {className="px-4 pt-3 pb-2 text-sm prose prose-sm max-w-none prose-headings:font-semibold prose-headings:text-sm prose-ul:my-1 prose-li:my-0 prose-li:pl-1"style={{ color: 'var(--text)' }}>- <ReactMarkdown remarkPlugins={[remarkGfm]}>- {question.question}- </ReactMarkdown>+ <ApprovalQuestionContent question={question} /></div>{/* 选项按钮 */}diff --git a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.tsindex 3db17d3633..b5d6ec4397 100644--- a/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts+++ b/jiuwenswarm/channels/web/frontend/src/hooks/useWebSocket.ts@@ -46,6 +46,18 @@ import {const WS_RECONNECT_EVENT = 'jiuwenclaw:ws-reconnect-request';+function isCompletedResumeResult(interruptResult: unknown): boolean {+ if (!interruptResult || typeof interruptResult !== 'object') {+ return false;+ }+ const result = interruptResult as {+ intent?: unknown;+ success?: unknown;+ has_active_task?: unknown;+ };+ return result.intent === 'resume' && result.success === true && result.has_active_task === false;+}+const TEAM_TASK_STATUS_SET = new Set<TeamTaskStatus>(['pending','blocked',@@ -989,25 +1001,42 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {async (sessionId: string, requestId: string, answers: UserAnswer[], source?: string) => {try {const pendingQuestion = useChatStore.getState().pendingQuestion;+ const pendingMatches = pendingQuestion?.request_id === requestId;+ const effectiveSource = source ?? (pendingMatches ? pendingQuestion?.source : undefined);+ const approvalSchema =+ pendingMatches+ ? pendingQuestion?.approvalSchema+ : undefined;const evolutionMeta =- pendingQuestion?.request_id === requestId+ pendingMatches? pendingQuestion.evolutionMeta: undefined;const evolutionMetaPayload =evolutionMeta && typeof evolutionMeta === 'object'? { evolution_meta: evolutionMeta }: {};+ const approvalSchemaPayload = approvalSchema ? { approval_schema: approvalSchema } : {};+ const sourcePayload = effectiveSource ? { source: effectiveSource } : {};+ const approvalTransport =+ evolutionMeta && typeof evolutionMeta.approval_transport === 'string'+ ? evolutionMeta.approval_transport+ : undefined;// 如果是需要走 interrupt/interact 的确认,发送 chat.send- if (source === 'permission_interrupt' || source === 'confirm_interrupt') {+ if (+ effectiveSource === 'permission_interrupt' ||+ effectiveSource === 'confirm_interrupt' ||+ (effectiveSource === 'skill_evolution_approval' && approvalTransport === 'interrupt')+ ) {await request('chat.send', {session_id: sessionId,query: '',request_id: requestId,answers: answers,- source,+ ...sourcePayload,+ ...approvalSchemaPayload,...evolutionMetaPayload,});- } else if (source === 'activate_confirm') {+ } else if (effectiveSource === 'activate_confirm') {const action = answers[0]?.selected_options[0] === '拒绝' ? 'reject' : 'accept';const interactionId = requestId || useHarnessStore.getState().activateInteraction?.interactionId || '';if (!interactionId) {@@ -1030,6 +1059,8 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {session_id: sessionId,request_id: requestId,answers,+ ...sourcePayload,+ ...approvalSchemaPayload,...evolutionMetaPayload,});}@@ -1704,12 +1735,13 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {if (useChatStore.getState().switchingMode) return;// 加载历史消息时忽略处理状态更新if (useChatStore.getState().isLoadingHistory) return;+ const isProcessingNow = Boolean(payload.is_processing);// 如果 interrupt_result 指示任务已完成,忽略 processing_status=trueconst { interruptResult } = useChatStore.getState();- if (interruptResult && interruptResult.intent === 'resume' && interruptResult.success && interruptResult.has_active_task === false) {+ const resumeAlreadyCompleted = isCompletedResumeResult(interruptResult);+ if (isProcessingNow && resumeAlreadyCompleted) {return;}- const isProcessingNow = Boolean(payload.is_processing);if (isProcessingNow && useChatStore.getState().isPaused) {return;}@@ -1717,11 +1749,16 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {if (!isProcessingNow) {setThinking(false);clearSubtasks();+ stopStreaming();// 检查是否有等待的任务队列const currentMode = useSessionStore.getState().mode;const { taskQueue } = useChatStore.getState();- if (currentMode === 'agent.fast' && taskQueue.length > 0) {+ if (+ currentMode === 'agent.fast' &&+ !resumeAlreadyCompleted &&+ taskQueue.length > 0+ ) {// 智能执行模式下,自动处理队列中的下一个任务const nextTask = taskQueue[0];if (nextTask && activeSessionIdRef.current && sendMessageRef.current) {@@ -1937,10 +1974,16 @@ export function useWebSocket(options: UseWebSocketOptions): UseWebSocketReturn {: questionPayload._evolution_meta && typeof questionPayload._evolution_meta === 'object'? (questionPayload._evolution_meta as Record<string, unknown>): undefined;+ const questions = Array.isArray(questionPayload.questions) ? questionPayload.questions : [];+ const approvalSchema =+ typeof questionPayload.approval_schema === 'string'+ ? questionPayload.approval_schema+ : undefined;const normalizedPayload: AskUserQuestionPayload = {request_id: typeof questionPayload.request_id === 'string' ? questionPayload.request_id : '',source: typeof questionPayload.source === 'string' ? questionPayload.source : undefined,- questions: Array.isArray(questionPayload.questions) ? questionPayload.questions : [],+ questions,+ ...(approvalSchema ? { approvalSchema } : {}),...(evolutionMeta ? { evolutionMeta } : {}),};setPendingQuestion(normalizedPayload);diff --git a/jiuwenswarm/channels/web/frontend/src/types/websocket.ts b/jiuwenswarm/channels/web/frontend/src/types/websocket.tsindex 05e8ae624f..1ddf48dcac 100644--- a/jiuwenswarm/channels/web/frontend/src/types/websocket.ts+++ b/jiuwenswarm/channels/web/frontend/src/types/websocket.ts@@ -143,6 +143,7 @@ export interface AskUserQuestionPayload {request_id: string;questions: Question[];source?: string; // 来源标识,用于区分自进化确认和工具权限确认+ approvalSchema?: string;evolutionMeta?: Record<string, unknown>;}diff --git a/jiuwenswarm/common/e2a/wire_codec.py b/jiuwenswarm/common/e2a/wire_codec.pyindex 75bf9c7732..0f4ea6c871 100644--- a/jiuwenswarm/common/e2a/wire_codec.py+++ b/jiuwenswarm/common/e2a/wire_codec.py@@ -6,6 +6,8 @@ from __future__ import annotationsimport loggingfrom dataclasses import asdict+from datetime import date, datetime+from enum import Enumfrom typing import Anyfrom jiuwenswarm.common.e2a.constants import (@@ -33,6 +35,29 @@ from jiuwenswarm.common.schema.agent import AgentResponse, AgentResponseChunklogger = logging.getLogger(__name__)+def _json_safe(value: Any) -> Any:+ if value is None or isinstance(value, (str, int, float, bool)):+ return value+ if isinstance(value, (datetime, date)):+ return value.isoformat()+ if isinstance(value, Enum):+ return value.value+ if isinstance(value, dict):+ return {str(k): _json_safe(v) for k, v in value.items()}+ if isinstance(value, (list, tuple, set)):+ return [_json_safe(v) for v in value]+ if hasattr(value, "model_dump"):+ try:+ return _json_safe(value.model_dump(mode="json"))+ except Exception:+ return _json_safe(value.model_dump())+ if hasattr(value, "dict"):+ return _json_safe(value.dict())+ if hasattr(value, "__dict__"):+ return _json_safe(vars(value))+ return str(value)++def _raw_dict_to_agent_response(data: dict[str, Any]) -> AgentResponse:return AgentResponse(request_id=str(data["request_id"]),@@ -226,7 +251,10 @@ def encode_agent_response_for_wire(te,)return _fallback_wire_unary_from_legacy(- asdict(resp), response_id=response_id, sequence=sequence, exc=te+ _json_safe(asdict(resp)),+ response_id=response_id,+ sequence=sequence,+ exc=te,)logger.info("[E2A][wire][out] unary request_id=%s response_id=%s response_kind=%s legacy_stashed=false",@@ -234,7 +262,7 @@ def encode_agent_response_for_wire(response_id,e2a.response_kind,)- return wire+ return _json_safe(wire)except Exception as e:logger.exception("[E2A][wire][out][FAIL] stage=encode unary request_id=%s response_id=%s err=%s legacy_stashed=true",@@ -243,7 +271,10 @@ def encode_agent_response_for_wire(e,)return _fallback_wire_unary_from_legacy(- asdict(resp), response_id=response_id, sequence=sequence, exc=e+ _json_safe(asdict(resp)),+ response_id=response_id,+ sequence=sequence,+ exc=e,)@@ -277,13 +308,13 @@ def encode_agent_chunk_for_wire(te,)return _fallback_wire_chunk_from_legacy(- asdict(chunk),+ _json_safe(asdict(chunk)),response_id=response_id,sequence=sequence,exc=te,is_stream=is_stream,)- return wire+ return _json_safe(wire)except Exception as e:logger.exception("[E2A][wire][out][FAIL] stage=encode chunk request_id=%s response_id=%s seq=%s err=%s legacy_stashed=true",@@ -293,7 +324,7 @@ def encode_agent_chunk_for_wire(e,)return _fallback_wire_chunk_from_legacy(- asdict(chunk),+ _json_safe(asdict(chunk)),response_id=response_id,sequence=sequence,exc=e,diff --git a/jiuwenswarm/gateway/message_handler/message_handler.py b/jiuwenswarm/gateway/message_handler/message_handler.pyindex 368b2b17e0..6274ccf29b 100644--- a/jiuwenswarm/gateway/message_handler/message_handler.py+++ b/jiuwenswarm/gateway/message_handler/message_handler.py@@ -52,6 +52,7 @@ _KNOWN_JIUWENSWARM_SESSION_PREFIXES = ("discord_","whatsapp_",)+_SKILL_EVOLUTION_APPROVAL_SCHEMA = "openjiuwen.skill_evolution_approval.v1"_A2UI_OPEN_TAG_MARKER = "<a2ui-json>"@@ -2097,7 +2098,7 @@ class MessageHandler(ABC):"""from jiuwenswarm.common.schema.message import ReqMethod- m = env.method+ m = getattr(env.method, "value", env.method)if not m:return Falsereturn m not in (@@ -2152,6 +2153,96 @@ class MessageHandler(ABC):request_id.startswith("team_skill_evolve_"))+ @classmethod+ def _is_evolution_approval_payload(cls, payload: Any) -> bool:+ if not isinstance(payload, dict):+ return False+ if cls._is_evolution_approval_request_id(payload.get("request_id")):+ return True+ if payload.get("source") == "skill_evolution_approval":+ return True+ if payload.get("approval_schema") == _SKILL_EVOLUTION_APPROVAL_SCHEMA:+ return True++ evolution_meta = payload.get("evolution_meta")+ if isinstance(evolution_meta, dict) and evolution_meta.get("event_kind") == "approval":+ return True+ return False++ def _is_current_pending_evolution_approval(+ self,+ session_id: str | None,+ request_id: Any,+ ) -> bool:+ return (+ isinstance(session_id, str)+ and isinstance(request_id, str)+ and self._pending_evolution_approval.get(session_id) == request_id+ )++ def _is_interrupt_evolution_approval_chat_send(+ self,+ msg: "Message",+ *,+ method: Any | None = None,+ ) -> bool:+ effective_method = getattr(method, "value", method)+ if effective_method is None:+ if not self._is_chat_send_message(msg):+ return False+ elif effective_method != "chat.send":+ return False+ if not isinstance(msg.params, dict):+ return False+ return self._is_interrupt_evolution_approval_answer_payload(msg.params)++ @classmethod+ def _is_interrupt_evolution_approval_answer_payload(cls, payload: Any) -> bool:+ if not cls._is_evolution_approval_payload(payload):+ return False+ evolution_meta = payload.get("evolution_meta")+ return (+ isinstance(evolution_meta, dict)+ and evolution_meta.get("approval_transport") == "interrupt"+ )++ async def _dispatch_interrupt_evolution_approval_as_chat_send(+ self,+ msg: "Message",+ ) -> None:+ from jiuwenswarm.common.schema.message import ReqMethod++ if self._is_current_pending_evolution_approval(+ msg.session_id,+ (msg.params or {}).get("request_id") if isinstance(msg.params, dict) else None,+ ):+ self._user_messages.put_nowait(+ replace(msg, req_method=ReqMethod.CHAT_SEND, is_stream=True)+ )+ return+ logger.info(+ "[MessageHandler] stale interrupt evolution approval answer ignored: "+ "session_id=%s request_id=%s",+ msg.session_id,+ (msg.params or {}).get("request_id") if isinstance(msg.params, dict) else None,+ )++ @staticmethod+ def _ensure_regular_evolution_approval_metadata(payload: dict[str, Any]) -> dict[str, Any]:+ enriched = dict(payload)+ enriched["source"] = "skill_evolution_approval"+ enriched.setdefault("approval_schema", _SKILL_EVOLUTION_APPROVAL_SCHEMA)+ request_id = enriched.get("request_id")+ evolution_meta = enriched.get("evolution_meta")+ if not isinstance(evolution_meta, dict):+ evolution_meta = {}+ evolution_meta = dict(evolution_meta)+ evolution_meta.setdefault("event_kind", "approval")+ evolution_meta.setdefault("rail_kind", "regular")+ evolution_meta.setdefault("approval_kind", "evolve")+ enriched["evolution_meta"] = evolution_meta+ return enriched+def _queue_supplement_input(self,session_id: str | None,@@ -2170,11 +2261,14 @@ class MessageHandler(ABC):return Nonereturn self._queued_supplement_input.pop(session_id, None)- def _mark_pending_evolution_approval(self, session_id: str | None, request_id: Any) -> None:+ def _mark_pending_evolution_approval(+ self,+ session_id: str | None,+ request_id: Any,+ ) -> None:if not session_id:return- if self._is_evolution_approval_request_id(request_id):- self._pending_evolution_approval[session_id] = str(request_id)+ self._pending_evolution_approval[session_id] = str(request_id)def _build_auto_accept_evolution_answer(self,@@ -2186,16 +2280,19 @@ class MessageHandler(ABC):) -> "Message":from jiuwenswarm.common.schema.message import Message, ReqMethod+ params = self._ensure_regular_evolution_approval_metadata({+ "request_id": request_id,+ "answers": [{"selected_options": ["接收"]}],+ })+ if request_id.startswith("call_"):+ params["evolution_meta"]["approval_transport"] = "interrupt"+return Message(id=f"auto_evolve_answer_{int(time.time() * 1000):x}_{secrets.token_hex(3)}",type="req",channel_id=channel_id,session_id=session_id,- params={- "request_id": request_id,- "answers": [{"selected_options": ["接收"]}],- "source": "auto_accept",- },+ params=params,timestamp=time.time(),ok=True,req_method=ReqMethod.CHAT_ANSWER,@@ -2273,6 +2370,61 @@ class MessageHandler(ABC):self._clear_session_evolution_in_progress(session_id)return self._pop_queued_supplement_input(session_id)+ async def _complete_evolution_approval_if_current(+ self,+ msg: "Message",+ answered_request_id: str | None,+ ) -> None:+ if not self._is_current_pending_evolution_approval(msg.session_id, answered_request_id):+ self._finish_evolution_approval_if_current(+ msg.session_id,+ answered_request_id,+ )+ return++ queued_payload = self._finish_evolution_approval_if_current(+ msg.session_id,+ answered_request_id,+ )+ queued_input = str((queued_payload or {}).get("new_input") or "").strip()+ queued_attachments = (queued_payload or {}).get("attachments")+ if queued_input:+ queued_msg = self._build_queued_chat_send_message(+ msg,+ queued_input,+ queued_attachments if isinstance(queued_attachments, list) else None,+ self._get_session_last_user_query(msg.session_id),+ )+ self._user_messages.put_nowait(queued_msg)+ logger.info(+ "[MessageHandler] evolution approval answered (resolved), "+ "queued supplement dispatched: id=%s session_id=%s",+ queued_msg.id,+ msg.session_id,+ )+ else:+ logger.info(+ "[MessageHandler] evolution approval answered (resolved), "+ "no queued supplement: request_id=%s session_id=%s",+ answered_request_id,+ msg.session_id,+ )+ await self._send_processing_status(+ msg.id,+ msg.session_id,+ msg.channel_id,+ is_processing=False,+ )++ @staticmethod+ def _approval_response_resolved(resp: Any) -> bool:+ return (+ resp is not None+ and hasattr(resp, "payload")+ and isinstance(resp.payload, dict)+ and resp.payload.get("resolved", False) is True+ )+async def _handle_evolution_chunk(self,chunk,@@ -2307,7 +2459,7 @@ class MessageHandler(ABC):approval_request_id = chunk.payload.get("request_id")if (event_type == "chat.ask_user_question"- and self._is_evolution_approval_request_id(approval_request_id)+ and self._is_evolution_approval_payload(chunk.payload)):self._maybe_auto_accept_replaced_evolution_approval(session_id=session_id,@@ -2401,6 +2553,16 @@ class MessageHandler(ABC):resp.request_id,resp.channel_id,)+ if (+ self._is_interrupt_evolution_approval_chat_send(msg, method=env.method)+ and self._approval_response_resolved(resp)+ ):+ answer_payload = msg.params if isinstance(msg.params, dict) else {}+ answer_request_id = answer_payload.get("request_id")+ await self._complete_evolution_approval_if_current(+ msg,+ str(answer_request_id or ""),+ )return respexcept Exception as e:logger.exception("AgentServer send_request failed for %s: %s", msg.id, e)@@ -2453,36 +2615,24 @@ class MessageHandler(ABC):# 检查是否是中断请求if msg.req_method == ReqMethod.CHAT_ANSWER:+ answer_payload = msg.params if isinstance(msg.params, dict) else {}+ is_evolution_approval_answer = self._is_evolution_approval_payload(answer_payload)+ if is_evolution_approval_answer:+ msg.params = self._ensure_regular_evolution_approval_metadata(answer_payload)+ if self._is_interrupt_evolution_approval_answer_payload(msg.params):+ await self._dispatch_interrupt_evolution_approval_as_chat_send(msg)+ continueagent_msg = await self._prepare_agent_dispatch_message(msg)env = self.message_to_e2a(agent_msg)resp = await self._process_non_stream_request(msg, env)- answer_request_id = (msg.params or {}).get("request_id")- if self._is_evolution_approval_request_id(answer_request_id):- # Check whether the response indicates the approval was actually resolved.- resolved = False- if resp is not None and hasattr(resp, "payload") and isinstance(resp.payload, dict):- resolved = resp.payload.get("resolved", False) is True- if resolved:- queued_payload = self._finish_evolution_approval_if_current(- msg.session_id,+ answer_payload = msg.params if isinstance(msg.params, dict) else {}+ answer_request_id = answer_payload.get("request_id")+ if is_evolution_approval_answer:+ if self._approval_response_resolved(resp):+ await self._complete_evolution_approval_if_current(+ msg,str(answer_request_id or ""),)- queued_input = str((queued_payload or {}).get("new_input") or "").strip()- queued_attachments = (queued_payload or {}).get("attachments")- if queued_input:- queued_msg = self._build_queued_chat_send_message(- msg,- queued_input,- queued_attachments if isinstance(queued_attachments, list) else None,- self._get_session_last_user_query(msg.session_id),- )- self._user_messages.put_nowait(queued_msg)- logger.info(- "[MessageHandler] evolution approval answered (resolved), "- "queued supplement dispatched: id=%s session_id=%s",- queued_msg.id,- msg.session_id,- )else:logger.info("[MessageHandler] evolution approval answered but not resolved: "@@ -2754,6 +2904,20 @@ class MessageHandler(ABC):"[MessageHandler] 从 user_messages 取出,发往 AgentServer: id=%s channel_id=%s is_stream=%s",msg.id, msg.channel_id, msg.is_stream,)+ if self._is_interrupt_evolution_approval_chat_send(msg):+ if self._is_current_pending_evolution_approval(+ msg.session_id,+ (msg.params or {}).get("request_id") if isinstance(msg.params, dict) else None,+ ):+ msg = replace(msg, is_stream=True)+ else:+ logger.info(+ "[MessageHandler] stale interrupt evolution approval chat.send ignored: "+ "session_id=%s request_id=%s",+ msg.session_id,+ (msg.params or {}).get("request_id") if isinstance(msg.params, dict) else None,+ )+ continueagent_msg = await self._prepare_agent_dispatch_message(msg)await self._trigger_before_chat_request_hook(agent_msg)env = self.message_to_e2a(agent_msg)@@ -2877,6 +3041,28 @@ class MessageHandler(ABC):)raise # 重新抛出,让调用者知道任务被取消finally:+ if (+ not cancelled+ and self._is_interrupt_evolution_approval_answer_payload(env.params)+ ):+ from jiuwenswarm.common.schema.message import Message, ReqMethod++ await self._complete_evolution_approval_if_current(+ Message(+ id=rid,+ type="req",+ channel_id=channel_id,+ session_id=session_id,+ params=dict(env.params or {}),+ timestamp=time.time(),+ ok=True,+ req_method=ReqMethod.CHAT_SEND,+ is_stream=True,+ metadata=request_metadata,+ ),+ str((env.params or {}).get("request_id") or ""),+ )+ has_processing_status_false = True# 清理状态self._pop_stream_tracking(rid)if session_id is not None and session_id not in self._stream_sessions.values():@@ -3028,6 +3214,12 @@ class MessageHandler(ABC):metadata=None,)await self.publish_robot_messages(status_msg)+ logger.info(+ "[MessageHandler] processing status sent: request_id=%s session_id=%s is_processing=%s",+ request_id,+ session_id,+ is_processing,+ )def _build_error_out_message(self, msg: "Message", error: Exception) -> "Message":from jiuwenswarm.common.schema.message import Messagediff --git a/jiuwenswarm/server/runtime/agent_adapter/evolution_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/evolution_helpers.pyindex bf245639ff..066967982a 100644--- a/jiuwenswarm/server/runtime/agent_adapter/evolution_helpers.py+++ b/jiuwenswarm/server/runtime/agent_adapter/evolution_helpers.py@@ -57,6 +57,11 @@ TEAM_EVOLUTION_VISIBLE_PROGRESS_STAGES = {"completed",*TEAM_EVOLUTION_NOOP_STAGES,}+REGULAR_EVOLUTION_VISIBLE_START_STAGES = {+ "generating",+ "approval_required",+ "completed",+}@dataclass(frozen=True)@@ -103,7 +108,15 @@ _SDK_PROGRESS_TERMINAL_STAGES = {"timed_out",}-EVOLUTION_ACCEPT_LABELS = ("accept", "接收", "接受")+EVOLUTION_ACCEPT_LABELS = (+ "accept",+ "接收",+ "接受",+ "allow_once",+ "allow_always",+ "本次允许",+ "总是允许",+)EVOLUTION_EXECUTE_LABELS = ("execute", "执行")REGULAR_EVOLUTION_SLASH_WARNING_PHRASES = ("未生成可保存经验",@@ -602,6 +615,16 @@ def visible_evolution_progress_from_events(events: list[Any]) -> list[EvolutionP]+def visible_regular_evolution_start_progress(+ progress_statuses: list[EvolutionProgressStatus],+) -> list[EvolutionProgressStatus]:+ return [+ progress+ for progress in progress_statuses+ if progress.stage in REGULAR_EVOLUTION_VISIBLE_START_STAGES+ ]++def progress_for_request(progress_statuses: list[EvolutionProgressStatus],request_id: str,diff --git a/jiuwenswarm/server/runtime/agent_adapter/evolution_slash.py b/jiuwenswarm/server/runtime/agent_adapter/evolution_slash.pynew file mode 100644index 0000000000..57559164ce--- /dev/null+++ b/jiuwenswarm/server/runtime/agent_adapter/evolution_slash.py@@ -0,0 +1,333 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Rail-independent handlers for active Skill evolution slash commands."""++from __future__ import annotations++import logging+from dataclasses import dataclass+from typing import Any++from openjiuwen.agent_evolving.checkpointing.evolution_store import EvolutionStore+from openjiuwen.agent_evolving.experience.query import ExperienceQueryService+from openjiuwen.agent_evolving.experience.rebuild import ExperienceRebuildService+from openjiuwen.harness.rails.evolution.commands import (+ build_evolve_review_command_prompt,+ build_rebuild_command_prompt,+ build_simplify_command_prompt,+)++from jiuwenswarm.server.runtime.agent_adapter.evolution_helpers import (+ validate_evolution_log_writable,+ validate_evolution_skill,+ validate_team_evolution_skill,+)+from jiuwenswarm.server.runtime.skill import filter_visible_skill_names++logger = logging.getLogger(__name__)++_COMMANDS = (+ "evolve_simplify",+ "evolve_rebuild",+ "evolve_list",+)+_DEFAULT_REVIEW_AGENT_NAME = "evolution_reviewer"+++@dataclass(frozen=True)+class EvolutionSlashContext:+ """Context needed to resolve evolution slash commands without a rail."""++ mode: str+ session_id: str+ skills_dir: str | list[str]+ evolution_enabled: bool = True+ language: str = "cn"+ review_agent_name: str = _DEFAULT_REVIEW_AGENT_NAME+++async def handle_evolution_slash_command(+ query: Any,+ context: EvolutionSlashContext,+) -> dict[str, Any] | None:+ """Handle active evolution slash commands without requiring a mounted rail.++ Args:+ query: User query to inspect.+ context: Store and prompt-building context supplied by the caller.++ Returns:+ A slash result dict when handled, or ``None`` when this is not one of+ the active evolution commands owned by this handler.+ """+ if not isinstance(query, str):+ return None++ stripped = query.strip()+ command = _command_name(stripped)+ if command is None:+ return None+ if context.mode not in {"agent.plan", "team"}:+ display_mode = str(context.mode or "当前").strip() or "当前"+ return _error(f"{display_mode} 模式下演进功能不可用。")+ if not context.evolution_enabled:+ return _error("演进功能未启用。")++ try:+ store = EvolutionStore(context.skills_dir)+ except Exception as exc:+ logger.warning("[EvolutionSlash] failed to initialize store: %s", exc)+ return _error(f"演进经验库初始化失败:{exc}")++ if command == "evolve_list":+ return await _handle_evolve_list(stripped, store, context)+ if command == "evolve_simplify":+ return await _handle_evolve_simplify(stripped, store, context)+ if command == "evolve_rebuild":+ return await _handle_evolve_rebuild(stripped, store, context)+ return await _handle_evolve(stripped, store, context)+++def _command_name(stripped: str) -> str | None:+ if stripped == "/evolve" or stripped.startswith("/evolve "):+ return "evolve"+ for command in _COMMANDS:+ prefix = f"/{command}"+ if stripped == prefix or stripped.startswith(f"{prefix} "):+ return command+ return None+++def _subject(store: EvolutionStore, skill_name: str) -> dict[str, str]:+ resolver = getattr(store, "resolve_subject_payload", None)+ if callable(resolver):+ try:+ payload = resolver(skill_name)+ except Exception:+ logger.debug("[EvolutionSlash] could not resolve subject payload for '%s'", skill_name)+ else:+ if isinstance(payload, dict):+ kind = str(payload.get("kind") or "").strip()+ name = str(payload.get("name") or skill_name).strip() or skill_name+ if kind:+ return {"kind": kind, "name": name}+ return {"kind": "skill", "name": skill_name}+++def _followup_response(action: str, followup_prompt: str, skill_name: str) -> dict[str, Any]:+ return {+ "action": action,+ "followup_prompt": followup_prompt,+ "skill_name": skill_name,+ "result_type": "followup",+ }+++def _error(output: str) -> dict[str, Any]:+ return {"output": output, "result_type": "error"}+++def _answer(output: str) -> dict[str, Any]:+ return {"output": output, "result_type": "answer"}+++def _validate_skill(+ store: EvolutionStore,+ skill_name: str,+ *,+ require_skill_md: bool,+ context: EvolutionSlashContext,+ subject: dict[str, str],+) -> str | None:+ subject_kind = str(subject.get("kind") or "skill")+ if context.mode == "team" and subject_kind == "swarm-skill":+ return validate_team_evolution_skill(store, skill_name, require_skill_md=require_skill_md)+ return validate_evolution_skill(store, skill_name, require_skill_md=require_skill_md)+++async def _handle_evolve(+ query: str,+ store: EvolutionStore,+ context: EvolutionSlashContext,+) -> dict[str, Any]:+ parts = query.split(maxsplit=2)+ if len(parts) < 2:+ skill_names = filter_visible_skill_names(store.list_skill_names())+ if not skill_names:+ return _answer("当前 skills_base_dir 下未找到任何 Skill 目录。")+ summary = await store.list_pending_summary(skill_names)+ return _answer(f"**Skills 演进记录:**\n\n{summary}")++ skill_name = parts[1].strip()+ user_intent = parts[2].strip() if len(parts) > 2 else ""+ if not user_intent:+ return _error("请补充演进意图:`/evolve <skill_name> <user_query>`")++ subject = _subject(store, skill_name)+ validation_error = _validate_skill(+ store,+ skill_name,+ require_skill_md=True,+ context=context,+ subject=subject,+ )+ if validation_error is not None:+ return _error(validation_error)+ writable_error = validate_evolution_log_writable(store, skill_name)+ if writable_error is not None:+ return _error(writable_error)++ prompt = build_evolve_review_command_prompt(+ subject=subject,+ user_intent=user_intent,+ review_agent_name=context.review_agent_name,+ language=context.language,+ )+ return _followup_response("run_evolve_followup", prompt, skill_name)+++async def _handle_evolve_list(+ query: str,+ store: EvolutionStore,+ context: EvolutionSlashContext,+) -> dict[str, Any]:+ parts = query.split()+ skill_name = parts[1] if len(parts) > 1 else ""+ if not skill_name or skill_name.startswith("--"):+ return _error("请指定 Skill 名称:`/evolve_list <skill_name>`")++ subject = _subject(store, skill_name)+ validation_error = _validate_skill(+ store,+ skill_name,+ require_skill_md=False,+ context=context,+ subject=subject,+ )+ if validation_error is not None:+ return _error(validation_error)++ records = await store.get_records_by_score(skill_name, subject_kind=subject["kind"])+ if not records:+ return _answer(f"Skill '{skill_name}' 暂无演进经验。")++ avg_score = sum(record.score for record in records) / len(records)+ lines = [+ f'📊 Skill "{skill_name}" — 经验库摘要\n',+ f"共 {len(records)} 条经验 | 平均分:{avg_score:.2f}\n",+ "| # | Score | Used | Effect | Section | Content (preview) |",+ "|---|---:|---|---|---|---|",+ ]+ for index, record in enumerate(records, 1):+ stats = record.usage_stats+ if stats:+ used_str = (+ f"{stats.times_used}/{stats.times_presented}"+ if stats.times_presented+ else "0/0"+ )+ effect_str = f"+{stats.times_positive}/-{stats.times_negative}"+ else:+ used_str = "0/0"+ effect_str = "+0/-0"+ section = str(record.change.section).replace("|", "\\|")+ preview = record.change.content.split("\n")[0][:40].replace("|", "\\|")+ lines.append(+ f"| {index} | {record.score:.2f} | {used_str} | {effect_str} | {section} | {preview} |"+ )++ lines.append(f"\n提示:使用 /evolve_simplify {skill_name} 执行智能整理")+ return _answer("\n".join(lines))+++async def _handle_evolve_simplify(+ query: str,+ store: EvolutionStore,+ context: EvolutionSlashContext,+) -> dict[str, Any]:+ parts = query.split(maxsplit=2)+ skill_name = parts[1] if len(parts) > 1 else ""+ user_intent = parts[2] if len(parts) > 2 else None++ if not skill_name:+ return _error("请指定 Skill 名称:`/evolve_simplify <skill_name> [user_intent]`")++ subject = _subject(store, skill_name)+ validation_error = _validate_skill(+ store,+ skill_name,+ require_skill_md=True,+ context=context,+ subject=subject,+ )+ if validation_error is not None:+ return _error(validation_error)+ writable_error = validate_evolution_log_writable(store, skill_name)+ if writable_error is not None:+ return _error(writable_error)++ query_service = ExperienceQueryService(store=store)+ index = await query_service.list_experiences(+ subject,+ min_score=None,+ limit=100,+ cursor=None,+ target=None,+ section=None,+ query=None,+ sort="score_desc",+ )+ if not index.get("items"):+ return _answer(f"Skill '{skill_name}' 暂无演进经验,无需整理。")++ prompt = build_simplify_command_prompt(+ subject=subject,+ user_intent=user_intent,+ full_index=index,+ index_complete=not bool(index.get("has_more")),+ language=context.language,+ )+ return _followup_response("run_simplify_followup", prompt, skill_name)+++async def _handle_evolve_rebuild(+ query: str,+ store: EvolutionStore,+ context: EvolutionSlashContext,+) -> dict[str, Any]:+ parts = query.split(maxsplit=2)+ skill_name = parts[1] if len(parts) > 1 else ""+ user_intent = parts[2] if len(parts) > 2 else None++ if not skill_name:+ return _error("请指定 Skill 名称:`/evolve_rebuild <skill_name> [user_intent]`")++ subject = _subject(store, skill_name)+ validation_error = _validate_skill(+ store,+ skill_name,+ require_skill_md=False,+ context=context,+ subject=subject,+ )+ if validation_error is not None:+ return _error(validation_error)++ rebuild_service = ExperienceRebuildService(store=store)+ rebuild_context = await rebuild_service.prepare_rebuild_context(+ subject,+ user_intent=user_intent,+ )+ if rebuild_context is None:+ return _error(f"Skill '{skill_name}' 未生成可执行的重建指令。")++ prompt = build_rebuild_command_prompt(+ subject=subject,+ user_intent=user_intent,+ rebuild_context=rebuild_context,+ language=context.language,+ )+ return _followup_response("run_rebuild_followup", prompt, skill_name)+++__all__ = ["EvolutionSlashContext", "handle_evolution_slash_command"]diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface.py b/jiuwenswarm/server/runtime/agent_adapter/interface.pyindex 8f4a6526d6..63b0a53f11 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface.py@@ -821,6 +821,38 @@ class JiuWenSwarm:)return interactive_input+ if source == "skill_evolution_approval":+ answer = answers[0] if answers else {}+ selected_options = answer.get("selected_options", []) if isinstance(answer, dict) else []+ custom_input = answer.get("custom_input", "") if isinstance(answer, dict) else ""+ value = str(selected_options[0] if selected_options else "").strip()+ action_by_value = {+ "accept": "allow_once",+ "接收": "allow_once",+ "接受": "allow_once",+ "allow_once": "allow_once",+ "本次允许": "allow_once",+ "Allow Once": "allow_once",+ "allow_always": "allow_always",+ "总是允许": "allow_always",+ "Always Allow": "allow_always",+ "reject": "reject",+ "拒绝": "reject",+ "Reject": "reject",+ }+ action = action_by_value.get(value)+ if action is None:+ action = "reject"+ payload = {"action": action}+ if custom_input:+ payload["feedback"] = custom_input+ interactive_input.update(request_id, payload)+ logger.info(+ "[JiuWenSwarm] SkillEvolutionApproval InteractiveInput.update: request_id=%s payload=%s",+ request_id, payload+ )+ return interactive_input+if source and source not in {"permission_interrupt","confirm_interrupt",diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.pyindex aad508b015..35baf079ac 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py@@ -1016,6 +1016,7 @@ class JiuwenSwarmCodeAdapter(JiuWenSwarmDeepAdapter):rail_specs = (("_task_planning_rail", "TaskPlanningRail"),("_skill_evolution_rail", "SkillEvolutionRail"),+ ("_evolution_interrupt_rail", "EvolutionInterruptRail"),)for attr, label in rail_specs:diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 81897cff1a..a142766c58 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -56,11 +56,13 @@ from openjiuwen.harness.rails import (TaskPlanningRail,SecurityRail,SkillEvolutionRail,+ EvolutionInterruptRail,SkillCreateRail,SubagentRail,SysOperationRail,HeartbeatRail,- MemoryRail+ MemoryRail,+ configure_skill_evolution_runtime,)from openjiuwen.harness.rails.context_engineer.context_assemble_rail import ContextAssembleRailfrom openjiuwen.harness.rails.context_engineer.context_processor_rail import ContextProcessorRail@@ -73,7 +75,6 @@ from openjiuwen.harness.tools import (WebPaidSearchTool,create_audio_tools,create_vision_tools,- TodoModifyTool,)try:@@ -107,6 +108,7 @@ from jiuwenswarm.agents.harness.team.a2x.a2x_registry_runtime import (from jiuwenswarm.agents.harness.common.tools.cron.cron_runtime import CronRuntimeBridgefrom jiuwenswarm.agents.harness.common.auto_harness import AutoHarnessServicefrom jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (+ SKILL_EVOLUTION_APPROVAL_SCHEMA,build_permission_rail,convert_interactions_to_ask_user_question,)@@ -149,15 +151,18 @@ from jiuwenswarm.server.runtime.agent_adapter.evolution_helpers import (EVOLUTION_ACCEPT_LABELS,EVOLUTION_EXECUTE_LABELS,EvolutionPushContext,+ REGULAR_EVOLUTION_SLASH_WARNING_PHRASES,TEAM_EVOLUTION_EVENT_TIMEOUT_SEC,TEAM_EVOLUTION_HIDDEN_TERMINAL_STAGES,TEAM_EVOLUTION_IDLE_SLEEP_SEC,+ TEAM_EVOLUTION_NOOP_STAGES,approve_evolution_records,answers_select_option,approved_record_ids_from_answers,build_evolution_status_update,evolution_outcome_from_event,evolution_meta_from_params,+ evolution_slash_command_name,evolution_slash_result,evolution_status_response,is_evolution_approval_event,@@ -173,6 +178,11 @@ from jiuwenswarm.server.runtime.agent_adapter.evolution_helpers import (validate_evolution_log_writable,validate_evolution_skill,visible_evolution_progress_from_events,+ visible_regular_evolution_start_progress,+)+from jiuwenswarm.server.runtime.agent_adapter.evolution_slash import (+ EvolutionSlashContext,+ handle_evolution_slash_command,)from jiuwenswarm.server.utils.stream_utils import parse_ask_user_question_payloadfrom jiuwenswarm.agents.harness.common.tools.multimodal_config import (@@ -241,16 +251,10 @@ from jiuwenswarm.agents.harness.common.plugins.rail_manager import get_rail_manafrom jiuwenswarm.gateway.cron import CronTargetChannelfrom jiuwenswarm.common.schema.agent import AgentRequest, AgentResponse, AgentResponseChunkfrom jiuwenswarm.common.utils import (- get_agent_memory_dir,get_agent_skills_dir,get_agent_workspace_dir,get_checkpoint_dir,get_config_dir,- get_deepagent_agent_md_path,- get_deepagent_heartbeat_path,- get_deepagent_identity_md_path,- get_deepagent_soul_md_path,- get_deepagent_user_md_path,get_env_file,get_prompt_attachment_dir,reset_free_search_runtime_flags,@@ -569,6 +573,7 @@ class JiuWenSwarmDeepAdapter:self._external_memory_rail_registered: bool = Falseself._heartbeat_rail: HeartbeatRail | None = Noneself._skill_evolution_rail: SkillEvolutionRail | None = None+ self._evolution_interrupt_rail: EvolutionInterruptRail | None = Noneself._skill_create_rail: SkillCreateRail | None = Noneself._subagent_rail: SubagentRail | None = Noneself._permission_rail: Any = None@@ -2334,6 +2339,73 @@ class JiuWenSwarmDeepAdapter:skill_evolution_rail = Nonereturn skill_evolution_rail+ async def _ensure_active_evolution_rails_registered(self) -> None:+ """Configure, register, and cache single-agent skill evolution rails."""+ if self._instance is None:+ return++ _env_auto_scan = os.getenv("EVOLUTION_AUTO_SCAN")+ if _env_auto_scan is not None:+ evolution_auto_scan = _env_auto_scan.lower() in ("true", "1", "yes")+ else:+ evolution_auto_scan = self._config_cache.get("evolution", {}).get("auto_scan", False)++ disabled_skills = (+ self._skill_manager.list_execution_disabled_skills()+ if self._skill_manager is not None+ else []+ )+ await configure_skill_evolution_runtime(+ self._instance,+ skills_dir=str(get_agent_skills_dir()),+ llm=self._model,+ model=self._default_model_name+ or self._config_cache.get("model_name", "gpt-4"),+ auto_scan=evolution_auto_scan,+ auto_save=False,+ disabled_skills=disabled_skills,+ language=self._resolve_runtime_language(),+ )+ self._refresh_active_evolution_rail_refs()++ def _refresh_active_evolution_rail_refs(self) -> None:+ """Refresh cached rail references after agent-core runtime configure."""+ if self._instance is None:+ return+ find_rails = getattr(self._instance, "find_rails_by_type", None)+ if not callable(find_rails):+ return++ regular_rails = find_rails((SkillEvolutionRail,))+ self._skill_evolution_rail = None+ for rail in regular_rails:+ if isinstance(rail, SkillEvolutionRail) and not isinstance(+ rail, EvolutionInterruptRail+ ):+ self._skill_evolution_rail = rail+ break+ interrupt_rails = find_rails((EvolutionInterruptRail,))+ self._evolution_interrupt_rail = next(iter(interrupt_rails), None)+ subagent_rails = find_rails((SubagentRail,))+ self._subagent_rail = next(iter(subagent_rails), None)++ def _sync_active_evolution_review_agent_after_reload(self) -> None:+ """Restore SkillEvolutionRail-owned review subagent after DeepAgent hot reload."""+ if self._instance is None or self._skill_evolution_rail is None:+ return+ if not self._config_cache.get("evolution", {}).get("enabled", False):+ return++ register_review_agent = getattr(+ self._skill_evolution_rail,+ "_register_evolution_review_agent",+ None,+ )+ if callable(register_review_agent):+ register_review_agent(self._instance)++ self._refresh_active_evolution_rail_refs()+def _build_skill_create_rail(self, config: dict[str, Any]) -> SkillCreateRail | None:"""Build SkillCreateRail for new skill creation proposals.@@ -3216,6 +3288,7 @@ class JiuWenSwarmDeepAdapter:rails=rails_list,)self._instance.configure(deep_cfg)+ self._sync_active_evolution_review_agent_after_reload()await self._sync_mcp_servers_for_runtime(config_base, tag="agent.reload")logger.info("[JiuWenSwarmDeepAdapter] 配置已热更新(configure),未重启进程")@@ -3320,14 +3393,10 @@ class JiuWenSwarmDeepAdapter:"[JiuWenSwarmDeepAdapter] ContextProcessorRail unregistered for plan mode (disabled)")- # SkillEvolutionRail+ # SkillEvolutionRail runtime configure creates/reuses and registers its rail set.evolution_enabled = self._config_cache.get("evolution", {}).get("enabled", False)if evolution_enabled:- if self._skill_evolution_rail is None:- self._skill_evolution_rail = self._build_skill_evolution_rail(self._config_cache)- if self._skill_evolution_rail is not None:- await self._instance.register_rail(self._skill_evolution_rail)- logger.info("[JiuWenSwarmDeepAdapter] SkillEvolutionRail registered for plan mode")+ await self._ensure_active_evolution_rails_registered()else:# evolution disabled: unregister if existsif self._skill_evolution_rail is not None:@@ -3358,19 +3427,13 @@ class JiuWenSwarmDeepAdapter:self._skill_create_rail = Nonelogger.info("[JiuWenSwarmDeepAdapter] SkillCreateRail unregistered (skill_create=false)")- # 注册 subagent rail(plan 模式下启用)- if self._subagent_rail is None:- self._subagent_rail = self._build_subagent_rail()- if self._subagent_rail is not None:- await self._instance.register_rail(self._subagent_rail)- logger.info("[JiuWenSwarmDeepAdapter] SubagentRail registered for plan mode")-async def _update_agent_mode_rails(self, mode: str | None = None) -> None:"""agent 模式:卸载 plan 专属 rails,按需注册 agent 专属 rails。"""# 卸载 plan 专属 railsrail_specs = (("_task_planning_rail", "TaskPlanningRail"),("_skill_evolution_rail", "SkillEvolutionRail"),+ ("_evolution_interrupt_rail", "EvolutionInterruptRail"),("_skill_create_rail", "SkillCreateRail"),("_subagent_rail", "SubagentRail"),)@@ -4191,6 +4254,14 @@ class JiuWenSwarmDeepAdapter:)elif request_id.startswith("skill_evolve_"):resolved = await self._handle_evolution_approval(request_id, answers)+ elif self._is_interrupt_skill_evolution_approval_params(request_id, request.params):+ logger.warning(+ "[JiuWenSwarmDeepAdapter] interrupt evolution approval received via "+ "chat.user_answer; gateway should route it as chat.send: request_id=%s",+ request_id,+ )+ elif self._is_regular_skill_evolution_approval_params(request.params):+ resolved = await self._handle_evolution_approval(request_id, answers)return AgentResponse(request_id=request.request_id,@@ -4200,6 +4271,39 @@ class JiuWenSwarmDeepAdapter:metadata=request.metadata,)+ @staticmethod+ def _is_interrupt_skill_evolution_approval_params(request_id: str, params: Any) -> bool:+ if not isinstance(params, dict):+ return False+ if isinstance(request_id, str) and request_id.startswith("call_"):+ return JiuWenSwarmDeepAdapter._is_regular_skill_evolution_approval_params(params)+ evolution_meta = evolution_meta_from_params(params)+ return (+ evolution_meta.get("approval_transport") == "interrupt"+ and JiuWenSwarmDeepAdapter._is_regular_skill_evolution_approval_params(params)+ )++ @staticmethod+ def _is_regular_skill_evolution_approval_params(params: Any) -> bool:+ if not isinstance(params, dict):+ return False+ if params.get("source") == "skill_evolution_approval":+ return True+ if params.get("approval_schema") == SKILL_EVOLUTION_APPROVAL_SCHEMA:+ return True+ approval_detail = params.get("approval_detail")+ if (+ isinstance(approval_detail, dict)+ and approval_detail.get("schema") == SKILL_EVOLUTION_APPROVAL_SCHEMA+ ):+ return True+ evolution_meta = evolution_meta_from_params(params)+ if evolution_meta.get("event_kind") != "approval":+ return False+ approval_kind = evolution_meta.get("approval_kind")+ rail_kind = evolution_meta.get("rail_kind")+ return approval_kind in (None, "", "evolve") and rail_kind in (None, "", "regular")+async def handle_heartbeat(self, request: AgentRequest) -> AgentResponse | None:"""Handle heartbeat request. Returns None to continue normal flow.@@ -4447,7 +4551,8 @@ class JiuWenSwarmDeepAdapter:async def _handle_evolve_command(self, query: str, session_id: str) -> dict[str, Any]:"""/evolve [<skill_name> [<user_query>...]] handler using the active SDK path.- Uses SkillEvolutionRail.request_user_evolution to return structured+ Newer regular SkillEvolutionRail returns a follow-up prompt for the+ agent-driven active review path. Older SDKs may still return structuredapproval data directly. Passive/background evolution still uses thehost-event drain path.@@ -4532,7 +4637,6 @@ class JiuWenSwarmDeepAdapter:evolve_result = await rail.request_user_evolution(skill_name,evolution_intent,- auto_approve=False,)except Exception as exc:logger.warning("[JiuWenSwarmDeepAdapter] evolve generate failed (skill=%s): %s", skill_name, exc)@@ -4541,6 +4645,10 @@ class JiuWenSwarmDeepAdapter:"result_type": "error",}+ followup_prompt = str(getattr(evolve_result, "followup_prompt", "") or "").strip()+ if followup_prompt:+ return self._followup_response("run_evolve_followup", followup_prompt, skill_name)+status_response = evolution_status_response(evolve_result,generation_failed_output="llm error",@@ -4779,6 +4887,10 @@ class JiuWenSwarmDeepAdapter:logger.warning("[JiuWenSwarmDeepAdapter] evolve_simplify failed: %s", exc)return {"output": f"智能整理分析失败:{exc}", "result_type": "error"}+ followup_prompt = str(getattr(simplify_result, "followup_prompt", "") or "").strip()+ if followup_prompt:+ return self._followup_response("run_simplify_followup", followup_prompt, skill_name)+return self._approval_response_from_simplify_result(skill_name=skill_name,simplify_result=simplify_result,@@ -4816,12 +4928,7 @@ class JiuWenSwarmDeepAdapter:"result_type": "error",}- return {- "action": "run_rebuild_followup",- "followup_prompt": followup_prompt,- "skill_name": skill_name,- "result_type": "followup",- }+ return self._followup_response("run_rebuild_followup", followup_prompt, skill_name)async def _handle_evolve_rollback_command(self, query: str) -> dict[str, Any]:"""/evolve_rollback <skill_name> [version] — Rollback skill to archived version."""@@ -4934,11 +5041,20 @@ class JiuWenSwarmDeepAdapter:return True@staticmethod- def _extract_rebuild_followup_prompt(slash_result: dict[str, Any] | None) -> str | None:- """Return followup prompt when slash_result requests rebuild continuation."""+ def _followup_response(action: str, followup_prompt: str, skill_name: str) -> dict[str, Any]:+ return {+ "action": action,+ "followup_prompt": followup_prompt,+ "skill_name": skill_name,+ "result_type": "followup",+ }++ @staticmethod+ def _extract_followup_prompt(slash_result: dict[str, Any] | None) -> str | None:+ """Return follow-up prompt when a slash command should continue as an agent turn."""if not isinstance(slash_result, dict):return None- if slash_result.get("action") != "run_rebuild_followup":+ if slash_result.get("result_type") != "followup":return Noneprompt = slash_result.get("followup_prompt")if not isinstance(prompt, str):@@ -4946,7 +5062,7 @@ class JiuWenSwarmDeepAdapter:prompt = prompt.strip()return prompt or None- def _ensure_evolution_rail_for_slash(self, mode: str) -> str | None:+ async def _ensure_evolution_rail_for_slash(self, mode: str) -> str | None:"""Check evolution availability for slash commands; lazily init rail if needed.Returns None when the rail is (or becomes) available, or an error message string.@@ -4956,8 +5072,7 @@ class JiuWenSwarmDeepAdapter:return f"{display_mode} 模式下演进功能不可用。"if not self._config_cache.get("evolution", {}).get("enabled", False):return "演进功能未启用。"- if self._skill_evolution_rail is None:- self._skill_evolution_rail = self._build_skill_evolution_rail(self._config_cache)+ await self._ensure_active_evolution_rails_registered()if self._skill_evolution_rail is None:return "演进功能初始化失败。"@@ -4984,32 +5099,25 @@ class JiuWenSwarmDeepAdapter:stripped = query.strip()- if stripped.startswith("/evolve_simplify"):- err = self._ensure_evolution_rail_for_slash(mode)- if err:- return evolution_slash_result(- "evolve_simplify",- {"output": err, "result_type": "error"},- )- return evolution_slash_result(- "evolve_simplify",- await self._handle_evolve_simplify_command(stripped),- )-- if stripped.startswith("/evolve_rebuild"):- err = self._ensure_evolution_rail_for_slash(mode)- if err:- return evolution_slash_result(- "evolve_rebuild",- {"output": err, "result_type": "error"},- )+ slash_result = await handle_evolution_slash_command(+ stripped,+ EvolutionSlashContext(+ mode=mode,+ session_id=session_id,+ skills_dir=str(get_agent_skills_dir()),+ evolution_enabled=bool(self._config_cache.get("evolution", {}).get("enabled", False)),+ language=self._resolve_runtime_language(),+ ),+ )+ if slash_result is not None:return evolution_slash_result(- "evolve_rebuild",- await self._handle_evolve_rebuild_command(stripped),+ evolution_slash_command_name(stripped),+ slash_result,+ warning_phrases=REGULAR_EVOLUTION_SLASH_WARNING_PHRASES,)if stripped.startswith("/evolve_rollback"):- err = self._ensure_evolution_rail_for_slash(mode)+ err = await self._ensure_evolution_rail_for_slash(mode)if err:return evolution_slash_result("evolve_rollback",@@ -5020,30 +5128,6 @@ class JiuWenSwarmDeepAdapter:await self._handle_evolve_rollback_command(stripped),)- if stripped.startswith("/evolve_list"):- err = self._ensure_evolution_rail_for_slash(mode)- if err:- return evolution_slash_result(- "evolve_list",- {"output": err, "result_type": "error"},- )- return evolution_slash_result(- "evolve_list",- await self._handle_evolve_list_command(stripped),- )-- if stripped == "/evolve" or stripped.startswith("/evolve "):- err = self._ensure_evolution_rail_for_slash(mode)- if err:- return evolution_slash_result(- "evolve",- {"output": err, "result_type": "error"},- )- return evolution_slash_result(- "evolve",- await self._handle_evolve_command(stripped, session_id),- )-return Noneasync def _cancel_pending_todos(self, session_id: str) -> list[dict] | None:@@ -5135,10 +5219,11 @@ class JiuWenSwarmDeepAdapter:slash_result = await self._handle_slash_command(query, session_id, mode)if slash_result is not None:- followup_prompt = self._extract_rebuild_followup_prompt(slash_result)+ followup_prompt = self._extract_followup_prompt(slash_result)if followup_prompt is not None:inputs = dict(inputs)inputs["query"] = followup_prompt+ inputs["_invoke_turn_id"] = request.request_idelse:approval_chunks = slash_result.get("approval_chunks")if approval_chunks:@@ -5324,10 +5409,11 @@ class JiuWenSwarmDeepAdapter:# 拦截斜杠命令slash_result = await self._handle_slash_command(query, session_id, mode)if slash_result is not None:- followup_prompt = self._extract_rebuild_followup_prompt(slash_result)+ followup_prompt = self._extract_followup_prompt(slash_result)if followup_prompt is not None:inputs = dict(inputs)inputs["query"] = followup_prompt+ inputs["_invoke_turn_id"] = request.request_idelse:approval_chunks = slash_result.get("approval_chunks", [])if approval_chunks:@@ -6669,7 +6755,6 @@ class JiuWenSwarmDeepAdapter:Returns:完整上下文的 token 总数"""- from openjiuwen.core.foundation.llm import SystemMessagefrom openjiuwen.core.foundation.tool import ToolInfotoken_counter = context.token_counter()@@ -6800,13 +6885,19 @@ class JiuWenSwarmDeepAdapter:last_event_at = time.monotonic()visible_progress_statuses = visible_evolution_progress_from_events(events)- just_started = False- if not active and visible_progress_statuses:- start_stage = visible_progress_statuses[0].stage- start_message = visible_progress_statuses[0].message+ just_started_with_progress = None+ if not active:+ start_progress_statuses = visible_regular_evolution_start_progress(+ visible_progress_statuses+ )+ if start_progress_statuses:+ just_started_with_progress = start_progress_statuses[0]++ if just_started_with_progress is not None:+ start_stage = just_started_with_progress.stage+ start_message = just_started_with_progress.messageawait _push_status("start", start_stage, start_message)active = True- just_started = Trueawait push_evolution_progress(push_context,@@ -6816,11 +6907,13 @@ class JiuWenSwarmDeepAdapter:build_push_message=build_server_push_message,)- progress_statuses_to_push = (- visible_progress_statuses[1:]- if just_started- else visible_progress_statuses- )+ progress_statuses_to_push = visible_progress_statuses+ if just_started_with_progress is not None:+ progress_statuses_to_push = [+ progress_status+ for progress_status in visible_progress_statuses+ if progress_status is not just_started_with_progress+ ]for progress_status in progress_statuses_to_push:if progress_status.terminal:continue@@ -6850,7 +6943,13 @@ class JiuWenSwarmDeepAdapter:end_stage = "hidden"else:end_stage = stage or "completed"- if not active and end_stage == "hidden":+ if (+ not active+ and (+ end_stage == "hidden"+ or end_stage in TEAM_EVOLUTION_NOOP_STAGES+ )+ ):await _cleanup_evolution_rail()returnif not active:@@ -6874,7 +6973,13 @@ class JiuWenSwarmDeepAdapter:end_stage = terminal_stage(terminal) or "no_evolution_generated"if end_stage in TEAM_EVOLUTION_HIDDEN_TERMINAL_STAGES:end_stage = "hidden"- if not active and end_stage == "hidden":+ if (+ not active+ and (+ end_stage == "hidden"+ or end_stage in TEAM_EVOLUTION_NOOP_STAGES+ )+ ):await _cleanup_evolution_rail()returnif not active:diff --git a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.pyindex cde58279db..b4011cd151 100644--- a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py+++ b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py@@ -8,9 +8,10 @@ import asyncioimport loggingimport osimport time+from pathlib import Pathfrom typing import Any, AsyncIterator-from openjiuwen.agent_teams.paths import get_agent_teams_home+from openjiuwen.agent_teams.paths import get_agent_teams_home, team_homefrom openjiuwen.agent_teams.runtime import RunActionKindfrom openjiuwen.agent_teams.schema.team import TeamRolefrom openjiuwen.agent_teams.monitor import TeamStreamLogger@@ -47,7 +48,6 @@ from jiuwenswarm.server.runtime.agent_adapter.evolution_helpers import (evolution_progress_status_from_event,evolution_slash_command_name,evolution_slash_result,- evolution_status_response,extract_evolution_request_id,group_evolution_approvals,is_evolution_outcome_event,@@ -59,11 +59,14 @@ from jiuwenswarm.server.runtime.agent_adapter.evolution_helpers import (team_evolution_end_update,terminal_progress_from_events,terminal_stage,- validate_evolution_log_writable,validate_evolution_skill,validate_team_evolution_skill,visible_evolution_progress_from_events,)+from jiuwenswarm.server.runtime.agent_adapter.evolution_slash import (+ EvolutionSlashContext,+ handle_evolution_slash_command,+)logger = logging.getLogger(__name__)@@ -633,126 +636,66 @@ async def _handle_team_slash_command(channel_id: str | None,session_id: str,query: str,+ *,+ defer_missing_rail: bool = False,+ skills_dir: str | list[str] | None = None,+ language: str = "cn",) -> dict[str, Any] | None:"""Handle team-only slash commands before entering the team stream."""- evolve_list_result = await _handle_team_evolve_list_command(channel_id, session_id, query)- if evolve_list_result is not None:- return evolve_list_result-stripped = str(query or "").strip()if not (- stripped.startswith("/evolve_simplify")+ stripped.startswith("/evolve_list")+ or stripped.startswith("/evolve_rebuild")+ or stripped.startswith("/evolve_simplify")or stripped == "/evolve"or stripped.startswith("/evolve ")):return None- tm = get_team_manager(channel_id)- rail = tm.get_team_skill_rail(session_id)- if rail is None:- return {- "output": "团队技能演进不可用:未找到 TeamSkillEvolutionRail。",- "result_type": "error",- }-- store = rail.store-- if stripped.startswith("/evolve_simplify"):- parts = stripped.split(maxsplit=2)- skill_name = parts[1] if len(parts) > 1 else ""- user_intent = parts[2] if len(parts) > 2 else None-- if not skill_name:- return {- "output": "请指定 Skill 名称:`/evolve_simplify <skill_name> [user_intent]`",- "result_type": "error",- }-- validation_error = validate_team_evolution_skill(store, skill_name, require_skill_md=True)- if validation_error is not None:- return {"output": validation_error, "result_type": "error"}-- writable_error = validate_evolution_log_writable(store, skill_name)- if writable_error is not None:- return {"output": writable_error, "result_type": "error"}-- try:- simplify_result = await rail.request_simplify(skill_name, user_intent)- except Exception as exc:- logger.warning(- "[TeamHelpers] evolve_simplify failed: session_id=%s error=%s",- session_id,- exc,- )- return {- "output": f"团队技能整理分析失败:{exc}",- "result_type": "error",- }-- return _approval_result_from_event_or_items(- skill_name=skill_name,- event=getattr(simplify_result, "approval_event", None),- items=list(getattr(simplify_result, "actions", []) or []),- no_changes_output=f"Skill '{skill_name}' 经验库状态良好,无需整理。",- invalid_output=f"Skill '{skill_name}' 精简方案已生成,但审批事件为空或格式无效。",- )-- parts = stripped.split(maxsplit=2)- if len(parts) < 2:+ if stripped == "/evolve" or (+ stripped.startswith("/evolve ") and len(stripped.split(maxsplit=2)) < 3+ ):return {"output": "请补充演进意图:`/evolve <skill_name> <user_query>`","result_type": "error",}- skill_name = parts[1].strip()- user_query = parts[2].strip() if len(parts) > 2 else ""-- if not user_query:+ resolved_skills_dir = skills_dir or _resolve_team_slash_skills_dir(session_id)+ if resolved_skills_dir is None:+ if defer_missing_rail:+ return Nonereturn {- "output": "请补充演进意图:`/evolve <skill_name> <user_query>`",+ "output": "团队技能演进不可用:未找到团队 Skill 目录。","result_type": "error",}- validation_error = validate_team_evolution_skill(store, skill_name, require_skill_md=True)- if validation_error is not None:- return {"output": validation_error, "result_type": "error"}+ return await handle_evolution_slash_command(+ stripped,+ EvolutionSlashContext(+ mode="team",+ session_id=session_id,+ skills_dir=resolved_skills_dir,+ evolution_enabled=True,+ language=language,+ ),+ )- writable_error = validate_evolution_log_writable(store, skill_name)- if writable_error is not None:- return {"output": writable_error, "result_type": "error"}- try:- evolve_result = await rail.request_user_evolution(skill_name, user_query)- except Exception as exc:- logger.warning(- "[TeamHelpers] evolve failed: session_id=%s error=%s",- session_id,- exc,- )- return {- "output": f"团队技能演进请求失败:{exc}",- "result_type": "error",- }+def _resolve_team_slash_skills_dir(session_id: str) -> str | None:+ metadata = get_session_metadata(session_id)+ team_name = str(metadata.get("team_name") or "").strip()+ if not team_name:+ return None+ return str(team_home(team_name) / "team-workspace" / "skills")- if isinstance(evolve_result, str) and evolve_result.strip():- return {- "output": f"Skill '{skill_name}' 演进请求已提交,请等待审批。",- "result_type": "answer",- }- status_response = evolution_status_response(- evolve_result,- generation_failed_output="llm error",- no_records_output="已请求团队 Skill 演进,但本次未生成可保存经验。",- )- if status_response is not None:- return status_response- return _approval_result_from_event_or_items(- skill_name=skill_name,- event=getattr(evolve_result, "approval_event", None),- items=list(getattr(evolve_result, "records", []) or []),- no_changes_output=f"Skill '{skill_name}' 未生成新的团队技能演进经验。",- invalid_output=f"Skill '{skill_name}' 已生成团队技能演进经验,但审批事件为空或格式无效。",- )++def _team_spec_skills_dir(team_spec: Any) -> str:+ workspace = getattr(team_spec, "workspace", None)+ root_path = str(getattr(workspace, "root_path", "") or "").strip()+ if root_path:+ return str(Path(root_path) / "skills")+ team_name = str(getattr(team_spec, "team_name", "") or "").strip()+ return str(team_home(team_name) / "team-workspace" / "skills")async def process_team_message_stream(@@ -792,6 +735,7 @@ async def process_team_message_stream(debug = Falseif is_first_request:query, hide_dm, debug = _extract_query_directives(str(query or ""))+ query_text = query if isinstance(query, str) else ""if hide_dm or debug:logger.info("[TeamHelpers] query directives captured for first team request: "@@ -802,62 +746,6 @@ async def process_team_message_stream(debug,)- slash_result = await _handle_team_slash_command(- channel_id,- session_id,- query_text,- )- if slash_result is not None:- approval_chunks = slash_result.get("approval_chunks")- if isinstance(approval_chunks, list) and approval_chunks:- for chunk in approval_chunks:- yield AgentResponseChunk(- request_id=rid,- channel_id=channel_id,- payload=chunk,- is_complete=False,- )- yield _team_processing_done_chunk(rid, channel_id, session_id)- yield AgentResponseChunk(- request_id=rid,- channel_id=channel_id,- payload={"event_type": "chat.done"},- is_complete=True,- )- return-- slash_result = evolution_slash_result(- evolution_slash_command_name(query_text),- slash_result,- warning_phrases=TEAM_EVOLUTION_SLASH_WARNING_PHRASES,- )- result_type = str(slash_result.get("result_type", "answer")).strip().lower()- content = str(slash_result.get("output", ""))- slash_meta = {- "source": slash_result.get("source"),- "slash_command": slash_result.get("slash_command"),- "display_level": slash_result.get("display_level"),- }- payload = (- {"event_type": "chat.error", "error": content, **slash_meta}- if result_type == "error"- else {"event_type": "chat.final", "content": content, **slash_meta}- )- yield AgentResponseChunk(- request_id=rid,- channel_id=channel_id,- payload=payload,- is_complete=False,- )- yield _team_processing_done_chunk(rid, channel_id, session_id)- yield AgentResponseChunk(- request_id=rid,- channel_id=channel_id,- payload=None,- is_complete=True,- )- return-try:request_metadata = dict(request.metadata or {})if isinstance(getattr(request, "params", None), dict):@@ -901,28 +789,71 @@ async def process_team_message_stream(returnteam_name = team_spec.team_name+ team_skills_dir = _team_spec_skills_dir(team_spec)+ ensure_ready = getattr(team_manager, "ensure_team_shared_skills_ready_for_session", None)+ if callable(ensure_ready):+ ensure_ready(session_id, team_spec)- followup_prompt, rebuild_error = await _resolve_team_rebuild_followup(+ slash_result = await _handle_team_slash_command(channel_id,session_id,query_text,+ skills_dir=team_skills_dir,)- if rebuild_error is not None:- yield AgentResponseChunk(- request_id=rid,- channel_id=channel_id,- payload={"event_type": "chat.error", "error": rebuild_error},- is_complete=False,- )- yield AgentResponseChunk(- request_id=rid,- channel_id=channel_id,- payload=None,- is_complete=True,- )- return- if followup_prompt is not None:- query = followup_prompt+ if slash_result is not None:+ approval_chunks = slash_result.get("approval_chunks")+ if isinstance(approval_chunks, list) and approval_chunks:+ for chunk in approval_chunks:+ yield AgentResponseChunk(+ request_id=rid,+ channel_id=channel_id,+ payload=chunk,+ is_complete=False,+ )+ yield _team_processing_done_chunk(rid, channel_id, session_id)+ yield AgentResponseChunk(+ request_id=rid,+ channel_id=channel_id,+ payload={"event_type": "chat.done"},+ is_complete=True,+ )+ return++ prompt = str(slash_result.get("followup_prompt", "") or "").strip()+ if prompt:+ query = prompt+ else:+ slash_result = evolution_slash_result(+ evolution_slash_command_name(query_text),+ slash_result,+ warning_phrases=TEAM_EVOLUTION_SLASH_WARNING_PHRASES,+ )+ result_type = str(slash_result.get("result_type", "answer")).strip().lower()+ content = str(slash_result.get("output", ""))+ slash_meta = {+ "source": slash_result.get("source"),+ "slash_command": slash_result.get("slash_command"),+ "display_level": slash_result.get("display_level"),+ }+ payload = (+ {"event_type": "chat.error", "error": content, **slash_meta}+ if result_type == "error"+ else {"event_type": "chat.final", "content": content, **slash_meta}+ )+ yield AgentResponseChunk(+ request_id=rid,+ channel_id=channel_id,+ payload=payload,+ is_complete=False,+ )+ yield _team_processing_done_chunk(rid, channel_id, session_id)+ yield AgentResponseChunk(+ request_id=rid,+ channel_id=channel_id,+ payload=None,+ is_complete=True,+ )+ returntry:if is_first_request:@@ -932,7 +863,6 @@ async def process_team_message_stream(# matches the latest config toggle.from jiuwenswarm.agents.harness.team.team_manager import sync_team_observabilitysync_team_observability()- team_manager.ensure_team_shared_skills_ready_for_session(session_id, team_spec)await team_manager.prepare_runtime_activation(session_id, team_name)request_queue = asyncio.Queue()waiter_key = (_resolve_channel_id(channel_id), session_id)diff --git a/tests/agents/swarm/test_swarm_assembly.py b/tests/agents/swarm/test_swarm_assembly.pyindex f510089b7d..d8212497a2 100644--- a/tests/agents/swarm/test_swarm_assembly.py+++ b/tests/agents/swarm/test_swarm_assembly.py@@ -33,8 +33,9 @@ from openjiuwen.agent_teams.schema.deep_agent_spec import (BuiltinToolSpec,DeepAgentSpec,RailSpec,+ register_rail_provider,)-from openjiuwen.core.single_agent.rail.base import AgentCallbackContext, ToolCallInputs+from openjiuwen.core.single_agent.rail.base import AgentCallbackContext, AgentRail, ToolCallInputsfrom openjiuwen.harness.prompts.builder import SystemPromptBuilderfrom jiuwenswarm.agents.swarm import (@@ -59,9 +60,6 @@ from jiuwenswarm.agents.swarm.providers import (runtime_tools,tools,)-from jiuwenswarm.agents.harness.team.team_runtime_inheritance import (- resolve_model_config,-)from jiuwenswarm.common.config import get_configlogger = logging.getLogger(__name__)@@ -190,7 +188,7 @@ def test_runtime_prompt_rail_resolves_via_registry() -> None:rail = RailSpec(type=registry.RUNTIME_PROMPT).build(language="cn", context=fake_ctx)assert rail is not None- assert type(rail).__name__ == "RuntimePromptRail"+ assert rail.__class__.__name__ == "RuntimePromptRail"@pytest.mark.asyncio@@ -298,8 +296,19 @@ def test_unknown_swarm_rail_type_raises() -> None:@pytest.mark.parametrize(("role", "extra_rails"),[- ("leader", {registry.TEAM_SKILL_EVOLUTION, registry.TEAM_SKILL_CREATE}),- ("teammate", {registry.MEMBER_SKILL_EVOLUTION}),+ (+ "leader",+ {+ registry.TEAM_SKILL_EVOLUTION,+ registry.TEAM_SKILL_CREATE,+ },+ ),+ (+ "teammate",+ {+ registry.MEMBER_SKILL_EVOLUTION,+ },+ ),],)def test_build_member_capability_specs_rail_names(@@ -778,6 +787,164 @@ def test_vision_audio_config_params_empty_when_unconfigured() -> None:# ---------------------------------------------------------------------------+def test_team_skill_evolution_provider_passes_review_runtime(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ class _FakeTeamSkillEvolutionRail:+ def __init__(self, *args, **kwargs):+ self.args = args+ self.kwargs = kwargs+ self.swarm_context = {}+ self.approval_submission_service = object()++ def bind_swarm_context(self, **kwargs) -> None:+ self.swarm_context.update(kwargs)++ class _FakeEvolutionInterruptRail:+ def __init__(self, **kwargs):+ self.kwargs = kwargs++ monkeypatch.setattr(+ evolution_rails,+ "SwarmTeamSkillEvolutionRail",+ _FakeTeamSkillEvolutionRail,+ )+ monkeypatch.setattr(evolution_rails, "EvolutionInterruptRail", _FakeEvolutionInterruptRail)+ monkeypatch.setattr(+ evolution_rails,+ "_build_evolution_llm_from",+ lambda config: (object(), "model"),+ )+ monkeypatch.setattr(evolution_rails, "load_execution_disabled_skills", lambda: [])++ ctx = SwarmBuildContext(+ language="cn",+ role="leader",+ session_id="sess",+ channel="web",+ team_id="t",+ team_ws_root=str(tmp_path),+ team_skills_dir=str(tmp_path / "skills"),+ trajectory_registry=object(),+ config={},+ )++ built = evolution_rails.build_team_skill_evolution_rail(+ {"evolution_model_config": {}, "auto_scan": False},+ ctx,+ )++ assert len(built) == 2+ interrupt_rail, rail = built+ assert isinstance(rail, _FakeTeamSkillEvolutionRail)+ assert isinstance(interrupt_rail, _FakeEvolutionInterruptRail)+ assert "review_runtime" in rail.kwargs+ assert rail.kwargs["review_runtime"] is not None+ assert interrupt_rail.kwargs == {+ "review_runtime": rail.kwargs["review_runtime"],+ "submission_service": rail.approval_submission_service,+ "auto_save": False,+ "language": "cn",+ }+++def test_member_skill_evolution_provider_passes_review_runtime(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ class _FakeMemberSkillEvolutionRail:+ def __init__(self, *args, **kwargs):+ self.args = args+ self.kwargs = kwargs+ self.swarm_context = {}+ self.bound_sink = None+ self.approval_submission_service = object()++ def set_trajectory_sink(self, sink, *, team_id, member_role) -> None:+ self.bound_sink = (sink, team_id, member_role)++ def bind_swarm_context(self, **kwargs) -> None:+ self.swarm_context.update(kwargs)++ class _FakeEvolutionInterruptRail:+ def __init__(self, **kwargs):+ self.kwargs = kwargs++ monkeypatch.setattr(+ evolution_rails,+ "SwarmMemberSkillEvolutionRail",+ _FakeMemberSkillEvolutionRail,+ )+ monkeypatch.setattr(evolution_rails, "EvolutionInterruptRail", _FakeEvolutionInterruptRail)+ monkeypatch.setattr(+ evolution_rails,+ "_build_evolution_llm_from",+ lambda config: (object(), "model"),+ )+ monkeypatch.setattr(evolution_rails, "load_execution_disabled_skills", lambda: [])++ registry_obj = object()+ ctx = SwarmBuildContext(+ language="en",+ role="teammate",+ session_id="sess",+ channel="web",+ team_id="t",+ team_skills_dir=str(tmp_path / "skills"),+ trajectory_registry=registry_obj,+ config={},+ )++ built = evolution_rails.build_member_skill_evolution_rail(+ {"evolution_model_config": {}, "auto_scan": False},+ ctx,+ )++ assert len(built) == 2+ interrupt_rail, rail = built+ assert isinstance(rail, _FakeMemberSkillEvolutionRail)+ assert isinstance(interrupt_rail, _FakeEvolutionInterruptRail)+ assert "review_runtime" in rail.kwargs+ assert rail.kwargs["review_runtime"] is not None+ assert rail.kwargs["language"] == "en"+ assert interrupt_rail.kwargs == {+ "review_runtime": rail.kwargs["review_runtime"],+ "submission_service": rail.approval_submission_service,+ "auto_save": True,+ "language": "en",+ }+ assert rail.bound_sink == (registry_obj, "t", "teammate")+++def test_rail_spec_build_flattens_single_and_list_provider_returns() -> None:+ """Declarative rail providers may return either one rail or a rail stack."""+ single_rail = AgentRail()+ first_stack_rail = AgentRail()+ second_stack_rail = AgentRail()++ register_rail_provider("swarm.test_single_rail", lambda params, ctx: single_rail)+ register_rail_provider(+ "swarm.test_rail_stack",+ lambda params, ctx: [first_stack_rail, second_stack_rail],+ )++ spec = DeepAgentSpec(+ rails=[+ RailSpec(type="swarm.test_single_rail"),+ RailSpec(type="swarm.test_rail_stack"),+ ],+ )++ parts = spec.resolve_parts(context=SwarmBuildContext(language="cn"))++ assert parts.rails[:3] == [+ single_rail,+ first_stack_rail,+ second_stack_rail,+ ]++def test_team_skill_create_rail_registers_full_workspace(monkeypatch: pytest.MonkeyPatch,) -> None:@@ -960,10 +1127,14 @@ def test_code_member_builds_declaratively_without_post_processing("""register_swarm_providers()config = get_config()- model_client_config, _, _ = resolve_model_config(config)base = DeepAgentSpec(model=TeamModelConfig(- model_client_config=ModelClientConfig(**model_client_config)+ model_client_config=ModelClientConfig(+ client_provider="OpenAI",+ api_key="test-key",+ api_base="https://example.test/v1",+ verify_ssl=False,+ )),workspace=WorkspaceSpec(root_path=str(tmp_path), language="en"),)@@ -998,7 +1169,7 @@ def test_code_member_builds_declaratively_without_post_processing(rails = list(getattr(agent, "_pending_rails", [])) + list(getattr(agent, "_registered_rails", []))- rail_types = {type(rail).__name__ for rail in rails}+ rail_types = {rail.__class__.__name__ for rail in rails}# Zero post-processing: the legacy code customizer is never invoked.assert post_processing_calls == []diff --git a/tests/unit_tests/agentserver/test_agentserver_modes.py b/tests/unit_tests/agentserver/test_agentserver_modes.pyindex ec052bf257..f4cc324f96 100644--- a/tests/unit_tests/agentserver/test_agentserver_modes.py+++ b/tests/unit_tests/agentserver/test_agentserver_modes.py@@ -1,10 +1,12 @@import asyncioimport json+from unittest.mock import Mockimport pytestfrom jiuwenswarm.server import agent_ws_server as agent_ws_server_modulefrom jiuwenswarm.common.schema.agent import AgentRequest, AgentResponse, AgentResponseChunk+from jiuwenswarm.server.runtime.agent_adapter import interface_deep as interface_deep_moduleclass FakeWebSocket:@@ -281,6 +283,246 @@ def test_build_inputs_does_not_map_team_plan_approval_answers_to_interactive_inpassert not isinstance(inputs["query"], InteractiveInput)+def test_build_inputs_maps_skill_evolution_interrupt_answers_to_actions(monkeypatch):+ from openjiuwen.core.session.interaction.interactive_input import InteractiveInput+ from jiuwenswarm.server.runtime.agent_adapter import interface as interface_module++ monkeypatch.setattr(interface_module, "get_config", lambda: {"preferred_language": "zh"})+ monkeypatch.setattr(interface_module, "get_memory_mode", lambda _config: "disabled")++ expected_actions = {+ "accept": "allow_once",+ "接收": "allow_once",+ "接受": "allow_once",+ "allow_once": "allow_once",+ "本次允许": "allow_once",+ "allow_always": "allow_always",+ "总是允许": "allow_always",+ "reject": "reject",+ "拒绝": "reject",+ }+ for selected_option, expected_action in expected_actions.items():+ request = AgentRequest(+ request_id="req-answer",+ channel_id="web",+ session_id="web_session",+ params={+ "query": "",+ "request_id": "call_123",+ "answers": [{"selected_options": [selected_option], "custom_input": ""}],+ "source": "skill_evolution_approval",+ },+ )++ inputs, _, _ = interface_module.JiuWenSwarm().build_inputs(request)+ interactive_input = inputs["query"]++ assert isinstance(interactive_input, InteractiveInput)+ assert interactive_input is not None+ assert interactive_input.user_inputs["call_123"] == {"action": expected_action}+ assert "approved" not in interactive_input.user_inputs["call_123"]+++def test_deep_adapter_registers_evolution_interrupt_rail_before_skill_evolution(monkeypatch):+ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenSwarmDeepAdapter++ class FakeSkillEvolutionRail:+ pass++ class FakeEvolutionInterruptRail:+ pass++ class FakeSubagentRail:+ pass++ class FakeAbilityManager:+ @staticmethod+ def list():+ return []++ class FakeInstance:+ def __init__(self):+ self.registered = []+ self.ability_manager = FakeAbilityManager()++ async def register_rail(self, rail):+ self.registered.append(rail)++ async def unregister_rail(self, _rail):+ pass++ def find_rails_by_type(self, rail_types):+ return [rail for rail in self.registered if isinstance(rail, rail_types)]++ class FakeSkillManager:+ @staticmethod+ def list_execution_disabled_skills():+ return []++ adapter = JiuWenSwarmDeepAdapter()+ adapter._instance = FakeInstance() # pylint: disable=protected-access+ adapter._config_cache = { # pylint: disable=protected-access+ "evolution": {"enabled": True},+ "context_engineering": {"enabled": False},+ }+ adapter._skill_manager = FakeSkillManager() # pylint: disable=protected-access++ async def _noop(*_args, **_kwargs):+ return None++ monkeypatch.setattr(adapter, "_build_task_planning_rail", lambda: None)+ monkeypatch.setattr(adapter, "_handle_memory_rail_by_config", _noop)+ monkeypatch.setattr(adapter, "_handle_external_memory_rail_by_config", _noop)+ monkeypatch.setattr(interface_deep_module, "SkillEvolutionRail", FakeSkillEvolutionRail)+ monkeypatch.setattr(interface_deep_module, "EvolutionInterruptRail", FakeEvolutionInterruptRail)+ monkeypatch.setattr(interface_deep_module, "SubagentRail", FakeSubagentRail)++ async def _fake_configure(agent, **_kwargs):+ await agent.register_rail(FakeEvolutionInterruptRail())+ await agent.register_rail(FakeSkillEvolutionRail())++ monkeypatch.setattr(+ interface_deep_module,+ "configure_skill_evolution_runtime",+ _fake_configure,+ )++ asyncio.run(adapter._update_rails_for_mode("agent.plan")) # pylint: disable=protected-access++ registered = adapter._instance.registered # pylint: disable=protected-access+ interrupt_index = next(+ index for index, rail in enumerate(registered) if isinstance(rail, FakeEvolutionInterruptRail)+ )+ skill_evolution_index = next(+ index for index, rail in enumerate(registered) if isinstance(rail, FakeSkillEvolutionRail)+ )+ assert interrupt_index < skill_evolution_index+++def test_deep_adapter_unregisters_evolution_runtime_rails_when_leaving_plan(monkeypatch):+ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenSwarmDeepAdapter++ class FakeInstance:+ def __init__(self):+ self.unregistered = []++ async def unregister_rail(self, rail):+ self.unregistered.append(rail)++ async def _noop(*_args, **_kwargs):+ return None++ adapter = JiuWenSwarmDeepAdapter()+ adapter._instance = FakeInstance() # pylint: disable=protected-access+ adapter._task_planning_rail = "task-planning-rail" # pylint: disable=protected-access+ adapter._subagent_rail = "subagent-rail" # pylint: disable=protected-access+ adapter._evolution_interrupt_rail = "evolution-interrupt-rail" # pylint: disable=protected-access+ adapter._skill_evolution_rail = "skill-evolution-rail" # pylint: disable=protected-access+ adapter._context_assemble_rail = "agent-context-assemble-rail" # pylint: disable=protected-access+ adapter._context_assemble_mode = "agent.fast" # pylint: disable=protected-access++ monkeypatch.setattr(adapter, "_handle_memory_rail_by_config", _noop)+ monkeypatch.setattr(adapter, "_handle_external_memory_rail_by_config", _noop)+ monkeypatch.setattr(interface_deep_module, "_build_context_processor_rail", lambda _config: None)++ asyncio.run(adapter._update_rails_for_mode("agent.fast")) # pylint: disable=protected-access++ assert adapter._instance.unregistered[:4] == [ # pylint: disable=protected-access+ "task-planning-rail",+ "skill-evolution-rail",+ "evolution-interrupt-rail",+ "subagent-rail",+ ]+ assert adapter._skill_evolution_rail is None # pylint: disable=protected-access+ assert adapter._evolution_interrupt_rail is None # pylint: disable=protected-access+ assert adapter._subagent_rail is None # pylint: disable=protected-access+++def test_deep_adapter_reconfigures_plan_evolution_rails_idempotently(monkeypatch, tmp_path):+ from jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenSwarmDeepAdapter++ class FakeAbilityManager:+ @staticmethod+ def list():+ return []++ class FakeInstance:+ def __init__(self):+ self._pending_rails = []+ self._registered_rails = []+ self.ability_manager = FakeAbilityManager()++ def add_rail(self, rail):+ self._pending_rails.append(rail)+ return self++ async def register_rail(self, rail):+ self._registered_rails.append(rail)+ self._pending_rails = [queued for queued in self._pending_rails if queued is not rail]+ return self++ def find_rails_by_type(self, rail_types):+ return [+ rail+ for rail in (*self._pending_rails, *self._registered_rails)+ if isinstance(rail, rail_types)+ ]++ def strip_rails_by_type(self, rail_types):+ removed = 0+ kept_pending = []+ for rail in self._pending_rails:+ if isinstance(rail, rail_types):+ removed += 1+ else:+ kept_pending.append(rail)+ kept_registered = []+ for rail in self._registered_rails:+ if isinstance(rail, rail_types):+ removed += 1+ else:+ kept_registered.append(rail)+ self._pending_rails = kept_pending+ self._registered_rails = kept_registered+ return removed++ class FakeSkillManager:+ @staticmethod+ def list_execution_disabled_skills():+ return []++ adapter = JiuWenSwarmDeepAdapter()+ adapter._instance = FakeInstance() # pylint: disable=protected-access+ adapter._config_cache = { # pylint: disable=protected-access+ "evolution": {"enabled": True, "auto_scan": False},+ "model_name": "configured-model",+ }+ adapter._skill_manager = FakeSkillManager() # pylint: disable=protected-access+ adapter._model = Mock() # pylint: disable=protected-access++ monkeypatch.setattr(interface_deep_module, "get_agent_skills_dir", lambda: tmp_path)++ asyncio.run(adapter._ensure_active_evolution_rails_registered()) # pylint: disable=protected-access+ asyncio.run(adapter._ensure_active_evolution_rails_registered()) # pylint: disable=protected-access++ registered = adapter._instance._registered_rails # pylint: disable=protected-access+ assert (+ sum(+ isinstance(rail, interface_deep_module.EvolutionInterruptRail)+ for rail in registered+ )+ == 1+ )+ assert (+ sum(+ isinstance(rail, interface_deep_module.SkillEvolutionRail)+ and not isinstance(rail, interface_deep_module.EvolutionInterruptRail)+ for rail in registered+ )+ == 1+ )++def test_deep_adapter_handle_user_answer_ignores_team_plan_approval_compat(monkeypatch):from jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenSwarmDeepAdapterdiff --git a/tests/unit_tests/agentserver/test_evolution_helpers.py b/tests/unit_tests/agentserver/test_evolution_helpers.pyindex 4c32026964..e7a385739a 100644--- a/tests/unit_tests/agentserver/test_evolution_helpers.py+++ b/tests/unit_tests/agentserver/test_evolution_helpers.py@@ -213,6 +213,41 @@ def test_evolution_helpers_map_cancelled_progress_to_hidden():assert update.stage == "hidden"+def test_evolution_helpers_regular_start_progress_excludes_scan_and_noop_stages():+ events = [+ SimpleNamespace(+ type="llm_reasoning",+ payload={+ "_evolution_meta": {"event_kind": "progress", "stage": "detecting_signals"},+ "content": "checking regular skill(s) for evolution signals",+ },+ ),+ SimpleNamespace(+ type="llm_reasoning",+ payload={+ "_evolution_meta": {"event_kind": "progress", "stage": "completed"},+ "content": "no evolution records generated",+ },+ ),+ SimpleNamespace(+ type="llm_reasoning",+ payload={+ "_evolution_meta": {"event_kind": "progress", "stage": "generating_updates"},+ "content": "generating evolution records",+ },+ ),+ ]++ visible = evolution_helpers.visible_evolution_progress_from_events(events)+ regular_start = evolution_helpers.visible_regular_evolution_start_progress(visible)++ assert [progress.stage for progress in visible] == [+ "no_evolution_no_records",+ "generating",+ ]+ assert [progress.stage for progress in regular_start] == ["generating"]++def test_evolution_helpers_group_approvals_skips_missing_request_ids():missing_request_id = SimpleNamespace(type="chat.ask_user_question",@@ -265,6 +300,28 @@ def test_evolution_helpers_preserve_legacy_whole_request_without_record_ids():assert approved_ids is None[email protected]("label", ["allow_once", "allow_always", "本次允许", "总是允许"])+def test_evolution_helpers_accept_interrupt_approval_labels(label: str):+ accepted, approved_ids = evolution_helpers.approved_record_ids_from_answers(+ [{"selected_options": [label]}],+ evolution_helpers.EVOLUTION_ACCEPT_LABELS,+ )++ assert accepted is True+ assert approved_ids is None++[email protected]("label", ["reject", "拒绝"])+def test_evolution_helpers_do_not_accept_reject_labels(label: str):+ accepted, approved_ids = evolution_helpers.approved_record_ids_from_answers(+ [{"selected_options": [label]}],+ evolution_helpers.EVOLUTION_ACCEPT_LABELS,+ )++ assert accepted is False+ assert approved_ids == []++def test_evolution_helpers_do_not_whole_approve_when_snapshot_id_is_missing():accepted, approved_ids = evolution_helpers.approved_record_ids_from_answers([{"selected_options": ["接收"]}],diff --git a/tests/unit_tests/agentserver/test_evolution_push_delivery.py b/tests/unit_tests/agentserver/test_evolution_push_delivery.pyindex 46453ac070..0f15916736 100644--- a/tests/unit_tests/agentserver/test_evolution_push_delivery.py+++ b/tests/unit_tests/agentserver/test_evolution_push_delivery.py@@ -301,6 +301,43 @@ async def test_normal_evolution_watcher_ends_on_cancelled_progress(monkeypatch):assert rail.cleanup_calls == 1+async def test_normal_evolution_watcher_does_not_start_for_no_signal_scan(monkeypatch):+ _FakeTransport.pushes = []+ rail = _FakeEvolutionRail(+ [+ [_progress_event("starting regular skill evolution review", stage="started")],+ [+ _progress_event(+ "checking regular skill(s) for evolution signals",+ stage="detecting_signals",+ )+ ],+ [+ _progress_event(+ "no skill usage of a regular skill or actionable evolution signal detected",+ stage="cancelled",+ )+ ],+ ]+ )+ adapter = _TestAdapter.build_with_rail(rail)++ monkeypatch.setattr(+ "jiuwenswarm.server.gateway_push.WebSocketGatewayPushTransport",+ _FakeTransport,+ )++ await adapter.watch_evolution_and_push("stream-rid", "web", "sess-no-signal-scan")++ status_pushes = [+ push for push in _FakeTransport.pushes+ if push["payload"]["event_type"] == "chat.evolution_status"+ ]+ assert status_pushes == []+ assert rail.cleanup_calls == 1++@pytest.mark.asyncioasync def test_normal_evolution_watcher_ends_on_auto_approved_progress(monkeypatch):_FakeTransport.pushes = []@@ -350,7 +387,7 @@ async def test_normal_evolution_watcher_reads_outcome_status_from_metadata(monke@pytest.mark.asyncio-async def test_normal_evolution_watcher_ends_on_sdk_noop_outcome_without_prior_progress(monkeypatch):+async def test_normal_evolution_watcher_hides_sdk_noop_outcome_without_prior_generation(monkeypatch):_FakeTransport.pushes = []rail = _FakeEvolutionRail([[_sdk_noop_outcome_event()]])adapter = _TestAdapter.build_with_rail(rail)@@ -362,13 +399,39 @@ async def test_normal_evolution_watcher_ends_on_sdk_noop_outcome_without_prior_pawait adapter.watch_evolution_and_push("stream-rid", "web", "sess-sdk-noop-only")+ status_pushes = [+ push for push in _FakeTransport.pushes+ if push["payload"]["event_type"] == "chat.evolution_status"+ ]+ assert status_pushes == []+ assert rail.cleanup_calls == 1+++async def test_normal_evolution_watcher_ends_sdk_noop_outcome_after_generation(monkeypatch):+ _FakeTransport.pushes = []+ rail = _FakeEvolutionRail(+ [+ [_progress_event("generating", stage="generating_updates")],+ [_sdk_noop_outcome_event()],+ ]+ )+ adapter = _TestAdapter.build_with_rail(rail)++ monkeypatch.setattr(+ "jiuwenswarm.server.gateway_push.WebSocketGatewayPushTransport",+ _FakeTransport,+ )++ await adapter.watch_evolution_and_push("stream-rid", "web", "sess-sdk-noop-after-generation")+status_pushes = [push for push in _FakeTransport.pushesif push["payload"]["event_type"] == "chat.evolution_status"]assert [push["payload"]["status"] for push in status_pushes] == ["start", "end"]assert [push["payload"]["stage"] for push in status_pushes] == [- "no_evolution_no_records",+ "generating","no_evolution_no_records",]assert rail.cleanup_calls == 1diff --git a/tests/unit_tests/agentserver/test_evolution_slash.py b/tests/unit_tests/agentserver/test_evolution_slash.pynew file mode 100644index 0000000000..ac18fc3ef1--- /dev/null+++ b/tests/unit_tests/agentserver/test_evolution_slash.py@@ -0,0 +1,62 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Unit tests for rail-independent evolution slash handling."""++from __future__ import annotations++import pytest++from jiuwenswarm.server.runtime.agent_adapter.evolution_slash import (+ EvolutionSlashContext,+ handle_evolution_slash_command,+)+++def _write_skill(tmp_path, name: str, *, kind: str | None = None) -> str:+ skills_dir = tmp_path / "skills"+ skill_dir = skills_dir / name+ skill_dir.mkdir(parents=True)+ if kind is None:+ content = f"# {name}\n"+ else:+ content = f"---\nname: {name}\nkind: {kind}\n---\n# {name}\n"+ skill_dir.joinpath("SKILL.md").write_text(content, encoding="utf-8")+ return str(skills_dir)+++async def test_agent_plan_evolve_uses_actual_swarm_skill_kind(tmp_path):+ skills_dir = _write_skill(tmp_path, "research-team", kind="swarm-skill")++ result = await handle_evolution_slash_command(+ "/evolve research-team improve review flow",+ EvolutionSlashContext(+ mode="agent.plan",+ session_id="sess-agent-plan",+ skills_dir=skills_dir,+ evolution_enabled=True,+ ),+ )++ assert result is not None+ assert result["result_type"] == "followup"+ assert 'subject={"kind": "swarm-skill", "name": "research-team"}' in result["followup_prompt"]+++async def test_agent_plan_evolve_defaults_untyped_skill_to_skill_kind(tmp_path):+ skills_dir = _write_skill(tmp_path, "regular-skill")++ result = await handle_evolution_slash_command(+ "/evolve regular-skill improve retry flow",+ EvolutionSlashContext(+ mode="agent.plan",+ session_id="sess-agent-plan",+ skills_dir=skills_dir,+ evolution_enabled=True,+ ),+ )++ assert result is not None+ assert result["result_type"] == "followup"+ assert 'subject={"kind": "skill", "name": "regular-skill"}' in result["followup_prompt"]diff --git a/tests/unit_tests/agentserver/test_evolve_command_edges.py b/tests/unit_tests/agentserver/test_evolve_command_edges.pyindex 39b5e1b0e5..c2d3e9bdc8 100644--- a/tests/unit_tests/agentserver/test_evolve_command_edges.py+++ b/tests/unit_tests/agentserver/test_evolve_command_edges.py@@ -2,6 +2,9 @@ from types import SimpleNamespaceimport pytest+from jiuwenswarm.common.schema.agent import AgentRequest+from jiuwenswarm.common.schema.message import ReqMethod+from jiuwenswarm.server.runtime.agent_adapter import interface_deep as interface_deep_modulefrom jiuwenswarm.server.runtime.agent_adapter.interface_deep import JiuWenSwarmDeepAdapter@@ -49,6 +52,194 @@ async def test_evolve_slash_reports_current_mode_when_unsupported(assert result["output"] == expected_output+async def test_evolve_slash_checks_enabled_without_lazy_registering(monkeypatch):+ adapter = JiuWenSwarmDeepAdapter()+ adapter._config_cache = {"evolution": {"enabled": False}} # pylint: disable=protected-access++ async def _unexpected_register():+ raise AssertionError("slash enabled check must not register active evolution rails")++ def _unexpected_store(*_args, **_kwargs):+ raise AssertionError("disabled evolution slash must not initialize evolution store")++ monkeypatch.setattr(adapter, "_ensure_active_evolution_rails_registered", _unexpected_register)+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.agent_adapter.evolution_slash.EvolutionStore",+ _unexpected_store,+ )++ result = await adapter._handle_slash_command( # pylint: disable=protected-access+ "/evolve demo-skill improve",+ session_id="sess-evolve-disabled",+ mode="agent.plan",+ )++ assert result is not None+ assert result["slash_command"] == "evolve"+ assert result["result_type"] == "error"+ assert result["output"] == "演进功能未启用。"+++async def test_evolve_slash_allows_team_without_lazy_registering(monkeypatch):+ adapter = JiuWenSwarmDeepAdapter()+ adapter._config_cache = {"evolution": {"enabled": True}} # pylint: disable=protected-access++ async def _unexpected_register():+ raise AssertionError("team slash availability check must not register single-agent evolution rails")++ async def _fake_handler(_query, context):+ assert context.mode == "team"+ assert context.evolution_enabled is True+ return {"output": "team slash handled", "result_type": "answer"}++ monkeypatch.setattr(adapter, "_ensure_active_evolution_rails_registered", _unexpected_register)+ monkeypatch.setattr(interface_deep_module, "handle_evolution_slash_command", _fake_handler)++ result = await adapter._handle_slash_command( # pylint: disable=protected-access+ "/evolve_list demo-skill",+ session_id="sess-team-evolve",+ mode="team",+ )++ assert result is not None+ assert result["slash_command"] == "evolve_list"+ assert result["result_type"] == "answer"+ assert result["output"] == "team slash handled"+++async def test_evolve_slash_lazy_init_registers_active_review_rails(monkeypatch):+ class _FakeSkillEvolutionRail:+ pass++ class _FakeEvolutionInterruptRail:+ pass++ class _FakeSubagentRail:+ pass++ class _FakeInstance:+ def __init__(self):+ self.registered: list[object] = []++ async def register_rail(self, rail):+ self.registered.append(rail)++ def find_rails_by_type(self, rail_types):+ return [rail for rail in self.registered if isinstance(rail, rail_types)]++ class _FakeSkillManager:+ @staticmethod+ def list_execution_disabled_skills():+ return ["disabled-demo"]++ adapter = JiuWenSwarmDeepAdapter()+ adapter._instance = _FakeInstance() # pylint: disable=protected-access+ adapter._config_cache = { # pylint: disable=protected-access+ "evolution": {"enabled": True, "auto_scan": False},+ "model_name": "configured-model",+ }+ adapter._skill_manager = _FakeSkillManager() # pylint: disable=protected-access+ adapter._default_model_name = "default-model" # pylint: disable=protected-access+ adapter._model = object() # pylint: disable=protected-access++ monkeypatch.setattr(interface_deep_module, "SkillEvolutionRail", _FakeSkillEvolutionRail)+ monkeypatch.setattr(interface_deep_module, "EvolutionInterruptRail", _FakeEvolutionInterruptRail)+ monkeypatch.setattr(interface_deep_module, "SubagentRail", _FakeSubagentRail)+ monkeypatch.setattr(adapter, "_resolve_runtime_language", lambda: "en")+ monkeypatch.setenv("EVOLUTION_AUTO_SCAN", "true")++ configure_calls = []++ async def _fake_configure(agent, **kwargs):+ configure_calls.append(kwargs)+ await agent.register_rail(_FakeEvolutionInterruptRail())+ await agent.register_rail(_FakeSkillEvolutionRail())++ monkeypatch.setattr(+ interface_deep_module,+ "configure_skill_evolution_runtime",+ _fake_configure,+ )++ result = await adapter._ensure_evolution_rail_for_slash("agent.plan") # pylint: disable=protected-access++ assert result is None+ registered = adapter._instance.registered # pylint: disable=protected-access+ assert len(registered) == 2+ assert isinstance(registered[0], _FakeEvolutionInterruptRail)+ assert isinstance(registered[1], _FakeSkillEvolutionRail)+ assert configure_calls == [+ {+ "skills_dir": str(interface_deep_module.get_agent_skills_dir()),+ "llm": adapter._model, # pylint: disable=protected-access+ "model": "default-model",+ "auto_scan": True,+ "auto_save": False,+ "disabled_skills": ["disabled-demo"],+ "language": "en",+ }+ ]+++def test_sync_active_evolution_review_agent_after_reload_restores_retained_rail(monkeypatch):+ class _FakeSkillEvolutionRail:+ def __init__(self):+ self.registered_agent = None++ def _register_evolution_review_agent(self, agent):+ self.registered_agent = agent++ class _FakeEvolutionInterruptRail:+ pass++ class _FakeSubagentRail:+ pass++ class _FakeInstance:+ def __init__(self, rails):+ self.rails = rails++ def find_rails_by_type(self, rail_types):+ return [rail for rail in self.rails if isinstance(rail, rail_types)]++ rail = _FakeSkillEvolutionRail()+ interrupt_rail = _FakeEvolutionInterruptRail()+ subagent_rail = _FakeSubagentRail()+ instance = _FakeInstance([subagent_rail, interrupt_rail, rail])+ adapter = JiuWenSwarmDeepAdapter()+ adapter._instance = instance # pylint: disable=protected-access+ adapter._skill_evolution_rail = rail # pylint: disable=protected-access+ adapter._config_cache = {"evolution": {"enabled": True}} # pylint: disable=protected-access++ monkeypatch.setattr(interface_deep_module, "SkillEvolutionRail", _FakeSkillEvolutionRail)+ monkeypatch.setattr(interface_deep_module, "EvolutionInterruptRail", _FakeEvolutionInterruptRail)+ monkeypatch.setattr(interface_deep_module, "SubagentRail", _FakeSubagentRail)++ adapter._sync_active_evolution_review_agent_after_reload() # pylint: disable=protected-access++ assert rail.registered_agent is instance+ assert adapter._skill_evolution_rail is rail # pylint: disable=protected-access+ assert adapter._evolution_interrupt_rail is interrupt_rail # pylint: disable=protected-access+ assert adapter._subagent_rail is subagent_rail # pylint: disable=protected-access+++def test_sync_active_evolution_review_agent_after_reload_skips_when_disabled():+ class _FakeSkillEvolutionRail:+ @staticmethod+ def _register_evolution_review_agent(_agent):+ raise AssertionError("disabled evolution must not restore review agent")++ adapter = JiuWenSwarmDeepAdapter()+ adapter._instance = object() # pylint: disable=protected-access+ adapter._skill_evolution_rail = _FakeSkillEvolutionRail() # pylint: disable=protected-access+ adapter._config_cache = {"evolution": {"enabled": False}} # pylint: disable=protected-access++ adapter._sync_active_evolution_review_agent_after_reload() # pylint: disable=protected-access++@pytest.mark.anyioasync def test_agent_evolve_simplify_already_minimal_returns_answer():class _FakeStore:@@ -87,6 +278,74 @@ async def test_agent_evolve_simplify_already_minimal_returns_answer():assert result["output"].strip()+async def test_handle_user_answer_routes_regular_evolution_approval_without_request_prefix(monkeypatch):+ adapter = JiuWenSwarmDeepAdapter()+ seen: list[tuple[str, list[dict[str, list[str]]]]] = []++ async def _fake_handle_evolution_approval(request_id: str, answers: list):+ seen.append((request_id, answers))+ return True++ monkeypatch.setattr(adapter, "_handle_evolution_approval", _fake_handle_evolution_approval)++ response = await adapter.handle_user_answer(+ AgentRequest(+ request_id="answer-1",+ channel_id="web",+ session_id="sess-agent-evolve",+ req_method=ReqMethod.CHAT_ANSWER,+ params={+ "request_id": "regular_123",+ "answers": [{"selected_options": ["接收"]}],+ "source": "skill_evolution_approval",+ "approval_schema": "openjiuwen.skill_evolution_approval.v1",+ "evolution_meta": {+ "event_kind": "approval",+ "rail_kind": "regular",+ "approval_kind": "evolve",+ },+ },+ )+ )++ assert seen == [("regular_123", [{"selected_options": ["接收"]}])]+ assert response.payload == {"accepted": True, "resolved": True}+++async def test_handle_user_answer_does_not_route_call_interrupt_approval_to_regular_rail(monkeypatch):+ adapter = JiuWenSwarmDeepAdapter()++ async def _unexpected_handle_evolution_approval(*_args, **_kwargs):+ raise AssertionError("call_* interrupt approval must not use regular evolution rail")++ monkeypatch.setattr(adapter, "_handle_evolution_approval", _unexpected_handle_evolution_approval)++ response = await adapter.handle_user_answer(+ AgentRequest(+ request_id="answer-1",+ channel_id="web",+ session_id="sess-agent-evolve",+ req_method=ReqMethod.CHAT_ANSWER,+ params={+ "request_id": "call_123",+ "answers": [{"selected_options": ["allow_once"]}],+ "source": "skill_evolution_approval",+ "approval_schema": "openjiuwen.skill_evolution_approval.v1",+ "evolution_meta": {+ "event_kind": "approval",+ "rail_kind": "regular",+ "approval_kind": "evolve",+ "approval_transport": "interrupt",+ },+ },+ )+ )++ assert response.payload == {"accepted": True, "resolved": False}++@pytest.mark.anyioasync def test_agent_evolve_missing_skill_md_fails_before_sdk_call(monkeypatch):class _FakeStore:@@ -231,6 +490,57 @@ async def test_agent_evolve_without_local_signal_still_maps_sdk_generation_failuassert recorded_intents == ["用户显式请求演进 Skill 'code-runner'。"]+async def test_agent_evolve_returns_followup_when_sdk_uses_active_review(monkeypatch):+ class _FakeStore:+ @staticmethod+ def list_skill_names() -> list[str]:+ return ["code-runner"]++ @staticmethod+ def skill_exists(skill_name: str) -> bool:+ return skill_name == "code-runner"++ @staticmethod+ def skill_definition_exists(skill_name: str) -> bool:+ return skill_name == "code-runner"++ recorded_calls: list[tuple[str, str]] = []++ class _FakeRail:+ store = _FakeStore()+ processed_signal_keys: set[tuple[str, str]] = set()++ @staticmethod+ async def request_user_evolution(skill_name: str, evolution_intent: str):+ recorded_calls.append((skill_name, evolution_intent))+ return SimpleNamespace(+ followup_prompt="review and evolve code-runner",+ status=None,+ message="",+ has_changes=True,+ approval_event=None,+ records=[],+ )++ adapter = JiuWenSwarmDeepAdapter()+ adapter._skill_evolution_rail = _FakeRail() # pylint: disable=protected-access+ monkeypatch.setattr(adapter, "_collect_messages_for_evolve", lambda _session_id: [])++ result = await adapter._handle_evolve_command( # pylint: disable=protected-access+ "/evolve code-runner improve review flow",+ "sess-agent-evolve",+ )++ assert recorded_calls == [("code-runner", "improve review flow")]+ assert result == {+ "action": "run_evolve_followup",+ "followup_prompt": "review and evolve code-runner",+ "skill_name": "code-runner",+ "result_type": "followup",+ }++@pytest.mark.anyioasync def test_agent_evolve_hides_internal_toolchain_generation_error(monkeypatch):class _FakeStore:@@ -311,3 +621,175 @@ async def test_agent_evolve_list_allows_skill_without_skill_md():"output": "Skill 'demo-skill' 暂无演进经验。","result_type": "answer",}+++async def test_agent_evolve_simplify_returns_followup_when_sdk_uses_active_review():+ class _FakeStore:+ @staticmethod+ def skill_exists(skill_name: str) -> bool:+ return skill_name == "demo-skill"++ @staticmethod+ def skill_definition_exists(skill_name: str) -> bool:+ return skill_name == "demo-skill"++ recorded_calls: list[tuple[str, str | None]] = []++ class _FakeRail:+ store = _FakeStore()++ @staticmethod+ async def request_simplify(skill_name: str, user_intent: str | None):+ recorded_calls.append((skill_name, user_intent))+ return SimpleNamespace(+ followup_prompt="review and simplify demo-skill",+ request_id=None,+ approval_event=None,+ actions=[],+ )++ adapter = JiuWenSwarmDeepAdapter()+ adapter._skill_evolution_rail = _FakeRail() # pylint: disable=protected-access++ result = await adapter._handle_evolve_simplify_command( # pylint: disable=protected-access+ "/evolve_simplify demo-skill merge duplicate records",+ )++ assert recorded_calls == [("demo-skill", "merge duplicate records")]+ assert result == {+ "action": "run_simplify_followup",+ "followup_prompt": "review and simplify demo-skill",+ "skill_name": "demo-skill",+ "result_type": "followup",+ }+++ "action",+ [+ "run_rebuild_followup",+ "run_evolve_followup",+ "run_simplify_followup",+ ],+)+def test_agent_slash_followup_prompt_extraction_accepts_all_evolution_followups(action: str):+ result = {+ "action": action,+ "followup_prompt": "review and continue code-runner",+ "result_type": "followup",+ }++ assert (+ JiuWenSwarmDeepAdapter._extract_followup_prompt(result) # pylint: disable=protected-access+ == "review and continue code-runner"+ )+++def _adapter_ready_for_followup_execution(monkeypatch: pytest.MonkeyPatch) -> JiuWenSwarmDeepAdapter:+ adapter = JiuWenSwarmDeepAdapter()+ adapter._instance = SimpleNamespace( # pylint: disable=protected-access+ get_context_usage=lambda **_kwargs: {},+ )+ monkeypatch.setattr(adapter, "_has_valid_model_config", lambda _model_name="": True)+ monkeypatch.setattr(adapter, "_bind_runtime_cron_context", lambda **_kwargs: None)+ monkeypatch.setattr(adapter, "_reset_runtime_cron_context", lambda _tokens: None)+ monkeypatch.setattr(adapter, "_resolve_model_for_request", lambda _request: None)+ monkeypatch.setattr(adapter, "_apply_model_to_react_agent", lambda _model: None)+ monkeypatch.setattr(adapter, "_mark_session_active", lambda _session_id: None)+ monkeypatch.setattr(adapter, "_register_session_agent_task", lambda _session_id: None)+ monkeypatch.setattr(adapter, "_unregister_session_agent_task", lambda _session_id: None)+ monkeypatch.setattr(adapter, "_unmark_session_active", lambda _session_id, **_kwargs: None)++ async def _noop_update_runtime_config(_runtime_config):+ return None++ monkeypatch.setattr(adapter, "_update_runtime_config", _noop_update_runtime_config)+ return adapter+++async def test_agent_non_stream_slash_followup_continues_into_runner(monkeypatch):+ adapter = _adapter_ready_for_followup_execution(monkeypatch)+ seen_inputs: list[dict] = []++ async def _fake_slash_command(_query, _session_id, _mode):+ return {+ "action": "run_evolve_followup",+ "followup_prompt": "review and evolve code-runner",+ "result_type": "followup",+ }++ class _FakeRunner:+ @staticmethod+ async def run_agent(agent, inputs):+ assert agent is adapter._instance # pylint: disable=protected-access+ seen_inputs.append(dict(inputs))+ return "agent completed"++ monkeypatch.setattr(adapter, "_handle_slash_command", _fake_slash_command)+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.agent_adapter.interface_deep.Runner",+ _FakeRunner,+ )++ response = await adapter.process_message_impl(+ AgentRequest(+ request_id="req-followup",+ channel_id="web",+ session_id="sess-followup",+ params={"query": "/evolve code-runner", "mode": "agent.plan"},+ ),+ {"query": "/evolve code-runner"},+ )++ assert seen_inputs == [+ {"query": "review and evolve code-runner", "_invoke_turn_id": "req-followup"}+ ]+ assert response.ok is True+ assert response.payload == {"content": "agent completed"}+++async def test_agent_stream_slash_followup_continues_into_runner(monkeypatch):+ adapter = _adapter_ready_for_followup_execution(monkeypatch)+ seen_inputs: list[dict] = []++ async def _fake_slash_command(_query, _session_id, _mode):+ return {+ "action": "run_simplify_followup",+ "followup_prompt": "review and simplify code-runner",+ "result_type": "followup",+ }++ class _FakeRunner:+ @staticmethod+ async def run_agent_streaming(agent, inputs):+ assert agent is adapter._instance # pylint: disable=protected-access+ seen_inputs.append(dict(inputs))+ yield SimpleNamespace(type="llm_output", payload={"content": "agent delta"})++ monkeypatch.setattr(adapter, "_handle_slash_command", _fake_slash_command)+ monkeypatch.setattr(+ "jiuwenswarm.server.runtime.agent_adapter.interface_deep.Runner",+ _FakeRunner,+ )++ chunks = []+ async for chunk in adapter.process_message_stream_impl(+ AgentRequest(+ request_id="req-followup-stream",+ channel_id="web",+ session_id="sess-followup-stream",+ params={"query": "/evolve_simplify code-runner", "mode": "agent.plan"},+ is_stream=True,+ ),+ {"query": "/evolve_simplify code-runner"},+ ):+ chunks.append(chunk)++ assert seen_inputs == [+ {"query": "review and simplify code-runner", "_invoke_turn_id": "req-followup-stream"}+ ]+ assert chunks[0].payload == {"event_type": "chat.delta", "content": "agent delta"}+ assert chunks[-1].is_complete is Truediff --git a/tests/unit_tests/agentserver/test_interrupt_helpers.py b/tests/unit_tests/agentserver/test_interrupt_helpers.pynew file mode 100644index 0000000000..32db7f445c--- /dev/null+++ b/tests/unit_tests/agentserver/test_interrupt_helpers.py@@ -0,0 +1,85 @@+from types import SimpleNamespace++from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (+ convert_interactions_to_ask_user_question,+)+++def _evolution_interrupt(+ tool_name: str,+ operation: str,+):+ if operation == "evolve":+ message = "是否批准 Skill 'demo-skill' 的 1 条演进经验?"+ else:+ message = "是否执行 Skill 'demo-skill' 的 1 项经验精简操作?"++ value = {+ "message": message,+ "tool_name": tool_name,+ "ui_options": [+ {"label": "本次允许", "value": "allow_once", "description": "允许本次技能演进变更执行"},+ {"label": "总是允许", "value": "allow_always", "description": "自动允许后续匹配的技能演进变更"},+ {"label": "拒绝", "value": "reject", "description": "跳过本次技能演进变更"},+ ],+ }+ return SimpleNamespace(+ id="call_123",+ value=value,+ )+++def test_structured_simplify_approval_interrupt_is_classified():+ interaction = _evolution_interrupt("simplify_skill_experiences", "simplify")++ result = convert_interactions_to_ask_user_question([interaction])++ assert result is not None+ assert result["source"] == "skill_evolution_approval"+ assert result["approval_schema"] == "openjiuwen.skill_evolution_approval.v1"+ assert result["evolution_meta"]["approval_kind"] == "simplify"+ assert result["evolution_meta"]["approval_transport"] == "interrupt"+ assert "approval_detail" not in result["questions"][0]+ assert result["questions"][0]["question"] == "是否执行 Skill 'demo-skill' 的 1 项经验精简操作?"+ assert [option["value"] for option in result["questions"][0]["options"]] == [+ "allow_once",+ "allow_always",+ "reject",+ ]+++def test_structured_evolve_approval_interrupt_is_classified():+ interaction = _evolution_interrupt("evolve_skill_experiences", "evolve")++ result = convert_interactions_to_ask_user_question([interaction])++ assert result is not None+ assert result["source"] == "skill_evolution_approval"+ assert result["approval_schema"] == "openjiuwen.skill_evolution_approval.v1"+ assert result["evolution_meta"]["approval_kind"] == "evolve"+ assert result["evolution_meta"]["approval_transport"] == "interrupt"+ assert "approval_detail" not in result["questions"][0]+ assert result["questions"][0]["question"] == "是否批准 Skill 'demo-skill' 的 1 条演进经验?"+ assert [option["value"] for option in result["questions"][0]["options"]] == [+ "allow_once",+ "allow_always",+ "reject",+ ]+++def test_skill_evolution_tool_name_without_detail_is_classified():+ interaction = SimpleNamespace(+ id="call_123",+ value={+ "message": "Skill evolution approval required.",+ "tool_name": "simplify_skill_experiences",+ },+ )++ result = convert_interactions_to_ask_user_question([interaction])++ assert result is not None+ assert result["source"] == "skill_evolution_approval"+ assert result["approval_schema"] == "openjiuwen.skill_evolution_approval.v1"+ assert result["evolution_meta"]["approval_kind"] == "simplify"+ assert result["questions"][0]["question"] == "Skill evolution approval required."diff --git a/tests/unit_tests/agentserver/test_team_helpers.py b/tests/unit_tests/agentserver/test_team_helpers.pyindex ea2d3eea6f..7eb2533fbf 100644--- a/tests/unit_tests/agentserver/test_team_helpers.py+++ b/tests/unit_tests/agentserver/test_team_helpers.py@@ -5,6 +5,7 @@from __future__ import annotationsimport asyncio+import jsonfrom types import SimpleNamespaceimport pytest@@ -95,9 +96,10 @@ class _TeamHelpersTestApi:channel_id: str | None,session_id: str,query: str,+ **kwargs,) -> dict[str, object] | None:handler = getattr(team_helpers, "_handle_team_slash_command")- return await handler(channel_id, session_id, query)+ return await handler(channel_id, session_id, query, **kwargs)@staticmethodasync def consume_stream_with_query(@@ -119,6 +121,77 @@ class _TeamHelpersTestApi:await consumer(channel_id, session_id, monitor_handler)+def _write_team_skill(tmp_path, name: str, *, records: list[dict] | None = None) -> str:+ skills_dir = tmp_path / "team-workspace" / "skills"+ skill_dir = skills_dir / name+ skill_dir.mkdir(parents=True)+ skill_dir.joinpath("SKILL.md").write_text(+ "---\n"+ f"name: {name}\n"+ "kind: swarm-skill\n"+ "---\n"+ f"# {name}\n",+ encoding="utf-8",+ )+ skill_dir.joinpath("evolutions.json").write_text(+ json.dumps(+ {+ "skill_id": name,+ "version": "1.0.0",+ "updated_at": "2026-06-11T00:00:00Z",+ "entries": records or [],+ },+ ensure_ascii=False,+ ),+ encoding="utf-8",+ )+ return str(skills_dir)+++def _write_regular_skill(tmp_path, name: str, *, records: list[dict] | None = None) -> str:+ skills_dir = tmp_path / "team-workspace" / "skills"+ skill_dir = skills_dir / name+ skill_dir.mkdir(parents=True)+ skill_dir.joinpath("SKILL.md").write_text(f"# {name}\n", encoding="utf-8")+ skill_dir.joinpath("evolutions.json").write_text(+ json.dumps(+ {+ "skill_id": name,+ "version": "1.0.0",+ "updated_at": "2026-06-11T00:00:00Z",+ "entries": records or [],+ },+ ensure_ascii=False,+ ),+ encoding="utf-8",+ )+ return str(skills_dir)+++def _evolution_record(content: str, *, score: float = 1.0) -> dict:+ return {+ "id": "ev_test",+ "source": "user_correction",+ "timestamp": "2026-06-11T00:00:00Z",+ "context": "test",+ "change": {+ "section": "Instructions",+ "action": "append",+ "content": content,+ "target": "body",+ },+ "applied": False,+ "score": score,+ "usage_stats": {+ "times_presented": 0,+ "times_used": 0,+ "times_positive": 0,+ "times_negative": 0,+ },+ "summary": content,+ }++@pytest.mark.anyioasync def test_team_evolution_monitor_pushes_status_with_real_request_id(monkeypatch):_FakeTransport.pushes = []@@ -967,38 +1040,27 @@ async def test_handle_team_evolve_list_command_returns_team_store_summary(monkey@pytest.mark.anyio-async def test_process_team_message_stream_handles_team_evolve_list(monkeypatch):- record = SimpleNamespace(- score=1.0,- usage_stats=None,- change=SimpleNamespace(section="workflow", content="First summary line"),+async def test_process_team_message_stream_handles_team_evolve_list(monkeypatch, tmp_path):+ _write_team_skill(+ tmp_path,+ "demo-skill",+ records=[_evolution_record("First summary line")],)-- class _FakeStore:- @staticmethod- def skill_exists(skill_name: str) -> bool:- return skill_name == "demo-skill"-- @staticmethod- def list_skill_names() -> list[str]:- return ["demo-skill"]-- @staticmethod- async def get_records_by_score(skill_name: str):- return [record]+ captured_spec: list[object] = []class _FakeManager:- @staticmethod- async def get_or_create_team(**kwargs):- return object()-@staticmethoddef has_stream_task(session_id: str) -> bool:return False@staticmethod- def get_team_skill_rail(session_id: str):- return SimpleNamespace(store=_FakeStore())+ async def get_swarm_enriched_team_spec(**kwargs):+ spec = SimpleNamespace(+ team_name="unit-team",+ workspace=SimpleNamespace(root_path=str(tmp_path / "team-workspace")),+ )+ captured_spec.append(spec)+ return specmonkeypatch.setattr(team_helpers, "get_team_manager", lambda channel_id: _FakeManager())@@ -1030,6 +1092,7 @@ async def test_process_team_message_stream_handles_team_evolve_list(monkeypatch)}assert chunks[1].is_complete is Falseassert chunks[2].is_complete is True+ assert captured_spec@pytest.mark.anyio@@ -1154,52 +1217,188 @@ async def test_process_team_message_stream_converts_a2ui_followup_event(monkeypaassert chunks[1].is_complete is True-async def test_process_team_message_stream_emits_processing_done_for_evolve_approval(monkeypatch):- approval_event = SimpleNamespace(- payload={"request_id": "team_skill_evolve_req1", "questions": [{"header": "x"}]},+async def test_process_team_message_stream_defers_first_evolve_until_team_runtime_exists(monkeypatch, tmp_path):+ captured_queries: list[str] = []+ user_intent = "没有特殊要求时格式尽量简洁,如果使用颜色也需要保持美观"+ _write_team_skill(tmp_path, "xlsx")++ class _FakeManager:+ @classmethod+ def has_stream_task(cls, session_id: str) -> bool:+ return False++ @classmethod+ async def get_swarm_enriched_team_spec(cls, **kwargs):+ return SimpleNamespace(+ team_name="unit-team",+ workspace=SimpleNamespace(root_path=str(tmp_path / "team-workspace")),+ )++ @staticmethod+ def ensure_team_shared_skills_ready_for_session(session_id: str, team_spec: object) -> None:+ return None++ @staticmethod+ async def prepare_runtime_activation(session_id: str, team_name: str) -> None:+ return None++ @staticmethod+ def register_stream_task(session_id: str, task: object) -> None:+ return None++ async def _fake_consume_stream_with_query(+ channel_id: str | None,+ session_id: str,+ spec: object,+ query: str,+ *,+ round_id: int,+ envs: dict | None = None,+ ) -> None:+ captured_queries.append(query)++ monkeypatch.setattr(team_helpers, "get_team_manager", lambda channel_id: _FakeManager())+ monkeypatch.setattr(team_helpers, "increment_session_round_count", lambda session_id: 1)+ monkeypatch.setattr(team_helpers, "_consume_stream_with_query", _fake_consume_stream_with_query)++ request = SimpleNamespace(+ session_id="sess-first-evolve",+ request_id="req-first-evolve",+ channel_id="web",+ metadata=None,+ params={"mode": "team"},)+ inputs = {"query": f"/evolve xlsx {user_intent}"}- class _FakeStore:+ chunks = []+ async for chunk in team_helpers.process_team_message_stream(request, inputs, object()):+ chunks.append(chunk)+ await asyncio.sleep(0)++ assert len(captured_queries) == 1+ assert "prepare_skill_evolution" in captured_queries[0]+ assert user_intent in captured_queries[0]+ assert not any(+ chunk.payload+ and chunk.payload.get("event_type") == "chat.error"+ and "TeamSkillEvolutionRail" in str(chunk.payload.get("error", ""))+ for chunk in chunks+ )+++async def test_process_team_message_stream_syncs_team_skills_before_evolve_slash(monkeypatch, tmp_path):+ captured_queries: list[str] = []+ user_intent = "没有特殊要求时格式尽量简洁,如果使用颜色也需要保持美观"++ class _FakeManager:@staticmethod- def skill_exists(skill_name: str) -> bool:- return skill_name == "demo-skill"+ def has_stream_task(session_id: str) -> bool:+ return False@staticmethod- def list_skill_names() -> list[str]:- return ["demo-skill"]+ async def get_swarm_enriched_team_spec(**kwargs):+ return SimpleNamespace(+ team_name="unit-team",+ workspace=SimpleNamespace(root_path=str(tmp_path / "team-workspace")),+ )- class _FakeRail:- store = _FakeStore()+ @staticmethod+ def ensure_team_shared_skills_ready_for_session(session_id: str, team_spec: object) -> None:+ _write_team_skill(tmp_path, "xlsx")@staticmethod- async def request_user_evolution(skill_name: str, user_query: str):- return SimpleNamespace(approval_event=approval_event, records=[object()])+ async def prepare_runtime_activation(session_id: str, team_name: str) -> None:+ return None- class _FakeManager:@staticmethod- async def get_or_create_team(**kwargs):- return object()+ def register_stream_task(session_id: str, task: object) -> None:+ return None+ async def _fake_consume_stream_with_query(+ channel_id: str | None,+ session_id: str,+ spec: object,+ query: str,+ *,+ round_id: int,+ envs: dict | None = None,+ ) -> None:+ captured_queries.append(query)++ monkeypatch.setattr(team_helpers, "get_team_manager", lambda channel_id: _FakeManager())+ monkeypatch.setattr(team_helpers, "increment_session_round_count", lambda session_id: 1)+ monkeypatch.setattr(team_helpers, "_consume_stream_with_query", _fake_consume_stream_with_query)++ request = SimpleNamespace(+ session_id="sess-sync-evolve",+ request_id="req-sync-evolve",+ channel_id="web",+ metadata=None,+ params={"mode": "team"},+ )+ inputs = {"query": f"/evolve xlsx {user_intent}"}++ chunks = []+ async for chunk in team_helpers.process_team_message_stream(request, inputs, object()):+ chunks.append(chunk)+ await asyncio.sleep(0)++ assert captured_queries+ assert "prepare_skill_evolution" in captured_queries[0]+ assert user_intent in captured_queries[0]+ assert not any(+ chunk.payload+ and chunk.payload.get("event_type") == "chat.error"+ and "未找到 Skill 'xlsx'" in str(chunk.payload.get("error", ""))+ for chunk in chunks+ )+++async def test_process_team_message_stream_runs_evolve_followup_without_rail(monkeypatch, tmp_path):+ captured_queries: list[str] = []+ _write_team_skill(tmp_path, "demo-skill")++ class _FakeManager:@staticmethoddef has_stream_task(session_id: str) -> bool:- return True+ return False@staticmethod- def get_team_skill_rail(session_id: str):- return _FakeRail()+ async def get_swarm_enriched_team_spec(**kwargs):+ return SimpleNamespace(+ team_name="unit-team",+ workspace=SimpleNamespace(root_path=str(tmp_path / "team-workspace")),+ )++ @staticmethod+ def ensure_team_shared_skills_ready_for_session(session_id: str, team_spec: object) -> None:+ return None++ @staticmethod+ async def prepare_runtime_activation(session_id: str, team_name: str) -> None:+ return None++ @staticmethod+ def register_stream_task(session_id: str, task: object) -> None:+ return Nonemonkeypatch.setattr(team_helpers, "get_team_manager", lambda channel_id: _FakeManager())- monkeypatch.setattr(team_helpers, "ensure_team_evolution_watcher", lambda *args, **kwargs: None)- monkeypatch.setattr(- team_helpers,- "parse_stream_chunk",- lambda evt: {- "event_type": "chat.ask_user_question",- "request_id": evt.payload["request_id"],- "questions": evt.payload["questions"],- },- )+ monkeypatch.setattr(team_helpers, "increment_session_round_count", lambda session_id: 1)++ async def _fake_consume_stream_with_query(+ channel_id: str | None,+ session_id: str,+ spec: object,+ query: str,+ *,+ round_id: int,+ envs: dict | None = None,+ ) -> None:+ captured_queries.append(query)++ monkeypatch.setattr(team_helpers, "_consume_stream_with_query", _fake_consume_stream_with_query)request = SimpleNamespace(session_id="sess-team-evolve",@@ -1217,56 +1416,47 @@ async def test_process_team_message_stream_emits_processing_done_for_evolve_appr):chunks.append(chunk)- assert [chunk.payload for chunk in chunks] == [- {- "event_type": "chat.ask_user_question",- "request_id": "team_skill_evolve_req1",- "questions": [{"header": "x"}],- },- {- "event_type": "chat.processing_status",- "session_id": "sess-team-evolve",- "is_processing": False,- "is_complete": True,- },- {"event_type": "chat.done"},- ]- assert [chunk.is_complete for chunk in chunks] == [False, False, True]+ await asyncio.sleep(0)+ assert captured_queries+ assert "prepare_skill_evolution" in captured_queries[0]+ assert chunks[-1].is_complete is True@pytest.mark.anyio-async def test_process_team_message_stream_does_not_emit_evolution_status_for_no_evolve_records(monkeypatch):- class _FakeStore:- @staticmethod- def skill_exists(skill_name: str) -> bool:- return skill_name == "demo-skill"+async def test_process_team_message_stream_does_not_emit_evolution_status_for_no_evolve_records(monkeypatch, tmp_path):+ _write_team_skill(tmp_path, "demo-skill")+ class _FakeManager:@staticmethod- def list_skill_names() -> list[str]:- return ["demo-skill"]-- class _FakeRail:- store = _FakeStore()+ def has_stream_task(session_id: str) -> bool:+ return False@staticmethod- async def request_user_evolution(skill_name: str, user_query: str):- return SimpleNamespace(approval_event=None, records=[])+ async def get_swarm_enriched_team_spec(**kwargs):+ return SimpleNamespace(+ team_name="unit-team",+ workspace=SimpleNamespace(root_path=str(tmp_path / "team-workspace")),+ )- class _FakeManager:@staticmethod- async def get_or_create_team(**kwargs):- return object()+ def ensure_team_shared_skills_ready_for_session(session_id: str, team_spec: object) -> None:+ return None@staticmethod- def has_stream_task(session_id: str) -> bool:- return True+ async def prepare_runtime_activation(session_id: str, team_name: str) -> None:+ return None@staticmethod- def get_team_skill_rail(session_id: str):- return _FakeRail()+ def register_stream_task(session_id: str, task: object) -> None:+ return Nonemonkeypatch.setattr(team_helpers, "get_team_manager", lambda channel_id: _FakeManager())- monkeypatch.setattr(team_helpers, "ensure_team_evolution_watcher", lambda *args, **kwargs: None)+ monkeypatch.setattr(team_helpers, "increment_session_round_count", lambda session_id: 1)++ async def _fake_consume_stream_with_query(*args, **kwargs) -> None:+ return None++ monkeypatch.setattr(team_helpers, "_consume_stream_with_query", _fake_consume_stream_with_query)request = SimpleNamespace(session_id="sess-team-evolve-noop",@@ -1284,10 +1474,7 @@ async def test_process_team_message_stream_does_not_emit_evolution_status_for_no):chunks.append(chunk)- assert [chunk.payload["event_type"] for chunk in chunks if chunk.payload] == [- "chat.final",- "chat.processing_status",- ]+ assert [chunk.payload["event_type"] for chunk in chunks if chunk.payload] == []assert chunks[-1].is_complete is True@@ -1562,28 +1749,7 @@ async def test_consume_stream_with_query_propagates_hide_dm_to_monitor(monkeypat@pytest.mark.anyio-async def test_handle_team_slash_command_requires_explicit_evolve_intent(monkeypatch):- class _FakeStore:- @staticmethod- def skill_exists(skill_name: str) -> bool:- return skill_name == "demo-skill"-- @staticmethod- def list_skill_names() -> list[str]:- return ["demo-skill"]-- rail = SimpleNamespace(- store=_FakeStore(),- request_user_evolution=None,- )-- class _FakeManager:- @staticmethod- def get_team_skill_rail(session_id: str):- return rail-- monkeypatch.setattr(team_helpers, "get_team_manager", lambda channel_id: _FakeManager())-+async def test_handle_team_slash_command_requires_explicit_evolve_intent():result = await _TeamHelpersTestApi.handle_team_slash_command("web","sess-team-evolve",@@ -1597,177 +1763,117 @@ async def test_handle_team_slash_command_requires_explicit_evolve_intent(monkeyp@pytest.mark.anyio-async def test_handle_team_slash_command_submits_explicit_evolve_request(monkeypatch):- recorded_calls: list[tuple[str, str]] = []- watcher_calls: list[tuple[str | None, str, str]] = []-- class _FakeStore:- @staticmethod- def skill_exists(skill_name: str) -> bool:- return skill_name == "demo-skill"-- @staticmethod- def list_skill_names() -> list[str]:- return ["demo-skill"]-- class _FakeRail:- store = _FakeStore()-- @staticmethod- async def request_user_evolution(skill_name: str, user_query: str):- recorded_calls.append((skill_name, user_query))- return SimpleNamespace(- approval_event=SimpleNamespace(- type="chat.ask_user_question",- payload={- "request_id": "team_skill_evolve_req1",- "questions": [{"header": "x"}],- },- ),- records=[object()],- )-- class _FakeManager:- @staticmethod- def get_team_skill_rail(session_id: str):- return _FakeRail()-- monkeypatch.setattr(team_helpers, "get_team_manager", lambda channel_id: _FakeManager())- monkeypatch.setattr(- team_helpers,- "parse_stream_chunk",- lambda evt: {- "event_type": "chat.ask_user_question",- "request_id": evt.payload["request_id"],- "questions": evt.payload["questions"],- },- )- monkeypatch.setattr(- team_helpers,- "ensure_team_evolution_watcher",- lambda channel_id, session_id, *, source="unknown": watcher_calls.append(- (channel_id, session_id, source)- ),- )+async def test_handle_team_slash_command_submits_explicit_evolve_request(tmp_path):+ skills_dir = _write_team_skill(tmp_path, "demo-skill")result = await _TeamHelpersTestApi.handle_team_slash_command("web","sess-team-evolve","/evolve demo-skill improve review flow",+ skills_dir=skills_dir,)- assert recorded_calls == [("demo-skill", "improve review flow")]- assert watcher_calls == []- assert result == {- "output": "Skill 'demo-skill' 演进请求已生成,请在审批弹框中确认。",- "result_type": "answer",- "approval_chunks": [- {- "event_type": "chat.ask_user_question",- "request_id": "team_skill_evolve_req1",- "questions": [{"header": "x"}],- }- ],- "question_count": 1,- }+ assert result is not None+ assert result["result_type"] == "followup"+ assert result["action"] == "run_evolve_followup"+ assert result["skill_name"] == "demo-skill"+ assert "prepare_skill_evolution" in result["followup_prompt"]+ assert 'subject={"kind": "swarm-skill", "name": "demo-skill"}' in result["followup_prompt"]+ assert "improve review flow" in result["followup_prompt"]@pytest.mark.anyio-async def test_handle_team_slash_command_maps_generation_failed_status(monkeypatch):- class _FakeStore:- @staticmethod- def skill_exists(skill_name: str) -> bool:- return skill_name == "demo-skill"-- @staticmethod- def skill_definition_exists(skill_name: str) -> bool:- return skill_name == "demo-skill"-- @staticmethod- def list_skill_names() -> list[str]:- return ["demo-skill"]+async def test_handle_team_slash_command_uses_regular_skill_subject_kind(tmp_path):+ skills_dir = _write_regular_skill(tmp_path, "regular-skill")- class _FakeRail:- store = _FakeStore()+ result = await _TeamHelpersTestApi.handle_team_slash_command(+ "web",+ "sess-team-evolve",+ "/evolve regular-skill improve review flow",+ skills_dir=skills_dir,+ )- @staticmethod- async def request_user_evolution(skill_name: str, user_query: str):- return SimpleNamespace(- status="generation_failed",- message="llm unavailable",- approval_event=None,- records=[],- )+ assert result is not None+ assert result["result_type"] == "followup"+ assert result["action"] == "run_evolve_followup"+ assert result["skill_name"] == "regular-skill"+ assert 'subject={"kind": "skill", "name": "regular-skill"}' in result["followup_prompt"]+ assert "swarm-skill" not in result["followup_prompt"]- class _FakeManager:- @staticmethod- def get_team_skill_rail(session_id: str):- return _FakeRail()- monkeypatch.setattr(team_helpers, "get_team_manager", lambda channel_id: _FakeManager())+async def test_handle_team_slash_command_returns_agent_driven_followup_for_xlsx(tmp_path):+ user_intent = "没有特殊要求时格式尽量简洁,如果使用颜色也需要保持美观"+ skills_dir = _write_team_skill(tmp_path, "xlsx")result = await _TeamHelpersTestApi.handle_team_slash_command("web","sess-team-evolve",- "/evolve demo-skill improve review flow",+ f"/evolve xlsx {user_intent}",+ skills_dir=skills_dir,)- assert result == {- "output": "llm unavailable",- "result_type": "error",- }+ assert result is not None+ assert result["action"] == "run_evolve_followup"+ assert result["skill_name"] == "xlsx"+ assert result["result_type"] == "followup"+ assert user_intent in result["followup_prompt"]@pytest.mark.anyio-async def test_handle_team_slash_command_simplify_reports_noop(monkeypatch):- recorded_calls: list[tuple[str, str | None]] = []- watcher_calls: list[tuple[str | None, str, str]] = []+async def test_handle_team_slash_command_reports_missing_skill(tmp_path):+ skills_dir = str(tmp_path / "team-workspace" / "skills")- class _FakeStore:- @staticmethod- def skill_exists(skill_name: str) -> bool:- return skill_name == "demo-skill"-- @staticmethod- def list_skill_names() -> list[str]:- return ["demo-skill"]-- class _FakeRail:- store = _FakeStore()+ result = await _TeamHelpersTestApi.handle_team_slash_command(+ "web",+ "sess-team-evolve",+ "/evolve demo-skill improve review flow",+ skills_dir=skills_dir,+ )- @staticmethod- async def request_simplify(skill_name: str, user_intent: str | None):- recorded_calls.append((skill_name, user_intent))- return None+ assert result is not None+ assert result["result_type"] == "error"+ assert "未找到 Skill 'demo-skill'" in result["output"]- class _FakeManager:- @staticmethod- def get_team_skill_rail(session_id: str):- return _FakeRail()- monkeypatch.setattr(team_helpers, "get_team_manager", lambda channel_id: _FakeManager())- monkeypatch.setattr(- team_helpers,- "ensure_team_evolution_watcher",- lambda channel_id, session_id, *, source="unknown": watcher_calls.append(- (channel_id, session_id, source)- ),- )+async def test_handle_team_slash_command_simplify_reports_noop(tmp_path):+ skills_dir = _write_team_skill(tmp_path, "demo-skill")result = await _TeamHelpersTestApi.handle_team_slash_command("web","sess-team-simplify","/evolve_simplify demo-skill",+ skills_dir=skills_dir,)- assert recorded_calls == [("demo-skill", None)]- assert watcher_calls == []assert result == {- "output": "Skill 'demo-skill' 经验库状态良好,无需整理。",+ "output": "Skill 'demo-skill' 暂无演进经验,无需整理。","result_type": "answer",}+async def test_handle_team_slash_command_lists_regular_skill_records(tmp_path):+ skills_dir = _write_regular_skill(+ tmp_path,+ "regular-skill",+ records=[_evolution_record("Improve regular retry flow")],+ )++ result = await _TeamHelpersTestApi.handle_team_slash_command(+ "web",+ "sess-team-evolve",+ "/evolve_list regular-skill",+ skills_dir=skills_dir,+ )++ assert result is not None+ assert result["result_type"] == "answer"+ assert 'Skill "regular-skill"' in result["output"]+ assert "Improve regular retry flow" in result["output"]++# ---------------------------------------------------------------------------# WorkflowMonitorHandler integration tests# ---------------------------------------------------------------------------diff --git a/tests/unit_tests/agentserver/test_team_runtime_inheritance.py b/tests/unit_tests/agentserver/test_team_runtime_inheritance.pyindex 5c335de955..457744e669 100644--- a/tests/unit_tests/agentserver/test_team_runtime_inheritance.py+++ b/tests/unit_tests/agentserver/test_team_runtime_inheritance.py@@ -212,12 +212,19 @@ def test_build_member_rails_wires_team_trajectory_registry_to_evolution_rails(class _FakeTeamSkillEvolutionRail:def __init__(self, **kwargs):self.kwargs = kwargs+ self.experience_manager = SimpleNamespace(+ experience_submission_service=object()+ )class _FakeSkillEvolutionRail:def __init__(self, **kwargs):self.bound_sink = Noneself.bound_team_id = Noneself.bound_member_role = None+ self._review_runtime = kwargs.get("review_runtime")+ self.experience_manager = SimpleNamespace(+ experience_submission_service=object()+ )def set_trajectory_sink(self, sink, *, team_id, member_role):self.bound_sink = sink@@ -294,6 +301,9 @@ def test_build_member_rails_creates_leader_team_skill_evolution_rail_with_auto_sclass _FakeTeamSkillEvolutionRail:def __init__(self, **kwargs):self.kwargs = kwargs+ self.experience_manager = SimpleNamespace(+ experience_submission_service=object()+ )if env_auto_scan is None:monkeypatch.delenv("EVOLUTION_AUTO_SCAN", raising=False)@@ -321,14 +331,84 @@ def test_build_member_rails_creates_leader_team_skill_evolution_rail_with_auto_sassert team_skill_rails[0].kwargs["auto_scan"] is expected_auto_scan+def test_build_member_rails_wires_leader_team_skill_evolution_active_review_rails(+ tmp_path,+ monkeypatch,+):+ class _FakeEvolutionInterruptRail:+ def __init__(self, **kwargs):+ self.kwargs = kwargs++ class _FakeTeamSkillEvolutionRail:+ def __init__(self, **kwargs):+ self.kwargs = kwargs+ self.experience_manager = SimpleNamespace(+ experience_submission_service=object()+ )++ monkeypatch.delenv("EVOLUTION_AUTO_SCAN", raising=False)+ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.team.team_runtime_inheritance.EvolutionInterruptRail",+ _FakeEvolutionInterruptRail,+ )+ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.team.team_runtime_inheritance.TeamSkillEvolutionRail",+ _FakeTeamSkillEvolutionRail,+ )+ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.team.team_runtime_inheritance.build_evolution_llm",+ lambda config=None: (object(), "model"),+ )++ rails = build_member_rails(+ member_info=MemberInfo(role="leader"),+ runtime=RuntimeInfo(channel="web"),+ team_workspace=TeamWorkspaceInfo(+ skills_dir=str(tmp_path / "skills"),+ config={"evolution": {"auto_scan": False}},+ ),+ )++ interrupt_index = next(+ index for index, rail in enumerate(rails) if isinstance(rail, _FakeEvolutionInterruptRail)+ )+ team_index = next(+ index for index, rail in enumerate(rails) if isinstance(rail, _FakeTeamSkillEvolutionRail)+ )+ assert interrupt_index < team_index++ interrupt_rail = rails[interrupt_index]+ team_rail = rails[team_index]+ assert "review_runtime" in team_rail.kwargs+ assert interrupt_rail.kwargs["review_runtime"] is team_rail.kwargs["review_runtime"]+ assert (+ interrupt_rail.kwargs["submission_service"]+ is team_rail.experience_manager.experience_submission_service+ )+ assert interrupt_rail.kwargs["auto_save"] is False+ assert interrupt_rail.kwargs["language"] == "cn"++def test_build_member_rails_keeps_member_skill_evolution_when_auto_scan_disabled(tmp_path, monkeypatch):+ class _FakeEvolutionInterruptRail:+ def __init__(self, **kwargs):+ self.kwargs = kwargs+class _FakeSkillEvolutionRail:def __init__(self, **kwargs):self.auto_scan = kwargs["auto_scan"]+ self._review_runtime = kwargs.get("review_runtime")+ self.experience_manager = SimpleNamespace(+ experience_submission_service=object()+ )monkeypatch.delenv("EVOLUTION_AUTO_SCAN", raising=False)+ monkeypatch.setattr(+ "jiuwenswarm.agents.harness.team.team_runtime_inheritance.EvolutionInterruptRail",+ _FakeEvolutionInterruptRail,+ )monkeypatch.setattr("jiuwenswarm.agents.harness.team.team_runtime_inheritance.SkillEvolutionRail",_FakeSkillEvolutionRail,@@ -350,6 +430,11 @@ def test_build_member_rails_keeps_member_skill_evolution_when_auto_scan_disabledevo_rails = [rail for rail in rails if isinstance(rail, _FakeSkillEvolutionRail)]assert len(evo_rails) == 1assert evo_rails[0].auto_scan is False+ interrupt_index = next(+ index for index, rail in enumerate(rails) if isinstance(rail, _FakeEvolutionInterruptRail)+ )+ skill_index = next(index for index, rail in enumerate(rails) if isinstance(rail, _FakeSkillEvolutionRail))+ assert interrupt_index < skill_indexdef test_build_member_rails_keeps_team_skill_create_when_auto_scan_disabled(diff --git a/tests/unit_tests/e2a/test_wire_codec.py b/tests/unit_tests/e2a/test_wire_codec.pyindex f7a4ad0116..0de8fecef2 100644--- a/tests/unit_tests/e2a/test_wire_codec.py+++ b/tests/unit_tests/e2a/test_wire_codec.py@@ -4,9 +4,11 @@from __future__ import annotations+import jsonfrom dataclasses import asdictimport pytest+from openjiuwen.core.session.stream import OutputSchemafrom jiuwenswarm.common.e2a.constants import E2A_WIRE_LEGACY_AGENT_RESPONSE_KEYfrom jiuwenswarm.common.e2a.gateway_normalize import (@@ -54,6 +56,33 @@ def test_roundtrip_unary_error() -> None:assert back.payload == orig.payload+def test_encode_unary_with_nested_output_schema_is_json_serializable() -> None:+ orig = AgentResponse(+ request_id="approval-answer",+ channel_id="web",+ ok=True,+ payload={+ "result": OutputSchema(+ type="answer",+ index=0,+ payload={"output": "approval accepted", "result_type": "answer"},+ )+ },+ )++ wire = encode_agent_response_for_wire(orig, response_id="approval-answer")++ json.dumps(wire, ensure_ascii=False)+ back = parse_agent_server_wire_unary(wire)+ assert back.payload == {+ "result": {+ "type": "answer",+ "index": 0,+ "payload": {"output": "approval accepted", "result_type": "answer"},+ }+ }++def test_roundtrip_chunk_sentinel_complete() -> None:orig = AgentResponseChunk(request_id="s1",diff --git a/tests/unit_tests/evolution/test_signal_detector.py b/tests/unit_tests/evolution/test_signal_detector.pyindex 6ebec98da7..269275cbea 100644--- a/tests/unit_tests/evolution/test_signal_detector.py+++ b/tests/unit_tests/evolution/test_signal_detector.py@@ -60,8 +60,8 @@ class TestSignalDetector:]signals = await detector.detect_user_message_feedback(messages)assert len(signals) == 1- assert signals[0].signal_type == "user_correction"- assert signals[0].section == "Examples"+ assert signals[0].signal_type == "user_intent"+ assert signals[0].section == "Instructions"@staticmethod@pytest.mark.asyncio@@ -83,8 +83,8 @@ class TestSignalDetector:]signals = await detector.detect_user_message_feedback(messages)assert len(signals) == 1- assert signals[0].signal_type == "user_correction"- assert signals[0].section == "Examples"+ assert signals[0].signal_type == "user_intent"+ assert signals[0].section == "Instructions"@staticmethoddef test_detect_multiple_signals():diff --git a/tests/unit_tests/gateway/test_message_handler_evolution.py b/tests/unit_tests/gateway/test_message_handler_evolution.pyindex 5c17d0f6d5..680c9942a3 100644--- a/tests/unit_tests/gateway/test_message_handler_evolution.py+++ b/tests/unit_tests/gateway/test_message_handler_evolution.py@@ -1,5 +1,6 @@"""MessageHandler unit tests."""+import asynciofrom collections.abc import AsyncIteratorfrom types import SimpleNamespace@@ -10,8 +11,20 @@ from jiuwenswarm.common.schema.message import ReqMethodfrom jiuwenswarm.gateway.message_handler.message_handler import MessageHandler+_APPROVAL_SCHEMA = "openjiuwen.skill_evolution_approval.v1"+_APPROVAL_SOURCE = "skill_evolution_approval"+_INTERRUPT_APPROVAL_META = {+ "event_kind": "approval",+ "rail_kind": "regular",+ "approval_kind": "evolve",+ "approval_transport": "interrupt",+}++class _FakeAgentClient:sent_requests: list[object] = []+ sent_stream_requests: list[object] = []+ stream_payloads: list[dict[str, object]] = []response_payload: dict[str, object] = {"event_type": "chat.interrupt_result","message": "当前没有可取消的团队任务",@@ -31,8 +44,14 @@ class _FakeAgentClient:@staticmethodasync def send_request_stream(env: object) -> AsyncIterator[object]:- if False:- yield env+ _FakeAgentClient.sent_stream_requests.append(env)+ for index, payload in enumerate(_FakeAgentClient.stream_payloads):+ yield SimpleNamespace(+ request_id=getattr(env, "request_id", "") or f"stream-{index}",+ channel_id=getattr(env, "channel", "") or "web",+ payload=payload,+ is_complete=False,+ )class _TestMessageHandler(MessageHandler):@@ -41,6 +60,8 @@ class _TestMessageHandler(MessageHandler):setattr(MessageHandler, "_instance", None)setattr(cls, "_instance", None)_FakeAgentClient.sent_requests = []+ _FakeAgentClient.sent_stream_requests = []+ _FakeAgentClient.stream_payloads = []return cls(_FakeAgentClient())def seed_pending_evolution_approval(@@ -130,6 +151,9 @@ class _TestMessageHandler(MessageHandler):def get_session_last_user_query(self, session_id: str) -> str:return self._get_session_last_user_query(session_id)+ async def _trigger_before_chat_request_hook(self, msg: Message) -> None:+ return None+def _message(req_method: ReqMethod) -> Message:return Message(@@ -145,6 +169,121 @@ def _message(req_method: ReqMethod) -> Message:)+def _answer_message(params: dict[str, object]) -> Message:+ return Message(+ id="answer-1",+ type="req",+ channel_id="web",+ session_id="sess-1",+ params=params,+ timestamp=0,+ ok=True,+ req_method=ReqMethod.CHAT_ANSWER,+ is_stream=False,+ )+++def _chat_send_message(params: dict[str, object]) -> Message:+ return Message(+ id="chat-send-1",+ type="req",+ channel_id="web",+ session_id="sess-1",+ params=params,+ timestamp=0,+ ok=True,+ req_method=ReqMethod.CHAT_SEND,+ is_stream=False,+ )+++def _stream_chat_send_message(params: dict[str, object]) -> Message:+ msg = _chat_send_message(params)+ msg.is_stream = True+ return msg+++def _evolution_question_chunk(+ request_id: str,+ *,+ include_approval_context: bool = False,+) -> SimpleNamespace:+ payload: dict[str, object] = {+ "event_type": "chat.ask_user_question",+ "request_id": request_id,+ "questions": [{"header": "x"}],+ }+ if include_approval_context:+ payload.update(+ {+ "source": _APPROVAL_SOURCE,+ "approval_schema": _APPROVAL_SCHEMA,+ }+ )+ return SimpleNamespace(+ channel_id="web",+ request_id="stream-1",+ payload=payload,+ )+++def _interrupt_approval_meta() -> dict[str, str]:+ return dict(_INTERRUPT_APPROVAL_META)+++def _approval_answer_params(+ request_id: str,+ selected_options: list[str],+ *,+ query: str | None = None,+ evolution_meta: dict[str, str] | None = None,+) -> dict[str, object]:+ params: dict[str, object] = {+ "request_id": request_id,+ "answers": [{"selected_options": selected_options}],+ "source": _APPROVAL_SOURCE,+ "approval_schema": _APPROVAL_SCHEMA,+ }+ if query is not None:+ params["query"] = query+ if evolution_meta is not None:+ params["evolution_meta"] = evolution_meta+ return params+++def _is_finished_processing_status(msg: object) -> bool:+ payload = getattr(msg, "payload", None)+ return (+ isinstance(payload, dict)+ and payload.get("event_type") == "chat.processing_status"+ and payload.get("is_processing") is False+ )+++def _has_finished_processing_status(outputs: list[object]) -> bool:+ return any(_is_finished_processing_status(msg) for msg in outputs)+++async def _wait_for_pending_clear(+ handler: _TestMessageHandler,+ *,+ require_stream_request: bool = False,+) -> None:+ for _ in range(20):+ if (+ handler.pending_evolution_approval("sess-1") is None+ and (not require_stream_request or _FakeAgentClient.sent_stream_requests)+ ):+ return+ await asyncio.sleep(0.05)+++def _assert_evolution_state_cleared(handler: _TestMessageHandler) -> None:+ assert handler.pending_evolution_approval("sess-1") is None+ assert handler.has_session_evolution_in_progress("sess-1") is False+ assert handler.queued_supplement_input("sess-1") is None++def _control_message() -> Message:return Message(id="control-1",@@ -209,27 +348,283 @@ async def test_handle_evolution_chunk_auto_accepts_previous_pending_approval() -handler = _TestMessageHandler.create()handler.seed_pending_evolution_approval("sess-1", "team_skill_evolve_old")- chunk = SimpleNamespace(- channel_id="web",- request_id="stream-1",- payload={- "event_type": "chat.ask_user_question",- "request_id": "team_skill_evolve_new",- "questions": [{"header": "x"}],- },+ await handler.handle_evolution_chunk(+ _evolution_question_chunk("team_skill_evolve_new"),+ "sess-1",+ {"k": "v"},)- await handler.handle_evolution_chunk(chunk, "sess-1", {"k": "v"})-assert handler.pending_evolution_approval("sess-1") == "team_skill_evolve_new"auto_msg = handler.pop_user_message_nowait()assert auto_msg.session_id == "sess-1"assert auto_msg.channel_id == "web"assert auto_msg.params["request_id"] == "team_skill_evolve_old"assert auto_msg.params["answers"] == [{"selected_options": ["接收"]}]+ assert auto_msg.params["approval_schema"] == _APPROVAL_SCHEMA+ assert auto_msg.params["evolution_meta"]["rail_kind"] == "regular"+ assert auto_msg.metadata == {"k": "v"}+++async def test_handle_evolution_chunk_auto_accepts_replaced_regular_call_with_metadata() -> None:+ handler = _TestMessageHandler.create()+ handler.seed_pending_evolution_approval("sess-1", "call_123")++ await handler.handle_evolution_chunk(+ _evolution_question_chunk("skill_evolve_new"),+ "sess-1",+ {"k": "v"},+ )++ assert handler.pending_evolution_approval("sess-1") == "skill_evolve_new"+ auto_msg = handler.pop_user_message_nowait()+ assert auto_msg.params["request_id"] == "call_123"+ assert auto_msg.params["approval_schema"] == _APPROVAL_SCHEMA+ assert auto_msg.params["evolution_meta"] == _interrupt_approval_meta()assert auto_msg.metadata == {"k": "v"}+async def test_handle_evolution_chunk_tracks_regular_approval_without_request_prefix() -> None:+ handler = _TestMessageHandler.create()++ await handler.handle_evolution_chunk(+ _evolution_question_chunk("call_123", include_approval_context=True),+ "sess-1",+ {"k": "v"},+ )++ assert handler.pending_evolution_approval("sess-1") == "call_123"+++async def test_regular_evolution_approval_answer_resolved_clears_processing_status() -> None:+ handler = _TestMessageHandler.create()+ old_response_payload = dict(_FakeAgentClient.response_payload)+ _FakeAgentClient.response_payload = {"accepted": True, "resolved": True}+ await handler.handle_evolution_chunk(+ _evolution_question_chunk("call_123", include_approval_context=True),+ "sess-1",+ )+ await handler.start_forwarding()+ try:+ await handler.publish_user_messages(+ _answer_message(_approval_answer_params("call_123", ["接收"]))+ )++ outputs = [+ await handler.consume_robot_messages(timeout=2),+ await handler.consume_robot_messages(timeout=2),+ ]++ assert _has_finished_processing_status(outputs)+ finally:+ _FakeAgentClient.response_payload = old_response_payload+ await handler.stop_forwarding()+++async def test_interrupt_evolution_approval_chat_send_cleans_pending_and_releases_queued_supplement() -> None:+ handler = _TestMessageHandler.create()+ old_response_payload = dict(_FakeAgentClient.response_payload)+ _FakeAgentClient.response_payload = {"accepted": True}+ handler.seed_pending_evolution_approval("sess-1", "call_123")+ handler.seed_session_evolution_in_progress("sess-1")+ handler.seed_queued_supplement_input("sess-1", {"new_input": "继续补充"})+ await handler.start_forwarding()+ try:+ await handler.publish_user_messages(+ _chat_send_message(+ _approval_answer_params(+ "call_123",+ ["allow_once"],+ query="",+ evolution_meta=_interrupt_approval_meta(),+ )+ )+ )++ await _wait_for_pending_clear(handler, require_stream_request=True)++ _assert_evolution_state_cleared(handler)+ assert _FakeAgentClient.sent_requests == []+ sent_params = _FakeAgentClient.sent_stream_requests[0].params+ assert sent_params["request_id"] == "call_123"+ assert sent_params["source"] == _APPROVAL_SOURCE+ queued_params = _FakeAgentClient.sent_stream_requests[-1].params+ assert queued_params["supplement_input"] == "继续补充"+ assert queued_params["is_supplement"] is True+ finally:+ _FakeAgentClient.response_payload = old_response_payload+ await handler.stop_forwarding()+++async def test_interrupt_evolution_approval_chat_send_without_supplement_finishes_processing() -> None:+ handler = _TestMessageHandler.create()+ old_response_payload = dict(_FakeAgentClient.response_payload)+ _FakeAgentClient.response_payload = {"accepted": True}+ handler.seed_pending_evolution_approval("sess-1", "call_123")+ handler.seed_session_evolution_in_progress("sess-1")+ await handler.start_forwarding()+ try:+ await handler.publish_user_messages(+ _chat_send_message(+ _approval_answer_params(+ "call_123",+ ["allow_once"],+ evolution_meta=_interrupt_approval_meta(),+ )+ )+ )++ await _wait_for_pending_clear(handler)+ outputs = [+ await handler.consume_robot_messages(timeout=2),+ await handler.consume_robot_messages(timeout=2),+ ]++ _assert_evolution_state_cleared(handler)+ assert _FakeAgentClient.sent_requests == []+ assert _FakeAgentClient.sent_stream_requests[0].params["request_id"] == "call_123"+ assert _has_finished_processing_status(outputs)+ finally:+ _FakeAgentClient.response_payload = old_response_payload+ await handler.stop_forwarding()+++async def test_interrupt_evolution_approval_chat_send_streams_resume_output() -> None:+ handler = _TestMessageHandler.create()+ _FakeAgentClient.stream_payloads = [+ {"event_type": "chat.delta", "content": "审批后继续展示"},+ ]+ handler.seed_pending_evolution_approval("sess-1", "call_123")+ handler.seed_session_evolution_in_progress("sess-1")+ await handler.start_forwarding()+ try:+ await handler.publish_user_messages(+ _chat_send_message(+ _approval_answer_params(+ "call_123",+ ["allow_once"],+ evolution_meta=_interrupt_approval_meta(),+ )+ )+ )++ await _wait_for_pending_clear(handler, require_stream_request=True)+ outputs = [+ await handler.consume_robot_messages(timeout=2),+ await handler.consume_robot_messages(timeout=2),+ await handler.consume_robot_messages(timeout=2),+ ]++ _assert_evolution_state_cleared(handler)+ assert _FakeAgentClient.sent_requests == []+ assert _FakeAgentClient.sent_stream_requests[0].params["request_id"] == "call_123"+ assert any(+ getattr(msg, "payload", {}).get("content") == "审批后继续展示"+ for msg in outputs+ if msg is not None+ )+ assert _has_finished_processing_status(outputs)+ finally:+ await handler.stop_forwarding()+++async def test_stale_interrupt_evolution_approval_chat_send_keeps_current_processing() -> None:+ handler = _TestMessageHandler.create()+ handler.seed_pending_evolution_approval("sess-1", "call_new")+ handler.seed_session_evolution_in_progress("sess-1")+ await handler.start_forwarding()+ try:+ await handler.publish_user_messages(+ _chat_send_message(+ _approval_answer_params(+ "call_old",+ ["allow_once"],+ evolution_meta=_interrupt_approval_meta(),+ )+ )+ )++ await asyncio.sleep(0.05)++ assert handler.pending_evolution_approval("sess-1") == "call_new"+ assert handler.has_session_evolution_in_progress("sess-1") is True+ assert _FakeAgentClient.sent_requests == []+ assert _FakeAgentClient.sent_stream_requests == []+ assert await handler.consume_robot_messages(timeout=0) is None+ finally:+ await handler.stop_forwarding()+++async def test_interrupt_evolution_approval_user_answer_is_dispatched_as_chat_send() -> None:+ handler = _TestMessageHandler.create()+ old_response_payload = dict(_FakeAgentClient.response_payload)+ _FakeAgentClient.response_payload = {"accepted": True}+ handler.seed_pending_evolution_approval("sess-1", "call_123")+ handler.seed_session_evolution_in_progress("sess-1")+ handler.seed_queued_supplement_input("sess-1", {"new_input": "继续补充"})+ await handler.start_forwarding()+ try:+ await handler.publish_user_messages(+ _answer_message(+ _approval_answer_params(+ "call_123",+ ["allow_once"],+ evolution_meta=_interrupt_approval_meta(),+ )+ )+ )++ await _wait_for_pending_clear(handler, require_stream_request=True)++ assert handler.pending_evolution_approval("sess-1") is None+ assert _FakeAgentClient.sent_requests == []+ sent = _FakeAgentClient.sent_stream_requests[0]+ assert sent.method == ReqMethod.CHAT_SEND.value+ assert sent.is_stream is True+ assert sent.params["request_id"] == "call_123"+ assert sent.params["answers"] == [{"selected_options": ["allow_once"]}]+ queued_params = _FakeAgentClient.sent_stream_requests[-1].params+ assert queued_params["supplement_input"] == "继续补充"+ finally:+ _FakeAgentClient.response_payload = old_response_payload+ await handler.stop_forwarding()+++async def test_stream_interrupt_evolution_approval_chat_send_cleans_pending() -> None:+ handler = _TestMessageHandler.create()+ handler.seed_pending_evolution_approval("sess-1", "call_123")+ handler.seed_session_evolution_in_progress("sess-1")+ handler.seed_queued_supplement_input("sess-1", {"new_input": "继续补充"})+ await handler.start_forwarding()+ try:+ await handler.publish_user_messages(+ _stream_chat_send_message(+ _approval_answer_params(+ "call_123",+ ["allow_once"],+ query="",+ evolution_meta=_interrupt_approval_meta(),+ )+ )+ )++ await _wait_for_pending_clear(handler, require_stream_request=True)++ _assert_evolution_state_cleared(handler)+ assert _FakeAgentClient.sent_stream_requests[0].params["request_id"] == "call_123"+ assert _FakeAgentClient.sent_stream_requests[-1].params["supplement_input"] == "继续补充"+ finally:+ await handler.stop_forwarding()++def test_finish_evolution_approval_if_current_keeps_newer_pending_request() -> None:handler = _TestMessageHandler.create()handler.seed_pending_evolution_approval("sess-2", "team_skill_evolve_new")diff --git a/uv.lock b/uv.lockindex 84a169f7ac..8bf0d96732 100644--- a/uv.lock+++ b/uv.lock@@ -2656,7 +2656,7 @@ wheels = [[[package]]name = "openjiuwen"version = "0.1.14"-source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=develop#fc84d3b059b8a2f1a438d569f8305d9f70bcc228" }+source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=develop#5a569f534c202c74c8e973c0cd2e43eee7556441" }dependencies = [{ name = "aiofiles" },{ name = "aiohttp" },