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(agentserver): 拆分 LLM 补丁粒度并修正 SSE 渠道门控
guozirui15c142e6d7c76
diff --git a/jiuwenswarm/llm_sse_patch.py b/jiuwenswarm/llm_sse_patch.pyindex aa0aba3808..4a1a09f6ac 100644--- a/jiuwenswarm/llm_sse_patch.py+++ b/jiuwenswarm/llm_sse_patch.py@@ -95,7 +95,12 @@ def _sanitize_glm_tool_xml_tags(raw: str) -> str:return result_PATCH_APPLIED = False+# 每个补丁拥有独立的幂等标志:补丁之间互不短路,可以按渠道分别开启+# (例如仅 SSE 响应组装补丁需要按渠道门控)。_AUTH_HEADER_PATCH_APPLIED = False+_RESPONSE_ASSEMBLY_PATCH_APPLIED = False+_GLM_XML_SANITIZE_PATCH_APPLIED = False+_MAAS_SPAN_ID_PATCH_APPLIED = False_HUAWEI_MAAS_PLACEHOLDER_API_KEY = "huawei-maas-session"@@ -397,36 +402,39 @@ def assemble_openai_response(response: str) -> Any:)-def apply_openai_sse_invoke_patch() -> None:- """给 ``OpenAIModelClient`` 打补丁:-- 1. SSE-only 网关兼容:非流式调用下返回 str 时,先组装成标准 ChatCompletion。- 2. GLM XML 标签清洗:流式 chunk 中 tool_call.arguments 的 XML 标签剥离。- 3. 保留 tip ``default_headers`` 中的 ``Authorization``(Huawei MaaS Basic)。- 4. 华为 MaaS x-span-id 注入:调用华为云 ModelArts MaaS 时,在请求头注入- ``x-span-id`` 便于 MaaS 侧链路追踪。-- 幂等:重复调用只生效一次。在服务启动早期调用即可覆盖 subagent / 心跳等- 所有走 ``invoke()`` / ``stream()`` 的 LLM 调用。- """- global _PATCH_APPLIED- apply_openai_auth_header_patch()- if _PATCH_APPLIED:- return-+def _import_openai_model_client() -> Any | None:+ """导入 ``OpenAIModelClient``;openjiuwen 不可用时返回 ``None``。"""try:from openjiuwen.core.foundation.llm.model_clients.openai_model_client import (OpenAIModelClient,)except Exception as exc: # pragma: no cover - openjiuwen 不可用时静默跳过logger.warning("[llm_sse_patch] 未能导入 OpenAIModelClient,跳过补丁: %s", exc)+ return None+ return OpenAIModelClient+++def apply_openai_response_assembly_patch() -> None:+ """Patch 1: SSE-only 网关兼容 —— 非流式调用返回 ``str`` 时组装成标准 ``ChatCompletion``。++ 该补丁只对「以 ``text/event-stream`` 返回非流式响应」的网关有意义,因此是+ 唯一需要按渠道门控的补丁(见 ``app_agentserver._should_apply_sse_invoke_patch``);+ 其余补丁(GLM 清洗 / Authorization / MaaS x-span-id)对所有渠道无条件生效。++ 幂等:使用独立的 ``_RESPONSE_ASSEMBLY_PATCH_APPLIED`` 标志,不受其他补丁影响。+ """+ global _RESPONSE_ASSEMBLY_PATCH_APPLIED+ if _RESPONSE_ASSEMBLY_PATCH_APPLIED:+ return++ OpenAIModelClient = _import_openai_model_client()+ if OpenAIModelClient is None:return- if getattr(OpenAIModelClient, "_sse_invoke_patch_applied", False):- _PATCH_APPLIED = True+ if getattr(OpenAIModelClient, "_response_assembly_patch_applied", False):+ _RESPONSE_ASSEMBLY_PATCH_APPLIED = Truereturn- # --- Patch 1: _parse_response (SSE-only 网关兼容) ---_orig_parse_response = OpenAIModelClient._parse_response # pylint: disable=protected-accessasync def _parse_response_with_sse_guard(@@ -439,8 +447,30 @@ def apply_openai_sse_invoke_patch() -> None:return await _orig_parse_response(self, response, parser)OpenAIModelClient._parse_response = _parse_response_with_sse_guard # pylint: disable=protected-access+ OpenAIModelClient._response_assembly_patch_applied = True # pylint: disable=protected-access+ _RESPONSE_ASSEMBLY_PATCH_APPLIED = True+ logger.info("[llm_sse_patch] OpenAIModelClient SSE 响应组装补丁已应用")+++def apply_glm_tool_xml_sanitize_patch() -> None:+ """Patch 2: GLM XML 标签清洗 —— 剥离流式 chunk 中 tool_call.arguments 的原生 XML 标签。++ 生产使用 GLM 模型(含 glm-5.2)时必需,与渠道类型无关,必须无条件应用。++ 幂等:使用独立的 ``_GLM_XML_SANITIZE_PATCH_APPLIED`` 标志。+ """+ global _GLM_XML_SANITIZE_PATCH_APPLIED+ if _GLM_XML_SANITIZE_PATCH_APPLIED:+ return++ OpenAIModelClient = _import_openai_model_client()+ if OpenAIModelClient is None:+ return++ if getattr(OpenAIModelClient, "_glm_xml_sanitize_patch_applied", False):+ _GLM_XML_SANITIZE_PATCH_APPLIED = True+ return- # --- Patch 2: _parse_stream_chunk (GLM XML 标签清洗) ---_orig_parse_stream_chunk = OpenAIModelClient._parse_stream_chunk # pylint: disable=protected-accessdef _parse_stream_chunk_with_sanitize(self: Any, chunk: Any):@@ -458,12 +488,35 @@ def apply_openai_sse_invoke_patch() -> None:return resultOpenAIModelClient._parse_stream_chunk = _parse_stream_chunk_with_sanitize # pylint: disable=protected-access+ OpenAIModelClient._glm_xml_sanitize_patch_applied = True # pylint: disable=protected-access+ _GLM_XML_SANITIZE_PATCH_APPLIED = True+ logger.info("[llm_sse_patch] OpenAIModelClient GLM XML 标签清洗补丁已应用")+++def apply_huawei_maas_span_id_patch() -> None:+ """Patch 4: 华为 MaaS x-span-id 注入。++ 调用华为云 ModelArts MaaS 时,在请求头注入 ``x-span-id``(uuid4 hex)便于+ MaaS 侧链路追踪。通过包装 ``invoke`` / ``stream`` 出口,复用原 custom_headers+ 合并链路(``_build_request_headers``),非 MaaS 端点零开销透传。+ 每次 ``invoke`` / ``stream`` 调用(含重试触发的重新调用)都会生成独立 span_id。++ 生产 OfficeClaw + Huawei MaaS 链路依赖该补丁,与渠道类型无关,必须无条件应用。++ 幂等:使用独立的 ``_MAAS_SPAN_ID_PATCH_APPLIED`` 标志。+ """+ global _MAAS_SPAN_ID_PATCH_APPLIED+ if _MAAS_SPAN_ID_PATCH_APPLIED:+ return++ OpenAIModelClient = _import_openai_model_client()+ if OpenAIModelClient is None:+ return++ if getattr(OpenAIModelClient, "_maas_span_id_patch_applied", False):+ _MAAS_SPAN_ID_PATCH_APPLIED = True+ return- # --- Patch 3: invoke / stream 注入华为 MaaS x-span-id ---- # 调用华为云 ModelArts MaaS 时,在请求头注入 x-span-id(uuid4 hex)便于- # MaaS 侧链路追踪。通过包装 invoke / stream 出口,复用原 custom_headers- # 合并链路(_build_request_headers),非 MaaS 端点零开销透传。- # 每次 invoke / stream 调用(含重试触发的重新调用)都会生成独立 span_id。_orig_invoke = OpenAIModelClient.invoke_orig_stream = OpenAIModelClient.stream@@ -516,9 +569,25 @@ def apply_openai_sse_invoke_patch() -> None:OpenAIModelClient.invoke = _invoke_with_maas_spanOpenAIModelClient.stream = _stream_with_maas_span- OpenAIModelClient._sse_invoke_patch_applied = True # pylint: disable=protected-access+ OpenAIModelClient._maas_span_id_patch_applied = True # pylint: disable=protected-access+ _MAAS_SPAN_ID_PATCH_APPLIED = True+ logger.info("[llm_sse_patch] OpenAIModelClient 华为 MaaS x-span-id 注入补丁已应用")+++def apply_openai_sse_invoke_patch() -> None:+ """聚合入口:一次性应用全部 4 个补丁(保留以兼容既有调用方)。++ ⚠️ 服务启动路径**不要**直接调用本函数:它会把「仅对 SSE-only 网关有意义」的+ :func:`apply_openai_response_assembly_patch` 一并打开。启动时应分别调用+ :func:`apply_openai_auth_header_patch` / :func:`apply_glm_tool_xml_sanitize_patch`+ / :func:`apply_huawei_maas_span_id_patch`(无条件),再按渠道门控决定是否调用+ :func:`apply_openai_response_assembly_patch`。++ 幂等:4 个子补丁各自幂等,重复调用只生效一次。+ """+ global _PATCH_APPLIED+ apply_openai_auth_header_patch()+ apply_glm_tool_xml_sanitize_patch()+ apply_huawei_maas_span_id_patch()+ apply_openai_response_assembly_patch()_PATCH_APPLIED = True- logger.info(- "[llm_sse_patch] OpenAIModelClient SSE 兼容 + GLM XML 清洗 + Authorization 保留"- " + 华为 MaaS x-span-id 注入补丁已应用"- )diff --git a/jiuwenswarm/server/app_agentserver.py b/jiuwenswarm/server/app_agentserver.pyindex 4ac700f951..354bf969f4 100644--- a/jiuwenswarm/server/app_agentserver.py+++ b/jiuwenswarm/server/app_agentserver.py@@ -143,34 +143,57 @@ from jiuwenswarm.agents.harness.common.tools.bash_tool_safety import (install_shell_tool_safety_hooks()-# 兼容 SSE-only 网关:让非流式 invoke()(subagent / 心跳等)能解析 text/event-stream 响应-# 仅当 channels.xiaoyi.mode == xiaoyi_claw 时才打补丁(该网关以 SSE-only 方式返回非流式响应)。-from jiuwenswarm.llm_sse_patch import apply_openai_sse_invoke_patch+# LLM 客户端补丁分两类:+# 1) 与渠道无关:GLM XML 标签清洗、tip Authorization 保留(Huawei MaaS Basic)、+# 华为 MaaS x-span-id 注入——OfficeClaw + Huawei MaaS 生产链路硬依赖,无条件应用;+# 2) 仅对 SSE-only 网关有意义:非流式 invoke()(subagent / 心跳等)把+# text/event-stream 文本组装成 ChatCompletion——按渠道门控,见下方函数。+from jiuwenswarm.llm_sse_patch import (+ apply_glm_tool_xml_sanitize_patch,+ apply_huawei_maas_span_id_patch,+ apply_openai_auth_header_patch,+ apply_openai_response_assembly_patch,+)++apply_openai_auth_header_patch()+apply_glm_tool_xml_sanitize_patch()+apply_huawei_maas_span_id_patch()def _should_apply_sse_invoke_patch() -> bool:- """检测 channels.xiaoyi.mode 是否为 xiaoyi_claw。"""+ """检测是否存在 ``mode == "xiaoyi_claw"`` 的小艺渠道(决定是否启用 SSE 响应组装补丁)。++ ``mode`` 的规范位置是 ``channels.xiaoyi.apps[].mode``:Web UI 保存小艺渠道配置时+ 只保留 ``{"apps", "send_file_allowed"}``,顶层平铺键会被清理,因此这里优先遍历+ ``apps``;同时兼容旧的顶层平铺格式 ``channels.xiaoyi.mode``。+ """try:from jiuwenswarm.common.config import get_config- mode = (- get_config()- .get("channels", {})- .get("xiaoyi", {})- .get("mode")- )+ xiaoyi = (get_config().get("channels", {}) or {}).get("xiaoyi", {}) or {}except Exception as exc: # noqa: BLE001 - 启动早期读配置失败时保守兜底logger.warning(- "[app_agentserver] 读取 channels.xiaoyi.mode 失败,默认应用 SSE 兼容补丁: %s",+ "[app_agentserver] 读取 channels.xiaoyi 配置失败,默认应用 SSE 兼容补丁: %s",exc,)return True- return str(mode or "").strip() == "xiaoyi_claw"+ modes: list[str] = []+ apps = xiaoyi.get("apps")+ if isinstance(apps, list):+ for app in apps:+ if isinstance(app, dict) and app.get("mode") is not None:+ modes.append(str(app.get("mode")).strip())+ # 兼容旧平铺格式(channels.xiaoyi.mode)+ legacy_mode = xiaoyi.get("mode")+ if legacy_mode is not None:+ modes.append(str(legacy_mode).strip())++ return "xiaoyi_claw" in modesif _should_apply_sse_invoke_patch():- apply_openai_sse_invoke_patch()+ apply_openai_response_assembly_patch()# [PERF 实验] 企业版 + symphony 关闭时短路 evolution rail 轨迹 drainfrom jiuwenswarm.perf.evolution_rail_short_circuit import (diff --git a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.pyindex 3aa1a8d571..e1b5124025 100644--- a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py+++ b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py@@ -895,10 +895,7 @@ async def _wait_for_cron_team_round_events(continueif not isinstance(event, dict):continue- evt_type = str(event.get("event_type") or "").strip()yield event- if evt_type == "team.error":- breakapply_cron_team_round_event(round_state, event)if cron_team_round_should_end(round_state):if _cron_solo_harness_end_pending(round_state):@@ -1044,7 +1041,13 @@ _TEAM_BUILDING_EVENT_TYPES = frozenset({def _broadcast_event(channel_id: str | None, session_id: str, event: dict[str, Any]) -> None:- """Broadcast an event to all request queues waiting on the same session."""+ """Broadcast an event to all request queues waiting on the same session.++ ``team.error`` is remapped to ``chat.error`` here so the frontend receives a+ single unified error event type. This is the **only** write path into the+ request queues (``TeamManager.broadcast_event`` is called nowhere else), so+ consumers never observe ``team.error`` — do not add checks for it downstream.+ """tm = get_team_manager(channel_id)if event and event.get("event_type") == 'team.error':event.update({"event_type": "chat.error"})@@ -2427,7 +2430,7 @@ async def process_team_message_stream(metadata=_metadata,is_complete=False,)- if event.get("event_type") in {"team.completed", "team.error"}:+ if event.get("event_type") == "team.completed":breakfinally:team_manager.remove_waiter(session_id, rid)@@ -2496,8 +2499,6 @@ async def process_team_message_stream(metadata=_metadata,is_complete=False,)- if isinstance(event, dict) and event.get("event_type") == "team.error":- breakexcept asyncio.TimeoutError:if not team_manager.has_stream_task(session_id):break@@ -2526,9 +2527,6 @@ async def process_team_message_stream(payload=event,is_complete=False,)- if isinstance(event, dict):- if event.get("event_type") == "team.error":- breakif drained:logger.info("[TeamHelpers] drained remaining events after has_stream_task loop: "diff --git a/tests/unit_tests/test_llm_sse_patch_granularity.py b/tests/unit_tests/test_llm_sse_patch_granularity.pynew file mode 100644index 0000000000..aa053a111a--- /dev/null+++ b/tests/unit_tests/test_llm_sse_patch_granularity.py@@ -0,0 +1,169 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""LLM 客户端补丁粒度拆分与渠道门控的回归测试。++背景(code review P0 / P1):++* P0 —— ``apply_openai_sse_invoke_patch`` 原先把 4 个互相独立的补丁捆绑成一个整体,+ 并被 ``channels.xiaoyi.mode == "xiaoyi_claw"`` 整体门控。OfficeClaw + Huawei MaaS+ 生产链路只依赖其中与渠道无关的 3 个(GLM XML 清洗 / Authorization 保留 /+ MaaS x-span-id 注入),门控为 False 时 Authorization 补丁随之失效,网关报+ APIG.0303。本文件第一条用例即为该回归的防护点。+* P1 —— 门控读取的是会被 Web UI 保存流程清理掉的顶层 ``channels.xiaoyi.mode``,+ 而 ``mode`` 的规范位置是 ``channels.xiaoyi.apps[].mode``。+"""++from __future__ import annotations++from typing import Any++import pytest++import jiuwenswarm.llm_sse_patch as patch_mod+from jiuwenswarm.server import app_agentserver++from openjiuwen.core.foundation.llm import headers_helper+from openjiuwen.core.foundation.llm.model_clients import openai_model_client as oai_mod++_MODULE_PATCH_FLAGS = (+ "_PATCH_APPLIED",+ "_AUTH_HEADER_PATCH_APPLIED",+ "_RESPONSE_ASSEMBLY_PATCH_APPLIED",+ "_GLM_XML_SANITIZE_PATCH_APPLIED",+ "_MAAS_SPAN_ID_PATCH_APPLIED",+)++_CLIENT_PATCH_FLAGS = (+ "_response_assembly_patch_applied",+ "_glm_xml_sanitize_patch_applied",+ "_maas_span_id_patch_applied",+ "_auth_default_headers_patch_applied",+)+++def fresh_patch_state(monkeypatch: pytest.MonkeyPatch) -> None:+ """清空所有补丁幂等标志,模拟「服务启动早期尚未打补丁」的进程状态。"""+ for name in _MODULE_PATCH_FLAGS:+ monkeypatch.setattr(patch_mod, name, False, raising=False)+ for name in _CLIENT_PATCH_FLAGS:+ monkeypatch.setattr(oai_mod.OpenAIModelClient, name, False, raising=False)+ monkeypatch.setattr(headers_helper, "_auth_header_patch_applied", False, raising=False)+++# ── P0:补丁粒度与幂等 ────────────────────────────────────────────────+++def test_channel_independent_patches_apply_without_sse_assembly(+ fresh_patch_state: None,+) -> None:+ """P0 回归:即使不启用 SSE 响应组装补丁,其余 3 个补丁仍必须全部生效。++ 这正是 OfficeClaw 部署下的场景——配置中没有 xiaoyi_claw 渠道,+ 但 Authorization 保留 / GLM 清洗 / MaaS x-span-id 一个都不能少。+ """+ patch_mod.apply_openai_auth_header_patch()+ patch_mod.apply_glm_tool_xml_sanitize_patch()+ patch_mod.apply_huawei_maas_span_id_patch()++ # ③ Authorization 保留必须生效+ assert headers_helper._auth_header_patch_applied is True # pylint: disable=protected-access+ headers = headers_helper.build_base_headers(+ custom_headers={"Authorization": "Basic dGVzdA=="}+ )+ assert headers.get("Authorization") == "Basic dGVzdA=="++ # ② GLM XML 清洗 与 ④ MaaS x-span-id 注入必须生效+ assert oai_mod.OpenAIModelClient._glm_xml_sanitize_patch_applied is True # pylint: disable=protected-access+ assert oai_mod.OpenAIModelClient._maas_span_id_patch_applied is True # pylint: disable=protected-access++ # ① SSE 响应组装补丁必须保持未启用(它才需要按渠道门控)+ assert (+ getattr(oai_mod.OpenAIModelClient, "_response_assembly_patch_applied", False) is False+ )+ assert patch_mod._RESPONSE_ASSEMBLY_PATCH_APPLIED is False # pylint: disable=protected-access+++def test_granular_patches_are_individually_idempotent(fresh_patch_state: None) -> None:+ """P0 回归:每个补丁拥有独立幂等标志,重复调用不得二次包装。"""+ patch_mod.apply_openai_auth_header_patch()+ patch_mod.apply_glm_tool_xml_sanitize_patch()+ wrapped_stream_chunk = oai_mod.OpenAIModelClient._parse_stream_chunk # pylint: disable=protected-access+ patch_mod.apply_glm_tool_xml_sanitize_patch()+ assert oai_mod.OpenAIModelClient._parse_stream_chunk is wrapped_stream_chunk # pylint: disable=protected-access++ patch_mod.apply_huawei_maas_span_id_patch()+ wrapped_invoke = oai_mod.OpenAIModelClient.invoke+ patch_mod.apply_huawei_maas_span_id_patch()+ assert oai_mod.OpenAIModelClient.invoke is wrapped_invoke++ patch_mod.apply_openai_response_assembly_patch()+ wrapped_parse_response = oai_mod.OpenAIModelClient._parse_response # pylint: disable=protected-access+ patch_mod.apply_openai_response_assembly_patch()+ assert oai_mod.OpenAIModelClient._parse_response is wrapped_parse_response # pylint: disable=protected-access+++def test_aggregate_entry_still_applies_all_patches(fresh_patch_state: None) -> None:+ """兼容入口 ``apply_openai_sse_invoke_patch`` 仍应一次性应用全部 4 个补丁。"""+ patch_mod.apply_openai_sse_invoke_patch()++ assert headers_helper._auth_header_patch_applied is True # pylint: disable=protected-access+ assert oai_mod.OpenAIModelClient._glm_xml_sanitize_patch_applied is True # pylint: disable=protected-access+ assert oai_mod.OpenAIModelClient._maas_span_id_patch_applied is True # pylint: disable=protected-access+ assert oai_mod.OpenAIModelClient._response_assembly_patch_applied is True # pylint: disable=protected-access+++# ── P1:渠道门控读取路径 ──────────────────────────────────────────────+++def _stub_config(monkeypatch: pytest.MonkeyPatch, config: dict[str, Any]) -> None:+ monkeypatch.setattr("jiuwenswarm.common.config.get_config", lambda: config)+++def test_gate_matches_mode_inside_xiaoyi_apps(monkeypatch: pytest.MonkeyPatch) -> None:+ """规范路径 ``channels.xiaoyi.apps[].mode`` 必须能命中 xiaoyi_claw。"""+ _stub_config(+ monkeypatch,+ {+ "channels": {+ "xiaoyi": {+ "apps": [{"mode": "chat"}, {"mode": "xiaoyi_claw"}],+ "send_file_allowed": True,+ }+ }+ },+ )+ assert app_agentserver._should_apply_sse_invoke_patch() is True # pylint: disable=protected-access+++def test_gate_returns_false_for_officeclaw_only_deployment(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """OfficeClaw 部署(无 xiaoyi_claw)下门控应为 False,且不影响其他补丁。"""+ _stub_config(+ monkeypatch,+ {+ "channels": {+ "officeclaw": {"send_file_allowed": True},+ "xiaoyi": {"apps": [{"mode": "chat"}], "send_file_allowed": True},+ }+ },+ )+ assert app_agentserver._should_apply_sse_invoke_patch() is False # pylint: disable=protected-access+++def test_gate_supports_legacy_flat_mode(monkeypatch: pytest.MonkeyPatch) -> None:+ """旧平铺格式 ``channels.xiaoyi.mode`` 仍应被兼容。"""+ _stub_config(monkeypatch, {"channels": {"xiaoyi": {"mode": "xiaoyi_claw"}}})+ assert app_agentserver._should_apply_sse_invoke_patch() is True # pylint: disable=protected-access+++def test_gate_defaults_to_true_when_config_unavailable(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """启动早期读配置失败时保守兜底为 True(保持原有行为)。"""++ def _raise() -> dict[str, Any]:+ raise RuntimeError("config not ready")++ monkeypatch.setattr("jiuwenswarm.common.config.get_config", _raise)+ assert app_agentserver._should_apply_sse_invoke_patch() is True # pylint: disable=protected-access