Skip to content

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): route large terminal results safely

hy59207061607fc5efdaf98
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py
index 56a85faf84..6128962747 100644
--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py
@@ -29,10 +29,6 @@ logger = logging.getLogger(__name__)
EXECUTION_SCHEMA = "openjiuwen.deepresearch.execute.v1"
_STATE_SCHEMA_VERSION = 1
_IN_FLIGHT_PHASES = frozenset({"starting", "resuming_feedback", "resuming_outline"})
-_DETAIL_KEYWORDS = re.compile(
- r"精简|简略|简要|简洁|概要|速览|专业|详细|深入|全面|详尽|完整",
- re.IGNORECASE,
-)
_QUESTION_NUMBER_PREFIX = re.compile(r"^\s*\d+[.、)]\s*")
_OUTLINE_SECTION = re.compile(r"^\s*###\s+P\d+\s*:\s*(.+?)\s*$", re.MULTILINE)
_JSON_FENCE = re.compile(r"^\s*```(?:json)?\s*(.*?)\s*```\s*$", re.DOTALL | re.IGNORECASE)
@@ -247,27 +243,6 @@ def _append_timing_window(
return next_state
-def _detail_interaction(state: dict[str, Any]) -> dict[str, Any]:
- return _result(
- "interaction",
- state,
- interaction={
- "query": "请选择研究报告的详略度",
- "return_json": True,
- "questions": [
- {
- "header": "报告详略度",
- "question": "您希望这份报告是通用版还是专业版?",
- "options": [
- {"label": "专业版(包含深度分析和详细评测)"},
- {"label": "通用版(仅包含核心结论和快速对比)"},
- ],
- }
- ],
- },
- )
-
-
def _decode_user_input(value: Any) -> Any:
if isinstance(value, str):
try:
@@ -300,25 +275,6 @@ def _terminal_interaction_status(value: Any) -> str:
return status if status in {"error", "cancelled"} else ""
-def _detail_query(query: str, user_input: Any) -> str:
- """Append the same detail requirement that the original Skill used."""
- response = _parse_response(user_input)
- if response.status == "skipped" or not response.answers:
- return query
- answer = response.answers[0]
- values = [*answer.selected_options]
- if answer.custom_input:
- values.append(answer.custom_input)
- selected = " ".join(values)
- if "专业版" in selected:
- requirement = "请生成专业版报告"
- elif "通用版" in selected or "精简版" in selected:
- requirement = "请生成精简版报告"
- else:
- requirement = selected.strip()
- return f"{query}({requirement})" if requirement else query
-
-
def _split_questions(raw: Any) -> list[str]:
candidates: list[Any]
if isinstance(raw, list):
@@ -941,39 +897,6 @@ async def deepresearch_execute(query: str, file_name: str = "") -> dict[str, Any
kind = phase if phase != "error" else "error"
return _result(kind, state, content="DeepResearch 任务已经结束。")
- if phase == "new" and not _DETAIL_KEYWORDS.search(str(state.get("query") or "")):
- state = _persist(context, state, "wait_report_detail")
- return _detail_interaction(state)
- if phase == "wait_report_detail":
- terminal_status = _terminal_interaction_status(context.user_input)
- if terminal_status:
- state = _persist(context, state, terminal_status)
- content = (
- "DeepResearch 任务已取消。"
- if terminal_status == "cancelled"
- else "报告详略度交互失败,DeepResearch 任务已停止。"
- )
- return _result(terminal_status, state, content=content)
- try:
- final_query = _detail_query(
- str(state.get("query") or query), context.user_input
- )
- except AskUserResponseError as exc:
- return _terminal_error(
- context,
- state,
- error_code="interaction_invalid",
- content=f"报告详略度结果无效:{exc}",
- )
- state = _persist(context, state, "starting", query=final_query)
- outcome = await _call_sdk(
- context,
- action="start",
- query=final_query,
- conversation_id=str(state.get("conversation_id") or ""),
- file_name=str(state.get("file_name") or file_name),
- )
- return await _handle_outcome(context, state, outcome, action="start")
if phase == "new":
state = _persist(context, state, "starting")
outcome = await _call_sdk(
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py
index 591a61d311..16c777ed74 100644
--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py
@@ -51,6 +51,13 @@ _SECTION_PROCESS_NODES = {
"collector_summary",
"sub_reporter",
}
+# Brief mode performs report-wide collection/review outside the per-section
+# process branch. Their ordinary ``content`` carries the evidence detail that
+# users expect in the expanded reasoning view, not final report prose.
+_BRIEF_PROCESS_CONTENT_NODES = {
+ "brief_info_collector",
+ "brief_evidence_reviewer",
+}
_FINAL_REPORT_NODES = {
"reporter",
"vlm_chart_generator",
@@ -72,6 +79,7 @@ MAX_SECTION_COUNT = 256
MAX_STATE_ENTRIES = 256
MAX_IDENTIFIER_CHARS = 1024
MAX_CHUNK_TEXT_CHARS = 1_048_576
+MAX_TERMINAL_RESULT_TEXT_CHARS = 16 * 1024 * 1024
MAX_ACCUMULATED_TEXT_CHARS = 1_048_576
MAX_JSON_DEPTH = 64
MAX_JSON_NODES = 16_384
@@ -155,7 +163,9 @@ def _validate_identifier(value: Any) -> str:
return text
-def _validate_json_shape(value: Any) -> int:
+def _validate_json_shape(
+ value: Any, *, max_text_chars: int = MAX_CHUNK_TEXT_CHARS
+) -> int:
"""Bound container traversal without recursion or copying caller data."""
stack: list[tuple[Any, int, bool]] = [(value, 0, False)]
active: set[int] = set()
@@ -170,10 +180,10 @@ def _validate_json_shape(value: Any) -> int:
if nodes > MAX_JSON_NODES or depth > MAX_JSON_DEPTH:
raise ValueError(ROUTER_LIMIT_ERROR)
if isinstance(current, str):
- if len(current) > MAX_CHUNK_TEXT_CHARS:
+ if len(current) > max_text_chars:
raise ValueError(ROUTER_LIMIT_ERROR)
text_chars += len(current)
- if text_chars > MAX_CHUNK_TEXT_CHARS:
+ if text_chars > max_text_chars:
raise ValueError(ROUTER_LIMIT_ERROR)
continue
if not isinstance(current, (dict, list, tuple)):
@@ -307,15 +317,24 @@ def _node_frames_for_chunk(
frames: list[dict] = []
if starts_node and event != "done":
frames.append(_node_reasoning(stage, agent, display, f"{display[0]}开始\n"))
- reasoning = _chunk_reasoning_content(chunk, content)
- if reasoning:
- frames.append(_node_reasoning(stage, agent, display, _as_text(reasoning)))
+ if agent in _BRIEF_PROCESS_CONTENT_NODES:
+ process_parts = _raw_process_parts(chunk, content, agent=agent)
+ else:
+ reasoning = _chunk_reasoning_content(chunk, content)
+ process_parts = [_as_text(reasoning)] if reasoning else []
+ for process_content in process_parts:
+ frames.append(_node_reasoning(stage, agent, display, process_content))
if completes_node:
frames.append(_node_reasoning(stage, agent, display, f"{display[0]}完成\n"))
return frames, starts_node, completes_node
-def _validate_router_input(chunk: dict, state: RouterState) -> None:
+def _validate_router_input(
+ chunk: dict,
+ state: RouterState,
+ *,
+ terminal_result_content: bool = False,
+) -> None:
if not isinstance(chunk, dict):
raise ValueError(ROUTER_INVALID_ERROR)
for key in ("agent", "section_idx", "message_id", "conversation_id"):
@@ -326,7 +345,9 @@ def _validate_router_input(chunk: dict, state: RouterState) -> None:
incoming_text_chars = 0
for key in ("content", "reasoning_content"):
value = chunk.get(key)
- if value is not None:
+ if value is not None and not (
+ terminal_result_content and key == "content"
+ ):
incoming_text_chars += _validate_json_shape(value)
if len(state.active_nodes) > MAX_STATE_ENTRIES:
raise ValueError(ROUTER_LIMIT_ERROR)
@@ -760,7 +781,17 @@ def _is_successful_workflow_end(chunk: dict, agent: str, event: str) -> bool:
or str(chunk.get("section_idx", "0")).strip() not in {"", "0"}
):
return False
- result = _as_json_object(chunk.get("content"))
+ content = chunk.get("content")
+ _validate_json_shape(
+ content,
+ max_text_chars=MAX_TERMINAL_RESULT_TEXT_CHARS,
+ )
+ result = _as_json_object(content)
+ if result is not None:
+ _validate_json_shape(
+ result,
+ max_text_chars=MAX_TERMINAL_RESULT_TEXT_CHARS,
+ )
return bool(
result
and isinstance(result.get("response_content"), str)
@@ -871,16 +902,30 @@ def route_chunk(chunk: dict, state: RouterState) -> list[dict]:
status marker(__deepsearch_status__)不在此处理(由 tool 主循环识别);interrupted marker
本体由 tool 主循环捕获后整块传给 build_interrupt_prompt(marker 参数)。
"""
- _validate_router_input(chunk, state)
+ if not isinstance(chunk, dict):
+ raise ValueError(ROUTER_INVALID_ERROR)
+ agent = _validate_identifier(chunk.get("agent", ""))
+ event = str(chunk.get("event", "")).strip()
+ section_idx = _validate_identifier(chunk.get("section_idx", "0")) or "0"
+ # The successful EndNode embeds the complete final result in ``content``.
+ # It is a workflow boundary, not process text for the frontend, so keep it
+ # under the terminal 16 MiB protocol bound without applying the 1 MiB
+ # process-display accumulator limit.
+ successful_workflow_end = _is_successful_workflow_end(chunk, agent, event)
+
+ _validate_router_input(
+ chunk,
+ state,
+ terminal_result_content=successful_workflow_end,
+ )
frames: list[dict] = []
if "__deepsearch_status__" in chunk:
return frames
+ if successful_workflow_end:
+ return start_final_report_processing(state)
- agent = _validate_identifier(chunk.get("agent", ""))
- event = str(chunk.get("event", "")).strip()
content = chunk.get("content", "")
message_type = str(chunk.get("message_type", "")).strip()
- section_idx = _validate_identifier(chunk.get("section_idx", "0")) or "0"
target_stage = 3 if agent in _SECTION_PROCESS_NODES and section_idx != "0" else _NODE_STAGE.get(agent)
key = _node_key(agent, section_idx)
display = NODE_DISPLAY_INFO.get(agent)
@@ -949,14 +994,6 @@ def route_chunk(chunk: dict, state: RouterState) -> list[dict]:
})
return frames
- # DeepSearch emits a successful top-level EndNode result before the runner's
- # terminal marker. It is the formal workflow boundary even when an SDK
- # version omits one of the parallel sub_reporter ``done`` events. Section
- # ``end``/``SECTION END`` frames are excluded by section_idx and content.
- if _is_successful_workflow_end(chunk, agent, event):
- frames.extend(start_final_report_processing(state))
- return frames
-
if not agent or agent in _SKIP_NODES:
return frames
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py
index bcbe97ff92..4a49a49559 100644
--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py
@@ -40,6 +40,7 @@ from jiuwenswarm.agents.harness.common.tools.deepresearch.path_safety import (
private_mode_is_compatible,
)
from jiuwenswarm.agents.harness.common.tools.deepresearch.stream_router import (
+ ROUTER_LIMIT_ERROR,
RouterState,
_format_outline_card_markdown,
advance_stage,
@@ -98,6 +99,7 @@ _REPORT_PUBLICATION_ATTEMPTS = 8
_CHILD_ERROR_CODE_PATTERN = re.compile(r"[A-Za-z][A-Za-z0-9_.-]{0,63}")
_PROTOCOL_IDENTIFIER_PATTERN = re.compile(r"[A-Za-z][A-Za-z0-9_.-]{0,127}")
+_LOG_CORRELATION_ID_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}")
_PROTOCOL_FIXED_KEYS = frozenset(
{
"__deepsearch_status__",
@@ -205,6 +207,14 @@ class _StreamProtocolInvalid(ValueError):
"""A child-controlled JSON structure cannot be forwarded safely."""
+def _safe_log_correlation_id(value: object) -> str:
+ """Return a bounded identifier for logs without echoing arbitrary input."""
+ candidate = str(value or "").strip()
+ if _LOG_CORRELATION_ID_PATTERN.fullmatch(candidate):
+ return candidate
+ return "-"
+
+
@dataclass(frozen=True, slots=True)
class _ProgressArtifact:
path: Path
@@ -841,9 +851,22 @@ async def _stop_deepresearch_process(proc: Any, timeout: float = 10.0) -> None:
await proc.wait()
-async def _iter_ndjson_lines(stream: Any, read_size: int = 64 * 1024):
+async def _iter_ndjson_lines(
+ stream: Any,
+ read_size: int = 64 * 1024,
+ *,
+ request_id: str = "",
+ session_id: str = "",
+ conversation_id: str = "",
+):
if stream is None:
return
+ correlation_ids = (
+ _safe_log_correlation_id(request_id),
+ _safe_log_correlation_id(session_id),
+ _safe_log_correlation_id(conversation_id),
+ )
+
read = getattr(stream, "read", None)
if not callable(read):
async for line in stream:
@@ -856,6 +879,14 @@ async def _iter_ndjson_lines(stream: Any, read_size: int = 64 * 1024):
break
pending.extend(chunk)
if len(pending) > DEEPRESEARCH_STDOUT_PENDING_MAX_BYTES:
+ logger.error(
+ "[deepresearch_stream] stdout frame limit exceeded "
+ "pending_bytes=%s limit_bytes=%s request_id=%s session_id=%s "
+ "conversation_id=%s",
+ len(pending),
+ DEEPRESEARCH_STDOUT_PENDING_MAX_BYTES,
+ *correlation_ids,
+ )
raise ValueError("deepresearch_stdout_limit_exceeded")
while True:
newline = pending.find(b"\n")
@@ -1877,6 +1908,22 @@ async def deepresearch_stream( # pylint: disable=huawei-too-many-arguments
except _StreamProtocolInvalid:
outcome = _stream_protocol_error()
except Exception as exc: # pylint: disable=broad-exception-caught
+ safe_reason = "unclassified"
+ if isinstance(exc, ValueError) and str(exc) in {
+ "deepresearch_stdout_limit_exceeded",
+ ROUTER_LIMIT_ERROR,
+ }:
+ safe_reason = str(exc)
+ logger.error(
+ "[deepresearch_stream] stream consume failed type=%s reason=%s "
+ "request_id=%s session_id=%s conversation_id=%s",
+ type(exc).__name__,
+ safe_reason,
+ _safe_log_correlation_id(route.get("request_id")),
+ _safe_log_correlation_id(session_id),
+ _safe_log_correlation_id(conversation_id),
+ exc_info=safe_reason != "unclassified",
+ )
outcome = {
"status": "error",
"error_code": "stream_failed",
@@ -2060,7 +2107,12 @@ async def _consume_stream(
result["timing"] = timing
return result
- async for raw in _iter_ndjson_lines(proc.stdout):
+ async for raw in _iter_ndjson_lines(
+ proc.stdout,
+ request_id=str(route.get("request_id") or ""),
+ session_id=str(route.get("session_id") or ""),
+ conversation_id=conversation_id,
+ ):
try:
line = raw.decode("utf-8").strip()
except UnicodeDecodeError:
diff --git a/tests/unit_tests/agentserver/test_deepresearch_execute_tool.py b/tests/unit_tests/agentserver/test_deepresearch_execute_tool.py
index 0eb07754e1..9dc18a1677 100644
--- a/tests/unit_tests/agentserver/test_deepresearch_execute_tool.py
+++ b/tests/unit_tests/agentserver/test_deepresearch_execute_tool.py
@@ -82,25 +82,6 @@ async def _invoke(
return result, saved
-async def test_missing_detail_interrupts_before_sdk_start():
- with patch.object(de, "_call_deepresearch_stream_impl", new=AsyncMock()) as stream:
- result, saved = await _invoke()
-
- assert result["kind"] == "interaction"
- assert result["interaction"]["questions"][0]["header"] == "报告详略度"
- assert result["interaction"]["questions"][0]["question"] == (
- "您希望这份报告是通用版还是专业版?"
- )
- assert result["interaction"]["questions"][0]["options"] == [
- {"label": "专业版(包含深度分析和详细评测)"},
- {"label": "通用版(仅包含核心结论和快速对比)"},
- ]
- assert result["state"]["phase"] == "wait_report_detail"
- assert saved[-1]["phase"] == "wait_report_detail"
- stream.assert_not_awaited()
-
-
@pytest.mark.asyncio
async def test_missing_query_fails_before_sdk_start():
with patch.object(de, "_call_deepresearch_stream_impl", new=AsyncMock()) as stream:
@@ -136,140 +117,19 @@ async def test_runner_error_preserves_bounded_subprocess_diagnostics():
@pytest.mark.asyncio
-async def test_detail_answer_starts_sdk_and_preserves_sdk_questions():
- state = {
- "schema_version": 1,
- "phase": "wait_report_detail",
- "query": "研究智能家电竞争格局",
- "file_name": "智能家电报告",
- "revision": 1,
- }
- questions = ["重点研究哪些品类?", "覆盖哪些市场?", "报告用于什么决策?"]
- outcome = {
- "status": "interrupted",
- "conversation_id": "conversation-1",
- "node_id": "feedback_handler",
- "marker": {"questions": "\n".join(f"{i}. {q}" for i, q in enumerate(questions, 1))},
- }
- model = _Model(_option_payload(*questions))
- answer = {
- "status": "answered",
- "answers": [{"selected_options": ["专业版(包含深度分析和详细评测)"]}],
- }
-
- with patch.object(
- de,
- "_call_deepresearch_stream_impl",
- new=AsyncMock(return_value=json.dumps(outcome, ensure_ascii=False)),
- ) as stream:
- result, saved = await _invoke(state=state, user_input=answer, model=model)
-
- assert [item["question"] for item in result["interaction"]["questions"]] == questions
- assert all(len(item["options"]) == 2 for item in result["interaction"]["questions"])
- assert result["state"]["phase"] == "wait_feedback"
- assert saved[0]["phase"] == "starting"
- stream.assert_awaited_once()
- assert stream.await_args.kwargs["action"] == "start"
- assert "请生成专业版报告" in stream.await_args.kwargs["query"]
-
-
- "selected_option",
- [
- "通用版(仅包含核心结论和快速对比)",
- "精简版(仅包含核心结论和快速对比)",
- ],
-)
-async def test_general_and_legacy_brief_detail_answers_map_to_brief_sdk_query(
- selected_option,
-):
- state = {
- "schema_version": 1,
- "phase": "wait_report_detail",
- "query": "研究智能家电竞争格局",
- "file_name": "智能家电报告",
- "revision": 1,
- }
+async def test_new_query_starts_sdk_directly():
completed = {
"status": "completed",
"conversation_id": "conversation-1",
"report_delivered": True,
"report_chars": 42,
}
- answer = {
- "status": "answered",
- "answers": [{"selected_options": [selected_option]}],
- }
-
with patch.object(
de,
"_call_deepresearch_stream_impl",
new=AsyncMock(return_value=json.dumps(completed, ensure_ascii=False)),
) as stream:
- result, _ = await _invoke(state=state, user_input=answer)
-
- assert result["kind"] == "completed"
- assert stream.await_args.kwargs["query"] == (
- "研究智能家电竞争格局(请生成精简版报告)"
- )
-
-
[email protected]("terminal_status", ["cancelled", "error"])
-async def test_terminal_report_detail_stops_without_starting_sdk(terminal_status):
- state = {
- "schema_version": 1,
- "phase": "wait_report_detail",
- "query": "研究智能家电竞争格局",
- "file_name": "智能家电报告",
- "revision": 1,
- }
-
- with patch.object(de, "_call_deepresearch_stream_impl", new=AsyncMock()) as stream:
- result, saved = await _invoke(
- state=state,
- user_input={"status": terminal_status, "answers": []},
- )
-
- assert result["kind"] == terminal_status
- assert saved[-1]["phase"] == terminal_status
- stream.assert_not_awaited()
-
-
-async def test_invalid_report_detail_stops_without_starting_sdk():
- state = {
- "schema_version": 1,
- "phase": "wait_report_detail",
- "query": "研究智能家电竞争格局",
- "file_name": "智能家电报告",
- "revision": 1,
- }
-
- with patch.object(de, "_call_deepresearch_stream_impl", new=AsyncMock()) as stream:
- result, saved = await _invoke(state=state, user_input="not-json")
-
- assert result["kind"] == "error"
- assert result["error_code"] == "interaction_invalid"
- assert saved[-1]["phase"] == "error"
- stream.assert_not_awaited()
-
-
-async def test_explicit_detail_query_starts_without_detail_card():
- completed = {
- "status": "completed",
- "conversation_id": "conversation-1",
- "report_delivered": True,
- "report_chars": 42,
- }
- with patch.object(
- de,
- "_call_deepresearch_stream_impl",
- new=AsyncMock(return_value=json.dumps(completed, ensure_ascii=False)),
- ) as stream:
- result, saved = await _invoke(query="请生成一份详细的智能家电竞争报告")
+ result, saved = await _invoke(query="研究智能家电竞争格局")
assert result["kind"] == "completed"
assert saved[0]["phase"] == "starting"
@@ -278,13 +138,6 @@ async def test_explicit_detail_query_starts_without_detail_card():
@pytest.mark.asyncio
async def test_invalid_option_generation_retries_then_keeps_free_text_questions():
- state = {
- "schema_version": 1,
- "phase": "wait_report_detail",
- "query": "研究智能家电竞争格局",
- "file_name": "智能家电报告",
- "revision": 1,
- }
questions = ["重点研究哪些品类?", "覆盖哪些市场?"]
outcome = {
"status": "interrupted",
@@ -293,14 +146,13 @@ async def test_invalid_option_generation_retries_then_keeps_free_text_questions(
"marker": {"questions": "\n".join(questions)},
}
model = _Model("not-json")
- answer = {"status": "skipped", "answers": []}
with patch.object(
de,
"_call_deepresearch_stream_impl",
new=AsyncMock(return_value=json.dumps(outcome, ensure_ascii=False)),
):
- result, _ = await _invoke(state=state, user_input=answer, model=model)
+ result, _ = await _invoke(model=model)
assert [item["question"] for item in result["interaction"]["questions"]] == questions
assert [item["options"] for item in result["interaction"]["questions"]] == [[], []]
@@ -518,7 +370,7 @@ async def test_feedback_answer_resumes_once_and_returns_direct_completion():
state = {
"schema_version": 1,
"phase": "wait_feedback",
- "query": "研究智能家电竞争格局(请生成专业版报告)",
+ "query": "研究智能家电竞争格局",
"file_name": "智能家电报告",
"conversation_id": "conversation-1",
"questions": ["重点研究哪些品类?"],
@@ -578,7 +430,7 @@ async def test_terminal_result_preserves_all_sdk_timing_windows():
state = {
"schema_version": 1,
"phase": "wait_outline",
- "query": "研究智能家电竞争格局(请生成专业版报告)",
+ "query": "研究智能家电竞争格局",
"file_name": "智能家电报告",
"conversation_id": "conversation-1",
"outline_presented": True,
@@ -798,18 +650,18 @@ def _rail_ctx(*, result, session=None, resume_input=None, tool_call_id="call-1")
@pytest.mark.asyncio
async def test_execution_rail_turns_interaction_result_into_native_interrupt():
- state = {"schema_version": 1, "phase": "wait_report_detail", "revision": 1}
+ state = {"schema_version": 1, "phase": "wait_feedback", "revision": 1}
result = {
"schema_version": de.EXECUTION_SCHEMA,
"kind": "interaction",
"interaction": {
- "query": "请选择",
+ "query": "请回答以下研究主题澄清问题",
"return_json": True,
"questions": [
{
- "header": "报告详略度",
- "question": "通用版还是专业版?",
- "options": [{"label": "专业版"}, {"label": "通用版"}],
+ "header": "研究方向反馈",
+ "question": "重点研究哪些品类?",
+ "options": [{"label": "方向A"}, {"label": "方向B"}],
}
],
},
@@ -884,53 +736,33 @@ async def test_same_outer_tool_call_survives_multiple_native_interrupts():
session = _Session()
rail = DeepResearchExecutionRail(model_provider=lambda: None)
- first = _rail_ctx(result=None, session=session)
- await rail.before_tool_call(first)
- first.inputs.tool_result = await de.deepresearch_execute._func(
- query="研究智能家电竞争格局",
- file_name="智能家电报告",
- )
- await rail.after_tool_call(first)
- assert isinstance(first.inputs.tool_result, ToolInterruptException)
- first_interaction_id = first.inputs.tool_result.tool_call.id
- assert first_interaction_id != "call-1"
- assert session.state[DEEPRESEARCH_EXECUTION_STATE_KEY]["call-1"]["phase"] == (
- "wait_report_detail"
- )
-
sdk_questions = {
"status": "interrupted",
"conversation_id": "conversation-1",
"node_id": "feedback_handler",
"marker": {"questions": "1. 重点研究哪些品类?"},
}
- detail_answer = {
- "status": "answered",
- "answers": [{"selected_options": ["专业版(包含深度分析和详细评测)"]}],
- }
- second = _rail_ctx(
- result=None,
- session=session,
- resume_input=detail_answer,
- tool_call_id=first_interaction_id,
- )
- await rail.before_tool_call(second)
+
+ first = _rail_ctx(result=None, session=session)
+ await rail.before_tool_call(first)
start_sdk = AsyncMock(return_value=json.dumps(sdk_questions, ensure_ascii=False))
with patch.object(
de,
"_call_deepresearch_stream_impl",
new=start_sdk,
):
- second.inputs.tool_result = await de.deepresearch_execute._func(
+ first.inputs.tool_result = await de.deepresearch_execute._func(
query="研究智能家电竞争格局",
file_name="智能家电报告",
)
- assert "请生成专业版报告" in start_sdk.await_args.kwargs["query"]
- await rail.after_tool_call(second)
- assert isinstance(second.inputs.tool_result, ToolInterruptException)
- second_interaction_id = second.inputs.tool_result.tool_call.id
- assert second_interaction_id not in {"call-1", first_interaction_id}
- assert second.inputs.tool_result.request.questions[0]["question"] == (
+ await rail.after_tool_call(first)
+ assert isinstance(first.inputs.tool_result, ToolInterruptException)
+ first_interaction_id = first.inputs.tool_result.tool_call.id
+ assert first_interaction_id != "call-1"
+ assert session.state[DEEPRESEARCH_EXECUTION_STATE_KEY]["call-1"]["phase"] == (
+ "wait_feedback"
+ )
+ assert first.inputs.tool_result.request.questions[0]["question"] == (
"重点研究哪些品类?"
)
@@ -949,25 +781,25 @@ async def test_same_outer_tool_call_survives_multiple_native_interrupts():
"report_delivered": True,
"report_chars": 321,
}
- third = _rail_ctx(
+ second = _rail_ctx(
result=None,
session=session,
resume_input=feedback_answer,
- tool_call_id=second_interaction_id,
+ tool_call_id=first_interaction_id,
)
- await rail.before_tool_call(third)
+ await rail.before_tool_call(second)
with patch.object(
de,
"_call_deepresearch_stream_impl",
new=AsyncMock(return_value=json.dumps(completed, ensure_ascii=False)),
):
- third.inputs.tool_result = await de.deepresearch_execute._func(
+ second.inputs.tool_result = await de.deepresearch_execute._func(
query="研究智能家电竞争格局",
file_name="智能家电报告",
)
- await rail.after_tool_call(third)
+ await rail.after_tool_call(second)
- assert third.force_finish_requests[0]["result_type"] == "answer"
- assert "321" in third.force_finish_requests[0]["output"]
+ assert second.force_finish_requests[0]["result_type"] == "answer"
+ assert "321" in second.force_finish_requests[0]["output"]
assert session.state[DEEPRESEARCH_EXECUTION_STATE_KEY] == {}
assert session.state[DEEPRESEARCH_EXECUTION_ALIAS_KEY] == {}
diff --git a/tests/unit_tests/agentserver/test_deepresearch_stream_router.py b/tests/unit_tests/agentserver/test_deepresearch_stream_router.py
index e57a56ddb9..6d27952a11 100644
--- a/tests/unit_tests/agentserver/test_deepresearch_stream_router.py
+++ b/tests/unit_tests/agentserver/test_deepresearch_stream_router.py
@@ -4,8 +4,12 @@ import json
import pytest
+from jiuwenswarm.agents.harness.common.tools.deepresearch import (
+ stream_router as stream_router_module,
+)
from jiuwenswarm.agents.harness.common.tools.deepresearch.stream_router import (
MAX_ACCUMULATED_TEXT_CHARS,
+ MAX_CHUNK_TEXT_CHARS,
RouterState,
advance_stage,
build_interrupt_prompt,
@@ -1187,6 +1191,49 @@ def test_skip_node_no_frame():
assert route_chunk({"agent": "end"}, state) == []
+def test_successful_end_result_bypasses_process_display_text_limit():
+ state = RouterState()
+ content = json.dumps({"response_content": "x" * MAX_CHUNK_TEXT_CHARS})
+
+ frames = route_chunk(
+ {
+ "agent": "end",
+ "event": "summary_response",
+ "section_idx": "0",
+ "content": content,
+ },
+ state,
+ )
+
+ assert len(content) > MAX_CHUNK_TEXT_CHARS
+ assert state.final_report_started is True
+ assert frames[-1] == {
+ "event_type": "task.start",
+ "task_id": "deepresearch_stage_4",
+ "task_content": "最终报告处理",
+ "stream_source_id": "deepresearch_final_report",
+ }
+
+
+def test_successful_end_result_keeps_json_shape_limit(monkeypatch):
+ monkeypatch.setattr(stream_router_module, "MAX_JSON_NODES", 4)
+ content = json.dumps({
+ "response_content": "# Final",
+ "metadata": [1, 2, 3],
+ })
+
+ with pytest.raises(ValueError, match="deepresearch_router_limit_exceeded"):
+ route_chunk(
+ {
+ "agent": "end",
+ "event": "summary_response",
+ "section_idx": "0",
+ "content": content,
+ },
+ RouterState(),
+ )
+
+
def test_unknown_node_no_frame():
state = RouterState()
assert route_chunk({"agent": "mystery_node", "content": "x"}, state) == []
@@ -1728,3 +1775,31 @@ def test_brief_research_nodes_are_visible_in_stage_three(agent):
_assert_stage(_stage_update(frames), 3)
assert any(frame["event_type"] == "chat.reasoning" for frame in frames)
+
+
+ ("agent", "start_message"),
+ [
+ ("brief_info_collector", "报告级资料检索开始\n"),
+ ("brief_evidence_reviewer", "证据审阅开始\n"),
+ ],
+)
+def test_brief_process_nodes_preserve_reasoning_and_content(agent, start_message):
+ frames = route_chunk(
+ {
+ "agent": agent,
+ "event": "message",
+ "reasoning_content": "正在判断证据覆盖范围",
+ "content": "证据详情:Redis 适合共享状态,SQLite 适合本地持久化。",
+ },
+ RouterState(current_stage=2),
+ )
+
+ reasoning = _process_reasoning(frames)
+ assert [frame["content"] for frame in reasoning] == [
+ start_message,
+ "正在判断证据覆盖范围",
+ "证据详情:Redis 适合共享状态,SQLite 适合本地持久化。",
+ ]
+ assert all(frame["task_id"] == "deepresearch_stage_3" for frame in reasoning)
+ assert all(frame["stream_source_id"] == f"dr_{agent}" for frame in reasoning)
diff --git a/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py b/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py
index 1a87379d3f..4af42b3e4b 100644
--- a/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py
+++ b/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py
@@ -14,6 +14,7 @@ import zipfile
from contextlib import ExitStack, asynccontextmanager
from pathlib import Path
from types import SimpleNamespace
+from typing import Any
from unittest.mock import AsyncMock, Mock, patch
import pytest
@@ -22,6 +23,9 @@ from jiuwenswarm.agents.harness.common.tools.deepresearch import tools as dt
from jiuwenswarm.agents.harness.common.tools.deepresearch.runtime import (
DeepResearchRuntimeError,
)
+from jiuwenswarm.agents.harness.common.tools.deepresearch.stream_router import (
+ MAX_CHUNK_TEXT_CHARS,
+)
from jiuwenswarm.common.local_env_config import (
bind_task_env_overlay,
clear_agent_env_ns,
@@ -560,11 +564,98 @@ async def test_repeated_cancellation_finishes_reap_and_untrack_before_reraising(
@pytest.mark.asyncio
-async def test_stdout_pending_buffer_is_bounded():
+async def test_stdout_pending_buffer_enforces_legacy_limit():
+ legacy_limit = 16 * 1024 * 1024
+ stream = _Reader(b"x" * (legacy_limit + 1))
+
+ with patch.object(dt.logger, "error") as error:
+ with pytest.raises(ValueError, match="deepresearch_stdout_limit_exceeded"):
+ async for _line in dt._iter_ndjson_lines(stream):
+ pass
+
+ assert error.call_args.args[1:3] == (
+ legacy_limit + 1,
+ legacy_limit,
+ )
+
+
+async def test_stdout_pending_buffer_is_bounded_and_logs_dimensions():
stream = _Reader(b"x" * (dt.DEEPRESEARCH_STDOUT_PENDING_MAX_BYTES + 1))
- with pytest.raises(ValueError, match="deepresearch_stdout_limit_exceeded"):
- async for _line in dt._iter_ndjson_lines(stream):
- pass
+ with patch.object(dt.logger, "error") as error:
+ with pytest.raises(ValueError, match="deepresearch_stdout_limit_exceeded"):
+ async for _line in dt._iter_ndjson_lines(stream):
+ pass
+
+ assert error.call_args.args[1:3] == (
+ dt.DEEPRESEARCH_STDOUT_PENDING_MAX_BYTES + 1,
+ dt.DEEPRESEARCH_STDOUT_PENDING_MAX_BYTES,
+ )
+
+
+ ("exception_message", "expected_reason", "expected_exc_info"),
+ [
+ (
+ "deepresearch_stdout_limit_exceeded",
+ "deepresearch_stdout_limit_exceeded",
+ True,
+ ),
+ (
+ "deepresearch_router_limit_exceeded",
+ "deepresearch_router_limit_exceeded",
+ True,
+ ),
+ ("exception-secret-that-must-not-be-logged", "unclassified", False),
+ ],
+)
+async def test_stream_failure_logs_safe_reason_and_correlation(
+ exception_message: str, expected_reason: str, expected_exc_info: bool
+):
+ proc = _Proc([])
+ route = {
+ "request_id": "REQ-123",
+ "channel_id": "CHANNEL-123",
+ "session_id": "SESSION-123",
+ "service_id": "default",
+ "agent_id": "default",
+ }
+ patches = _stream_patches(proc, route=route)
+
+ with ExitStack() as stack:
+ for item in patches:
+ stack.enter_context(item)
+ logged_error = stack.enter_context(patch.object(dt.logger, "error"))
+ stack.enter_context(
+ patch.object(
+ dt,
+ "_consume_stream",
+ new=AsyncMock(side_effect=ValueError(exception_message)),
+ )
+ )
+ outcome = json.loads(
+ await dt.deepresearch_stream._func(
+ action="resume",
+ conversation_id="CONVERSATION-123",
+ node="user_feedback_processor",
+ query="query-secret-that-must-not-be-logged",
+ )
+ )
+
+ assert outcome["error_code"] == "stream_failed"
+ assert outcome["error"] == "DeepResearch stream failed: ValueError"
+ assert logged_error.call_args.args[1:] == (
+ "ValueError",
+ expected_reason,
+ "REQ-123",
+ "SESSION-123",
+ "CONVERSATION-123",
+ )
+ assert logged_error.call_args.kwargs == {"exc_info": expected_exc_info}
+ logged_call = repr(logged_error.call_args)
+ assert "query-secret-that-must-not-be-logged" not in logged_call
+ assert "exception-secret-that-must-not-be-logged" not in logged_call
@pytest.mark.asyncio
@@ -1235,6 +1326,70 @@ async def test_completed_marker_accepts_formal_sdk_end_result_when_section_done_
}
+async def test_completed_marker_delivers_large_sdk_end_result(tmp_path: Path):
+ """Large final results are terminal artifacts, not process-display text."""
+ final_result = {
+ "response_content": "# Final",
+ "content": "x" * MAX_CHUNK_TEXT_CHARS,
+ }
+ end_content = json.dumps(final_result)
+ proc = _Proc(
+ [
+ json.dumps({"__deepsearch_status__": "started", "conversation_id": "C1"}),
+ json.dumps(
+ {
+ "agent": "end",
+ "section_idx": "0",
+ "event": "summary_response",
+ "content": end_content,
+ }
+ ),
+ json.dumps(
+ {
+ "__deepsearch_status__": "completed",
+ "conversation_id": "C1",
+ "final_result": final_result,
+ }
+ ),
+ ]
+ )
+ route = {
+ "request_id": "R1",
+ "channel_id": "CH1",
+ "session_id": "S1",
+ "service_id": "default",
+ "agent_id": "default",
+ }
+ patches = _stream_patches(proc, route=route)
+
+ with ExitStack() as stack:
+ for item in patches:
+ stack.enter_context(item)
+ stack.enter_context(
+ patch.object(dt, "WebSocketGatewayPushTransport", return_value=AsyncMock())
+ )
+ write_artifacts = stack.enter_context(
+ patch.object(
+ dt,
+ "_write_report_artifacts_stream",
+ new=AsyncMock(return_value={"md": str(tmp_path / "r.md")}),
+ )
+ )
+ outcome = json.loads(
+ await dt.deepresearch_stream._func(action="start", query="q")
+ )
+
+ assert len(end_content) > MAX_CHUNK_TEXT_CHARS
+ assert outcome == {
+ "status": "completed",
+ "conversation_id": "C1",
+ "report_delivered": True,
+ "report_chars": len("# Final"),
+ }
+ write_artifacts.assert_awaited_once()
+
+
@pytest.mark.asyncio
async def test_completed_marker_rejects_sdk_end_result_with_exception() -> None:
final_result = {
@@ -1971,6 +2126,57 @@ async def test_stage_three_remains_in_progress_when_research_fails():
)
+async def test_brief_process_content_reaches_gateway_reasoning():
+ detail = "证据详情:Redis 适合共享状态,SQLite 适合本地持久化。"
+ proc = _Proc(
+ [
+ json.dumps({"__deepsearch_status__": "started", "conversation_id": "C1"}),
+ json.dumps(
+ {
+ "agent": "brief_info_collector",
+ "event": "message",
+ "reasoning_content": "正在判断证据覆盖范围",
+ "content": detail,
+ },
+ ensure_ascii=False,
+ ),
+ json.dumps({"__deepsearch_status__": "error", "error": "failed"}),
+ ]
+ )
+ route = {
+ "request_id": "R",
+ "channel_id": "CH",
+ "session_id": "S",
+ "service_id": "default",
+ "agent_id": "default",
+ }
+ push = AsyncMock()
+ patches = _stream_patches(proc, route=route)
+ with ExitStack() as stack:
+ for item in patches:
+ stack.enter_context(item)
+ stack.enter_context(
+ patch.object(dt, "WebSocketGatewayPushTransport", return_value=push)
+ )
+ outcome = json.loads(
+ await dt.deepresearch_stream._func(action="start", query="q")
+ )
+
+ assert outcome["status"] == "error"
+ reasoning_payloads = [
+ call.args[0]["payload"]
+ for call in push.send_push.await_args_list
+ if call.args[0]["payload"].get("event_type") == "chat.reasoning"
+ ]
+ assert any(
+ payload.get("task_id") == "deepresearch_stage_3"
+ and payload.get("stream_source_id") == "dr_brief_info_collector"
+ and payload.get("content") == detail
+ for payload in reasoning_payloads
+ )
+
+
@pytest.mark.asyncio
async def test_large_completed_marker_above_streamreader_limit_is_supported(tmp_path: Path):
report = "R" * (70 * 1024)