JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat(swarmflow): 支持swarmflow能力
alan_cheng22bce9377eb1
diff --git a/jiuwenswarm/agents/harness/code/rails/code_task_planning_rail.py b/jiuwenswarm/agents/harness/code/rails/code_task_planning_rail.pyindex 72bf94d74b..76b78e9530 100644--- a/jiuwenswarm/agents/harness/code/rails/code_task_planning_rail.py+++ b/jiuwenswarm/agents/harness/code/rails/code_task_planning_rail.py@@ -79,8 +79,12 @@ class CodeTaskPlanningRail(TaskPlanningRail):"en",agent_id,)- Runner.resource_mgr.add_tool(new_tool)- agent.ability_manager.add(new_tool.card)+ # Unified registration (mirrors the parent TaskPlanningRail):+ # add_ability qualifies the stateful tool id to+ # ``{name}_{owner_id}`` and lets teardown_tools drop it at+ # round-end, instead of leaking a bare id that refresh-warns+ # on the next native rebuild.+ agent.ability_manager.add_ability(new_tool.card, new_tool)tools.append(new_tool)self.tools = toolsexcept Exception as exc:diff --git a/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py b/jiuwenswarm/agents/harness/common/rails/ask_user_rail.pyindex 9a0bac52c8..aefddbceb8 100644--- a/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py+++ b/jiuwenswarm/agents/harness/common/rails/ask_user_rail.py@@ -222,23 +222,24 @@ class StructuredAskUserRail(AskUserRail):tool = StructuredAskUserTool(language=language, agent_id=agent_id)self._structured_tools = [tool]- from openjiuwen.core.runner.runner import Runner- Runner.resource_mgr.add_tool(self._structured_tools)-+ # Unified registration: add_ability qualifies the stateful tool id to+ # ``{name}_{owner_id}`` and binds it in the resource manager, so+ # teardown_tools drops it at round-end instead of leaking a bare id that+ # refresh-warns on the next native rebuild.for tool in self._structured_tools:- agent.ability_manager.add(tool.card)+ agent.ability_manager.add_ability(tool.card, tool)def uninit(self, agent):"""Remove the extended ask_user tool."""+ if not hasattr(agent, "ability_manager"):+ self._structured_tools = []+ returnfor tool in self._structured_tools:name = getattr(tool.card, "name", None)- if name and hasattr(agent, "ability_manager"):- agent.ability_manager.remove(name)-- tool_id = tool.card.id- if tool_id:- from openjiuwen.core.runner.runner import Runner- Runner.resource_mgr.remove_tool(tool_id)+ if name:+ # Mirror add_ability: removes the agent-qualified id from both+ # this manager and the shared resource manager.+ agent.ability_manager.remove_ability(name)self._structured_tools = []def get_structured_tools(self) -> list[StructuredAskUserTool]:diff --git a/jiuwenswarm/agents/harness/team/rails/team_member_skill_toolkit_rail.py b/jiuwenswarm/agents/harness/team/rails/team_member_skill_toolkit_rail.pyindex 070e9b007c..47ea138acd 100644--- a/jiuwenswarm/agents/harness/team/rails/team_member_skill_toolkit_rail.py+++ b/jiuwenswarm/agents/harness/team/rails/team_member_skill_toolkit_rail.py@@ -7,8 +7,7 @@ from __future__ import annotationsimport loggingfrom typing import TYPE_CHECKING, Any, Callable-from openjiuwen.core.foundation.tool import LocalFunction, Tool, ToolCard-from openjiuwen.core.runner import Runner+from openjiuwen.core.foundation.tool import LocalFunction, Toolfrom openjiuwen.harness.rails.base import DeepAgentRailfrom jiuwenswarm.server.runtime.skill.skill_manager import SkillManager@@ -43,30 +42,24 @@ class MemberSkillToolkitRail(DeepAgentRail):if self._tools is not None:return- agent_id = str(agent.card.id or agent.card.name)if self._manager is None:self._manager = SkillManager(workspace_dir=self._workspace_dir)toolkit = SkillToolkit(manager=self._manager)tools = self._wrap_skill_tools(toolkit.get_tools())+ # ``add_ability`` qualifies the (stateful) skill-tool id with the owner+ # agent id and registers with refresh=True, so this rail's registration+ # deterministically wins over the declarative skill-toolkit tool element+ # carrying the same name.for tool in tools:- tool.card.id = self._qualify_tool_id(tool.card.id, agent_id)-- for tool in tools:- existing = agent.ability_manager.get(tool.card.name)- if isinstance(existing, ToolCard):- agent.ability_manager.remove(tool.card.name)-- Runner.resource_mgr.add_tool(list(tools))- for tool in tools:- agent.ability_manager.add(tool.card)+ agent.ability_manager.add_ability(tool.card, tool)self._tools = toolslogger.info("[MemberSkillToolkitRail] Registered %d skill tools for workspace=%s agent_id=%s",len(tools),self._workspace_dir,- agent_id,+ str(agent.card.id or agent.card.name),)def uninit(self, agent: "DeepAgent") -> None:@@ -75,8 +68,7 @@ class MemberSkillToolkitRail(DeepAgentRail):returnfor tool in self._tools:- agent.ability_manager.remove(tool.card.name)- Runner.resource_mgr.remove_tool(tool.card.id)+ agent.ability_manager.remove_ability(tool.card.name)logger.info("[MemberSkillToolkitRail] Unregistered %d skill tools for workspace=%s",@@ -85,10 +77,6 @@ class MemberSkillToolkitRail(DeepAgentRail):)self._tools = None- @staticmethod- def _qualify_tool_id(tool_id: str, agent_id: str) -> str:- return f"{tool_id}_{agent_id}"-def _wrap_skill_tools(self, tools: list[Tool]) -> list[Tool]:"""Refresh linked skill views after mutating skill operations."""if self._refresh_links is None:diff --git a/jiuwenswarm/agents/harness/team/remote_member_bootstrap.py b/jiuwenswarm/agents/harness/team/remote_member_bootstrap.pyindex d10a5e1205..a939a9358a 100644--- a/jiuwenswarm/agents/harness/team/remote_member_bootstrap.py+++ b/jiuwenswarm/agents/harness/team/remote_member_bootstrap.py@@ -429,6 +429,33 @@ def parse_remote_teammate_bootstrap_json(content: str) -> dict[str, Any] | None:return data+def _swarm_assembly_hint(team_agent: Any) -> dict[str, str]:+ """Extract provider-assembly hints (mode / project_dir) from a leader spec.++ Reads the serializable ``build_context_seed`` the swarm enrichment leaves on+ the spec, falling back to the live ``build_context``. Returns an empty dict+ when the team was built via the legacy customizer path, so the teammate+ keeps the legacy rebuild.+ """+ spec = getattr(team_agent, "spec", None)+ if spec is None:+ return {}+ seed = getattr(spec, "build_context_seed", None)+ if isinstance(seed, dict) and seed:+ mode = str(seed.get("mode") or "").strip()+ project_dir = str(seed.get("project_dir") or "").strip()+ else:+ build_context = getattr(spec, "build_context", None)+ mode = str(getattr(build_context, "mode", "") or "").strip()+ project_dir = str(getattr(build_context, "project_dir", "") or "").strip()+ hint: dict[str, str] = {}+ if mode:+ hint["mode"] = mode+ if project_dir:+ hint["project_dir"] = project_dir+ return hint++def build_bootstrap_envelope(team_agent: Any,*,@@ -450,7 +477,7 @@ def build_bootstrap_envelope(leader_member_name=str(leader_member_name or ""),)leader_direct_addr = _normalize_leader_direct_addr(messager.get("direct_addr"))- return {+ envelope = {"type": "jiuwen.remote_teammate_bootstrap","version": 1,"bootstrap_id": str(uuid.uuid4()),@@ -463,6 +490,10 @@ def build_bootstrap_envelope("messager": messager,"prompt": prompt or "",}+ # Carry provider-assembly hints so the remote teammate rebuilds with the+ # same request mode / project dir (empty dict for the legacy path).+ envelope.update(_swarm_assembly_hint(team_agent))+ return envelopedef build_team_destroy_envelope(@@ -1933,8 +1964,16 @@ async def _ensure_dynamic_member_execution_loop(channel_id: str = "default",leader_agent_id: str = "",leader_direct_addr: str = "",+ assembly_mode: str = "",+ assembly_project_dir: str = "",) -> tuple[bool, bool]:- """Best-effort bootstrap for teammate runtime loop after dynamic member takeover."""+ """Best-effort bootstrap for teammate runtime loop after dynamic member takeover.++ When ``assembly_mode`` is set (provider-based assembly), the auxiliary leader+ is rebuilt provider-style so the serialized spec carries provider declarations+ plus the ``build_context_seed`` that the teammate uses to reconstruct its+ build context — no customizer closure crosses the process boundary.+ """sid = str(session_id or "").strip()member = str(target_member or "").strip()if not sid or not member:@@ -1965,10 +2004,16 @@ async def _ensure_dynamic_member_execution_loop(return False, Falseteam_manager = get_team_manager(channel_id)+ request_metadata: dict[str, Any] | None = None+ if assembly_mode:+ request_metadata = {"mode": assembly_mode}+ if assembly_project_dir:+ request_metadata["project_dir"] = assembly_project_dirleader_team_agent = await team_manager.get_or_create_team(sid,deep_agent,channel_id=channel_id,+ request_metadata=request_metadata,)helper_token = set_session_id(sid)try:@@ -2156,6 +2201,10 @@ async def _apply_bootstrap_envelope_from_control_plane(return adopted_memberleader_agent_id = str(envelope.get("leader_agent_id", "")).strip()leader_direct_addr = str(envelope.get("leader_direct_addr", "")).strip()+ # Provider-assembly hints (empty for the legacy customizer path) so the+ # teammate's auxiliary leader is rebuilt provider-style with the same mode.+ assembly_mode = str(envelope.get("mode", "")).strip()+ assembly_project_dir = str(envelope.get("project_dir", "")).strip()effective_sid = envelope_session_idloop_key = (effective_sid, target_member)@@ -2184,6 +2233,8 @@ async def _apply_bootstrap_envelope_from_control_plane(channel_id="default",leader_agent_id=leader_agent_id,leader_direct_addr=leader_direct_addr,+ assembly_mode=assembly_mode,+ assembly_project_dir=assembly_project_dir,)if kicked:logger.info(diff --git a/jiuwenswarm/agents/harness/team/team_manager.py b/jiuwenswarm/agents/harness/team/team_manager.pyindex 4479945770..47b081c387 100644--- a/jiuwenswarm/agents/harness/team/team_manager.py+++ b/jiuwenswarm/agents/harness/team/team_manager.py@@ -10,14 +10,12 @@ import loggingimport refrom dataclasses import dataclassfrom pathlib import Path-from types import SimpleNamespace-from typing import Any, Callable+from typing import Anyfrom openjiuwen.agent_teams.agent.team_agent import TeamAgentfrom openjiuwen.agent_teams.paths import team_homefrom openjiuwen.agent_teams.schema.blueprint import TeamAgentSpecfrom openjiuwen.agent_teams.context import reset_session_id, set_session_id-from openjiuwen.agent_evolving.trajectory import InMemoryTrajectoryRegistryfrom openjiuwen.core.runner import Runnerfrom openjiuwen.harness import DeepAgentfrom openjiuwen.harness.rails import (@@ -25,15 +23,6 @@ from openjiuwen.harness.rails import (TeamSkillCreateRail,TeamSkillEvolutionRail,)-from jiuwenswarm.agents.harness.common.plugins.rail_manager import get_rail_manager-from jiuwenswarm.agents.harness.team.rails.team_member_skill_toolkit_rail import (- MemberSkillToolkitRail,-)-from jiuwenswarm.agents.harness.team.rails.team_shared_skill_link_refresh_rail import (- TeamSharedSkillLinkRefreshRail,-)-from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager-from jiuwenswarm.agents.harness.team.bootstrap import configure_agent_teams_homeconfigure_agent_teams_home()@@ -58,27 +47,17 @@ from jiuwenswarm.agents.harness.team.distributed_runtime import ()from jiuwenswarm.agents.harness.team.monitor_handler import TeamMonitorHandlerfrom jiuwenswarm.agents.harness.team.remote_member_bootstrap import release_a2x_reservations_for_session-from jiuwenswarm.agents.harness.team.team_skill_links import (- is_valid_skill_dir,- link_skill_dir,- path_exists_or_link,- prune_skill_dir_links,- remove_skill_dir_link,- sync_skill_dir_links,-)+from jiuwenswarm.agents.harness.team.team_skill_links import sync_skill_dir_linksfrom jiuwenswarm.common.config import get_config, get_default_modelsfrom jiuwenswarm.agents.harness.team.team_runtime_inheritance import (MemberInfo,- RAIL_WHITELIST,RuntimeInfo,TeamWorkspaceInfo,get_evolution_auto_scan_enabled,get_skill_create_enabled,build_member_rails,- filter_inheritable_ability_cards,- get_default_model_name,)-from jiuwenswarm.common.utils import get_agent_skills_dir, get_agent_workspace_dir+from jiuwenswarm.common.utils import get_agent_skills_dirfrom jiuwenswarm.server.runtime.session.session_metadata import get_session_metadatalogger = logging.getLogger(__name__)@@ -337,29 +316,47 @@ class TeamManager:return TeamAgentSpec.model_validate(spec_dict)- async def get_enriched_team_spec(++ async def get_swarm_enriched_team_spec(self,session_id: str,- deep_agent: DeepAgent,+ *,+ mode: str,+ project_dir: str | None = None,request_id: str | None = None,channel_id: str | None = None,request_metadata: dict[str, Any] | None = None,) -> TeamAgentSpec:+ """Build a team spec via provider-based assembly (no parent DeepAgent).++ Sources every member capability from the shared config source through+ ``enrich_team_spec_for_swarm`` instead of inheriting from a pre-built+ single agent, so creating a team never requires constructing one first.++ Args:+ session_id: Active session id.+ mode: Request mode (e.g. "team").+ project_dir: Resolved project directory, if any.+ request_id: Originating request id, if any.+ channel_id: Raw channel id from the request, if any.+ request_metadata: Request metadata mapping.++ Returns:+ The enriched ``TeamAgentSpec`` ready to build (``build_context`` set;+ assembly is fully declarative, no imperative post-processing).+ """+ from jiuwenswarm.agents.swarm import enrich_team_spec_for_swarm+config_base = get_config()await self._ensure_postgresql_for_leader(config_base)spec = self._load_team_spec(session_id)- self._apply_session_scoped_team_name(+ self._apply_session_scoped_team_name(spec, session_id=session_id)+ self.apply_team_plan_mode(spec, request_metadata=request_metadata)+ enrich_team_spec_for_swarm(spec,session_id=session_id,- )- self.apply_team_plan_mode(- spec,- request_metadata=request_metadata,- )- spec.agent_customizer = self.build_agent_customizer(- spec,- deep_agent,- session_id,+ mode=mode,+ project_dir=project_dir,request_id=request_id,channel_id=channel_id,request_metadata=request_metadata,@@ -466,427 +463,6 @@ class TeamManager:)return None- @staticmethod- def register_member_runtime_tools(- agent: DeepAgent,- *,- session_id: str,- request_id: str | None,- channel_id: str | None,- request_metadata: dict[str, Any] | None,- ) -> None:- from jiuwenswarm.agents.harness.common.tools.cron.cron_runtime import CronRuntimeBridge- from jiuwenswarm.agents.harness.common.tools.send_file_to_user import SendFileToolkit-- agent_id = getattr(getattr(agent, "card", None), "id", None)- cron_runtime = CronRuntimeBridge()- cron_context = SimpleNamespace(- tool_scope=f"team_member_{agent_id or 'unknown'}",- channel_id=channel_id or "web",- session_id=session_id,- metadata=request_metadata,- mode="team",- )-- try:- cron_tools = cron_runtime.build_tools(- context=cron_context,- agent_id=agent_id,- language=getattr(agent.deep_config, "language", "cn")- )- for cron_tool in cron_tools:- if not Runner.resource_mgr.get_tool(cron_tool.card.id):- Runner.resource_mgr.add_tool(cron_tool)- agent.ability_manager.add(cron_tool.card)- logger.info("[TeamManager] Registered %d cron tools for member agent=%s", len(cron_tools), agent_id)- except Exception as exc:- logger.warning("[TeamManager] cron tool registration failed for member agent=%s: %s", agent_id, exc)-- if not request_id or not channel_id:- logger.info("[TeamManager] SendFileToolkit skipped: missing request_id or channel_id")- return-- try:- config = get_config()- send_file_enabled = (- config.get("channels", {})- .get(str(channel_id), {})- .get("send_file_allowed")- )- # web channel defaults to True, others default to False- if send_file_enabled is None:- send_file_enabled = (channel_id == "web")- if not send_file_enabled:- logger.info(- "[TeamManager] SendFileToolkit skipped: send_file_allowed=False for channel=%s",- channel_id,- )- return-- for existing in list(agent.ability_manager.list() or []):- if getattr(existing, "name", "").startswith("send_file_to_user"):- agent.ability_manager.remove(existing.name)-- send_file_toolkit = SendFileToolkit(- request_id=request_id,- session_id=session_id,- channel_id=channel_id,- metadata=request_metadata,- )- for sf_tool in send_file_toolkit.get_tools():- Runner.resource_mgr.add_tool(sf_tool)- agent.ability_manager.add(sf_tool.card)- logger.info("[TeamManager] SendFileToolkit registered for channel=%s", channel_id)- except Exception as exc:- logger.warning("[TeamManager] SendFileToolkit registration failed: %s", exc)-- @staticmethod- def build_agent_customizer(- spec: TeamAgentSpec,- deep_agent: DeepAgent,- session_id: str,- *,- request_id: str | None = None,- channel_id: str | None = None,- request_metadata: dict[str, Any] | None = None,- ) -> Callable[..., None]:- global_skills_dir = get_agent_skills_dir()- resolved_channel = channel_id or "default"- resolved_model_name = get_default_model_name()-- # Resolve team shared workspace skills directory for TeamSkillEvolutionRail.- ws_config = spec.workspace- team_ws_root = (- ws_config.root_path if ws_config and ws_config.root_path- else str(team_home(spec.team_name) / "team-workspace")- )- team_ws_skills_dir = Path(team_ws_root) / "skills"- team_trajectory_registry = InMemoryTrajectoryRegistry()-- def resolve_member_spec(- member_name: str | None,- role: str | None,- ) -> Any:- if member_name and member_name in spec.agents:- return spec.agents[member_name]- if role and role in spec.agents:- return spec.agents[role]- return spec.agents.get("leader")-- def resolve_member_skills(- member_name: str | None,- role: str | None,- ) -> tuple[bool, list[str]]:- member_spec = resolve_member_spec(member_name, role)- if member_spec is None or not hasattr(member_spec, "skills"):- return False, []-- skills = getattr(member_spec, "skills", None)- if skills is None:- return False, []-- return True, [str(skill).strip() for skill in skills if str(skill).strip()]-- def link_member_configured_skills(- member_skills_dir: Path,- selected_skills: list[str],- ) -> None:- """Synchronize member-configured skills into the member's skills directory."""- if not global_skills_dir.exists():- logger.warning("[TeamManager] global_skills_dir does not exist: %s", global_skills_dir)- return-- selected_skill_set = set(selected_skills)- member_skills_dir.mkdir(parents=True, exist_ok=True)- prune_skill_dir_links(global_skills_dir, member_skills_dir, selected_skill_set)- linked_count = 0- for skill_dir in global_skills_dir.iterdir():- if not is_valid_skill_dir(skill_dir):- continue- if skill_dir.name not in selected_skill_set:- continue- dest = member_skills_dir / skill_dir.name- if path_exists_or_link(dest):- continue- link_skill_dir(skill_dir, dest)- linked_count += 1- logger.info("[TeamManager] Linked skill '%s' to member workspace", skill_dir.name)-- existing_skill_names = {- path.name for path in member_skills_dir.iterdir() if path_exists_or_link(path)- }- missing = sorted(selected_skill_set - existing_skill_names)- if missing:- logger.warning("[TeamManager] configured skills not found in global dir: %s", missing)-- logger.info("[TeamManager] Total configured skills linked to member: %d", linked_count)-- def extract_skill_name_from_tool_result(result: dict[str, object]) -> str:- """Extract a skill name from a skill tool result."""- skill = result.get("skill")- if isinstance(skill, dict):- skill_name = str(skill.get("name", "")).strip()- if skill_name:- return skill_name- return str(result.get("skill_name", "") or result.get("name", "")).strip()-- def customizer(- agent: DeepAgent,- member_name: str | None = None,- role: str | None = None,- ) -> None:- logger.info(- "[TeamManager] customizer called: channel=%s member_name=%s role=%s",- resolved_channel,- member_name,- role,- )- member_deep_config = getattr(agent, "deep_config", None)- agent_ws = (- getattr(member_deep_config, "workspace", None)- if member_deep_config- else None- )- if agent_ws:- logger.debug(- "[TeamManager] member workspace.root_path=%s",- getattr(agent_ws, "root_path", None),- )- else:- logger.warning("[TeamManager] agent deep_config.workspace is None")- parent_adapter_mode = str(- getattr(deep_agent, "_jiuwenswarm_adapter_mode", "") or ""- ).lower()- parent_deep_config = getattr(deep_agent, "deep_config", None)- parent_workspace = (- getattr(parent_deep_config, "workspace", None)- if parent_deep_config- else None- )- parent_project_dir = (- str(getattr(deep_agent, "_jiuwenswarm_project_dir", "") or "")- or str(getattr(deep_agent, "_jiuwenswarm_code_project_dir", "") or "")- or (- str(getattr(parent_workspace, "root_path", ""))- if parent_workspace and getattr(parent_workspace, "root_path", None)- else ""- )- )- if parent_project_dir and member_deep_config is not None:- setattr(agent, "_jiuwenswarm_project_dir", parent_project_dir)-- inheritable_cards = filter_inheritable_ability_cards(deep_agent)- existing_ability_ids = {card.id for card in agent.ability_manager.list() or []}- added_count = 0- for card in inheritable_cards:- if card.id not in existing_ability_ids:- agent.ability_manager.add(card)- existing_ability_ids.add(card.id)- added_count += 1- else:- logger.debug("[TeamManager] Ability '%s' already exists, skipped", card.name)- logger.info(- "[TeamManager] Added %d inheritable abilities (total: %d)",- added_count,- len(existing_ability_ids),- )-- member_workspace = agent_ws- member_workspace_root = getattr(member_workspace, "root_path", None)- member_skill_manager: Any | None = None- if member_workspace and member_workspace_root:- agent_workspace_dir = get_agent_workspace_dir()- member_skills_dir = Path(member_workspace_root) / "skills"- skills_configured, selected_skills = resolve_member_skills(member_name, role)-- def refresh_member_skill_links(result: dict[str, object]) -> None:- """Refresh linked skill views after a member skill tool mutation."""- if result.get("skill_removed") or result.get("removed"):- skill_name = extract_skill_name_from_tool_result(result)- if skill_name:- remove_skill_dir_link(member_skills_dir / skill_name)- get_team_manager(resolved_channel).refresh_team_shared_skill_links(session_id)- return- get_team_manager(resolved_channel).refresh_team_shared_skill_links(session_id)-- # Link member-configured skills so the member workspace exposes- # only that member's skill view.- try:- member_skills_dir.mkdir(parents=True, exist_ok=True)- if skills_configured and selected_skills:- link_member_configured_skills(member_skills_dir, selected_skills)- except Exception as exc:- logger.warning("[TeamManager] skill link refresh failed: %s", exc)-- try:- member_skill_manager = SkillManager(workspace_dir=str(agent_workspace_dir))- except Exception as exc:- logger.warning("[TeamManager] member SkillManager setup failed: %s", exc)-- # Create shared SkillManager and SkillToolkit for member installs.- try:- agent.add_rail(- MemberSkillToolkitRail(- workspace_dir=str(agent_workspace_dir),- manager=member_skill_manager,- refresh_links=refresh_member_skill_links,- )- )- logger.info(- "[TeamManager] MemberSkillToolkitRail queued for skill workspace: %s",- agent_workspace_dir,- )- except Exception as exc:- logger.warning("[TeamManager] MemberSkillToolkitRail setup failed: %s", exc)-- if parent_adapter_mode == "code":- try:- from jiuwenswarm.server.runtime.agent_adapter.interface_code import (- configure_code_team_member_agent,- )-- request_mode = str((request_metadata or {}).get("mode") or "").strip().lower()- role_name = str(getattr(role, "value", role) or "").strip().lower()- team_plan_enabled = (- request_mode == "team.plan"- or bool(getattr(spec, "enable_team_plan", False))- )- is_team_plan_leader = team_plan_enabled and role_name == "leader"- team_plan_runtime_language = None- if is_team_plan_leader:- config_language = str(- getattr(spec, "language", None)- or get_config().get("preferred_language", "zh")- )- team_plan_runtime_language = config_language-- configure_code_team_member_agent(- agent,- parent_agent=deep_agent,- skill_manager=member_skill_manager,- member_name=member_name,- role=role,- session_id=session_id,- channel_id=resolved_channel,- project_dir=parent_project_dir or None,- runtime_language=team_plan_runtime_language,- force_english_runtime_prompt=not is_team_plan_leader,- )- except Exception as exc:- logger.warning(- "[TeamManager] code team member adapter setup failed: member=%s role=%s error=%s",- member_name,- role,- exc,- )-- # Build all member rails (common + skill rails via role).- team_workspace = TeamWorkspaceInfo(- root_dir=str(Path(team_ws_root)),- skills_dir=str(global_skills_dir),- team_id=spec.team_name,- config=get_config(),- trajectory_registry=team_trajectory_registry,- )- team_manager = get_team_manager(resolved_channel)- team_manager.register_team_shared_skill_link_target(- session_id,- team_ws_skills_dir,- )-- def refresh_team_shared_skill_links() -> None:- """Refresh this session's team shared skill links."""- team_manager.refresh_team_shared_skill_links(session_id)-- agent.add_rail(- TeamSharedSkillLinkRefreshRail(- global_skills_dir=global_skills_dir,- refresh_links=refresh_team_shared_skill_links,- )- )-- try:- member_rails = build_member_rails(- member_info=MemberInfo(- agent_name=getattr(agent.card, "name", "team_member"),- model_name=resolved_model_name,- role=role- ),- runtime=RuntimeInfo(channel=resolved_channel),- team_workspace=team_workspace,- )- team_skill_rail: Any | None = None- team_skill_create_rail: Any | None = None- for rail in member_rails:- if type(rail).__name__ in RAIL_WHITELIST:- agent.add_rail(rail)- if isinstance(rail, (TeamSkillEvolutionRail, TeamSkillCreateRail)):- get_team_manager(resolved_channel).register_team_live_rail(- session_id,- agent,- rail,- )- else:- logger.debug("[TeamManager] Skipping non-whitelisted rail: %s", type(rail).__name__)- if isinstance(rail, TeamSkillEvolutionRail):- team_skill_rail = rail- elif isinstance(rail, SkillEvolutionRail):- get_team_manager(resolved_channel).register_team_member_skill_evolution_rail(- session_id,- rail,- )- elif isinstance(rail, TeamSkillCreateRail):- team_skill_create_rail = rail- logger.info("[TeamManager] Added %d rails for team member", len(member_rails))- # Register TeamSkillEvolutionRail with TeamManager for approval.- if team_skill_rail is not None:- tm = get_team_manager(resolved_channel)- tm.register_team_skill_rail(session_id, team_skill_rail)- logger.info(- "[TeamManager] TeamSkillEvolutionRail mounted on leader (skills_dir=%s)",- team_ws_skills_dir,- )- if team_skill_create_rail is not None:- get_team_manager(resolved_channel).register_team_skill_create_rail(- session_id,- team_skill_create_rail,- )- if role == "leader":- get_team_manager(resolved_channel).register_team_rail_context(- session_id,- TeamRailMountContext(- agent=agent,- member_info=MemberInfo(- agent_name=getattr(agent.card, "name", "team_member"),- model_name=resolved_model_name,- role=role,- ),- runtime=RuntimeInfo(channel=resolved_channel),- team_workspace=team_workspace,- ),- )- except Exception as exc:- logger.warning("[TeamManager] build_member_rails failed: %s", exc)-- rail_manager = get_rail_manager()- for rail_name in rail_manager.get_registered_rail_names():- try:- rail_instance = rail_manager.load_rail_instance_without_enabled_check(rail_name)- if rail_instance is not None:- agent.add_rail(rail_instance)- logger.info("[TeamManager] Added extension rail: %s", rail_name)- except Exception as exc:- logger.warning("[TeamManager] add rail %s failed: %s", rail_name, exc)-- TeamManager.register_member_runtime_tools(- agent,- session_id=session_id,- request_id=request_id,- channel_id=channel_id,- request_metadata=request_metadata,- )-- return customizer@staticmethoddef _is_postgresql_storage(team_cfg: dict[str, Any]) -> bool:@@ -994,10 +570,20 @@ class TeamManager:session_id=session_id,)- spec.agent_customizer = self.build_agent_customizer(+ resolved_mode = str((request_metadata or {}).get("mode") or "").strip()+ # Provider-based assembly: source every member capability from the shared+ # config source, no pre-built parent DeepAgent / customizer. Mirrors+ # get_swarm_enriched_team_spec so a team rebuilt here (e.g. the distributed+ # teammate's auxiliary leader) carries provider declarations plus the+ # serializable build_context_seed.+ from jiuwenswarm.agents.swarm import enrich_team_spec_for_swarm++ self.apply_team_plan_mode(spec, request_metadata=request_metadata)+ enrich_team_spec_for_swarm(spec,- deep_agent,- session_id,+ session_id=session_id,+ mode=resolved_mode,+ project_dir=(request_metadata or {}).get("project_dir"),request_id=request_id,channel_id=channel_id,request_metadata=request_metadata,diff --git a/jiuwenswarm/agents/swarm/DESIGN.md b/jiuwenswarm/agents/swarm/DESIGN.mdnew file mode 100644index 0000000000..c5561f6f29--- /dev/null+++ b/jiuwenswarm/agents/swarm/DESIGN.md@@ -0,0 +1,403 @@+# Swarm Spec 装配设计文档++> 模块路径:`jiuwenswarm/agents/swarm/`+> 范围:team 成员(leader / teammate)的 harness(rail / tool / sub-agent)**纯声明式装配**——从 config 源派生 spec,经 openjiuwen 构造为运行对象,并提供可序列化的自描述 manifest。++---++## 0. 一句话总览++一个 team 成员的能力 = 一组**声明式 spec**(`RailSpec` / `BuiltinToolSpec` / `SubAgentSpec`)→ openjiuwen 按 `type` / `factory_name` 解析到 **swarm provider 工厂** → 工厂用 **ConstructionInput** 从 `params`(属性)+ `SwarmBuildContext`(环境)提取构造参数 → 产出运行对象。所有元素另有一份**可序列化 descriptor**(manifest catalog),用于注册、内省与未来配置文件装配。++> **框架分层**:manifest 这套「descriptor + catalog + ConstructionInput + 反射 + catalog 驱动注册」是 harness 通用基础设施,已**下沉到 openjiuwen**(`openjiuwen.agent_teams.harness.manifest`)。swarm 只保留:① 各 provider 的元素**声明**(`@harness_element`);② `SwarmBuildContext` 与 `config_specs` 烘焙;③ 对框架的**注册编排**(`registry.py` 调 `register_from_catalog` + `register_build_context_factory`)。++设计三原则(见 `memory`):+1. **纯声明式装配**:能力声明为 config 源 provider spec,禁止 customizer / `rail.init` 后处理挂载。+2. **成员共享 config 源**:不从预构造父 DeepAgent 二次继承;创建 team 不必先造单 agent。+3. **跨序列化边界靠 seed 重建**:成员 spawn / 分布式 / 热恢复经 `build_context_seed` + 注册工厂重建上下文。++---++## 1. 分层架构++```+请求 (mode, role, channel, session, project_dir, config.yaml)+ │+ ▼+ enrich_team_spec_for_swarm() assembly.py+ │ ① register_swarm_providers() ② 建 SwarmBuildContext ③ 改写成员 spec ④ 挂 build_context + seed+ ▼+ TeamAgentSpec (openjiuwen schema)+ ├─ agents["leader"] : DeepAgentSpec+ └─ agents["teammate"] : DeepAgentSpec+ ├─ rails : list[RailSpec] config_specs.py 折叠 + 属性烘焙进 params+ ├─ tools : list[BuiltinToolSpec]+ └─ subagents: list[SubAgentSpec]+ │+ ▼ spec.build(context=SwarmBuildContext) openjiuwen 解析 type/factory_name+ swarm provider 工厂 build_xxx(params, ctx) providers/*.py+ │ inp = XxxInput.resolve(params, ctx) openjiuwen harness/manifest+ ▼+ 运行对象 (Rail / Tool / SubAgentConfig)+```++四个职责面:++| 面 | 文件 | 职责 |+|---|---|---|+| **声明 + 装配** | `assembly.py`、`config_specs.py` | 从 config 派生成员 spec;把 config 派生**属性烘焙进 `params`** |+| **构造** | `providers/*.py` + openjiuwen `harness/manifest`(框架) | provider 工厂声明 + `ConstructionInput` 从 params+context 提取并构造对象 |+| **运行载体** | `context.py` | `SwarmBuildContext`:构造期的环境句柄 |+| **自描述** | openjiuwen `harness/manifest`(框架)+ `providers/*.py` 声明 + `registry.py` 注册编排 | 可序列化 descriptor + catalog 驱动注册 + 内省 |++---++## 2. openjiuwen Spec 与注册底座(依赖,不在本模块)++安装位置:`/Users/alan/Developer/alan_workspace/agent-core/openjiuwen/agent_teams/schema/`。++### 2.1 Spec 模型(pydantic,可 JSON round-trip)++| Spec | 关键字段 | `.build()` 解析 |+|---|---|---|+| `RailSpec` | `type: str`、`params: dict` | 只走 provider(`_RAIL_PROVIDER_REGISTRY[type]`),未命中抛 `ValueError`(openjiuwen 已删 class 注册表) |+| `BuiltinToolSpec` | `type: str`、`params: dict` | 同上(`_TOOL_PROVIDER_REGISTRY`) |+| `SubAgentSpec` | `agent_card`、`system_prompt`、`factory_name`、`factory_kwargs: dict`、… | `factory_name` 命中 `_SUBAGENT_PROVIDER_REGISTRY` 时走 provider |+| `DeepAgentSpec` | `rails` / `tools` / `subagents` / `system_prompt` / `model` / … | 逐元素 `.build()` 装配成 `DeepAgent` |+| `TeamAgentSpec` | `agents: dict[role, DeepAgentSpec]`、`team_name`、`build_context`、`build_context_seed` | team 机制构造各成员 |++### 2.2 注册表(纯 `dict[str, Callable]`,**无元数据**)++```python+_RAIL_PROVIDER_REGISTRY: dict[str, Callable] # register_rail_provider(name, factory)+_TOOL_PROVIDER_REGISTRY: dict[str, Callable] # register_tool_provider(name, factory)+_SUBAGENT_PROVIDER_REGISTRY: dict[str, Callable] # register_subagent_provider(name, factory)+```++工厂签名约定:+- rail / tool:`factory(params: dict, context: BuildContext) -> obj | list | None`+- subagent:`factory(factory_kwargs: dict, context: BuildContext) -> SubAgentConfig | None`++### 2.3 BuildContext 与 seed++`BuildContext` 是 **dataclass(非 pydantic)**——Spec→Runtime 边界对象,**不参与 JSON 序列化**。跨序列化边界(spawn / 分布式 / 冷恢复)通过:+- `register_build_context_factory(factory)`:平台注册「从 seed 重建 context」工厂;+- `TeamAgentSpec.build_context_seed`:spec 上携带可序列化 seed;+- 接收侧 `build_context_from_seed(seed)` 用本地句柄(config / registry)重建活 context。++---++## 3. SwarmBuildContext(环境载体)++`context.py` 的 `SwarmBuildContext(BuildContext)`,是构造期所有 provider 工厂拿到的第二个入参。**只承载 per-request / per-session / per-member 的运行时句柄**(环境值),不承载 harness 设定(那是 params)。++| 字段 | 类型 | 来源 | 进 seed? |+|---|---|---|---|+| `session_id` / `request_id` / `channel_id` / `channel` / `request_metadata` | str / dict | 请求 | ✅(除非句柄) |+| `mode` | str | 请求(team / code.team / team.plan) | ✅ |+| `project_dir` | str\|None | 请求 | ✅ |+| `team_id` / `team_ws_root` / `team_skills_dir` / `global_skills_dir` | str | team 工作区 | ✅ |+| `config` | dict | `get_config()`(config.yaml) | ❌(接收侧本地 `get_config()`) |+| `trajectory_registry` | Any | 进程内 per-team registry | ❌(接收侧本地重建) |+| `language` / `member_name` / `role` / `workspace` / `member_card_id` | — | openjiuwen `setup_agent` 经 `derive()` 注入 | per-member 派生 |+| `extras` | dict | 进程内 side-channel | 运行时句柄(如 `_parent_model` / `_coding_memory_rail`) |++- `to_seed()` / `from_seed(seed, *, config, trajectory_registry)`:序列化只导出原语,`config` / `trajectory_registry` 由接收侧本地注入。+- **`config` 例外说明**:`config` 虽挂在 context 上,但它是 *harness 设定的源*(属性),不是 per-request 环境值。本模块刻意**不让 provider 工厂直接读 `ctx.config` 派生构造参数**——那些属性由 `config_specs` 烘焙进 `params`(见 §6、§7)。`ctx.config` 仅保留给基础设施级用途(如 evolution 热重载 `bind_swarm_context(config=ctx.config)`)。++---++## 4. providers/:能力工厂++`providers/` 下按域分文件,每个文件声明若干 `swarm.*` 名称常量 + `build_*` 工厂 + `@harness_element` 装饰;类 rail 集中在 `providers/builtin_rails.py`。++| 文件 | 元素 |+|---|---|+| `tools.py` | base_tools、code_extra_tools |+| `runtime_tools.py` | cron_tools、send_file |+| `skills.py` | member_skill_toolkit |+| `member_rails.py` | runtime_prompt、team_workspace_report_path、context_processor、plugin_rails |+| `evolution_rails.py` | team_skill_evolution、team_skill_create、member_skill_evolution |+| `code_rails.py` | 10 个 `swarm.code_*` rail(lsp / confirm_interrupt / worktree 已下沉 openjiuwen) |+| `code_subagents.py` | code agent(explore / plan / browser 已下沉 openjiuwen) |+| `builtin_rails.py` | 3 个 swarm 自有无参类 rail(response_prompt / stream_event / avatar_prompt) |++工厂体范式(保留 `(params, ctx)` 签名,openjiuwen 契约不变):++```python+@harness_element(kind=ElementKind.RAIL, name=STRUCTURED_ASK_USER, description="...",+ input_model=StructuredAskUserInput)+def build_structured_ask_user(params: dict[str, Any], ctx: SwarmBuildContext) -> Any:+ inp = StructuredAskUserInput.resolve(params, ctx) # 从 params+context 提取并校验+ return StructuredAskUserRail(language=inp.language)+```++---++## 5. ConstructionInput(构造输入框架)++框架在 `openjiuwen.agent_teams.harness.manifest`(`inputs` 子模块)。每个元素在 swarm `providers/*.py` 声明一份 `ConstructionInput` 子类,**逐字段标注来源**,`resolve` 在构造期从 `params` + `context` 提取并 pydantic 校验。++```python+class InputSource(str, Enum):+ PARAMS = "params" # harness 设定属性(config_specs 烘焙进 RailSpec.params)+ CONTEXT = "context" # per-request 运行时环境(SwarmBuildContext 字段 / 派生)++def param_field(*, default=..., default_factory=None, description=""): ...+def context_field(*, attr=None, resolver=None, default=None, description=""): ...++class ConstructionInput(BaseModel):+ @classmethod+ def resolve(cls, params, context) -> Self:+ # 逐字段:source=params → params[name](缺省走默认)+ # source=context → getattr(context, attr) 或 resolver(context)+ # None 结果丢弃以走字段默认,保留工厂对缺省句柄的容忍+```++- **来源元数据可序列化**:`context_field` 把 `source` + `context_attr` / `resolver_ref`(entry-point 点路径)写进 `Field(json_schema_extra=...)`;`resolver_ref` 由 `factory_ref(resolver)` 计算,可经 `resolve_factory` 反射还原 → 整个 `input_schema` 跨进程可述。+- **不进 schema 的输入**:`ctx.extras` 运行时句柄(parent_model / coding_memory)、全局(skill 目录 / 禁用技能 / rail manager)、env(API key / BROWSER_DRIVER)——属运行时 / 部署 plumbing,工厂直读,不建模。++---++## 6. param vs context 边界(核心心智模型)++> 这是本模块最重要的概念约定。++| 类别 | 判据 | 去向 | 谁填 |+|---|---|---|---|+| **属性值** | 是 config.yaml 里的 harness 设定吗?换请求不变 | `params`(`param_field`) | `config_specs` 在 spec-build 期烘焙 |+| **环境值** | 随请求 / 会话 / 成员动态变化吗? | `context`(`context_field`) | 运行时由 `SwarmBuildContext` 注入 |+| **基础设施/句柄** | 既非设定也非构造参数(extras / 全局 / env) | 不建模 | 工厂直读 ctx / 全局 / env |++**关键洞察**:`ctx.config` 是「伪装成环境的属性源」。所有 config 派生的构造参数(`skill_mode` / `model_name` / `auto_scan` / `permissions` / `embed` 等)**本质是属性**,统一由 `config_specs` 读 config → 投射进 `RailSpec.params`(与既有 `skills` / `tool_names` / `max_iterations` 同一套机制),provider 工厂只从 `params` 读,**不再在构造期读 `ctx.config` 派生**。++收益:`RailSpec.params` 自洽且可序列化地描述元素的**全部设定**;`SwarmBuildContext` 保持纯环境;为「配置文件 → harness」loader 打好基础(文件即 params)。++---++## 7. config_specs.py:声明 + 属性烘焙++### 7.1 模式 / 角色 → 元素集合++```python+_CODE_MODES = {"code.team", "team.plan"}+_COMMON_RAIL_NAMES / _COMMON_TOOL_NAMES # team 档+_CODE_RAIL_NAMES / _CODE_SHARED_RAIL_NAMES / _CODE_TOOL_NAMES # code 档+_role_evolution_rails(config, role) # leader: 进化+创建;teammate: 成员进化+```++`build_member_capability_specs(config, mode, role) -> (rails, tools)` 按 mode 分档;`build_member_subagent_specs` 仅 code 档(explore/plan 常驻,code/browser 受 `react.subagents.<name>.enabled` 门控);`build_member_deep_agent_spec` 把能力 spec 折叠到 base `DeepAgentSpec`。++### 7.2 属性烘焙(本模块核心机制)++参数化元素显式构造 `RailSpec(type=name, params=...)`;其余经分派注入:++```python+_RAIL_PARAM_BUILDERS: dict[name, (config) -> params] # context_processor / code_project_memory /+ # permission_interrupt / code_coding_memory /+ # user_hooks / code_skill_use+_TOOL_PARAM_BUILDERS: dict[name, (config) -> params] # send_file / code_extra_tools++[RailSpec(type=name, params=_rail_params(name, config)) for name in _CODE_RAIL_NAMES]+```++`_extract_*` helper 复用既有底层函数(不重写逻辑):++| param 字段(元素) | 抽取来源 |+|---|---|+| `skill_mode`(code_skill_use) | `react.skill_mode` 校验(`SkillUseRail.SKILL_MODE_*`) |+| `additional_directories`(code_project_memory) | `react.project_memory` + env `JIUWENSWARM_ADDITIONAL_DIRECTORIES` |+| `permissions_config` + `model_name`(permission_interrupt) | `config.permissions` + `config.models.default…model_name` |+| `embed_config`(code_coding_memory) | `config.embed` |+| `hooks_section`(user_hooks) | `config.hooks` |+| `context_engine_enabled` + `context_engine_config`(context_processor) | `get_context_engine_enabled(config)` + `config.context_engine_config` |+| `acp_enabled`(code_extra_tools) | `config.acp_agents` 非空 |+| `channels_config`(send_file) | `config.channels` |+| `evolution_model_config` + `auto_scan`(evolution×2) | `resolve_model_config(config)`(序列化 dict)+ `get_evolution_auto_scan_enabled(config)` |+| `skill_create`(team_skill_create) | `get_skill_create_enabled(config)` |++> **evolution_llm**:`config_specs` 只烘焙*可序列化的模型配置*(`model_client_config` / `model_config_obj` / `model_name`)进 params;活的 LLM 句柄由工厂 `_build_evolution_llm_from(inp.evolution_model_config)` 在 **build 期**构造,**不进 schema**。++> **blob builder**(permission / coding_memory / context_processor)签名不动:`config_specs` 抽 config 子树进 params,工厂传子 dict(如 `build_permission_rail(config={"permissions": inp.permissions_config}, ...)`)。**零 legacy 回归面**。++> **env 烘焙**:env 派生位(`EVOLUTION_AUTO_SCAN` / `JIUWENSWARM_ADDITIONAL_DIRECTORIES` 等)在 enrich 期一并解析烘焙,随 spec 序列化——与既有 params 一致(团队级配置)。++---++## 8. assembly.py:enrich 流程++`enrich_team_spec_for_swarm(spec, *, session_id, mode, project_dir, request_id, channel_id, request_metadata)`(就地改写 `spec`):++1. `register_swarm_providers()`(幂等,把 manifest catalog 驱动注册进 openjiuwen 注册表);+2. 用 `get_config()` + 工作区路径 + `InMemoryTrajectoryRegistry` 建 per-team `SwarmBuildContext`;+3. 对 `leader` / `teammate` 调 `build_member_deep_agent_spec`,把能力 spec(含烘焙好的 params)折叠到成员 `DeepAgentSpec`;+4. `spec.build_context = base`;`spec.build_context_seed = base.to_seed()`(跨边界重建)。++---++## 9. manifest:自描述 descriptor catalog(框架在 openjiuwen)++> 本节描述的 descriptor / catalog / 反射 / 注册驱动均为通用框架,位于 `openjiuwen.agent_teams.harness.manifest`。swarm 通过 `@harness_element` 声明元素、`registry.py` 驱动注册,不持有框架实现。++### 9.1 descriptor 模型(`harness/manifest/models.py`)++```python+class HarnessElementDescriptor(BaseModel):+ kind: ElementKind # tool / rail / subagent+ name: str # "swarm.*",即 spec 的 type / factory_name+ description: str+ factory_ref: str # "module:qualname",反射点路径+ input_schema: dict # ConstructionInput.model_json_schema(),每属性带 source 标记+ input_model_ref: str | None # 入参模型点路径,供未来 loader 校验+ interface_methods: list[InterfaceMethod] # 构造对象对外接口方法 + 描述+```++`name` / `description` / `input_schema` 即「LLM tool 三件套」镜像(对照 `ToolCard`),扩展 `kind` / `factory_ref` / `interface_methods` 适配 harness。++### 9.2 单一声明入口 + catalog 驱动注册++```python+@harness_element(kind=..., name=..., description=..., input_model=...) # 装饰工厂+harness_element(kind=RAIL, name=..., builder=SomeRailClass) # 直接声明类 rail+```++- `harness_element` **纯元数据记录器**:算 `factory_ref`、取 `input_model.model_json_schema()`、按 kind 兜底 `interface_methods`,写入进程内 `_CATALOG`;**不做 openjiuwen 注册**。+- `register_from_catalog()`(被 `registry.register_swarm_providers` 调用)遍历 catalog,按 kind 分派到 `register_tool/rail/subagent_provider`。+- **rail 归一**:descriptor 层只有 `RAIL`(无 `RAIL_TYPE`)。类 rail 经 `class_rail_adapter(cls)` 包成 `(params, context) -> cls`(复刻 openjiuwen class 分支的 language 注入),统一走 `register_rail_provider`——彻底移除 swarm 侧 `register_rail_type`。++### 9.3 内省与反射++- `list_elements() -> list[dict]`:全量 descriptor 的 JSON 列表(内省 / 未来配置 UI / loader)。+- `resolve_factory("module:qualname")`:importlib 反射还原工厂 / 类 / resolver。+- round-trip:`HarnessElementDescriptor.model_validate_json(d.model_dump_json())` 还原后 `factory_ref` 在任何可 import 进程还原为同一可调用。++### 9.4 registry.py++`register_swarm_providers()`(幂等闸门 `_REGISTERED`)= import 各 provider 模块(触发 `@harness_element` 填 catalog)→ `register_from_catalog()` → `register_build_context_factory(_build_swarm_context_from_seed)`。re-export 全部 `swarm.*` 名称常量供 `config_specs` 按符号引用。++---++## 10. 元素全量清单(36)++> P=param(属性,config_specs 烘焙);C=context(环境,SwarmBuildContext);—=无输入。+> 模式:T=team,K=code(code.team/team.plan)。++### 10.1 Tool(8,swarm 自有)++| name | 模式 | P(属性) | C(环境) |+|---|---|---|---|+| `swarm.skill_toolkit` | T+K | — | workspace_root |+| `swarm.user_todos` | T+K | — | — |+| `swarm.video` | T+K | — | config(models.video 门控) |+| `swarm.image_gen` | T+K | — | config(IMAGE_GEN_API_KEY 门控) |+| `swarm.xiaoyi_phone` | T+K | — | config(channels.xiaoyi 门控) |+| `swarm.code_extra_tools` | K | acp_enabled | — |+| `swarm.cron_tools` | T+K | — | member_card_id, channel_id, session_id, request_metadata, language |+| `swarm.send_file` | T+K | channels_config | request_id, channel_id, session_id, request_metadata |++> 通用 web / vision / audio 工具由 openjiuwen 提供(见 10.5)。++### 10.2 Rail — 工厂(18)++| name | 模式/角色 | P(属性) | C(环境) |+|---|---|---|---|+| `swarm.member_skill_toolkit` | T+K | skills | workspace_root, global_skills_dir, team_skills_dir |+| `swarm.runtime_prompt` | T | — | language, channel |+| `swarm.team_workspace_report_path` | T+K | — | team_ws_root, team_id, language |+| `swarm.context_processor` | T+K | context_engine_enabled, context_engine_config | — |+| `swarm.plugin_rails` | T+K | — | —(全局 rail manager) |+| `swarm.team_skill_evolution` | T+K / leader | evolution_model_config, auto_scan | team_skills_dir, language, role, team_id, trajectory_registry, channel, session_id, team_ws_root, global_skills_dir |+| `swarm.team_skill_create` | T+K / leader | skill_create | team_skills_dir, language, channel, session_id, team_ws_root, team_id, trajectory_registry |+| `swarm.member_skill_evolution` | T+K / teammate | evolution_model_config, auto_scan | team_skills_dir, trajectory_registry, team_id, channel, session_id |+| `swarm.code_runtime_prompt` | K | — | language, channel |+| `swarm.code_project_memory` | K | additional_directories | project_dir, language |+| `swarm.permission_interrupt` | K | permissions_config, model_name | — |+| `swarm.code_coding_memory` | K | embed_config | project_dir, workspace_root(+ 写 ctx.extras) |+| `swarm.code_agent_mode` | K | — | — |+| `swarm.structured_ask_user` | K | — | language |+| `swarm.code_task_planning` | K | — | — |+| `swarm.code_agent_rail` | K | — | workspace_dir |+| `swarm.user_hooks` | K | hooks_section | — |+| `swarm.code_skill_use` | K | skill_mode | —(skills_dir/disabled 全局) |++### 10.3 Rail — 类(3,无输入,`EmptyInput`)++`response_prompt`(T+K)、`stream_event`(T+K)、`avatar_prompt`(T)。++### 10.4 Sub-agent(1,code)++| name | P(属性) | C(环境) | 句柄(ctx.extras) |+|---|---|---|---|+| `swarm.code_agent`(门控) | max_iterations | workspace_root, language | `_parent_model`, `_coding_memory_rail` |++### 10.5 openjiuwen 提供(按 `core.*` 名引用,不在 swarm catalog)++归一后这些元素由 openjiuwen 声明 + 注册,swarm 经 `config_specs` 按 `core.*` 名引用(params 由 swarm 烘焙):++- Rail:`core.sys_operation`、`core.task_planning`、`core.security`、`core.heartbeat`、`core.confirm_interrupt`(tool_names)、`core.worktree`(enabled)、`core.lsp`(project_dir)。+- Tool:`core.web_search`、`core.web_fetch`、`core.web_paid_search`、`core.vision`(vision_model_config)、`core.audio`(dedicated + audio_model_config)。vision/audio 的 config 由 swarm `tools.vision_model_config_params` / `audio_model_config_params` 从 yaml+env 填充后烘焙进 params。+- Sub-agent:`core.explore_agent`、`core.plan_agent`、`core.browser_agent`(language / max_iterations 为 params,model 取 `ctx.extras["_parent_model"]`)。++`registry.register_swarm_providers` 先调 `ensure_harness_elements_registered()` 确保上述 openjiuwen 元素已注册。++---++## 11. 端到端数据流(以 `code_skill_use` 为例)++```+config.yaml: react.skill_mode = "auto_list"+ │ enrich → config_specs._skill_mode(config) = "auto_list"+ ▼+RailSpec(type="swarm.code_skill_use", params={"skill_mode": "auto_list"}) # 属性烘焙+ │ (随 DeepAgentSpec 序列化 / 跨进程重建保留)+ ▼+RailSpec.build(language=..., context=SwarmBuildContext)+ │ openjiuwen: _RAIL_PROVIDER_REGISTRY["swarm.code_skill_use"](params, context)+ ▼+build_code_skill_use(params={"skill_mode": "auto_list"}, ctx)+ │ inp = CodeSkillUseInput.resolve(params, ctx) # skill_mode 来自 params+ ▼+SkillUseRail(skills_dir=get_agent_skills_dir(), skill_mode="auto_list", ...)+```++---++## 12. 序列化与跨进程重建++- `DeepAgentSpec` / `TeamAgentSpec` 全 pydantic,`model_dump_json()` / `model_validate_json()` 完整 round-trip;rails/tools 序列化为 `{type, params}`、subagents 为 `{factory_name, factory_kwargs, ...}`。+- 属性全在 `params`(含 `evolution_model_config` 等),跨边界自洽——重建侧无需再读 config 即可还原元素设定。+- 非序列化句柄(`config` / `trajectory_registry` / `extras`)经 `build_context_seed` + `register_build_context_factory` 在接收侧本地重建。++---++## 13. 如何新增一个 harness 元素++1. 在对应 `providers/*.py` 定义 `NAME = "swarm.xxx"` 常量并在 `registry.py` re-export。+2. 写 `XxxInput(ConstructionInput)`:属性用 `param_field`,环境用 `context_field(attr=... | resolver=...)`。+3. 写工厂 `build_xxx(params, ctx)`:首行 `inp = XxxInput.resolve(params, ctx)`,用 `inp.*` 构造;加 `@harness_element(kind=..., name=NAME, description=..., input_model=XxxInput)`。+4. 若有 config 派生属性:在 `config_specs.py` 加 `_extract_*` 并注册进 `_RAIL_PARAM_BUILDERS` / `_TOOL_PARAM_BUILDERS`(或在显式构造点注入 `params=`);并把该元素名加入对应模式的 `_*_NAMES`。+5. subagent:经 `_code_subagent_spec` + `register_subagent_provider`。+6. 测试:`tests/agents/swarm/test_manifest_catalog.py`(catalog parity / source 标记 / schema 校验)+ `test_swarm_assembly.py`(构造回归)。++---++## 14. 测试与不变量++`tests/agents/swarm/`:+- `test_manifest_catalog.py`:常量 ↔ descriptor parity、catalog ↔ openjiuwen 注册表 parity、`factory_ref` / `resolver_ref` 反射、`input_schema` 校验、source 分类(属性=params / 环境=context)、`config_specs` 烘焙 params、JSON round-trip、注册幂等、接口自省、kind 覆盖。+- `test_swarm_assembly.py`:enrich / 折叠 / 跨进程重建 / 各元素构造的**行为回归闸门**。++合规:huawei-python-lint 0 违规 + ruff check/format。++---++## 15. 后续工作(未实现)++| 项 | 说明 |+|---|---|+| **配置文件 → harness loader** | 读元素清单(name + params),用 `input_model_ref` 校验 params,映射成 `RailSpec`/`BuiltinToolSpec`/`SubAgentSpec` → `DeepAgentSpec`。`input_schema` 的 source 标记已能区分「作者填的 params」与「运行时注入的 context」。需先定:context 派生值是否允许 params 覆盖。 |+| **前端 Agent Configuration 接入** | 把 `list_elements()` 经 CLI/HTTP 暴露,按 source 标记渲染表单。 |+| **base_tools 多模态拆解** | 当前 base_tools 多模态 / xiaoyi / paid_search 因 config+env+`os.environ` mutation 纠缠保持现状;后续把 enabled 开关 + 模型名抽成 attribute params、api_key 留 env、去 `multimodal_config` 的 env-mutation 副作用。 |+| **builder 内部收窄** | permission / coding_memory / context_processor / evolution 的本地 builder 当前收原 config 子 dict(swarm 隔离);后续可收窄签名并迁移 legacy 调用方(interface_code / interface_deep / team_manager)。 |+| **interface_methods 精化** | 当前按 kind 自省基类契约;可按产出类精化(受惰性导入约束)。 |+| **上游 openjiuwen 对齐** | 把元数据 / 输入声明能力下沉到 openjiuwen 注册表。 |diff --git a/jiuwenswarm/agents/swarm/__init__.py b/jiuwenswarm/agents/swarm/__init__.pynew file mode 100644index 0000000000..8e26ec854b--- /dev/null+++ b/jiuwenswarm/agents/swarm/__init__.py@@ -0,0 +1,24 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Swarm provider-based team assembly package.++Importing this package registers all swarm capability providers and rail types+(idempotent) so a ``TeamAgentSpec`` can be enriched and built without inheriting+from a pre-built single agent. The public surface is the enrichment entry point+``enrich_team_spec_for_swarm`` plus the runtime build context+``SwarmBuildContext``.+"""++from __future__ import annotations++from jiuwenswarm.agents.swarm.assembly import enrich_team_spec_for_swarm+from jiuwenswarm.agents.swarm.context import SwarmBuildContext+from jiuwenswarm.agents.swarm.registry import register_swarm_providers++register_swarm_providers()++__all__ = [+ "enrich_team_spec_for_swarm",+ "SwarmBuildContext",+ "register_swarm_providers",+]diff --git a/jiuwenswarm/agents/swarm/assembly.py b/jiuwenswarm/agents/swarm/assembly.pynew file mode 100644index 0000000000..ba099b08ee--- /dev/null+++ b/jiuwenswarm/agents/swarm/assembly.py@@ -0,0 +1,116 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Swarm team-spec enrichment entry point.++``enrich_team_spec_for_swarm`` is the single seam between the platform and the+provider-based assembly. Given a ``TeamAgentSpec`` it:++* registers all swarm providers / rail types (idempotent),+* builds the per-team base :class:`SwarmBuildContext` carrying the live runtime+ handles every provider needs,+* rewrites each present member spec ("leader" / "teammate") with its+ config-sourced rails and tools, and+* attaches the base context to ``spec.build_context`` so openjiuwen's+ ``setup_agent`` derives a per-member view through ``derive()``.++It never receives or inspects a pre-built ``DeepAgent``: members are assembled+purely from the config source plus provider name references.+"""++from __future__ import annotations++import logging+from pathlib import Path+from typing import Any++from openjiuwen.agent_evolving.trajectory import InMemoryTrajectoryRegistry+from openjiuwen.agent_teams.paths import team_home++from jiuwenswarm.agents.swarm.config_specs import build_member_deep_agent_spec+from jiuwenswarm.agents.swarm.context import SwarmBuildContext+from jiuwenswarm.agents.swarm.registry import register_swarm_providers+from jiuwenswarm.common.config import get_config+from jiuwenswarm.common.utils import get_agent_skills_dir++logger = logging.getLogger(__name__)++# Member roles enriched in place, in deterministic order.+_MEMBER_ROLES: tuple[str, ...] = ("leader", "teammate")+++def enrich_team_spec_for_swarm(+ spec: Any,+ *,+ session_id: str,+ mode: str,+ project_dir: str | None = None,+ request_id: str | None = None,+ channel_id: str | None = None,+ request_metadata: dict[str, Any] | None = None,+) -> None:+ """Enrich *spec* in place for provider-based swarm assembly.++ Registers swarm providers, builds the per-team base context, rewrites the+ present member specs with their config-sourced capabilities, and attaches the+ base context to the spec. Modifies *spec* in place and returns nothing.++ Args:+ spec: The ``TeamAgentSpec`` to enrich (mutated in place).+ session_id: Active session id.+ mode: Request mode (e.g. "team").+ project_dir: Resolved project directory, if any.+ request_id: Originating request id, if any.+ channel_id: Raw channel id from the request, if any.+ request_metadata: Request metadata mapping (carries ``mode`` etc.).+ """+ register_swarm_providers()++ config = get_config()+ workspace = spec.workspace+ team_ws_root = (+ workspace.root_path+ if workspace and workspace.root_path+ else str(team_home(spec.team_name) / "team-workspace")+ )+ team_skills_dir = str(Path(team_ws_root) / "skills")+ global_skills_dir = str(get_agent_skills_dir())++ base = SwarmBuildContext(+ session_id=session_id,+ request_id=request_id,+ channel_id=channel_id,+ channel=channel_id or "default",+ request_metadata=request_metadata,+ mode=mode,+ project_dir=project_dir,+ team_id=spec.team_name,+ team_ws_root=team_ws_root,+ team_skills_dir=team_skills_dir,+ global_skills_dir=global_skills_dir,+ trajectory_registry=InMemoryTrajectoryRegistry(),+ config=config,+ )++ for role in _MEMBER_ROLES:+ if role in spec.agents:+ spec.agents[role] = build_member_deep_agent_spec(+ config,+ mode,+ role,+ spec.agents[role],+ )++ spec.build_context = base+ # Carry a serializable seed alongside the live context so members rebuilt+ # across a serialization boundary (spawned teammate, distributed remote,+ # cold recovery) can reconstruct the context via the registered factory.+ spec.build_context_seed = base.to_seed()+ logger.info(+ "[swarm.assembly] enriched team spec '%s' (roles=%s, session=%s)",+ spec.team_name,+ [role for role in _MEMBER_ROLES if role in spec.agents],+ session_id,+ )+++__all__ = ["enrich_team_spec_for_swarm"]diff --git a/jiuwenswarm/agents/swarm/config_specs.py b/jiuwenswarm/agents/swarm/config_specs.pynew file mode 100644index 0000000000..d57038b018--- /dev/null+++ b/jiuwenswarm/agents/swarm/config_specs.py@@ -0,0 +1,547 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Config-sourced capability specs for swarm team members.++This module is the rewritten "member capability" assembly: a member's rails,+tools and sub-agents are declared entirely as ``RailSpec`` / ``BuiltinToolSpec``+/ ``SubAgentSpec`` references to ``swarm.*`` providers, derived from the config+source and the member role. It deliberately depends on **no DeepAgent instance**+— only on the config mapping and the provider name constants re-exported by+:mod:`jiuwenswarm.agents.swarm.registry`.++``build_member_deep_agent_spec`` folds those specs onto a base ``DeepAgentSpec``+so openjiuwen builds the member from the merged spec. Two modes are supported:++* ``team`` — the chat team profile (common rails + base tools).+* ``code.team`` / ``team.plan`` — the code profile (``swarm.code_*`` rails, code+ sub-agents, code system prompt), all still purely declarative.+"""++from __future__ import annotations++import os+from typing import (+ Any,+ Callable,+)++from openjiuwen.agent_teams.schema.deep_agent_spec import (+ BuiltinToolSpec,+ DeepAgentSpec,+ RailSpec,+ SubAgentSpec,+)+from openjiuwen.core.single_agent import AgentCard+from openjiuwen.harness.prompts import resolve_language+from openjiuwen.harness.rails import SkillUseRail++from jiuwenswarm.agents.harness.team.team_runtime_inheritance import (+ get_context_engine_enabled,+ get_evolution_auto_scan_enabled,+ get_skill_create_enabled,+ resolve_model_config,+)+from jiuwenswarm.agents.swarm import registry+from jiuwenswarm.agents.swarm.providers import tools as _tools++# Modes that route to the code adapter and get the code member profile.+_CODE_MODES: frozenset[str] = frozenset({"code.team", "team.plan"})++# Rails common to both roles, in mount order. Each entry is a ``swarm.*``+# provider name re-exported from the registry (no hard-coded strings).+_COMMON_RAIL_NAMES: tuple[str, ...] = (+ registry.RUNTIME_PROMPT,+ registry.RESPONSE_PROMPT,+ registry.SYS_OPERATION,+ registry.STREAM_EVENT,+ registry.TASK_PLANNING,+ registry.SECURITY,+ registry.HEARTBEAT,+ registry.AVATAR_PROMPT,+ registry.TEAM_WORKSPACE_REPORT_PATH,+ registry.CONTEXT_PROCESSOR,+ registry.PLUGIN_RAILS,+)++# Tools common to both roles. Each element self-gates on config, so all are+# declared; an unconfigured element simply yields no tools.+_COMMON_TOOL_NAMES: tuple[str, ...] = (+ registry.WEB_SEARCH,+ registry.WEB_FETCH,+ registry.WEB_PAID_SEARCH,+ registry.VISION,+ registry.AUDIO,+ # Skill-management tools (search/install/uninstall_skill) are registered by+ # the MEMBER_SKILL_TOOLKIT rail (appended below), which owns them with a+ # link-refresh callback. Declaring SKILL_TOOLKIT here too only double-+ # registers the same-named tools, logging a refresh + duplicate-ability+ # warning per tool every build; the rail is the sole registrar.+ registry.USER_TODOS,+ registry.VIDEO,+ registry.IMAGE_GEN,+ registry.XIAOYI_PHONE,+ registry.CRON_TOOLS,+ registry.SEND_FILE,+)++# Parameterless code-profile rails (the code variant of the common rails plus+# code-specific rails). ``code_confirm_interrupt`` and ``member_skill_toolkit``+# carry params and are appended separately.+_CODE_RAIL_NAMES: tuple[str, ...] = (+ registry.CODE_RUNTIME_PROMPT,+ registry.RESPONSE_PROMPT,+ registry.STREAM_EVENT,+ registry.SECURITY,+ registry.CODE_LSP,+ registry.CODE_PROJECT_MEMORY,+ registry.PERMISSION_INTERRUPT,+ registry.SYS_OPERATION,+ registry.CODE_CODING_MEMORY,+ registry.CODE_AGENT_MODE,+ registry.STRUCTURED_ASK_USER,+ registry.CONTEXT_PROCESSOR,+ registry.CODE_TASK_PLANNING,+ registry.CODE_AGENT_RAIL,+ registry.USER_HOOKS,+ registry.CODE_SKILL_USE,+ registry.CODE_WORKTREE,+)++# Rails shared with the team profile, appended to the code profile.+_CODE_SHARED_RAIL_NAMES: tuple[str, ...] = (+ registry.TEAM_WORKSPACE_REPORT_PATH,+ registry.PLUGIN_RAILS,+)++# Code member tools: the common tool set plus the code-exclusive acp_chat.+_CODE_TOOL_NAMES: tuple[str, ...] = (+ registry.WEB_SEARCH,+ registry.WEB_FETCH,+ registry.WEB_PAID_SEARCH,+ registry.VISION,+ registry.AUDIO,+ # See _COMMON_TOOL_NAMES: skill tools come from the MEMBER_SKILL_TOOLKIT+ # rail; declaring SKILL_TOOLKIT here too would double-register them.+ registry.USER_TODOS,+ registry.VIDEO,+ registry.IMAGE_GEN,+ registry.XIAOYI_PHONE,+ registry.CODE_EXTRA_TOOLS,+ registry.CRON_TOOLS,+ registry.SEND_FILE,+)++# code_agent sub-agents are always-on (explore / plan) or config-gated.+_DEFAULT_SUBAGENT_MAX_ITERATIONS = 15+++def _is_code_mode(mode: str) -> bool:+ """Return whether *mode* routes to the code member profile."""+ return mode in _CODE_MODES+++def _resolve_member_skills(config: dict[str, Any], role: str) -> list[str]:+ """Resolve the skill names selected for *role* from the config source.++ Mirrors the legacy ``resolve_member_skills``: reads ``config.agents.<role>.skills``+ and returns the cleaned, non-empty names.++ Args:+ config: The resolved ``config.yaml`` mapping (team blueprint shape).+ role: The member role ("leader" or "teammate").++ Returns:+ The selected skill names for the role (possibly empty).+ """+ agents = config.get("agents") if isinstance(config, dict) else None+ if not isinstance(agents, dict):+ return []+ member = agents.get(role)+ if not isinstance(member, dict):+ return []+ skills = member.get("skills")+ if not isinstance(skills, list):+ return []+ return [str(skill).strip() for skill in skills if str(skill).strip()]+++# ---------------------------------------------------------------------------+# Config-attribute extraction: harness settings (config.yaml) baked into spec+# ``params`` at spec-build time. Per-request environment values stay on the+# build context; only these attributes are projected into ``RailSpec.params`` /+# ``BuiltinToolSpec.params``.+# ---------------------------------------------------------------------------+++def _config_section(config: dict[str, Any], key: str) -> dict[str, Any]:+ """Return ``config[key]`` as a dict (empty when absent or the wrong type)."""+ section = (config or {}).get(key, {})+ return section if isinstance(section, dict) else {}+++def _evolution_model_config(config: dict[str, Any]) -> dict[str, Any]:+ """Resolve the serializable evolution model config (the LLM is built later)."""+ model_client_config, model_config_obj, model_name = resolve_model_config(+ config or {}+ )+ return {+ "model_client_config": model_client_config,+ "model_config_obj": model_config_obj,+ "model_name": model_name,+ }+++def _skill_mode(config: dict[str, Any]) -> str:+ """Resolve the validated skill-use mode from ``react.skill_mode``."""+ react = _config_section(config, "react")+ raw = react.get("skill_mode", SkillUseRail.SKILL_MODE_ALL)+ valid = {SkillUseRail.SKILL_MODE_AUTO_LIST, SkillUseRail.SKILL_MODE_ALL}+ return raw if isinstance(raw, str) and raw in valid else SkillUseRail.SKILL_MODE_ALL+++def _additional_directories(config: dict[str, Any]) -> list[str]:+ """Resolve project-memory additional directories from config + env."""+ react = _config_section(config, "react")+ raw = react.get("project_memory", {}).get("additional_directories")+ if raw is None:+ raw = os.getenv("JIUWENSWARM_ADDITIONAL_DIRECTORIES", "")+ if isinstance(raw, str):+ return [item.strip() for item in raw.split(os.pathsep) if item.strip()]+ if isinstance(raw, (list, tuple, set)):+ return [str(item).strip() for item in raw if str(item).strip()]+ return []+++def _permission_model_name(config: dict[str, Any]) -> str:+ """Resolve the permission rail's model name from config."""+ return (+ _config_section(config, "models")+ .get("default", {})+ .get("model_client_config", {})+ .get("model_name", "gpt-4")+ )+++def _acp_enabled(config: dict[str, Any]) -> bool:+ """Resolve whether ACP agents are configured (gates the acp_chat tool)."""+ acp_cfg = (config or {}).get("acp_agents")+ return isinstance(acp_cfg, dict) and bool(acp_cfg)+++def _context_processor_params(config: dict[str, Any]) -> dict[str, Any]:+ """Attribute params for the context-compression rail."""+ return {+ "context_engine_enabled": get_context_engine_enabled(config),+ "context_engine_config": _config_section(config, "context_engine_config"),+ }+++def _permission_params(config: dict[str, Any]) -> dict[str, Any]:+ """Attribute params for the permission-interrupt rail."""+ return {+ "permissions_config": _config_section(config, "permissions"),+ "model_name": _permission_model_name(config),+ }+++def _evolution_rail_params(config: dict[str, Any]) -> dict[str, Any]:+ """Attribute params for the team / member skill-evolution rails."""+ return {+ "evolution_model_config": _evolution_model_config(config),+ "auto_scan": get_evolution_auto_scan_enabled(config),+ }+++# Per-element attribute params, keyed by provider name; empty for parameterless.+_RAIL_PARAM_BUILDERS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {+ registry.CONTEXT_PROCESSOR: _context_processor_params,+ registry.CODE_PROJECT_MEMORY: lambda c: {+ "additional_directories": _additional_directories(c)+ },+ registry.PERMISSION_INTERRUPT: _permission_params,+ registry.CODE_CODING_MEMORY: lambda c: {+ "embed_config": _config_section(c, "embed")+ },+ registry.USER_HOOKS: lambda c: {"hooks_section": _config_section(c, "hooks")},+ registry.CODE_SKILL_USE: lambda c: {"skill_mode": _skill_mode(c)},+ registry.CODE_WORKTREE: lambda c: {"enabled": True},+}+++def _vision_tool_params(config: dict[str, Any]) -> dict[str, Any]:+ """Bake the core vision element's VisionModelConfig kwargs (empty disables it)."""+ return {"vision_model_config": _tools.vision_model_config_params(config)}+++def _audio_tool_params(config: dict[str, Any]) -> dict[str, Any]:+ """Bake the core audio element's dedicated flag + AudioModelConfig kwargs."""+ return {+ "dedicated": _tools.audio_dedicated_configured(config),+ "audio_model_config": _tools.audio_model_config_params(config),+ }+++_TOOL_PARAM_BUILDERS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {+ registry.SEND_FILE: lambda c: {"channels_config": _config_section(c, "channels")},+ registry.CODE_EXTRA_TOOLS: lambda c: {"acp_enabled": _acp_enabled(c)},+ registry.VISION: _vision_tool_params,+ registry.AUDIO: _audio_tool_params,+}+++def _rail_params(name: str, config: dict[str, Any]) -> dict[str, Any]:+ """Return attribute params baked into rail *name* (empty when parameterless)."""+ builder = _RAIL_PARAM_BUILDERS.get(name)+ return builder(config) if builder else {}+++def _tool_params(name: str, config: dict[str, Any]) -> dict[str, Any]:+ """Return attribute params baked into tool *name* (empty when parameterless)."""+ builder = _TOOL_PARAM_BUILDERS.get(name)+ return builder(config) if builder else {}+++def _role_evolution_rails(config: dict[str, Any], role: str) -> list[RailSpec]:+ """Return the role-specific skill-evolution rails (shared by both profiles)."""+ if role == "leader":+ return [+ RailSpec(+ type=registry.TEAM_SKILL_EVOLUTION,+ params=_evolution_rail_params(config),+ ),+ RailSpec(+ type=registry.TEAM_SKILL_CREATE,+ params={"skill_create": get_skill_create_enabled(config)},+ ),+ ]+ return [+ RailSpec(+ type=registry.MEMBER_SKILL_EVOLUTION, params=_evolution_rail_params(config)+ ),+ ]+++def _build_team_capability_specs(+ config: dict[str, Any],+ role: str,+) -> tuple[list[RailSpec], list[BuiltinToolSpec]]:+ """Build the chat-team profile rail/tool specs for a member."""+ rails_specs: list[RailSpec] = [+ RailSpec(type=name, params=_rail_params(name, config))+ for name in _COMMON_RAIL_NAMES+ ]+ rails_specs.append(+ RailSpec(+ type=registry.MEMBER_SKILL_TOOLKIT,+ params={"skills": _resolve_member_skills(config, role)},+ )+ )+ rails_specs.extend(_role_evolution_rails(config, role))++ tool_specs: list[BuiltinToolSpec] = [+ BuiltinToolSpec(type=name, params=_tool_params(name, config))+ for name in _COMMON_TOOL_NAMES+ ]+ return rails_specs, tool_specs+++def _build_code_capability_specs(+ config: dict[str, Any],+ role: str,+) -> tuple[list[RailSpec], list[BuiltinToolSpec]]:+ """Build the code profile (code.team / team.plan) rail/tool specs for a member."""+ rails_specs: list[RailSpec] = [+ RailSpec(type=name, params=_rail_params(name, config))+ for name in _CODE_RAIL_NAMES+ ]+ rails_specs.append(+ RailSpec(+ type=registry.CODE_CONFIRM_INTERRUPT,+ params={"tool_names": ["switch_mode", "exit_plan_mode"]},+ )+ )+ rails_specs.append(+ RailSpec(+ type=registry.MEMBER_SKILL_TOOLKIT,+ params={"skills": _resolve_member_skills(config, role)},+ )+ )+ rails_specs.extend(+ RailSpec(type=name, params=_rail_params(name, config))+ for name in _CODE_SHARED_RAIL_NAMES+ )+ rails_specs.extend(_role_evolution_rails(config, role))++ tool_specs: list[BuiltinToolSpec] = [+ BuiltinToolSpec(type=name, params=_tool_params(name, config))+ for name in _CODE_TOOL_NAMES+ ]+ return rails_specs, tool_specs+++def build_member_capability_specs(+ config: dict[str, Any],+ mode: str,+ role: str,+) -> tuple[list[RailSpec], list[BuiltinToolSpec]]:+ """Build the rail and tool specs for a team member.++ Branches by mode: the code modes get the code profile (``swarm.code_*``+ rails), all other modes get the chat-team profile. The member-skill toolkit+ rail carries the role's selected skill names, and the role adds its skill+ evolution rails.++ Args:+ config: The resolved ``config.yaml`` mapping (team blueprint shape).+ mode: The request mode ("team" / "code.team" / "team.plan").+ role: The member role ("leader" or "teammate").++ Returns:+ A ``(rails_specs, tool_specs)`` tuple of openjiuwen specs.+ """+ if _is_code_mode(mode):+ return _build_code_capability_specs(config, role)+ return _build_team_capability_specs(config, role)+++def _is_subagent_enabled(sub_cfg: Any) -> bool:+ """Return whether a ``react.subagents.<name>`` entry is enabled."""+ return isinstance(sub_cfg, dict) and bool(sub_cfg.get("enabled", False))+++def _subagent_language(mode: str, role: str, config: dict[str, Any]) -> str:+ """Resolve the code sub-agent runtime language (mirrors ``code_runtime_language``).++ Code mode is English-only except the team.plan leader, which uses the+ configured preferred language. Baked into ``factory_kwargs`` so the generic+ openjiuwen sub-agent providers stay free of swarm mode/role policy.+ """+ if mode == "team.plan" and role == "leader":+ return resolve_language((config or {}).get("preferred_language", "zh"))+ return "en"+++def _code_subagent_spec(+ name: str,+ factory_name: str,+ react_cfg: dict[str, Any],+ language: str,+) -> SubAgentSpec:+ """Build a declarative ``SubAgentSpec`` for a code sub-agent provider.++ The ``agent_card`` / ``system_prompt`` are placeholders: ``SubAgentSpec.build``+ short-circuits to the registered provider (by ``factory_name``), which returns+ a fully-formed ``SubAgentConfig``.+ """+ subagents_cfg = (+ react_cfg.get("subagents", {}) if isinstance(react_cfg, dict) else {}+ )+ sub_cfg = subagents_cfg.get(name) if isinstance(subagents_cfg, dict) else None+ max_iterations = react_cfg.get("max_iterations", _DEFAULT_SUBAGENT_MAX_ITERATIONS)+ if isinstance(sub_cfg, dict) and sub_cfg.get("max_iterations"):+ max_iterations = sub_cfg["max_iterations"]+ return SubAgentSpec(+ agent_card=AgentCard(name=name),+ system_prompt="",+ factory_name=factory_name,+ factory_kwargs={+ "max_iterations": int(max_iterations),+ "language": language,+ },+ )+++def build_member_subagent_specs(+ config: dict[str, Any],+ mode: str,+ role: str,+) -> list[SubAgentSpec]:+ """Build the declarative code sub-agent specs (empty for non-code modes).++ explore / plan are always present, while code / browser are config-gated via+ ``react.subagents.<name>.enabled``.++ Args:+ config: The resolved ``config.yaml`` mapping.+ mode: The request mode.+ role: The member role (reserved, both roles get the same sub-agents).++ Returns:+ The ``SubAgentSpec`` list (empty when not a code mode).+ """+ if not _is_code_mode(mode):+ return []+ react = (config or {}).get("react", {})+ react = react if isinstance(react, dict) else {}+ subagents_cfg = react.get("subagents", {}) if isinstance(react, dict) else {}+ language = _subagent_language(mode, role, config)++ specs: list[SubAgentSpec] = [+ _code_subagent_spec("explore_agent", registry.EXPLORE_AGENT, react, language),+ _code_subagent_spec("plan_agent", registry.PLAN_AGENT, react, language),+ ]+ if isinstance(subagents_cfg, dict):+ if _is_subagent_enabled(subagents_cfg.get("code_agent")):+ specs.append(+ _code_subagent_spec("code_agent", registry.CODE_AGENT, react, language)+ )+ if _is_subagent_enabled(subagents_cfg.get("browser_agent")):+ specs.append(+ _code_subagent_spec(+ "browser_agent", registry.BROWSER_AGENT, react, language+ )+ )+ return specs+++def build_member_deep_agent_spec(+ config: dict[str, Any],+ mode: str,+ role: str,+ base_spec: DeepAgentSpec,+) -> DeepAgentSpec:+ """Fold the member capability specs onto *base_spec*.++ Appends the rails/tools (and, for code modes, sub-agents + the code system+ prompt) after the base spec's existing entries and returns a new+ ``DeepAgentSpec`` (the input is left unmodified).++ Args:+ config: The resolved ``config.yaml`` mapping.+ mode: The request mode ("team" / "code.team" / "team.plan").+ role: The member role ("leader" or "teammate").+ base_spec: The base member ``DeepAgentSpec`` to extend.++ Returns:+ A new ``DeepAgentSpec`` with the capability specs applied.+ """+ rails_specs, tool_specs = build_member_capability_specs(config, mode, role)++ merged_rails = list(base_spec.rails or [])+ merged_rails.extend(rails_specs)+ merged_tools = list(base_spec.tools or [])+ merged_tools.extend(tool_specs)++ update: dict[str, Any] = {"rails": merged_rails, "tools": merged_tools}++ subagent_specs = build_member_subagent_specs(config, mode, role)+ if subagent_specs:+ merged_subagents = list(base_spec.subagents or [])+ merged_subagents.extend(subagent_specs)+ update["subagents"] = merged_subagents++ if _is_code_mode(mode):+ from jiuwenswarm.agents.harness.code.prompt.code_prompt_builder import (+ build_code_system_prompt,+ )++ update["system_prompt"] = build_code_system_prompt()++ return base_spec.model_copy(update=update)+++__all__ = [+ "build_member_capability_specs",+ "build_member_subagent_specs",+ "build_member_deep_agent_spec",+]diff --git a/jiuwenswarm/agents/swarm/context.py b/jiuwenswarm/agents/swarm/context.pynew file mode 100644index 0000000000..4a77529f39--- /dev/null+++ b/jiuwenswarm/agents/swarm/context.py@@ -0,0 +1,130 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Runtime build context for swarm provider-based team assembly.++``SwarmBuildContext`` carries the live, non-serializable jiuwenswarm handles+a capability provider needs at build time. It extends openjiuwen's+``BuildContext`` so openjiuwen's ``setup_agent`` can fill the per-member view+(``member_name`` / ``role`` / ``workspace`` / ``member_card_id``) via+``derive()`` while the platform attaches the per-team/per-process handles.++It deliberately holds no parent DeepAgent: team members build from the shared+config source (``config.yaml``), not by inheriting a pre-built single agent.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Any++from openjiuwen.agent_teams.schema.build_context import BuildContext+++@dataclass+class SwarmBuildContext(BuildContext):+ """BuildContext subclass carrying jiuwenswarm runtime handles.++ Per-team / per-process fields are set once when enriching the team spec.+ Per-member fields (``member_name`` / ``role`` / ``language`` / ``workspace``+ / ``member_card_id``) are inherited from ``BuildContext`` and filled by+ openjiuwen's ``setup_agent`` through ``derive()``.++ Attributes:+ session_id: Active session id.+ request_id: Originating request id (may be None).+ channel_id: Raw channel id from the request (may be None).+ channel: Resolved channel key for ``get_team_manager`` (``channel_id``+ or "default").+ request_metadata: Request metadata dict (carries ``mode`` etc.).+ mode: Request mode (e.g. "team"); replaces the old parent+ ``_jiuwenswarm_adapter_mode`` lookup.+ project_dir: Resolved project directory (from request / session /+ config); replaces the old parent ``_jiuwenswarm_project_dir``.+ team_id: Team name.+ team_ws_root: Team shared workspace root path.+ team_skills_dir: Team shared skills directory (``team_ws_root/skills``).+ global_skills_dir: Global agent skills directory.+ trajectory_registry: Per-team in-memory trajectory registry shared by+ evolution rails.+ config: The resolved ``config.yaml`` mapping (``get_config()``).+ """++ session_id: str = ""+ request_id: str | None = None+ channel_id: str | None = None+ channel: str = "default"+ request_metadata: dict[str, Any] | None = None+ mode: str = "team"+ project_dir: str | None = None+ team_id: str = ""+ team_ws_root: str | None = None+ team_skills_dir: str | None = None+ global_skills_dir: str | None = None+ trajectory_registry: Any = None+ config: dict[str, Any] | None = None++ def to_seed(self) -> dict[str, Any]:+ """Export the serializable per-team / per-process fields as a seed.++ The seed travels on ``TeamAgentSpec.build_context_seed`` across a+ serialization boundary; :meth:`from_seed` rebuilds the context from it+ plus locally-sourced non-serializable handles. Per-member fields+ (``member_name`` / ``role`` / ``language`` / ``workspace`` /+ ``member_card_id``) are intentionally excluded — ``setup_agent`` fills+ them per member through ``derive()``. The live ``config`` and+ ``trajectory_registry`` are excluded too: the receiver supplies them.++ Returns:+ A plain mapping of serializable primitives.+ """+ return {+ "session_id": self.session_id,+ "request_id": self.request_id,+ "channel_id": self.channel_id,+ "channel": self.channel,+ "request_metadata": self.request_metadata,+ "mode": self.mode,+ "project_dir": self.project_dir,+ "team_id": self.team_id,+ "team_ws_root": self.team_ws_root,+ "team_skills_dir": self.team_skills_dir,+ "global_skills_dir": self.global_skills_dir,+ }++ @classmethod+ def from_seed(+ cls,+ seed: dict[str, Any],+ *,+ config: dict[str, Any] | None,+ trajectory_registry: Any,+ ) -> "SwarmBuildContext":+ """Rebuild a context from a :meth:`to_seed` mapping plus local handles.++ Args:+ seed: The serializable mapping produced by :meth:`to_seed`.+ config: The receiving process's resolved ``config.yaml`` mapping.+ trajectory_registry: A per-team trajectory registry for this process.++ Returns:+ A ``SwarmBuildContext`` with the seed fields restored and the+ non-serializable handles sourced from the receiving process.+ """+ return cls(+ session_id=seed.get("session_id", ""),+ request_id=seed.get("request_id"),+ channel_id=seed.get("channel_id"),+ channel=seed.get("channel") or "default",+ request_metadata=seed.get("request_metadata"),+ mode=seed.get("mode") or "team",+ project_dir=seed.get("project_dir"),+ team_id=seed.get("team_id", ""),+ team_ws_root=seed.get("team_ws_root"),+ team_skills_dir=seed.get("team_skills_dir"),+ global_skills_dir=seed.get("global_skills_dir"),+ trajectory_registry=trajectory_registry,+ config=config,+ )+++__all__ = ["SwarmBuildContext"]diff --git a/jiuwenswarm/agents/swarm/providers/__init__.py b/jiuwenswarm/agents/swarm/providers/__init__.pynew file mode 100644index 0000000000..5989458955--- /dev/null+++ b/jiuwenswarm/agents/swarm/providers/__init__.py@@ -0,0 +1,3 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Swarm capability providers (config-sourced rails, tools, sub-agents)."""diff --git a/jiuwenswarm/agents/swarm/providers/builtin_rails.py b/jiuwenswarm/agents/swarm/providers/builtin_rails.pynew file mode 100644index 0000000000..deb240c3cd--- /dev/null+++ b/jiuwenswarm/agents/swarm/providers/builtin_rails.py@@ -0,0 +1,60 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""No-factory class-rail declarations for swarm-owned team rails.++These rails take no construction params (a bare ``cls()``), so they are declared+with a class ``builder`` rather than a factory function. Only swarm-owned rail+classes live here; the generic openjiuwen rails (``sys_operation`` /+``task_planning`` / ``security`` / ``heartbeat`` / ...) are declared and+registered by openjiuwen itself and referenced by their bare names from+``config_specs``.++Declarations run at import time (the module-level ``harness_element`` calls+populate the catalog). ``registry`` imports this module so the declarations are+present before ``register_from_catalog`` runs.+"""++from __future__ import annotations++from openjiuwen.agent_teams.harness.manifest import (+ ElementKind,+ harness_element,+)++from jiuwenswarm.agents.harness.common.rails.avatar_rail import AvatarPromptRail+from jiuwenswarm.agents.harness.common.rails.response_prompt_rail import (+ ResponsePromptRail,+)+from jiuwenswarm.agents.harness.common.rails.stream_event_rail import (+ JiuClawStreamEventRail,+)++# No-parameter swarm-owned rail type names; namespaced under "swarm.".+RESPONSE_PROMPT = "swarm.response_prompt"+STREAM_EVENT = "swarm.stream_event"+AVATAR_PROMPT = "swarm.avatar_prompt"++harness_element(+ kind=ElementKind.RAIL,+ name=RESPONSE_PROMPT,+ description="Appends the response-format prompt segment before each model call.",+ builder=ResponsePromptRail,+)+harness_element(+ kind=ElementKind.RAIL,+ name=STREAM_EVENT,+ description="Emits JiuClaw streaming events across the member's lifecycle.",+ builder=JiuClawStreamEventRail,+)+harness_element(+ kind=ElementKind.RAIL,+ name=AVATAR_PROMPT,+ description="Injects per-request digital-avatar prompt sections.",+ builder=AvatarPromptRail,+)++__all__ = [+ "RESPONSE_PROMPT",+ "STREAM_EVENT",+ "AVATAR_PROMPT",+]diff --git a/jiuwenswarm/agents/swarm/providers/code_rails.py b/jiuwenswarm/agents/swarm/providers/code_rails.pynew file mode 100644index 0000000000..6692dd8e0a--- /dev/null+++ b/jiuwenswarm/agents/swarm/providers/code_rails.py@@ -0,0 +1,423 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Config-sourced code-mode rail providers for swarm team assembly.++Each code (code.team / team.plan) member rail is declared as a ``swarm.code_*``+factory resolved during ``spec.build()``. The factories mirror the construction+in ``interface_code.py::_build_*_rail`` but read everything from the build+context (config / project_dir / workspace) instead of a live adapter, so code+members are assembled **purely declaratively** — no ``configure_team_member_agent``,+no post-build / rail.init imperative mounting.++The ``CodingMemoryRail`` instance is stashed on ``ctx.extras`` so the code_agent+sub-agent can share it: ``DeepAgentSpec.build`` builds rails before sub-agents+under the same ``build_ctx`` (whose ``extras`` is one shared dict). See+:mod:`jiuwenswarm.agents.swarm.providers.code_subagents`.++Heavy / adapter-coupled symbols (``create_coding_memory_rail``,+``JiuwenAgentModeRail``, ``CodeAgentRail``) are imported lazily inside the+factories to avoid pulling the code adapter at module load.+"""++from __future__ import annotations++import logging+from typing import Any++from openjiuwen.agent_teams.harness.manifest import (+ ConstructionInput,+ context_field,+ ElementKind,+ harness_element,+ param_field,+)+from openjiuwen.harness.prompts import resolve_language+from openjiuwen.harness.rails import SkillUseRail++from jiuwenswarm.agents.swarm.context import SwarmBuildContext++logger = logging.getLogger(__name__)++# Provider name constants; namespaced under the shared "swarm." prefix.+CODE_RUNTIME_PROMPT = "swarm.code_runtime_prompt"+CODE_PROJECT_MEMORY = "swarm.code_project_memory"+PERMISSION_INTERRUPT = "swarm.permission_interrupt"+CODE_CODING_MEMORY = "swarm.code_coding_memory"+CODE_AGENT_MODE = "swarm.code_agent_mode"+STRUCTURED_ASK_USER = "swarm.structured_ask_user"+CODE_TASK_PLANNING = "swarm.code_task_planning"+CODE_AGENT_RAIL = "swarm.code_agent_rail"+USER_HOOKS = "swarm.user_hooks"+CODE_SKILL_USE = "swarm.code_skill_use"++# Key under ``ctx.extras`` where the main agent's CodingMemoryRail is published+# for the code_agent sub-agent to reuse the same instance.+CODING_MEMORY_EXTRAS_KEY = "_coding_memory_rail"+++def code_runtime_language(ctx: SwarmBuildContext) -> str:+ """Resolve the code member's runtime-prompt language.++ Code mode is English-only except the team.plan leader, which uses the+ configured preferred language (mirrors the legacy ``force_english_runtime_prompt``+ / ``team_plan_runtime_language`` handling).++ Args:+ ctx: The per-member build context.++ Returns:+ The resolved language code ("en" or the configured preferred language).+ """+ is_team_plan_leader = ctx.mode == "team.plan" and ctx.role == "leader"+ if is_team_plan_leader:+ return resolve_language((ctx.config or {}).get("preferred_language", "zh"))+ return "en"+++def _project_dir(ctx: SwarmBuildContext) -> str:+ """Resolve the code project directory from the build context."""+ workspace_root = (+ getattr(ctx.workspace, "root_path", None) if ctx.workspace else None+ )+ return ctx.project_dir or workspace_root or "./"+++def _workspace_root(ctx: SwarmBuildContext) -> str | None:+ """Resolve the member workspace root path (None when absent)."""+ return getattr(ctx.workspace, "root_path", None) if ctx.workspace else None+++def _code_agent_workspace_dir(ctx: SwarmBuildContext) -> str:+ """Resolve the CodeAgentRail workspace dir (workspace root or project dir)."""+ return str(_workspace_root(ctx) or _project_dir(ctx))+++class CodeRuntimePromptInput(ConstructionInput):+ """Construction inputs for the code runtime prompt rail."""++ language: str = context_field(+ resolver=code_runtime_language,+ default="en",+ description="Code runtime language (English, or plan-leader preferred language).",+ )+ channel: str = context_field(+ attr="channel", default="default", description="Resolved channel key."+ )+++@harness_element(+ kind=ElementKind.RAIL,+ name=CODE_RUNTIME_PROMPT,+ description="Code-mode runtime prompt rail (English, or the configured language "+ "for the team.plan leader).",+ input_model=CodeRuntimePromptInput,+)+def build_code_runtime_prompt(params: dict[str, Any], ctx: SwarmBuildContext) -> Any:+ """Build the code RuntimePromptRail (English, or configured lang for plan leader)."""+ from jiuwenswarm.agents.harness.common.rails.runtime_prompt_rail import (+ RuntimePromptRail,+ )++ try:+ inp = CodeRuntimePromptInput.resolve(params, ctx)+ return RuntimePromptRail(language=inp.language, channel=inp.channel)+ except Exception as exc:+ logger.warning("[swarm.code_runtime_prompt] create failed: %s", exc)+ return None+++class CodeProjectMemoryInput(ConstructionInput):+ """Construction inputs for the code project-memory rail."""++ project_dir: str = context_field(+ resolver=_project_dir,+ default="./",+ description="Project root scanned for memory files.",+ )+ language: str = context_field(+ resolver=code_runtime_language,+ default="en",+ description="Code runtime language.",+ )+ additional_directories: list[str] = param_field(+ default_factory=list,+ description="Extra memory directories from config (react.project_memory) or env.",+ )+++@harness_element(+ kind=ElementKind.RAIL,+ name=CODE_PROJECT_MEMORY,+ description="Project memory rail (auto-loads JIUWENSWARM.md / CLAUDE.md and any "+ "additional configured directories).",+ input_model=CodeProjectMemoryInput,+)+def build_code_project_memory(params: dict[str, Any], ctx: SwarmBuildContext) -> Any:+ """Build ProjectMemoryRail (auto-loads JIUWENSWARM.md / CLAUDE.md etc.)."""+ from jiuwenswarm.agents.harness.common.rails import ProjectMemoryRail++ try:+ inp = CodeProjectMemoryInput.resolve(params, ctx)+ return ProjectMemoryRail(+ workspace=inp.project_dir,+ language=inp.language,+ additional_directories=tuple(inp.additional_directories),+ )+ except Exception as exc:+ logger.warning("[swarm.code_project_memory] create failed: %s", exc)+ return None+++class PermissionInterruptInput(ConstructionInput):+ """Construction inputs for the permission-interrupt rail."""++ permissions_config: dict[str, Any] = param_field(+ default_factory=dict,+ description="Permission settings (enabled / tools / rules) from config.permissions.",+ )+ model_name: str = param_field(+ default="gpt-4",+ description="Model name from config models.default (drives permission policy).",+ )+++@harness_element(+ kind=ElementKind.RAIL,+ name=PERMISSION_INTERRUPT,+ description="Permission-interrupt rail; mounted only when permissions are enabled "+ "in config.",+ input_model=PermissionInterruptInput,+)+def build_permission_interrupt(params: dict[str, Any], ctx: SwarmBuildContext) -> Any:+ """Build PermissionInterruptRail (None unless ``permissions.enabled`` in config)."""+ try:+ from jiuwenswarm.agents.harness.common.rails.interrupt.interrupt_helpers import (+ build_permission_rail,+ )++ inp = PermissionInterruptInput.resolve(params, ctx)+ return build_permission_rail(+ config={"permissions": inp.permissions_config},+ llm=None,+ model_name=inp.model_name,+ )+ except Exception as exc:+ logger.warning("[swarm.permission_interrupt] create failed: %s", exc)+ return None+++class CodeCodingMemoryInput(ConstructionInput):+ """Construction inputs for the coding-memory rail."""++ project_dir: str | None = context_field(+ attr="project_dir", description="Code project directory."+ )+ workspace_root: str | None = context_field(+ resolver=_workspace_root,+ description="Member workspace root (defaults to ./ when absent).",+ )+ embed_config: dict[str, Any] = param_field(+ default_factory=dict,+ description="Embedding config (api key / base url / model) from config.embed.",+ )+++@harness_element(+ kind=ElementKind.RAIL,+ name=CODE_CODING_MEMORY,+ description="Coding memory rail; also published on the build context so the code "+ "sub-agent reuses the same instance.",+ input_model=CodeCodingMemoryInput,+)+def build_code_coding_memory(params: dict[str, Any], ctx: SwarmBuildContext) -> Any:+ """Build CodingMemoryRail and publish it on ``ctx.extras`` for code_agent reuse."""+ try:+ from jiuwenswarm.server.runtime.agent_adapter.interface_code import (+ create_coding_memory_rail,+ )++ inp = CodeCodingMemoryInput.resolve(params, ctx)+ rail = create_coding_memory_rail(+ project_dir=inp.project_dir,+ agent_workspace_dir=str(inp.workspace_root or "./"),+ config={"embed": inp.embed_config},+ )+ # Share the instance with the code_agent sub-agent via the build context.+ ctx.extras[CODING_MEMORY_EXTRAS_KEY] = rail+ return rail+ except Exception as exc:+ logger.warning("[swarm.code_coding_memory] create failed: %s", exc)+ return None+++@harness_element(+ kind=ElementKind.RAIL,+ name=CODE_AGENT_MODE,+ description="Code plan-mode rail (Claude-Code-aligned agent mode).",+)+def build_code_agent_mode(params: dict[str, Any], ctx: SwarmBuildContext) -> Any:+ """Build the code plan-mode rail (Claude-Code-aligned AgentModeRail)."""+ try:+ from jiuwenswarm.server.runtime.agent_adapter.interface_code import (+ JiuwenAgentModeRail,+ )++ return JiuwenAgentModeRail()+ except Exception as exc:+ logger.warning("[swarm.code_agent_mode] create failed: %s", exc)+ return None+++class StructuredAskUserInput(ConstructionInput):+ """Construction inputs for the structured ask-user rail."""++ language: str = context_field(+ resolver=code_runtime_language,+ default="en",+ description="Code runtime language.",+ )+++@harness_element(+ kind=ElementKind.RAIL,+ name=STRUCTURED_ASK_USER,+ description="Structured ask-user rail in the code runtime language.",+ input_model=StructuredAskUserInput,+)+def build_structured_ask_user(params: dict[str, Any], ctx: SwarmBuildContext) -> Any:+ """Build the StructuredAskUserRail in the code runtime language."""+ from jiuwenswarm.agents.harness.common.rails import StructuredAskUserRail++ try:+ inp = StructuredAskUserInput.resolve(params, ctx)+ return StructuredAskUserRail(language=inp.language)+ except Exception as exc:+ logger.warning("[swarm.structured_ask_user] create failed: %s", exc)+ return None+++@harness_element(+ kind=ElementKind.RAIL,+ name=CODE_TASK_PLANNING,+ description="Code-specific task planning rail (Claude-Code-aligned todo tools).",+)+def build_code_task_planning(params: dict[str, Any], ctx: SwarmBuildContext) -> Any:+ """Build the code-specific task planning rail (CC-aligned todo tools)."""+ try:+ from jiuwenswarm.agents.harness.code.rails import CodeTaskPlanningRail++ return CodeTaskPlanningRail()+ except Exception as exc:+ logger.warning("[swarm.code_task_planning] create failed: %s", exc)+ return None+++class CodeAgentRailInput(ConstructionInput):+ """Construction inputs for the CodeAgentRail."""++ workspace_dir: str = context_field(+ resolver=_code_agent_workspace_dir,+ default="./",+ description="Workspace dir for /agents custom agents (workspace root or project dir).",+ )+++@harness_element(+ kind=ElementKind.RAIL,+ name=CODE_AGENT_RAIL,+ description="CodeAgentRail managing /agents custom agents, rooted at the workspace.",+ input_model=CodeAgentRailInput,+)+def build_code_agent_rail(params: dict[str, Any], ctx: SwarmBuildContext) -> Any:+ """Build CodeAgentRail (manages /agents custom agents) rooted at the workspace."""+ try:+ from jiuwenswarm.server.runtime.agent_adapter.code_agent_rail import (+ CodeAgentRail,+ )++ inp = CodeAgentRailInput.resolve(params, ctx)+ return CodeAgentRail(workspace_dir=inp.workspace_dir)+ except Exception as exc:+ logger.warning("[swarm.code_agent_rail] create failed: %s", exc)+ return None+++class UserHooksInput(ConstructionInput):+ """Construction inputs for the user-hook rail."""++ hooks_section: dict[str, Any] = param_field(+ default_factory=dict,+ description="User hooks config section (config.hooks); built when it declares events.",+ )+++@harness_element(+ kind=ElementKind.RAIL,+ name=USER_HOOKS,+ description="User hook rail built from config.hooks (skipped when no events are "+ "configured).",+ input_model=UserHooksInput,+)+def build_user_hooks(params: dict[str, Any], ctx: SwarmBuildContext) -> Any:+ """Build UserHookRail from ``config.hooks`` (None when no events are configured)."""+ try:+ from jiuwenswarm.common.hooks_config import load_hooks_config+ from jiuwenswarm.server.hooks.user_hook_rail import UserHookRail++ inp = UserHooksInput.resolve(params, ctx)+ hooks_config = load_hooks_config({"hooks": inp.hooks_section})+ if getattr(hooks_config, "events", None):+ return UserHookRail(hooks_config)+ return None+ except Exception as exc:+ logger.warning("[swarm.user_hooks] create failed: %s", exc)+ return None+++class CodeSkillUseInput(ConstructionInput):+ """Construction inputs for the code skill-use rail."""++ skill_mode: str = param_field(+ default=SkillUseRail.SKILL_MODE_ALL,+ description="Skill exposure mode (ALL or AUTO_LIST) from react.skill_mode.",+ )+++@harness_element(+ kind=ElementKind.RAIL,+ name=CODE_SKILL_USE,+ description="Skill-use rail from the config source (skill_mode plus disabled skills).",+ input_model=CodeSkillUseInput,+)+def build_code_skill_use(params: dict[str, Any], ctx: SwarmBuildContext) -> Any:+ """Build SkillUseRail from the config source (skill_mode + disabled skills)."""+ from jiuwenswarm.common.utils import get_agent_skills_dir+ from jiuwenswarm.server.runtime.skill import load_execution_disabled_skills++ try:+ inp = CodeSkillUseInput.resolve(params, ctx)+ return SkillUseRail(+ skills_dir=str(get_agent_skills_dir()),+ skill_mode=inp.skill_mode,+ include_tools=True,+ disabled_skills=load_execution_disabled_skills(),+ )+ except Exception as exc:+ logger.warning("[swarm.code_skill_use] create failed: %s", exc)+ return None+++__all__ = [+ "CODE_RUNTIME_PROMPT",+ "CODE_PROJECT_MEMORY",+ "PERMISSION_INTERRUPT",+ "CODE_CODING_MEMORY",+ "CODE_AGENT_MODE",+ "STRUCTURED_ASK_USER",+ "CODE_TASK_PLANNING",+ "CODE_AGENT_RAIL",+ "USER_HOOKS",+ "CODE_SKILL_USE",+ "CODING_MEMORY_EXTRAS_KEY",+ "code_runtime_language",+]diff --git a/jiuwenswarm/agents/swarm/providers/code_subagents.py b/jiuwenswarm/agents/swarm/providers/code_subagents.pynew file mode 100644index 0000000000..bb4befb93b--- /dev/null+++ b/jiuwenswarm/agents/swarm/providers/code_subagents.py@@ -0,0 +1,111 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Config-sourced code sub-agent provider for swarm team assembly.++Declares the swarm-specific ``code`` sub-agent as a ``swarm.*`` sub-agent+provider resolved via ``SubAgentSpec.factory_name`` during ``spec.build()``. The+generic explore / plan / browser sub-agents are provided by openjiuwen+(``explore_agent`` / ``plan_agent`` / ``browser_agent``); only ``code_agent``+stays swarm-side because it reuses the swarm ``CodingMemoryRail`` instance.++The parent member model and the main agent's ``CodingMemoryRail`` are read from+``ctx.extras`` (published by ``DeepAgentSpec.build`` and the+``swarm.code_coding_memory`` rail provider respectively, both before sub-agents+build under the same build context). ``build_code_agent_config`` requires a+model, so it skips when none is present.+"""++from __future__ import annotations++import logging+from typing import Any++from openjiuwen.agent_teams.harness.manifest import (+ ConstructionInput,+ context_field,+ ElementKind,+ harness_element,+ param_field,+)+from openjiuwen.harness.subagents.code_agent import build_code_agent_config++from jiuwenswarm.agents.swarm.context import SwarmBuildContext+from jiuwenswarm.agents.swarm.providers.code_rails import (+ code_runtime_language,+ CODING_MEMORY_EXTRAS_KEY,+)++logger = logging.getLogger(__name__)++CODE_AGENT = "swarm.code_agent"++# Key under ``ctx.extras`` where ``DeepAgentSpec.build`` publishes the resolved+# parent member model for sub-agent providers to reuse.+_PARENT_MODEL_EXTRAS_KEY = "_parent_model"+_DEFAULT_MAX_ITERATIONS = 15+++def _workspace_root(ctx: SwarmBuildContext) -> str | None:+ """Resolve the member workspace root path."""+ return getattr(ctx.workspace, "root_path", None) if ctx.workspace else None+++class CodeAgentInput(ConstructionInput):+ """Construction inputs for the swarm code sub-agent."""++ max_iterations: int = param_field(+ default=_DEFAULT_MAX_ITERATIONS,+ description="Maximum task-loop iterations for the sub-agent.",+ )+ workspace_root: str | None = context_field(+ resolver=_workspace_root,+ description="Member workspace root (defaults to ./ when absent).",+ )+ language: str = context_field(+ resolver=code_runtime_language,+ default="en",+ description="Code runtime language for the sub-agent.",+ )+++@harness_element(+ kind=ElementKind.SUBAGENT,+ name=CODE_AGENT,+ description="Code execution sub-agent reusing the main agent's CodingMemoryRail; "+ "skipped when no parent model is available.",+ input_model=CodeAgentInput,+)+def build_code_agent(factory_kwargs: dict[str, Any], ctx: SwarmBuildContext) -> Any:+ """Build the code sub-agent, reusing the main agent's CodingMemoryRail.++ ``build_code_agent_config`` requires a model; returns None (skipped) when no+ parent model is available on the context.+ """+ inp = CodeAgentInput.resolve(factory_kwargs, ctx)+ model = ctx.extras.get(_PARENT_MODEL_EXTRAS_KEY)+ if model is None:+ logger.warning("[swarm.code_agent] skipped: no parent model on build context")+ return None+ rails = None+ coding_memory_rail = ctx.extras.get(CODING_MEMORY_EXTRAS_KEY)+ if coding_memory_rail is not None:+ # SysOperationRail is code_agent's default rail; passing rails overrides+ # the defaults, so it must be included explicitly alongside the shared+ # CodingMemoryRail.+ from openjiuwen.harness.rails import SysOperationRail++ rails = [SysOperationRail(), coding_memory_rail]+ spec = build_code_agent_config(+ model,+ rails=rails,+ workspace=str(inp.workspace_root or "./"),+ language=inp.language,+ max_iterations=inp.max_iterations,+ )+ spec.factory_kwargs = {"auto_create_workspace": False}+ return spec+++__all__ = [+ "CODE_AGENT",+]diff --git a/jiuwenswarm/agents/swarm/providers/evolution_rails.py b/jiuwenswarm/agents/swarm/providers/evolution_rails.pynew file mode 100644index 0000000000..264dd886e5--- /dev/null+++ b/jiuwenswarm/agents/swarm/providers/evolution_rails.py@@ -0,0 +1,632 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Skill-evolution rail providers for swarm provider-based team assembly.++This module ports the leader-only ``TeamSkillEvolutionRail`` /+``TeamSkillCreateRail`` and the teammate-only ``SkillEvolutionRail`` branches of+the legacy ``team_manager`` customizer into config-sourced rail providers.++In the legacy flow the customizer built each evolution rail and then imperatively+registered it with the per-channel :class:`TeamManager` (live-rail bookkeeping,+approval/sync targets, hot-reload contexts). Providers, however, only return rail+instances and never see the live agent. To preserve that bookkeeping without a+customizer, each evolution rail is wrapped in a thin subclass that overrides+``init(self, agent)`` to perform the same ``TeamManager`` registration once+openjiuwen attaches the rail to its agent. The build-time context handles are+captured on the instance at construction time by the provider factory.+"""++from __future__ import annotations++import logging+from pathlib import Path+from typing import Any++from openjiuwen.agent_teams.harness.manifest import (+ ConstructionInput,+ context_field,+ ElementKind,+ harness_element,+ param_field,+)+from openjiuwen.harness.rails import (+ SkillEvolutionRail,+ TeamSkillCreateRail,+ TeamSkillEvolutionRail,+)++from jiuwenswarm.agents.swarm.context import SwarmBuildContext+from jiuwenswarm.server.runtime.skill import load_execution_disabled_skills++logger = logging.getLogger(__name__)++# Provider name constants; namespaced under the shared "swarm." prefix.+TEAM_SKILL_EVOLUTION = "swarm.team_skill_evolution"+TEAM_SKILL_CREATE = "swarm.team_skill_create"+MEMBER_SKILL_EVOLUTION = "swarm.member_skill_evolution"+++def _build_team_workspace_info(+ *,+ team_ws_root: str | None,+ team_skills_dir: str | None,+ team_id: str,+ config: dict[str, Any] | None,+ trajectory_registry: Any,+) -> Any:+ """Build a fully-populated ``TeamWorkspaceInfo`` for rail-context registration.++ The hot-reload path (``update_evolution_config`` →+ ``_build_and_mount_member_rails_for_context`` → ``build_member_rails``)+ rebuilds the leader evolution / create rails from the stored+ ``TeamRailMountContext.team_workspace``; populating every field keeps that+ rebuild working for provider-mounted teams (the legacy customizer passed the+ same fields, the swarm path previously passed an empty object).++ Args:+ team_ws_root: Team shared workspace root path.+ team_skills_dir: Team shared skills directory (rebuild gate + sync source).+ team_id: Team name.+ config: The resolved ``config.yaml`` mapping.+ trajectory_registry: Per-team in-memory trajectory registry.++ Returns:+ A populated ``TeamWorkspaceInfo``.+ """+ from jiuwenswarm.agents.harness.team.team_runtime_inheritance import (+ TeamWorkspaceInfo,+ )++ return TeamWorkspaceInfo(+ root_dir=team_ws_root,+ skills_dir=team_skills_dir,+ team_id=team_id,+ config=config,+ trajectory_registry=trajectory_registry,+ )+++def _register_team_rail_context(+ channel: str,+ session_id: str,+ agent: Any,+ team_workspace: Any,+) -> None:+ """Register the leader rail-mount context for hot config reloads.++ Mirrors the legacy customizer's ``register_team_rail_context`` call. Imported+ lazily so this provider module never imports ``team_manager`` at module load+ (the swarm assembly entry point is imported from team code paths).++ Args:+ channel: Resolved channel key used to locate the team manager.+ session_id: Active session id owning the rail.+ agent: The live member agent the rail was attached to.+ team_workspace: Fully-populated ``TeamWorkspaceInfo`` so hot-reload can+ rebuild the leader rails.+ """+ from jiuwenswarm.agents.harness.team.team_manager import (+ TeamRailMountContext,+ get_team_manager,+ )+ from jiuwenswarm.agents.harness.team.team_runtime_inheritance import (+ MemberInfo,+ RuntimeInfo,+ get_default_model_name,+ )++ team_manager = get_team_manager(channel)+ context = team_manager.get_team_rail_context(session_id)+ if context is not None:+ return+ team_manager.register_team_rail_context(+ session_id,+ TeamRailMountContext(+ agent=agent,+ member_info=MemberInfo(+ agent_name=getattr(agent.card, "name", "team_member"),+ model_name=get_default_model_name(),+ role="leader",+ ),+ runtime=RuntimeInfo(channel=channel),+ team_workspace=team_workspace,+ ),+ )+++class SwarmTeamSkillEvolutionRail(TeamSkillEvolutionRail):+ """``TeamSkillEvolutionRail`` that self-registers with the team manager.++ On ``init`` it records itself as a live rail, as the session's team skill+ rail, and registers the workspace-to-global skill sync target, reproducing+ the leader-side registration the legacy customizer performed.+ """++ def bind_swarm_context(+ self,+ *,+ channel: str,+ session_id: str,+ team_ws_root: str | None,+ team_skills_dir: str,+ team_id: str,+ config: dict[str, Any] | None,+ trajectory_registry: Any,+ ) -> None:+ """Capture the build-time handles needed for team-manager registration.++ Args:+ channel: Resolved channel key used to locate the team manager.+ session_id: Active session id owning the rail.+ team_ws_root: Team shared workspace root path.+ team_skills_dir: Team shared skills directory.+ team_id: Team name.+ config: The resolved ``config.yaml`` mapping.+ trajectory_registry: Per-team in-memory trajectory registry.+ """+ self._swarm_channel = channel+ self._swarm_session_id = session_id+ self._swarm_team_skills_dir = team_skills_dir+ self._swarm_team_workspace = _build_team_workspace_info(+ team_ws_root=team_ws_root,+ team_skills_dir=team_skills_dir,+ team_id=team_id,+ config=config,+ trajectory_registry=trajectory_registry,+ )++ def init(self, agent: Any) -> None:+ """Attach to *agent* and register with the per-channel team manager.++ Args:+ agent: The live member agent this rail is mounted on.+ """+ super().init(agent)+ try:+ from jiuwenswarm.agents.harness.team.team_manager import get_team_manager++ team_manager = get_team_manager(self._swarm_channel)+ team_manager.register_team_live_rail(self._swarm_session_id, agent, self)+ team_manager.register_team_skill_rail(self._swarm_session_id, self)+ _register_team_rail_context(+ self._swarm_channel,+ self._swarm_session_id,+ agent,+ self._swarm_team_workspace,+ )+ logger.info(+ "[swarm.team_skill_evolution] registered live rail "+ "(session=%s, skills_dir=%s)",+ self._swarm_session_id,+ self._swarm_team_skills_dir,+ )+ except Exception as exc:+ logger.warning(+ "[swarm.team_skill_evolution] team manager registration failed: %s", exc+ )+++class SwarmTeamSkillCreateRail(TeamSkillCreateRail):+ """``TeamSkillCreateRail`` that self-registers with the team manager."""++ def bind_swarm_context(+ self,+ *,+ channel: str,+ session_id: str,+ team_ws_root: str | None,+ team_skills_dir: str,+ team_id: str,+ config: dict[str, Any] | None,+ trajectory_registry: Any,+ ) -> None:+ """Capture the build-time handles needed for team-manager registration.++ Args:+ channel: Resolved channel key used to locate the team manager.+ session_id: Active session id owning the rail.+ team_ws_root: Team shared workspace root path.+ team_skills_dir: Team shared skills directory.+ team_id: Team name.+ config: The resolved ``config.yaml`` mapping.+ trajectory_registry: Per-team in-memory trajectory registry.+ """+ self._swarm_channel = channel+ self._swarm_session_id = session_id+ self._swarm_team_workspace = _build_team_workspace_info(+ team_ws_root=team_ws_root,+ team_skills_dir=team_skills_dir,+ team_id=team_id,+ config=config,+ trajectory_registry=trajectory_registry,+ )++ def init(self, agent: Any) -> None:+ """Attach to *agent* and register with the per-channel team manager.++ Args:+ agent: The live member agent this rail is mounted on.+ """+ super().init(agent)+ try:+ from jiuwenswarm.agents.harness.team.team_manager import get_team_manager++ team_manager = get_team_manager(self._swarm_channel)+ team_manager.register_team_live_rail(self._swarm_session_id, agent, self)+ team_manager.register_team_skill_create_rail(self._swarm_session_id, self)+ _register_team_rail_context(+ self._swarm_channel,+ self._swarm_session_id,+ agent,+ self._swarm_team_workspace,+ )+ logger.info(+ "[swarm.team_skill_create] registered live rail (session=%s)",+ self._swarm_session_id,+ )+ except Exception as exc:+ logger.warning(+ "[swarm.team_skill_create] team manager registration failed: %s", exc+ )+++class SwarmMemberSkillEvolutionRail(SkillEvolutionRail):+ """``SkillEvolutionRail`` that self-registers as a teammate evolution rail.++ The teammate evolution rail is not a "live" rail (no approval flow), so it+ only registers itself for hot config updates, matching the legacy+ ``register_team_member_skill_evolution_rail`` call.+ """++ def bind_swarm_context(self, *, channel: str, session_id: str) -> None:+ """Capture the build-time handles needed for team-manager registration.++ Args:+ channel: Resolved channel key used to locate the team manager.+ session_id: Active session id owning the rail.+ """+ self._swarm_channel = channel+ self._swarm_session_id = session_id++ def init(self, agent: Any) -> None:+ """Attach to *agent* and register with the per-channel team manager.++ Args:+ agent: The live member agent this rail is mounted on.+ """+ super().init(agent)+ try:+ from jiuwenswarm.agents.harness.team.team_manager import get_team_manager++ get_team_manager(+ self._swarm_channel+ ).register_team_member_skill_evolution_rail(+ self._swarm_session_id,+ self,+ )+ logger.info(+ "[swarm.member_skill_evolution] registered member evolution rail "+ "(session=%s)",+ self._swarm_session_id,+ )+ except Exception as exc:+ logger.warning(+ "[swarm.member_skill_evolution] team manager registration failed: %s",+ exc,+ )+++def _build_evolution_llm_from(model_config: dict[str, Any]) -> tuple[Any, str]:+ """Build the evolution LLM Model from the serializable model-config param.++ Mirrors ``team_runtime_inheritance.build_evolution_llm`` but takes the already+ resolved (serializable) model config baked into ``params`` at spec-build time,+ so the live LLM handle is constructed here at build time (never in the schema).+ """+ from openjiuwen.core.foundation.llm import (+ Model,+ ModelClientConfig,+ ModelRequestConfig,+ )++ model_client_config = model_config.get("model_client_config") or {}+ model_config_obj = model_config.get("model_config_obj") or {}+ model_name = model_config.get("model_name") or "gpt-4"+ request_config = ModelRequestConfig(+ model=model_name,+ temperature=model_config_obj.get("temperature", 0.95),+ )+ client_config = ModelClientConfig(**model_client_config)+ return Model(+ model_client_config=client_config, model_config=request_config+ ), model_name+++class TeamSkillEvolutionInput(ConstructionInput):+ """Construction inputs for the leader team skill-evolution rail."""++ evolution_model_config: dict[str, Any] = param_field(+ default_factory=dict,+ description="Serializable evolution model config (LLM built at build time).",+ )+ auto_scan: bool = param_field(+ default=False, description="Evolution auto-scan flag."+ )+ 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."+ )+ role: str | None = context_field(attr="role", description="Team role value.")+ team_id: str = context_field(attr="team_id", default="", description="Team name.")+ trajectory_registry: Any = context_field(+ attr="trajectory_registry", description="Per-team trajectory registry."+ )+ channel: str = context_field(+ attr="channel", default="default", description="Resolved channel key."+ )+ session_id: str | None = context_field(+ attr="session_id", description="Active session id."+ )+ team_ws_root: str | None = context_field(+ attr="team_ws_root", description="Team shared workspace root."+ )+++@harness_element(+ kind=ElementKind.RAIL,+ name=TEAM_SKILL_EVOLUTION,+ description="Leader-only team skill evolution rail (builds the evolution LLM and "+ "binds the per-team trajectory registry); skipped for non-leaders.",+ input_model=TeamSkillEvolutionInput,+)+def build_team_skill_evolution_rail(+ params: dict[str, Any],+ ctx: SwarmBuildContext,+) -> SwarmTeamSkillEvolutionRail | None:+ """Build the leader-only team skill evolution rail from the config source.++ Mirrors the leader branch of the legacy ``build_member_rails``: builds the+ evolution LLM, resolves auto-scan, binds the per-team trajectory registry+ when a team id is present, and wires the team-manager registration via the+ rail subclass ``init``.++ Args:+ params: Provider params (unused; kept for the provider contract).+ 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.+ """+ # Cheap gate before resolving (avoids building the evolution LLM for non-leaders).+ if ctx.role != "leader" or not ctx.team_skills_dir:+ return None++ try:+ inp = TeamSkillEvolutionInput.resolve(params, ctx)+ Path(inp.team_skills_dir).mkdir(parents=True, exist_ok=True)+ llm_model, actual_model_name = _build_evolution_llm_from(+ inp.evolution_model_config+ )+ bound_registry = inp.trajectory_registry if inp.team_id else None+ rail = SwarmTeamSkillEvolutionRail(+ inp.team_skills_dir,+ llm=llm_model,+ model=actual_model_name,+ language=inp.language,+ trajectory_source=bound_registry,+ trajectory_sink=bound_registry,+ member_role=inp.role,+ auto_scan=inp.auto_scan,+ auto_save=False,+ team_id=inp.team_id,+ disabled_skills=load_execution_disabled_skills(),+ )+ rail.bind_swarm_context(+ channel=inp.channel,+ session_id=inp.session_id,+ team_ws_root=inp.team_ws_root,+ team_skills_dir=inp.team_skills_dir,+ team_id=inp.team_id,+ config=ctx.config,+ trajectory_registry=inp.trajectory_registry,+ )+ logger.info(+ "[swarm.team_skill_evolution] built: skills_dir=%s, model=%s, auto_scan=%s",+ inp.team_skills_dir,+ actual_model_name,+ inp.auto_scan,+ )+ return rail+ except Exception as exc:+ logger.warning(+ "[swarm.team_skill_evolution] build failed: %s", exc, exc_info=True+ )+ return None+++class TeamSkillCreateInput(ConstructionInput):+ """Construction inputs for the leader team skill-create rail."""++ skill_create: bool = param_field(+ default=False,+ description="Skill-create flag (env SKILL_CREATE overrides config).",+ )+ 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."+ )+ channel: str = context_field(+ attr="channel", default="default", description="Resolved channel key."+ )+ session_id: str | None = context_field(+ attr="session_id", description="Active session id."+ )+ team_ws_root: str | None = context_field(+ attr="team_ws_root", description="Team shared workspace root."+ )+ team_id: str = context_field(attr="team_id", default="", description="Team name.")+ trajectory_registry: Any = context_field(+ attr="trajectory_registry", description="Per-team trajectory registry."+ )+++@harness_element(+ kind=ElementKind.RAIL,+ name=TEAM_SKILL_CREATE,+ description="Leader-only team skill creation rail (gated by SKILL_CREATE and a "+ "configured team skills directory); skipped otherwise.",+ input_model=TeamSkillCreateInput,+)+def build_team_skill_create_rail(+ params: dict[str, Any],+ ctx: SwarmBuildContext,+) -> SwarmTeamSkillCreateRail | None:+ """Build the leader-only team skill creation rail from the config source.++ Mirrors the leader branch of the legacy ``build_member_rails``: gated on+ ``get_skill_create_enabled`` (env ``SKILL_CREATE`` overrides config) and a+ configured team skills directory.++ Args:+ params: Provider params (unused; kept for the provider contract).+ ctx: The per-member build context.++ Returns:+ A ``SwarmTeamSkillCreateRail`` for the leader, or ``None`` when the+ member is not the leader, no team skills directory is configured, or+ skill creation is disabled.+ """+ if ctx.role != "leader" or not ctx.team_skills_dir:+ return None++ inp = TeamSkillCreateInput.resolve(params, ctx)+ if not inp.skill_create:+ return None++ try:+ rail = SwarmTeamSkillCreateRail(+ inp.team_skills_dir,+ language=inp.language,+ auto_trigger=True,+ )+ rail.bind_swarm_context(+ channel=inp.channel,+ session_id=inp.session_id,+ team_ws_root=inp.team_ws_root,+ team_skills_dir=inp.team_skills_dir,+ team_id=inp.team_id,+ config=ctx.config,+ trajectory_registry=inp.trajectory_registry,+ )+ logger.info(+ "[swarm.team_skill_create] built: skills_dir=%s", inp.team_skills_dir+ )+ return rail+ except Exception as exc:+ logger.warning("[swarm.team_skill_create] build failed: %s", exc, exc_info=True)+ return None+++class MemberSkillEvolutionInput(ConstructionInput):+ """Construction inputs for the teammate member skill-evolution rail."""++ evolution_model_config: dict[str, Any] = param_field(+ default_factory=dict,+ description="Serializable evolution model config (LLM built at build time).",+ )+ auto_scan: bool = param_field(+ default=False, description="Evolution auto-scan flag."+ )+ team_skills_dir: str | None = context_field(+ attr="team_skills_dir", description="Team shared skills directory."+ )+ trajectory_registry: Any = context_field(+ attr="trajectory_registry", description="Per-team trajectory registry."+ )+ team_id: str = context_field(attr="team_id", default="", description="Team name.")+ channel: str = context_field(+ attr="channel", default="default", description="Resolved channel key."+ )+ session_id: str | None = context_field(+ attr="session_id", description="Active session id."+ )+++@harness_element(+ kind=ElementKind.RAIL,+ name=MEMBER_SKILL_EVOLUTION,+ description="Teammate-only member skill evolution rail (auto-scan, auto-save, "+ "disabled skills, conditional team trajectory sink).",+ input_model=MemberSkillEvolutionInput,+)+def build_member_skill_evolution_rail(+ params: dict[str, Any],+ ctx: SwarmBuildContext,+) -> SwarmMemberSkillEvolutionRail | None:+ """Build the teammate-only member skill evolution rail from the config source.++ Replicates ``build_skill_evolution_rail`` (auto-scan, ``auto_save=True``,+ disabled skills, conditional team trajectory sink with+ ``member_role="teammate"``) but constructs the swarm subclass so the rail can+ self-register with the team manager from its ``init``.++ Args:+ params: Provider params (unused; kept for the provider contract).+ 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.+ """+ # Cheap gate before resolving (avoids building the evolution LLM for the leader).+ if ctx.role == "leader" or not ctx.team_skills_dir:+ return None++ try:+ inp = MemberSkillEvolutionInput.resolve(params, ctx)+ llm_model, actual_model_name = _build_evolution_llm_from(+ inp.evolution_model_config+ )+ rail = SwarmMemberSkillEvolutionRail(+ inp.team_skills_dir,+ llm=llm_model,+ model=actual_model_name,+ auto_scan=inp.auto_scan,+ auto_save=True,+ disabled_skills=load_execution_disabled_skills(),+ )+ if inp.trajectory_registry is not None and inp.team_id:+ rail.set_trajectory_sink(+ inp.trajectory_registry,+ team_id=inp.team_id,+ member_role="teammate",+ )+ rail.bind_swarm_context(channel=inp.channel, session_id=inp.session_id)+ logger.info(+ "[swarm.member_skill_evolution] built: model=%s, auto_scan=%s, "+ "team_trajectory_sink=%s",+ actual_model_name,+ inp.auto_scan,+ inp.trajectory_registry is not None and bool(inp.team_id),+ )+ return rail+ except Exception as exc:+ logger.warning(+ "[swarm.member_skill_evolution] build failed: %s", exc, exc_info=True+ )+ return None+++__all__ = [+ "TEAM_SKILL_EVOLUTION",+ "TEAM_SKILL_CREATE",+ "MEMBER_SKILL_EVOLUTION",+ "build_team_skill_evolution_rail",+ "build_team_skill_create_rail",+ "build_member_skill_evolution_rail",+]diff --git a/jiuwenswarm/agents/swarm/providers/member_rails.py b/jiuwenswarm/agents/swarm/providers/member_rails.pynew file mode 100644index 0000000000..db4e7fe69d--- /dev/null+++ b/jiuwenswarm/agents/swarm/providers/member_rails.py@@ -0,0 +1,218 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Swarm member rail providers (config-sourced, per-member).++Each provider is a factory ``factory(params, context) -> rail | list | None``+invoked by openjiuwen at build time with the per-member ``SwarmBuildContext``.+Returning ``None`` / ``[]`` means "skip this rail for this member" (config gate).+Providers take precedence over same-named class registrations.++Mirrors the legacy ``build_member_rails`` runtime-prompt / report-path /+context-processor segments and the team manager plugin-rails segment, but driven+by the build context instead of imperatively threaded dataclasses.+"""++from __future__ import annotations++import logging+from typing import Any++from openjiuwen.agent_teams.harness.manifest import (+ ConstructionInput,+ context_field,+ ElementKind,+ harness_element,+ param_field,+)++from jiuwenswarm.agents.harness.common.plugins.rail_manager import get_rail_manager+from jiuwenswarm.agents.harness.common.rails.runtime_prompt_rail import (+ RuntimePromptRail,+)+from jiuwenswarm.agents.harness.team.rails.team_workspace_report_path_rail import (+ TeamWorkspaceReportPathRail,+)+from jiuwenswarm.agents.harness.team.team_runtime_inheritance import (+ _build_context_processor_rail,+)+from jiuwenswarm.agents.swarm.context import SwarmBuildContext++logger = logging.getLogger(__name__)++RUNTIME_PROMPT = "swarm.runtime_prompt"+TEAM_WORKSPACE_REPORT_PATH = "swarm.team_workspace_report_path"+CONTEXT_PROCESSOR = "swarm.context_processor"+PLUGIN_RAILS = "swarm.plugin_rails"+++class RuntimePromptInput(ConstructionInput):+ """Construction inputs for the member runtime prompt rail."""++ language: str = context_field(+ attr="language",+ default="cn",+ description="Resolved member language code.",+ )+ channel: str = context_field(+ attr="channel",+ default="default",+ description="Resolved channel key.",+ )+++@harness_element(+ kind=ElementKind.RAIL,+ name=RUNTIME_PROMPT,+ description="Per-member runtime prompt rail bound to the member's language and channel.",+ input_model=RuntimePromptInput,+)+def _build_runtime_prompt_rail(+ params: dict[str, Any],+ context: SwarmBuildContext,+) -> RuntimePromptRail:+ """Build the runtime prompt rail for a member.++ Args:+ params: Spec params (unused; kept for the provider contract).+ context: Per-member build context.++ Returns:+ A ``RuntimePromptRail`` bound to the member's language and channel.+ """+ inp = RuntimePromptInput.resolve(params, context)+ return RuntimePromptRail(language=inp.language, channel=inp.channel)+++class TeamWorkspaceReportPathInput(ConstructionInput):+ """Construction inputs for the team workspace report-path rail."""++ team_ws_root: str | None = context_field(+ attr="team_ws_root",+ description="Team shared workspace root path (gate; skipped when absent).",+ )+ team_id: str = context_field(attr="team_id", default="", description="Team name.")+ language: str = context_field(+ attr="language",+ default="cn",+ description="Resolved member language code.",+ )+++@harness_element(+ kind=ElementKind.RAIL,+ name=TEAM_WORKSPACE_REPORT_PATH,+ description="Rewrites report paths under the shared team workspace root "+ "(skipped when no shared root is configured).",+ input_model=TeamWorkspaceReportPathInput,+)+def _build_team_workspace_report_path_rail(+ params: dict[str, Any],+ context: SwarmBuildContext,+) -> TeamWorkspaceReportPathRail | None:+ """Build the team workspace report-path rail when a shared root exists.++ Args:+ params: Spec params (unused; kept for the provider contract).+ context: Per-member build context.++ Returns:+ A ``TeamWorkspaceReportPathRail`` rooted at the team workspace, or+ ``None`` when no shared workspace root is configured.+ """+ inp = TeamWorkspaceReportPathInput.resolve(params, context)+ if not inp.team_ws_root:+ return None+ return TeamWorkspaceReportPathRail(+ root_dir=inp.team_ws_root,+ team_id=inp.team_id,+ language=inp.language,+ )+++class ContextProcessorInput(ConstructionInput):+ """Construction inputs for the context-compression rail."""++ context_engine_enabled: bool = param_field(+ default=True,+ description="Whether the context engine is enabled in config (gate).",+ )+ context_engine_config: dict[str, Any] = param_field(+ default_factory=dict,+ description="Context-engine config (compressor sub-configs).",+ )+++@harness_element(+ kind=ElementKind.RAIL,+ name=CONTEXT_PROCESSOR,+ description="Context-compression rail, mounted only when the context engine "+ "is enabled in config.",+ input_model=ContextProcessorInput,+)+def _build_context_processor(+ params: dict[str, Any],+ context: SwarmBuildContext,+) -> Any | None:+ """Build the context-compression rail when the context engine is enabled.++ Args:+ params: Spec params (unused; kept for the provider contract).+ context: Per-member build context.++ Returns:+ A preset ``ContextProcessorRail`` when enabled, otherwise ``None``.+ """+ inp = ContextProcessorInput.resolve(params, context)+ if not inp.context_engine_enabled:+ return None+ return _build_context_processor_rail(+ {"context_engine_config": inp.context_engine_config}+ )+++@harness_element(+ kind=ElementKind.RAIL,+ name=PLUGIN_RAILS,+ description="User-registered extension rails: a fresh instance of every "+ "registered rail extension, one per member.",+)+def _build_plugin_rails(+ params: dict[str, Any],+ context: SwarmBuildContext,+) -> list[Any]:+ """Build user-registered extension rails for a member.++ Enumerates every registered rail extension and instantiates a fresh+ instance per member, skipping any that fail to load.++ Args:+ params: Spec params (unused; kept for the provider contract).+ context: Per-member build context.++ Returns:+ A list of extension rail instances (possibly empty).+ """+ rail_manager = get_rail_manager()+ rails: list[Any] = []+ for rail_name in rail_manager.get_registered_rail_names():+ try:+ rail_instance = rail_manager.load_rail_instance_without_enabled_check(+ rail_name,+ )+ if rail_instance is not None:+ rails.append(rail_instance)+ except Exception as exc:+ logger.warning(+ "[SwarmRails] load extension rail %s failed: %s",+ rail_name,+ exc,+ )+ return rails+++__all__ = [+ "RUNTIME_PROMPT",+ "TEAM_WORKSPACE_REPORT_PATH",+ "CONTEXT_PROCESSOR",+ "PLUGIN_RAILS",+]diff --git a/jiuwenswarm/agents/swarm/providers/runtime_tools.py b/jiuwenswarm/agents/swarm/providers/runtime_tools.pynew file mode 100644index 0000000000..9b3d08181b--- /dev/null+++ b/jiuwenswarm/agents/swarm/providers/runtime_tools.py@@ -0,0 +1,224 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Runtime tool providers for swarm provider-based team assembly.++Ports the ``register_member_runtime_tools`` logic of the legacy ``team_manager``+into config-sourced tool providers. Each factory returns a flat list of tool+*instances*; openjiuwen's ``create_deep_agent`` performs the actual resource/+ability registration, so these providers never touch ``Runner.resource_mgr`` or+``agent.ability_manager`` (that imperative wiring is the customizer's job, not a+provider's).++Covered runtime tools:++* ``cron_tools`` — the per-member cron toolkit built by ``CronRuntimeBridge``,+ scoped to ``team_member_<member_card_id>``.+* ``send_file`` — the ``send_file_to_user`` toolkit, gated by the channel's+ ``send_file_allowed`` config (web defaults to enabled, others disabled) and by+ the presence of a request id / channel id.+"""++from __future__ import annotations++import logging+from types import SimpleNamespace+from typing import Any++from openjiuwen.agent_teams.harness.manifest import (+ ConstructionInput,+ context_field,+ ElementKind,+ harness_element,+ param_field,+)++from jiuwenswarm.agents.harness.common.tools.cron.cron_runtime import CronRuntimeBridge+from jiuwenswarm.agents.harness.common.tools.send_file_to_user import SendFileToolkit+from jiuwenswarm.agents.swarm.context import SwarmBuildContext++logger = logging.getLogger(__name__)++# Provider name constants; namespaced under the shared "swarm." prefix.+CRON_TOOLS = "swarm.cron_tools"+SEND_FILE = "swarm.send_file"+++class CronToolsInput(ConstructionInput):+ """Construction inputs for the per-member cron toolkit."""++ member_card_id: str | None = context_field(+ attr="member_card_id",+ description="Member card id used as the cron tool scope / agent id.",+ )+ channel_id: str | None = context_field(+ attr="channel_id", description="Raw channel id."+ )+ session_id: str | None = context_field(+ attr="session_id", description="Active session id."+ )+ request_metadata: dict[str, Any] | None = context_field(+ attr="request_metadata",+ description="Request metadata mapping.",+ )+ language: str = context_field(+ attr="language", default="cn", description="Member language code."+ )+++@harness_element(+ kind=ElementKind.TOOL,+ name=CRON_TOOLS,+ description="Per-member cron toolkit (create/list/manage scheduled tasks), "+ "scoped to team_member_<member_card_id>.",+ input_model=CronToolsInput,+)+def build_cron_tools(params: dict[str, Any], ctx: SwarmBuildContext) -> list[Any]:+ """Build the per-member cron toolkit from the config source.++ Mirrors the cron branch of ``register_member_runtime_tools``: builds a+ ``team``-mode cron context scoped to this member and delegates to+ ``CronRuntimeBridge.build_tools``.++ Args:+ params: Provider params (unused; kept for the provider contract).+ ctx: The per-member build context.++ Returns:+ The cron tool instances, or an empty list when construction fails.+ """+ inp = CronToolsInput.resolve(params, ctx)+ agent_id = inp.member_card_id+ cron_context = SimpleNamespace(+ tool_scope=f"team_member_{agent_id or 'unknown'}",+ channel_id=inp.channel_id or "web",+ session_id=inp.session_id,+ metadata=inp.request_metadata,+ mode="team",+ )+ try:+ cron_tools = CronRuntimeBridge().build_tools(+ context=cron_context,+ agent_id=agent_id,+ language=inp.language,+ )+ logger.info(+ "[swarm.cron_tools] built %d cron tools for agent_id=%s",+ len(cron_tools),+ agent_id,+ )+ return list(cron_tools)+ except Exception as exc:+ logger.warning(+ "[swarm.cron_tools] cron tool construction failed for agent_id=%s: %s",+ agent_id,+ exc,+ )+ return []+++def _is_send_file_enabled(config: dict[str, Any] | None, channel_id: str) -> bool:+ """Resolve whether file sending is allowed for *channel_id*.++ Reads ``channels.<channel_id>.send_file_allowed``; when unset, the ``web``+ channel defaults to enabled and all other channels default to disabled.++ Args:+ config: The resolved ``config.yaml`` mapping.+ channel_id: The channel id to resolve the switch for.++ Returns:+ ``True`` when file sending is allowed for the channel.+ """+ send_file_allowed = None+ if isinstance(config, dict):+ send_file_allowed = (+ config.get("channels", {}).get(str(channel_id), {}).get("send_file_allowed")+ )+ if send_file_allowed is None:+ return channel_id == "web"+ return bool(send_file_allowed)+++class SendFileInput(ConstructionInput):+ """Construction inputs for the send_file_to_user toolkit."""++ channels_config: dict[str, Any] = param_field(+ default_factory=dict,+ description="Per-channel config (the send_file_allowed switch lives here).",+ )+ request_id: str | None = context_field(+ attr="request_id",+ description="Originating request id (required; skipped when absent).",+ )+ channel_id: str | None = context_field(+ attr="channel_id",+ description="Raw channel id (required; skipped when absent).",+ )+ session_id: str | None = context_field(+ attr="session_id", description="Active session id."+ )+ request_metadata: dict[str, Any] | None = context_field(+ attr="request_metadata",+ description="Request metadata mapping.",+ )+++@harness_element(+ kind=ElementKind.TOOL,+ name=SEND_FILE,+ description="The send_file_to_user toolkit, gated by the channel's "+ "send_file_allowed config and the presence of a request/channel id.",+ input_model=SendFileInput,+)+def build_send_file_tools(params: dict[str, Any], ctx: SwarmBuildContext) -> list[Any]:+ """Build the ``send_file_to_user`` toolkit from the config source.++ Mirrors the send-file branch of ``register_member_runtime_tools``: requires a+ request id and channel id, and is gated by the channel's ``send_file_allowed``+ config switch.++ Args:+ params: Provider params (unused; kept for the provider contract).+ ctx: The per-member build context.++ Returns:+ The send-file tool instances, or an empty list when the capability is+ skipped (missing ids / disabled by config) or construction fails.+ """+ inp = SendFileInput.resolve(params, ctx)+ if not inp.request_id or not inp.channel_id:+ logger.info("[swarm.send_file] skipped: missing request_id or channel_id")+ return []++ if not _is_send_file_enabled({"channels": inp.channels_config}, inp.channel_id):+ logger.info(+ "[swarm.send_file] skipped: send_file_allowed=False for channel=%s",+ inp.channel_id,+ )+ return []++ try:+ toolkit = SendFileToolkit(+ request_id=inp.request_id,+ session_id=inp.session_id,+ channel_id=inp.channel_id,+ metadata=inp.request_metadata,+ )+ tools = list(toolkit.get_tools())+ logger.info(+ "[swarm.send_file] built %d send-file tools for channel=%s",+ len(tools),+ inp.channel_id,+ )+ return tools+ except Exception as exc:+ logger.warning("[swarm.send_file] send-file tool construction failed: %s", exc)+ return []+++__all__ = [+ "CRON_TOOLS",+ "SEND_FILE",+ "build_cron_tools",+ "build_send_file_tools",+]diff --git a/jiuwenswarm/agents/swarm/providers/skills.py b/jiuwenswarm/agents/swarm/providers/skills.pynew file mode 100644index 0000000000..eef3c29c70--- /dev/null+++ b/jiuwenswarm/agents/swarm/providers/skills.py@@ -0,0 +1,243 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Member-skill rail provider for swarm provider-based team assembly.++This module ports the "member skills" branch of the legacy+``team_manager`` customizer into a config-sourced rail provider. The provider+factory links the member's configured skills into the member workspace+``skills`` directory and returns a ``MemberSkillToolkitRail`` bound to the+shared agent workspace, so members share one skill store while each exposes+only its own configured skill view through directory links.++The directory-preparation helpers below are pure functions extracted from the+former customizer closure: the variables the closure captured implicitly+(``global_skills_dir`` / the per-channel team manager) are now explicit+parameters or resolved from the build context.+"""++from __future__ import annotations++import logging+from pathlib import Path+from typing import Any++from openjiuwen.agent_teams.harness.manifest import (+ ConstructionInput,+ context_field,+ ElementKind,+ harness_element,+ param_field,+)++from jiuwenswarm.agents.harness.team.rails.team_member_skill_toolkit_rail import (+ MemberSkillToolkitRail,+)+from jiuwenswarm.agents.harness.team.team_skill_links import (+ is_valid_skill_dir,+ link_skill_dir,+ path_exists_or_link,+ prune_skill_dir_links,+ remove_skill_dir_link,+)+from jiuwenswarm.common.utils import get_agent_workspace_dir+from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager++logger = logging.getLogger(__name__)++# Provider name registered for the member-skill toolkit rail.+MEMBER_SKILL_TOOLKIT = "swarm.member_skill_toolkit"+++def _link_member_configured_skills(+ member_skills_dir: Path,+ selected_skills: list[str],+ global_skills_dir: Path,+) -> None:+ """Link the member's configured skills into its own skills directory.++ Synchronizes the member ``skills`` directory so it holds exactly one+ directory link per selected skill, pruning links for skills no longer+ selected. Skills are linked (not copied) so runtime installs/uninstalls in+ the shared store propagate without stale copies.++ Args:+ member_skills_dir: Member workspace ``skills`` directory.+ selected_skills: Skill names selected for this member.+ global_skills_dir: Global agent skills directory to link from.+ """+ if not global_skills_dir.exists():+ logger.warning(+ "[swarm.member_skill_toolkit] global_skills_dir does not exist: %s",+ global_skills_dir,+ )+ return++ selected_skill_set = set(selected_skills)+ member_skills_dir.mkdir(parents=True, exist_ok=True)+ prune_skill_dir_links(global_skills_dir, member_skills_dir, selected_skill_set)+ linked_count = 0+ for skill_dir in global_skills_dir.iterdir():+ if not is_valid_skill_dir(skill_dir):+ continue+ if skill_dir.name not in selected_skill_set:+ continue+ dest = member_skills_dir / skill_dir.name+ if path_exists_or_link(dest):+ continue+ link_skill_dir(skill_dir, dest)+ linked_count += 1+ logger.info(+ "[swarm.member_skill_toolkit] Linked skill '%s' to member workspace",+ skill_dir.name,+ )++ existing_skill_names = {+ path.name for path in member_skills_dir.iterdir() if path_exists_or_link(path)+ }+ missing = sorted(selected_skill_set - existing_skill_names)+ if missing:+ logger.warning(+ "[swarm.member_skill_toolkit] configured skills not found in global dir: %s",+ missing,+ )++ logger.info(+ "[swarm.member_skill_toolkit] Total configured skills linked to member: %d",+ linked_count,+ )+++def _extract_skill_name_from_tool_result(result: dict[str, object]) -> str:+ """Extract a skill name from a skill tool result.++ Args:+ result: The skill tool invocation result mapping.++ Returns:+ The resolved skill name, or an empty string when none is present.+ """+ skill = result.get("skill")+ if isinstance(skill, dict):+ skill_name = str(skill.get("name", "")).strip()+ if skill_name:+ return skill_name+ return str(result.get("skill_name", "") or result.get("name", "")).strip()+++def _workspace_root(ctx: Any) -> str | None:+ """Resolve the member workspace root path (gate for the toolkit)."""+ workspace = ctx.workspace+ return getattr(workspace, "root_path", None) if workspace else None+++class MemberSkillToolkitInput(ConstructionInput):+ """Construction inputs for the member skill-toolkit rail."""++ skills: list[str] = param_field(+ default_factory=list,+ description="Selected member skill names to expose in the toolkit.",+ )+ workspace_root: str | None = context_field(+ resolver=_workspace_root,+ description="Member workspace root (gate; skipped when absent).",+ )+ global_skills_dir: str | None = context_field(+ attr="global_skills_dir",+ description="Global agent skills directory.",+ )+ session_id: str = context_field(+ attr="session_id",+ default="",+ description="Active session id (for runtime skill-link refresh).",+ )+ channel: str = context_field(+ attr="channel",+ default="default",+ description="Resolved channel key for the per-channel team manager.",+ )+++@harness_element(+ kind=ElementKind.RAIL,+ name=MEMBER_SKILL_TOOLKIT,+ description="Member-scoped skill toolkit rail: prepares the member workspace "+ "skills directory and exposes skill discovery/management.",+ input_model=MemberSkillToolkitInput,+)+def build_member_skill_toolkit(params: dict, ctx: Any) -> object | None:+ """Build a member-scoped skill toolkit rail for the current member.++ Links the member's configured skills into its workspace ``skills``+ directory and returns a ``MemberSkillToolkitRail`` bound to the shared+ agent workspace, wired with a callback that refreshes the link views after+ runtime skill installs/uninstalls.++ Args:+ params: Provider params; ``params["skills"]`` carries the selected+ member skill names (from ``config_specs``).+ ctx: The active ``SwarmBuildContext`` for the current member.++ Returns:+ A ``MemberSkillToolkitRail`` instance, or ``None`` when the member has+ no usable workspace (the capability is skipped for this member).+ """+ inp = MemberSkillToolkitInput.resolve(params, ctx)+ root_path = inp.workspace_root+ if not root_path:+ return None++ member_skills_dir = Path(root_path) / "skills"+ selected_skills = [str(skill).strip() for skill in inp.skills if str(skill).strip()]+ global_skills_dir = Path(inp.global_skills_dir)+ agent_workspace_dir = get_agent_workspace_dir()+ session_id = inp.session_id+ channel = inp.channel++ # Link member-configured skills so the member workspace exposes only that+ # member's skill view (no copies, no per-member skills_state.json).+ try:+ member_skills_dir.mkdir(parents=True, exist_ok=True)+ if selected_skills:+ _link_member_configured_skills(+ member_skills_dir, selected_skills, global_skills_dir+ )+ except Exception as exc:+ logger.warning(+ "[swarm.member_skill_toolkit] skill link refresh failed: %s", exc+ )++ # The skill manager / toolkit operate on the shared agent workspace so+ # installs are shared; each member only sees its own linked view.+ member_skill_manager: Any | None = None+ try:+ member_skill_manager = SkillManager(workspace_dir=str(agent_workspace_dir))+ except Exception as exc:+ logger.warning(+ "[swarm.member_skill_toolkit] member SkillManager setup failed: %s", exc+ )++ def refresh_member_skill_links(result: dict[str, object]) -> None:+ """Refresh linked skill views after a member skill tool mutation."""+ from jiuwenswarm.agents.harness.team.team_manager import get_team_manager++ if result.get("skill_removed") or result.get("removed"):+ skill_name = _extract_skill_name_from_tool_result(result)+ if skill_name:+ remove_skill_dir_link(member_skills_dir / skill_name)+ get_team_manager(channel).refresh_team_shared_skill_links(session_id)++ logger.info(+ "[swarm.member_skill_toolkit] MemberSkillToolkitRail built for skill workspace: %s",+ agent_workspace_dir,+ )+ return MemberSkillToolkitRail(+ workspace_dir=str(agent_workspace_dir),+ manager=member_skill_manager,+ refresh_links=refresh_member_skill_links,+ )+++__all__ = [+ "MEMBER_SKILL_TOOLKIT",+ "build_member_skill_toolkit",+]diff --git a/jiuwenswarm/agents/swarm/providers/tools.py b/jiuwenswarm/agents/swarm/providers/tools.pynew file mode 100644index 0000000000..8be18e54c1--- /dev/null+++ b/jiuwenswarm/agents/swarm/providers/tools.py@@ -0,0 +1,400 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Config-sourced swarm-owned tool providers for team assembly.++Only swarm-owned tools are declared here as individual ``swarm.*`` tool+elements, each self-gated by the config source and filtered against the swarm+``TOOL_WHITELIST``:++* ``swarm.skill_toolkit`` — skill discovery / install / uninstall tools.+* ``swarm.user_todos`` — the personal todo tool.+* ``swarm.video`` — the video-understanding tool (``models.video`` gated).+* ``swarm.image_gen`` — the image-generation tool (``IMAGE_GEN_API_KEY`` gated).+* ``swarm.xiaoyi_phone`` — the xiaoyi phone tools (channel-switch gated).+* ``swarm.code_extra_tools`` — code-mode-exclusive ``acp_chat``.++The generic web / vision / audio tools are provided by openjiuwen+(``core.web_search`` / ``core.web_fetch`` / ``core.web_paid_search`` /+``core.vision`` / ``core.audio``); ``vision_model_config_params`` /+``audio_model_config_params`` here fill the openjiuwen ``VisionModelConfig`` /+``AudioModelConfig`` constructor kwargs from the swarm config + env so+``config_specs`` can bake them into those elements' params.+"""++from __future__ import annotations++import logging+import os+from typing import Any++from openjiuwen.agent_teams.harness.manifest import (+ ConstructionInput,+ context_field,+ ElementKind,+ harness_element,+ param_field,+)++from jiuwenswarm.agents.harness.common.tools.image_tools import generate_image+from jiuwenswarm.agents.harness.common.tools.multimodal_config import (+ apply_audio_model_config_from_yaml,+ apply_image_gen_model_config_from_yaml,+ apply_video_model_config_from_yaml,+ apply_vision_model_config_from_yaml,+ dedicated_multimodal_model_configured,+)+from jiuwenswarm.agents.harness.common.tools.skill_toolkits import SkillToolkit+from jiuwenswarm.agents.harness.common.tools.user_todo_tool import get_decorated_tools+from jiuwenswarm.agents.harness.common.tools.video_tools import video_understanding+from jiuwenswarm.agents.harness.common.tools.xiaoyi_phone_tools import (+ add_collection,+ call_phone,+ convert_timestamp_to_utc8_time,+ create_alarm,+ create_calendar_event,+ create_note,+ delete_alarm,+ delete_collection,+ get_user_location,+ image_reading,+ modify_alarm,+ modify_note,+ query_collection,+ save_file_to_file_manager,+ save_media_to_gallery,+ search_alarms,+ search_calendar_event,+ search_contact,+ search_file,+ search_message,+ search_notes,+ search_photo_gallery,+ send_message,+ upload_file,+ upload_photo,+ view_push_result,+ xiaoyi_gui_agent,+)+from jiuwenswarm.agents.harness.team.team_runtime_inheritance import TOOL_WHITELIST+from jiuwenswarm.agents.swarm.context import SwarmBuildContext+from jiuwenswarm.server.runtime.skill.skill_manager import SkillManager++logger = logging.getLogger(__name__)++# Provider name constants; namespaced under the shared "swarm." prefix.+SKILL_TOOLKIT = "swarm.skill_toolkit"+USER_TODOS = "swarm.user_todos"+VIDEO = "swarm.video"+IMAGE_GEN = "swarm.image_gen"+XIAOYI_PHONE = "swarm.xiaoyi_phone"+CODE_EXTRA_TOOLS = "swarm.code_extra_tools"++# xiaoyi phone tool objects, gated by ``channels.xiaoyi.phone_tools_enabled``.+_XIAOYI_PHONE_TOOLS = (+ get_user_location,+ create_note,+ search_notes,+ modify_note,+ create_calendar_event,+ search_calendar_event,+ search_contact,+ search_photo_gallery,+ upload_photo,+ search_file,+ upload_file,+ call_phone,+ send_message,+ search_message,+ create_alarm,+ search_alarms,+ modify_alarm,+ delete_alarm,+ query_collection,+ add_collection,+ delete_collection,+ save_media_to_gallery,+ save_file_to_file_manager,+ convert_timestamp_to_utc8_time,+ view_push_result,+ image_reading,+ xiaoyi_gui_agent,+)+++def _filter_whitelist(tools: list[Any]) -> list[Any]:+ """Keep only tools whose ``card.name`` is in the swarm ``TOOL_WHITELIST``."""+ return [tool for tool in tools if tool.card.name in TOOL_WHITELIST]+++def _mark_stateless(tools: list[Any]) -> list[Any]:+ """Flag module-level singleton tools as stateless.++ These tools are shared ``@tool`` singletons (no per-agent/session state), so+ they are registered once under their bare id and shared across members+ rather than agent-qualified. Without this flag the harness would treat them+ as agent-owned and rewrite the shared card id per member, corrupting it.+ """+ for tool in tools:+ card = getattr(tool, "card", None)+ if card is not None:+ card.stateless = True+ return tools+++def _workspace_root(ctx: SwarmBuildContext) -> str | None:+ """Resolve the member workspace root path (None when absent)."""+ return getattr(ctx.workspace, "root_path", None) if ctx.workspace else None+++def _parse_int(value: Any, default: int) -> int:+ """Parse an int from a possibly-None/str value, falling back to ``default``."""+ try:+ return int(str(value).strip())+ except (TypeError, ValueError):+ return default+++# ---------------------------------------------------------------------------+# openjiuwen vision / audio config filling. The tool elements live in+# openjiuwen (``core.vision`` / ``core.audio``); these helpers fill the+# openjiuwen config-constructor kwargs from the swarm config + env so+# ``config_specs`` can bake them into the elements' params.+# ---------------------------------------------------------------------------+++def vision_model_config_params(config: dict[str, Any]) -> dict[str, Any]:+ """Return ``VisionModelConfig`` constructor kwargs, or {} when unconfigured.++ Requires a dedicated ``models.vision`` key and a complete ``VISION_*`` env+ mapping after applying the yaml config (mirrors the single-agent build).+ """+ if not dedicated_multimodal_model_configured(config, "vision"):+ return {}+ apply_vision_model_config_from_yaml(config)+ api_key = str(os.getenv("VISION_API_KEY", "")).strip()+ base_url = str(+ os.getenv("VISION_BASE_URL") or os.getenv("VISION_API_BASE") or ""+ ).strip()+ model_name = str(+ os.getenv("VISION_MODEL") or os.getenv("VISION_MODEL_NAME") or ""+ ).strip()+ if not api_key or not base_url or not model_name:+ return {}+ return {+ "api_key": api_key,+ "base_url": base_url,+ "model": model_name,+ "max_retries": _parse_int(os.getenv("VISION_MAX_RETRIES"), 3),+ }+++def audio_dedicated_configured(config: dict[str, Any]) -> bool:+ """Return whether a dedicated audio model is configured."""+ return dedicated_multimodal_model_configured(config, "audio")+++def audio_model_config_params(config: dict[str, Any]) -> dict[str, Any]:+ """Return ``AudioModelConfig`` constructor kwargs, or {} when incomplete.++ Empty result with a dedicated key present means the core ``audio`` element+ keeps only ``audio_metadata`` (the degraded fallback).+ """+ if not dedicated_multimodal_model_configured(config, "audio"):+ return {}+ apply_audio_model_config_from_yaml(config)+ api_key = str(os.getenv("AUDIO_API_KEY", "")).strip()+ base_url = str(+ os.getenv("AUDIO_BASE_URL") or os.getenv("AUDIO_API_BASE") or ""+ ).strip()+ if not api_key or not base_url:+ return {}+ transcription_model = str(+ os.getenv("AUDIO_TRANSCRIPTION_MODEL") or os.getenv("AUDIO_MODEL_NAME") or "",+ ).strip()+ question_answering_model = str(+ os.getenv("AUDIO_QUESTION_ANSWERING_MODEL")+ or os.getenv("AUDIO_MODEL_NAME")+ or "",+ ).strip()+ config_kwargs: dict[str, Any] = {+ "api_key": api_key,+ "base_url": base_url,+ "max_retries": _parse_int(os.getenv("AUDIO_MAX_RETRIES"), 3),+ "http_timeout": _parse_int(os.getenv("AUDIO_HTTP_TIMEOUT"), 20),+ "max_audio_bytes": _parse_int(+ os.getenv("AUDIO_MAX_AUDIO_BYTES"), 25 * 1024 * 1024+ ),+ }+ acr_access_key = str(os.getenv("ACR_ACCESS_KEY", "")).strip()+ acr_access_secret = str(os.getenv("ACR_ACCESS_SECRET", "")).strip()+ acr_base_url = str(os.getenv("ACR_BASE_URL", "")).strip()+ if acr_access_key:+ config_kwargs["acr_access_key"] = acr_access_key+ if acr_access_secret:+ config_kwargs["acr_access_secret"] = acr_access_secret+ if acr_base_url:+ config_kwargs["acr_base_url"] = acr_base_url+ if transcription_model:+ config_kwargs["transcription_model"] = transcription_model+ if question_answering_model:+ config_kwargs["question_answering_model"] = question_answering_model+ return config_kwargs+++# ---------------------------------------------------------------------------+# Swarm-owned tool builders (unfiltered) + provider elements (whitelist-filtered).+# ---------------------------------------------------------------------------+++def _build_skill_toolkit_tools(workspace_root: str | None) -> list[Any]:+ """Build the skill-management tools bound to the member workspace."""+ try:+ manager = SkillManager(workspace_dir=workspace_root)+ toolkit = SkillToolkit(manager=manager)+ return list(toolkit.get_tools())+ except Exception as exc:+ logger.warning("[swarm.skill_toolkit] construction failed: %s", exc)+ return []+++def _build_user_todo_tools() -> list[Any]:+ """Build the user's personal todo tool."""+ try:+ return _mark_stateless(list(get_decorated_tools()))+ except Exception as exc:+ logger.warning("[swarm.user_todos] construction failed: %s", exc)+ return []+++def _build_video_tools(ctx: SwarmBuildContext) -> list[Any]:+ """Build the video understanding tool when ``models.video`` is configured."""+ config = ctx.config or {}+ apply_video_model_config_from_yaml(config)+ if not dedicated_multimodal_model_configured(config, "video"):+ return []+ if not os.getenv("VIDEO_API_KEY"):+ return []+ return _mark_stateless([video_understanding])+++def _build_image_gen_tools(ctx: SwarmBuildContext) -> list[Any]:+ """Build the image-generation tool when ``models.image_gen`` is configured."""+ apply_image_gen_model_config_from_yaml(ctx.config or {})+ if not os.getenv("IMAGE_GEN_API_KEY"):+ return []+ return _mark_stateless([generate_image])+++def _build_xiaoyi_phone_tools(ctx: SwarmBuildContext) -> list[Any]:+ """Build xiaoyi phone tools when ``channels.xiaoyi.phone_tools_enabled``."""+ config = ctx.config or {}+ enabled = (+ config.get("channels", {}).get("xiaoyi", {}).get("phone_tools_enabled", False)+ )+ if not enabled:+ return []+ return _mark_stateless(list(_XIAOYI_PHONE_TOOLS))+++class SkillToolkitInput(ConstructionInput):+ """Construction inputs for the skill-toolkit tool."""++ workspace_root: str | None = context_field(+ resolver=_workspace_root,+ description="Member workspace root; the SkillManager resolves skills from it.",+ )+++@harness_element(+ kind=ElementKind.TOOL,+ name=SKILL_TOOLKIT,+ description="Skill discovery / install / uninstall tools bound to the member workspace.",+ input_model=SkillToolkitInput,+)+def build_skill_toolkit(params: dict[str, Any], ctx: SwarmBuildContext) -> list[Any]:+ """Build the whitelist-filtered skill toolkit tools."""+ inp = SkillToolkitInput.resolve(params, ctx)+ return _filter_whitelist(_build_skill_toolkit_tools(inp.workspace_root))+++@harness_element(+ kind=ElementKind.TOOL,+ name=USER_TODOS,+ description="The user's personal todo tool.",+)+def build_user_todos(params: dict[str, Any], ctx: SwarmBuildContext) -> list[Any]:+ """Build the whitelist-filtered user todo tools."""+ return _filter_whitelist(_build_user_todo_tools())+++@harness_element(+ kind=ElementKind.TOOL,+ name=VIDEO,+ description="Video-understanding tool (built only when models.video is configured).",+)+def build_video_tools(params: dict[str, Any], ctx: SwarmBuildContext) -> list[Any]:+ """Build the whitelist-filtered video tools."""+ return _filter_whitelist(_build_video_tools(ctx))+++@harness_element(+ kind=ElementKind.TOOL,+ name=IMAGE_GEN,+ description="Image-generation tool (built only when IMAGE_GEN_API_KEY is set).",+)+def build_image_gen_tools(params: dict[str, Any], ctx: SwarmBuildContext) -> list[Any]:+ """Build the whitelist-filtered image-generation tools."""+ return _filter_whitelist(_build_image_gen_tools(ctx))+++@harness_element(+ kind=ElementKind.TOOL,+ name=XIAOYI_PHONE,+ description="xiaoyi phone tools (built only when the channel switch is on).",+)+def build_xiaoyi_phone(params: dict[str, Any], ctx: SwarmBuildContext) -> list[Any]:+ """Build the whitelist-filtered xiaoyi phone tools."""+ return _filter_whitelist(_build_xiaoyi_phone_tools(ctx))+++class CodeExtraToolsInput(ConstructionInput):+ """Construction inputs for the code-extra tools."""++ acp_enabled: bool = param_field(+ default=False,+ description="Whether acp_agents is configured (gates acp_chat).",+ )+++@harness_element(+ kind=ElementKind.TOOL,+ name=CODE_EXTRA_TOOLS,+ description="Code-mode-exclusive tools (currently acp_chat).",+ input_model=CodeExtraToolsInput,+)+def build_code_extra_tools(params: dict[str, Any], ctx: SwarmBuildContext) -> list[Any]:+ """Build code-mode-exclusive tools (currently ``acp_chat``) from the config source."""+ inp = CodeExtraToolsInput.resolve(params, ctx)+ if not inp.acp_enabled:+ return []+ try:+ from jiuwenswarm.agents.harness.common.tools.acp_chat import acp_chat++ return [acp_chat]+ except Exception as exc:+ logger.warning("[swarm.code_extra_tools] acp_chat construction failed: %s", exc)+ return []+++__all__ = [+ "SKILL_TOOLKIT",+ "USER_TODOS",+ "VIDEO",+ "IMAGE_GEN",+ "XIAOYI_PHONE",+ "CODE_EXTRA_TOOLS",+ "vision_model_config_params",+ "audio_dedicated_configured",+ "audio_model_config_params",+ "build_code_extra_tools",+]diff --git a/jiuwenswarm/agents/swarm/registry.py b/jiuwenswarm/agents/swarm/registry.pynew file mode 100644index 0000000000..cd5fd3305a--- /dev/null+++ b/jiuwenswarm/agents/swarm/registry.py@@ -0,0 +1,223 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Central registration for swarm capability providers and rail types.++``register_swarm_providers`` wires the whole provider-based assembly into+openjiuwen's registries once per process. Importing the provider modules runs+their ``@harness_element`` declarations, which populate the manifest catalog+(the single source of truth for element metadata). ``register_swarm_providers``+then drives the openjiuwen registration from that catalog via+``register_from_catalog`` — tools, factory rails, the unified class rails (all+through ``register_rail_provider``), and sub-agents — and registers the+build-context seed factory.++The provider name constants are re-exported here so ``config_specs`` can build+``RailSpec`` / ``BuiltinToolSpec`` references without hard-coding strings.+"""++from __future__ import annotations++from typing import Any++from openjiuwen.agent_evolving.trajectory import InMemoryTrajectoryRegistry+from openjiuwen.agent_teams.harness.manifest import register_from_catalog+from openjiuwen.agent_teams.rails.builtin_elements import (+ AUDIO as _OJ_AUDIO,+ CONFIRM_INTERRUPT as _OJ_CONFIRM_INTERRUPT,+ HEARTBEAT as _OJ_HEARTBEAT,+ LSP as _OJ_LSP,+ SECURITY as _OJ_SECURITY,+ SYS_OPERATION as _OJ_SYS_OPERATION,+ TASK_PLANNING as _OJ_TASK_PLANNING,+ VISION as _OJ_VISION,+ WEB_FETCH as _OJ_WEB_FETCH,+ WEB_PAID_SEARCH as _OJ_WEB_PAID_SEARCH,+ WEB_SEARCH as _OJ_WEB_SEARCH,+ WORKTREE as _OJ_WORKTREE,+)+from openjiuwen.agent_teams.rails.registration import (+ ensure_harness_elements_registered,+)+from openjiuwen.agent_teams.rails.subagent_elements import (+ BROWSER_AGENT as _OJ_BROWSER_AGENT,+ EXPLORE_AGENT as _OJ_EXPLORE_AGENT,+ PLAN_AGENT as _OJ_PLAN_AGENT,+)+from openjiuwen.agent_teams.schema.build_context import register_build_context_factory++from jiuwenswarm.agents.swarm.context import SwarmBuildContext+from jiuwenswarm.agents.swarm.providers import (+ builtin_rails as _builtin_rails,+ code_rails as _code_rails,+ code_subagents as _code_subagents,+ evolution_rails as _evolution_rails,+ member_rails as _member_rails,+ runtime_tools as _runtime_tools,+ skills as _skills,+ tools as _tools,+)+from jiuwenswarm.common.config import get_config++# Re-exported provider name constants for config_specs to reference by symbol.+# Swarm-owned tools (each self-gated by config + whitelist-filtered).+SKILL_TOOLKIT = _tools.SKILL_TOOLKIT+USER_TODOS = _tools.USER_TODOS+VIDEO = _tools.VIDEO+IMAGE_GEN = _tools.IMAGE_GEN+XIAOYI_PHONE = _tools.XIAOYI_PHONE+CRON_TOOLS = _runtime_tools.CRON_TOOLS+SEND_FILE = _runtime_tools.SEND_FILE+MEMBER_SKILL_TOOLKIT = _skills.MEMBER_SKILL_TOOLKIT+# Generic tools provided + registered by openjiuwen (referenced by bare name).+WEB_SEARCH = _OJ_WEB_SEARCH+WEB_FETCH = _OJ_WEB_FETCH+WEB_PAID_SEARCH = _OJ_WEB_PAID_SEARCH+VISION = _OJ_VISION+AUDIO = _OJ_AUDIO+RUNTIME_PROMPT = _member_rails.RUNTIME_PROMPT+TEAM_WORKSPACE_REPORT_PATH = _member_rails.TEAM_WORKSPACE_REPORT_PATH+CONTEXT_PROCESSOR = _member_rails.CONTEXT_PROCESSOR+PLUGIN_RAILS = _member_rails.PLUGIN_RAILS+TEAM_SKILL_EVOLUTION = _evolution_rails.TEAM_SKILL_EVOLUTION+TEAM_SKILL_CREATE = _evolution_rails.TEAM_SKILL_CREATE+MEMBER_SKILL_EVOLUTION = _evolution_rails.MEMBER_SKILL_EVOLUTION++# Code-mode (code.team / team.plan) swarm-owned rail provider names.+CODE_EXTRA_TOOLS = _tools.CODE_EXTRA_TOOLS+CODE_RUNTIME_PROMPT = _code_rails.CODE_RUNTIME_PROMPT+CODE_PROJECT_MEMORY = _code_rails.CODE_PROJECT_MEMORY+PERMISSION_INTERRUPT = _code_rails.PERMISSION_INTERRUPT+CODE_CODING_MEMORY = _code_rails.CODE_CODING_MEMORY+CODE_AGENT_MODE = _code_rails.CODE_AGENT_MODE+STRUCTURED_ASK_USER = _code_rails.STRUCTURED_ASK_USER+CODE_TASK_PLANNING = _code_rails.CODE_TASK_PLANNING+CODE_AGENT_RAIL = _code_rails.CODE_AGENT_RAIL+USER_HOOKS = _code_rails.USER_HOOKS+CODE_SKILL_USE = _code_rails.CODE_SKILL_USE++# Sub-agent provider names (resolved via SubAgentSpec.factory_name). explore /+# plan / browser are provided by openjiuwen; code_agent stays swarm-side (reuses+# the swarm CodingMemoryRail).+EXPLORE_AGENT = _OJ_EXPLORE_AGENT+PLAN_AGENT = _OJ_PLAN_AGENT+BROWSER_AGENT = _OJ_BROWSER_AGENT+CODE_AGENT = _code_subagents.CODE_AGENT++# Swarm-owned no-parameter class rails declared in ``builtin_rails``.+RESPONSE_PROMPT = _builtin_rails.RESPONSE_PROMPT+STREAM_EVENT = _builtin_rails.STREAM_EVENT+AVATAR_PROMPT = _builtin_rails.AVATAR_PROMPT++# Generic rails provided + registered by openjiuwen (referenced by bare name).+SYS_OPERATION = _OJ_SYS_OPERATION+TASK_PLANNING = _OJ_TASK_PLANNING+SECURITY = _OJ_SECURITY+HEARTBEAT = _OJ_HEARTBEAT+CODE_LSP = _OJ_LSP+CODE_CONFIRM_INTERRUPT = _OJ_CONFIRM_INTERRUPT+CODE_WORKTREE = _OJ_WORKTREE++_REGISTERED = False++# Per-(session_id, team_id) trajectory registries, so members of the same team+# rebuilt in one process share evolution state while different processes / teams+# stay isolated. Populated lazily; grows with the process's distinct teams.+_TRAJECTORY_REGISTRIES: dict[tuple[str, str], Any] = {}+++def _trajectory_registry_for(seed: dict[str, Any]) -> Any:+ """Return a process-local trajectory registry for the seed's team."""+ key = (str(seed.get("session_id") or ""), str(seed.get("team_id") or ""))+ registry = _TRAJECTORY_REGISTRIES.get(key)+ if registry is None:+ registry = InMemoryTrajectoryRegistry()+ _TRAJECTORY_REGISTRIES[key] = registry+ return registry+++def _build_swarm_context_from_seed(seed: dict[str, Any]) -> SwarmBuildContext:+ """Rebuild a :class:`SwarmBuildContext` from a serializable seed.++ Sources the non-serializable handles from the receiving process: ``config``+ from this process's ``config.yaml`` and a per-team ``trajectory_registry``.+ Registered with openjiuwen so ``from_spawn_payload`` / ``recover_from_session``+ restore the provider build context after deserialization.+ """+ return SwarmBuildContext.from_seed(+ seed,+ config=get_config(),+ trajectory_registry=_trajectory_registry_for(seed),+ )+++def register_swarm_providers() -> None:+ """Register all swarm providers and rail types with openjiuwen (idempotent).++ Importing this module (and the provider modules above) runs the+ ``@harness_element`` declarations that populate the manifest catalog. This+ function drives the actual openjiuwen registration from that catalog and+ wires the build-context seed factory. Safe to call multiple times, but only+ the first call performs the registration.+ """+ global _REGISTERED+ if _REGISTERED:+ return++ # Ensure the openjiuwen built-in rails / tools / sub-agents this platform+ # references by bare name (sys_operation / task_planning / confirm_interrupt /+ # worktree / lsp / explore_agent / ...) are declared and registered.+ ensure_harness_elements_registered()+ register_from_catalog()+ register_build_context_factory(_build_swarm_context_from_seed)++ _REGISTERED = True+++__all__ = [+ "register_swarm_providers",+ "SKILL_TOOLKIT",+ "USER_TODOS",+ "VIDEO",+ "IMAGE_GEN",+ "XIAOYI_PHONE",+ "WEB_SEARCH",+ "WEB_FETCH",+ "WEB_PAID_SEARCH",+ "VISION",+ "AUDIO",+ "CRON_TOOLS",+ "SEND_FILE",+ "MEMBER_SKILL_TOOLKIT",+ "RUNTIME_PROMPT",+ "TEAM_WORKSPACE_REPORT_PATH",+ "CONTEXT_PROCESSOR",+ "PLUGIN_RAILS",+ "TEAM_SKILL_EVOLUTION",+ "TEAM_SKILL_CREATE",+ "MEMBER_SKILL_EVOLUTION",+ "RESPONSE_PROMPT",+ "SYS_OPERATION",+ "STREAM_EVENT",+ "TASK_PLANNING",+ "SECURITY",+ "HEARTBEAT",+ "AVATAR_PROMPT",+ "CODE_EXTRA_TOOLS",+ "CODE_RUNTIME_PROMPT",+ "CODE_LSP",+ "CODE_PROJECT_MEMORY",+ "PERMISSION_INTERRUPT",+ "CODE_CODING_MEMORY",+ "CODE_AGENT_MODE",+ "STRUCTURED_ASK_USER",+ "CODE_CONFIRM_INTERRUPT",+ "CODE_TASK_PLANNING",+ "CODE_AGENT_RAIL",+ "USER_HOOKS",+ "CODE_SKILL_USE",+ "CODE_WORKTREE",+ "EXPLORE_AGENT",+ "PLAN_AGENT",+ "CODE_AGENT",+ "BROWSER_AGENT",+]diff --git a/jiuwenswarm/server/runtime/agent_adapter/code_agent_rail.py b/jiuwenswarm/server/runtime/agent_adapter/code_agent_rail.pyindex d166803763..b9038541d9 100644--- a/jiuwenswarm/server/runtime/agent_adapter/code_agent_rail.py+++ b/jiuwenswarm/server/runtime/agent_adapter/code_agent_rail.py@@ -16,7 +16,6 @@ from openjiuwen.core.common.exception.codes import StatusCodefrom openjiuwen.core.common.exception.errors import build_errorfrom openjiuwen.core.common.logging import loggerfrom openjiuwen.core.foundation.tool import Tool, ToolCard-from openjiuwen.core.runner import Runnerfrom openjiuwen.harness.rails.base import DeepAgentRailfrom openjiuwen.harness.tools.base_tool import ToolOutputfrom openjiuwen.harness.workspace.workspace import Workspace@@ -384,8 +383,10 @@ class CodeAgentRail(DeepAgentRail):parent_agent=self._agent,custom_agents=custom_agents,)- Runner.resource_mgr.add_tool([self._agent_tool])- self._agent.ability_manager.add(self._agent_tool.card)+ # Unified registration: add_ability qualifies the stateful tool id and+ # binds it in the resource manager, so teardown_tools drops it at+ # round-end instead of leaking a bare id that refresh-warns on rebuild.+ self._agent.ability_manager.add_ability(self._agent_tool.card, self._agent_tool)logger.info("[CodeAgentRail] Agent tool registered with %d custom agent(s): %s",len(custom_agents),@@ -399,15 +400,11 @@ class CodeAgentRail(DeepAgentRail):name = getattr(self._agent_tool.card, "name", None)if name:try:- agent.ability_manager.remove(name)+ # Mirror add_ability: removes the agent-qualified id from+ # both this manager and the shared resource manager.+ agent.ability_manager.remove_ability(name)except Exception as e:- logger.debug("Failed to remove agent tool '%s' from ability_manager: %s", name, e)- tool_id = self._agent_tool.card.id- if tool_id:- try:- Runner.resource_mgr.remove_tool(tool_id)- except Exception as e:- logger.debug("Failed to remove tool '%s' from resource_mgr: %s", tool_id, e)+ logger.debug("Failed to remove agent tool '%s': %s", name, e)self._agent_tool = Nonedef _load_custom_agents(self) -> list:diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py b/jiuwenswarm/server/runtime/agent_adapter/interface_code.pyindex 9b7b942702..bb6b0f87f6 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_code.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_code.py@@ -173,6 +173,25 @@ implementing the approved plan.</system-reminder>"""+class JiuwenAgentModeRail(AgentModeRail):+ """AgentModeRail preconfigured with jiuwenswarm's code plan-mode contract.++ Bakes in the Claude-Code-aligned plan-mode behavior (switch_mode disabled,+ static plan-mode system note, enter/exit plan instructions) so both the+ legacy adapter path and the declarative swarm provider construct an+ identical rail without duplicating configuration.+ """++ def __init__(self) -> None:+ """Initialize the rail with the fixed code plan-mode configuration."""+ super().__init__(+ allow_switch_mode=False,+ plan_mode_system_note=_PLAN_MODE_SYSTEM_NOTE,+ enter_plan_instructions=_ENTER_PLAN_MODE_INSTRUCTIONS_EN,+ exit_plan_notification=_EXIT_PLAN_MODE_NOTIFICATION,+ )++# 名字 → 构建方法映射(rail/tool 名字与类方法名对照)_RAIL_BUILD_NAMES: dict[str, str] = {"SysOperationRail": "_build_filesystem_rail",@@ -627,12 +646,7 @@ class JiuwenClawCodeAdapter(JiuWenClawDeepAdapter):def _build_agent_mode_rail(self) -> AgentModeRail | None:"""构建 AgentModeRail(屏蔽 switch_mode + 静态 plan 提示词 + plan 指令进对话)."""try:- return AgentModeRail(- allow_switch_mode=False,- plan_mode_system_note=_PLAN_MODE_SYSTEM_NOTE,- enter_plan_instructions=_ENTER_PLAN_MODE_INSTRUCTIONS_EN,- exit_plan_notification=_EXIT_PLAN_MODE_NOTIFICATION,- )+ return JiuwenAgentModeRail()except Exception as exc:logger.warning("[JiuwenClawCodeAdapter] AgentModeRail create failed: %s", exc)return Nonediff --git a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.pyindex b9e6e7f9c0..68e972f305 100644--- a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py+++ b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py@@ -728,14 +728,16 @@ async def process_team_message_stream(returntry:- if deep_agent is None:- raise RuntimeError("DeepAgent not initialized")request_metadata = dict(request.metadata or {})if isinstance(getattr(request, "params", None), dict):request_metadata.setdefault("mode", request.params.get("mode"))- team_spec = await team_manager.get_enriched_team_spec(+ resolved_mode = str(request_metadata.get("mode") or "").strip()+ # Provider-based assembly: build members from the shared config source,+ # no pre-built parent DeepAgent required.+ team_spec = await team_manager.get_swarm_enriched_team_spec(session_id=session_id,- deep_agent=deep_agent,+ mode=resolved_mode,+ project_dir=request_metadata.get("project_dir"),request_id=rid,channel_id=channel_id,request_metadata=request_metadata,diff --git a/tests/agents/__init__.py b/tests/agents/__init__.pynew file mode 100644index 0000000000..fc7f53948b--- /dev/null+++ b/tests/agents/__init__.py@@ -0,0 +1 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.diff --git a/tests/agents/swarm/__init__.py b/tests/agents/swarm/__init__.pynew file mode 100644index 0000000000..fc7f53948b--- /dev/null+++ b/tests/agents/swarm/__init__.py@@ -0,0 +1 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.diff --git a/tests/agents/swarm/test_manifest_catalog.py b/tests/agents/swarm/test_manifest_catalog.pynew file mode 100644index 0000000000..b0d52a9112--- /dev/null+++ b/tests/agents/swarm/test_manifest_catalog.py@@ -0,0 +1,310 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Tests for the swarm harness-element manifest catalog.++Covers the serializable descriptor catalog: parity with the registry name+constants and the openjiuwen registries, reflective factory resolution, params+schema validation, JSON round-trip, idempotent registration, interface-method+introspection, and the unification of class rails with factory rails.+"""++from __future__ import annotations++import inspect+import json+import logging++import pytest+from pydantic import ValidationError++from openjiuwen.agent_teams.schema import deep_agent_spec as das+from openjiuwen.agent_teams.schema.deep_agent_spec import RailSpec++from jiuwenswarm.agents.swarm import register_swarm_providers, registry+from jiuwenswarm.agents.swarm.context import SwarmBuildContext+from openjiuwen.agent_teams.harness.manifest import (+ ElementKind,+ HarnessElementDescriptor,+ factory_ref,+ get_catalog,+ list_elements,+ register_from_catalog,+ resolve_factory,+)++logger = logging.getLogger(__name__)+++def _registry_swarm_names() -> set[str]:+ """Collect every ``swarm.*`` element-name constant exported by ``registry``."""+ return {+ value+ for value in vars(registry).values()+ if isinstance(value, str) and value.startswith("swarm.")+ }+++def _swarm_keys(registry_dict: dict) -> set[str]:+ """Return the ``swarm.*`` keys of an openjiuwen provider/type registry."""+ return {key for key in registry_dict if key.startswith("swarm.")}+++def _swarm_catalog() -> dict[str, HarnessElementDescriptor]:+ """Return only the ``swarm.*`` descriptors from the shared global catalog.++ The catalog is process-global and also holds openjiuwen's built-in elements+ (``task_planning`` / ``team.tool`` / ...), so swarm tests scope to the+ ``swarm.*`` namespace they own.+ """+ return {+ name: descriptor+ for name, descriptor in get_catalog().items()+ if name.startswith("swarm.")+ }+++def test_every_registry_name_has_descriptor() -> None:+ """The catalog covers exactly the registry's ``swarm.*`` name constants."""+ register_swarm_providers()+ names = _registry_swarm_names()+ catalog = _swarm_catalog()++ for name in names:+ assert name in catalog, f"missing descriptor for {name}"+ extra = set(catalog) - names+ assert not extra, f"descriptors without a registry constant: {extra}"+ logger.info("parity: %d registry names == %d descriptors", len(names), len(catalog))+++def test_catalog_matches_openjiuwen_registries() -> None:+ """Every descriptor is registered into the matching openjiuwen registry."""+ register_swarm_providers()++ for descriptor in _swarm_catalog().values():+ if descriptor.kind is ElementKind.TOOL:+ assert descriptor.name in das._TOOL_PROVIDER_REGISTRY, descriptor.name+ elif descriptor.kind is ElementKind.RAIL:+ assert descriptor.name in das._RAIL_PROVIDER_REGISTRY, descriptor.name+ elif descriptor.kind is ElementKind.SUBAGENT:+ assert descriptor.name in das._SUBAGENT_PROVIDER_REGISTRY, descriptor.name+++def test_factory_ref_resolves_for_every_descriptor() -> None:+ """Each ``factory_ref`` resolves back to a callable/class with a stable ref."""+ for descriptor in _swarm_catalog().values():+ target = resolve_factory(descriptor.factory_ref)+ assert callable(target), descriptor.name+ assert factory_ref(target) == descriptor.factory_ref, descriptor.name+++ ("name", "good", "bad"),+ [+ (+ registry.CODE_CONFIRM_INTERRUPT,+ {"tool_names": ["switch_mode"]},+ {"tool_names": 123},+ ),+ (registry.MEMBER_SKILL_TOOLKIT, {"skills": ["alpha"]}, {"skills": 7}),+ (registry.EXPLORE_AGENT, {"max_iterations": 20}, {"max_iterations": "many"}),+ (+ registry.PERMISSION_INTERRUPT,+ {"permissions_config": {"enabled": True}, "model_name": "gpt-4"},+ {"model_name": 123},+ ),+ (registry.CODE_SKILL_USE, {"skill_mode": "all"}, {"skill_mode": 5}),+ ],+)+def test_input_schema_validates(name: str, good: dict, bad: dict) -> None:+ """Parameterized elements expose an input model that validates good/bad input."""+ descriptor = get_catalog()[name]+ assert descriptor.input_model_ref is not None, name++ model = resolve_factory(descriptor.input_model_ref)+ model.model_validate(good)+ with pytest.raises(ValidationError):+ model.model_validate(bad)+ assert descriptor.input_schema == model.model_json_schema()+++def test_every_input_schema_property_is_source_tagged() -> None:+ """Every input field declares its source (params / context) in the schema."""+ for descriptor in _swarm_catalog().values():+ for prop_name, prop in descriptor.input_schema.get("properties", {}).items():+ where = f"{descriptor.name}.{prop_name}"+ assert prop.get("source") in {"params", "context"}, where+ if prop["source"] == "context":+ assert "context_attr" in prop or "resolver_ref" in prop, where+++def test_every_resolver_ref_resolves() -> None:+ """Every context resolver_ref reflects back to a callable."""+ for descriptor in _swarm_catalog().values():+ for prop in descriptor.input_schema.get("properties", {}).values():+ ref = prop.get("resolver_ref")+ if ref is not None:+ assert callable(resolve_factory(ref)), ref+++def test_input_resolve_extracts_from_params_and_context() -> None:+ """``Input.resolve`` pulls each field from params / context as declared."""+ from jiuwenswarm.agents.swarm.context import SwarmBuildContext+ from jiuwenswarm.agents.swarm.providers.code_rails import CodeProjectMemoryInput+ from jiuwenswarm.agents.swarm.providers.member_rails import RuntimePromptInput++ ctx = SwarmBuildContext(language="cn", channel="web", project_dir="/tmp/proj")++ prompt = RuntimePromptInput.resolve({}, ctx)+ assert (prompt.language, prompt.channel) == ("cn", "web")++ # Context-sourced field (project_dir resolver) plus a params-sourced field.+ memory = CodeProjectMemoryInput.resolve({}, ctx)+ assert memory.project_dir == "/tmp/proj"+ assert memory.additional_directories == []+ assert CodeProjectMemoryInput.resolve(+ {"additional_directories": ["/x"]}, ctx+ ).additional_directories == ["/x"]+++def test_attribute_fields_are_params_env_fields_are_context() -> None:+ """Config-derived attributes are params; per-request runtime values are context."""+ catalog = get_catalog()+ expected = {+ registry.CODE_SKILL_USE: {"skill_mode": "params"},+ registry.PERMISSION_INTERRUPT: {+ "permissions_config": "params",+ "model_name": "params",+ },+ registry.CODE_CODING_MEMORY: {+ "embed_config": "params",+ "project_dir": "context",+ "workspace_root": "context",+ },+ registry.SEND_FILE: {"channels_config": "params", "channel_id": "context"},+ registry.CONTEXT_PROCESSOR: {+ "context_engine_enabled": "params",+ "context_engine_config": "params",+ },+ registry.TEAM_SKILL_EVOLUTION: {+ "evolution_model_config": "params",+ "auto_scan": "params",+ "team_skills_dir": "context",+ "trajectory_registry": "context",+ },+ registry.TEAM_SKILL_CREATE: {"skill_create": "params"},+ }+ for name, fields in expected.items():+ props = catalog[name].input_schema["properties"]+ for field, want in fields.items():+ assert props[field]["source"] == want, f"{name}.{field}"+++def test_config_specs_bakes_attribute_params() -> None:+ """config_specs projects config-derived attributes into spec ``params``."""+ from openjiuwen.harness.rails import SkillUseRail++ from jiuwenswarm.agents.swarm.config_specs import build_member_capability_specs++ config = {+ "react": {"skill_mode": SkillUseRail.SKILL_MODE_AUTO_LIST},+ "permissions": {"enabled": True},+ "models": {"default": {"model_client_config": {"model_name": "gpt-4o"}}},+ }+ rails, _ = build_member_capability_specs(config, "code.team", "leader")+ by_type = {spec.type: spec.params for spec in rails}++ assert (+ by_type[registry.CODE_SKILL_USE]["skill_mode"]+ == SkillUseRail.SKILL_MODE_AUTO_LIST+ )+ assert by_type[registry.PERMISSION_INTERRUPT]["permissions_config"] == {+ "enabled": True+ }+ assert by_type[registry.PERMISSION_INTERRUPT]["model_name"] == "gpt-4o"+ assert (+ by_type[registry.TEAM_SKILL_EVOLUTION]["evolution_model_config"]["model_name"]+ == "gpt-4o"+ )+++def test_descriptor_json_round_trip() -> None:+ """Every descriptor round-trips through JSON and the full list is serializable."""+ for descriptor in _swarm_catalog().values():+ restored = HarnessElementDescriptor.model_validate_json(+ descriptor.model_dump_json()+ )+ assert restored == descriptor++ payload = json.dumps(list_elements())+ assert payload+ logger.info("list_elements serialized to %d bytes", len(payload))+++def test_register_from_catalog_idempotent() -> None:+ """Re-running registration leaves the ``swarm.*`` registry keys unchanged."""+ register_from_catalog()+ rail_before = _swarm_keys(das._RAIL_PROVIDER_REGISTRY)+ tool_before = _swarm_keys(das._TOOL_PROVIDER_REGISTRY)+ sub_before = _swarm_keys(das._SUBAGENT_PROVIDER_REGISTRY)++ register_from_catalog()++ assert rail_before == _swarm_keys(das._RAIL_PROVIDER_REGISTRY)+ assert tool_before == _swarm_keys(das._TOOL_PROVIDER_REGISTRY)+ assert sub_before == _swarm_keys(das._SUBAGENT_PROVIDER_REGISTRY)+++def test_rail_interface_methods_introspected() -> None:+ """A rail descriptor exposes the AgentRail lifecycle hooks, minus internals."""+ descriptor = get_catalog()[registry.CODE_CONFIRM_INTERRUPT]+ names = {method.name for method in descriptor.interface_methods}++ assert "before_model_call" in names+ assert "before_tool_call" in names+ assert "get_callbacks" not in names+++def test_tool_interface_methods_triad() -> None:+ """A tool descriptor exposes the invoke/stream/card surface."""+ descriptor = get_catalog()[registry.SKILL_TOOLKIT]+ by_name = {method.name: method for method in descriptor.interface_methods}++ assert {"invoke", "stream", "card"} <= set(by_name)+ assert by_name["invoke"].is_async+++def test_subagent_has_no_interface_methods() -> None:+ """A sub-agent builds a SubAgentConfig spec, so it exposes no interface object."""+ descriptor = get_catalog()[registry.EXPLORE_AGENT]+ assert descriptor.interface_methods == []+++def test_catalog_covers_all_kinds_without_swarm_rail_types() -> None:+ """All three kinds appear and swarm rails live in the rail-provider registry."""+ register_swarm_providers()+ kinds = {descriptor.kind for descriptor in _swarm_catalog().values()}+ assert kinds == {ElementKind.TOOL, ElementKind.RAIL, ElementKind.SUBAGENT}++ # The legacy class-type registry is gone in openjiuwen; swarm class rails are+ # unified into the rail-provider registry.+ assert not hasattr(das, "_RAIL_TYPE_REGISTRY")+ swarm_rails = {+ descriptor.name+ for descriptor in _swarm_catalog().values()+ if descriptor.kind is ElementKind.RAIL+ }+ assert swarm_rails <= _swarm_keys(das._RAIL_PROVIDER_REGISTRY)+++def test_class_rail_builds_via_railspec() -> None:+ """A unified class rail resolves and builds through openjiuwen RailSpec.build."""+ register_swarm_providers()+ ctx = SwarmBuildContext(language="cn", channel="web")++ rail = RailSpec(type=registry.RESPONSE_PROMPT).build(language="cn", context=ctx)++ assert rail is not None+ assert type(rail).__name__ == "ResponsePromptRail"+ assert inspect.isclass(+ resolve_factory(get_catalog()[registry.RESPONSE_PROMPT].factory_ref)+ )diff --git a/tests/agents/swarm/test_skills_provider.py b/tests/agents/swarm/test_skills_provider.pynew file mode 100644index 0000000000..1da6270885--- /dev/null+++ b/tests/agents/swarm/test_skills_provider.py@@ -0,0 +1,84 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Unit tests for the swarm member-skill provider.++Exercises the member-configured skill linking that the+``swarm.member_skill_toolkit`` provider performs, called directly on the provider+helpers (no customizer, no live ``DeepAgent``). These cover the behaviour the+legacy ``TeamManager.build_agent_customizer`` used to own before the provider+unification, now link-based to match the shared-skill-link runtime model.+"""++from __future__ import annotations++from pathlib import Path++from jiuwenswarm.agents.swarm.providers import skills+++def _make_skill(parent: Path, name: str) -> None:+ """Create a minimal skill directory (with a ``SKILL.md``) under *parent*."""+ skill_dir = parent / name+ skill_dir.mkdir(parents=True)+ (skill_dir / "SKILL.md").write_text(f"---\nname: {name}\n---\n", encoding="utf-8")+++def test_link_member_configured_skills_links_only_selected(tmp_path):+ """Only the member's selected skills are linked into its skills directory."""+ global_skills = tmp_path / "global"+ for name in ("skill-a", "skill-b", "skill-c"):+ _make_skill(global_skills, name)++ member_skills = tmp_path / "member" / "skills"+ member_skills.mkdir(parents=True)++ skills._link_member_configured_skills(+ member_skills,+ ["skill-a", "skill-c"],+ global_skills,+ )++ # Selected skills become links resolving back to the global store (no copies).+ assert (member_skills / "skill-a").resolve() == (global_skills / "skill-a").resolve()+ assert (member_skills / "skill-c").resolve() == (global_skills / "skill-c").resolve()+ assert not (member_skills / "skill-b").exists()+++def test_link_member_configured_skills_prunes_unselected_link(tmp_path):+ """Re-linking with a narrower selection prunes the dropped skill link."""+ global_skills = tmp_path / "global"+ for name in ("skill-a", "skill-b"):+ _make_skill(global_skills, name)++ member_skills = tmp_path / "member" / "skills"+ member_skills.mkdir(parents=True)++ skills._link_member_configured_skills(member_skills, ["skill-a", "skill-b"], global_skills)+ assert (member_skills / "skill-a").exists()+ assert (member_skills / "skill-b").exists()++ skills._link_member_configured_skills(member_skills, ["skill-a"], global_skills)+ assert (member_skills / "skill-a").exists()+ assert not (member_skills / "skill-b").exists()+++def test_link_member_configured_skills_skips_missing_global_dir(tmp_path):+ """A missing global skills directory is a no-op rather than an error."""+ member_skills = tmp_path / "member" / "skills"+ member_skills.mkdir(parents=True)++ skills._link_member_configured_skills(+ member_skills,+ ["skill-a"],+ tmp_path / "does-not-exist",+ )++ assert list(member_skills.iterdir()) == []+++def test_extract_skill_name_from_tool_result_prefers_nested_skill():+ """The skill name resolver reads nested ``skill`` then flat fallbacks."""+ assert skills._extract_skill_name_from_tool_result({"skill": {"name": "alpha"}}) == "alpha"+ assert skills._extract_skill_name_from_tool_result({"skill_name": "beta"}) == "beta"+ assert skills._extract_skill_name_from_tool_result({"name": "gamma"}) == "gamma"+ assert skills._extract_skill_name_from_tool_result({}) == ""diff --git a/tests/agents/swarm/test_swarm_assembly.py b/tests/agents/swarm/test_swarm_assembly.pynew file mode 100644index 0000000000..3bdd867b34--- /dev/null+++ b/tests/agents/swarm/test_swarm_assembly.py@@ -0,0 +1,948 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Unit tests for the swarm provider-based team assembly framework.++These tests exercise the config-sourced assembly path end to end without ever+touching a real LLM, the network, or a live ``DeepAgent``:++* provider/rail-type registration is idempotent and lands in openjiuwen's+ registries,+* ``build_member_capability_specs`` emits the expected ``swarm.*`` rail/tool+ references per role (purely from a config dict),+* ``enrich_team_spec_for_swarm`` rewrites a real ``TeamAgentSpec`` in place,+ attaches a ``SwarmBuildContext``, and keeps the parent-free contract,+* the enriched spec serializes cleanly with the live build context excluded,+* individual providers degrade gracefully (return ``[]`` / ``None``) when their+ config gate is closed.+"""++from __future__ import annotations++import inspect+import json+import logging+import types++import pytest++from openjiuwen.agent_teams.schema import deep_agent_spec as das+from openjiuwen.agent_teams.schema.blueprint import LeaderSpec, TeamAgentSpec+from openjiuwen.agent_teams.schema.deep_agent_spec import (+ BuiltinToolSpec,+ DeepAgentSpec,+ RailSpec,+)++from jiuwenswarm.agents.swarm import (+ SwarmBuildContext,+ enrich_team_spec_for_swarm,+ register_swarm_providers,+)+from openjiuwen.agent_teams.schema.deep_agent_spec import TeamModelConfig, WorkspaceSpec+from openjiuwen.agent_evolving.trajectory import InMemoryTrajectoryRegistry+from openjiuwen.core.foundation.llm import ModelClientConfig++from jiuwenswarm.agents.swarm import registry+from jiuwenswarm.agents.swarm.config_specs import (+ build_member_capability_specs,+ build_member_deep_agent_spec,+ build_member_subagent_specs,+)+from jiuwenswarm.agents.swarm.providers import (+ code_rails,+ evolution_rails,+ member_rails,+ runtime_tools,+ tools,+)+from jiuwenswarm.agents.harness.team.team_runtime_inheritance import (+ resolve_model_config,+)+from jiuwenswarm.common.config import get_config++logger = logging.getLogger(__name__)++# Rail provider names shared by both roles (no role-specific evolution rails).+# Sourced from the registry symbols so the test tracks renames automatically.+_COMMON_RAIL_NAMES: frozenset[str] = frozenset(+ {+ registry.RUNTIME_PROMPT,+ registry.RESPONSE_PROMPT,+ registry.SYS_OPERATION,+ registry.STREAM_EVENT,+ registry.TASK_PLANNING,+ registry.SECURITY,+ registry.HEARTBEAT,+ registry.AVATAR_PROMPT,+ registry.TEAM_WORKSPACE_REPORT_PATH,+ registry.CONTEXT_PROCESSOR,+ registry.PLUGIN_RAILS,+ registry.MEMBER_SKILL_TOOLKIT,+ }+)++_COMMON_TOOL_NAMES: frozenset[str] = frozenset(+ {+ registry.WEB_SEARCH,+ registry.WEB_FETCH,+ registry.WEB_PAID_SEARCH,+ registry.VISION,+ registry.AUDIO,+ # SKILL_TOOLKIT is no longer declared as a tool; the+ # MEMBER_SKILL_TOOLKIT rail is the sole registrar of skill tools.+ registry.USER_TODOS,+ registry.VIDEO,+ registry.IMAGE_GEN,+ registry.XIAOYI_PHONE,+ registry.CRON_TOOLS,+ registry.SEND_FILE,+ }+)+++def _make_team_spec() -> TeamAgentSpec:+ """Build a minimal, valid two-role team spec for enrichment tests.++ Uses bare ``DeepAgentSpec`` members (no model / card) so the spec stays+ free of any live runtime dependency; enrichment only reads/writes rails,+ tools and ``build_context``.++ Returns:+ A ``TeamAgentSpec`` with ``leader`` and ``teammate`` members.+ """+ return TeamAgentSpec(+ agents={"leader": DeepAgentSpec(), "teammate": DeepAgentSpec()},+ team_name="unit_team",+ leader=LeaderSpec(member_name="team_leader"),+ )+++def test_register_swarm_providers_is_idempotent() -> None:+ """Two consecutive registrations must not raise and stay consistent."""+ register_swarm_providers()+ rail_after_first = {+ k for k in das._RAIL_PROVIDER_REGISTRY if k.startswith("swarm.")+ }+ tool_after_first = {+ k for k in das._TOOL_PROVIDER_REGISTRY if k.startswith("swarm.")+ }++ register_swarm_providers()+ rail_after_second = {+ k for k in das._RAIL_PROVIDER_REGISTRY if k.startswith("swarm.")+ }+ tool_after_second = {+ k for k in das._TOOL_PROVIDER_REGISTRY if k.startswith("swarm.")+ }++ assert rail_after_first == rail_after_second+ assert tool_after_first == tool_after_second+ logger.info(+ "idempotent registration: %d rail providers, %d tool providers",+ len(rail_after_second),+ len(tool_after_second),+ )+++def test_register_swarm_providers_populates_registries() -> None:+ """Registration installs every common ``swarm.*`` provider name."""+ register_swarm_providers()++ rail_providers = set(das._RAIL_PROVIDER_REGISTRY)+ tool_providers = set(das._TOOL_PROVIDER_REGISTRY)++ # The legacy class-type registry is gone; every rail (including the unified+ # class rails) is now provider-backed.+ for name in _COMMON_RAIL_NAMES:+ assert name in rail_providers, name+ for name in _COMMON_TOOL_NAMES:+ assert name in tool_providers, name++ # Role-specific evolution rails are provider-backed.+ assert registry.TEAM_SKILL_EVOLUTION in rail_providers+ assert registry.TEAM_SKILL_CREATE in rail_providers+ assert registry.MEMBER_SKILL_EVOLUTION in rail_providers+++def test_runtime_prompt_rail_resolves_via_registry() -> None:+ """A ``RailSpec`` referencing a swarm provider builds a live rail.++ Proves the registration is wired through openjiuwen's resolution path (not+ just present as a dict key) using a fake per-member context.+ """+ register_swarm_providers()+ fake_ctx = SwarmBuildContext(language="cn", channel="web")++ rail = RailSpec(type=registry.RUNTIME_PROMPT).build(language="cn", context=fake_ctx)++ assert rail is not None+ assert type(rail).__name__ == "RuntimePromptRail"+++def test_unknown_swarm_rail_type_raises() -> None:+ """An unregistered ``swarm.*`` rail type surfaces a clear ``ValueError``."""+ register_swarm_providers()+ fake_ctx = SwarmBuildContext(language="cn", channel="web")++ with pytest.raises(ValueError):+ RailSpec(type="swarm.__does_not_exist__").build(+ language="cn",+ context=fake_ctx,+ )+++ ("role", "extra_rails"),+ [+ ("leader", {registry.TEAM_SKILL_EVOLUTION, registry.TEAM_SKILL_CREATE}),+ ("teammate", {registry.MEMBER_SKILL_EVOLUTION}),+ ],+)+def test_build_member_capability_specs_rail_names(+ role: str,+ extra_rails: set[str],+) -> None:+ """Each role gets the common rails plus its role-specific evolution rails."""+ config = {+ "agents": {+ "leader": {"skills": ["alpha"]},+ "teammate": {"skills": ["beta"]},+ }+ }++ rails_specs, _ = build_member_capability_specs(config, "team", role)+ rail_names = {spec.type for spec in rails_specs}++ assert _COMMON_RAIL_NAMES <= rail_names+ assert extra_rails <= rail_names+ # The common set has exactly 12 entries; the role adds only its evolution+ # rails on top.+ assert len(_COMMON_RAIL_NAMES) == 12+ assert rail_names == _COMMON_RAIL_NAMES | extra_rails+ # No DeepAgent is involved; every entry is a plain declarative RailSpec.+ assert all(isinstance(spec, RailSpec) for spec in rails_specs)+ logger.info("%s rails: %s", role, sorted(rail_names))++[email protected]("role", ["leader", "teammate"])+def test_build_member_capability_specs_tool_names(role: str) -> None:+ """Both roles declare the common tool set (base / cron / send_file)."""+ config = {"agents": {"leader": {"skills": []}, "teammate": {"skills": []}}}++ _, tool_specs = build_member_capability_specs(config, "team", role)+ tool_names = {spec.type for spec in tool_specs}++ assert tool_names == _COMMON_TOOL_NAMES+ assert all(isinstance(spec, BuiltinToolSpec) for spec in tool_specs)+++def test_member_skill_toolkit_carries_selected_skills() -> None:+ """The skill-toolkit rail forwards the role's cleaned skill selection."""+ config = {+ "agents": {+ "leader": {"skills": ["alpha", " ", "beta"]},+ "teammate": {"skills": []},+ }+ }++ leader_rails, _ = build_member_capability_specs(config, "team", "leader")+ toolkit = next(+ spec for spec in leader_rails if spec.type == registry.MEMBER_SKILL_TOOLKIT+ )++ # Blank entries are stripped; order is preserved.+ assert toolkit.params == {"skills": ["alpha", "beta"]}+++def test_enrich_team_spec_for_swarm_has_no_deep_agent_param() -> None:+ """The enrichment seam must never accept a pre-built DeepAgent."""+ params = set(inspect.signature(enrich_team_spec_for_swarm).parameters)++ assert "deep_agent" not in params+ assert "deep_agent_spec" not in params+ # The exact public surface is the session/request descriptors only.+ assert params == {+ "spec",+ "session_id",+ "mode",+ "project_dir",+ "request_id",+ "channel_id",+ "request_metadata",+ }+++def test_enrich_team_spec_for_swarm_rewrites_spec_in_place() -> None:+ """Enrichment rewrites member rails and attaches the build context."""+ spec = _make_team_spec()++ result = enrich_team_spec_for_swarm(+ spec,+ session_id="s",+ mode="team",+ channel_id="web",+ )++ # Mutates in place and returns nothing.+ assert result is None++ leader_rail_names = {rail.type for rail in (spec.agents["leader"].rails or [])}+ teammate_rail_names = {rail.type for rail in (spec.agents["teammate"].rails or [])}+ assert any(name.startswith("swarm.") for name in leader_rail_names)+ assert registry.TEAM_SKILL_EVOLUTION in leader_rail_names+ assert registry.MEMBER_SKILL_EVOLUTION in teammate_rail_names++ # Build context carries the per-team handles.+ assert isinstance(spec.build_context, SwarmBuildContext)+ assert spec.build_context.session_id == "s"+ assert spec.build_context.team_id == "unit_team"++ # The parent-free contract: openjiuwen removed the imperative customizer+ # hook entirely, so the field no longer exists on the spec.+ assert not hasattr(spec, "agent_customizer")+++def test_enrich_team_spec_appends_after_existing_rails() -> None:+ """Provider rails are appended after a member's pre-existing rails."""+ spec = _make_team_spec()+ # Seed the leader with a non-swarm rail to prove ordering is preserved.+ spec.agents["leader"].rails = [RailSpec(type="skill_use")]++ enrich_team_spec_for_swarm(spec, session_id="s", mode="team", channel_id="web")++ leader_rail_types = [rail.type for rail in (spec.agents["leader"].rails or [])]+ assert leader_rail_types[0] == "skill_use"+ assert leader_rail_types.count("skill_use") == 1+ assert len(leader_rail_types) > 1+++def test_enrich_skips_absent_roles_gracefully() -> None:+ """A team without a teammate role is enriched without error."""+ spec = TeamAgentSpec(+ agents={"leader": DeepAgentSpec()},+ team_name="solo_team",+ leader=LeaderSpec(member_name="team_leader"),+ )++ enrich_team_spec_for_swarm(spec, session_id="s", mode="team", channel_id="web")++ assert "teammate" not in spec.agents+ leader_rail_names = {rail.type for rail in (spec.agents["leader"].rails or [])}+ assert registry.TEAM_SKILL_EVOLUTION in leader_rail_names+++def test_enriched_spec_serialization_round_trip() -> None:+ """The enriched spec dumps to JSON with the build context excluded."""+ spec = _make_team_spec()+ enrich_team_spec_for_swarm(spec, session_id="s", mode="team", channel_id="web")++ dumped = spec.model_dump_json()+ data = json.loads(dumped)++ # ``build_context`` (live carrier) is excluded; ``agent_customizer`` was+ # removed from the spec entirely (F_32) and must not reappear.+ assert "build_context" not in data+ assert "agent_customizer" not in data++ # Rails serialize as {type, params} declarative references.+ leader_rails = data["agents"]["leader"]["rails"]+ assert leader_rails, "expected leader rails in the dumped spec"+ for rail in leader_rails:+ assert set(rail.keys()) == {"type", "params"}+ assert isinstance(rail["type"], str) and rail["type"]+ # The member profile mixes swarm-owned (swarm.*) and openjiuwen-provided+ # (bare name) rails after the element unification.+ rail_types = {rail["type"] for rail in leader_rails}+ assert any(name.startswith("swarm.") for name in rail_types)+ assert any(not name.startswith("swarm.") for name in rail_types)+++def test_send_file_returns_empty_without_request_id() -> None:+ """The send-file provider skips (returns []) when request_id is missing."""+ ctx = SwarmBuildContext(+ session_id="s",+ request_id=None,+ channel_id="web",+ config={},+ )++ assert runtime_tools.build_send_file_tools({}, ctx) == []+++def test_send_file_returns_empty_without_channel_id() -> None:+ """The send-file provider skips (returns []) when channel_id is missing."""+ ctx = SwarmBuildContext(+ session_id="s",+ request_id="r",+ channel_id=None,+ config={},+ )++ assert runtime_tools.build_send_file_tools({}, ctx) == []+++def test_send_file_gating_defaults_by_channel() -> None:+ """File sending defaults on for ``web`` and off for other channels."""+ assert runtime_tools._is_send_file_enabled(None, "web")+ assert not runtime_tools._is_send_file_enabled(None, "feishu")+ # Explicit config switch overrides the default.+ disabled = {"channels": {"web": {"send_file_allowed": False}}}+ assert not runtime_tools._is_send_file_enabled(disabled, "web")+++def test_cron_tools_built(monkeypatch: pytest.MonkeyPatch) -> None:+ """The cron provider builds the member-scoped toolkit via CronRuntimeBridge."""++ class _FakeCronBridge:+ def build_tools(self, *, context, agent_id, language="cn"):+ return [+ types.SimpleNamespace(+ card=types.SimpleNamespace(+ name="cron_list_jobs", id=f"cron_{agent_id}"+ )+ )+ ]++ monkeypatch.setattr(runtime_tools, "CronRuntimeBridge", _FakeCronBridge)+ ctx = SwarmBuildContext(member_card_id="m1", channel_id="web", session_id="s")++ built = runtime_tools.build_cron_tools({}, ctx)++ assert [tool.card.name for tool in built] == ["cron_list_jobs"]+++def test_context_processor_returns_none_when_engine_disabled() -> None:+ """The context-processor provider returns None when the engine is off.++ The enabled flag is a config-derived attribute baked into ``params`` by+ config_specs; the provider gates on it directly.+ """+ ctx = SwarmBuildContext()++ assert (+ member_rails._build_context_processor({"context_engine_enabled": False}, ctx)+ is None+ )+++def test_team_workspace_report_path_returns_none_without_root() -> None:+ """The report-path rail is skipped when no team workspace root is set."""+ ctx = SwarmBuildContext(team_ws_root=None)++ assert member_rails._build_team_workspace_report_path_rail({}, ctx) is None+++# ---------------------------------------------------------------------------+# Multimodal / xiaoyi tool gating (config-sourced base tools)+# ---------------------------------------------------------------------------+++def test_xiaoyi_phone_tools_gated_by_config() -> None:+ """xiaoyi phone tools are built only when the channel switch is on."""+ enabled = SwarmBuildContext(+ config={"channels": {"xiaoyi": {"phone_tools_enabled": True}}},+ )+ disabled = SwarmBuildContext(config={})++ assert len(tools._build_xiaoyi_phone_tools(enabled)) == 27+ assert tools._build_xiaoyi_phone_tools(disabled) == []+++def test_video_tool_gated_by_config(monkeypatch: pytest.MonkeyPatch) -> None:+ """The video tool is built only when models.video is configured."""+ ctx = SwarmBuildContext(config={})+ # Gate closed: empty config has no dedicated video model.+ assert tools._build_video_tools(ctx) == []++ # Gate open: dedicated key reported + VIDEO_API_KEY present.+ monkeypatch.setattr(tools, "apply_video_model_config_from_yaml", lambda cfg: None)+ monkeypatch.setattr(+ tools, "dedicated_multimodal_model_configured", lambda cfg, kind: True+ )+ monkeypatch.setenv("VIDEO_API_KEY", "k")+ built = tools._build_video_tools(ctx)+ assert [tool.card.name for tool in built] == ["video_understanding"]+++def test_image_gen_tool_gated_by_env(monkeypatch: pytest.MonkeyPatch) -> None:+ """The image-generation tool is built only when IMAGE_GEN_API_KEY is set."""+ ctx = SwarmBuildContext(config={})+ monkeypatch.setattr(+ tools, "apply_image_gen_model_config_from_yaml", lambda cfg: None+ )+ monkeypatch.delenv("IMAGE_GEN_API_KEY", raising=False)+ assert tools._build_image_gen_tools(ctx) == []++ monkeypatch.setenv("IMAGE_GEN_API_KEY", "k")+ built = tools._build_image_gen_tools(ctx)+ assert [tool.card.name for tool in built] == ["generate_image"]+++def test_vision_model_config_params_gating(monkeypatch: pytest.MonkeyPatch) -> None:+ """Vision config params are empty without a dedicated model, filled when complete."""+ assert tools.vision_model_config_params({}) == {}++ monkeypatch.setattr(+ tools, "dedicated_multimodal_model_configured", lambda cfg, kind: True+ )+ monkeypatch.setattr(tools, "apply_vision_model_config_from_yaml", lambda cfg: None)+ monkeypatch.setenv("VISION_API_KEY", "key")+ monkeypatch.setenv("VISION_BASE_URL", "https://vision.example")+ monkeypatch.setenv("VISION_MODEL", "vlm-1")++ params = tools.vision_model_config_params({})+ assert params["api_key"] == "key"+ assert params["base_url"] == "https://vision.example"+ assert params["model"] == "vlm-1"+++def test_vision_audio_config_params_empty_when_unconfigured() -> None:+ """Vision/audio config params are empty when no dedicated model is configured.++ The vision/audio tools themselves are openjiuwen elements (``core.vision`` /+ ``core.audio``); swarm only fills their config, so an unconfigured member+ yields empty params (the core element then builds nothing).+ """+ assert tools.vision_model_config_params({}) == {}+ assert tools.audio_model_config_params({}) == {}+ assert tools.audio_dedicated_configured({}) is False+++# ---------------------------------------------------------------------------+# Evolution hot-reload: full TeamWorkspaceInfo on the registered rail context+# ---------------------------------------------------------------------------+++def test_team_skill_create_rail_registers_full_workspace(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The leader create rail registers a fully-populated ``TeamWorkspaceInfo``.++ An empty workspace info previously broke ``update_evolution_config`` rebuilds+ (``build_member_rails`` skips the leader branch without ``skills_dir``). This+ asserts the rail-mount context now carries root_dir / skills_dir / team_id /+ config / trajectory_registry from the build context.+ """+ register_swarm_providers()+ monkeypatch.setenv("SKILL_CREATE", "true")++ registry_obj = object()+ config = {"react": {"evolution": {"skill_create": True}}}+ ctx = SwarmBuildContext(+ language="cn",+ role="leader",+ member_card_id="t_leader",+ session_id="sess",+ channel="web",+ team_id="t",+ team_ws_root="/tmp/team-x",+ team_skills_dir="/tmp/team-x/skills",+ global_skills_dir="/tmp/global",+ trajectory_registry=registry_obj,+ config=config,+ )++ rail = evolution_rails.build_team_skill_create_rail({"skill_create": True}, ctx)+ assert rail is not None++ captured: dict[str, object] = {}++ class _RecorderTeamManager:+ def register_team_live_rail(self, session_id, agent, registered_rail) -> None:+ captured["live_rail"] = (session_id, registered_rail)++ def register_team_skill_create_rail(self, session_id, registered_rail) -> None:+ captured["create_rail"] = (session_id, registered_rail)++ def get_team_rail_context(self, session_id):+ return None++ def register_team_rail_context(self, session_id, context) -> None:+ captured["rail_context"] = context++ import jiuwenswarm.agents.harness.team.team_manager as tm_mod++ monkeypatch.setattr(+ tm_mod, "get_team_manager", lambda channel=None: _RecorderTeamManager()+ )++ fake_agent = types.SimpleNamespace(+ card=types.SimpleNamespace(name="leader", id="t_leader"),+ )+ rail.init(fake_agent)++ workspace = captured["rail_context"].team_workspace+ assert workspace.root_dir == "/tmp/team-x"+ assert workspace.skills_dir == "/tmp/team-x/skills"+ assert workspace.team_id == "t"+ assert workspace.config == config+ assert workspace.trajectory_registry is registry_obj+++# ---------------------------------------------------------------------------+# code.team / team.plan declarative profile+# ---------------------------------------------------------------------------++_EXPECTED_CODE_RAIL_NAMES: frozenset[str] = frozenset(+ {+ registry.CODE_RUNTIME_PROMPT,+ registry.RESPONSE_PROMPT,+ registry.STREAM_EVENT,+ registry.SECURITY,+ registry.CODE_LSP,+ registry.CODE_PROJECT_MEMORY,+ registry.PERMISSION_INTERRUPT,+ registry.SYS_OPERATION,+ registry.CODE_CODING_MEMORY,+ registry.CODE_AGENT_MODE,+ registry.STRUCTURED_ASK_USER,+ registry.CONTEXT_PROCESSOR,+ registry.CODE_TASK_PLANNING,+ registry.CODE_AGENT_RAIL,+ registry.USER_HOOKS,+ registry.CODE_SKILL_USE,+ registry.CODE_WORKTREE,+ registry.CODE_CONFIRM_INTERRUPT,+ registry.MEMBER_SKILL_TOOLKIT,+ registry.TEAM_WORKSPACE_REPORT_PATH,+ registry.PLUGIN_RAILS,+ }+)++[email protected]("mode", ["code.team", "team.plan"])+def test_code_capability_specs_rail_and_tool_names(mode: str) -> None:+ """Code modes emit the code rail/tool profile (not the chat-team common rails)."""+ register_swarm_providers()+ rails_specs, tool_specs = build_member_capability_specs({}, mode, "leader")+ rail_names = {spec.type for spec in rails_specs}+ tool_names = {spec.type for spec in tool_specs}++ assert _EXPECTED_CODE_RAIL_NAMES <= rail_names+ assert registry.TEAM_SKILL_EVOLUTION in rail_names+ # The chat-team common runtime prompt is replaced by the code variant.+ assert registry.RUNTIME_PROMPT not in rail_names+ assert tool_names == {+ registry.WEB_SEARCH,+ registry.WEB_FETCH,+ registry.WEB_PAID_SEARCH,+ registry.VISION,+ registry.AUDIO,+ # SKILL_TOOLKIT moved to the MEMBER_SKILL_TOOLKIT rail (see common set).+ registry.USER_TODOS,+ registry.VIDEO,+ registry.IMAGE_GEN,+ registry.XIAOYI_PHONE,+ registry.CODE_EXTRA_TOOLS,+ registry.CRON_TOOLS,+ registry.SEND_FILE,+ }+++def test_code_subagent_specs_use_factory_names() -> None:+ """Code modes declare explore/plan (+ gated code) sub-agents via factory_name."""+ register_swarm_providers()+ config = {"react": {"subagents": {"code_agent": {"enabled": True}}}}++ subs = build_member_subagent_specs(config, "code.team", "leader")+ factory_names = [spec.factory_name for spec in subs]++ assert registry.EXPLORE_AGENT in factory_names+ assert registry.PLAN_AGENT in factory_names+ assert registry.CODE_AGENT in factory_names+ # Team mode has no code sub-agents.+ assert build_member_subagent_specs({}, "team", "leader") == []+++def test_code_runtime_language_by_mode_and_role() -> None:+ """Only the team.plan leader uses the configured language; code is else English."""+ plan_leader = SwarmBuildContext(+ mode="team.plan",+ role="leader",+ config={"preferred_language": "zh"},+ )+ plan_teammate = SwarmBuildContext(mode="team.plan", role="teammate", config={})+ code_team = SwarmBuildContext(mode="code.team", role="leader", config={})++ assert code_rails.code_runtime_language(plan_leader) in {"cn", "zh"}+ assert code_rails.code_runtime_language(plan_teammate) == "en"+ assert code_rails.code_runtime_language(code_team) == "en"+++def test_code_extra_tools_gated_by_config() -> None:+ """The code-exclusive tool provider only builds when ``acp_agents`` is configured."""+ register_swarm_providers()+ enabled = SwarmBuildContext(config={"acp_agents": {"demo": {}}})+ disabled = SwarmBuildContext(config={})++ assert tools.build_code_extra_tools({}, disabled) == []+ assert isinstance(tools.build_code_extra_tools({}, enabled), list)+++def test_code_member_builds_declaratively_without_post_processing(+ tmp_path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A code.team member builds through ``spec.build`` with zero post-processing.++ This is the crux of the "no customizer / no rail.init hack" contract: the+ code rails, sub-agents and system prompt materialize through openjiuwen's+ normal declarative build, and ``configure_code_team_member_agent`` is never+ invoked.+ """+ register_swarm_providers()+ config = get_config()+ model_client_config, _, _ = resolve_model_config(config)+ base = DeepAgentSpec(+ model=TeamModelConfig(+ model_client_config=ModelClientConfig(**model_client_config)+ ),+ workspace=WorkspaceSpec(root_path=str(tmp_path), language="en"),+ )+ spec = build_member_deep_agent_spec(config, "code.team", "leader", base)++ import jiuwenswarm.server.runtime.agent_adapter.interface_code as interface_code++ post_processing_calls: list[int] = []+ monkeypatch.setattr(+ interface_code,+ "configure_code_team_member_agent",+ lambda *args, **kwargs: post_processing_calls.append(1),+ )++ ctx = SwarmBuildContext(+ mode="code.team",+ role="leader",+ member_name="leader",+ member_card_id="t_leader",+ session_id="s",+ channel="web",+ team_id="t",+ project_dir=str(tmp_path),+ team_ws_root=str(tmp_path),+ team_skills_dir=str(tmp_path / "skills"),+ global_skills_dir=str(tmp_path / "global"),+ trajectory_registry=InMemoryTrajectoryRegistry(),+ config=config,+ )+ agent = spec.build(context=ctx)++ rails = list(getattr(agent, "_pending_rails", [])) + list(+ getattr(agent, "_registered_rails", [])+ )+ rail_types = {type(rail).__name__ for rail in rails}++ # Zero post-processing: the legacy code customizer is never invoked.+ assert post_processing_calls == []+ # Code-specific rails materialized via the normal declarative spec.build.+ for expected in (+ "CodeTaskPlanningRail",+ "JiuwenAgentModeRail",+ "StructuredAskUserRail",+ "WorktreeRail",+ ):+ assert expected in rail_types, (expected, sorted(rail_types))+ # The code system prompt is set declaratively on the spec.+ assert agent.deep_config.system_prompt+ # CodingMemoryRail is published for the code_agent sub-agent to reuse.+ assert ctx.extras.get(code_rails.CODING_MEMORY_EXTRAS_KEY) is not None+ logger.info("code member declarative build rail types: %s", sorted(rail_types))+++# ---------------------------------------------------------------------------+# Serializable build-context seed (spawned / distributed member rebuild)+# ---------------------------------------------------------------------------+++def test_swarm_build_context_seed_round_trip() -> None:+ """``to_seed`` exports the serializable fields; ``from_seed`` restores them."""+ base = SwarmBuildContext(+ session_id="s1",+ request_id="r1",+ channel_id="c1",+ channel="web",+ request_metadata={"mode": "code.team"},+ mode="code.team",+ project_dir="/tmp/proj",+ team_id="t1",+ team_ws_root="/tmp/ws",+ team_skills_dir="/tmp/ws/skills",+ global_skills_dir="/tmp/global",+ trajectory_registry=InMemoryTrajectoryRegistry(),+ config={"team": {}},+ )+ seed = base.to_seed()++ # Per-member and non-serializable fields stay out of the seed.+ for excluded in (+ "member_name",+ "role",+ "language",+ "workspace",+ "member_card_id",+ "config",+ "trajectory_registry",+ ):+ assert excluded not in seed++ registry_obj = InMemoryTrajectoryRegistry()+ restored = SwarmBuildContext.from_seed(+ seed,+ config={"k": "v"},+ trajectory_registry=registry_obj,+ )+ assert restored.session_id == "s1"+ assert restored.mode == "code.team"+ assert restored.project_dir == "/tmp/proj"+ assert restored.team_id == "t1"+ assert restored.team_ws_root == "/tmp/ws"+ assert restored.request_metadata == {"mode": "code.team"}+ # Non-serializable handles are sourced from the receiver, not the seed.+ assert restored.config == {"k": "v"}+ assert restored.trajectory_registry is registry_obj+++def test_build_context_factory_rebuilds_and_shares_registry() -> None:+ """The registered factory rebuilds a context and shares per-team registries."""+ from openjiuwen.agent_teams.schema.build_context import build_context_from_seed++ register_swarm_providers()+ seed = {"session_id": "s", "team_id": "t", "mode": "team", "project_dir": "/p"}++ ctx = build_context_from_seed(seed)+ assert isinstance(ctx, SwarmBuildContext)+ assert ctx.mode == "team"+ assert ctx.project_dir == "/p"+ # config is sourced locally (this process's config.yaml), not from the seed.+ assert ctx.config is not None+ assert ctx.trajectory_registry is not None++ # Same (session, team) shares a registry; a different team is isolated.+ again = build_context_from_seed(seed)+ assert again.trajectory_registry is ctx.trajectory_registry+ other = build_context_from_seed(+ {"session_id": "s", "team_id": "t2", "mode": "team"}+ )+ assert other.trajectory_registry is not ctx.trajectory_registry+++def test_enrich_sets_serializable_build_context_seed() -> None:+ """Enrichment leaves a serializable seed mirroring the live build context."""+ spec = _make_team_spec()+ enrich_team_spec_for_swarm(+ spec,+ session_id="s",+ mode="code.team",+ project_dir="/tmp/proj",+ channel_id="web",+ )+ assert spec.build_context_seed is not None+ assert spec.build_context_seed["mode"] == "code.team"+ assert spec.build_context_seed["project_dir"] == "/tmp/proj"+ assert spec.build_context_seed["team_id"] == spec.team_name+ # The seed equals what the live context exports.+ assert spec.build_context_seed == spec.build_context.to_seed()+++def test_distributed_member_rebuild_reconstructs_build_context() -> None:+ """A serialized member spec rebuilds its provider context from the seed.++ Simulates the spawn / distributed boundary without ZMQ: ``model_dump`` drops+ the live ``build_context`` but carries ``build_context_seed``;+ ``materialize_build_context`` reconstructs the context from it via the+ registered factory.+ """+ register_swarm_providers()+ spec = _make_team_spec()+ enrich_team_spec_for_swarm(+ spec,+ session_id="s",+ mode="code.team",+ project_dir="/tmp/proj",+ channel_id="web",+ )++ payload = spec.model_dump(mode="json")+ # build_context (live) is excluded; the seed survives the round-trip.+ assert "build_context" not in payload+ assert payload["build_context_seed"]["mode"] == "code.team"++ rebuilt = TeamAgentSpec.model_validate(payload)+ assert rebuilt.build_context is None+ rebuilt.materialize_build_context()++ assert isinstance(rebuilt.build_context, SwarmBuildContext)+ assert rebuilt.build_context.mode == "code.team"+ assert rebuilt.build_context.project_dir == "/tmp/proj"+ assert rebuilt.build_context.config is not None+ assert rebuilt.build_context.trajectory_registry is not None+ # Idempotent: a second call does not replace the rebuilt context.+ existing = rebuilt.build_context+ rebuilt.materialize_build_context()+ assert rebuilt.build_context is existing+++def test_rebuilt_member_spec_keeps_provider_declarations() -> None:+ """Provider rail / sub-agent declarations and the code prompt survive the round-trip.++ Complements the build-context reconstruction: the existing crown-jewel proves the+ declarative build itself, so here we prove the *serialized* code.team spec still+ carries its ``swarm.*`` rail / sub-agent references and code system prompt — so the+ post-round-trip build yields the same capabilities with no post-processing. (We do+ not build here: a second in-process ``spec.build`` would collide on the global tool+ registry, which never happens in production where each member builds in its own+ process.)+ """+ register_swarm_providers()+ spec = _make_team_spec()+ enrich_team_spec_for_swarm(+ spec,+ session_id="s",+ mode="code.team",+ project_dir="/tmp/proj",+ channel_id="web",+ )++ rebuilt = TeamAgentSpec.model_validate(spec.model_dump(mode="json"))+ teammate = rebuilt.agents["teammate"]++ rail_types = {rail.type for rail in teammate.rails}+ assert registry.CODE_TASK_PLANNING in rail_types+ assert registry.CODE_AGENT_MODE in rail_types+ assert registry.CODE_WORKTREE in rail_types+ # The code runtime prompt replaces the chat-team common runtime prompt.+ assert registry.CODE_RUNTIME_PROMPT in rail_types+ assert registry.RUNTIME_PROMPT not in rail_types+ # Sub-agents are declared by ``factory_name`` and survive serialization.+ leader_factory_names = {+ sub.factory_name for sub in rebuilt.agents["leader"].subagents+ }+ assert registry.EXPLORE_AGENT in leader_factory_names+ assert registry.PLAN_AGENT in leader_factory_names+ # The code system prompt is carried declaratively on the spec.+ assert teammate.system_prompt+++def test_swarm_assembly_hint_from_seed_and_legacy() -> None:+ """The bootstrap envelope hint carries mode/project_dir; empty for legacy."""+ from jiuwenswarm.agents.harness.team import remote_member_bootstrap as rmb++ spec = _make_team_spec()+ enrich_team_spec_for_swarm(+ spec,+ session_id="s",+ mode="code.team",+ project_dir="/tmp/proj",+ channel_id="web",+ )+ leader = types.SimpleNamespace(spec=spec)+ assert rmb._swarm_assembly_hint(leader) == {+ "mode": "code.team",+ "project_dir": "/tmp/proj",+ }++ # Legacy spec (no seed, no live context) yields no hint -> teammate stays legacy.+ legacy = types.SimpleNamespace(spec=_make_team_spec())+ assert rmb._swarm_assembly_hint(legacy) == {}+ # Defensive: a team agent without a spec yields no hint.+ assert rmb._swarm_assembly_hint(types.SimpleNamespace()) == {}diff --git a/tests/system_tests/test_structured_ask_user.py b/tests/system_tests/test_structured_ask_user.pyindex e713ea17ed..eb59f37538 100644--- a/tests/system_tests/test_structured_ask_user.py+++ b/tests/system_tests/test_structured_ask_user.py@@ -158,8 +158,8 @@ class TestStructuredAskUserRailLifecycle:with patch("openjiuwen.harness.rails.interrupt.ask_user_rail.resolve_language", return_value="en"):rail.init(agent)- agent.ability_manager.add.assert_called_once()- added_card = agent.ability_manager.add.call_args[0][0]+ agent.ability_manager.add_ability.assert_called_once()+ added_card = agent.ability_manager.add_ability.call_args[0][0]assert added_card.name == "ask_user"@staticmethod@@ -172,7 +172,7 @@ class TestStructuredAskUserRailLifecycle:rail.init(agent)rail.uninit(agent)- agent.ability_manager.remove.assert_called_once_with("ask_user")+ agent.ability_manager.remove_ability.assert_called_once_with("ask_user")@staticmethoddef test_init_uninit_clears_structured_tools():diff --git a/tests/unit_tests/agentserver/test_code_agent_rail.py b/tests/unit_tests/agentserver/test_code_agent_rail.pyindex a5bca54cd7..fbf87200a1 100644--- a/tests/unit_tests/agentserver/test_code_agent_rail.py+++ b/tests/unit_tests/agentserver/test_code_agent_rail.py@@ -168,42 +168,31 @@ class TestCodeAgentRail:rail = CodeAgentRail(workspace_dir="/tmp")agent = MagicMock()agent_def = _make_agent_def(name="reviewer")- with (- patch.object(rail, "_load_custom_agents", return_value=[agent_def]),- patch(- "jiuwenswarm.server.runtime.agent_adapter.code_agent_rail.Runner.resource_mgr"- ) as mock_mgr,- ):+ with patch.object(rail, "_load_custom_agents", return_value=[agent_def]):rail.init(agent)assert rail._agent_tool is not None+ # Registration now goes through the unified ability_manager.add_ability.+ agent.ability_manager.add_ability.assert_called_once()def test_uninit_removes_tool(self):rail = CodeAgentRail(workspace_dir="/tmp")agent = MagicMock()agent_def = _make_agent_def(name="reviewer")- with (- patch.object(rail, "_load_custom_agents", return_value=[agent_def]),- patch(- "jiuwenswarm.server.runtime.agent_adapter.code_agent_rail.Runner.resource_mgr"- ) as mock_mgr,- ):+ with patch.object(rail, "_load_custom_agents", return_value=[agent_def]):rail.init(agent)assert rail._agent_tool is not Nonerail.uninit(agent)assert rail._agent_tool is Noneassert rail._agent is None+ # Removal mirrors add_ability via ability_manager.remove_ability.+ agent.ability_manager.remove_ability.assert_called_once()def test_init_twice_replaces_tool(self):"""Initializing twice should create a new AgentTool each time."""rail = CodeAgentRail(workspace_dir="/tmp")agent = MagicMock()agent_def = _make_agent_def(name="reviewer")- with (- patch.object(rail, "_load_custom_agents", return_value=[agent_def]),- patch(- "jiuwenswarm.server.runtime.agent_adapter.code_agent_rail.Runner.resource_mgr"- ),- ):+ with patch.object(rail, "_load_custom_agents", return_value=[agent_def]):rail.init(agent)first_tool = rail._agent_toolrail.init(agent)diff --git a/tests/unit_tests/agentserver/test_team_manager_registry.py b/tests/unit_tests/agentserver/test_team_manager_registry.pyindex bb6d1db173..72fe698be0 100644--- a/tests/unit_tests/agentserver/test_team_manager_registry.py+++ b/tests/unit_tests/agentserver/test_team_manager_registry.py@@ -220,10 +220,6 @@ def test_refresh_team_shared_skill_links_across_managers_uses_registered_session"jiuwenswarm.agents.harness.team.team_manager.get_agent_skills_dir",lambda: global_skills_dir,)- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_agent_workspace_dir",- lambda: tmp_path / "global-workspace",- )manager = get_team_manager("web")manager.register_team_shared_skill_link_target("sess-1", team_shared_skills)@@ -316,109 +312,6 @@ async def test_register_team_rail_context_keeps_leader_context() -> None:assert manager.get_team_rail_context("sess-1") is leader_context-def test_build_agent_customizer_shares_one_trajectory_registry_per_runtime(- tmp_path,- monkeypatch: pytest.MonkeyPatch,-) -> None:- captured_registries = []-- class _FakeAbilityManager:- @staticmethod- def list():- return []-- class _FakeAgentWithWorkspace:- def __init__(self, root_path):- self.card = type("Card", (), {"name": "agent"})()- self.ability_manager = _FakeAbilityManager()- self.deep_config = type(- "DeepConfig",- (),- {- "workspace": type(- "Workspace",- (),- {"root_path": str(root_path)},- )()- },- )()- self.added_rails = []-- def add_rail(self, rail):- self.added_rails.append(rail)-- global_skills_dir = tmp_path / "global-skills"- global_skills_dir.mkdir()- (global_skills_dir / "skills_state.json").write_text("{}", encoding="utf-8")-- spec = type(- "Spec",- (),- {- "team_name": "demo-team",- "workspace": type(- "Workspace",- (),- {"root_path": str(tmp_path / "team-workspace")},- )(),- "agents": {},- },- )()- deep_agent = _FakeAgentWithWorkspace(tmp_path / "parent-workspace")-- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_agent_skills_dir",- lambda: global_skills_dir,- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_agent_workspace_dir",- lambda: tmp_path / "global-workspace",- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.SkillManager",- lambda workspace_dir: object(),- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.MemberSkillToolkitRail",- lambda workspace_dir, **kwargs: object(),- )-- def _fake_build_member_rails(**kwargs):- captured_registries.append(kwargs["team_workspace"].trajectory_registry)- return []-- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.build_member_rails",- _fake_build_member_rails,- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.filter_inheritable_ability_cards",- lambda deep_agent: [],- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_default_model_name",- lambda: "model",- )- monkeypatch.setattr(- TeamManager,- "register_member_runtime_tools",- staticmethod(lambda *args, **kwargs: None),- )-- customizer = TeamManager.build_agent_customizer(- spec,- deep_agent,- "sess-1",- channel_id="web",- )- customizer(_FakeAgentWithWorkspace(tmp_path / "leader-workspace"), role="leader")- customizer(_FakeAgentWithWorkspace(tmp_path / "member-workspace"), role="teammate")-- assert len(captured_registries) == 2- assert captured_registries[0] is not None- assert captured_registries[0] is captured_registries[1]--@pytest.mark.asyncioasync def test_update_evolution_config_skips_rail_rebuild_when_skill_create_disabled(monkeypatch: pytest.MonkeyPatch,@@ -507,7 +400,6 @@ async def test_team_manager_keeps_single_session_per_channel(monkeypatch: pytestdef fake_load_team_spec(session_id: str):class _Spec:team_name = f"team-{session_id}"- agent_customizer = Noneworkspace = _FakeWorkspace()@staticmethod@@ -524,6 +416,12 @@ async def test_team_manager_keeps_single_session_per_channel(monkeypatch: pytest"_initialize_team_shared_skill_links",staticmethod(lambda spec: None),)+ # Provider assembly is covered by the swarm suite; stub it so this+ # session-management test runs on the minimal fake spec.+ monkeypatch.setattr(+ "jiuwenswarm.agents.swarm.enrich_team_spec_for_swarm",+ lambda spec, **kwargs: None,+ )web_manager = get_team_manager("web")feishu_manager = get_team_manager("feishu")@@ -548,7 +446,6 @@ async def test_create_team_does_not_run_global_runtime_cleanup(monkeypatch: pytedef fake_load_team_spec(_session_id: str):class _Spec:team_name = "demo-team"- agent_customizer = Noneworkspace = _FakeWorkspace()@staticmethod@@ -564,6 +461,12 @@ async def test_create_team_does_not_run_global_runtime_cleanup(monkeypatch: pyte"_initialize_team_shared_skill_links",staticmethod(lambda spec: None),)+ # Provider assembly is covered by the swarm suite; stub it so this+ # session-management test runs on the minimal fake spec.+ monkeypatch.setattr(+ "jiuwenswarm.agents.swarm.enrich_team_spec_for_swarm",+ lambda spec, **kwargs: None,+ )manager = TeamManager()team_agent = await manager.create_team("sess-1", deep_agent=object(), channel_id="web")@@ -582,7 +485,6 @@ async def test_create_team_appends_session_id_to_team_name(monkeypatch: pytest.Mclass _Spec:def __init__(self) -> None:self.team_name = "demo_team"- self.agent_customizer = Noneself.workspace = _FakeWorkspace()def build(self):@@ -595,6 +497,12 @@ async def test_create_team_appends_session_id_to_team_name(monkeypatch: pytest.M"_initialize_team_shared_skill_links",staticmethod(lambda spec: None),)+ # Provider assembly is covered by the swarm suite; stub it so this+ # session-management test runs on the minimal fake spec.+ monkeypatch.setattr(+ "jiuwenswarm.agents.swarm.enrich_team_spec_for_swarm",+ lambda spec, **kwargs: None,+ )manager = TeamManager()team_agent = await manager.create_team("oc_abc123", deep_agent=object(), channel_id="feishu")@@ -613,7 +521,6 @@ async def test_create_team_appends_session_id_to_web_team_name(monkeypatch: pyteclass _Spec:def __init__(self) -> None:self.team_name = "demo_team"- self.agent_customizer = Noneself.workspace = _FakeWorkspace()def build(self):@@ -626,6 +533,12 @@ async def test_create_team_appends_session_id_to_web_team_name(monkeypatch: pyte"_initialize_team_shared_skill_links",staticmethod(lambda spec: None),)+ # Provider assembly is covered by the swarm suite; stub it so this+ # session-management test runs on the minimal fake spec.+ monkeypatch.setattr(+ "jiuwenswarm.agents.swarm.enrich_team_spec_for_swarm",+ lambda spec, **kwargs: None,+ )manager = TeamManager()team_agent = await manager.create_team("oc_abc123", deep_agent=object(), channel_id="web")diff --git a/tests/unit_tests/agentserver/test_team_manager_runtime_tools.py b/tests/unit_tests/agentserver/test_team_manager_runtime_tools.pydeleted file mode 100644index 767f222016..0000000000--- a/tests/unit_tests/agentserver/test_team_manager_runtime_tools.py+++ /dev/null@@ -1,100 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.--"""Unit tests for team member runtime tool registration."""--from types import SimpleNamespace--from openjiuwen.core.foundation.tool import LocalFunction, ToolCard-from openjiuwen.core.single_agent.ability_manager import AbilityManager--from jiuwenswarm.agents.harness.team.team_manager import TeamManager---class _FakeResourceManager:- def __init__(self) -> None:- self.tools = {}-- def get_tool(self, tool_id):- return self.tools.get(tool_id)-- def add_tool(self, tools):- items = tools if isinstance(tools, list) else [tools]- for tool in items:- self.tools[tool.card.id] = tool---class _FakeCronRuntimeBridge:- @staticmethod- def build_tools(*, context, agent_id, language="cn"):- _ = (context, agent_id, language)- return [- LocalFunction(- card=ToolCard(- id="cron_list_jobs_member-agent",- name="cron_list_jobs",- description="cron list",- input_params={"type": "object"},- ),- func=lambda **_: None,- )- ]---class _FakeSendFileToolkit:- def __init__(self, request_id, session_id, channel_id, *, metadata=None):- self.request_id = request_id- self.session_id = session_id- self.channel_id = channel_id- self.metadata = metadata-- @staticmethod- def get_tools():- return [- LocalFunction(- card=ToolCard(- id="send_file_to_user_tool",- name="send_file_to_user",- description="send file",- input_params={"type": "object"},- ),- func=lambda **_: None,- )- ]---def test_register_member_runtime_tools_adds_cron_and_send_file(monkeypatch):- resource_mgr = _FakeResourceManager()- monkeypatch.setattr(- "jiuwenswarm.agents.harness.common.tools.cron.cron_runtime.CronRuntimeBridge",- _FakeCronRuntimeBridge,- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.common.tools.send_file_to_user.SendFileToolkit",- _FakeSendFileToolkit,- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_config",- lambda: {"channels": {"web": {"send_file_allowed": True}}},- )- monkeypatch.setattr(- "openjiuwen.core.runner.Runner.resource_mgr",- resource_mgr,- raising=False,- )-- agent = SimpleNamespace(- card=SimpleNamespace(id="member-agent", name="member-agent"),- ability_manager=AbilityManager(),- deep_config=SimpleNamespace(language="cn"),- )-- TeamManager.register_member_runtime_tools(- agent,- session_id="sess-1",- request_id="req-1",- channel_id="web",- request_metadata={"request_id": "req-1"},- )-- assert agent.ability_manager.get("cron_list_jobs") is not None- assert agent.ability_manager.get("send_file_to_user") is not Nonediff --git a/tests/unit_tests/agentserver/test_team_manager_skill_state.py b/tests/unit_tests/agentserver/test_team_manager_skill_state.pyindex 8823d87ea5..c16eb506b7 100644--- a/tests/unit_tests/agentserver/test_team_manager_skill_state.py+++ b/tests/unit_tests/agentserver/test_team_manager_skill_state.py@@ -2,338 +2,10 @@"""Unit tests for team member skill views."""-import jsonfrom pathlib import Pathfrom types import SimpleNamespace-from openjiuwen.agent_teams.schema.blueprint import TeamAgentSpec-from jiuwenswarm.agents.harness.team.team_manager import TeamManager---def test_member_skill_view_links_configured_skills_without_state_file(monkeypatch, tmp_path):- """Member workspace should expose configured skill links without local state."""- global_skills_dir = tmp_path / "global_skills"- global_skills_dir.mkdir(parents=True)- for skill_name in ("skill-a", "skill-b"):- skill_dir = global_skills_dir / skill_name- skill_dir.mkdir()- (skill_dir / "SKILL.md").write_text(f"---\ndescription: {skill_name}\n---\n", encoding="utf-8")-- (global_skills_dir / "skills_state.json").write_text(- """-{- "marketplaces": [{"name": "demo", "url": "https://example.com/demo.git", "enabled": true}],- "installed_plugins": [- {"name": "skill-a", "marketplace": "demo", "version": "1.0.0", "source": "demo"},- {"name": "skill-b", "marketplace": "demo", "version": "1.0.0", "source": "demo"}- ],- "local_skills": [- {"name": "skill-a", "origin": "/tmp/skill-a", "source": "demo"},- {"name": "skill-b", "origin": "/tmp/skill-b", "source": "demo"}- ]-}- """.strip(),- encoding="utf-8",- )-- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_agent_skills_dir",- lambda: global_skills_dir,- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_agent_workspace_dir",- lambda: tmp_path / "global_workspace",- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_runtime_inheritance.build_member_rails",- lambda **kwargs: [],- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.common.plugins.rail_manager.get_rail_manager",- lambda: type(- "_DummyRailManager",- (),- {- "get_registered_rail_names": lambda self: [],- "load_rail_instance_without_enabled_check": lambda self, name: None,- },- )(),- )-- spec = TeamAgentSpec.model_validate(- {- "team_name": "demo_team",- "agents": {- "leader": {},- "member_a": {"skills": ["skill-a"]},- },- }- )- customizer = TeamManager.build_agent_customizer(- spec=spec,- deep_agent=type(- "_DeepAgent",- (),- {- "deep_config": type("_Config", (), {"sys_operation": None})(),- "ability_manager": type("_AbilityManager", (), {"list": lambda self: []})(),- },- )(),- session_id="session-1",- request_id=None,- channel_id=None,- request_metadata=None,- )-- member_root = tmp_path / "member_workspace"- agent = type(- "_Agent",- (),- {- "deep_config": type(- "_Config",- (),- {"workspace": type("_Workspace", (), {"root_path": str(member_root)})(), "sys_operation": None},- )(),- "ability_manager": type(- "_AbilityManager",- (),- {- "list": lambda self: [],- "add": lambda self, card: None,- },- )(),- "card": type("_Card", (), {"id": "member_a", "name": "member"})(),- "add_rail": lambda self, rail: None,- },- )()-- customizer(agent, member_name="member_a", role="teammate")-- member_skills_dir = member_root / "skills"- assert (member_skills_dir / "skill-a").resolve() == (global_skills_dir / "skill-a").resolve()- assert not (member_skills_dir / "skill-b").exists()- assert not (member_skills_dir / "skills_state.json").exists()---def test_code_team_customizer_applies_code_profile_to_member(monkeypatch, tmp_path):- """code.team parent agents should make each team member use the code profile."""- global_skills_dir = tmp_path / "global_skills"- global_skills_dir.mkdir(parents=True)- (global_skills_dir / "skills_state.json").write_text(- json.dumps({"marketplaces": [], "installed_plugins": [], "local_skills": []}),- encoding="utf-8",- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_agent_skills_dir",- lambda: global_skills_dir,- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_agent_workspace_dir",- lambda: tmp_path / "global_workspace",- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.build_member_rails",- lambda **kwargs: [],- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.common.plugins.rail_manager.get_rail_manager",- lambda: type(- "_DummyRailManager",- (),- {- "get_registered_rail_names": lambda self: [],- "load_rail_instance_without_enabled_check": lambda self, name: None,- },- )(),- )- monkeypatch.setattr(- TeamManager,- "register_member_runtime_tools",- staticmethod(lambda *args, **kwargs: None),- )-- calls = []-- def fake_configure_code_member(agent, **kwargs):- calls.append({"agent": agent, **kwargs})-- monkeypatch.setattr(- "jiuwenswarm.server.runtime.agent_adapter.interface_code.configure_code_team_member_agent",- fake_configure_code_member,- )-- spec = TeamAgentSpec.model_validate(- {- "team_name": "demo_team",- "agents": {- "leader": {},- "member_a": {},- },- }- )- parent_project = tmp_path / "project"- parent_project.mkdir()- parent_agent = SimpleNamespace(- _jiuwenswarm_adapter_mode="code",- _jiuwenswarm_code_project_dir=str(parent_project),- deep_config=SimpleNamespace(- workspace=SimpleNamespace(root_path=str(parent_project)),- sys_operation=None,- ),- ability_manager=SimpleNamespace(list=lambda: []),- )- customizer = TeamManager.build_agent_customizer(- spec=spec,- deep_agent=parent_agent,- session_id="session-1",- request_id="request-1",- channel_id="tui",- request_metadata={"source": "test"},- )-- class AbilityManager:- def __init__(self):- self.cards = []-- def list(self):- return list(self.cards)-- def add(self, card):- self.cards.append(card)-- class Agent:- def __init__(self):- self.deep_config = SimpleNamespace(- workspace=SimpleNamespace(root_path=str(tmp_path / "member_workspace")),- sys_operation=None,- )- self.ability_manager = AbilityManager()- self.card = SimpleNamespace(id="member_a", name="member")- self.rails = []-- def add_rail(self, rail):- self.rails.append(rail)-- agent = Agent()-- customizer(agent, member_name="member_a", role="teammate")-- assert len(calls) == 1- assert calls[0]["agent"] is agent- assert calls[0]["parent_agent"] is parent_agent- assert calls[0]["member_name"] == "member_a"- assert calls[0]["role"] == "teammate"- assert calls[0]["session_id"] == "session-1"- assert calls[0]["channel_id"] == "tui"- assert calls[0]["project_dir"] == str(parent_project)- assert calls[0]["skill_manager"] is not None- assert calls[0]["runtime_language"] is None- assert calls[0]["force_english_runtime_prompt"] is True---def test_team_plan_leader_uses_preferred_language_for_code_profile(monkeypatch, tmp_path):- """team.plan leader should not inherit code profile's English-only runtime prompt."""- global_skills_dir = tmp_path / "global_skills"- global_skills_dir.mkdir(parents=True)- (global_skills_dir / "skills_state.json").write_text(- json.dumps({"marketplaces": [], "installed_plugins": [], "local_skills": []}),- encoding="utf-8",- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_agent_skills_dir",- lambda: global_skills_dir,- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_agent_workspace_dir",- lambda: tmp_path / "global_workspace",- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.build_member_rails",- lambda **kwargs: [],- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_config",- lambda: {"preferred_language": "zh"},- )- monkeypatch.setattr(- TeamManager,- "register_member_runtime_tools",- staticmethod(lambda *args, **kwargs: None),- )-- calls = []-- def fake_configure_code_member(agent, **kwargs):- calls.append({"agent": agent, **kwargs})-- monkeypatch.setattr(- "jiuwenswarm.server.runtime.agent_adapter.interface_code.configure_code_team_member_agent",- fake_configure_code_member,- )-- spec = TeamAgentSpec.model_validate(- {- "team_name": "demo_team",- "agents": {- "leader": {},- "member_a": {},- },- "language": "cn",- }- )- parent_project = tmp_path / "project"- parent_project.mkdir()- parent_agent = SimpleNamespace(- _jiuwenswarm_adapter_mode="code",- _jiuwenswarm_code_project_dir=str(parent_project),- deep_config=SimpleNamespace(- workspace=SimpleNamespace(root_path=str(parent_project)),- sys_operation=None,- ),- ability_manager=SimpleNamespace(list=lambda: []),- )- customizer = TeamManager.build_agent_customizer(- spec=spec,- deep_agent=parent_agent,- session_id="session-1",- request_id="request-1",- channel_id="tui",- request_metadata={"mode": "team.plan"},- )-- class AbilityManager:- def __init__(self):- self.cards = []-- def list(self):- return list(self.cards)-- def add(self, card):- self.cards.append(card)-- class Agent:- def __init__(self):- self.deep_config = SimpleNamespace(- workspace=SimpleNamespace(root_path=str(tmp_path / "leader_workspace")),- sys_operation=None,- )- self.ability_manager = AbilityManager()- self.card = SimpleNamespace(id="team_leader", name="leader")- self.rails = []-- def add_rail(self, rail):- self.rails.append(rail)-- agent = Agent()-- customizer(agent, member_name="team_leader", role="leader")-- assert len(calls) == 1- assert calls[0]["agent"] is agent- assert calls[0]["runtime_language"] == "cn"- assert calls[0]["force_english_runtime_prompt"] is Falsedef test_configure_code_team_member_uses_agent_workspace_coding_memory_path(monkeypatch, tmp_path):diff --git a/tests/unit_tests/agentserver/test_team_member_skill_toolkit_rail.py b/tests/unit_tests/agentserver/test_team_member_skill_toolkit_rail.pyindex e76296c40a..be74ec0d0c 100644--- a/tests/unit_tests/agentserver/test_team_member_skill_toolkit_rail.py+++ b/tests/unit_tests/agentserver/test_team_member_skill_toolkit_rail.py@@ -19,9 +19,11 @@ class _FakeResourceManager:self.tools = {}self.removed = []- def add_tool(self, tools):+ def add_tool(self, tools, *, tag=None, refresh=False, skip_if_exists=False):items = tools if isinstance(tools, list) else [tools]for tool in items:+ if skip_if_exists and tool.card.id in self.tools:+ continueself.tools[tool.card.id] = tooldef remove_tool(self, tool_id):@@ -57,17 +59,9 @@ class _FakeSkillToolkit:def _make_agent(agent_id: str):- ability_manager = AbilityManager()- for tool_name in ("search_skill", "install_skill", "uninstall_skill"):- ability_manager.add(- ToolCard(- id=tool_name,- name=tool_name,- description=f"global {tool_name}",- input_params={"type": "object"},- )- )-+ # The owner id drives ``add_ability`` id qualification (mirrors how+ # BaseAgent / DeepAgent.configure wire it from the agent card in production).+ ability_manager = AbilityManager(owner_id=agent_id)return SimpleNamespace(card=SimpleNamespace(id=agent_id, name=agent_id),ability_manager=ability_manager,@@ -79,7 +73,7 @@ def test_team_member_skill_toolkit_rail_init_registers_member_scoped_tools(monkeresource_mgr = _FakeResourceManager()rail_module = "jiuwenswarm.agents.harness.team.rails.team_member_skill_toolkit_rail"- monkeypatch.setattr(f"{rail_module}.Runner", SimpleNamespace(resource_mgr=resource_mgr))+ monkeypatch.setattr("openjiuwen.core.runner.Runner.resource_mgr", resource_mgr, raising=False)monkeypatch.setattr(f"{rail_module}.SkillManager", _FakeSkillManager)monkeypatch.setattr(f"{rail_module}.SkillToolkit", _FakeSkillToolkit)@@ -103,7 +97,7 @@ def test_team_member_skill_toolkit_rail_uninit_cleans_up_registered_tools(monkeyresource_mgr = _FakeResourceManager()rail_module = "jiuwenswarm.agents.harness.team.rails.team_member_skill_toolkit_rail"- monkeypatch.setattr(f"{rail_module}.Runner", SimpleNamespace(resource_mgr=resource_mgr))+ monkeypatch.setattr("openjiuwen.core.runner.Runner.resource_mgr", resource_mgr, raising=False)monkeypatch.setattr(f"{rail_module}.SkillManager", _FakeSkillManager)monkeypatch.setattr(f"{rail_module}.SkillToolkit", _FakeSkillToolkit)@@ -146,7 +140,7 @@ async def test_team_member_skill_toolkit_rail_refreshes_links_after_install(monk)return [LocalFunction(card=card, func=self.install_skill)]- monkeypatch.setattr(f"{rail_module}.Runner", SimpleNamespace(resource_mgr=resource_mgr))+ monkeypatch.setattr("openjiuwen.core.runner.Runner.resource_mgr", resource_mgr, raising=False)monkeypatch.setattr(f"{rail_module}.SkillToolkit", _InstallSkillToolkit)monkeypatch.setattr(_InstallSkillToolkit, "__init__", lambda self, manager: toolkit_managers.append(manager))diff --git a/tests/unit_tests/agentserver/test_team_shared_skills.py b/tests/unit_tests/agentserver/test_team_shared_skills.pyindex 465f18b564..483d3ae702 100644--- a/tests/unit_tests/agentserver/test_team_shared_skills.py+++ b/tests/unit_tests/agentserver/test_team_shared_skills.py@@ -15,11 +15,8 @@ from openjiuwen.agent_teams.schema.blueprint import TeamAgentSpecfrom jiuwenswarm.agents.harness.team.rails.team_shared_skill_link_refresh_rail import (TeamSharedSkillLinkRefreshRail,)-from jiuwenswarm.agents.harness.team.rails.team_member_skill_toolkit_rail import (- MemberSkillToolkitRail,-)from jiuwenswarm.agents.harness.team.team_manager import TeamManager-from jiuwenswarm.agents.harness.team.team_skill_links import link_skill_dir, remove_skill_dir_link+from jiuwenswarm.agents.harness.team.team_skill_links import remove_skill_dir_linkdef _assert_link_points_to(path: Path, target: Path) -> None:@@ -106,168 +103,6 @@ def test_existing_skill_entry_is_not_replaced(tmp_path, monkeypatch):assert "existing-skill-a" in (team_shared_skills / "skill-a" / "SKILL.md").read_text(encoding="utf-8")-def test_member_configured_skills_linked_to_own_dir(tmp_path, monkeypatch):- """Member-configured skills should be linked to member's own skills directory."""- global_skills_dir = tmp_path / "global_skills"- global_skills_dir.mkdir(parents=True)- for skill_name in ("skill-a", "skill-b", "skill-c"):- skill_dir = global_skills_dir / skill_name- skill_dir.mkdir()- (skill_dir / "SKILL.md").write_text(f"---\nname: {skill_name}\n---\n", encoding="utf-8")- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_agent_skills_dir",- lambda: global_skills_dir,- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_agent_workspace_dir",- lambda: tmp_path / "global_workspace",- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_runtime_inheritance.build_member_rails",- lambda **kwargs: [],- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.common.plugins.rail_manager.get_rail_manager",- lambda: type(- "_DummyRailManager",- (),- {- "get_registered_rail_names": lambda self: [],- "load_rail_instance_without_enabled_check": lambda self, name: None,- },- )(),- )-- # Create team shared directory.- team_workspace = tmp_path / "team_workspace"- team_workspace.mkdir(parents=True)- team_shared_skills = team_workspace / "skills"- team_shared_skills.mkdir(parents=True)-- member_root = tmp_path / "member_workspace"- member_root.mkdir(parents=True)- (member_root / "skills").mkdir(parents=True)-- spec = TeamAgentSpec.model_validate(- {- "team_name": "demo_team",- "agents": {- "leader": {},- "member_a": {"skills": ["skill-a"]}, # Only configure skill-a- },- "workspace": {"root_path": str(team_workspace), "enabled": True},- }- )- TeamManager().ensure_team_shared_skills_initialized(spec)-- customizer = TeamManager.build_agent_customizer(- spec=spec,- deep_agent=type("_DeepAgent", (), {- "deep_config": type("_Config", (), {"sys_operation": None})(),- "ability_manager": type("_AbilityManager", (), {"list": lambda self: []})(),- })(),- session_id="session-1",- )-- agent = type("_Agent", (), {- "deep_config": type("_Config", (), {- "workspace": type("_Workspace", (), {"root_path": str(member_root)})(),- "sys_operation": None,- })(),- "ability_manager": type("_AbilityManager", (), {"list": lambda self: [], "add": lambda self, card: None})(),- "card": type("_Card", (), {"id": "member_a", "name": "member"})(),- "add_rail": lambda self, rail: None,- })()-- customizer(agent, member_name="member_a", role="teammate")-- # Only member-configured skills are linked into the member workspace on spawn.- member_skills_dir = member_root / "skills"- assert member_skills_dir.is_dir()- assert not member_skills_dir.is_symlink()- _assert_link_points_to(member_skills_dir / "skill-a", global_skills_dir / "skill-a")- assert not (member_skills_dir / "skill-b").exists()- assert not (member_skills_dir / "skill-c").exists()-- assert not (member_skills_dir / "skills_state.json").exists()---def test_member_no_configured_skills_keeps_empty_link_view(tmp_path, monkeypatch):- """When member has no configured skills, member directory does not link shared skills."""- global_skills_dir = tmp_path / "global_skills"- global_skills_dir.mkdir(parents=True)- for skill_name in ("skill-a", "skill-b", "skill-c"):- skill_dir = global_skills_dir / skill_name- skill_dir.mkdir()- (skill_dir / "SKILL.md").write_text(f"---\nname: {skill_name}\n---\n", encoding="utf-8")- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_agent_skills_dir",- lambda: global_skills_dir,- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_agent_workspace_dir",- lambda: tmp_path / "global_workspace",- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_runtime_inheritance.build_member_rails",- lambda **kwargs: [],- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.common.plugins.rail_manager.get_rail_manager",- lambda: type("_DummyRailManager", (), {- "get_registered_rail_names": lambda self: [],- "load_rail_instance_without_enabled_check": lambda self, name: None,- })(),- )-- # Create team shared directory- team_workspace = tmp_path / "team_workspace"- team_workspace.mkdir(parents=True)- team_shared_skills = team_workspace / "skills"- team_shared_skills.mkdir(parents=True)- member_root = tmp_path / "member_workspace"- member_root.mkdir(parents=True)- (member_root / "skills").mkdir(parents=True)-- spec = TeamAgentSpec.model_validate(- {- "team_name": "demo_team",- "agents": {- "leader": {},- "member_a": {}, # No skills configured- },- "workspace": {"root_path": str(team_workspace), "enabled": True},- }- )-- customizer = TeamManager.build_agent_customizer(- spec=spec,- deep_agent=type("_DeepAgent", (), {- "deep_config": type("_Config", (), {"sys_operation": None})(),- "ability_manager": type("_AbilityManager", (), {"list": lambda self: []})(),- })(),- session_id="session-1",- )-- agent = type("_Agent", (), {- "deep_config": type("_Config", (), {- "workspace": type("_Workspace", (), {"root_path": str(member_root)})(),- "sys_operation": None,- })(),- "ability_manager": type("_AbilityManager", (), {"list": lambda self: [], "add": lambda self, card: None})(),- "card": type("_Card", (), {"id": "member_a", "name": "member"})(),- "add_rail": lambda self, rail: None,- })()-- customizer(agent, member_name="member_a", role="teammate")-- member_skills_dir = member_root / "skills"- assert not (member_skills_dir / "skill-a").exists()- assert not (member_skills_dir / "skill-b").exists()- assert not (member_skills_dir / "skill-c").exists()- assert not (member_skills_dir / "skills_state.json").exists()--def test_refresh_team_shared_skill_links_adds_new_global_skill(tmp_path, monkeypatch):"""Refreshing shared links should add newly installed global skills."""global_skills_dir = tmp_path / "global_skills"@@ -327,266 +162,6 @@ def test_refresh_team_shared_skill_links_prunes_removed_global_skill(tmp_path, massert not os.path.lexists(team_shared_skills / "skill-b")-def test_member_skill_tool_install_refresh_does_not_link_unselected_skill(tmp_path, monkeypatch):- """Installing a skill should refresh team shared links without broadening member-selected links."""- global_skills_dir = tmp_path / "global_skills"- global_skills_dir.mkdir(parents=True)- skill_a = global_skills_dir / "skill-a"- skill_a.mkdir()- (skill_a / "SKILL.md").write_text("---\nname: skill-a\n---\n", encoding="utf-8")-- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_agent_skills_dir",- lambda: global_skills_dir,- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_agent_workspace_dir",- lambda: tmp_path / "global_workspace",- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_runtime_inheritance.build_member_rails",- lambda **kwargs: [],- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.common.plugins.rail_manager.get_rail_manager",- lambda: type(- "_DummyRailManager",- (),- {- "get_registered_rail_names": lambda self: [],- "load_rail_instance_without_enabled_check": lambda self, name: None,- },- )(),- )-- team_workspace = tmp_path / "team_workspace"- team_workspace.mkdir(parents=True)- spec = TeamAgentSpec.model_validate(- {- "team_name": "demo_team",- "agents": {- "leader": {},- "member_a": {"skills": ["skill-a"]},- },- "workspace": {"root_path": str(team_workspace), "enabled": True},- }- )-- customizer = TeamManager.build_agent_customizer(- spec=spec,- deep_agent=type(- "_DeepAgent",- (),- {- "deep_config": type("_Config", (), {"sys_operation": None})(),- "ability_manager": type("_AbilityManager", (), {"list": lambda self: []})(),- },- )(),- session_id="session-1",- )-- rails = []- member_root = tmp_path / "member_workspace"- agent = type(- "_Agent",- (),- {- "deep_config": type(- "_Config",- (),- {"workspace": type("_Workspace", (), {"root_path": str(member_root)})(), "sys_operation": None},- )(),- "ability_manager": type("_AbilityManager", (), {"list": lambda self: [], "add": lambda self, card: None})(),- "card": type("_Card", (), {"id": "member_a", "name": "member"})(),- "add_rail": lambda self, rail: rails.append(rail),- },- )()-- customizer(agent, member_name="member_a", role="teammate")- member_rail = next(rail for rail in rails if isinstance(rail, MemberSkillToolkitRail))- skill_b = global_skills_dir / "skill-b"- skill_b.mkdir()- (skill_b / "SKILL.md").write_text("---\nname: skill-b\n---\n", encoding="utf-8")-- member_rail._refresh_links({"success": True, "skill": {"name": "skill-b"}})-- member_skills_dir = member_root / "skills"- team_shared_skills = team_workspace / "skills"- _assert_link_points_to(member_skills_dir / "skill-a", skill_a)- assert not os.path.lexists(member_skills_dir / "skill-b")- _assert_link_points_to(team_shared_skills / "skill-b", skill_b)---def test_member_skill_tool_uninstall_removes_member_link(tmp_path, monkeypatch):- """Uninstalling a selected skill should remove the member's stale skill link."""- global_skills_dir = tmp_path / "global_skills"- global_skills_dir.mkdir(parents=True)- skill_a = global_skills_dir / "skill-a"- skill_a.mkdir()- (skill_a / "SKILL.md").write_text("---\nname: skill-a\n---\n", encoding="utf-8")-- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_agent_skills_dir",- lambda: global_skills_dir,- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_agent_workspace_dir",- lambda: tmp_path / "global_workspace",- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_runtime_inheritance.build_member_rails",- lambda **kwargs: [],- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.common.plugins.rail_manager.get_rail_manager",- lambda: type(- "_DummyRailManager",- (),- {- "get_registered_rail_names": lambda self: [],- "load_rail_instance_without_enabled_check": lambda self, name: None,- },- )(),- )-- team_workspace = tmp_path / "team_workspace"- team_workspace.mkdir(parents=True)- spec = TeamAgentSpec.model_validate(- {- "team_name": "demo_team",- "agents": {- "leader": {},- "member_a": {"skills": ["skill-a"]},- },- "workspace": {"root_path": str(team_workspace), "enabled": True},- }- )-- customizer = TeamManager.build_agent_customizer(- spec=spec,- deep_agent=type(- "_DeepAgent",- (),- {- "deep_config": type("_Config", (), {"sys_operation": None})(),- "ability_manager": type("_AbilityManager", (), {"list": lambda self: []})(),- },- )(),- session_id="session-2",- )-- rails = []- member_root = tmp_path / "member_workspace"- agent = type(- "_Agent",- (),- {- "deep_config": type(- "_Config",- (),- {"workspace": type("_Workspace", (), {"root_path": str(member_root)})(), "sys_operation": None},- )(),- "ability_manager": type("_AbilityManager", (), {"list": lambda self: [], "add": lambda self, card: None})(),- "card": type("_Card", (), {"id": "member_a", "name": "member"})(),- "add_rail": lambda self, rail: rails.append(rail),- },- )()-- customizer(agent, member_name="member_a", role="teammate")- member_skills_dir = member_root / "skills"- _assert_link_points_to(member_skills_dir / "skill-a", skill_a)-- shutil.rmtree(skill_a)- member_rail = next(rail for rail in rails if isinstance(rail, MemberSkillToolkitRail))- member_rail._refresh_links({"success": True, "removed": True, "name": "skill-a"})-- assert not os.path.lexists(member_skills_dir / "skill-a")- assert not os.path.lexists(team_workspace / "skills" / "skill-a")---def test_member_configured_skill_sync_prunes_unselected_link(tmp_path, monkeypatch):- """Member initialization should remove stale unselected skill links only when they are links."""- global_skills_dir = tmp_path / "global_skills"- global_skills_dir.mkdir(parents=True)- for skill_name in ("skill-a", "skill-b"):- skill_dir = global_skills_dir / skill_name- skill_dir.mkdir()- (skill_dir / "SKILL.md").write_text(f"---\nname: {skill_name}\n---\n", encoding="utf-8")-- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_agent_skills_dir",- lambda: global_skills_dir,- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_manager.get_agent_workspace_dir",- lambda: tmp_path / "global_workspace",- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.team.team_runtime_inheritance.build_member_rails",- lambda **kwargs: [],- )- monkeypatch.setattr(- "jiuwenswarm.agents.harness.common.plugins.rail_manager.get_rail_manager",- lambda: type(- "_DummyRailManager",- (),- {- "get_registered_rail_names": lambda self: [],- "load_rail_instance_without_enabled_check": lambda self, name: None,- },- )(),- )-- team_workspace = tmp_path / "team_workspace"- team_workspace.mkdir(parents=True)- member_root = tmp_path / "member_workspace"- member_skills_dir = member_root / "skills"- member_skills_dir.mkdir(parents=True)- link_skill_dir(global_skills_dir / "skill-b", member_skills_dir / "skill-b")-- spec = TeamAgentSpec.model_validate(- {- "team_name": "demo_team",- "agents": {- "leader": {},- "member_a": {"skills": ["skill-a"]},- },- "workspace": {"root_path": str(team_workspace), "enabled": True},- }- )- customizer = TeamManager.build_agent_customizer(- spec=spec,- deep_agent=type(- "_DeepAgent",- (),- {- "deep_config": type("_Config", (), {"sys_operation": None})(),- "ability_manager": type("_AbilityManager", (), {"list": lambda self: []})(),- },- )(),- session_id="session-3",- )- agent = type(- "_Agent",- (),- {- "deep_config": type(- "_Config",- (),- {"workspace": type("_Workspace", (), {"root_path": str(member_root)})(), "sys_operation": None},- )(),- "ability_manager": type("_AbilityManager", (), {"list": lambda self: [], "add": lambda self, card: None})(),- "card": type("_Card", (), {"id": "member_a", "name": "member"})(),- "add_rail": lambda self, rail: None,- },- )()-- customizer(agent, member_name="member_a", role="teammate")-- _assert_link_points_to(member_skills_dir / "skill-a", global_skills_dir / "skill-a")- assert not os.path.lexists(member_skills_dir / "skill-b")--def test_remove_skill_dir_link_keeps_ordinary_directory(tmp_path):"""Removing a skill link should not delete ordinary directories."""ordinary_skill_dir = tmp_path / "ordinary-skill"diff --git a/uv.lock b/uv.lockindex a38c779f7d..93701fecca 100644--- a/uv.lock+++ b/uv.lock@@ -2642,7 +2642,7 @@ wheels = [[[package]]name = "openjiuwen"version = "0.1.14"-source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=develop#ca551cf83f90e18fa024cb33f02bd1977dff9d37" }+source = { git = "https://gitcode.com/openJiuwen/agent-core.git?rev=develop#59a675dd57ea929e071f0a410ba7db1d22679869" }dependencies = [{ name = "aiofiles" },{ name = "aiohttp" },@@ -2672,7 +2672,7 @@ dependencies = [{ name = "python-docx" },{ name = "python-dotenv" },{ name = "requests" },- { name = "sqlalchemy" },+ { name = "sqlalchemy", extra = ["asyncio"] },{ name = "sqlmodel" },{ name = "tenacity" },{ name = "tiktoken" },@@ -4577,6 +4577,11 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/e5/30/8519fdde58a7bdf155b714359791ad1dc018b47d60269d5d160d311fdc36/sqlalchemy-2.0.49-py3-none-any.whl", hash = "sha256:ec44cfa7ef1a728e88ad41674de50f6db8cfdb3e2af84af86e0041aaf02d43d0", size = 1942158, upload-time = "2026-04-03T16:53:44.135Z" },]+[package.optional-dependencies]+asyncio = [+ { name = "greenlet" },+]+[[package]]name = "sqlite-vec"version = "0.1.6"