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:deepresearch]深度研究改写功能引用改写异常
zjjggwx8c9969c49400
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.pyindex 02433cbe6f..b3a9f696e2 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py@@ -2530,6 +2530,10 @@ async def _call_deepresearch_stream_impl(@tool(name="deepresearch_stream",description=(+ "Low-level compatibility interface, not a substitute for loading the skill. "+ "For requests to use the deepresearch skill, including the DeepResearch "+ "capsule, first call skill_tool(skill_name=\"deepresearch\") and follow "+ "the skill's deepresearch_execute entry instead of calling this tool. ""Run or resume DeepResearch through the isolated external skill runner. ""Progress is pushed to the current Gateway route; only a terminal ""interrupted, completed, or structured error outcome is returned. "diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/citation_links.py b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/citation_links.pynew file mode 100644index 0000000000..296815ddf8--- /dev/null+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/citation_links.py@@ -0,0 +1,45 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""Parse report citation destinations with CommonMark's balanced-link rules."""+from __future__ import annotations++import re+from collections.abc import Iterator+from dataclasses import dataclass++from markdown_it.helpers import parseLinkDestination++_PREFIX = re.compile(r"\[\[(?P<index>\d+)\]\]\(")+++@dataclass(frozen=True)+class CitationLink:+ index: str+ url: str+ start: int+ end: int+++def parse_citation(+ source: str, start: int = 0, *, full: bool = False+) -> CitationLink | None:+ """Return a citation's source span without changing its original bytes."""+ prefix = _PREFIX.match(source, start)+ if prefix is None:+ return None+ destination = parseLinkDestination(source, prefix.end(), len(source))+ if not destination.ok or not destination.str.startswith(("http://", "https://")):+ return None+ if destination.pos >= len(source) or source[destination.pos] != ")":+ return None+ end = destination.pos + 1+ if full and end != len(source):+ return None+ return CitationLink(prefix.group("index"), destination.str, start, end)+++def iter_citations(source: str) -> Iterator[CitationLink]:+ """Find citations while sharing the rewrite map's destination parser."""+ for prefix in _PREFIX.finditer(source):+ citation = parse_citation(source, prefix.start())+ if citation is not None:+ yield citationdiff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/conversion_utils.py b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/conversion_utils.pyindex 2264042161..9b31f5d545 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/conversion_utils.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/conversion_utils.py@@ -9,6 +9,8 @@ from urllib.parse import urlsplitimport unicodedata+from .citation_links import iter_citations+logger = logging.getLogger(__name__)TEXT_READ_ENCODINGS = ("utf-8-sig", "utf-8", "gb18030", "gbk")@@ -100,7 +102,6 @@ INDENTED_HTML_BLOCK_END_RE = re.compile()SENTENCE_END_RE = re.compile(r"[。!??!…]$")-CITATION_RE = re.compile(r"\[\[(\d+)\]\]\((https?://[^\s)]+(?:\([^\s)]+\)[^\s)]*)*)\)")CHECKED_CITATION_RE = re.compile(r"\[\s*checked_citation:\s*\d+\s*\](\[\[\d+\]\]\((?:[^()]|\([^()]*\))*\))")@@ -259,16 +260,19 @@ def replace_citations(text: str) -> str:- URLs are HTML-escaped for security- Removes whitespace before <sup class="citation"> tags"""- def _repl(match: re.Match[str]) -> str:- idx, url = match.group(1), match.group(2).strip()- safe_url = html.escape(url, quote=True)- return (+ parts: list[str] = []+ cursor = 0+ for citation in iter_citations(text):+ parts.append(text[cursor:citation.start])+ safe_url = html.escape(citation.url, quote=True)+ parts.append(f'<sup class="citation">'- f'<a href="{safe_url}" target="_blank" rel="noopener noreferrer">[{idx}]</a>'+ f'<a href="{safe_url}" target="_blank" rel="noopener noreferrer">[{citation.index}]</a>'f"</sup>")-- text = CITATION_RE.sub(_repl, text)+ cursor = citation.end+ parts.append(text[cursor:])+ text = "".join(parts)return re.sub(r'[ \t]+(<sup class="citation">)', r"\1", text)@@ -278,11 +282,19 @@ def strip_internal_citation_markers(text: str) -> str:def replace_citations_with_markdown_links(text: str) -> str:- def _repl(match: re.Match[str]) -> str:- idx, url = match.group(1), match.group(2).strip()- return rf"[\[{idx}\]]({url})"-- return CITATION_RE.sub(_repl, text)+ parts: list[str] = []+ cursor = 0+ for citation in iter_citations(text):+ parts.append(text[cursor:citation.start])+ # Keep the original destination syntax, including Markdown escapes.+ parts.append(+ text[citation.start:citation.end].replace(+ f"[[{citation.index}]]", rf"[\[{citation.index}\]]", 1+ )+ )+ cursor = citation.end+ parts.append(text[cursor:])+ return "".join(parts)def _is_pipe_table_delimiter_line(line: str) -> bool:diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/document_rewrite.py b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/document_rewrite.pyindex bc65967f75..266325d54e 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/document_rewrite.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/document_rewrite.py@@ -20,6 +20,7 @@ from typing import Iteratorfrom urllib.parse import quotefrom markdown_it import MarkdownIt+from markdown_it.common.utils import unescapeAllfrom jiuwenswarm.agents.harness.common.tools.deepresearch.path_safety import (is_direct_directory,@@ -29,7 +30,10 @@ from jiuwenswarm.agents.harness.common.tools.deepresearch_plugin.artifact_namingArtifactPaths,allocate_next_paths,)-+from jiuwenswarm.agents.harness.common.tools.deepresearch_plugin.citation_links import (+ iter_citations,+ parse_citation,+)from jiuwenswarm.agents.harness.common.tools.deepresearch_plugin.markdown_rewrite_map import (MarkdownRewriteMap,ProtectedAnchor,@@ -47,7 +51,6 @@ from jiuwenswarm.agents.harness.common.tools.deepresearch_plugin.markdown_rewritlogger = logging.getLogger(__name__)SAFE_ID_RE = re.compile(r"^(?:doc|rev)_[A-Za-z0-9_-]{1,128}$")-CITATION_RE = re.compile(r"\[\[(?P<index>\d+)\]\]\((?P<url>https?://[^\s)]+)\)")FORBIDDEN_OUTPUT_RE = re.compile(r"(?<![A-Za-z0-9+.-])[A-Za-z][A-Za-z0-9+.-]*://|"r"(?<![A-Za-z0-9+.-])(?:javascript|vbscript|data|mailto|tel|sms|urn):[ \t\r\n]*|"@@ -638,7 +641,8 @@ def _citation_index(or field_size(value) > CITATION_FIELD_MAX_BYTES):raise RewriteError("DOCUMENT_NOT_FOUND", "report citation data is invalid")- key = f"{reference_index}\0{url}"+ # Body destinations receive the same single CommonMark unescape pass.+ key = f"{reference_index}\0{unescapeAll(url)}"if source_id in by_id:raise RewriteError("DOCUMENT_NOT_FOUND", "report citation data is ambiguous")by_id[source_id] = item@@ -652,12 +656,12 @@ def _citation_occurrence_index(_, by_key = _citation_index(citations)boundary_table = Utf8BoundaryTable(markdown)ranges_by_key: dict[str, list[tuple[int, int]]] = {}- for match in CITATION_RE.finditer(markdown):- key = f"{match.group('index')}\0{match.group('url')}"+ for match in iter_citations(markdown):+ key = f"{match.index}\0{match.url}"ranges_by_key.setdefault(key, []).append((- boundary_table.codepoint_to_byte[match.start()],- boundary_table.codepoint_to_byte[match.end()],+ boundary_table.codepoint_to_byte[match.start],+ boundary_table.codepoint_to_byte[match.end],))@@ -746,8 +750,8 @@ def _slot_slice(slot: RewriteSlot, start: int, end: int) -> tuple[str, int, int]def _anchor_visible_text(anchor: ProtectedAnchor) -> str:if anchor.kind == "citation":- match = CITATION_RE.fullmatch(anchor.source)- return f"[{match.group('index')}]" if match else ""+ match = parse_citation(anchor.source, full=True)+ return f"[{match.index}]" if match else ""if anchor.kind == "hard_break":return "\n"if anchor.kind == "inline_code":@@ -988,7 +992,7 @@ def prepare_rewrite(for anchor in selected_anchors:if anchor.kind != "citation":continue- match = CITATION_RE.fullmatch(anchor.source)+ match = parse_citation(anchor.source, full=True)if match is not None:citation = citation_occurrences.get((anchor.start_byte, anchor.end_byte))if citation is not None:@@ -1408,10 +1412,10 @@ def _validate_affected_citations(for anchor in rewrite_map.units[index].protected:if anchor.kind != "citation":continue- match = CITATION_RE.fullmatch(anchor.source)+ match = parse_citation(anchor.source, full=True)if match is None:raise RewriteError("FORMAT_CONFLICT", "citation syntax changed")- result.append((match.group("index"), match.group("url")))+ result.append((match.index, match.url))return resultexpected = identities(original_map)diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/markdown_rewrite_map.py b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/markdown_rewrite_map.pyindex c1fba3400f..2d5c8bec81 100644--- a/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/markdown_rewrite_map.py+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/markdown_rewrite_map.py@@ -14,6 +14,9 @@ from markdown_it.common.entities import entitiesfrom markdown_it.common.utils import fromCodePoint, isValidEntityCodefrom markdown_it.token import Token+from jiuwenswarm.agents.harness.common.tools.deepresearch_plugin.citation_links import (+ parse_citation,+)from jiuwenswarm.agents.harness.common.tools.deepresearch_plugin.cjk_friendly_emphasis import (apply_cjk_friendly_rules,)@@ -280,7 +283,6 @@ _LIST_MARKER = re.compile(r"^[ \t]*(?P<marker>[-+*]|\d+[.)])(?=[ \t])")_LIST_PREFIX = re.compile(r"^[ \t]*(?:[-+*]|\d+[.)])[ \t]+")_HEADING_PREFIX = re.compile(r"^[ \t]{0,3}#{1,6}[ \t]+")_HEADING_SUFFIX = re.compile(r"(?:[ \t]+#+)?[ \t]*")-_CITATION = re.compile(r"\[\[(?P<number>\d+)\]\]\((?P<href>https?://[^\s)]+)\)")_INTERNAL_LINK_SOURCE = re.compile(r"(?<!!)\[[^\]\r\n]*\]\(\s*(?P<destination>#[^\s)>]+)"r"(?:\s+(?:\"[^\"\r\n]*\"|'[^'\r\n]*'|\([^\r\n)]*\)))?\s*\)"@@ -533,17 +535,17 @@ class _InlineScanner:href = link_open.attrGet("href") or ""link_start = self.cursor- citation = _CITATION.match(self.raw, self.cursor)+ citation = parse_citation(self.raw, self.cursor)if citation is not None:expected_citation = (close_index == index + 2and self.children[index + 1].type == "text"- and self.children[index + 1].content == f"[{citation.group('number')}]"- and href == citation.group("href")+ and self.children[index + 1].content == f"[{citation.index}]"+ and href == self.parser.normalizeLink(citation.url))if not expected_citation:raise _InlineTopologyError("citation disagrees with inline tokens")- self.cursor = citation.end()+ self.cursor = citation.endself._add_anchor("citation", link_start, self.cursor)return close_index + 1diff --git a/tests/unit_tests/agentserver/test_deepresearch_document_rewrite.py b/tests/unit_tests/agentserver/test_deepresearch_document_rewrite.pyindex 7996dfa017..30fca86dff 100644--- a/tests/unit_tests/agentserver/test_deepresearch_document_rewrite.py+++ b/tests/unit_tests/agentserver/test_deepresearch_document_rewrite.py@@ -1255,7 +1255,7 @@ def test_commit_preserves_multiple_citation_identity_order_count(tmp_path):)child = Path(result["report_path"]).read_text(encoding="utf-8")- assert rewrite_module.CITATION_RE.findall(child) == [+ assert [(item.index, item.url) for item in rewrite_module.iter_citations(child)] == [("1", "https://example.com/source"),("2", "https://second.example/source"),]@@ -3152,3 +3152,106 @@ def test_commit_rejects_trusted_workspace_root_swap_after_allocation(assert not (owned_old / "artifacts" / "report-v2.provenance.json").exists()++[email protected]("select_citations", [False, True])[email protected]("url", [+ "https://example.com/report(1).pdf",+ "https://example.com/report?a=1&b=2",+ r"https://example.com/report\(1\).pdf",+])+def test_rewrite_parenthesized_duplicate_citations_prepare_and_commit(+ tmp_path, select_citations, url+):+ body = f"English introduction.\n\nFirst [[1]]({url}) and second [[1]]({url}) end.\n"+ report, provenance = _write_document(tmp_path, body)+ citations = [+ {+ "id": source_id,+ "reference_index": 1,+ "url": url,+ "title": "PDF",+ "content": f"evidence {source_id}",+ "chunk": "source",+ "source": "web",+ }+ for source_id in (3, 4)+ ]+ _set_snapshot_citations(report, provenance, citations)+ original = report.read_bytes()+ raw = (+ body.split("\n\n")[1].rstrip("\n")+ if select_citations+ else "English introduction."+ )+ visible = "First [1] and second [1] end." if select_citations else raw+ prepared = _prepare(tmp_path, report, raw, visible=visible, action="polish")+ replacements = {+ slot["slot_id"]: slot["text"]+ .replace("English", "Clear English")+ .replace("First", "Initial")+ for unit in prepared["units"]+ for slot in unit["slots"]+ }+ result = commit_rewrite(+ context_token=prepared["context_token"],+ session_id="S1",+ structured_result=_structured_payload(prepared, replacements),+ )+ assert report.read_bytes() == original+ child = Path(result["report_path"]).read_text(encoding="utf-8")+ assert child.count(f"[[1]]({url})") == 2+ history = json.loads(Path(result["provenance_path"]).read_text())[+ "rewrite_history"+ ][-1]+ assert history["citation_ids"] == (["3", "4"] if select_citations else [])++[email protected]("destination", [+ "https://example.com/report(1).pdf",+ "https://example.com/report(a(b)).pdf",+ r"https://example.com/report\(1\).pdf",+ "<https://example.com/report(1).pdf>",+ "https://example.com/report?a=1&b=2",+])+def test_conversion_preserves_complete_citation_destination(destination, tmp_path):+ import html+ from markdown_it.helpers import parseLinkDestination++ raw = f"Before [[1]]({destination}) after [[2]](https://example.com/other)."+ url = parseLinkDestination(destination, 0, len(destination)).str+ expected = (+ 'Before<sup class="citation">'+ f'<a href="{html.escape(url, quote=True)}" target="_blank" '+ 'rel="noopener noreferrer">[1]</a></sup>'+ ' after<sup class="citation">'+ '<a href="https://example.com/other" target="_blank" '+ 'rel="noopener noreferrer">[2]</a></sup>.'+ )+ from html.parser import HTMLParser+ from jiuwenswarm.agents.harness.common.tools.deepresearch_plugin.convert_html_offline import convert_md_to_html++ assert conversion_utils.replace_citations(raw) == expected+ assert conversion_utils.preprocess_markdown_text(raw) == expected+ assert conversion_utils.replace_citations_with_markdown_links(raw) == (+ rf"Before [\[1\]]({destination}) after [\[2\]](https://example.com/other)."+ )++ class Links(HTMLParser):+ def __init__(self):+ super().__init__()+ self.hrefs = []++ def handle_starttag(self, tag, attrs):+ if tag == "a":+ self.hrefs.append(dict(attrs).get("href"))++ source = tmp_path / "report.md"+ output = tmp_path / "report.html"+ source.write_text(raw, encoding="utf-8")+ convert_md_to_html(source, output)+ rendered = output.read_text(encoding="utf-8")+ links = Links()+ links.feed(rendered)+ assert links.hrefs == [url, "https://example.com/other"]+ assert ".pdf)</sup>" not in rendereddiff --git a/tests/unit_tests/agentserver/test_deepresearch_tool_registration.py b/tests/unit_tests/agentserver/test_deepresearch_tool_registration.pyindex c1c270ccb4..54f94db8c7 100644--- a/tests/unit_tests/agentserver/test_deepresearch_tool_registration.py+++ b/tests/unit_tests/agentserver/test_deepresearch_tool_registration.py@@ -26,6 +26,13 @@ def test_formal_tools_honor_enable_flag(monkeypatch):assert dr.get_deepresearch_tools() == []+def test_stream_description_routes_skill_requests_through_skill_entry():+ description = dr.deepresearch_stream.card.description+ assert 'skill_tool(skill_name="deepresearch")' in description+ assert "deepresearch_execute" in description+ assert "not a substitute for loading the skill" in description++@pytest.mark.parametrize(("config", "expected"),[({}, True), ({"enable_deepresearch": True}, True),diff --git a/tests/unit_tests/agentserver/test_markdown_rewrite_map.py b/tests/unit_tests/agentserver/test_markdown_rewrite_map.pyindex 4e4e468dd6..85c44e477c 100644--- a/tests/unit_tests/agentserver/test_markdown_rewrite_map.py+++ b/tests/unit_tests/agentserver/test_markdown_rewrite_map.py@@ -1019,3 +1019,42 @@ def test_protocol_v2_fixture_uses_real_utf8_ranges_and_hashes():"full","partial",]+++ "destination",+ [+ "https://example.com/report(1).pdf",+ "https://example.com/report(a(b)).pdf",+ r"https://example.com/report\(1\).pdf",+ "https://example.com/report%281%29.pdf",+ "<https://example.com/report(1).pdf>",+ ],+)+def test_citation_parentheses_preserve_atomic_source_and_utf8_ranges(destination):+ citation = f"[[77]]({destination})"+ markdown = f"中文😀 English {citation} tail."+ result = rewrite_map_module.build_rewrite_map(markdown)+ assert not result.unsupported_regions+ assert len(result.units) == 1+ anchors = [a for a in result.units[0].protected if a.kind == "citation"]+ assert len(anchors) == 1+ assert anchors[0].source == citation+ raw = markdown.encode("utf-8")+ assert raw[anchors[0].start_byte : anchors[0].end_byte].decode() == citation+ assert (+ "".join(slot.text for slot in result.units[0].slots) == "中文😀 English tail."+ )+++ "source",+ [+ "[[77]](https://example.com/report(1.pdf)",+ "[[77]](https://example.com/report(1).pdf",+ "[[77]](javascript:alert(1))",+ '[[77]](https://example.com/report.pdf "title")',+ ],+)+def test_citation_parser_does_not_truncate_invalid_destinations(source):+ assert rewrite_map_module.parse_citation(source, full=True) is None