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(web_search): 搜索引擎web_search及fetch性能优化
d300296968bc9ac33a488
diff --git a/jiuwenswarm/agents/harness/common/tools/harness_named_web_tools.py b/jiuwenswarm/agents/harness/common/tools/harness_named_web_tools.pyindex 6afdb678d2..1d521d868f 100644--- a/jiuwenswarm/agents/harness/common/tools/harness_named_web_tools.py+++ b/jiuwenswarm/agents/harness/common/tools/harness_named_web_tools.py@@ -9,7 +9,7 @@ from openjiuwen.core.common.exception.errors import build_errorfrom openjiuwen.core.foundation.tool.base import Tool, ToolCardfrom openjiuwen.harness.prompts import resolve_language-from jiuwenswarm.agents.harness.common.tools.web_fetch_tools import mcp_fetch_webpage+from jiuwenswarm.agents.harness.common.tools.web_fetch_tools import mcp_fetch_webpage, mcp_fetch_webpage_implfrom jiuwenswarm.agents.harness.common.tools.web_search.harness import JiuwenHarnessWebSearchToolfrom jiuwenswarm.common.utils import logger@@ -29,6 +29,53 @@ def _build_fetch_webpage_tool_card(*, agent_id: Optional[str], language: str) ->)+def _override_fetch_card_url_array(base_card: ToolCard, lang: str) -> ToolCard:+ """Override the harness fetch_webpage card so ``url`` is an array.++ The upstream ``FetchWebpageMetadataProvider`` (openjiuwen package) still+ declares ``url`` as a string. We rebuild the card with an array schema and+ a multi-URL description so the LLM is told to pass several URLs at once.+ """+ ud = {+ "cn": "一个或多个要抓取的网页 URL。",+ "en": "One or more webpage URLs to fetch.",+ }[lang]+ description = {+ "cn": (+ "抓取网页文本,返回列表,每个元素含一个 URL 的状态码、标题和正文。"+ "可一次传入多个 URL 并行抓取。通常配合 web_search 使用:先搜索,"+ "再抓取前几个结果页。可设置 max_chars=0 关闭截断,"+ "也可调大 timeout_seconds 处理慢站点。"+ ),+ "en": (+ "Fetch webpage text and return a list; each item holds status, title and plain "+ "text of one URL. Accepts multiple URLs at once for parallel fetch. "+ "Usually used after web_search. Set max_chars=0 to disable clipping "+ "and use a larger timeout_seconds for slow pages."+ ),+ }[lang]+ input_params = {+ "type": "object",+ "properties": {+ "url": {"type": "array", "items": {"type": "string"}, "description": ud},+ "max_chars": {"type": "integer", "description": "返回内容最大字符数;设置为 0 表示不截断。", "default": 20000},+ "timeout_seconds": {"type": "integer", "description": "请求超时时间(秒);慢站点可适当调大。", "default": 45},+ "use_cache": {+ "type": "boolean",+ "description": "是否优先从内存缓存读取(默认 true)。若需要最新数据,设为 false 从原站重新抓取。",+ "default": True,+ },+ },+ "required": ["url"],+ }+ return ToolCard(+ id=base_card.id,+ name=base_card.name,+ description=description,+ input_params=input_params,+ )++class JiuwenHarnessFetchWebpageTool(Tool):"""Fetch webpage; body from ``mcp_fetch_webpage``."""@@ -37,19 +84,24 @@ class JiuwenHarnessFetchWebpageTool(Tool):language: str = "cn",agent_id: Optional[str] = None,card: Optional[ToolCard] = None,+ cache: Any | None = None,) -> None:lang = resolve_language(language or "cn")- super().__init__(- card- or _build_fetch_webpage_tool_card(agent_id=agent_id, language=lang)- )+ base_card = _build_fetch_webpage_tool_card(agent_id=agent_id, language=lang)+ fetch_card = card or _override_fetch_card_url_array(base_card, lang)+ super().__init__(fetch_card)+ self._cache = cacheasync def invoke(self, inputs: Dict[str, Any], **kwargs) -> Any:logger.info("[JiuwenHarnessWebTools] LLM tool name=fetch_webpage (card_id=%s)",self.card.id,)- return await mcp_fetch_webpage.invoke(inputs, **kwargs)+ if self._cache is not None:+ kwargs["cache"] = self._cache+ return await mcp_fetch_webpage_impl(+ **inputs, **{k: v for k, v in kwargs.items() if k in ("cache",)}+ )async def stream(self, inputs: Dict[str, Any], **kwargs) -> AsyncIterator[Any]:yield "Stream is not supported for this tool."@@ -60,12 +112,13 @@ def build_jiuwen_harness_named_web_tools(*,agent_id: Optional[str],language: str = "cn",+ cache: Any | None = None,) -> List[Tool]:"""Build ``web_search`` + ``fetch_webpage`` for a scoped ``agent_id``."""lang = resolve_language(language or "cn")return [- JiuwenHarnessWebSearchTool(language=lang, agent_id=agent_id),- JiuwenHarnessFetchWebpageTool(language=lang, agent_id=agent_id),+ JiuwenHarnessWebSearchTool(language=lang, agent_id=agent_id, cache=cache),+ JiuwenHarnessFetchWebpageTool(language=lang, agent_id=agent_id, cache=cache),]diff --git a/jiuwenswarm/agents/harness/common/tools/web_fetch_tools.py b/jiuwenswarm/agents/harness/common/tools/web_fetch_tools.pyindex e92fe82137..15e4ca7241 100644--- a/jiuwenswarm/agents/harness/common/tools/web_fetch_tools.py+++ b/jiuwenswarm/agents/harness/common/tools/web_fetch_tools.py@@ -5,8 +5,10 @@from __future__ import annotationsimport asyncio+import loggingimport osimport re+import timefrom html import unescapefrom typing import Anyfrom urllib.parse import parse_qs, unquote, urlparse@@ -18,6 +20,11 @@ from openjiuwen.core.foundation.tool import toolfrom jiuwenswarm.common.http_proxy_config import requests_getfrom jiuwenswarm.common.local_env_config import get_local_config+logger = logging.getLogger(__name__)+# 独立 baseline logger,命名空间挂在 jiuwenswarm 日志树下,避免被日志框架丢弃。+# 日志行以 "BASELINE " 前缀开头,便于 grep 摸底。+baseline = logging.getLogger("jiuwenswarm.agents.harness.common.tools.web_fetch_tools.baseline")+_USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) ""AppleWebKit/537.36 (KHTML, like Gecko) "@@ -227,19 +234,121 @@ def _fetch_webpage_sync(url: str, timeout_seconds: int) -> dict[str, str | int]:}-@tool(- name="mcp_fetch_webpage",- description=(- "抓取网页文本内容,返回状态码、标题和纯文本正文。"- "设置 max_chars=0 可禁用输出截断。"- "慢速网站可增大 timeout_seconds。"- ),-)-async def mcp_fetch_webpage(url: str, max_chars: int = 0, timeout_seconds: int = 30) -> str:- url = _normalize_url(url)+async def _fetch_single_url(+ raw_url: str,+ *,+ max_chars: int,+ timeout_seconds: int,+ use_cache: bool,+ cache: Any | None,+) -> dict[str, Any]:+ """Fetch a single URL and return one result-item dict.++ The returned dict always carries the (normalized) ``url`` key plus either+ success fields (``status_code``/``title``/``content``/``provider``/+ ``from_cache``...) or an ``error`` field when fetching failed.+ """+ url = _normalize_url(raw_url)if not url:- return "[ERROR]: url cannot be empty."+ return {+ "url": str(raw_url or "").strip(),+ "status_code": None,+ "title": "",+ "content": "",+ "provider": "",+ "from_cache": False,+ "error": "url cannot be empty.",+ }++ # 模式 1:查缓存+ if cache is not None and use_cache:+ cached = await cache.get(url)+ if cached is not None:+ now = time.time()+ cache_age_days = round((now - float(cached.cached_at or 0)) / 86400, 1)+ update_time = cached.update_time+ page_update_days = None+ if update_time is not None:+ page_update_days = round((now - float(update_time)) / 86400, 1)+ return {+ "url": cached.url,+ "status_code": 200,+ "title": cached.title or "",+ "content": _clip_text(str(cached.content or ""), max_chars) or "[empty]",+ "provider": f"cache:{cached.source or 'unknown'}",+ "from_cache": True,+ "cache_age_days": cache_age_days,+ "page_update_days": page_update_days,+ }+ elif cache is not None and not use_cache:+ cache.bypassed += 1++ # 模式 2:实时抓取(不回写缓存)+ _fetch_start = time.perf_counter()+ try:+ data = await asyncio.to_thread(_fetch_webpage_sync, url, timeout_seconds)+ except Exception as exc:+ cost_ms = int((time.perf_counter() - _fetch_start) * 1000)+ baseline.info(+ "BASELINE fetch url=%s ok=N cost_ms=%d",+ url,+ cost_ms,+ )+ reason = str(exc).strip() or "unknown error"+ return {+ "url": url,+ "status_code": None,+ "title": "",+ "content": "",+ "provider": "",+ "from_cache": False,+ "error": f"fetch failed ({reason})",+ }++ cost_ms = int((time.perf_counter() - _fetch_start) * 1000)+ content_chars = len(str(data.get("content", "") or ""))+ baseline.info(+ "BASELINE fetch url=%s ok=Y cost_ms=%d chars=%d provider=direct",+ url,+ cost_ms,+ content_chars,+ )+ return {+ "url": data.get("url", url),+ "status_code": data.get("status_code"),+ "title": data.get("title", ""),+ "content": _clip_text(str(data.get("content", "") or ""), max_chars) or "[empty]",+ "provider": "direct",+ "from_cache": False,+ }+++def _coerce_url_list(url: str | list[str]) -> list[str]:+ """Normalize the ``url`` argument into a flat list of URL strings."""+ if url is None:+ return []+ if isinstance(url, str):+ return [url] if url.strip() else []+ if isinstance(url, (list, tuple)):+ return [str(u).strip() for u in url if str(u).strip()]+ return [str(url).strip()] if str(url).strip() else []+++async def mcp_fetch_webpage_impl(+ url: str | list[str],+ max_chars: int = 0,+ timeout_seconds: int = 30,+ use_cache: bool = True,+ cache: Any | None = None,+) -> list[dict[str, Any]]:+ """Fetch one or more webpages.++ ``url`` accepts either a single URL string or a list of URLs. Each URL is+ fetched concurrently (cache-first when ``use_cache`` is true). Returns a+ list of per-URL items preserving the input order.+ """+ urls = _coerce_url_list(url)try:max_chars = int(max_chars)except (TypeError, ValueError):@@ -258,17 +367,51 @@ async def mcp_fetch_webpage(url: str, max_chars: int = 0, timeout_seconds: int =max_timeout_seconds = max(1, max_timeout_seconds)timeout_seconds = max(1, min(timeout_seconds, max_timeout_seconds))- try:- data = await asyncio.to_thread(_fetch_webpage_sync, url, timeout_seconds)- except Exception as exc:- return f"[ERROR]: failed to fetch webpage: {exc}"-- lines = [- f"URL: {data.get('url', url)}",- f"Status: {data.get('status_code', '')}",+ if not urls:+ if cache is not None:+ _log_cache_stats(cache)+ return []++ tasks = [+ _fetch_single_url(+ u,+ max_chars=max_chars,+ timeout_seconds=timeout_seconds,+ use_cache=use_cache,+ cache=cache,+ )+ for u in urls]- if data.get("title"):- lines.append(f"Title: {data['title']}")- lines.append("Content:")- lines.append(_clip_text(str(data.get("content", "") or ""), max_chars) or "[empty]")- return "\n".join(lines)+ items = await asyncio.gather(*tasks)++ if cache is not None:+ _log_cache_stats(cache)++ return list(items)+++mcp_fetch_webpage = tool(+ name="mcp_fetch_webpage",+ description=(+ "抓取网页文本内容,支持一次传入多个 URL 并行抓取。"+ "默认优先从内存缓存读取(use_cache=true),"+ "若缓存内容不够新或需要最新数据,请用 use_cache=false 重新从原站抓取。"+ "返回列表,每个元素含一个 URL 的状态码、标题、纯文本正文与是否命中缓存。"+ ),+)(mcp_fetch_webpage_impl)+++def _log_cache_stats(cache: Any) -> None:+ """输出缓存命中率汇总日志(与 enterprise_dev [FetchCache] 风格对齐)。"""+ try:+ stats = cache.stats()+ logger.info(+ "[FetchCache] hits=%d misses=%d bypassed=%d hit_rate=%.1f%% entries=%d",+ stats["hits"],+ stats["misses"],+ stats["bypassed"],+ stats["hit_rate_pct"],+ stats["entries"],+ )+ except Exception:+ logger.debug("[FetchCache] stats log failed", exc_info=True)diff --git a/jiuwenswarm/agents/harness/common/tools/web_search/content_cache.py b/jiuwenswarm/agents/harness/common/tools/web_search/content_cache.pynew file mode 100644index 0000000000..154a25ff20--- /dev/null+++ b/jiuwenswarm/agents/harness/common/tools/web_search/content_cache.py@@ -0,0 +1,253 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""进程内网页正文缓存:按 agent 隔离,LRU 淘汰,超时清理。"""++from __future__ import annotations++import asyncio+import logging+import time+from dataclasses import dataclass, field+from typing import Optional, Union+from urllib.parse import urlsplit, urlunsplit++logger = logging.getLogger(__name__)++_AGENT_TIMEOUT_SECONDS: int = 2 * 3600+_MAX_AGENTS: int = 32+++@dataclass+class CacheEntry:+ """缓存条目。++ Attributes:+ url: 规范化后的 URL(与缓存键一致)。+ title: 网页标题(可选,仅用于诊断日志)。+ content: 网页正文(markdown 或纯文本)。+ update_time: 网页更新时间 epoch 秒;未知则为 None。+ cached_at: 写入缓存的 epoch 秒。+ source: 来源标记,如 "paid:petal"。+ """+ url: str+ content: str+ update_time: Optional[float] = None+ cached_at: float = field(default_factory=time.time)+ title: str = ""+ source: str = ""+++def normalize_url(url: str) -> str:+ """URL 规范化:去除 fragment、去除尾部斜杠、转小写 host。"""+ from jiuwenswarm.agents.harness.common.tools.web_fetch_tools import _normalize_url+ raw = _normalize_url(url).strip()+ if not raw:+ return ""+ parts = urlsplit(raw)+ scheme = (parts.scheme or "https").lower()+ netloc = (parts.netloc or "").lower()+ path = parts.path or ""+ if len(path) > 1 and path.endswith("/"):+ path = path.rstrip("/")+ return urlunsplit((scheme, netloc, path, parts.query, ""))+++class WebContentCache:+ """单个 agent 的网页正文缓存,并发安全,无条目上限。"""++ def __init__(self) -> None:+ self._store: dict[str, CacheEntry] = {}+ self._order: list[str] = []+ self._lock = asyncio.Lock()+ self.hits = 0+ self.misses = 0+ self.bypassed = 0++ async def get(self, url: str) -> Optional[CacheEntry]:+ key = normalize_url(url)+ if not key:+ return None+ async with self._lock:+ entry = self._store.get(key)+ if entry is None:+ self.misses += 1+ return None+ if key in self._order:+ self._order.remove(key)+ self._order.append(key)+ self.hits += 1+ return entry++ async def put(self, entry: CacheEntry) -> None:+ key = normalize_url(entry.url)+ if not key or not (entry.content or "").strip():+ return+ async with self._lock:+ existing = self._store.get(key)+ if existing is not None:+ if entry.update_time is None and existing.update_time is not None:+ entry.update_time = existing.update_time+ self._store[key] = entry+ if key in self._order:+ self._order.remove(key)+ self._order.append(key)++ async def clear(self) -> None:+ async with self._lock:+ self._store.clear()+ self._order.clear()+ self.hits = 0+ self.misses = 0+ self.bypassed = 0++ def __len__(self) -> int:+ return len(self._store)++ def stats(self) -> dict[str, Union[int, float]]:+ total = self.hits + self.misses + self.bypassed+ hit_rate = (self.hits / total * 100) if total > 0 else 0.0+ return {+ "hits": self.hits,+ "misses": self.misses,+ "bypassed": self.bypassed,+ "total": total,+ "hit_rate_pct": round(hit_rate, 1),+ "entries": len(self._store),+ }+++class AgentCacheRegistry:+ """按 agent 管理缓存实例。++ - 最多 _MAX_AGENTS 个 agent 并发缓存,超出时淘汰最久未活跃的 agent。+ - agent 超时未活跃(_AGENT_TIMEOUT_SECONDS)时清理其缓存。+ - 每个 agent 的缓存无条目上限。+ """++ def __init__(+ self,+ *,+ max_agents: int = _MAX_AGENTS,+ timeout_seconds: int = _AGENT_TIMEOUT_SECONDS,+ ) -> None:+ self._caches: dict[str, WebContentCache] = {}+ self._last_active: dict[str, float] = {}+ self._lock = asyncio.Lock()+ self._max_agents = max_agents+ self._timeout_seconds = timeout_seconds++ async def get_cache(self, agent_id: str) -> WebContentCache:+ aid = (agent_id or "default").strip() or "default"+ async with self._lock:+ now = time.time()+ self._last_active[aid] = now+ self._cleanup_inactive_locked(now)+ cache = self._caches.get(aid)+ if cache is None:+ if len(self._caches) >= self._max_agents:+ lru_aid = min(self._last_active, key=lambda k: self._last_active[k])+ self._caches.pop(lru_aid, None)+ self._last_active.pop(lru_aid, None)+ logger.info(+ "[AgentCacheRegistry] evicted agent=%s (capacity=%d)",+ lru_aid, self._max_agents,+ )+ cache = WebContentCache()+ self._caches[aid] = cache+ return cache++ def _cleanup_inactive_locked(self, now: float) -> None:+ inactive = [+ aid for aid, t in self._last_active.items()+ if now - t > self._timeout_seconds+ ]+ for aid in inactive:+ self._caches.pop(aid, None)+ self._last_active.pop(aid, None)+ logger.info(+ "[AgentCacheRegistry] cleaned inactive agent=%s (timeout=%ds)",+ aid, self._timeout_seconds,+ )++ def get_cache_sync(self, agent_id: str) -> WebContentCache:+ """同步获取缓存,用于无法 await 的场景(如 @harness_element provider)。++ 不加锁,并发竞争最差情况是多创建一个 WebContentCache 被覆盖,不影响正确性。+ """+ aid = (agent_id or "default").strip() or "default"+ now = time.time()+ self._last_active[aid] = now+ self._cleanup_inactive_locked(now)+ cache = self._caches.get(aid)+ if cache is None:+ if len(self._caches) >= self._max_agents:+ lru_aid = min(self._last_active, key=lambda k: self._last_active[k])+ self._caches.pop(lru_aid, None)+ self._last_active.pop(lru_aid, None)+ logger.info(+ "[AgentCacheRegistry] evicted agent=%s (capacity=%d)",+ lru_aid, self._max_agents,+ )+ cache = WebContentCache()+ self._caches[aid] = cache+ return cache++ async def clear_all(self) -> None:+ async with self._lock:+ self._caches.clear()+ self._last_active.clear()++ def stats(self) -> dict[str, Union[int, list[str]]]:+ return {+ "agents": len(self._caches),+ "agent_ids": list(self._caches.keys()),+ "max_agents": self._max_agents,+ "timeout_seconds": self._timeout_seconds,+ }+++_REGISTRY = AgentCacheRegistry()+++def get_agent_cache_registry() -> AgentCacheRegistry:+ return _REGISTRY+++def reset_registry_for_tests() -> None:+ """仅供测试使用:重置全局 registry。"""+ global _REGISTRY+ _REGISTRY = AgentCacheRegistry()+++def parse_update_time(raw: object) -> Optional[float]:+ """从 Petal web_pages[*].update_time 字段解析 epoch 秒。"""+ import datetime as _dt++ if raw is None:+ return None+ try:+ if isinstance(raw, (int, float)):+ return float(raw)+ if isinstance(raw, str):+ s = raw.strip()+ if not s:+ return None+ if s.isdigit():+ return float(s)+ try:+ return _dt.datetime.fromisoformat(s.replace("Z", "+00:00")).timestamp()+ except ValueError:+ pass+ for fmt in (+ "%Y-%m-%d %H:%M:%S",+ "%Y-%m-%d",+ "%Y/%m/%d",+ "%d/%m/%Y",+ ):+ try:+ return _dt.datetime.strptime(s, fmt).timestamp()+ except ValueError:+ continue+ except Exception:+ logger.debug("parse_update_time failed for raw=%r", raw, exc_info=True)+ return Nonediff --git a/jiuwenswarm/agents/harness/common/tools/web_search/harness.py b/jiuwenswarm/agents/harness/common/tools/web_search/harness.pyindex 472bf7929e..188b1e268b 100644--- a/jiuwenswarm/agents/harness/common/tools/web_search/harness.py+++ b/jiuwenswarm/agents/harness/common/tools/web_search/harness.py@@ -11,7 +11,7 @@ from openjiuwen.harness.prompts import resolve_languagefrom jiuwenswarm.agents.harness.common.tools.web_search.tool import (build_web_search_tool_card,- web_search,+ web_search_impl,)from jiuwenswarm.common.utils import logger@@ -24,19 +24,23 @@ class JiuwenHarnessWebSearchTool(Tool):language: str = "cn",agent_id: Optional[str] = None,card: Optional[ToolCard] = None,+ cache: Any | None = None,) -> None:lang = resolve_language(language or "cn")super().__init__(cardor build_web_search_tool_card(agent_id=agent_id, language=lang),)+ self._cache = cacheasync def invoke(self, inputs: Dict[str, Any], **kwargs) -> Any:logger.debug("[JiuwenHarnessWebTools] web_search card_id=%s",self.card.id,)- return await web_search.invoke(inputs, **kwargs)+ if self._cache is not None:+ kwargs["cache"] = self._cache+ return await web_search_impl(**inputs, **{k: v for k, v in kwargs.items() if k in ("cache",)})async def stream(self, inputs: Dict[str, Any], **kwargs) -> AsyncIterator[Any]:yield "Stream is not supported for this tool."diff --git a/jiuwenswarm/agents/harness/common/tools/web_search/orchestrator.py b/jiuwenswarm/agents/harness/common/tools/web_search/orchestrator.pyindex 14008020e3..d3e0f20f4f 100644--- a/jiuwenswarm/agents/harness/common/tools/web_search/orchestrator.py+++ b/jiuwenswarm/agents/harness/common/tools/web_search/orchestrator.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport loggingimport re+from typing import Anyfrom jiuwenswarm.agents.harness.common.tools.web_search.constants import KNOWN_PAID_PROVIDERSfrom jiuwenswarm.agents.harness.common.tools.web_search.free import _free_search_engines@@ -170,6 +171,7 @@ async def run_web_search(search_mode: str = "default",search_source: str | None = None,max_results: int | None = None,+ cache: Any | None = None,) -> str:settings = resolve_web_search_settings(max_results)mode, extracted_source = normalize_search_mode(search_mode)@@ -237,7 +239,7 @@ async def run_web_search(paid_run: ProviderRun | None = Nonetried: list[str] = []if preferred_source:- paid_run, tried = await run_paid_chain(query, settings, preferred_provider=preferred_source)+ paid_run, tried = await run_paid_chain(query, settings, preferred_provider=preferred_source, cache=cache)else:if not any_paid_provider_available(settings.paid_provider_order):availability = paid_availability_report(settings.paid_provider_order)@@ -250,7 +252,7 @@ async def run_web_search(if _free_search_engines():return "[ERROR]: paid search unavailable. Use search_mode=free instead."return "[ERROR]: paid search unavailable. No search source is available."- paid_run, tried = await run_paid_chain(query, settings)+ paid_run, tried = await run_paid_chain(query, settings, cache=cache)if paid_run and paid_run.quality_passed:_log_done(query=query,diff --git a/jiuwenswarm/agents/harness/common/tools/web_search/paid.py b/jiuwenswarm/agents/harness/common/tools/web_search/paid.pyindex ee1af38254..bca4856dee 100644--- a/jiuwenswarm/agents/harness/common/tools/web_search/paid.py+++ b/jiuwenswarm/agents/harness/common/tools/web_search/paid.py@@ -8,17 +8,21 @@ import jsonimport loggingimport osimport re-from typing import Any+import time+from typing import Any, Optionalfrom jiuwenswarm.agents.harness.common.tools.web_search.http_client import http_request+from jiuwenswarm.agents.harness.common.tools.web_search.content_cache import parse_update_timefrom jiuwenswarm.common.config import get_configfrom jiuwenswarm.common.local_env_config import read_envlogger = logging.getLogger(__name__)+baseline = logging.getLogger("jiuwenswarm.agents.harness.common.tools.web_search.baseline")_PETAL_MAX_TITLE_LEN = 2000_PETAL_MAX_URL_LEN = 2048_PETAL_MAX_SUMMARY_LEN = 4000+_PETAL_MAX_CONTENT_LEN = 20000_TAVILY_DEFAULT_API_URL = "https://api.tavily.com"_TAVILY_MAX_CONTENT_LEN = 4000@@ -39,14 +43,20 @@ def _load_llm_default_headers() -> dict[str, str]:return header_map-def _petal_normalize_web_page_item(item: dict[str, Any]) -> dict[str, str]:+def _petal_normalize_web_page_item(item: dict[str, Any]) -> dict[str, Any]:raw_url = item.get("url") or item.get("link") or item.get("source_url") or ""title = (item.get("title") or item.get("name") or "").strip()summary = (item.get("summary") or "").strip()+ content = (item.get("content") or item.get("text") or "").strip()+ update_time_raw = (+ item.get("update_time") or item.get("publish_time") or item.get("date")+ )return {"title": title[:_PETAL_MAX_TITLE_LEN],"url": str(raw_url).strip()[:_PETAL_MAX_URL_LEN],"summary": summary[:_PETAL_MAX_SUMMARY_LEN],+ "content": content[:_PETAL_MAX_CONTENT_LEN],+ "update_time": parse_update_time(update_time_raw),}@@ -70,10 +80,11 @@ def _petal_format_answer_from_records(records: list[dict[str, str]]) -> str:def petal_search_sync(query: str, max_results: int, timeout_seconds: int) -> dict[str, Any]:+ _start = time.perf_counter()search_url = _resolve_petal_search_url()header_map = _load_llm_default_headers()headers = {**header_map, "Content-Type": "application/json"}- payload = {"query": query, "content": False}+ payload = {"query": query, "content": True}response = http_request("POST",@@ -86,7 +97,7 @@ def petal_search_sync(query: str, max_results: int, timeout_seconds: int) -> dicdata = response.json()web_pages = data.get("web_pages", [])- records: list[dict[str, str]] = []+ records: list[dict[str, Any]] = []if isinstance(web_pages, list):for raw in web_pages[:max_results]:if not isinstance(raw, dict):@@ -95,7 +106,19 @@ def petal_search_sync(query: str, max_results: int, timeout_seconds: int) -> dicanswer = _petal_format_answer_from_records(records)urls = [r["url"] for r in records if r.get("url")][:max_results]- return {"provider": "petal", "answer": answer, "urls": urls}+ cost_ms = int((time.perf_counter() - _start) * 1000)+ baseline.info(+ "BASELINE petal_search query=%r urls=%d cost_ms=%d",+ query,+ len(urls),+ cost_ms,+ )+ return {+ "provider": "petal",+ "answer": answer,+ "urls": urls,+ "records": records,+ }def enable_petal_search() -> bool:diff --git a/jiuwenswarm/agents/harness/common/tools/web_search/providers.py b/jiuwenswarm/agents/harness/common/tools/web_search/providers.pyindex 7f3c4dce37..6632c27de3 100644--- a/jiuwenswarm/agents/harness/common/tools/web_search/providers.py+++ b/jiuwenswarm/agents/harness/common/tools/web_search/providers.py@@ -83,16 +83,34 @@ def records_from_paid_payload(for item in (payload.get("urls") or [])if item][:max_results]+ # petal 携带 records(含 content/update_time/summary);其他 provider 无此字段+ raw_records = payload.get("records") if isinstance(payload.get("records"), list) else []++ # 构建 url -> {content, update_time, summary} 映射(仅 petal 有)+ extras: dict[str, dict[str, Any]] = {}+ for rr in raw_records:+ if isinstance(rr, dict):+ u = str(rr.get("url") or "").strip()+ if u:+ extras[u] = {+ "content": str(rr.get("content") or ""),+ "update_time": rr.get("update_time"), # Optional[float],None 表示缺失+ "summary": str(rr.get("summary") or ""),+ }+records: list[WebSearchRecord] = []for url in urls:if not _is_valid_http_url(url):continue+ extra = extras.get(url, {})records.append(WebSearchRecord(title=_title_from_url(url),url=url,- snippet="",+ snippet=extra.get("summary", ""), # 修复:petal summary 透传到 snippetsource=f"paid:{provider}",+ content=extra.get("content", ""),+ update_time=extra.get("update_time"),))return records, answer@@ -103,6 +121,7 @@ async def invoke_paid_provider(query: str,max_results: int,timeout_seconds: int,+ cache: Any | None = None,) -> ProviderRun:label = f"paid:{name}"if not paid_provider_available(name):@@ -152,6 +171,25 @@ async def invoke_paid_provider(return ProviderRun(provider=label, error=str(exc))records, answer = records_from_paid_payload(name, payload, max_results)++ # 仅 petal 写缓存(其他 provider 未开启 content)+ if name == "petal" and cache is not None:+ from jiuwenswarm.agents.harness.common.tools.web_search.content_cache import (+ CacheEntry,+ )++ for rec in records:+ if rec.content and rec.url:+ await cache.put(+ CacheEntry(+ url=rec.url,+ content=rec.content,+ update_time=rec.update_time,+ title=rec.title,+ source=f"paid:{name}",+ )+ )+passed, reason = evaluate_search_quality(records,answer=answer,@@ -177,6 +215,7 @@ async def run_paid_chain(query: str,settings: WebSearchSettings,preferred_provider: str | None = None,+ cache: Any | None = None,) -> tuple[ProviderRun | None, list[str]]:tried: list[str] = []last_run: ProviderRun | None = None@@ -193,6 +232,7 @@ async def run_paid_chain(query,settings.max_results,settings.timeout_seconds,+ cache=cache,)last_run = runif run.error == "skipped":diff --git a/jiuwenswarm/agents/harness/common/tools/web_search/response.py b/jiuwenswarm/agents/harness/common/tools/web_search/response.pyindex f332ef3931..8ef1b27b7c 100644--- a/jiuwenswarm/agents/harness/common/tools/web_search/response.py+++ b/jiuwenswarm/agents/harness/common/tools/web_search/response.py@@ -30,6 +30,8 @@ def _format_records_block(if not deduped and not include_answer.strip():lines.append("(no structured results)")return lines+ # 提示模型按需调用 fetch_webpage(正文已在内存缓存,命中快)+ lines.append("Hint: 仅展示摘要与 URL。如需正文,请调用 fetch_webpage 工具。")for idx, rec in enumerate(deduped, 1):lines.append(f"{idx}. {rec.title}")if rec.url:diff --git a/jiuwenswarm/agents/harness/common/tools/web_search/tool.py b/jiuwenswarm/agents/harness/common/tools/web_search/tool.pyindex 1622585a02..2c2bdac525 100644--- a/jiuwenswarm/agents/harness/common/tools/web_search/tool.py+++ b/jiuwenswarm/agents/harness/common/tools/web_search/tool.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport loggingimport uuid-from typing import Any+from typing import Any, Optionalfrom openjiuwen.core.foundation.tool import toolfrom openjiuwen.core.foundation.tool.base import ToolCard@@ -51,6 +51,10 @@ def _has_enabled_free_engines() -> bool:def _build_web_search_description() -> str:+ suffix = (+ "搜索结果默认仅返回摘要与 URL 列表;"+ "若需查看网页正文,请调用 fetch_webpage 工具(优先从内存缓存读取)。"+ )has_free = _has_enabled_free_engines()if has_free:return (@@ -63,7 +67,7 @@ def _build_web_search_description() -> str:"若用户指定使用某搜索引擎(如 bing、duckduckgo),请在 query 开头包含该引擎名称(如 'bing 今天的天气'),""以便系统识别并在引擎不可用时向用户说明。""default 模式已尝试所有可用搜索源(付费与免费),任何失败(all sources exhausted 或 no results)都不要再单独用 search_mode=paid 或 free 重试,"- "也不要换 query 重试,直接告知用户搜索失败。"+ "也不要换 query 重试,直接告知用户搜索失败。" + suffix)else:return (@@ -75,19 +79,16 @@ def _build_web_search_description() -> str:"若用户指定使用某搜索引擎(如 bing、duckduckgo),请在 query 开头包含该引擎名称(如 'bing 今天的天气'),""以便系统识别并在引擎不可用时向用户说明。""default 模式已尝试所有可用搜索源(付费),任何失败(all sources exhausted 或 no results)都不要再单独用 search_mode=paid 重试,"- "也不要换 query 重试,直接告知用户搜索失败。"+ "也不要换 query 重试,直接告知用户搜索失败。" + suffix)-@tool(- name="web_search",- description=_build_web_search_description(),-)-async def web_search(+async def web_search_impl(query: str,search_mode: str = "default",search_source: str | None = None,max_results: int | None = None,+ cache: Any | None = None,) -> str:query = (query or "").strip()if not query:@@ -109,7 +110,15 @@ async def web_search(if raw in KNOWN_PAID_PROVIDERS:source = raw- return await run_web_search(query, search_mode=mode, search_source=source, max_results=max_results)+ return await run_web_search(+ query, search_mode=mode, search_source=source, max_results=max_results, cache=cache,+ )+++web_search = tool(+ name="web_search",+ description=_build_web_search_description(),+)(web_search_impl)def _import_harness_web_schema():diff --git a/jiuwenswarm/agents/harness/common/tools/web_search/types.py b/jiuwenswarm/agents/harness/common/tools/web_search/types.pyindex 83ce94e2a0..1f4c2c1e6b 100644--- a/jiuwenswarm/agents/harness/common/tools/web_search/types.py+++ b/jiuwenswarm/agents/harness/common/tools/web_search/types.py@@ -3,6 +3,7 @@from __future__ import annotationsfrom dataclasses import dataclass, field+from typing import Optional@dataclass@@ -11,6 +12,8 @@ class WebSearchRecord:url: strsnippet: strsource: str+ content: str = "" # 网页正文(仅 petal content=True 时携带;不进给模型的响应)+ update_time: Optional[float] = None # 网页更新时间 epoch 秒;None 表示缺失@dataclassdiff --git a/jiuwenswarm/agents/swarm/providers/tools.py b/jiuwenswarm/agents/swarm/providers/tools.pyindex d0d729889f..1d5f2b7785 100644--- a/jiuwenswarm/agents/swarm/providers/tools.py+++ b/jiuwenswarm/agents/swarm/providers/tools.py@@ -480,7 +480,12 @@ def build_jiuwen_web_search(ctx: SwarmBuildContext,) -> list[Any]:agent_id, language = _member_web_tool_identity(ctx)- tool = JiuwenHarnessWebSearchTool(language=language, agent_id=agent_id)+ from jiuwenswarm.agents.harness.common.tools.web_search.content_cache import (+ get_agent_cache_registry,+ )++ content_cache = get_agent_cache_registry().get_cache_sync(agent_id or "default")+ tool = JiuwenHarnessWebSearchTool(language=language, agent_id=agent_id, cache=content_cache)return [_reuse_registered_tool(tool)]@@ -494,7 +499,12 @@ def build_jiuwen_web_fetch(ctx: SwarmBuildContext,) -> list[Any]:agent_id, language = _member_web_tool_identity(ctx)- tool = JiuwenHarnessFetchWebpageTool(language=language, agent_id=agent_id)+ from jiuwenswarm.agents.harness.common.tools.web_search.content_cache import (+ get_agent_cache_registry,+ )++ content_cache = get_agent_cache_registry().get_cache_sync(agent_id or "default")+ tool = JiuwenHarnessFetchWebpageTool(language=language, agent_id=agent_id, cache=content_cache)return [_reuse_registered_tool(tool)]diff --git a/jiuwenswarm/common/e2a/acp/acp_tool_updates.py b/jiuwenswarm/common/e2a/acp/acp_tool_updates.pyindex 53f87b4e00..43424d1fb3 100644--- a/jiuwenswarm/common/e2a/acp/acp_tool_updates.py+++ b/jiuwenswarm/common/e2a/acp/acp_tool_updates.py@@ -340,11 +340,37 @@ def _infer_tool_kind(tool_name: str) -> str:return "other"+def _first_url_value(arguments: dict[str, Any]) -> str | None:+ """Resolve the ``url`` argument to a displayable string.++ ``url`` may be a single string or an array of strings (multi-URL fetch).+ For arrays, the first URL is returned.+ """+ value = arguments.get("url")+ if isinstance(value, str) and value.strip():+ return value.strip()+ if isinstance(value, (list, tuple)):+ for item in value:+ if isinstance(item, str) and item.strip():+ return item.strip()+ return None+++def _url_list(arguments: dict[str, Any]) -> list[str]:+ """Return the ``url`` argument as a list of non-empty strings."""+ value = arguments.get("url")+ if isinstance(value, str) and value.strip():+ return [value.strip()]+ if isinstance(value, (list, tuple)):+ return [str(v).strip() for v in value if str(v).strip()]+ return []++def _build_tool_title(tool_name: str, arguments: dict[str, Any]) -> str:normalized = normalize_tool_name(tool_name).lower()path = _summarize_path(_first_string_value(arguments, *_PATH_KEYS))query = _first_string_value(arguments, "pattern", "query", "term", "text")- url = _first_string_value(arguments, "url")+ url = _first_url_value(arguments)command = _first_string_value(arguments, "command", "cmd")terminal_id = _first_string_value(arguments, "terminalId", "terminal_id")@@ -362,8 +388,12 @@ def _build_tool_title(tool_name: str, arguments: dict[str, Any]) -> str:return f"Running in {path}"return "Running command"- if normalized in _FETCH_TOOL_NAMES and url:- return f"Fetching {url}"+ if normalized in _FETCH_TOOL_NAMES:+ urls = _url_list(arguments)+ if len(urls) > 1:+ return f"Fetching {len(urls)} URLs"+ if url:+ return f"Fetching {url}"if normalized in _SEARCH_TOOL_NAMES:if query and path:return f"Searching {query} in {path}"diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 530e11c3cc..1bf1022662 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -3414,6 +3414,10 @@ class JiuWenSwarmDeepAdapter:research_agent_cfg = subagents_cfg.get("research_agent")if self._is_subagent_enabled(research_agent_cfg):+ from jiuwenswarm.agents.harness.common.tools.web_search.content_cache import (+ get_agent_cache_registry,+ )+subagents.append(build_research_agent_config(model,@@ -3427,6 +3431,9 @@ class JiuWenSwarmDeepAdapter:tools=build_jiuwen_harness_named_web_tools(agent_id="research_agent",language=resolved_language,+ cache=get_agent_cache_registry().get_cache_sync(+ "research_agent",+ ),),))@@ -7153,9 +7160,15 @@ class JiuWenSwarmDeepAdapter:registered = self._register_shared_tool(wtool)tool_cards.append(registered.card)+ from jiuwenswarm.agents.harness.common.tools.web_search.content_cache import (+ get_agent_cache_registry,+ )++ content_cache = await get_agent_cache_registry().get_cache(agent_id)for tool_instance in build_jiuwen_harness_named_web_tools(agent_id=agent_id,language=self._resolve_runtime_language(),+ cache=content_cache,):registered = self._register_agent_owned_tool(tool_instance, agent_id)tool_cards.append(registered.card)diff --git a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/deep_research.py b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/deep_research.pyindex f25a2e75cf..363d5c2f5e 100644--- a/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/deep_research.py+++ b/jiuwenswarm/server/runtime/skill_turbo/skill_codes/ppt/deep_research.py@@ -8,6 +8,27 @@ from dataclasses import dataclassfrom datetime import datetime, timezonefrom typing import Any++def _extract_fetch_result_items(result: Any) -> list[dict[str, Any]]:+ """Normalize a fetch_webpage tool result into a list of per-URL item dicts.++ fetch_webpage now returns a bare list of per-URL items; older callers may+ still receive ``{"results": [...]}`` or a plain string, so we keep tolerant+ fallbacks.+ """+ if isinstance(result, list):+ return [i for i in result if isinstance(i, dict)]+ if isinstance(result, dict):+ items = result.get("results")+ if isinstance(items, list):+ return [i for i in items if isinstance(i, dict)]+ if isinstance(items, dict):+ return [items]+ if isinstance(result, str) and result.strip():+ return [{"url": "", "content": result}]+ return []++from jiuwenswarm.server.runtime.skill_turbo.plan_node import AbortError, PlanNodefrom jiuwenswarm.server.runtime.skill_turbo.skill_codes.ppt.ppt_common import PptCommon@@ -1004,38 +1025,39 @@ class PageWorkerNode(PlanNode):if url not in existing_top_urls:top_sources.append({"url": url})- fetch_tasks = []fetch_urls: list[str] = []for source in top_sources:url = source.get("url", "")- if not url:- continue- fetch_tasks.append(- self.call_tool(- "fetch_webpage",- url=url,- max_chars=8000,- timeout_seconds=8,- )- )- fetch_urls.append(url)+ if url and url not in fetch_urls:+ fetch_urls.append(url)- if not fetch_tasks:+ if not fetch_urls:return []- results = await asyncio.gather(*fetch_tasks, return_exceptions=True)+ try:+ result = await self.call_tool(+ "fetch_webpage",+ url=fetch_urls,+ max_chars=8000,+ timeout_seconds=8,+ )+ except Exception as exc:+ logger.warning("[P6.1] WebFetch 批量抓取失败 urls=%s: %s", fetch_urls, exc)+ return []++ items = _extract_fetch_result_items(result)extractions: list[dict[str, Any]] = []- for url, result in zip(fetch_urls, results):- if isinstance(result, Exception):- logger.warning("[P6.1] WebFetch 失败 url=%s: %s", url[:80], result)+ for item in items:+ url = str(item.get("url", "")).strip()+ error = item.get("error")+ if error:+ logger.warning("[P6.1] WebFetch 失败 url=%s: %s", url[:80], error)continue- if isinstance(result, str) and result.startswith("[ERROR]"):+ content = str(item.get("content", "") or "")+ if not content:continue- extractions.append({- "url": url,- "content": str(result),- })+ extractions.append({"url": url, "content": content})return extractionsdiff --git a/tests/unit_tests/agents/harness/test_web_search.py b/tests/unit_tests/agents/harness/test_web_search.pyindex 0027c1c598..d1c80c7af0 100644--- a/tests/unit_tests/agents/harness/test_web_search.py+++ b/tests/unit_tests/agents/harness/test_web_search.py@@ -191,7 +191,7 @@ def test_web_search_entry_delegates_to_orchestrator(monkeypatch):calls = 0- async def fake_run(query, *, search_mode="default", search_source=None, max_results=None):+ async def fake_run(query, *, search_mode="default", search_source=None, max_results=None, cache=None):nonlocal callscalls += 1assert query == "hello"@@ -216,7 +216,7 @@ def test_web_search_invalid_search_mode_falls_back_to_default(monkeypatch):calls: list[str] = []- async def fake_run(query, *, search_mode="default", search_source=None, max_results=None):+ async def fake_run(query, *, search_mode="default", search_source=None, max_results=None, cache=None):calls.append(search_mode)return "ok"diff --git a/tests/unit_tests/tools/test_web_content_cache.py b/tests/unit_tests/tools/test_web_content_cache.pynew file mode 100644index 0000000000..cdb943a211--- /dev/null+++ b/tests/unit_tests/tools/test_web_content_cache.py@@ -0,0 +1,195 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""content_cache 单元测试(per-agent 隔离版)。++覆盖:normalize_url、WebContentCache put/get、覆盖保护、stats、AgentCacheRegistry。+"""++from __future__ import annotations++import asyncio+import time++import pytest++from jiuwenswarm.agents.harness.common.tools.web_search.content_cache import (+ AgentCacheRegistry,+ CacheEntry,+ WebContentCache,+ normalize_url,+ parse_update_time,+ reset_registry_for_tests,+ get_agent_cache_registry,+)+++def _run(coro):+ return asyncio.run(coro)+++class TestNormalizeUrl:+ def test_strips_fragment(self):+ assert normalize_url("https://example.com/page#section") == "https://example.com/page"++ def test_lowercases_host(self):+ assert normalize_url("https://Example.COM/Path") == "https://example.com/Path"++ def test_strips_trailing_slash(self):+ assert normalize_url("https://example.com/path/") == "https://example.com/path"++ def test_keeps_root_slash(self):+ assert normalize_url("https://example.com/") == "https://example.com/"++ def test_keeps_query(self):+ assert normalize_url("https://example.com/path?a=1&b=2") == "https://example.com/path?a=1&b=2"++ def test_empty_returns_empty(self):+ assert normalize_url("") == ""+ assert normalize_url(" ") == ""+++class TestWebContentCachePutGet:+ def test_put_then_get_returns_entry(self):+ cache = WebContentCache()+ _run(cache.put(CacheEntry(url="https://example.com/test", content="hello", update_time=1700000000.0, title="T", source="paid:petal")))+ entry = _run(cache.get("https://example.com/test"))+ assert entry is not None+ assert entry.content == "hello"+ assert entry.update_time == 1700000000.0+ assert entry.source == "paid:petal"++ def test_get_miss_returns_none(self):+ cache = WebContentCache()+ entry = _run(cache.get("https://example.com/nonexistent"))+ assert entry is None++ def test_put_empty_content_skipped(self):+ cache = WebContentCache()+ _run(cache.put(CacheEntry(url="https://example.com/empty", content="", update_time=1700000000.0)))+ entry = _run(cache.get("https://example.com/empty"))+ assert entry is None++ def test_get_returns_without_update_time(self):+ cache = WebContentCache()+ _run(cache.put(CacheEntry(url="https://example.com/nout", content="c", update_time=None)))+ entry = _run(cache.get("https://example.com/nout"))+ assert entry is not None+ assert entry.update_time is None+++class TestOverwriteProtection:+ def test_overwrites_when_newer_content(self):+ cache = WebContentCache()+ _run(cache.put(CacheEntry(url="https://example.com/ow", content="c1", update_time=1700000000.0, title="T1")))+ _run(cache.put(CacheEntry(url="https://example.com/ow", content="c2", update_time=1700000001.0, title="T2")))+ entry = _run(cache.get("https://example.com/ow"))+ assert entry.content == "c2"+ assert entry.update_time == 1700000001.0++ def test_preserves_old_update_time_when_new_is_none(self):+ cache = WebContentCache()+ _run(cache.put(CacheEntry(url="https://example.com/preserve", content="c1", update_time=1700000000.0, title="T1")))+ _run(cache.put(CacheEntry(url="https://example.com/preserve", content="c2", update_time=None, title="T2")))+ entry = _run(cache.get("https://example.com/preserve"))+ assert entry.content == "c2"+ assert entry.update_time == 1700000000.0+++class TestCacheStats:+ def test_hits_misses_counted(self):+ cache = WebContentCache()+ _run(cache.put(CacheEntry(url="https://example.com/s1", content="c1", update_time=1700000000.0)))+ _run(cache.get("https://example.com/s1"))+ _run(cache.get("https://example.com/miss"))+ stats = cache.stats()+ assert stats["hits"] == 1+ assert stats["misses"] == 1+ assert stats["bypassed"] == 0+ assert stats["total"] == 2++ def test_bypass_counted(self):+ cache = WebContentCache()+ cache.bypassed += 1+ cache.bypassed += 1+ stats = cache.stats()+ assert stats["bypassed"] == 2++ def test_hit_rate_pct(self):+ cache = WebContentCache()+ _run(cache.put(CacheEntry(url="https://example.com/hr", content="c", update_time=1700000000.0)))+ _run(cache.get("https://example.com/hr"))+ _run(cache.get("https://example.com/miss1"))+ _run(cache.get("https://example.com/miss2"))+ cache.bypassed += 1+ stats = cache.stats()+ assert stats["hit_rate_pct"] == 25.0++ def test_clear_resets(self):+ cache = WebContentCache()+ _run(cache.put(CacheEntry(url="https://example.com/c", content="c", update_time=1700000000.0)))+ _run(cache.get("https://example.com/c"))+ _run(cache.clear())+ stats = cache.stats()+ assert stats["hits"] == 0+ assert stats["entries"] == 0+++class TestAgentCacheRegistry:+ def setup_method(self):+ reset_registry_for_tests()++ def test_get_cache_returns_per_agent_isolated(self):+ registry = get_agent_cache_registry()+ cache_a = _run(registry.get_cache("agent_a"))+ cache_b = _run(registry.get_cache("agent_b"))+ assert cache_a is not cache_b++ _run(cache_a.put(CacheEntry(url="https://example.com/iso", content="from_a", update_time=1700000000.0)))+ entry_b = _run(cache_b.get("https://example.com/iso"))+ assert entry_b is None # agent B 看不到 agent A 的缓存++ def test_same_agent_returns_same_cache(self):+ registry = get_agent_cache_registry()+ cache1 = _run(registry.get_cache("agent_x"))+ cache2 = _run(registry.get_cache("agent_x"))+ assert cache1 is cache2++ def test_default_agent_id(self):+ registry = get_agent_cache_registry()+ cache = _run(registry.get_cache(""))+ assert cache is not None++ def test_stats(self):+ registry = get_agent_cache_registry()+ _run(registry.get_cache("agent1"))+ _run(registry.get_cache("agent2"))+ stats = registry.stats()+ assert stats["agents"] == 2+ assert "agent1" in stats["agent_ids"]+ assert "agent2" in stats["agent_ids"]+++class TestParseUpdateTime:+ def test_parse_int_epoch(self):+ assert parse_update_time(1700000000) == 1700000000.0++ def test_parse_iso8601(self):+ result = parse_update_time("2026-08-19T12:00:00")+ assert result is not None+ assert result > 0++ def test_parse_date_only(self):+ result = parse_update_time("2026-08-19")+ assert result is not None++ def test_parse_none_returns_none(self):+ assert parse_update_time(None) is None++ def test_parse_empty_string_returns_none(self):+ assert parse_update_time("") is None++ def test_parse_invalid_returns_none(self):+ assert parse_update_time("not a date") is None++ def test_parse_digit_string_as_epoch(self):+ assert parse_update_time("1700000000") == 1700000000.0diff --git a/tests/unit_tests/tools/test_web_fetch_cache_mode.py b/tests/unit_tests/tools/test_web_fetch_cache_mode.pynew file mode 100644index 0000000000..374e5a0387--- /dev/null+++ b/tests/unit_tests/tools/test_web_fetch_cache_mode.py@@ -0,0 +1,163 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""fetch 双模式(use_cache)单元测试(per-agent cache + 多 URL 并行版)。++通过 mcp_fetch_webpage_impl 直接调用,cache 作为参数传入(绕过 @tool 的 pydantic 复制)。+"""++from __future__ import annotations++import asyncio+import time+from unittest.mock import patch++import pytest++from jiuwenswarm.agents.harness.common.tools.web_search.content_cache import (+ CacheEntry,+ WebContentCache,+)+++def _run(coro):+ return asyncio.run(coro)+++def _make_cache_with_entry(url: str, content: str, update_time=None) -> WebContentCache:+ cache = WebContentCache()+ _run(cache.put(CacheEntry(url=url, content=content, update_time=update_time, title="T", source="paid:petal")))+ return cache+++def _first(result):+ assert isinstance(result, list)+ assert result, "expected at least one result item"+ return result[0]+++def _invoke(url, cache=None, use_cache=True):+ from jiuwenswarm.agents.harness.common.tools.web_fetch_tools import mcp_fetch_webpage_impl+ return _run(mcp_fetch_webpage_impl(url=url, use_cache=use_cache, cache=cache))+++class TestFetchCacheHit:+ def test_cache_hit_returns_content_and_metadata(self):+ cache = _make_cache_with_entry("https://example.com/cached", "cached content body", time.time() - 86400)+ result = _invoke("https://example.com/cached", cache=cache)+ item = _first(result)+ assert item["from_cache"] is True+ assert "cached content body" in item["content"]+ assert item.get("cache_age_days") is not None+ assert item.get("page_update_days") is not None++ def test_cache_hit_no_update_time_shows_none(self):+ cache = _make_cache_with_entry("https://example.com/nout", "content", update_time=None)+ result = _invoke("https://example.com/nout", cache=cache)+ item = _first(result)+ assert item["from_cache"] is True+ assert item.get("page_update_days") is None+++class TestFetchCacheMiss:+ def test_cache_miss_falls_back_to_network(self):+ cache = WebContentCache()+ mock_data = {"url": "https://example.com/live", "status_code": 200, "title": "Live", "content": "live content"}+ with patch("jiuwenswarm.agents.harness.common.tools.web_fetch_tools._fetch_webpage_sync", return_value=mock_data):+ result = _invoke("https://example.com/live", cache=cache)+ item = _first(result)+ assert item["from_cache"] is False+ assert "live content" in item["content"]+ assert item["provider"] == "direct"+ stats = cache.stats()+ assert stats["hits"] == 0+ assert stats["misses"] == 1+++class TestUseCacheFalse:+ def test_use_cache_false_bypasses_cache(self):+ cache = _make_cache_with_entry("https://example.com/bypass", "cached content", time.time() - 3600)+ mock_data = {"url": "https://example.com/bypass", "status_code": 200, "title": "Live", "content": "fresh content"}+ with patch("jiuwenswarm.agents.harness.common.tools.web_fetch_tools._fetch_webpage_sync", return_value=mock_data):+ result = _invoke("https://example.com/bypass", cache=cache, use_cache=False)+ item = _first(result)+ assert item["from_cache"] is False+ assert "fresh content" in item["content"]+ stats = cache.stats()+ assert stats["bypassed"] == 1+ assert stats["hits"] == 0+++class TestFetchNoWriteback:+ def test_network_fetch_does_not_write_cache(self):+ cache = WebContentCache()+ mock_data = {"url": "https://example.com/nowrite", "status_code": 200, "title": "NW", "content": "should not be cached"}+ with patch("jiuwenswarm.agents.harness.common.tools.web_fetch_tools._fetch_webpage_sync", return_value=mock_data):+ _invoke("https://example.com/nowrite", cache=cache)+ with patch("jiuwenswarm.agents.harness.common.tools.web_fetch_tools._fetch_webpage_sync", return_value=mock_data):+ _invoke("https://example.com/nowrite", cache=cache)+ stats = cache.stats()+ assert stats["hits"] == 0+ assert stats["misses"] == 2+++class TestFetchNoCache:+ def test_no_cache_still_works(self):+ mock_data = {"url": "https://example.com/nocache", "status_code": 200, "title": "NC", "content": "no cache content"}+ with patch("jiuwenswarm.agents.harness.common.tools.web_fetch_tools._fetch_webpage_sync", return_value=mock_data):+ result = _invoke("https://example.com/nocache")+ item = _first(result)+ assert item["from_cache"] is False+ assert "no cache content" in item["content"]+++class TestFetchMultipleUrls:+ def test_multiple_urls_returns_one_item_per_url_in_order(self):+ urls = ["https://example.com/a", "https://example.com/b", "https://example.com/c"]+ contents = {"a": "content A", "b": "content B", "c": "content C"}++ def fake_fetch(url, timeout_seconds):+ key = url.rsplit("/", 1)[-1]+ return {"url": url, "status_code": 200, "title": "", "content": contents.get(key, "")}++ with patch("jiuwenswarm.agents.harness.common.tools.web_fetch_tools._fetch_webpage_sync", side_effect=fake_fetch):+ result = _invoke(urls)++ assert isinstance(result, list)+ assert len(result) == 3+ for item, url in zip(result, urls):+ assert item["url"] == url+ assert item["from_cache"] is False++ def test_multiple_urls_partial_failure_keeps_error_item(self):+ good = "https://example.com/ok"+ bad = "https://example.com/bad"++ def fake_fetch(url, timeout_seconds):+ if url == bad:+ raise RuntimeError("boom")+ return {"url": url, "status_code": 200, "title": "", "content": "ok content"}++ with patch("jiuwenswarm.agents.harness.common.tools.web_fetch_tools._fetch_webpage_sync", side_effect=fake_fetch):+ result = _invoke([good, bad])++ assert isinstance(result, list)+ assert len(result) == 2+ ok_item, bad_item = result+ assert ok_item["url"] == good+ assert "ok content" in ok_item["content"]+ assert "error" not in ok_item+ assert bad_item["url"] == bad+ assert bad_item.get("error")+ assert bad_item["content"] == ""++ def test_empty_url_list_returns_empty_results(self):+ result = _invoke([])+ assert result == []++ def test_single_url_string_still_works(self):+ mock_data = {"url": "https://example.com/single", "status_code": 200, "title": "S", "content": "single content"}+ with patch("jiuwenswarm.agents.harness.common.tools.web_fetch_tools._fetch_webpage_sync", return_value=mock_data):+ result = _invoke("https://example.com/single")+ item = _first(result)+ assert item["url"] == "https://example.com/single"+ assert "single content" in item["content"]