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

深度研究精简模式【默认】 + 溯源推理优化

jdfff87c3022de760
diff --git a/jiuwenswarm/agents/harness/common/rails/deepresearch_execution_rail.py b/jiuwenswarm/agents/harness/common/rails/deepresearch_execution_rail.py
index d343a6fea3..d83d400100 100644
--- a/jiuwenswarm/agents/harness/common/rails/deepresearch_execution_rail.py
+++ b/jiuwenswarm/agents/harness/common/rails/deepresearch_execution_rail.py
@@ -148,6 +148,7 @@ class DeepResearchExecutionRail(DeepAgentRail):
session_id=extract_session_id_from_callback(ctx)
)
request_id = str((request_context or {}).get("request_id") or "").strip()
+ requested_report_type = (request_context or {}).get("requested_report_type")
token = bind_deepresearch_execution_context(
tool_call_id=workflow_id,
state=states.get(workflow_id),
@@ -156,6 +157,7 @@ class DeepResearchExecutionRail(DeepAgentRail):
save_state=save_state,
agent_id=self._agent_id,
request_id=request_id,
+ requested_report_type=requested_report_type,
)
tokens = ctx.extra.setdefault(_TOKENS_KEY, {})
tokens[tool_call_id] = token
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py
index 84884c77ff..4d5ce6a8d2 100644
--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/execution.py
@@ -4,6 +4,7 @@
from __future__ import annotations
+import asyncio
import json
import logging
import re
@@ -21,6 +22,7 @@ from jiuwenswarm.common.schema.ask_user import (
decode_user_input,
parse_ask_user_response,
)
+from jiuwenswarm.perf.context import DeepResearchReportType
from .stream_router import _format_outline_card_markdown
from .tools import _call_deepresearch_stream_impl
@@ -38,6 +40,7 @@ _FINISH_KEYWORDS = re.compile(r"(?:结束|完成|finish|\bend\b)", re.IGNORECASE
_OTHER_LABELS = frozenset({"其他", "Other"})
_OPTION_DESCRIPTION_MAX_CHARS = 50
_OPTIONS_MAX_TOKENS = 2048
+_OPTIONS_GENERATION_TIMEOUT_SECONDS = 60.0
_MAX_TIMING_WINDOWS = 8
_MAX_TIMING_SPANS = 128
@@ -53,6 +56,7 @@ class DeepResearchExecutionContext:
agent_id: str
save_state: Callable[[dict[str, Any]], None]
request_id: str = ""
+ requested_report_type: DeepResearchReportType | None = None
_execution_context: ContextVar[DeepResearchExecutionContext | None] = ContextVar(
@@ -69,6 +73,7 @@ def bind_deepresearch_execution_context(
save_state: Callable[[dict[str, Any]], None],
agent_id: str = "jiuwenswarm",
request_id: str = "",
+ requested_report_type: DeepResearchReportType | None = None,
) -> Token:
"""Bind state and resume input for one outer tool execution."""
return _execution_context.set(
@@ -80,6 +85,7 @@ def bind_deepresearch_execution_context(
agent_id=agent_id.strip() or "jiuwenswarm",
save_state=save_state,
request_id=request_id.strip(),
+ requested_report_type=requested_report_type,
)
)
@@ -439,42 +445,59 @@ async def _generate_options(
f"研究主题:{query}\n问题:{json.dumps(questions, ensure_ascii=False)}"
)
started = time.monotonic()
- for attempt in range(2):
- attempt_started = time.monotonic()
- try:
- response = await model.invoke(
- [{"role": "user", "content": prompt}],
- max_tokens=_OPTIONS_MAX_TOKENS,
- )
- _record_options_llm_perf(
- context,
- response=response,
- duration_ms=(time.monotonic() - attempt_started) * 1000,
- status="ok",
- )
- parsed = _parse_option_payload(_response_text(response), len(questions))
- if parsed is not None:
- logger.info(
- "[deepresearch_execute] option generation completed attempts=%d "
- "questions=%d duration_ms=%.1f",
- attempt + 1,
- len(questions),
- (time.monotonic() - started) * 1000,
- )
- return parsed
- except Exception as exc: # pylint: disable=broad-exception-caught
- _record_options_llm_perf(
- context,
- response=None,
- duration_ms=(time.monotonic() - attempt_started) * 1000,
- status="error",
- error_message=type(exc).__name__,
- )
- logger.warning(
- "[deepresearch_execute] option generation failed attempt=%d type=%s",
- attempt + 1,
- type(exc).__name__,
- )
+ attempt_started = started
+ try:
+ async with asyncio.timeout(_OPTIONS_GENERATION_TIMEOUT_SECONDS):
+ for attempt in range(2):
+ attempt_started = time.monotonic()
+ try:
+ response = await model.invoke(
+ [{"role": "user", "content": prompt}],
+ max_tokens=_OPTIONS_MAX_TOKENS,
+ )
+ _record_options_llm_perf(
+ context,
+ response=response,
+ duration_ms=(time.monotonic() - attempt_started) * 1000,
+ status="ok",
+ )
+ parsed = _parse_option_payload(_response_text(response), len(questions))
+ if parsed is not None:
+ logger.info(
+ "[deepresearch_execute] option generation completed attempts=%d "
+ "questions=%d duration_ms=%.1f",
+ attempt + 1,
+ len(questions),
+ (time.monotonic() - started) * 1000,
+ )
+ return parsed
+ except Exception as exc: # pylint: disable=broad-exception-caught
+ _record_options_llm_perf(
+ context,
+ response=None,
+ duration_ms=(time.monotonic() - attempt_started) * 1000,
+ status="error",
+ error_message=type(exc).__name__,
+ )
+ logger.warning(
+ "[deepresearch_execute] option generation failed attempt=%d type=%s",
+ attempt + 1,
+ type(exc).__name__,
+ )
+ except TimeoutError:
+ _record_options_llm_perf(
+ context,
+ response=None,
+ duration_ms=(time.monotonic() - attempt_started) * 1000,
+ status="error",
+ error_message="TimeoutError",
+ )
+ logger.warning(
+ "[deepresearch_execute] option generation timed out "
+ "questions=%d timeout_s=%.1f",
+ len(questions),
+ _OPTIONS_GENERATION_TIMEOUT_SECONDS,
+ )
logger.warning(
"[deepresearch_execute] option generation fell back to free text "
"questions=%d duration_ms=%.1f",
@@ -877,10 +900,16 @@ async def _handle_outcome(
description=(
"Execute one complete interactive DeepResearch workflow. It preserves "
"the standard detail, research-question, and outline review cards, "
- "resumes the same SDK conversation, and directly delivers the terminal result."
+ "resumes the same SDK conversation, and directly delivers the terminal result. "
+ "report_type: 'professional' for in-depth multi-section reports, 'brief' for "
+ "single-page concise reports; infer from the user's original wording."
),
)
-async def deepresearch_execute(query: str, file_name: str = "") -> dict[str, Any]:
+async def deepresearch_execute(
+ query: str,
+ file_name: str = "",
+ report_type: DeepResearchReportType | None = None,
+) -> dict[str, Any]:
"""Run the interactive workflow without Main Agent resume choreography."""
context = _execution_context.get()
if context is None:
@@ -899,6 +928,12 @@ async def deepresearch_execute(query: str, file_name: str = "") -> dict[str, Any
"query": query.strip(),
"file_name": file_name.strip(),
"conversation_id": str(uuid.uuid4()),
+ # report_type 优先取 Main Agent 工具入参(从用户原话识别);未传入时
+ # 回退执行上下文(params 通道),最终兜底 brief。归一后写入 state,
+ # resume 路径读此值不重新识别。deepresearch_stream:1918 据此写
+ # config REPORT_TYPE -> run_deepsearch.py -> SDK config.report_type,
+ # 触发 IntentRecognitionNode 锁死 report_type 字段,LLM 无决定权。
+ "requested_report_type": report_type or context.requested_report_type or "brief",
"revision": 0,
}
if not str(state.get("query") or "").strip():
@@ -931,6 +966,7 @@ async def deepresearch_execute(query: str, file_name: str = "") -> dict[str, Any
query=str(state.get("query") or query),
conversation_id=str(state.get("conversation_id") or ""),
file_name=str(state.get("file_name") or file_name),
+ report_type=state.get("requested_report_type"),
)
return await _handle_outcome(context, state, outcome, action="start")
if phase == "wait_feedback":
@@ -964,6 +1000,7 @@ async def deepresearch_execute(query: str, file_name: str = "") -> dict[str, Any
feedback=feedback,
interaction_result=interaction_result,
file_name=str(state.get("file_name") or file_name),
+ report_type=state.get("requested_report_type"),
)
return await _handle_outcome(
context,
@@ -1000,6 +1037,7 @@ async def deepresearch_execute(query: str, file_name: str = "") -> dict[str, Any
feedback=feedback,
interaction_result=interaction_result,
file_name=str(state.get("file_name") or file_name),
+ report_type=state.get("requested_report_type"),
)
return await _handle_outcome(
context,
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py
index 4d164b52df..8c6b556582 100644
--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/stream_router.py
@@ -28,6 +28,7 @@ NODE_DISPLAY_INFO: dict[str, tuple[str, str]] = {
"brief_reporter": ("精简报告整合", "生成核心摘要"),
"brief_mermaid_generator": ("图表生成", "生成精简报告图表"),
"brief_source_tracer": ("溯源校验", "核查精简报告引用"),
+ "brief_html_reporter": ("精简报告排版", "生成精简版 HTML 成品"),
"plan_reasoning": ("规划调研", "为当前章节制定分步信息采集计划"),
"collector_query_generation": ("生成检索词", "为当前章节生成搜索查询"),
"collector_info_retrieval": ("资料检索", "并行检索网页和资料"),
@@ -58,17 +59,23 @@ _BRIEF_PROCESS_CONTENT_NODES = {
"brief_info_collector",
"brief_evidence_reviewer",
}
-_FINAL_REPORT_NODES = {
+BRIEF_FINAL_REPORT_NODES = frozenset({
+ "brief_reporter",
+ "brief_mermaid_generator",
+ "brief_source_tracer",
+ "brief_html_reporter",
+})
+FINAL_REPORT_NODES = frozenset({
"reporter",
"vlm_chart_generator",
"source_tracer",
"source_tracer_infer",
- "brief_reporter",
- "brief_mermaid_generator",
- "brief_source_tracer",
-}
+ *BRIEF_FINAL_REPORT_NODES,
+})
-_CONTROL_PROCESS_VALUES = {"SUCCESS", "ALL END", "SECTION END"}
+_SUMMARY_RESPONSE_EVENT = "summary_response"
+_SECTION_SUCCESS_MARKER = "SUCCESS"
+_CONTROL_PROCESS_VALUES = {_SECTION_SUCCESS_MARKER, "ALL END", "SECTION END"}
_QUESTION_NODES = {"question_generator", "generate_questions"}
_MARKDOWN_ESCAPE_RE = re.compile(r"""([!"#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~])""")
_SAFE_HTTP_URL_RE = re.compile(r"https?://[^\x00-\x20\x7f<>]+", re.IGNORECASE)
@@ -107,9 +114,7 @@ _NODE_STAGE: dict[str, int] = {
"brief_info_collector": 3,
"brief_evidence_reviewer": 3,
"brief_sub_reporter": 3,
- "brief_reporter": 3,
- "brief_mermaid_generator": 3,
- "brief_source_tracer": 3,
+ **dict.fromkeys(FINAL_REPORT_NODES, 3),
}
@@ -759,11 +764,16 @@ def _all_sections_completed(state: RouterState) -> bool:
return bool(expected) and expected.issubset(state.completed_section_indices)
+def _can_start_final_report(state: RouterState, agent: str) -> bool:
+ """Brief is report-wide; only Professional waits for per-section completion."""
+ return agent in BRIEF_FINAL_REPORT_NODES or _all_sections_completed(state)
+
+
def _is_successful_workflow_end(chunk: dict, agent: str, event: str) -> bool:
"""Recognize the SDK EndNode result emitted after the workflow has finished."""
if (
agent != "end"
- or event != "summary_response"
+ or event != _SUMMARY_RESPONSE_EVENT
or str(chunk.get("section_idx", "0")).strip() not in {"", "0"}
):
return False
@@ -823,7 +833,7 @@ def _node_reasoning(
display: tuple[str, str],
content: str,
) -> dict:
- if agent not in _FINAL_REPORT_NODES:
+ if agent not in FINAL_REPORT_NODES:
return _stage_child_reasoning(stage, agent, display, content)
return {
"event_type": "chat.reasoning",
@@ -934,9 +944,9 @@ def route_chunk(chunk: dict, state: RouterState) -> list[dict]:
must_defer_final_report = (
display
and target_stage in {1, 2, 3}
- and agent in _FINAL_REPORT_NODES
+ and agent in FINAL_REPORT_NODES
and not state.final_report_started
- and not _all_sections_completed(state)
+ and not _can_start_final_report(state, agent)
)
if must_defer_final_report:
preflight_node_frames = _node_frames_for_chunk(
@@ -1022,11 +1032,17 @@ def route_chunk(chunk: dict, state: RouterState) -> list[dict]:
if event == "done" and not node_state["done"]:
node_state["done"] = True
frames.append(_section_reasoning(state, chunk, f"{display[0]}完成\n"))
- if agent == "sub_reporter" and section_idx not in state.completed_section_indices:
- state.completed_section_indices.add(section_idx)
- frames.append(_section_boundary(state, chunk, "task.complete"))
- if _all_sections_completed(state):
- start_final_report = True
+
+ section_succeeded = (
+ agent == "sub_reporter"
+ and event == _SUMMARY_RESPONSE_EVENT
+ and _text_field(content) == _SECTION_SUCCESS_MARKER
+ )
+ if section_succeeded and section_idx not in state.completed_section_indices:
+ state.completed_section_indices.add(section_idx)
+ frames.append(_section_boundary(state, chunk, "task.complete"))
+ if _all_sections_completed(state):
+ start_final_report = True
for process_content in process_parts:
frames.append(_section_reasoning(state, chunk, process_content))
@@ -1050,7 +1066,7 @@ def route_chunk(chunk: dict, state: RouterState) -> list[dict]:
return frames
if target_stage in {1, 2, 3}:
- if agent in _FINAL_REPORT_NODES and _all_sections_completed(state):
+ if agent in FINAL_REPORT_NODES and _can_start_final_report(state, agent):
frames.extend(start_final_report_processing(state))
node_frames, starts_node, completes_node = (
preflight_node_frames
@@ -1078,10 +1094,12 @@ def route_chunk(chunk: dict, state: RouterState) -> list[dict]:
state.active_nodes[key] = node_state
if completes_node:
node_state["done"] = True
- if agent in _FINAL_REPORT_NODES and not state.final_report_started:
+ if agent in FINAL_REPORT_NODES and not state.final_report_started:
_extend_pending_final_report_frames(state, node_frames)
else:
frames.extend(node_frames)
+ if agent == "brief_sub_reporter" and completes_node:
+ frames.extend(start_final_report_processing(state))
return frames
reasoning = _chunk_reasoning_content(chunk, content)
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py
index 263fcb0f52..e1ae941e58 100644
--- a/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch/tools.py
@@ -41,6 +41,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 (
+ FINAL_REPORT_NODES,
ROUTER_LIMIT_ERROR,
RouterState,
_format_outline_card_markdown,
@@ -78,6 +79,7 @@ from jiuwenswarm.common.utils import (
get_shared_agent_skills_dirs,
parse_shared_skills_dirs_raw,
)
+from jiuwenswarm.perf.context import DeepResearchReportType
from jiuwenswarm.server.gateway_push import WebSocketGatewayPushTransport
from jiuwenswarm.server.runtime.runtime_scope import RuntimeScopeKey
@@ -105,6 +107,7 @@ DEEPRESEARCH_ZIP_INPUT_MAX_BYTES = 192 * 1024 * 1024
_REPORT_PUBLICATION_ATTEMPTS = 8
_CHILD_ERROR_CODE_PATTERN = re.compile(r"[A-Za-z][A-Za-z0-9_.-]{0,63}")
+_CHILD_NUMERIC_ERROR_CODE_PATTERN = re.compile(r"[0-9]{6}", re.ASCII)
_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(
@@ -129,6 +132,7 @@ _PROTOCOL_FIXED_KEYS = frozenset(
"message_id",
"message_type",
"metadata",
+ "mime_type",
"name",
"node_id",
"outline",
@@ -141,6 +145,7 @@ _PROTOCOL_FIXED_KEYS = frozenset(
"report_chars",
"report_delivered",
"response_content",
+ "response_content_type",
"returncode",
"section_idx",
"section_title",
@@ -154,6 +159,15 @@ _PROTOCOL_FIXED_KEYS = frozenset(
"total_tasks",
}
)
+
+
+def _is_valid_child_error_code(value: object) -> bool:
+ return isinstance(value, str) and bool(
+ _CHILD_ERROR_CODE_PATTERN.fullmatch(value)
+ or _CHILD_NUMERIC_ERROR_CODE_PATTERN.fullmatch(value)
+ )
+
+
_PROTOCOL_STATUS_VALUES = frozenset(
{
"cancelled",
@@ -237,15 +251,6 @@ class _KeyedLock:
_REPORT_OUTPUT_LOCKS: dict[Path, _KeyedLock] = {}
_REPORT_OUTPUT_LOCKS_GUARD = threading.Lock()
-_FINAL_PIPELINE_NODES = frozenset({
- "reporter",
- "vlm_chart_generator",
- "source_tracer",
- "source_tracer_infer",
- "brief_reporter",
- "brief_mermaid_generator",
- "brief_source_tracer",
-})
_TIMED_SDK_NODES = frozenset({
"intent_recognition",
"generate_questions",
@@ -679,7 +684,9 @@ def _is_protocol_control_value(key: str, value: str) -> bool:
if key in {"__deepsearch_status__", "status", "current_task"}:
return value in _PROTOCOL_STATUS_VALUES
if key == "error_code":
- return bool(_CHILD_ERROR_CODE_PATTERN.fullmatch(value))
+ return _is_valid_child_error_code(value)
+ if key in {"mime_type", "response_content_type"}:
+ return value in {"text/markdown", "text/html"}
if key in {
"agent",
"event",
@@ -797,9 +804,7 @@ def _sanitize_terminal_outcome(
return sanitized
error_code = sanitized.get("error_code")
- if not isinstance(error_code, str) or not _CHILD_ERROR_CODE_PATTERN.fullmatch(
- error_code
- ):
+ if not _is_valid_child_error_code(error_code):
error_code = "workflow_error"
sanitized["error_code"] = error_code
sanitized["error"] = _bounded_diagnostic(
@@ -1685,6 +1690,23 @@ def _normalize_citation_artifacts(value: object) -> dict[str, str]:
return normalized
+def _normalize_response_content_type(
+ final_result: dict[str, Any],
+) -> str | None:
+ """Classify the final body without guessing from its contents."""
+ value = final_result.get("response_content_type")
+ if value is None or value == "":
+ return "text/markdown"
+ if not isinstance(value, str):
+ return None
+ normalized = value.strip().lower()
+ if not normalized:
+ return "text/markdown"
+ if normalized in {"text/markdown", "text/html"}:
+ return normalized
+ return None
+
+
def _build_related_artifact_bundle(
value: object, markdown_index: int
) -> dict[str, object] | None:
@@ -1738,7 +1760,7 @@ def _report_output_lock(output_dir: Path):
def _has_completed_final_pipeline_node(state: RouterState) -> bool:
return any(
isinstance(node_state, dict)
- and node_state.get("agent_name") in _FINAL_PIPELINE_NODES
+ and node_state.get("agent_name") in FINAL_REPORT_NODES
and node_state.get("done") is True
for node_state in state.active_nodes.values()
)
@@ -1771,9 +1793,19 @@ async def deepresearch_stream( # pylint: disable=huawei-too-many-arguments
node: str = "",
file_name: str = "",
interaction_result: str = "",
+ report_type: DeepResearchReportType | None = None,
) -> str:
skill_started_ns = time.monotonic_ns()
route = _get_route()
+ if report_type is not None and report_type not in {"professional", "brief"}:
+ return json.dumps(
+ {
+ "status": "error",
+ "error_code": "report_type_invalid",
+ "error": "report_type must be one of: professional, brief",
+ },
+ ensure_ascii=False,
+ )
try:
python_bin = resolve_python_executable()
except DeepResearchRuntimeError as exc:
@@ -1883,6 +1915,8 @@ async def deepresearch_stream( # pylint: disable=huawei-too-many-arguments
service_id=str(route.get("service_id") or "default"),
agent_id=str(route.get("agent_id") or "default"),
)
+ if report_type is not None:
+ config["REPORT_TYPE"] = report_type
child_env = _build_deepresearch_child_env(
interactive_ask=True,
service_id=str(route.get("service_id") or "default"),
@@ -2177,9 +2211,10 @@ async def _consume_stream(
}
first_sdk_node_ns: int | None = None
report_delivery_settled = False
+ seen_started = False
- async def send_final_report_progress() -> None:
- if not state.final_report_started or report_delivery_settled:
+ async def send_processing_progress() -> None:
+ if not seen_started or report_delivery_settled:
return
await send(
{
@@ -2216,7 +2251,7 @@ async def _consume_stream(
session_id=str(route.get("session_id") or ""),
conversation_id=conversation_id,
),
- send_final_report_progress,
+ send_processing_progress,
):
try:
line = raw.decode("utf-8").strip()
@@ -2248,6 +2283,7 @@ async def _consume_stream(
if is_timed_node and chunk.get("event") != "done":
first_sdk_node_ns = time.monotonic_ns()
if status_value in {"started", "resuming"}:
+ seen_started = True
outcome_cid = str(chunk.get("conversation_id") or outcome_cid)
stage = 1
if action == "resume" and node == "outline_interaction":
@@ -2346,6 +2382,9 @@ async def _consume_stream(
"error_code": "empty_report",
"error": "completed marker missing final_result.response_content",
}, chunk)
+ response_content_type = _normalize_response_content_type(final_result)
+ if response_content_type is None:
+ return attach_terminal_timing(_stream_protocol_error(), chunk)
if not state.final_report_started:
# dev-stable may deliberately finish with a degraded section and
# still run the final report pipeline. Flush that observed
@@ -2372,18 +2411,41 @@ async def _consume_stream(
"status": "error",
"conversation_id": chunk.get("conversation_id", outcome_cid),
"error_code": "report_file_delivery_failed",
- "error": "Markdown report file route is unavailable",
+ "error": "Report file route is unavailable",
}, chunk)
+ html_style_status = None
+ html_style_phase = None
+ html_style_reason_code = None
try:
- artifact_result = await _await_with_periodic_progress(
- _write_report_artifacts_stream(
- final_result,
- file_name,
- str(chunk.get("conversation_id") or outcome_cid),
- _normalize_citation_artifacts(chunk),
- ),
- send_final_report_progress,
- )
+ if response_content_type == "text/html":
+ primary_path = await _await_with_periodic_progress(
+ _write_report_html(response_content, file_name),
+ send_processing_progress,
+ )
+ artifacts = {"html": primary_path}
+ else:
+ artifact_result = await _await_with_periodic_progress(
+ _write_report_artifacts_stream(
+ final_result,
+ file_name,
+ str(chunk.get("conversation_id") or outcome_cid),
+ _normalize_citation_artifacts(chunk),
+ ),
+ send_processing_progress,
+ )
+ if isinstance(artifact_result, tuple) and len(artifact_result) == 4:
+ (
+ artifacts,
+ html_style_status,
+ html_style_phase,
+ html_style_reason_code,
+ ) = artifact_result
+ elif isinstance(artifact_result, tuple):
+ artifacts, html_style_status = artifact_result
+ else:
+ # Preserve compatibility with private test doubles and older callers.
+ artifacts = artifact_result
+ primary_path = artifacts.get("md", "")
except Exception as exc: # pylint: disable=broad-exception-caught
return attach_terminal_timing({
"status": "error",
@@ -2391,34 +2453,29 @@ async def _consume_stream(
"error_code": "report_file_write_failed",
"error": type(exc).__name__,
}, chunk)
- html_style_phase = None
- html_style_reason_code = None
- if isinstance(artifact_result, tuple) and len(artifact_result) == 4:
- (
- artifacts,
- html_style_status,
- html_style_phase,
- html_style_reason_code,
- ) = artifact_result
- elif isinstance(artifact_result, tuple):
- artifacts, html_style_status = artifact_result
- else:
- # Preserve compatibility with private test doubles and older callers.
- artifacts = artifact_result
- html_style_status = None
+ artifact_mime_types = {
+ "md": "text/markdown",
+ "html": "text/html",
+ }
files = [
- {"path": value, "name": Path(value).name}
- for value in artifacts.values()
+ {
+ "path": value,
+ "name": Path(value).name,
+ "mime_type": artifact_mime_types.get(key),
+ }
+ for key, value in artifacts.items()
+ if key in artifact_mime_types
]
file_payload: dict[str, Any] = {
"event_type": "chat.file",
"files": files,
}
- markdown_index = list(artifacts).index("md")
- bundle = _build_related_artifact_bundle(chunk, markdown_index)
file_metadata: dict[str, Any] = {}
- if bundle:
- file_metadata["artifactBundle"] = bundle
+ if response_content_type == "text/markdown":
+ markdown_index = list(artifacts).index("md")
+ bundle = _build_related_artifact_bundle(chunk, markdown_index)
+ if bundle:
+ file_metadata["artifactBundle"] = bundle
if html_style_status in {"applied", "fallback"}:
file_metadata["htmlStyleStatus"] = html_style_status
if (
@@ -2436,7 +2493,7 @@ async def _consume_stream(
"conversation_id": chunk.get("conversation_id", outcome_cid),
"error_code": "report_file_delivery_failed",
"error": "Report files could not be delivered",
- "report_path": artifacts.get("md", ""),
+ "report_path": primary_path,
}, chunk)
report_delivery_settled = True
for payload in advance_stage(state, 4, complete=True):
@@ -2498,6 +2555,64 @@ async def _consume_stream(
return outcome
+async def _write_report_html(response_content: str, file_name: str) -> str:
+ return await asyncio.to_thread(
+ _write_report_html_sync,
+ response_content,
+ file_name,
+ )
+
+
+def _write_report_html_sync(response_content: str, file_name: str) -> str:
+ """Publish one immutable native HTML artifact with bounded collision retries."""
+ from jiuwenswarm.agents.harness.common.tools.deepresearch_plugin.artifact_naming import (
+ allocate_initial_html_path,
+ )
+
+ if not isinstance(response_content, str) or not response_content:
+ raise ValueError("native HTML report content is empty")
+ output_dir = _get_effective_request_output_dir()
+ output_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
+ payload = response_content.encode("utf-8")
+ for _ in range(_REPORT_PUBLICATION_ATTEMPTS):
+ with _report_output_lock(output_dir):
+ root_fd, root_identity = _open_output_root(output_dir)
+ path: Path | None = None
+ published_identity: tuple[int, int] | None = None
+ try:
+ path = allocate_initial_html_path(output_dir, file_name)
+ _verify_output_root(output_dir, root_identity)
+ try:
+ published_identity = _exclusive_write_at(
+ root_fd,
+ path.name,
+ payload,
+ output_dir=output_dir,
+ )
+ except FileExistsError as exc:
+ raise _ReportPublicationCollision() from exc
+ if root_fd is not None:
+ os.fsync(root_fd)
+ _verify_output_root(output_dir, root_identity)
+ return str(path)
+ except _ReportPublicationCollision:
+ continue
+ except BaseException:
+ if path is not None and published_identity is not None:
+ _cleanup_owned_output(
+ root_fd,
+ path.name,
+ published_identity,
+ False,
+ output_dir=output_dir,
+ )
+ raise
+ finally:
+ if root_fd is not None:
+ os.close(root_fd)
+ raise FileExistsError("report publication attempts exhausted")
+
+
def _write_report_markdown(
final_result: dict[str, Any],
file_name: str,
diff --git a/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/artifact_naming.py b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/artifact_naming.py
index 2532053ba9..1b0d614396 100644
--- a/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/artifact_naming.py
+++ b/jiuwenswarm/agents/harness/common/tools/deepresearch_plugin/artifact_naming.py
@@ -278,6 +278,29 @@ def allocate_initial_paths(output_dir: Path, requested_name: str) -> ArtifactPat
raise _invalid("artifact allocation attempts exhausted")
+def allocate_initial_html_path(output_dir: Path, requested_name: str) -> Path:
+ """Allocate one visible HTML path without reserving Markdown sidecars."""
+ if not isinstance(output_dir, Path):
+ raise _invalid("output_dir must be a Path")
+ if not isinstance(requested_name, str):
+ raise _invalid("requested_name must be a string")
+ requested_stem = requested_name
+ for suffix in (".html", ".md"):
+ if requested_stem.lower().endswith(suffix):
+ requested_stem = requested_stem[: -len(suffix)]
+ break
+ base_stem = _normalize_base_stem(requested_stem)
+ snapshot = _snapshot_directory_names(output_dir)
+ for ordinal in range(1, MAX_ALLOCATION_ATTEMPTS + 1):
+ candidate_stem = _base_stem_with_ordinal(base_stem, ordinal)
+ candidate = output_dir / f"{candidate_stem}-v1.html"
+ if len(candidate.name.encode("utf-8")) > MAX_FILENAME_BYTES:
+ raise _invalid("artifact filename exceeds the byte limit")
+ if _conservative_name_key(candidate.name) not in snapshot.occupied_keys:
+ return candidate
+ raise _invalid("artifact allocation attempts exhausted")
+
+
def _require_document_id(provenance: dict) -> str:
if not isinstance(provenance, dict):
raise _invalid("provenance must be a dictionary")
diff --git a/jiuwenswarm/perf/context.py b/jiuwenswarm/perf/context.py
index eeab8d8ab4..91a111ef57 100644
--- a/jiuwenswarm/perf/context.py
+++ b/jiuwenswarm/perf/context.py
@@ -6,10 +6,12 @@ import logging
import threading
import time
from contextvars import ContextVar
-from typing import Any
+from typing import Any, Literal, TypeAlias
logger = logging.getLogger(__name__)
+DeepResearchReportType: TypeAlias = Literal["professional", "brief"]
+
_request_context: ContextVar[dict[str, Any] | None] = ContextVar("perf_request_context", default=None)
_request_wall_start: ContextVar[float | None] = ContextVar("perf_request_wall_start", default=None)
_current_llm_call_id: ContextVar[str | None] = ContextVar("perf_current_llm_call_id", default=None)
@@ -46,6 +48,8 @@ def set_request_context(
trace_id: str | None = None,
service_id: str | None = None,
agent_id: str | None = None,
+ requested_report_type: DeepResearchReportType | None = None,
+ begin_perf_collection: bool = True,
) -> dict[str, Any]:
started_at = time.time()
ctx: dict[str, Any] = {
@@ -57,23 +61,25 @@ def set_request_context(
"started_at": started_at,
"service_id": service_id,
"agent_id": agent_id,
+ "requested_report_type": requested_report_type,
}
_request_context.set(ctx)
_request_wall_start.set(started_at)
with _REGISTRY_LOCK:
_SESSION_ACTIVE[normalize_session_key(session_id)] = ctx
- from jiuwenswarm.perf.collector import get_perf_collector
-
- get_perf_collector().begin_request(
- session_id=session_id,
- request_id=request_id,
- channel_id=channel_id,
- mode=mode,
- trace_id=trace_id,
- started_at=started_at,
- service_id=service_id,
- agent_id=agent_id,
- )
+ if begin_perf_collection:
+ from jiuwenswarm.perf.collector import get_perf_collector
+
+ get_perf_collector().begin_request(
+ session_id=session_id,
+ request_id=request_id,
+ channel_id=channel_id,
+ mode=mode,
+ trace_id=trace_id,
+ started_at=started_at,
+ service_id=service_id,
+ agent_id=agent_id,
+ )
return ctx
diff --git a/jiuwenswarm/perf/interface_hooks.py b/jiuwenswarm/perf/interface_hooks.py
index 3dbaf894ee..d07b402a29 100644
--- a/jiuwenswarm/perf/interface_hooks.py
+++ b/jiuwenswarm/perf/interface_hooks.py
@@ -9,6 +9,7 @@ from typing import Any
from jiuwenswarm.perf.collector import get_perf_collector
from jiuwenswarm.perf.config import get_perf_summary_config
from jiuwenswarm.perf.context import (
+ DeepResearchReportType,
clear_request_context,
mark_first_answer_latency,
mark_first_byte_latency,
@@ -107,18 +108,18 @@ def set_perf_summary_context(
mode: str = "agent.plan",
service_id: str | None = None,
agent_id: str | None = None,
+ requested_report_type: DeepResearchReportType | None = None,
) -> None:
"""Bind perf request context at parent-agent request entry.
- Always begins the collector request (even if ``rail`` is None). When a
- RequestSummaryRail is present, also bind on the rail instance so LLM/tool
- hooks running on DeepAgent's interaction-round Task can resolve request_id
- without relying on ContextVar inheritance.
+ Always binds the execution request context, even when performance summaries
+ are disabled. When collection is enabled, it also begins the collector
+ request and binds a RequestSummaryRail so interaction-round hooks can resolve
+ request_id without relying on ContextVar inheritance.
"""
def _setup() -> None:
- if not get_perf_summary_config().enabled:
- return
+ perf_enabled = get_perf_summary_config().enabled
ctx = set_request_context(
session_id=session_id,
request_id=request_id,
@@ -126,7 +127,11 @@ def set_perf_summary_context(
mode=mode,
service_id=service_id,
agent_id=agent_id,
+ requested_report_type=requested_report_type,
+ begin_perf_collection=perf_enabled,
)
+ if not perf_enabled:
+ return
bind = getattr(rail, "bind_request_context", None)
if callable(bind):
bind(ctx)
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
index e71e49dd5f..92fd264333 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py
@@ -28,7 +28,7 @@ from contextvars import ContextVar, Token
from dataclasses import dataclass, replace
from pathlib import Path
from shutil import which
-from typing import TYPE_CHECKING, Any, AsyncIterator, Callable, List, Optional, Tuple
+from typing import TYPE_CHECKING, Any, AsyncIterator, Callable, List, Optional, Tuple, cast
from urllib.parse import quote_plus
import yaml
@@ -366,7 +366,10 @@ from jiuwenswarm.server.runtime.agent_adapter.evolution_slash import (
handle_evolution_slash_command,
)
from jiuwenswarm.server.runtime.agent_adapter import evolution_version as evolution_version_ctl
-from jiuwenswarm.server.utils.stream_utils import parse_ask_user_question_payload
+from jiuwenswarm.server.utils.stream_utils import (
+ build_tool_result_payload,
+ parse_ask_user_question_payload,
+)
from jiuwenswarm.edition import is_enterprise
from jiuwenswarm.common.local_env_config import (
bind_agent_env_ns,
@@ -488,6 +491,7 @@ from jiuwenswarm.common.mcp_config import (
validate_office_claw_mcp_config,
)
from jiuwenswarm.common.mcp_call_timeout_patch import apply_mcp_call_timeout_patch
+from jiuwenswarm.perf.context import DeepResearchReportType
from jiuwenswarm.perf.interface_hooks import (
clear_perf_summary_context,
finalize_perf_summary_request,
@@ -592,6 +596,22 @@ from jiuwenswarm.dotenv_early import load_dotenv_runtime
load_dotenv_runtime(dotenv_path=get_env_file(), override=True)
reset_free_search_runtime_flags()
+
+_DEEPRESEARCH_REPORT_TYPES = frozenset({"professional", "brief"})
+_INVALID_DEEPRESEARCH_REPORT_TYPE_MESSAGE = (
+ "params.report_type must be one of: professional, brief"
+)
+
+
+def _extract_requested_report_type(request: AgentRequest) -> DeepResearchReportType | None:
+ """Return the strict request-scoped report type; metadata is not trusted."""
+ params = request.params if isinstance(request.params, dict) else {}
+ if "report_type" not in params:
+ return None
+ value = params["report_type"]
+ if not isinstance(value, str) or value not in _DEEPRESEARCH_REPORT_TYPES:
+ raise ValueError(_INVALID_DEEPRESEARCH_REPORT_TYPE_MESSAGE)
+ return cast(DeepResearchReportType, value)
TodoModifyTool = CompatibleTodoModifyTool
install_todo_modify_compat_patch()
install_evolution_rail_kwargs_compat()
@@ -7967,6 +7987,7 @@ class JiuWenSwarmDeepAdapter:
scope = RuntimeScopeKey.from_adapter(
self, session_id=route["session_id"]
)
+ output_dir = str(route.get("output_dir") or "").strip()
return {
"request_id": str(route.get("request_id") or ""),
"channel_id": str(route.get("channel_id") or ""),
@@ -7981,6 +8002,7 @@ class JiuWenSwarmDeepAdapter:
context = self._runtime_cron_tool_context
metadata = context.metadata if isinstance(context.metadata, dict) else {}
scope = RuntimeScopeKey.from_adapter(self, session_id=context.session_id)
+ request_workspace = metadata.get("workspace_dir") or metadata.get("project_dir")
return {
"request_id": str(metadata.get("request_id") or ""),
"channel_id": str(context.channel_id or ""),
@@ -9842,6 +9864,7 @@ class JiuWenSwarmDeepAdapter:
metadata: dict[str, Any] | None,
request_id: str | None,
mode: str | None,
+ workspace_dir: str | None = None,
project_dir: str | None = None,
params: dict[str, Any] | None = None,
) -> _RuntimeCronContextTokens:
@@ -9945,6 +9968,9 @@ class JiuWenSwarmDeepAdapter:
)
scope = RuntimeScopeKey.from_adapter(self, session_id=session_id)
+ request_workspace = workspace_dir or project_dir or normalized_metadata.get(
+ "project_dir"
+ )
try:
deepresearch_token = push_deepresearch_route(
request_id=request_id or "",
@@ -16417,6 +16443,17 @@ class JiuWenSwarmDeepAdapter:
metadata=request.metadata,
)
+ try:
+ requested_report_type = _extract_requested_report_type(request)
+ except ValueError as exc:
+ return AgentResponse(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ ok=False,
+ payload={"error_code": "invalid_request", "error": str(exc)},
+ metadata=request.metadata,
+ )
+
if not self._is_session_scoped_adapter:
# 提前绑定 LLM trace ContextVar,使 supervisor task(由
# _get_or_create_session_adapter → start_interaction →
@@ -16616,6 +16653,7 @@ class JiuWenSwarmDeepAdapter:
metadata=request.metadata,
request_id=request.request_id,
mode=mode,
+ workspace_dir=inputs.get("workspace_dir"),
project_dir=(request.params.get("project_dir") if isinstance(request.params, dict) else None),
params=request.params if isinstance(request.params, dict) else None,
)
@@ -16666,6 +16704,7 @@ class JiuWenSwarmDeepAdapter:
session_id=request.session_id or "",
request_id=request.request_id or "",
mode=mode,
+ requested_report_type=requested_report_type,
)
perf_context_initialized = True
except BaseException:
@@ -17046,6 +17085,22 @@ class JiuWenSwarmDeepAdapter:
Yields:
AgentResponseChunk 流式响应块
"""
+ try:
+ requested_report_type = _extract_requested_report_type(request)
+ except ValueError as exc:
+ yield AgentResponseChunk(
+ request_id=request.request_id,
+ channel_id=request.channel_id,
+ payload={
+ "event_type": "chat.error",
+ "error_code": "invalid_request",
+ "error": str(exc),
+ },
+ is_complete=True,
+ metadata=request.metadata or {},
+ )
+ return
+
# Start of this adapter's own share of the turn; reported on the
# "entering runner streaming" line so the pre-dispatch work is visible.
stream_impl_started_at = time.monotonic()
@@ -17221,9 +17276,7 @@ class JiuWenSwarmDeepAdapter:
"channel_id": cid or "",
"resource_id": extract_routing_triple(request.metadata, request.params)[1] or "",
"output_dir": self._deepresearch_artifact_output_dir(
- request.params.get("project_dir")
- if isinstance(request.params, dict)
- else None
+ inputs.get("workspace_dir") or inputs.get("project_dir")
),
}
@@ -17652,6 +17705,7 @@ class JiuWenSwarmDeepAdapter:
metadata=request.metadata,
request_id=request.request_id,
mode=mode,
+ workspace_dir=inputs.get("workspace_dir"),
project_dir=(request.params.get("project_dir") if isinstance(request.params, dict) else None),
params=request.params if isinstance(request.params, dict) else None,
)
@@ -17704,6 +17758,7 @@ class JiuWenSwarmDeepAdapter:
session_id=request.session_id or "",
request_id=request.request_id or "",
mode=mode,
+ requested_report_type=requested_report_type,
)
perf_context_initialized = True
initialization_complete = True
@@ -19194,39 +19249,7 @@ class JiuWenSwarmDeepAdapter:
if chunk_type == "tool_result":
if isinstance(payload, dict):
result_info = payload.get("tool_result", payload)
- result_payload = {
- "result": (
- result_info.get("result", str(result_info))
- if isinstance(result_info, dict)
- else str(result_info)
- ),
- }
- if isinstance(result_info, dict):
- result_payload["tool_name"] = result_info.get(
- "tool_name"
- ) or result_info.get("name")
- result_payload["tool_call_id"] = result_info.get(
- "tool_call_id"
- ) or result_info.get("toolCallId")
- raw_output = result_info.get("raw_output")
- if raw_output is None:
- raw_output = result_info.get("rawOutput")
- if raw_output is not None:
- result_payload["raw_output"] = raw_output
- for key in (
- "status",
- "success",
- "is_error",
- "error",
- "summary",
- "score_status",
- "score_build",
- "direct_display",
- "display_format",
- "mermaid",
- ):
- if key in result_info:
- result_payload[key] = result_info[key]
+ result_payload = build_tool_result_payload(result_info)
else:
result_payload = {"result": str(payload)}
return {
diff --git a/jiuwenswarm/server/utils/stream_utils.py b/jiuwenswarm/server/utils/stream_utils.py
index 62bd947107..76350622c2 100644
--- a/jiuwenswarm/server/utils/stream_utils.py
+++ b/jiuwenswarm/server/utils/stream_utils.py
@@ -4,12 +4,56 @@
from __future__ import annotations
+import json
import logging
from typing import Any
logger = logging.getLogger(__name__)
+def serialize_tool_result_value(result_info: Any) -> Any:
+ """Preserve explicit results and JSON-encode a missing-result envelope."""
+ if not isinstance(result_info, dict):
+ return str(result_info)
+ if "result" in result_info:
+ return result_info["result"]
+ return json.dumps(result_info, ensure_ascii=False, default=str)
+
+
+def build_tool_result_payload(result_info: Any) -> dict[str, Any]:
+ """Build the common ``chat.tool_result`` payload for every adapter path."""
+ result_payload = {"result": serialize_tool_result_value(result_info)}
+ if not isinstance(result_info, dict):
+ return result_payload
+
+ result_payload["tool_name"] = result_info.get("tool_name") or result_info.get("name")
+ result_payload["tool_call_id"] = result_info.get("tool_call_id") or result_info.get(
+ "toolCallId"
+ )
+
+ raw_output = result_info.get("raw_output")
+ if raw_output is None:
+ raw_output = result_info.get("rawOutput")
+ if raw_output is not None:
+ result_payload["raw_output"] = raw_output
+
+ for key in (
+ "status",
+ "success",
+ "is_error",
+ "error",
+ "summary",
+ "score_status",
+ "score_build",
+ "direct_display",
+ "display_format",
+ "mermaid",
+ ):
+ if key in result_info:
+ result_payload[key] = result_info[key]
+ return result_payload
+
+
def _propagate_stream_source_id(src_payload: Any) -> dict[str, Any]:
"""从上游 payload 提取 stream_source_id(skill_turbo 并发节点用它标识 source)。
@@ -370,38 +414,7 @@ def _parse_typed_chunk(chunk: Any, _has_streamed_content: bool) -> dict[str, Any
if chunk_type == "tool_result":
if isinstance(payload, dict):
result_info = payload.get("tool_result", payload)
- result_payload = {
- "result": (
- result_info.get("result", str(result_info))
- if isinstance(result_info, dict)
- else str(result_info)
- ),
- }
- if isinstance(result_info, dict):
- result_payload["tool_name"] = (
- result_info.get("tool_name") or result_info.get("name")
- )
- result_payload["tool_call_id"] = (
- result_info.get("tool_call_id") or result_info.get("toolCallId")
- )
- raw_output = result_info.get("raw_output")
- if raw_output is None:
- raw_output = result_info.get("rawOutput")
- if raw_output is not None:
- result_payload["raw_output"] = raw_output
- for key in (
- "success",
- "status",
- "is_error",
- "summary",
- "score_status",
- "score_build",
- "direct_display",
- "display_format",
- "mermaid",
- ):
- if key in result_info:
- result_payload[key] = result_info.get(key)
+ result_payload = build_tool_result_payload(result_info)
else:
result_payload = {"result": str(payload)}
return {
diff --git a/tests/unit_tests/agentserver/test_agentserver_acp.py b/tests/unit_tests/agentserver/test_agentserver_acp.py
index 8734ab40fe..957f0b4b8f 100644
--- a/tests/unit_tests/agentserver/test_agentserver_acp.py
+++ b/tests/unit_tests/agentserver/test_agentserver_acp.py
@@ -340,6 +340,49 @@ def test_interface_deep_parse_stream_chunk_preserves_tool_result_status():
}
+ "parser",
+ [
+ parse_stream_chunk,
+ getattr(interface_deep_module.JiuWenSwarmDeepAdapter, "_parse_stream_chunk"),
+ ],
+ ids=["shared_stream_parser", "deep_adapter_parser"],
+)
+def test_tool_result_without_result_uses_valid_json_fallback(parser):
+ raw_output = {
+ "kind": "error",
+ "status": "error",
+ "error_code": "workflow_error",
+ "returncode": 1,
+ }
+ parsed = parser(
+ types.SimpleNamespace(
+ type="tool_result",
+ payload={
+ "tool_result": {
+ "tool_call_id": "deepresearch-1",
+ "tool_name": "deepresearch_execute",
+ "status": "error",
+ "success": False,
+ "is_error": True,
+ "error": "section generation failed",
+ "raw_output": raw_output,
+ }
+ },
+ )
+ )
+
+ decoded_result = json.loads(parsed["result"])
+ assert decoded_result["status"] == "error"
+ assert decoded_result["success"] is False
+ assert decoded_result["is_error"] is True
+ assert decoded_result["raw_output"]["kind"] == "error"
+ assert parsed["status"] == "error"
+ assert parsed["is_error"] is True
+ assert parsed["error"] == "section generation failed"
+ assert parsed["raw_output"] == raw_output
+
+
def test_parse_stream_chunk_uses_raw_output_skill_tree_for_frontend():
raw_output = {
"success": True,
diff --git a/tests/unit_tests/agentserver/test_agentserver_modes.py b/tests/unit_tests/agentserver/test_agentserver_modes.py
index ec159a18f7..3070e1861f 100644
--- a/tests/unit_tests/agentserver/test_agentserver_modes.py
+++ b/tests/unit_tests/agentserver/test_agentserver_modes.py
@@ -115,6 +115,42 @@ def test_deep_adapter_builds_usage_reporting_task_planning_rail():
assert isinstance(rail, ConcurrentSafeTaskPlanningRail)
+async def test_invalid_deepresearch_report_type_fails_before_session_child_spawn():
+ adapter = object.__new__(interface_deep_module.JiuWenSwarmDeepAdapter)
+ adapter._is_session_scoped_adapter = False
+ adapter._get_or_create_session_adapter = AsyncMock(
+ side_effect=AssertionError("session child must not be spawned")
+ )
+ request = AgentRequest(
+ request_id="request-invalid-report-type",
+ channel_id="officeclaw",
+ session_id="session-invalid-report-type",
+ params={
+ "query": "research topic",
+ "mode": "agent",
+ "report_type": "Brief",
+ },
+ )
+
+ chunks = [
+ chunk
+ async for chunk in adapter.process_message_stream_impl(
+ request,
+ {"query": "research topic"},
+ )
+ ]
+
+ assert len(chunks) == 1
+ assert chunks[0].payload == {
+ "event_type": "chat.error",
+ "error_code": "invalid_request",
+ "error": "params.report_type must be one of: professional, brief",
+ }
+ assert chunks[0].is_complete is True
+ adapter._get_or_create_session_adapter.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_concurrent_task_planning_rail_uses_session_api_and_preserves_terminal_todos():
from openjiuwen.core.single_agent.rail.base import AgentCallbackContext
diff --git a/tests/unit_tests/agentserver/test_deep_adapter_interrupt.py b/tests/unit_tests/agentserver/test_deep_adapter_interrupt.py
index 86e30571a2..a55576f80d 100644
--- a/tests/unit_tests/agentserver/test_deep_adapter_interrupt.py
+++ b/tests/unit_tests/agentserver/test_deep_adapter_interrupt.py
@@ -915,6 +915,52 @@ def test_runtime_route_binds_adapter_artifact_output_dir(tmp_path: Path) -> None
adapter._reset_runtime_cron_context(tokens)
+def test_runtime_route_binds_request_workspace_as_artifact_output_dir(
+ tmp_path: Path,
+) -> None:
+ from jiuwenswarm.agents.harness.common.tools.deepresearch import tools as dt
+
+ agent_workspace = tmp_path / "agent-workspace"
+ request_workspace = tmp_path / "session-workspace"
+ adapter = _make_adapter(
+ _env_service_id="service-output",
+ _env_agent_id="agent-output",
+ _workspace_dir=str(agent_workspace),
+ )
+ tokens = adapter._bind_runtime_cron_context(
+ channel_id="officeclaw",
+ session_id="sess-output",
+ metadata={},
+ request_id="req-output",
+ mode="agent",
+ project_dir=str(request_workspace),
+ )
+ try:
+ assert dt._get_effective_request_output_dir() == request_workspace.resolve()
+ finally:
+ adapter._reset_runtime_cron_context(tokens)
+
+
+def test_progressive_deepresearch_context_keeps_request_workspace(
+ tmp_path: Path,
+) -> None:
+ request_workspace = tmp_path / "session-workspace"
+ adapter = _make_adapter(
+ _env_service_id="service-output",
+ _env_agent_id="agent-output",
+ )
+ adapter._current_request_route = {
+ "session_id": "sess-output",
+ "request_id": "req-output",
+ "channel_id": "officeclaw",
+ "output_dir": str(request_workspace),
+ }
+
+ assert adapter._get_deepresearch_tool_context()["output_dir"] == str(
+ request_workspace.resolve()
+ )
+
+
def test_runtime_route_keeps_artifact_leaf_lexical(tmp_path: Path) -> None:
agent_workspace = tmp_path / "agent-workspace"
outside = tmp_path / "outside"
diff --git a/tests/unit_tests/agentserver/test_deepresearch_artifact_naming.py b/tests/unit_tests/agentserver/test_deepresearch_artifact_naming.py
index 94442e3556..370792e3ce 100644
--- a/tests/unit_tests/agentserver/test_deepresearch_artifact_naming.py
+++ b/tests/unit_tests/agentserver/test_deepresearch_artifact_naming.py
@@ -169,6 +169,30 @@ def test_allocate_initial_paths_adds_same_title_suffix_for_markdown_and_sidecar_
)
[email protected]("requested_name", ["report", "report.md", "report.html"])
+def test_allocate_initial_html_path_strips_known_suffixes(requested_name, tmp_path):
+ api = _api()
+
+ allocated = api.allocate_initial_html_path(tmp_path, requested_name)
+
+ assert allocated.name == "report-v1.html"
+
+
+def test_allocate_initial_html_path_checks_html_collision_without_markdown_reservation(
+ tmp_path,
+):
+ api = _api()
+ (tmp_path / "report-v1.md").write_text("professional", encoding="utf-8")
+
+ first = api.allocate_initial_html_path(tmp_path, "report.md")
+ first.write_text("brief", encoding="utf-8")
+ second = api.allocate_initial_html_path(tmp_path, "report.html")
+
+ assert first.name == "report-v1.html"
+ assert second.name == "report-2-v1.html"
+ assert not (tmp_path / "report-2-v1.md").exists()
+
+
@pytest.mark.parametrize("path_field", ["markdown_path", "provenance_path", "final_result_path"])
def test_allocate_initial_paths_treats_hidden_atomic_target_as_collision(tmp_path, path_field):
api = _api()
diff --git a/tests/unit_tests/agentserver/test_deepresearch_execute_tool.py b/tests/unit_tests/agentserver/test_deepresearch_execute_tool.py
index b1ec15dff9..a38a291376 100644
--- a/tests/unit_tests/agentserver/test_deepresearch_execute_tool.py
+++ b/tests/unit_tests/agentserver/test_deepresearch_execute_tool.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import asyncio
import json
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock, patch
@@ -66,6 +67,7 @@ async def _invoke(
model=None,
query="研究智能家电竞争格局",
file_name="智能家电报告",
+ requested_report_type=None,
):
saved: list[dict] = []
token = de.bind_deepresearch_execution_context(
@@ -74,6 +76,7 @@ async def _invoke(
user_input=user_input,
model=model,
save_state=lambda value: saved.append(dict(value)),
+ requested_report_type=requested_report_type,
)
try:
result = await de.deepresearch_execute._func(query=query, file_name=file_name)
@@ -145,6 +148,25 @@ async def test_new_query_starts_sdk_directly():
stream.assert_awaited_once()
+async def test_new_query_persists_request_report_type_before_sdk_start():
+ completed = {
+ "status": "completed",
+ "conversation_id": "conversation-1",
+ "report_delivered": True,
+ }
+ with patch.object(
+ de,
+ "_call_deepresearch_stream_impl",
+ new=AsyncMock(return_value=json.dumps(completed, ensure_ascii=False)),
+ ) as stream:
+ _, saved = await _invoke(requested_report_type="brief")
+
+ assert saved[0]["phase"] == "starting"
+ assert saved[0]["requested_report_type"] == "brief"
+ assert stream.await_args.kwargs["report_type"] == "brief"
+
+
@pytest.mark.asyncio
async def test_invalid_option_generation_retries_then_keeps_free_text_questions():
questions = ["重点研究哪些品类?", "覆盖哪些市场?"]
@@ -168,6 +190,40 @@ async def test_invalid_option_generation_retries_then_keeps_free_text_questions(
assert model.invoke.await_count == 2
+async def test_option_generation_timeout_keeps_free_text_questions():
+ questions = ["重点研究哪些品类?", "覆盖哪些市场?"]
+ outcome = {
+ "status": "interrupted",
+ "conversation_id": "conversation-1",
+ "node_id": "feedback_handler",
+ "marker": {"questions": "\n".join(questions)},
+ }
+
+ async def never_returns(*_args, **_kwargs):
+ await asyncio.Event().wait()
+
+ model = SimpleNamespace(invoke=never_returns)
+ with (
+ patch.object(
+ de,
+ "_OPTIONS_GENERATION_TIMEOUT_SECONDS",
+ 0.01,
+ ),
+ patch.object(
+ de,
+ "_call_deepresearch_stream_impl",
+ new=AsyncMock(return_value=json.dumps(outcome, ensure_ascii=False)),
+ ),
+ ):
+ result, saved = await asyncio.wait_for(_invoke(model=model), timeout=0.2)
+
+ assert result["kind"] == "interaction"
+ assert [item["question"] for item in result["interaction"]["questions"]] == questions
+ assert [item["options"] for item in result["interaction"]["questions"]] == [[], []]
+ assert saved[-1]["phase"] == "wait_feedback"
+
+
@pytest.mark.asyncio
async def test_option_generation_preserves_model_defaults_and_completion_budget():
questions = ["重点研究哪些品类?", "覆盖哪些市场?", "报告用于什么决策?"]
@@ -383,6 +439,7 @@ async def test_feedback_answer_resumes_once_and_returns_direct_completion():
"file_name": "智能家电报告",
"conversation_id": "conversation-1",
"questions": ["重点研究哪些品类?"],
+ "requested_report_type": "brief",
"revision": 3,
}
answer = {
@@ -406,7 +463,11 @@ async def test_feedback_answer_resumes_once_and_returns_direct_completion():
"_call_deepresearch_stream_impl",
new=AsyncMock(return_value=json.dumps(completed, ensure_ascii=False)),
) as stream:
- result, saved = await _invoke(state=state, user_input=answer)
+ result, saved = await _invoke(
+ state=state,
+ user_input=answer,
+ requested_report_type="professional",
+ )
assert result["kind"] == "completed"
assert "12,345" in result["content"]
@@ -417,9 +478,45 @@ async def test_feedback_answer_resumes_once_and_returns_direct_completion():
assert stream.await_count == 1
assert stream.await_args.kwargs["action"] == "resume"
assert stream.await_args.kwargs["node"] == "feedback_handler"
+ assert stream.await_args.kwargs["report_type"] == "brief"
assert "空调与冰箱" in stream.await_args.kwargs["feedback"]
+async def test_legacy_feedback_state_resumes_with_native_auto_report_type():
+ state = {
+ "schema_version": 1,
+ "phase": "wait_feedback",
+ "query": "q",
+ "file_name": "r",
+ "conversation_id": "conversation-1",
+ "questions": ["继续吗?"],
+ "revision": 3,
+ }
+ answer = {
+ "status": "answered",
+ "answers": [{"question": "继续吗?", "selected_options": ["继续"]}],
+ }
+ completed = {
+ "status": "completed",
+ "conversation_id": "conversation-1",
+ "report_delivered": True,
+ }
+
+ with patch.object(
+ de,
+ "_call_deepresearch_stream_impl",
+ new=AsyncMock(return_value=json.dumps(completed, ensure_ascii=False)),
+ ) as stream:
+ await _invoke(
+ state=state,
+ user_input=answer,
+ requested_report_type="brief",
+ )
+
+ assert stream.await_args.kwargs["report_type"] is None
+
+
@pytest.mark.asyncio
async def test_completion_warns_when_html_style_falls_back():
completed = {
@@ -565,6 +662,7 @@ async def test_outline_is_presented_once_then_confirmed_without_main_agent():
"file_name": "智能家电报告",
"conversation_id": "conversation-1",
"questions": ["重点研究哪些品类?"],
+ "requested_report_type": "professional",
"revision": 3,
}
outline = "## 页面规划\n\n### P1: 市场格局"
@@ -606,13 +704,16 @@ async def test_outline_is_presented_once_then_confirmed_without_main_agent():
new=AsyncMock(return_value=json.dumps(completed, ensure_ascii=False)),
) as stream:
result, saved = await _invoke(
- state=interaction["state"], user_input=outline_answer
+ state=interaction["state"],
+ user_input=outline_answer,
+ requested_report_type="brief",
)
assert result["kind"] == "completed"
assert "1. 市场格局" in result["content"]
assert saved[0]["phase"] == "resuming_outline"
assert stream.await_args.kwargs["node"] == "outline_interaction"
+ assert stream.await_args.kwargs["report_type"] == "professional"
assert "accepted" in stream.await_args.kwargs["feedback"]
diff --git a/tests/unit_tests/agentserver/test_deepresearch_stream_router.py b/tests/unit_tests/agentserver/test_deepresearch_stream_router.py
index 5a915439aa..889f4736d8 100644
--- a/tests/unit_tests/agentserver/test_deepresearch_stream_router.py
+++ b/tests/unit_tests/agentserver/test_deepresearch_stream_router.py
@@ -289,6 +289,19 @@ def test_parallel_section_nodes_emit_one_section_boundary():
{"agent": agent, "section_idx": "3", "event": "done", "content": ""},
state,
)
+ validated = (
+ route_chunk(
+ {
+ "agent": agent,
+ "section_idx": "3",
+ "event": "summary_response",
+ "content": "SUCCESS",
+ },
+ state,
+ )
+ if agent == "sub_reporter"
+ else []
+ )
started_reasoning = _process_reasoning(started)
assert started_reasoning == [{
@@ -317,7 +330,11 @@ def test_parallel_section_nodes_emit_one_section_boundary():
"task_index": 3,
"stream_source_id": "deepresearch_section_3",
}]
- completes = [frame for frame in completed if frame["event_type"] == "task.complete"]
+ completes = [
+ frame
+ for frame in completed + validated
+ if frame["event_type"] == "task.complete"
+ ]
assert len(completes) == (1 if agent == "sub_reporter" else 0)
@@ -352,7 +369,8 @@ def test_final_report_nodes_share_stage_four_aggregate_stream():
"agent": "sub_reporter",
"section_idx": "1",
"section_total": 1,
- "event": "done",
+ "event": "summary_response",
+ "content": "SUCCESS",
},
state,
)
@@ -372,11 +390,23 @@ def test_final_report_nodes_share_stage_four_aggregate_stream():
def test_final_report_aggregate_starts_only_after_all_sections_complete():
state = RouterState(section_titles={"1": "第一章", "2": "第二章"})
first = route_chunk(
- {"agent": "sub_reporter", "section_idx": "1", "section_total": 2, "event": "done"},
+ {
+ "agent": "sub_reporter",
+ "section_idx": "1",
+ "section_total": 2,
+ "event": "summary_response",
+ "content": "SUCCESS",
+ },
state,
)
second = route_chunk(
- {"agent": "sub_reporter", "section_idx": "2", "section_total": 2, "event": "done"},
+ {
+ "agent": "sub_reporter",
+ "section_idx": "2",
+ "section_total": 2,
+ "event": "summary_response",
+ "content": "SUCCESS",
+ },
state,
)
@@ -415,7 +445,8 @@ def test_final_report_waits_for_every_expected_section():
"agent": "sub_reporter",
"section_idx": "1",
"section_total": 2,
- "event": "done",
+ "event": "summary_response",
+ "content": "SUCCESS",
},
state,
)
@@ -429,7 +460,8 @@ def test_final_report_waits_for_every_expected_section():
"agent": "sub_reporter",
"section_idx": "2",
"section_total": 2,
- "event": "done",
+ "event": "summary_response",
+ "content": "SUCCESS",
},
state,
)
@@ -471,7 +503,8 @@ def test_section_total_has_small_deterministic_bound():
"agent": "sub_reporter",
"section_idx": "1",
"section_total": 10**18,
- "event": "done",
+ "event": "summary_response",
+ "content": "SUCCESS",
},
state,
)
@@ -722,7 +755,8 @@ def test_final_report_boundaries_remain_exactly_once():
"agent": "sub_reporter",
"section_idx": "1",
"section_total": 1,
- "event": "done",
+ "event": "summary_response",
+ "content": "SUCCESS",
},
state,
))
@@ -731,7 +765,8 @@ def test_final_report_boundaries_remain_exactly_once():
"agent": "sub_reporter",
"section_idx": "1",
"section_total": 1,
- "event": "done",
+ "event": "summary_response",
+ "content": "SUCCESS",
},
state,
))
@@ -750,7 +785,13 @@ def test_final_report_boundaries_remain_exactly_once():
def test_final_report_reasoning_waits_for_all_sections_then_follows_start_boundary():
state = RouterState(section_titles={"1": "第一章", "2": "第二章"})
route_chunk(
- {"agent": "sub_reporter", "section_idx": "1", "section_total": 2, "event": "done"},
+ {
+ "agent": "sub_reporter",
+ "section_idx": "1",
+ "section_total": 2,
+ "event": "summary_response",
+ "content": "SUCCESS",
+ },
state,
)
@@ -764,7 +805,13 @@ def test_final_report_reasoning_waits_for_all_sections_then_follows_start_bounda
)
released = route_chunk(
- {"agent": "sub_reporter", "section_idx": "2", "section_total": 2, "event": "done"},
+ {
+ "agent": "sub_reporter",
+ "section_idx": "2",
+ "section_total": 2,
+ "event": "summary_response",
+ "content": "SUCCESS",
+ },
state,
)
aggregate = [
@@ -782,7 +829,13 @@ def test_final_report_reasoning_waits_for_all_sections_then_follows_start_bounda
def test_final_report_aggregate_completes_after_stage_four_starts():
state = RouterState(section_titles={"1": "第一章"})
frames = route_chunk(
- {"agent": "sub_reporter", "section_idx": "1", "section_total": 1, "event": "done"},
+ {
+ "agent": "sub_reporter",
+ "section_idx": "1",
+ "section_total": 1,
+ "event": "summary_response",
+ "content": "SUCCESS",
+ },
state,
)
@@ -825,6 +878,12 @@ def test_last_section_reasoning_finishes_before_stage_four_transition():
},
state,
)
+ frames.extend(
+ route_chunk(
+ {**base, "event": "summary_response", "content": "SUCCESS"},
+ state,
+ )
+ )
final_section_reasoning = next(
index for index, frame in enumerate(frames)
@@ -1037,6 +1096,13 @@ def test_parallel_sections_emit_one_stage_update_without_chapter_snapshots():
"event": "done",
"content": "SUCCESS",
}, state)
+ validated = route_chunk({
+ "agent": "sub_reporter",
+ "section_idx": "1",
+ "section_total": 2,
+ "event": "summary_response",
+ "content": "SUCCESS",
+ }, state)
repeated_success = route_chunk({
"agent": "sub_reporter",
"section_idx": "1",
@@ -1051,6 +1117,11 @@ def test_parallel_sections_emit_one_stage_update_without_chapter_snapshots():
frame["stream_source_id"] == "deepresearch_section_1"
for frame in _process_reasoning(started + completed)
)
+ assert [
+ frame["event_type"]
+ for frame in validated
+ if frame.get("stream_source_id") == "deepresearch_section_1"
+ ] == ["task.complete"]
assert repeated_success == []
@@ -1075,7 +1146,7 @@ def test_parallel_section_emits_distinct_reasoning_and_content_without_compactio
def test_parallel_section_filters_control_process_values():
- for value in ("SUCCESS", " ALL END ", "SECTION END", "", " "):
+ for value in (" ALL END ", "SECTION END", "", " "):
state = RouterState()
route_chunk({
"agent": "sub_reporter",
@@ -1116,7 +1187,38 @@ def test_sub_reporter_success_response_does_not_restart_reasoning():
state,
)
- assert frames == []
+ assert _process_reasoning(frames) == []
+ assert any(frame["event_type"] == "task.complete" for frame in frames)
+ assert state.final_report_started is True
+
+
+def test_sub_reporter_section_completes_only_after_validated_success_marker():
+ state = RouterState()
+ base = {
+ "agent": "sub_reporter",
+ "section_idx": "1",
+ "section_title": "第一章",
+ "section_total": 1,
+ }
+
+ done_frames = route_chunk({**base, "event": "done"}, state)
+
+ assert state.completed_section_indices == set()
+ assert not any(frame["event_type"] == "task.complete" for frame in done_frames)
+ assert state.final_report_started is False
+
+ success_frames = route_chunk(
+ {**base, "event": "summary_response", "content": "SUCCESS"},
+ state,
+ )
+
+ assert state.completed_section_indices == {"1"}
+ assert any(
+ frame["event_type"] == "task.complete"
+ and frame.get("stream_source_id") == "deepresearch_section_1"
+ for frame in success_frames
+ )
+ assert state.final_report_started is True
def test_sub_reporter_forwards_reasoning_without_streaming_chapter_body():
@@ -1812,9 +1914,6 @@ def test_brief_outline_uses_stage_two_and_outline_preview_contract():
"brief_info_collector",
"brief_evidence_reviewer",
"brief_sub_reporter",
- "brief_reporter",
- "brief_mermaid_generator",
- "brief_source_tracer",
],
)
def test_brief_research_nodes_advance_stage_three_in_task_list(agent):
@@ -1827,6 +1926,64 @@ def test_brief_research_nodes_advance_stage_three_in_task_list(agent):
assert all(frame["event_type"] != "chat.delta" for frame in frames)
+def test_brief_sub_reporter_completion_starts_stage_four_before_final_node_chunk():
+ state = RouterState(current_stage=3)
+
+ frames = route_chunk(
+ {"agent": "brief_sub_reporter", "event": "done", "content": "章节写作完成"},
+ state,
+ )
+
+ assert state.final_report_started is True
+ _assert_stage(_stage_update(frames), 4)
+ node_complete = next(
+ index
+ for index, frame in enumerate(frames)
+ if frame["event_type"] == "chat.reasoning"
+ and frame.get("task_id") == "deepresearch_stage_3"
+ and frame.get("stream_source_id") == "dr_brief_sub_reporter"
+ and frame.get("content") == "精简章节撰写完成\n"
+ )
+ stage_four = next(
+ index
+ for index, frame in enumerate(frames)
+ if frame["event_type"] == "task.update"
+ and frame["tasks"][3]["status"] == "in_progress"
+ )
+ assert node_complete < stage_four
+
+
+ "agent",
+ [
+ "brief_reporter",
+ "brief_mermaid_generator",
+ "brief_source_tracer",
+ "brief_html_reporter",
+ ],
+)
+def test_brief_final_nodes_start_stage_four_without_professional_sections(agent):
+ state = RouterState(current_stage=3)
+
+ frames = route_chunk(
+ {"agent": agent, "event": "start", "content": "处理中"},
+ state,
+ )
+
+ assert state.final_report_started is True
+ _assert_stage(_stage_update(frames), 4)
+ final_frames = [
+ frame
+ for frame in frames
+ if frame.get("stream_source_id") == "deepresearch_final_report"
+ ]
+ assert final_frames[0]["event_type"] == "task.start"
+ assert any(
+ frame["event_type"] == "chat.reasoning"
+ for frame in final_frames
+ )
+
+
@pytest.mark.parametrize(
("agent", "start_message"),
[
diff --git a/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py b/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py
index af71cf05ce..e403352bd2 100644
--- a/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py
+++ b/tests/unit_tests/agentserver/test_deepresearch_stream_tool.py
@@ -347,6 +347,54 @@ async def test_stream_sends_versioned_config_over_stdin_only():
assert parsed_outcome["skill_execution_ms"] >= 0
[email protected]("report_type", ["professional", "brief"])
+async def test_stream_sends_explicit_report_type_in_config_frame_only(report_type: str):
+ proc = _Proc(
+ [
+ json.dumps(
+ {
+ "__deepsearch_status__": "error",
+ "error_code": "workflow_error",
+ "error": "done",
+ }
+ )
+ ]
+ )
+ patches = _stream_patches(proc)
+ with patches[0], patches[1], patches[2], patches[3], patches[4], patches[5] as spawn:
+ await dt.deepresearch_stream._func(
+ action="start",
+ query="q",
+ report_type=report_type,
+ )
+
+ frame = json.loads(bytes(proc.stdin.data))
+ assert frame["config"]["REPORT_TYPE"] == report_type
+ assert "REPORT_TYPE" not in spawn.await_args.kwargs["env"]
+
+
+async def test_stream_rejects_invalid_report_type_before_child_spawn():
+ proc = _Proc()
+ patches = _stream_patches(proc)
+ with patches[0], patches[1], patches[2], patches[3], patches[4], patches[5] as spawn:
+ outcome = json.loads(
+ await dt.deepresearch_stream._func(
+ action="start",
+ query="q",
+ report_type="Brief",
+ )
+ )
+
+ assert outcome == {
+ "status": "error",
+ "error_code": "report_type_invalid",
+ "error": "report_type must be one of: professional, brief",
+ }
+ spawn.assert_not_awaited()
+
+
def test_only_six_standard_proxy_names_are_forwarded(tmp_path: Path, monkeypatch):
venv = tmp_path / "runtime"
python = venv / "bin" / "python"
@@ -473,6 +521,40 @@ async def test_track_and_untrack_cover_terminal_error_exit():
assert proc.waited >= 1
+async def test_numeric_deepsearch_error_code_is_preserved():
+ proc = _Proc(
+ [
+ json.dumps(
+ {
+ "__deepsearch_status__": "error",
+ "error_code": "212001",
+ "error": "HTML report generation failed",
+ }
+ )
+ ]
+ )
+ patches = _stream_patches(proc)
+ with ExitStack() as stack:
+ for item in patches:
+ stack.enter_context(item)
+ outcome = json.loads(
+ await dt.deepresearch_stream._func(action="start", query="q")
+ )
+
+ assert outcome["error_code"] == "212001"
+
+
[email protected]("error_code", ["12345", "1234567", "123456"])
+def test_non_six_ascii_digit_error_codes_are_rejected(error_code: str):
+ outcome = dt._sanitize_terminal_outcome(
+ {"status": "error", "error_code": error_code, "error": "failed"},
+ _valid_config(),
+ )
+
+ assert outcome["error_code"] == "workflow_error"
+
+
@pytest.mark.asyncio
async def test_track_failure_reaps_locally_without_untrack():
proc = _Proc([], running=True)
@@ -1179,7 +1261,8 @@ async def test_completed_marker_accepts_p_numbered_sections_beneath_wrapper_head
"agent": "sub_reporter",
"section_idx": str(index),
"section_total": 5,
- "event": "done",
+ "event": "summary_response",
+ "content": "SUCCESS",
}
)
for index in range(1, 6)
@@ -1534,7 +1617,8 @@ async def test_completed_report_delivers_markdown_html_and_hidden_bundle(tmp_pat
"agent": "sub_reporter",
"section_idx": "1",
"section_total": 1,
- "event": "done",
+ "event": "summary_response",
+ "content": "SUCCESS",
}
),
json.dumps(
@@ -1592,6 +1676,10 @@ async def test_completed_report_delivers_markdown_html_and_hidden_bundle(tmp_pat
if call.args[0]["payload"].get("event_type") == "chat.file"
)
assert [item["name"] for item in file_payload["files"]] == ["r.md", "r.html"]
+ assert [item["mime_type"] for item in file_payload["files"]] == [
+ "text/markdown",
+ "text/html",
+ ]
assert file_payload["metadata"]["htmlStyleStatus"] == "fallback"
assert file_payload["metadata"]["htmlStylePhase"] == "invoke_llm"
assert file_payload["metadata"]["htmlStyleReasonCode"] == "llm_call_failed"
@@ -1602,24 +1690,166 @@ async def test_completed_report_delivers_markdown_html_and_hidden_bundle(tmp_pat
@pytest.mark.asyncio
-async def test_final_report_idle_stream_emits_processing_heartbeat_without_cancelling_reader(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-):
- initial = b"".join(
- (
+async def test_completed_native_html_delivers_exactly_one_brief_file(tmp_path: Path):
+ native_html = "<!doctype html><html><body>Brief</body></html>"
+ final_result = {
+ "response_content": native_html,
+ "response_content_type": "text/html",
+ }
+ proc = _Proc(
+ [
+ json.dumps({"__deepsearch_status__": "started", "conversation_id": "C1"}),
json.dumps(
- {"__deepsearch_status__": "started", "conversation_id": "C1"}
- ).encode("utf-8")
- + b"\n",
+ {
+ "agent": "brief_reporter",
+ "section_idx": "1",
+ "section_total": 1,
+ "event": "done",
+ }
+ ),
json.dumps(
{
- "agent": "sub_reporter",
+ "__deepsearch_status__": "completed",
+ "conversation_id": "C1",
+ "final_result": final_result,
+ "raw_report_path": "/must/not/expose.md",
+ }
+ ),
+ ]
+ )
+ route = {
+ "request_id": "R1",
+ "channel_id": "CH1",
+ "session_id": "S1",
+ "service_id": "default",
+ "agent_id": "default",
+ }
+ push = AsyncMock()
+ html_path = tmp_path / "brief-v1.html"
+ write_html = AsyncMock(return_value=str(html_path))
+ 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)
+ )
+ stack.enter_context(patch.object(dt, "_write_report_html", new=write_html))
+ markdown_writer = stack.enter_context(
+ patch.object(dt, "_write_report_artifacts_stream", new=AsyncMock())
+ )
+ generic_html = stack.enter_context(
+ patch.object(dt, "_generate_report_html", new=AsyncMock())
+ )
+ outcome = json.loads(
+ await dt.deepresearch_stream._func(
+ action="start",
+ query="q",
+ file_name="brief.md",
+ )
+ )
+
+ assert outcome == {
+ "status": "completed",
+ "conversation_id": "C1",
+ "report_delivered": True,
+ "report_chars": len(native_html),
+ }
+ write_html.assert_awaited_once_with(native_html, "brief.md")
+ markdown_writer.assert_not_awaited()
+ generic_html.assert_not_awaited()
+ file_payload = next(
+ call.args[0]["payload"]
+ for call in push.send_push.await_args_list
+ if call.args[0]["payload"].get("event_type") == "chat.file"
+ )
+ assert file_payload == {
+ "event_type": "chat.file",
+ "files": [
+ {
+ "path": str(html_path),
+ "name": "brief-v1.html",
+ "mime_type": "text/html",
+ }
+ ],
+ }
+
+
+async def test_completed_unknown_response_mime_fails_without_report_file(tmp_path: Path):
+ final_result = {
+ "response_content": "opaque",
+ "response_content_type": "application/octet-stream",
+ }
+ proc = _Proc(
+ [
+ json.dumps({"__deepsearch_status__": "started", "conversation_id": "C1"}),
+ json.dumps(
+ {
+ "agent": "brief_html_reporter",
"section_idx": "1",
"section_total": 1,
"event": "done",
}
+ ),
+ 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",
+ }
+ 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)
+ )
+ markdown_writer = stack.enter_context(
+ patch.object(dt, "_write_report_artifacts_stream", new=AsyncMock())
+ )
+ html_writer = stack.enter_context(
+ patch.object(dt, "_write_report_html", new=AsyncMock())
+ )
+ outcome = json.loads(
+ await dt.deepresearch_stream._func(action="start", query="q")
+ )
+
+ assert outcome["error_code"] == "stream_protocol_invalid"
+ markdown_writer.assert_not_awaited()
+ html_writer.assert_not_awaited()
+ assert not any(
+ call.args[0]["payload"].get("event_type") == "chat.file"
+ for call in push.send_push.await_args_list
+ )
+
+
+async def _run_delayed_final_report_heartbeat_case(
+ monkeypatch: pytest.MonkeyPatch,
+ *,
+ node_chunk: dict[str, Any],
+ final_result: dict[str, Any],
+ writer_name: str,
+ writer_result: object,
+) -> tuple[dict[str, Any], _DelayedFinalReportReader, list[tuple[str, int]]]:
+ initial = b"".join(
+ (
+ json.dumps(
+ {"__deepsearch_status__": "started", "conversation_id": "C1"}
).encode("utf-8")
+ b"\n",
+ json.dumps(node_chunk).encode("utf-8") + b"\n",
)
)
terminal = (
@@ -1627,7 +1857,7 @@ async def test_final_report_idle_stream_emits_processing_heartbeat_without_cance
{
"__deepsearch_status__": "completed",
"conversation_id": "C1",
- "final_result": {"response_content": "# Final"},
+ "final_result": final_result,
}
).encode("utf-8")
+ b"\n"
@@ -1661,11 +1891,11 @@ async def test_final_report_idle_stream_emits_processing_heartbeat_without_cance
push.send_push.side_effect = record_push
- async def delayed_write(*_args: Any, **_kwargs: Any) -> dict[str, str]:
+ async def delayed_write(*_args: Any, **_kwargs: Any) -> object:
nonlocal phase
phase = "artifact"
await asyncio.sleep(0.08)
- return {"md": str(tmp_path / "r.md")}
+ return writer_result
monkeypatch.setattr(
dt,
@@ -1683,7 +1913,7 @@ async def test_final_report_idle_stream_emits_processing_heartbeat_without_cance
stack.enter_context(
patch.object(
dt,
- "_write_report_artifacts_stream",
+ writer_name,
new=delayed_write,
)
)
@@ -1691,13 +1921,30 @@ async def test_final_report_idle_stream_emits_processing_heartbeat_without_cance
await dt.deepresearch_stream._func(action="start", query="q")
)
- heartbeats = [
- call.args[0]["payload"]
- for call in push.send_push.await_args_list
- if call.args[0]["payload"].get("event_type") == "chat.processing_status"
- and call.args[0]["payload"].get("current_task") == "in_progress"
- ]
- assert len(heartbeats) >= 4
+ return outcome, reader, heartbeat_observations
+
+
+async def test_final_report_idle_stream_emits_processing_heartbeat_without_cancelling_reader(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ outcome, reader, heartbeat_observations = (
+ await _run_delayed_final_report_heartbeat_case(
+ monkeypatch,
+ node_chunk={
+ "agent": "sub_reporter",
+ "section_idx": "1",
+ "section_total": 1,
+ "event": "summary_response",
+ "content": "SUCCESS",
+ },
+ final_result={"response_content": "# Final"},
+ writer_name="_write_report_artifacts_stream",
+ writer_result={"md": str(tmp_path / "r.md")},
+ )
+ )
+
+ assert len(heartbeat_observations) >= 4
stream_heartbeat_reads = {
read_number
for observed_phase, read_number in heartbeat_observations
@@ -1713,6 +1960,139 @@ async def test_final_report_idle_stream_emits_processing_heartbeat_without_cance
assert outcome["report_delivered"] is True
+async def test_processing_status_sent_during_stage_1_3_silence(
+ monkeypatch: pytest.MonkeyPatch,
+):
+ """SDK silence before final-report stage must still emit processing heartbeats."""
+ initial = (
+ json.dumps(
+ {"__deepsearch_status__": "started", "conversation_id": "C1"}
+ ).encode("utf-8")
+ + b"\n"
+ )
+ terminal = (
+ json.dumps(
+ {
+ "__deepsearch_status__": "error",
+ "conversation_id": "C1",
+ "error_code": "workflow_boom",
+ "error": "boom",
+ }
+ ).encode("utf-8")
+ + b"\n"
+ )
+ reader = _DelayedFinalReportReader(initial, terminal, delay=0.08)
+ proc = _Proc()
+ proc.stdout = reader
+ route = {
+ "request_id": "R1",
+ "channel_id": "CH1",
+ "session_id": "S1",
+ "service_id": "default",
+ "agent_id": "default",
+ }
+ push = AsyncMock()
+ heartbeat_observations: list[int] = []
+
+ async def record_push(envelope: dict[str, Any]) -> None:
+ payload = envelope["payload"]
+ if (
+ payload.get("event_type") == "chat.processing_status"
+ and payload.get("current_task") == "in_progress"
+ ):
+ heartbeat_observations.append(reader.reads)
+
+ push.send_push.side_effect = record_push
+
+ monkeypatch.setattr(
+ dt,
+ "DEEPRESEARCH_FINAL_REPORT_PROGRESS_INTERVAL_SECONDS",
+ 0.02,
+ raising=False,
+ )
+ 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 len(heartbeat_observations) >= 1
+ assert outcome["status"] == "error"
+
+
+async def test_brief_final_report_idle_stream_emits_processing_heartbeat(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ native_html = "<!doctype html><html><body>Brief</body></html>"
+ outcome, reader, heartbeat_observations = (
+ await _run_delayed_final_report_heartbeat_case(
+ monkeypatch,
+ node_chunk={
+ "agent": "brief_reporter",
+ "section_idx": "0",
+ "event": "done",
+ },
+ final_result={
+ "response_content": native_html,
+ "response_content_type": "text/html",
+ },
+ writer_name="_write_report_html",
+ writer_result=str(tmp_path / "brief-v1.html"),
+ )
+ )
+
+ assert any(
+ observed_phase == "stream" and read_number == 2
+ for observed_phase, read_number in heartbeat_observations
+ )
+ assert any(
+ observed_phase == "artifact"
+ for observed_phase, _read_number in heartbeat_observations
+ )
+ assert reader.cancelled is False
+ assert outcome["status"] == "completed"
+ assert outcome["report_delivered"] is True
+
+
+async def test_brief_sub_reporter_completion_keeps_silent_final_pipeline_alive(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+):
+ native_html = "<!doctype html><html><body>Brief</body></html>"
+ outcome, reader, heartbeat_observations = (
+ await _run_delayed_final_report_heartbeat_case(
+ monkeypatch,
+ node_chunk={
+ "agent": "brief_sub_reporter",
+ "section_idx": "0",
+ "event": "done",
+ "content": "章节写作完成",
+ },
+ final_result={
+ "response_content": native_html,
+ "response_content_type": "text/html",
+ },
+ writer_name="_write_report_html",
+ writer_result=str(tmp_path / "brief-v1.html"),
+ )
+ )
+
+ assert any(
+ observed_phase == "stream" and read_number == 2
+ for observed_phase, read_number in heartbeat_observations
+ )
+ assert reader.cancelled is False
+ assert outcome["status"] == "completed"
+ assert outcome["report_delivered"] is True
+
+
def test_offline_html_converter_sanitizes_active_content(tmp_path: Path):
from jiuwenswarm.agents.harness.common.tools.deepresearch_plugin.convert_html_offline import (
convert_md_to_html,
@@ -1895,6 +2275,28 @@ async def test_report_publication_writes_markdown_html_snapshot_and_provenance(
assert snapshot["response_content"] == final_result["response_content"]
+async def test_native_html_publication_is_exclusive_and_creates_no_markdown_sidecars(
+ tmp_path: Path,
+):
+ native_html = "<!doctype html><html><body>native</body></html>"
+ with patch.object(dt, "get_cwd", return_value=str(tmp_path)):
+ first, second = await asyncio.gather(
+ dt._write_report_html(native_html, "Research.md"),
+ dt._write_report_html(native_html, "Research.html"),
+ )
+
+ assert {Path(first).name, Path(second).name} == {
+ "Research-v1.html",
+ "Research-2-v1.html",
+ }
+ assert Path(first).read_text(encoding="utf-8") == native_html
+ assert Path(second).read_text(encoding="utf-8") == native_html
+ assert list(tmp_path.glob("*.md")) == []
+ assert list(tmp_path.glob("*.json")) == []
+ assert dt._REPORT_OUTPUT_LOCKS == {}
+
+
@pytest.mark.asyncio
async def test_html_failure_keeps_published_markdown(tmp_path: Path):
final_result = {
@@ -2269,7 +2671,13 @@ async def test_file_delivery_failure_never_falls_back_to_report_chat(tmp_path: P
[
json.dumps({"__deepsearch_status__": "started", "conversation_id": "C1"}),
json.dumps(
- {"agent": "sub_reporter", "section_idx": "1", "section_total": 1, "event": "done"}
+ {
+ "agent": "sub_reporter",
+ "section_idx": "1",
+ "section_total": 1,
+ "event": "summary_response",
+ "content": "SUCCESS",
+ }
),
json.dumps(
{
@@ -2414,7 +2822,13 @@ async def test_large_completed_marker_above_streamreader_limit_is_supported(tmp_
proc = _Proc(
[
json.dumps(
- {"agent": "sub_reporter", "section_idx": "1", "section_total": 1, "event": "done"}
+ {
+ "agent": "sub_reporter",
+ "section_idx": "1",
+ "section_total": 1,
+ "event": "summary_response",
+ "content": "SUCCESS",
+ }
),
json.dumps(
{
@@ -3005,7 +3419,13 @@ async def test_ordered_stage_gateway_updates_reach_completed_todo_snapshot(tmp_p
json.dumps({"__deepsearch_status__": "started", "conversation_id": "C1"}),
json.dumps({"agent": "outline", "content": "# 1. Scope"}),
json.dumps(
- {"agent": "sub_reporter", "section_idx": "1", "section_total": 1, "event": "done"}
+ {
+ "agent": "sub_reporter",
+ "section_idx": "1",
+ "section_total": 1,
+ "event": "summary_response",
+ "content": "SUCCESS",
+ }
),
json.dumps(
{
@@ -3798,8 +4218,8 @@ async def test_protocol_control_keys_and_values_survive_secret_redaction(
"agent": "sub_reporter",
"section_idx": "1",
"section_total": 1,
- "event": "done",
- "content": free_text,
+ "event": "summary_response",
+ "content": "SUCCESS",
}
),
json.dumps(
diff --git a/tests/unit_tests/agentserver/test_progressive_deepresearch_context.py b/tests/unit_tests/agentserver/test_progressive_deepresearch_context.py
index f51c866c23..9979e1adf0 100644
--- a/tests/unit_tests/agentserver/test_progressive_deepresearch_context.py
+++ b/tests/unit_tests/agentserver/test_progressive_deepresearch_context.py
@@ -13,6 +13,10 @@ from openjiuwen.core.single_agent.rail.base import ToolCallInputs
from jiuwenswarm.agents.harness.common.rails.progressive_tool_rail import (
ProgressiveToolRail,
)
+from jiuwenswarm.agents.harness.common.rails.deepresearch_execution_rail import (
+ DeepResearchExecutionRail,
+)
+from jiuwenswarm.agents.harness.common.tools.deepresearch import execution as de
from jiuwenswarm.agents.harness.common.tools.deepresearch import tools as dt
from jiuwenswarm.agents.harness.common.tools.invoke_tool_tool import (
InvokeToolInput,
@@ -24,6 +28,99 @@ from jiuwenswarm.common.local_env_config import (
get_task_env_overlay,
replace_active_env,
)
+from jiuwenswarm.common.schema.agent import AgentRequest
+from jiuwenswarm.perf.context import clear_request_context, set_request_context
+from jiuwenswarm.server.runtime.agent_adapter import interface_deep
+
+
+class _RequestContextSession:
+ def __init__(self, session_id: str):
+ self.session_id = session_id
+ self.state: dict[str, object] = {}
+
+ def get_session_id(self):
+ return self.session_id
+
+ def get_state(self, key):
+ return self.state.get(key)
+
+ def update_state(self, values):
+ self.state.update(values)
+
+
+def _execution_rail_context(session_id: str):
+ tool_call = SimpleNamespace(
+ id=f"call-{session_id}",
+ name="deepresearch_execute",
+ arguments={"query": "q"},
+ )
+ return SimpleNamespace(
+ session=_RequestContextSession(session_id),
+ inputs=ToolCallInputs(
+ tool_call=tool_call,
+ tool_name="deepresearch_execute",
+ tool_args=tool_call.arguments,
+ tool_result=None,
+ ),
+ extra={},
+ )
+
+
+async def test_report_type_uses_params_and_isolated_execution_contexts():
+ requests = (
+ AgentRequest(
+ request_id="request-brief",
+ channel_id="officeclaw",
+ session_id="session-brief",
+ params={"report_type": "brief"},
+ metadata={"report_type": "professional"},
+ ),
+ AgentRequest(
+ request_id="request-professional",
+ channel_id="officeclaw",
+ session_id="session-professional",
+ params={"report_type": "professional"},
+ metadata={"report_type": "brief"},
+ ),
+ )
+ both_bound = asyncio.Event()
+ bound_count = 0
+ bound_lock = asyncio.Lock()
+
+ async def _observe(request: AgentRequest) -> str | None:
+ nonlocal bound_count
+ requested_report_type = interface_deep._extract_requested_report_type(request)
+ set_request_context(
+ session_id=request.session_id or "",
+ request_id=request.request_id or "",
+ channel_id=request.channel_id or "",
+ mode="agent",
+ requested_report_type=requested_report_type,
+ )
+ async with bound_lock:
+ bound_count += 1
+ if bound_count == len(requests):
+ both_bound.set()
+ await both_bound.wait()
+
+ rail = DeepResearchExecutionRail(model_provider=lambda: None)
+ ctx = _execution_rail_context(request.session_id or "")
+ await rail.before_tool_call(ctx)
+ try:
+ execution_context = de._execution_context.get()
+ return execution_context.requested_report_type
+ finally:
+ await rail.after_tool_call(ctx)
+ clear_request_context(
+ session_id=request.session_id,
+ request_id=request.request_id,
+ )
+
+ assert await asyncio.gather(*(_observe(request) for request in requests)) == [
+ "brief",
+ "professional",
+ ]
@pytest.mark.asyncio
@@ -50,7 +147,7 @@ async def test_deferred_deepresearch_rebinds_trusted_adapter_context():
"service_id": service_id,
"agent_id": agent_id,
}
- assert dt._get_effective_request_output_dir() == Path(output_dir)
+ assert dt._get_effective_request_output_dir() == Path(output_dir).resolve()
return "ok"
target.invoke.side_effect = _invoke