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: 增加请求头的日志埋点接口
openJiuwen-bot2a8e403174d5
diff --git a/jiuwenswarm/extensions/hook_event.py b/jiuwenswarm/extensions/hook_event.pyindex 02004e8f1a..d5bb3c2cf0 100644--- a/jiuwenswarm/extensions/hook_event.py+++ b/jiuwenswarm/extensions/hook_event.py@@ -29,6 +29,7 @@ class AgentServerHookEvents(HookEventBase):MEMORY_BEFORE_CHAT = HookEventBase.get_event("memory_before_chat")MEMORY_AFTER_CHAT = HookEventBase.get_event("memory_after_chat")BEFORE_SYSTEM_PROMPT_BUILD = HookEventBase.get_event("before_system_prompt_build")+ BEFORE_MODEL_HTTP = HookEventBase.get_event("before_model_http")IMAGE_ARTIFACT_POST_PROCESS = HookEventBase.get_event("image_artifact_post_process")ARTIFACT_POST_PROCESS = HookEventBase.get_event("artifact_post_process")AGENT_RELOAD_CONFIG = HookEventBase.get_event("agent_reload_config")diff --git a/jiuwenswarm/extensions/hooks_context.py b/jiuwenswarm/extensions/hooks_context.pyindex 6158921557..72a06f78ad 100644--- a/jiuwenswarm/extensions/hooks_context.py+++ b/jiuwenswarm/extensions/hooks_context.py@@ -70,6 +70,34 @@ class SystemPromptHookContext:return asdict(self)+@dataclass+class ModelHttpHookContext:+ """模型 HTTP 出口埋点(``before_model_http``)的扩展回调上下文。++ 在模型客户端 ``invoke`` / ``stream`` / ``generate_image`` 组装完请求、真正+ 发出 HTTP 之前触发;工具循环、重试、换模型都经过该出口。扩展往 ``headers``+ / ``extra_body`` 两个口袋写值,宿主在trigger 返回后按保留键白名单合并进本次请求:++ - ``headers`` 并进 ``custom_headers``(``Authorization``、``x-span-id``+ 扩展写了也丢弃);+ - ``extra_body`` 并进请求正文扩展字段(``thinking``、+ ``enable_thinking``、``reasoning_effort`` 扩展写了也丢弃);+ - 未写的口袋保持原样。++ ``api_base`` / ``model_name`` 只读,供扩展自行判断要不要填。+ """++ api_base: str = ""+ model_name: str = ""+ # 扩展可写:并进本次请求 custom_headers+ headers: dict[str, str] = field(default_factory=dict)+ # 扩展可写:并进请求正文 extra_body+ extra_body: dict[str, Any] = field(default_factory=dict)++ def to_dict(self) -> dict[str, Any]:+ return asdict(self)++@dataclassclass ImageArtifactHookContext:"""图像产物落盘后的扩展回调上下文(兼容旧版扩展)。diff --git a/jiuwenswarm/llm_sse_patch.py b/jiuwenswarm/llm_sse_patch.pyindex 7589ee662d..fee9f2fa22 100644--- a/jiuwenswarm/llm_sse_patch.py+++ b/jiuwenswarm/llm_sse_patch.py@@ -19,6 +19,12 @@4. 华为 MaaS x-span-id 注入:调用华为云 ModelArts MaaS 时,在 HTTP 请求头注入``x-span-id``(uuid4 hex),便于 MaaS 侧做链路追踪与本地日志对齐。仅当``api_base`` 识别为 MaaS 端点时触发,非 MaaS 调用零开销透传。++5. before_model_http 扩展埋点:模型 HTTP 出口的公共事件点。按清单包装各模型+ 客户端的 ``invoke`` / ``stream`` / ``generate_image``,在真正发出 HTTP 之前+ 触发 ``agent_server:before_model_http``,扩展往 context 的 ``headers`` /+ ``extra_body`` 口袋写值,核心在 trigger返回后按保留键白名单合并进本次请求。+ 无人登记或扩展框架未初始化时零副作用,请求与现状完全一致。"""from __future__ import annotations@@ -101,8 +107,46 @@ _AUTH_HEADER_PATCH_APPLIED = False_RESPONSE_ASSEMBLY_PATCH_APPLIED = False_GLM_XML_SANITIZE_PATCH_APPLIED = False_MAAS_SPAN_ID_PATCH_APPLIED = False+_MODEL_HTTP_HOOK_PATCH_APPLIED = False_HUAWEI_MAAS_PLACEHOLDER_API_KEY = "huawei-maas-session"+# before_model_http 埋点:扩展口袋的保留键,防止扩展弄坏鉴权与 thinking。+# 请求头按大小写不敏感匹配(HTTP header 名本身大小写不敏感)。+_RESERVED_HOOK_HEADERS = frozenset({"authorization", "x-span-id"})+_RESERVED_HOOK_EXTRA_BODY_KEYS = frozenset(+ {"thinking", "enable_thinking", "reasoning_effort"}+)++# before_model_http 出口包装清单:方法集合按各客户端实际支持的 custom_headers+# 通道确定(方法内 pop custom_headers 并经 merge_request_headers 合并进+# extra_headers)。Anthropic / OpenAIAccount 的 generate_image 等多媒体出口+# 直接抛 NotImplementedError、无 HTTP 出口,不包;OpenAIAccount 为独立实现+# 但 invoke/stream 通道完整,已列入。+# 无法通过追加清单覆盖的客户端(2026-10 逐文件核实):SiliconFlow /+# IntelliRouter / AscendAffinity / InferenceAffinity 的出口方法不支持+# custom_headers 通道(口袋合并后进不了请求头);DashScope 重写的+# generate_image 走自有 Wanx HTTP、DeepSeek 的 generate_image/speech/video+# 均为 pass 桩——需上游先支持通道后才可追加。子类重写的同名方法会遮蔽父类+# 包装,要覆盖需将子类追加进本清单(包装器只包类自身定义的方法,继承方法+# 由父类包装覆盖,不会双包)。+_MODEL_HTTP_HOOK_CLIENT_SPECS: tuple = (+ (+ "openjiuwen.core.foundation.llm.model_clients."+ "openai_model_client.OpenAIModelClient",+ ("invoke", "stream", "generate_image"),+ ),+ (+ "openjiuwen.core.foundation.llm.model_clients."+ "anthropic_model_client.AnthropicModelClient",+ ("invoke", "stream"),+ ),+ (+ "openjiuwen.core.foundation.llm.model_clients."+ "openai_account_model_client.OpenAIAccountModelClient",+ ("invoke", "stream"),+ ),+)+def _extract_authorization_header(headers: dict[str, Any] | None,@@ -607,6 +651,212 @@ def apply_huawei_maas_span_id_patch() -> None:logger.info("[llm_sse_patch] OpenAIModelClient 华为 MaaS x-span-id 注入补丁已应用")+def _merge_model_http_hook_ctx(ctx: Any, kwargs: dict) -> None:+ """把扩展写入的 ``headers`` / ``extra_body`` 口袋合并进本次调用 kwargs。++ - ``headers`` 逐键 setdefault 进 ``kwargs["custom_headers"]``(调用方显式+ 传入的值优先),经 ``_build_request_headers`` 进入最终请求头;+ - ``extra_body`` 逐键 setdefault 进 ``kwargs["extra_body"]``,经+ ``_build_request_params`` 进入 ``params["extra_body"]``,最终由 SDK+ 摊开进请求 JSON 正文;+ - 保留键(``Authorization`` / ``x-span-id`` / thinking 族)扩展写了也丢弃;+ - 含 CR/LF 的头值、非 latin-1 头值(httpx 发送时仅接受 latin-1,中文等+ 需扩展侧先行 URL 编码)、无法 JSON 序列化的正文字段一律跳过,防扩展+ 写出非法值弄坏本次请求;+ - 未写的口袋保持原样;``extra_body`` 为空则正文零变化。+ """+ headers = getattr(ctx, "headers", None)+ if headers:+ merged = dict(kwargs.get("custom_headers") or {})+ for key, value in headers.items():+ name = str(key or "").strip()+ if not name or name.lower() in _RESERVED_HOOK_HEADERS:+ continue+ if value is None:+ continue+ text = str(value)+ if "\r" in text or "\n" in text:+ continue+ try:+ # httpx 头值仅接受 latin-1 可编码字符;中文等需扩展侧先编码+ text.encode("latin-1")+ except UnicodeEncodeError:+ continue+ merged.setdefault(name, text)+ kwargs["custom_headers"] = merged+ extra_body = getattr(ctx, "extra_body", None)+ if extra_body:+ merged_body = dict(kwargs.get("extra_body") or {})+ for key, value in extra_body.items():+ name = str(key or "")+ if not name or name in _RESERVED_HOOK_EXTRA_BODY_KEYS:+ continue+ if value is None:+ continue+ try:+ json.dumps(value)+ except (TypeError, ValueError):+ continue+ merged_body.setdefault(name, value)+ kwargs["extra_body"] = merged_body+++async def _trigger_before_model_http(client: Any, kwargs: dict) -> None:+ """触发 ``before_model_http`` 埋点并把扩展口袋合并进本次调用。++ - 扩展框架不可导入或 registry 未初始化(``trigger_if_initialized``+ 返回 False):零副作用跳过;+ - handler 异常只记日志,本次请求不带扩展字段照常发出——积分参数失败+ 不能变成用户可见的对话失败;+ - 无人登记该事件时 callback 框架空转,请求与现状完全一致。+ """+ # 惰性导入:llm_sse_patch 在进程启动极早期被加载,此时扩展框架尚未+ # 初始化;且 extensions.registry 会拉起 gateway 一大片依赖,避免循环导入。+ try:+ from jiuwenswarm.extensions.hook_event import AgentServerHookEvents+ from jiuwenswarm.extensions.hooks_context import ModelHttpHookContext+ from jiuwenswarm.extensions.registry import ExtensionRegistry+ except Exception: # pragma: no cover - jiuwenswarm 扩展框架不可用+ logger.debug("[before_model_http] extension framework unavailable, skip")+ return++ mcc = getattr(client, "model_client_config", None)+ mc = getattr(client, "model_config", None)+ ctx = ModelHttpHookContext(+ # api_base 来自 ModelClientConfig(与 x-span-id 补丁同源);+ # model_name 来自 ModelRequestConfig(base 客户端组参同源)+ api_base=str(getattr(mcc, "api_base", "") or ""),+ model_name=str(getattr(mc, "model_name", "") or ""),+ )+ try:+ triggered = await ExtensionRegistry.trigger_if_initialized(+ AgentServerHookEvents.BEFORE_MODEL_HTTP, ctx+ )+ except Exception:+ logger.warning(+ "[before_model_http] handler failed; send request without hook attrs",+ exc_info=True,+ )+ return+ if not triggered:+ return+ try:+ _merge_model_http_hook_ctx(ctx, kwargs)+ except Exception:+ logger.warning(+ "[before_model_http] merge hook attrs failed; send without them",+ exc_info=True,+ )+++def _import_model_client_class(dotted: str) -> Any:+ """按 ``module.Class`` 点名导入模型客户端类;失败返回 None。"""+ module_name, _, class_name = dotted.rpartition(".")+ try:+ module = importlib.import_module(module_name)+ return getattr(module, class_name, None)+ except Exception:+ return None+++def _wrap_model_http_hook_on_class(+ client_cls: Any, method_names: tuple+) -> list:+ """对单个模型客户端类安装 before_model_http 出口包装(幂等)。++ 返回实际包装的方法名列表。只包装类自身定义的方法(``vars`` 直查):+ 从父类继承的方法已由父类上的包装覆盖,再包一层会导致每次调用双触发+ 埋点。注意继承遮蔽:子类若重写了清单中的同名方法(如 DashScope 重写+ generate_image),父类上的包装对子类实例无效,需把子类追加进+ ``_MODEL_HTTP_HOOK_CLIENT_SPECS`` 才能覆盖。+ """+ if getattr(client_cls, "_model_http_hook_patch_applied", False):+ return []++ wrapped: list = []+ for name in method_names:+ if name not in vars(client_cls):+ continue+ orig = getattr(client_cls, name, None)+ if orig is None:+ continue+ if name == "stream":++ async def _stream_with_model_http_hook(+ self: Any, *args, _orig=orig, **kwargs+ ):+ # 与 invoke 同口:先触发埋点(原地改 kwargs),再转发原生成器。+ await _trigger_before_model_http(self, kwargs)+ async for chunk in _orig(self, *args, **kwargs):+ yield chunk++ setattr(client_cls, name, _stream_with_model_http_hook)+ else:++ async def _call_with_model_http_hook(+ self: Any, *args, _orig=orig, **kwargs+ ):+ await _trigger_before_model_http(self, kwargs)+ return await _orig(self, *args, **kwargs)++ setattr(client_cls, name, _call_with_model_http_hook)+ wrapped.append(name)++ if wrapped:+ setattr(client_cls, "_model_http_hook_patch_applied", True)+ return wrapped+++def apply_before_model_http_hook_patch() -> None:+ """Patch 5: ``before_model_http`` 扩展埋点 —— 模型 HTTP 出口的公共事件点。++ 按 ``_MODEL_HTTP_HOOK_CLIENT_SPECS`` 包装各模型客户端的 ``invoke`` /+ ``stream`` / ``generate_image``,在真正发出 HTTP 之前触发+ ``agent_server:before_model_http``:扩展往 context 的 ``headers`` /+ ``extra_body`` 口袋写值,核心在 trigger+ 返回后按保留键白名单合并进本次请求。工具循环、重试、换模型、图像生成都经过该出口。++ 客户端覆盖范围(见清单):OpenAI 兼容族(未重写出口方法的子类含+ HuaweiMaas / OpenRouter 经继承自动覆盖)、Anthropic 与 OpenAIAccount。+ SiliconFlow / IntelliRouter / Ascend & InferenceAffinity 及 DashScope /+ DeepSeek 重写的多媒体出口因上游不支持 custom_headers 通道而无法经本+ 清单覆盖(包装了口袋也进不了请求头);generate_speech / generate_video+ 出口 openjiuwen 尚不支持 custom_headers 通道,均不在本埋点覆盖内。++ 与渠道无关,无条件应用;扩展框架未初始化或无人登记时零副作用,请求与+ 现状完全一致。幂等:使用独立的 ``_MODEL_HTTP_HOOK_PATCH_APPLIED`` 标志,+ 不受其他补丁影响;仅当至少包装了一个客户端时才置位——全部客户端导入+ 失败时保持未应用,下次调用可重试(与 Patch 1/2 的可重试语义一致)。+ """+ global _MODEL_HTTP_HOOK_PATCH_APPLIED+ if _MODEL_HTTP_HOOK_PATCH_APPLIED:+ return++ wrapped_classes: list = []+ for dotted, method_names in _MODEL_HTTP_HOOK_CLIENT_SPECS:+ client_cls = _import_model_client_class(dotted)+ if client_cls is None:+ logger.warning(+ "[llm_sse_patch] before_model_http: 客户端 %s 不可用,跳过", dotted+ )+ continue+ methods = _wrap_model_http_hook_on_class(client_cls, method_names)+ if methods:+ wrapped_classes.append(f"{client_cls.__name__}({','.join(methods)})")++ if wrapped_classes:+ _MODEL_HTTP_HOOK_PATCH_APPLIED = True+ logger.info(+ "[llm_sse_patch] before_model_http 扩展埋点补丁已应用: %s",+ ", ".join(wrapped_classes),+ )+ else:+ logger.warning(+ "[llm_sse_patch] before_model_http 扩展埋点补丁未包装任何客户端,"+ "保持未应用状态以便后续重试"+ )++def apply_openai_sse_invoke_patch() -> None:"""聚合入口:一次性应用全部 4 个补丁(保留以兼容既有调用方)。diff --git a/jiuwenswarm/server/app_agentserver.py b/jiuwenswarm/server/app_agentserver.pyindex 74a1cd3262..b8a8c8cf75 100644--- a/jiuwenswarm/server/app_agentserver.py+++ b/jiuwenswarm/server/app_agentserver.py@@ -145,10 +145,12 @@ install_shell_tool_safety_hooks()# LLM 客户端补丁分两类:# 1) 与渠道无关:GLM XML 标签清洗、tip Authorization 保留(Huawei MaaS Basic)、-# 华为 MaaS x-span-id 注入——OfficeClaw + Huawei MaaS 生产链路硬依赖,无条件应用;+# 华为 MaaS x-span-id 注入、before_model_http 扩展埋点(模型 HTTP 出口的+# 公共事件点,积分对账头等扩展字段经此注入)生产链路硬依赖,无条件应用;# 2) 仅对 SSE-only 网关有意义:非流式 invoke()(subagent / 心跳等)把# text/event-stream 文本组装成 ChatCompletion——按渠道门控,见下方函数。from jiuwenswarm.llm_sse_patch import (+ apply_before_model_http_hook_patch,apply_glm_tool_xml_sanitize_patch,apply_huawei_maas_span_id_patch,apply_openai_auth_header_patch,@@ -159,6 +161,7 @@ from jiuwenswarm.llm_sse_patch import (apply_openai_auth_header_patch()apply_glm_tool_xml_sanitize_patch()apply_huawei_maas_span_id_patch()+apply_before_model_http_hook_patch()def _should_apply_sse_invoke_patch() -> bool:diff --git a/tests/unit_tests/test_llm_model_http_hook_patch.py b/tests/unit_tests/test_llm_model_http_hook_patch.pynew file mode 100644index 0000000000..6330b5e87e--- /dev/null+++ b/tests/unit_tests/test_llm_model_http_hook_patch.py@@ -0,0 +1,464 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""before_model_http 扩展埋点(llm_sse_patch Patch 5)的单元测试。++覆盖核心埋点的验收要点(F153):++* 合并规则:保留键丢弃(Authorization / x-span-id / thinking 族)、非法值+ (含 CR/LF 的头、不可序列化的正文字段)跳过、调用方显式值优先、未写的+ 口袋保持原样;+* 触发链路:invoke / stream 出口触发事件并合并口袋;+* 失败语义:handler 抛错、registry 未初始化时请求照常发出(零新增字段);+* 幂等:独立标志,重复安装不二次包装。+"""++from __future__ import annotations++import asyncio+import importlib+from types import SimpleNamespace+from typing import Any++import pytest++import jiuwenswarm.llm_sse_patch as patch_mod++from openjiuwen.core.foundation.llm.model_clients import openai_model_client as oai_mod++_MODULE_FLAG = "_MODEL_HTTP_HOOK_PATCH_APPLIED"+_CLIENT_FLAG = "_model_http_hook_patch_applied"+++def fresh_patch_state(monkeypatch: pytest.MonkeyPatch) -> None:+ """清空埋点补丁幂等标志,模拟「服务启动早期尚未打补丁」的进程状态。++ 清单内各客户端(OpenAI / Anthropic / OpenAIAccount,后两者若可用)一并+ 复位类级标志(app_agentserver 导入即打过补丁),并把出口方法换成 no-op+ 假方法,避免每个用例的 apply() 在真实包装上叠层。+ """+ monkeypatch.setattr(patch_mod, _MODULE_FLAG, False, raising=False)++ async def _noop_invoke(self: Any, *args: Any, **kwargs: Any):+ return "ok"++ async def _noop_stream(self: Any, *args: Any, **kwargs: Any):+ yield 1++ async def _noop_generate_image(self: Any, *args: Any, **kwargs: Any):+ return "image-ok"++ monkeypatch.setattr(oai_mod.OpenAIModelClient, _CLIENT_FLAG, False, raising=False)+ monkeypatch.setattr(oai_mod.OpenAIModelClient, "invoke", _noop_invoke)+ monkeypatch.setattr(oai_mod.OpenAIModelClient, "stream", _noop_stream)+ monkeypatch.setattr(+ oai_mod.OpenAIModelClient, "generate_image", _noop_generate_image+ )++ for _mod_name, _class_name in (+ ("anthropic_model_client", "AnthropicModelClient"),+ ("openai_account_model_client", "OpenAIAccountModelClient"),+ ):+ try:+ _mod = importlib.import_module(+ f"openjiuwen.core.foundation.llm.model_clients.{_mod_name}"+ )+ except Exception:+ continue+ _cls = getattr(_mod, _class_name)+ monkeypatch.setattr(_cls, _CLIENT_FLAG, False, raising=False)+ monkeypatch.setattr(_cls, "invoke", _noop_invoke)+ monkeypatch.setattr(_cls, "stream", _noop_stream)+++def _fake_client() -> SimpleNamespace:+ return SimpleNamespace(+ model_client_config=SimpleNamespace(api_base="https://modelarts-maas.cn/v1"),+ model_config=SimpleNamespace(model_name="glm-5.2"),+ )+++def _install_fake_trigger(+ monkeypatch: pytest.MonkeyPatch,+ *,+ filler: Any = None,+ error: Exception | None = None,+ initialized: bool = True,+) -> list[dict[str, Any]]:+ """替换 ExtensionRegistry.trigger_if_initialized,记录调用并可控返回。"""+ calls: list[dict[str, Any]] = []++ async def _fake_trigger(event: str, context: Any = None, **kwargs: Any) -> bool:+ calls.append({"event": event, "context": context})+ if error is not None:+ raise error+ if filler is not None:+ filler(context)+ return initialized++ monkeypatch.setattr(+ "jiuwenswarm.extensions.registry.ExtensionRegistry.trigger_if_initialized",+ _fake_trigger,+ )+ return calls+++# ── 事件名与合并规则 ─────────────────────────────────────────────────+++def test_event_name_is_scoped() -> None:+ from jiuwenswarm.extensions.hook_event import AgentServerHookEvents++ assert AgentServerHookEvents.BEFORE_MODEL_HTTP == "agent_server:before_model_http"+++def test_merge_drops_reserved_and_invalid_values() -> None:+ from jiuwenswarm.extensions.hooks_context import ModelHttpHookContext++ kwargs: dict[str, Any] = {}+ ctx = ModelHttpHookContext(+ headers={+ "x-client": "miniprogram|vivo|trial",+ "Authorization": "Basic evil",+ "X-SPAN-ID": "evil", # 保留键按大小写不敏感匹配+ "x-bad": "a\r\nSet-Cookie: pwn",+ "x-cn": "用户中文原话", # 非 latin-1 头值会让 httpx 发送时抛错,必须跳过+ "": "empty-name",+ },+ extra_body={+ "report_id": "r-1",+ "thinking": {"type": "enabled"},+ "enable_thinking": True,+ "reasoning_effort": "high",+ "unserializable": object(),+ },+ )+ patch_mod._merge_model_http_hook_ctx(ctx, kwargs) # pylint: disable=protected-access++ assert kwargs["custom_headers"] == {+ "x-client": "miniprogram|vivo|trial"+ }+ assert kwargs["extra_body"] == {"report_id": "r-1"}+++def test_merge_keeps_caller_values_and_empty_pockets() -> None:+ from jiuwenswarm.extensions.hooks_context import ModelHttpHookContext++ kwargs: dict[str, Any] = {"custom_headers": {"x-client": "caller"}}+ ctx = ModelHttpHookContext(headers={"x-client": "extension"})+ patch_mod._merge_model_http_hook_ctx(ctx, kwargs) # pylint: disable=protected-access++ # 调用方显式传入的值优先,扩展不得覆盖+ assert kwargs["custom_headers"]["x-client"] == "caller"+ # 只写 headers 口包不产生 extra_body:正文零变化+ assert "extra_body" not in kwargs+++# ── 安装幂等 ─────────────────────────────────────────────────────────+++def test_patch_is_idempotent(+ monkeypatch: pytest.MonkeyPatch, fresh_patch_state: None+) -> None:+ async def _fake_orig_invoke(self: Any, *args: Any, **kwargs: Any):+ return "ok"++ async def _fake_orig_stream(self: Any, *args: Any, **kwargs: Any):+ yield 1++ monkeypatch.setattr(oai_mod.OpenAIModelClient, "invoke", _fake_orig_invoke)+ monkeypatch.setattr(oai_mod.OpenAIModelClient, "stream", _fake_orig_stream)++ patch_mod.apply_before_model_http_hook_patch()+ wrapped_invoke = oai_mod.OpenAIModelClient.invoke+ wrapped_stream = oai_mod.OpenAIModelClient.stream++ patch_mod.apply_before_model_http_hook_patch()+ assert oai_mod.OpenAIModelClient.invoke is wrapped_invoke+ assert oai_mod.OpenAIModelClient.stream is wrapped_stream+ assert getattr(patch_mod, _MODULE_FLAG) is True # pylint: disable=protected-access+ assert ( # pylint: disable=protected-access+ getattr(oai_mod.OpenAIModelClient, _CLIENT_FLAG) is True+ )+++# ── invoke / stream 出口触发与合并 ───────────────────────────────────+++def test_invoke_wrapper_triggers_and_merges(+ monkeypatch: pytest.MonkeyPatch, fresh_patch_state: None+) -> None:+ recorded: list[dict[str, Any]] = []++ async def _fake_orig_invoke(self: Any, *args: Any, **kwargs: Any):+ recorded.append(kwargs)+ return "ok"++ monkeypatch.setattr(oai_mod.OpenAIModelClient, "invoke", _fake_orig_invoke)+ patch_mod.apply_before_model_http_hook_patch()++ def _fill(ctx: Any) -> None:+ ctx.headers["x-client"] = "miniprogram|vivo|trial"+ ctx.headers["x-message-meta"] = "scen|sid|inv|msg"+ ctx.extra_body["report_id"] = "r-1"++ calls = _install_fake_trigger(monkeypatch, filler=_fill)++ result = asyncio.run(+ oai_mod.OpenAIModelClient.invoke(_fake_client(), messages="hi")+ )++ assert result == "ok"+ assert calls[0]["event"] == "agent_server:before_model_http"+ assert calls[0]["context"].api_base == "https://modelarts-maas.cn/v1"+ assert calls[0]["context"].model_name == "glm-5.2"+ assert recorded[0]["custom_headers"] == {+ "x-client": "miniprogram|vivo|trial",+ "x-message-meta": "scen|sid|inv|msg",+ }+ assert recorded[0]["extra_body"] == {"report_id": "r-1"}+++def test_stream_wrapper_triggers_and_passes_chunks(+ monkeypatch: pytest.MonkeyPatch, fresh_patch_state: None+) -> None:+ recorded: list[dict[str, Any]] = []++ async def _fake_orig_stream(self: Any, *args: Any, **kwargs: Any):+ recorded.append(kwargs)+ for chunk in (1, 2, 3):+ yield chunk++ monkeypatch.setattr(oai_mod.OpenAIModelClient, "stream", _fake_orig_stream)+ patch_mod.apply_before_model_http_hook_patch()++ _install_fake_trigger(+ monkeypatch,+ filler=lambda ctx: ctx.headers.update({"x-client": "miniprogram"}),+ )++ async def _collect() -> list[int]:+ agen = oai_mod.OpenAIModelClient.stream(_fake_client(), messages="hi")+ return [chunk async for chunk in agen]++ chunks = asyncio.run(_collect())++ assert chunks == [1, 2, 3]+ assert recorded[0]["custom_headers"] == {"x-client": "miniprogram"}+++def test_generate_image_wrapper_triggers_and_merges(+ monkeypatch: pytest.MonkeyPatch, fresh_patch_state: None+) -> None:+ """图像生成出口(images.generate)同样计费,必须经过埋点。"""+ recorded: list[dict[str, Any]] = []++ async def _fake_orig_generate_image(self: Any, *args: Any, **kwargs: Any):+ recorded.append(kwargs)+ return "image-ok"++ monkeypatch.setattr(+ oai_mod.OpenAIModelClient, "generate_image", _fake_orig_generate_image+ )+ patch_mod.apply_before_model_http_hook_patch()++ _install_fake_trigger(+ monkeypatch,+ filler=lambda ctx: ctx.headers.update(+ {"x-client": "miniprogram|vivo|trial"}+ ),+ )++ result = asyncio.run(+ oai_mod.OpenAIModelClient.generate_image(_fake_client(), messages=["hi"])+ )++ assert result == "image-ok"+ assert recorded[0]["custom_headers"] == {"x-client": "miniprogram|vivo|trial"}+++def test_anthropic_client_is_covered(+ monkeypatch: pytest.MonkeyPatch, fresh_patch_state: None+) -> None:+ """AC-7:Anthropic 等异构客户端的 invoke/stream 也在埋点覆盖内。"""+ anthropic_mod = pytest.importorskip(+ "openjiuwen.core.foundation.llm.model_clients.anthropic_model_client"+ )+ recorded: list[dict[str, Any]] = []++ async def _fake_orig_invoke(self: Any, *args: Any, **kwargs: Any):+ recorded.append(kwargs)+ return "ok"++ monkeypatch.setattr(+ anthropic_mod.AnthropicModelClient, "invoke", _fake_orig_invoke+ )+ patch_mod.apply_before_model_http_hook_patch()++ calls = _install_fake_trigger(+ monkeypatch,+ filler=lambda ctx: ctx.headers.update({"x-client": "miniprogram"}),+ )++ result = asyncio.run(+ anthropic_mod.AnthropicModelClient.invoke(_fake_client(), messages="hi")+ )++ assert result == "ok"+ assert calls[0]["event"] == "agent_server:before_model_http"+ assert recorded[0]["custom_headers"] == {"x-client": "miniprogram"}+++def test_openai_account_client_is_covered(+ monkeypatch: pytest.MonkeyPatch, fresh_patch_state: None+) -> None:+ """OpenAIAccount(独立实现,custom_headers 通道完整)也在埋点覆盖内。"""+ account_mod = pytest.importorskip(+ "openjiuwen.core.foundation.llm.model_clients.openai_account_model_client"+ )+ recorded: list[dict[str, Any]] = []++ async def _fake_orig_invoke(self: Any, *args: Any, **kwargs: Any):+ recorded.append(kwargs)+ return "ok"++ monkeypatch.setattr(+ account_mod.OpenAIAccountModelClient, "invoke", _fake_orig_invoke+ )+ patch_mod.apply_before_model_http_hook_patch()++ calls = _install_fake_trigger(+ monkeypatch,+ filler=lambda ctx: ctx.headers.update({"x-client": "miniprogram"}),+ )++ result = asyncio.run(+ account_mod.OpenAIAccountModelClient.invoke(_fake_client(), messages="hi")+ )++ assert result == "ok"+ assert calls[0]["event"] == "agent_server:before_model_http"+ assert recorded[0]["custom_headers"] == {"x-client": "miniprogram"}+++# ── 覆盖面与安装语义 ─────────────────────────────────────────────────+++def test_inherited_methods_are_not_double_wrapped(+ monkeypatch: pytest.MonkeyPatch, fresh_patch_state: None+) -> None:+ """vars 护栏:子类继承的方法不再包装,避免每次调用双触发埋点。"""+ async def _fake_orig_invoke(self: Any, *args: Any, **kwargs: Any):+ return "ok"++ monkeypatch.setattr(oai_mod.OpenAIModelClient, "invoke", _fake_orig_invoke)+ patch_mod.apply_before_model_http_hook_patch()++ class _SubClient(oai_mod.OpenAIModelClient):+ """未重写任何出口方法的子类(HuaweiMaas / OpenRouter 场景)。"""++ class _OverrideClient(oai_mod.OpenAIModelClient):+ """仅重写 generate_image 的子类(DashScope 场景)。"""++ async def generate_image(self, *args: Any, **kwargs: Any):+ return "img"++ for _cls in (_SubClient, _OverrideClient):+ # 复位继承来的类级标志,模拟「该子类尚未打过补丁」+ _cls._model_http_hook_patch_applied = False # pylint: disable=protected-access++ # 未重写方法:零包装,继承方法仍指向父类(已包装)实现+ assert (+ patch_mod._wrap_model_http_hook_on_class( # pylint: disable=protected-access+ _SubClient, ("invoke", "stream", "generate_image")+ )+ == []+ )+ assert _SubClient.invoke is oai_mod.OpenAIModelClient.invoke++ # 重写的方法:只包自己定义的 generate_image,invoke 仍走父类包装+ assert (+ patch_mod._wrap_model_http_hook_on_class( # pylint: disable=protected-access+ _OverrideClient, ("invoke", "stream", "generate_image")+ )+ == ["generate_image"]+ )+ assert _OverrideClient.invoke is oai_mod.OpenAIModelClient.invoke++ # 继承方法只触发一次埋点(若被子类二次包装会触发两次)+ calls = _install_fake_trigger(monkeypatch)+ result = asyncio.run(_SubClient.invoke(_fake_client(), messages="hi"))+ assert result == "ok"+ assert len(calls) == 1+++def test_flag_not_set_when_no_client_wrapped(+ monkeypatch: pytest.MonkeyPatch, fresh_patch_state: None+) -> None:+ """全部客户端不可导入时不置位幂等标志,下次调用可重试(与 P1/P2 一致)。"""+ real_import = patch_mod._import_model_client_class # pylint: disable=protected-access+ monkeypatch.setattr(patch_mod, "_import_model_client_class", lambda dotted: None)++ patch_mod.apply_before_model_http_hook_patch()+ assert getattr(patch_mod, _MODULE_FLAG) is False++ monkeypatch.setattr(patch_mod, "_import_model_client_class", real_import)++ async def _fake_orig_invoke(self: Any, *args: Any, **kwargs: Any):+ return "ok"++ async def _fake_orig_stream(self: Any, *args: Any, **kwargs: Any):+ yield 1++ monkeypatch.setattr(oai_mod.OpenAIModelClient, "invoke", _fake_orig_invoke)+ monkeypatch.setattr(oai_mod.OpenAIModelClient, "stream", _fake_orig_stream)+ patch_mod.apply_before_model_http_hook_patch()+ assert getattr(patch_mod, _MODULE_FLAG) is True+++# ── 失败语义:绝不阻塞模型调用 ───────────────────────────────────────+++def test_handler_failure_does_not_block_invoke(+ monkeypatch: pytest.MonkeyPatch, fresh_patch_state: None+) -> None:+ recorded: list[dict[str, Any]] = []++ async def _fake_orig_invoke(self: Any, *args: Any, **kwargs: Any):+ recorded.append(kwargs)+ return "ok"++ monkeypatch.setattr(oai_mod.OpenAIModelClient, "invoke", _fake_orig_invoke)+ patch_mod.apply_before_model_http_hook_patch()+ _install_fake_trigger(monkeypatch, error=RuntimeError("handler boom"))++ result = asyncio.run(+ oai_mod.OpenAIModelClient.invoke(_fake_client(), messages="hi")+ )++ # handler 抛错:请求照常发出,只是不带扩展字段+ assert result == "ok"+ assert "custom_headers" not in recorded[0]+ assert "extra_body" not in recorded[0]+++def test_registry_not_initialized_is_noop(+ monkeypatch: pytest.MonkeyPatch, fresh_patch_state: None+) -> None:+ recorded: list[dict[str, Any]] = []++ async def _fake_orig_invoke(self: Any, *args: Any, **kwargs: Any):+ recorded.append(kwargs)+ return "ok"++ monkeypatch.setattr(oai_mod.OpenAIModelClient, "invoke", _fake_orig_invoke)+ patch_mod.apply_before_model_http_hook_patch()+ _install_fake_trigger(monkeypatch, initialized=False)++ result = asyncio.run(+ oai_mod.OpenAIModelClient.invoke(_fake_client(), messages="hi")+ )++ # registry 未初始化:零副作用,请求与现状完全一致+ assert result == "ok"+ assert "custom_headers" not in recorded[0]+ assert "extra_body" not in recorded[0]