JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(flash): 修复 PPT 加速依赖技能检索的问题
wangjiudong06d5ca29260b
diff --git a/jiuwenswarm/agents/harness/flash/rails/flash_turbo_prompt_rail.py b/jiuwenswarm/agents/harness/flash/rails/flash_turbo_prompt_rail.pynew file mode 100644index 0000000000..5a7916b997--- /dev/null+++ b/jiuwenswarm/agents/harness/flash/rails/flash_turbo_prompt_rail.py@@ -0,0 +1,97 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Flash Turbo routing guidance, independent of installed-skill retrieval."""++from __future__ import annotations++from openjiuwen.core.single_agent.rail.base import AgentCallbackContext+from openjiuwen.harness.prompts import PromptSection++from jiuwenswarm.agents.harness.common.prompt.prompt_builder import PromptPriority++from jiuwenswarm.server.runtime.skill_turbo.rails.skill_prompt_rail import (+ SkillTurboPromptRail,+ _SECTION_NAME,+ _SKILL_ACCELERATION_TOOL,+)+from jiuwenswarm.server.runtime.skill_turbo.region_edit import region_edit_keyword_summary+++class FlashTurboPromptRail(SkillTurboPromptRail):+ """Reuse Turbo discovery without restoring Deep's task-loop instructions."""++ async def before_model_call(self, ctx: AgentCallbackContext) -> None:+ builder = getattr(ctx.agent, "system_prompt_builder", None) or self.system_prompt_builder+ if builder is None:+ return+ self.system_prompt_builder = builder+ # Never guide the model to a tool absent from this call's actual tool set.+ tools = getattr(ctx.inputs, "tools", None) or []+ if self._acceleration_disabled or not any(tool.name == _SKILL_ACCELERATION_TOOL for tool in tools):+ builder.remove_section(_SECTION_NAME)+ return++ # Reuse cached discovery; Flash owns its guide without changing the shared rail.+ from jiuwenswarm.server.runtime.skill_turbo.skill_turbo_tools import (+ refresh_skill_acceleration_description,+ )++ skill_names = refresh_skill_acceleration_description()+ if not skill_names:+ builder.remove_section(_SECTION_NAME)+ return+ language = self._resolve_language()+ builder.add_section(PromptSection(+ name=_SECTION_NAME,+ content={language: self._build_guide_text(language, skill_names)},+ priority=self._resolve_priority(_SECTION_NAME, PromptPriority.SKILL_PROTOCOL),+ ))++ def _build_guide_text(self, language: str, skill_names: list[str]) -> str:+ names = "、".join(skill_names) if language == "cn" else ", ".join(skill_names)+ keywords = region_edit_keyword_summary()+ if language == "cn":+ return f"""## 技能加速通道(skill_acceleration_exec)++当前支持:{names}。以工具描述中的支持范围为准。+- 对符合支持范围的新建 PPT,第一个工具调用必须是 skill_acceleration_exec。+ 用户手动写“使用 pptx-craft 技能”和前端选择“幻灯片”遵循同一规则;指定 pptx-craft 包含使用它的加速流程,不代表要求普通流程。+ 这条规则不依赖技能检索开关,也适用于未指定技能的新建 PPT。+- 无需先检索、调用 skill_tool 加载 SKILL.md、搜索资料或检查环境,流水线会完成这些工作。+ 若已误加载 pptx-craft,但尚未生成产物且没有失败/不支持结果,仍应转入加速。+ 用户明确要求的、流水线不处理的独立前置任务须先完成;指定其他技能不能因涉及 PPT 就被替换。+- 用户明确要求普通流程或禁用加速时遵从。+ 模板包/指定的自定义模板文件(不含普通预置风格)、沿用已有 PPT 风格、图片转可编辑 PPT、编辑已有 PPTX 或选区({keywords})不走本加速通道;图片仅作为新建演示文稿的素材不属于图片转换。+ 按用户原始请求及历史上下文判断,不要把编辑任务改写为新建。+- query 忠实保留用户需求、附件路径和约束,不扩写需求;多个产物分别串行调用,等待前一任务结束后再开始下一任务。+- 成功后不要重复生成或重复发送交付总结;继续完成本请求剩余任务。+ 有待办时使用实际提供的 todo 工具更新。单个 PPT 成功不代表整个请求完成。+- 返回失败或未处理时,改用 skill_tool 的标准流程完成该任务,不重复尝试同一加速任务。+ 若提示已有完成产物,继续编辑该产物,不从头重跑。+- 等待审批、用户回答或返回 __skill_turbo_hitl__ 是暂停,不是失败。+ 停止后续工具调用并等待原任务续跑,不切到普通流程重新生成。+"""+ return f"""## Skill Acceleration Channel (skill_acceleration_exec)++Currently supported: {names}. Follow the supported scope in the tool description.+- For supported new PPT tasks, the FIRST tool call MUST be skill_acceleration_exec.+ Typing “使用 pptx-craft 技能” and selecting “幻灯片” use the same rule: naming pptx-craft includes its accelerated workflow, not a request for the standard workflow.+ This rule is independent of skill retrieval and also covers new PPT requests without an explicit skill name.+- Do not first search skills, load SKILL.md through skill_tool, research, or check the environment; the pipeline handles these steps.+ If pptx-craft was mistakenly loaded but no artifact was generated and no failure/unsupported result was returned, still use acceleration.+ First complete any explicitly requested independent prerequisite the pipeline cannot handle.+ Do not replace a different explicitly selected skill just because the task mentions PPT.+- Honor requests for the standard workflow or no acceleration.+ Exclude template packages/specified custom template files (not ordinary preset styles), reusing an existing PPT style, image-to-editable-PPT conversion, and existing PPTX or region edits ({keywords}).+ Images used only as material for a new deck are not image conversion.+ Judge the original request and history; never rewrite an edit as a new-deck task.+- Preserve the user's requirements, attachment paths, and constraints in query without inventing requirements.+ Invoke separately and serially for multiple artifacts, waiting for each task to end.+- After success, do not regenerate or repeat the delivery summary; complete remaining work.+ Update pending items using the available todo tool.+ One successful PPT does not imply the entire request is complete.+- On failure or an unhandled result, use skill_tool's standard workflow; do not retry the same acceleration task.+ If completed artifacts already exist, continue editing them without restarting generation.+- Approval, user questions, or __skill_turbo_hitl__ mean PAUSE, not failure.+ Stop further tool calls and wait for the original task to resume; do not restart through the standard workflow.+"""diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py b/jiuwenswarm/server/runtime/agent_adapter/interface_flash.pyindex bc14db3138..01d11d0b1a 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py@@ -244,6 +244,8 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):"_flash_artifact_post_process_rail",# Turbo 工具会缓存交付总结;保留发送组件,启用仍由父类 Turbo 开关控制。"_skill_turbo_delivery_summary_rail",+ # Turbo routing must remain available when skill retrieval is disabled.+ "_skill_turbo_prompt_rail","_task_planning_rail",# auto 档动态路由:请求级 enable_routing / 进程级 model_routing.enabled@@ -844,6 +846,16 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):return CodingArtifactPostProcessRail(coauthor_header_enabled=False)+ def _build_skill_turbo_prompt_rail(self) -> Any | None:+ """Use Flash guidance independently of the optional skill retriever."""+ if not self._flash_turbo_enabled(self._config_cache):+ return None+ from jiuwenswarm.agents.harness.flash.rails.flash_turbo_prompt_rail import (+ FlashTurboPromptRail,+ )++ return FlashTurboPromptRail()+def _build_skill_turbo_delivery_summary_rail(self) -> Any | None:"""仅在 Turbo 开启时装配 Flash 专用的总结与收尾组件。"""try:diff --git a/tests/unit_tests/agentserver/test_flash_adapter_tool_face.py b/tests/unit_tests/agentserver/test_flash_adapter_tool_face.pyindex c8a0844db0..5cf043441a 100644--- a/tests/unit_tests/agentserver/test_flash_adapter_tool_face.py+++ b/tests/unit_tests/agentserver/test_flash_adapter_tool_face.py@@ -76,10 +76,10 @@ def test_keep_whitelist_retains_skill_and_security_rails() -> None:"_disabled_tools_rail","_permission_rail","_filesystem_rail",+ "_skill_turbo_prompt_rail",]drop = ["_skill_evolution_rail",- "_skill_turbo_prompt_rail","_a2a_outbound_toolkit_rail","_symphony_orchestration_rail",]diff --git a/tests/unit_tests/agentserver/test_flash_turbo_discovery.py b/tests/unit_tests/agentserver/test_flash_turbo_discovery.pyindex da25c862cd..03011ab17f 100644--- a/tests/unit_tests/agentserver/test_flash_turbo_discovery.py+++ b/tests/unit_tests/agentserver/test_flash_turbo_discovery.py@@ -16,8 +16,10 @@ from openjiuwen.core.foundation.llm.schema.message_chunk import AssistantMessagefrom openjiuwen.core.runner import Runnerfrom openjiuwen.core.session.agent import Sessionfrom openjiuwen.harness import create_deep_agent+from openjiuwen.harness.rails.skills.skill_use_rail import SkillUseRailfrom jiuwenswarm.agents.harness.common.rails.progressive_tool_rail import ProgressiveToolRail+from jiuwenswarm.agents.harness.flash.skill_selection import execution, servicefrom jiuwenswarm.common import utilsfrom jiuwenswarm.common.local_env_config import bind_task_env_overlay, reset_task_env_overlayfrom jiuwenswarm.server.runtime.agent_adapter import interface_deep, interface_flash@@ -47,6 +49,10 @@ def skill_roots(tmp_path, monkeypatch):turbo = shared / "pptx-craft" / "turbo"codes = turbo / "turbo_codes" / "ppt"codes.mkdir(parents=True)+ (shared / "pptx-craft" / "SKILL.md").write_text(+ "---\nname: pptx-craft\ndescription: Create PPT presentations\n---\n# Workflow\nGenerate a deck.\n",+ encoding="utf-8",+ )(codes / "ppt_gen_root.py").write_text("root = None\n", encoding="utf-8")(turbo / "meta.json").write_text(json.dumps({"external_name": "pptx-craft", "description": "生成 PPT", "match_keywords": ["ppt"],@@ -55,12 +61,17 @@ def skill_roots(tmp_path, monkeypatch):monkeypatch.setattr(skill_turbo_tools, "_entries_cache", {})monkeypatch.setattr(skill_turbo_tools, "_last_good_entries", {})monkeypatch.setattr(skill_turbo_tools.skill_turbo.card, "description", "")- return empty, shared+ monkeypatch.setattr(execution, "_runtime", None)+ monkeypatch.setattr(execution, "_startup_gate", execution.StartupGate())+ monkeypatch.setattr(service, "_services", service.OrderedDict())+ yield empty, shared+ if execution._runtime is not None:+ execution._runtime.shutdown()-def _assemble_flash(monkeypatch, *, enabled=True, disabled=None, lazy=True):+def _assemble_flash(monkeypatch, *, enabled=True, disabled=None, lazy=True, selection=False, skill_root=None):adapter = object.__new__(JiuwenSwarmFlashAdapter)- config = adapter._apply_flash_react_override({"react": {+ config = adapter._apply_flash_react_override({"flash": {"skill_selection": {"enabled": selection}}, "react": {"skill_turbo": {"enabled": enabled},"tool_lazy_load": {"enabled": lazy},"disabled_tools": disabled or [],@@ -73,9 +84,11 @@ def _assemble_flash(monkeypatch, *, enabled=True, disabled=None, lazy=True):adapter._instance_overrides = {}adapter._stream_event_rail = adapter._checkpointer = Noneadapter._skill_turbo_prompt_rail = None+ adapter._skill_rail = Nonereal_builders = {"_build_agent_rails", "_build_progressive_tool_rail",- "_build_disabled_tools_rail",+ "_build_disabled_tools_rail", "_build_skill_turbo_prompt_rail",+ "_build_flash_skill_selection_rail",}for name in dir(JiuwenSwarmFlashAdapter):if name.startswith("_build_") and name not in real_builders:@@ -92,9 +105,11 @@ def _assemble_flash(monkeypatch, *, enabled=True, disabled=None, lazy=True):# real Flash request hook and exercise its ordering before the real SDK.monkeypatch.setattr(interface_deep.JiuWenSwarmDeepAdapter, "_update_runtime_config", AsyncMock())monkeypatch.setattr(adapter, "_sync_unified_memory_tool_visibility", Mock())+ if skill_root is not None:+ native = SkillUseRail([str(skill_root)], skill_mode="all", include_tools=False)+ monkeypatch.setattr(adapter, "_build_skill_rail", lambda **_: native)rails = adapter._build_agent_rails(config["react"], config, mode="flash")adapter._build_task_execution_rail.assert_not_called()- adapter._build_skill_turbo_prompt_rail.assert_not_called()adapter._build_skill_protocol_prompt_rail.assert_not_called()return adapter, rails@@ -122,15 +137,21 @@ class _Model:@pytest.mark.asyncio@pytest.mark.parametrize("mode", ["invoke", "stream"])@pytest.mark.parametrize("lazy", [True, False])[email protected]("selection", [False, True])[email protected]("query", [+ "生成环保碳中和汇报 PPT,全程不出现任何人像 使用 pptx-craft 技能",+ "幻灯片 生成环保碳中和汇报 PPT,全程不出现任何人像 使用 pptx-craft 技能",+ "生成环保碳中和汇报 PPT,全程不出现任何人像",+])async def test_relay_empty_prewarm_refreshes_before_first_real_model_call(- monkeypatch, tmp_path, skill_roots, mode, lazy,+ monkeypatch, tmp_path, skill_roots, mode, lazy, selection, query,):_, shared = skill_rootswith _skill_env():initial = skill_turbo_tools._build_tool_description()assert "当前内部支持:暂无" in initialskill_turbo_tools.skill_turbo.card.description = initial- adapter, rails = _assemble_flash(monkeypatch, lazy=lazy)+ adapter, rails = _assemble_flash(monkeypatch, lazy=lazy, selection=selection, skill_root=shared)scans = Mock(wraps=turbo_package_loader.discover_external_turbo_skills)monkeypatch.setattr(turbo_package_loader, "discover_external_turbo_skills", scans)@@ -151,13 +172,13 @@ async def test_relay_empty_prewarm_refreshes_before_first_real_model_call(session = Session(session_id=f"relay-flash-{uuid4().hex}", card=core.card)with _skill_env(shared):await adapter._update_runtime_config(SimpleNamespace(mode="flash"))- await session.pre_run(inputs={"query": "制作销售复盘 PPT"})+ await session.pre_run(inputs={"query": query})if mode == "stream":_ = [chunk async for chunk in core.stream(- {"query": "制作销售复盘 PPT"}, session=session,+ {"query": query}, session=session,)]else:- await core.invoke({"query": "制作销售复盘 PPT"}, session=session)+ await core.invoke({"query": query}, session=session)await session.post_run()assert len(model.calls) == 2for messages, tools in model.calls:@@ -166,8 +187,20 @@ async def test_relay_empty_prewarm_refreshes_before_first_real_model_call(assert "当前内部支持:pptx-craft" in cards[0].descriptionassert "暂无" not in cards[0].descriptionassert not any("当前内部支持:暂无" in str(message.content) for message in messages)- # Do not bring back the full Turbo guide (with legacy todo names).- assert not any("## 技能加速通道" in str(message.content) for message in messages)+ # The model needs routing guidance, not just a visible tool card.+ system_text = "\n".join(str(message.content) for message in messages if message.role == "system")+ assert "## 技能加速通道" in system_text+ assert "todo_modify" not in system_text+ assert "当前支持:pptx-craft" in system_text+ assert "第一个工具调用必须是 skill_acceleration_exec" in system_text+ assert "这条规则不依赖技能检索开关" in system_text+ assert "__skill_turbo_hitl__" in system_text+ assert any(message.content == query for message in messages if message.role == "user")+ tool_names = [tool.name for tool in tools]+ assert ("search_installed_skills" in tool_names) is selection+ selection_rail = adapter._flash_skill_selection_rail+ assert selection_rail._last_error is None+ assert (selection_rail.service is not None) is selection# The second request reuses the existing roots-keyed TTL cache.assert scans.call_count == 1finally:@@ -234,3 +267,36 @@ async def test_refresh_updates_a_copied_card_and_skips_missing_or_disabled_tool(adapter._instance.ability_manager.get = lambda _: Noneawait adapter._update_runtime_config(SimpleNamespace(mode="flash"))refresh.assert_not_called()+++async def test_turbo_guide_follows_request_roots_and_actual_tool_visibility(monkeypatch, tmp_path, skill_roots):+ empty, shared = skill_roots+ adapter, rails = _assemble_flash(monkeypatch)+ monkeypatch.setattr("openjiuwen.harness.deep_agent.schedule_image_support_probe", lambda *_: None)+ model = _Model()+ await Runner.start()+ core = create_deep_agent(+ model=model, tools=[], rails=rails, system_prompt="Test",+ enable_task_loop=False, max_iterations=2, workspace=str(tmp_path / "workspace"),+ )+ adapter._instance = core+ try:+ await core._ensure_initialized()+ adapter._init_skill_turbo_tool()+ for root, present, expected in [(empty, True, False), (shared, True, True),+ (empty, True, False), (shared, True, True),+ (shared, False, False)]:+ if not present:+ core.ability_manager.remove(TURBO_TOOL_NAME)+ with _skill_env(root):+ await adapter._update_runtime_config(SimpleNamespace(mode="flash"))+ session = Session(session_id=f"flash-roots-{uuid4().hex}", card=core.card)+ await session.pre_run(inputs={"query": "使用 pptx-craft 生成 PPT"})+ await core.invoke({"query": "使用 pptx-craft 生成 PPT"}, session=session)+ await session.post_run()+ messages, _ = model.calls[-1]+ text = "\n".join(str(m.content) for m in messages if m.role == "system")+ assert ("## 技能加速通道" in text) is expected+ finally:+ await core.stop()diff --git a/tests/unit_tests/server/runtime/skill_turbo/test_flash_delivery_summary.py b/tests/unit_tests/server/runtime/skill_turbo/test_flash_delivery_summary.pyindex b6b64ded7f..46624db6ec 100644--- a/tests/unit_tests/server/runtime/skill_turbo/test_flash_delivery_summary.py+++ b/tests/unit_tests/server/runtime/skill_turbo/test_flash_delivery_summary.py@@ -107,7 +107,7 @@ def assemble_flash(monkeypatch):monkeypatch.setattr(adapter, "_task_execution_rail_enabled", lambda: True)rails = adapter._build_agent_rails(config["react"], config, mode="flash")adapter._build_task_execution_rail.assert_not_called()- adapter._build_skill_turbo_prompt_rail.assert_not_called()+ adapter._build_skill_turbo_prompt_rail.assert_called_once()adapter._build_skill_protocol_prompt_rail.assert_not_called()return adapter, rails